GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — opencode/scripts/sync-model-whitelist.py at dev · Cor-Incorporated/opencode Expand file tree/ Copy pathsync-model-whitelist.pyMore file actions executable file ·522 lines (448 loc) · 23.3 KB / Copy pathsync-model-whitelist.pyFile metadata and controlsexecutable file ·522 lines (448 loc) · 23.3 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 #!/usr/bin/env python3 """Keep the model whitelist in step with the models.dev catalog. Why this exists --------------- The whitelist lives in three places that must move together: 1. packages/guardrails/managed/model-policy.json (admin admission policy) 2. packages/guardrails/profile/model-policy.json (packaged admission policy) 3. guardrail-patterns.ts `paid` and `paidMedia` (cost-0-but-billed classification) On 2026-09-02 all three were stale at once. `glm-5.3-flash` (released 2026-08-26) was absent everywhere, as were `claude-opus-5`, `claude-sonnet-5` and `gpt-5.6-luna` -- the last being the model Codex itself runs. The provider *routes* were all present, which is what made the staleness easy to miss: "is deepseek wired up?" answers yes while the model list rots underneath. The refresh that closed that gap was done by hand. Doing it by hand is the defect: nothing detects the next drift. This script makes the refresh mechanical and, more importantly, gives the check a way to fail. The snapshot ------------ Running with no arguments (`python3 scripts/sync-model-whitelist.py`) is the check: it must run offline, in CI, without a warm `~/.cache/opencode`. So the catalog subset we care about is committed to the repo as a snapshot, and the check compares whitelist against snapshot. Refreshing is two steps that belong in one commit: python3 scripts/sync-model-whitelist.py --refresh-snapshot # catalog -> snapshot python3 scripts/sync-model-whitelist.py --apply # snapshot -> whitelist The snapshot is the declaration of "what the catalog offered on date X"; the whitelist is "what we allow". The no-args check links the two, so a snapshot refresh that forgets to apply fails, and so does a hand-edit that drops a model. The catalog is upstream's own bundled one by default: `packages/core/src/models-dev/snapshot.txt` (the models.dev experimental v2 API, refreshed by upstream and carried into this repo by every upstream sync). The 1.x cache `~/.cache/opencode/models.json` does not exist under 2.x, whose catalog lives in its KV store, so until 2026-11-05 the refresh had no source and the whitelist stayed at its 2026-09-12 state while the 2.x CLI listed newer models that the guardrail then rejected ("is not admitted by provider policy"). Because the default catalog is in the repo, the no-args check also compares the committed snapshot with it: an upstream sync that brings new models fails until the snapshot is refreshed and applied. `--catalog` still accepts a models.dev v1 `api.json`. 2.x lists every `experimental.modes` entry of a model and every service tier it offers as its own model id, `<id>-<mode>` and `<id>-<tier>` (packages/core/src/models-dev.ts), and the guardrail gate compares that id, so the snapshot carries those ids too. Provider environment variables ------------------------------ The same refresh writes `packages/guardrails/provider-env.json`: every catalog provider and the environment variables that switch it on. The launcher (`bin/opencode-guardrails`) reads it to name, on stderr, a provider whose key is set but which the packaged provider policy hides. A hidden provider is otherwise invisible (2026-11-28: a Gemini key was set and "Google" never appeared). Detecting drift against the *live* catalog still needs network; that stays with `local-dev-deploy.sh --check-openrouter-catalog`. Add-only -------- Entries are never removed. models.dev does not list the `gpt-5.x-codex` ids (reachable only through the Codex OAuth flow) and does not list the DeepSeek direct-API ids `deepseek-chat` / `deepseek-reasoner`, both of which still answer. A sync that treats the catalog as the sole truth deletes working routes -- that happened once already during the 2026-09-02 refresh and had to be reverted. """ from __future__ import annotations import argparse import json import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent MANAGED = ROOT / "packages/guardrails/managed/model-policy.json" PROFILE = ROOT / "packages/guardrails/profile/model-policy.json" MANAGED_CONFIG = ROOT / "packages/guardrails/managed/opencode.json" PATTERNS = ROOT / "packages/guardrails/profile/src/guardrail-patterns.ts" SNAPSHOT = ROOT / "packages/guardrails/model-catalog-snapshot.json" DEFAULT_CATALOG = ROOT / "packages/core/src/models-dev/snapshot.txt" PROVIDER_ENV = ROOT / "packages/guardrails/provider-env.json" # Providers whose models report cost 0 because a plan or subscription covers # them (or, for cor-local and cor-os, because they are self-hosted with no # billing at all). `paid` marks those so isFree() does not treat them as genuinely free. # openrouter reports real per-token cost and is deliberately absent. # `zai` (Z.AI platform lane) is absent too: it is not an admitted provider. PAID_PROVIDERS = ("zai-coding-plan", "deepseek", "openai", "cor-local", "cor-os") # Model types the catalog prices per image or per second. Core keeps only per-token text prices # (packages/core/src/models-dev.ts `cost`), so these read as cost 0 however they are billed; the snapshot # records whether the catalog asks a price for them, and `paidMedia` lists the billed ones. MEDIA_TYPES = ("image", "video") def enabled_providers() -> list[str]: return list(json.loads(MANAGED_CONFIG.read_text()).get("providers", {})) # The model types an agent can reach with a tool, and so the ones the request gate has to cover: chat (every session # request) and, since 2026-11-28, image and video (the generate_image and generate_video tools, which the 2.x adapter # judges on the same whitelist at the permission check they make for their model). The other types run in voice # sessions or are not called from a tool. TOOL_TYPES = ("chat", "image", "video") def priced(meta: dict) -> bool: """Whether the catalog asks a price above zero for the model, whatever the unit. Only `price` values are prices: a `when` condition (`duration.gt: 120`) selects them and a multiplier scales them. A model the catalog lists without a cost has none, and is not billed as far as the catalog says. """ def prices(node) -> list[float]: if isinstance(node, dict): price = node.get("price") own = [price] if isinstance(price, (int, float)) and not isinstance(price, bool) else [] # A multiplier's `price` scales a price; it is not one. nested = [value for key, value in node.items() if key != "multipliers" and isinstance(value, (dict, list))] return own + [found for value in nested for found in prices(value)] if isinstance(node, list): return [p for value in node for p in prices(value)] return [] return any(price > 0 for price in prices(meta.get("cost"))) def usable(meta: dict) -> bool: """A model an agent can reach with a tool: a chat model that can call tools and can emit text, or an image or video model.""" # v2 entries carry `capabilities` and `type`; v1 entries carry `tool_call` and are chat models. v2 = "capabilities" in meta if v2 and meta.get("type") not in TOOL_TYPES: return False if v2 and meta.get("type") != "chat": return True tools = meta["capabilities"].get("tools", {}).get("supported") if v2 else meta.get("tool_call") if not tools: return False out = (meta.get("modalities") or {}).get("output") or [] return (not out) or ("text" in out) def catalog_entries(mid: str, meta: dict, listed: set[str]) -> dict[str, dict]: """The model ids 2.x offers for one catalog model: the model, one id per service tier and one per mode. Mirrors the id derivation in packages/core/src/models-dev.ts. A service tier is a speed of its own, `<id>-<tier>`, where "priority" is the tier people know as "fast" unless the model also lists a "fast" tier. A mode only adds an id for a tier the model does not list, and a tier id the catalog lists as a model of its own is that model, not a speed of this one. Tiers are offered on `@opencode/ai` routes only. """ reasoning = meta.get("reasoning") if "capabilities" in meta: reasoning = (meta["capabilities"].get("reasoning") or {}).get("supported") entry = { "release_date": meta.get("release_date") or "", "reasoning": bool(reasoning), "context": (meta.get("limit") or {}).get("context"), # Whether an image or video model is billed, which its cost in the catalog does not say (MEDIA_TYPES). **({"priced": priced(meta)} if meta.get("type") in MEDIA_TYPES else {}), } modes = (meta.get("experimental") or {}).get("modes") or {} tiers = (meta.get("capabilities") or {}).get("service_tier") or [] apis = (meta.get("api") or {}).values() if any((api.get("sdk") or {}).get("opencodeai") for api in apis): # "priority" is the tier people know as "fast", unless the model also has a "fast" tier. names = [ "fast" if tier == "priority" and "fast" not in tiers else tier for tier in tiers ] else: names = [] for mode, options in modes.items(): # A mode says how to ask for its tier, so it only adds an id for a tier the model does not list. tier = options.get("service_tier") if isinstance(options, dict) else None if (tier or mode) not in tiers: names.append(mode) return { mid: entry, **{f"{mid}-{name}": entry for name in names if f"{mid}-{name}" not in listed}, } def build_snapshot(catalog_path: Path) -> dict: catalog = json.loads(catalog_path.read_text()) snapshot: dict[str, dict] = {} for pid in enabled_providers(): models = (catalog.get(pid) or {}).get("models", {}) listed = set(models) snapshot[pid] = { cid: entry for mid, meta in models.items() if usable(meta) for cid, entry in catalog_entries(mid, meta, listed).items() } return snapshot def build_provider_env(catalog_path: Path) -> dict[str, list[str]]: """Every catalog provider and the environment variables that switch it on.""" catalog = json.loads(catalog_path.read_text()) return { pid: list(meta["env"]) for pid, meta in sorted(catalog.items()) if isinstance(meta.get("env"), list) and meta["env"] } def write_provider_env(table: dict[str, list[str]]) -> None: """One provider a line with its variables inline, the layout prettier (printWidth 120) keeps.""" lines = [f" {json.dumps(pid)}: {json.dumps(names)}" for pid, names in table.items()] PROVIDER_ENV.write_text("{\n" + ",\n".join(lines) + "\n}\n") def provider_env_drift(catalog: Path = DEFAULT_CATALOG) -> list[str]: """Catalog environment variables that packages/guardrails/provider-env.json does not carry.""" if not catalog.exists(): return [f"upstream catalog missing: {catalog.relative_to(ROOT)}"] try: committed = json.loads(PROVIDER_ENV.read_text()) except (OSError, ValueError): committed = None if committed == build_provider_env(catalog): return [] return [ f"{PROVIDER_ENV.relative_to(ROOT)} is out of step with {catalog.relative_to(ROOT)}" " -- run --refresh-snapshot" ] def read_snapshot() -> dict: if not SNAPSHOT.exists(): sys.exit(f"snapshot missing: {SNAPSHOT}\nrun --refresh-snapshot first") return json.loads(SNAPSHOT.read_text()) def set_literal(literal: str) -> dict[str, list[str]]: """Parse a `Record<string, Set<string>>` literal (`paid`, `paidMedia`) out of guardrail-patterns.ts.""" src = PATTERNS.read_text() body = re.search( r"export const " + re.escape(literal) + r"\b[^=]*=\s*\{(.*?)\n\}", src, re.S ) if not body: sys.exit(f"could not locate `export const {literal}` in {PATTERNS}") out: dict[str, list[str]] = {} for hit in re.finditer( r'"?([\w-]+)"?\s*:\s*new Set\(\[(.*?)\]\)', body.group(1), re.S ): out[hit.group(1)] = re.findall(r'"([^"]+)"', hit.group(2)) return out def fill_set_literal( text: str, literal: str, additions: dict[str, list[str]], replace: bool = False ) -> str: """The text with ids added into the `Set` entries of one literal, or with `replace` made equal to them. Only the body of that literal is read, so an entry can never run on into the next one. An entry is `new Set([...])` over several lines, on one line, or empty as prettier writes it, `new Set([])`; it is written back over several lines, one id a line. Every entry must already exist. """ head = re.search(r"export const " + re.escape(literal) + r"\b[^=]*=\s*\{", text) if not head: sys.exit(f"could not locate `export const {literal}` in {PATTERNS}") start, end = head.end(), text.index("\n}", head.end()) body = text[start:end] for pid, ids in additions.items(): if not ids and not replace: continue key = pid if re.fullmatch(r"\w+", pid) else f'"{pid}"' entry = re.compile(r"(\n " + re.escape(key) + r": new Set\(\[)([^\]]*?)(\n \]\),|\]\),)") hit = entry.search(body) if not hit: sys.exit(f"could not locate {literal} entry for {pid} in {PATTERNS}") have = [] if replace else re.findall(r'"([^"]+)"', hit.group(2)) rendered = "".join(f'\n "{mid}",' for mid in sorted(set(have) | set(ids))) body = body[: hit.start()] + hit.group(1) + rendered + "\n ])," + body[hit.end() :] return text[:start] + body + text[end:] def write_set_literal(literal: str, additions: dict[str, list[str]], replace: bool = False) -> None: """fill_set_literal on guardrail-patterns.ts, written back.""" PATTERNS.write_text(fill_set_literal(PATTERNS.read_text(), literal, additions, replace)) def whitelists(path: Path) -> dict[str, list[str]]: cfg = json.loads(path.read_text()) return { pid: val.get("whitelist", []) for pid, val in (cfg.get("provider") or {}).items() } def write_whitelists(path: Path, merged: dict[str, list[str]]) -> None: cfg = json.loads(path.read_text()) for pid, ids in merged.items(): cfg.setdefault("provider", {}).setdefault(pid, {})["whitelist"] = ids path.write_text(json.dumps(cfg, indent=2, ensure_ascii=False) + "\n") def check(snapshot: dict) -> list[str]: problems: list[str] = [] mg, pf = whitelists(MANAGED), whitelists(PROFILE) paid, paid_media = set_literal("paid"), set_literal("paidMedia") for pid in enabled_providers(): have_mg, have_pf = set(mg.get(pid, [])), set(pf.get(pid, [])) if have_mg != have_pf: only_mg = sorted(have_mg - have_pf) only_pf = sorted(have_pf - have_mg) problems.append( f"{pid}: managed and profile disagree -- " f"managed-only={only_mg or '[]'} profile-only={only_pf or '[]'}" ) if not have_mg: # The runtime loader (profile/plugins/guardrail/index.ts) rejects the whole policy while one whitelist # is empty, which denies every model request, so a provider is never left with no model at all. problems.append( f"{pid}: no model is whitelisted; name at least one model id in both model-policy.json copies" ) missing = sorted(set(snapshot.get(pid, {})) - have_mg) if missing: problems.append( f"{pid}: {len(missing)} catalog models are not whitelisted " f"(snapshot has {len(snapshot.get(pid, {}))}, whitelist has {len(have_mg)}): " + ", ".join(missing[:8]) + (f" ... +{len(missing) - 8}" if len(missing) > 8 else "") ) if pid in PAID_PROVIDERS: unclassified = sorted(have_mg - set(paid.get(pid, []))) if unclassified: problems.append( f"{pid}: {len(unclassified)} whitelisted models missing from `paid`, " "so a plan-covered model would be misread as free: " + ", ".join(unclassified[:8]) ) else: # A billed image or video model reads as cost 0 when it has no per-token text prices (MEDIA_TYPES). # `paidMedia` is derived from the catalog alone, so it is kept equal to it, not only filled. billed = {mid for mid, entry in snapshot.get(pid, {}).items() if entry.get("priced")} listed = set(paid_media.get(pid, [])) missing = sorted(billed - listed) if missing: problems.append( f"{pid}: {len(missing)} billed image or video models missing from `paidMedia`, " "so a paid model would be refused as a free tier: " + ", ".join(missing[:8]) ) # Without one price the snapshot says nothing about billing: nothing in `paidMedia` is stale. stale = sorted(listed - billed) if has_prices(snapshot) else [] if stale: problems.append( f"{pid}: {len(stale)} models in `paidMedia` the catalog no longer prices, " "so a free model would be allowed: " + ", ".join(stale[:8]) ) return problems def upstream_drift(snapshot: dict) -> list[str]: """Models upstream's bundled catalog offers that the committed snapshot lacks.""" if not DEFAULT_CATALOG.exists(): return [f"upstream catalog missing: {DEFAULT_CATALOG.relative_to(ROOT)}"] upstream = build_snapshot(DEFAULT_CATALOG) problems: list[str] = [] for pid, models in upstream.items(): missing = sorted(set(models) - set(snapshot.get(pid, {}))) if missing: problems.append( f"{pid}: {len(missing)} models in {DEFAULT_CATALOG.relative_to(ROOT)} are not in the " f"committed snapshot (upstream has {len(models)}, snapshot has {len(snapshot.get(pid, {}))}): " + ", ".join(missing[:8]) + (f" ... +{len(missing) - 8}" if len(missing) > 8 else "") + " -- run --refresh-snapshot --apply" ) # A price that changed without the id leaves the committed `priced` flag stale, and `paidMedia` with it. reflagged = sorted( mid for mid, entry in models.items() if mid in snapshot.get(pid, {}) and entry.get("priced") != snapshot[pid][mid].get("priced") ) if reflagged: problems.append( f"{pid}: {len(reflagged)} models the bundled catalog prices differently from the committed " f"snapshot ({DEFAULT_CATALOG.relative_to(ROOT)} has {len(models)}, snapshot has {len(snapshot.get(pid, {}))}): " + ", ".join(reflagged[:8]) + (f" ... +{len(reflagged) - 8}" if len(reflagged) > 8 else "") + " -- run --refresh-snapshot --apply" ) # The whitelist keeps ids the catalog drops (by design); `paidMedia` must not keep their billing. gone = sorted( mid for mid, entry in snapshot.get(pid, {}).items() if entry.get("priced") and mid not in models ) if gone: problems.append( f"{pid}: {len(gone)} models the committed snapshot lists as billed that " f"{DEFAULT_CATALOG.relative_to(ROOT)} no longer offers: " + ", ".join(gone[:8]) + (f" ... +{len(gone) - 8}" if len(gone) > 8 else "") + " -- run --refresh-snapshot --apply" ) return problems def has_prices(snapshot: dict) -> bool: """Whether the snapshot carries one `priced` flag at all.""" return any("priced" in entry for models in snapshot.values() for entry in models.values()) def billed_media(snapshot: dict) -> dict[str, list[str]]: """Per provider outside PAID_PROVIDERS, the billed image and video models `paidMedia` is made equal to. A snapshot without one `priced` flag comes from a catalog that does not type its models (a v1 `api.json`). It says nothing about media prices, so it must not empty the sets: nothing is returned for them. """ if not has_prices(snapshot): return {} return { pid: sorted(mid for mid, entry in snapshot.get(pid, {}).items() if entry.get("priced")) for pid in enabled_providers() if pid not in PAID_PROVIDERS } def apply(snapshot: dict) -> dict[str, int]: mg, pf = whitelists(MANAGED), whitelists(PROFILE) paid = set_literal("paid") merged: dict[str, list[str]] = {} paid_add: dict[str, list[str]] = {} added: dict[str, int] = {} for pid in enabled_providers(): # add-only: the union keeps ids the catalog does not list (Codex OAuth # models, DeepSeek direct-API ids) that would otherwise be deleted. union = sorted( set(mg.get(pid, [])) | set(pf.get(pid, [])) | set(snapshot.get(pid, {})) ) added[pid] = len(union) - len(set(mg.get(pid, []))) merged[pid] = union if pid in PAID_PROVIDERS: paid_add[pid] = sorted(set(union) - set(paid.get(pid, []))) # A provider's chat models report their real cost; only its billed image and video models need a set. media_add = billed_media(snapshot) write_whitelists(MANAGED, merged) write_whitelists(PROFILE, merged) write_set_literal("paid", paid_add) write_set_literal("paidMedia", media_add, replace=True) return added def main() -> int: ap = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter ) ap.add_argument( "--catalog", type=Path, default=DEFAULT_CATALOG, help=f"models.dev catalog to read, v2 or v1 (default: {DEFAULT_CATALOG.relative_to(ROOT)})", ) ap.add_argument( "--refresh-snapshot", action="store_true", help="regenerate the committed snapshot from --catalog", ) ap.add_argument( "--apply", action="store_true", help="add every snapshot model missing from the whitelists (add-only)", ) args = ap.parse_args() if args.refresh_snapshot: if not args.catalog.exists(): sys.exit(f"catalog not found: {args.catalog}") snapshot = build_snapshot(args.catalog) SNAPSHOT.write_text(json.dumps(snapshot, indent=2, sort_keys=True) + "\n") for pid, models in snapshot.items(): print(f" snapshot {pid:18} {len(models):4} models") print(f"wrote {SNAPSHOT.relative_to(ROOT)}") provider_env = build_provider_env(args.catalog) write_provider_env(provider_env) print(f"wrote {PROVIDER_ENV.relative_to(ROOT)} ({len(provider_env)} providers)") snapshot = read_snapshot() if args.apply: for pid, n in apply(snapshot).items(): print(f" {pid:18} +{n}") print("applied to managed, profile, `paid` and `paidMedia`") # The no-argument check compares with the bundled catalog; a refresh compares with the one it was given. problems = check(snapshot) + upstream_drift(snapshot) + provider_env_drift(args.catalog) if problems: print( "\nFAIL: whitelist is out of step with the catalog snapshot", file=sys.stderr, ) for p in problems: print(f" - {p}", file=sys.stderr) return 1 print( "ok whitelist covers the catalog snapshot in all three copies, " f"and the snapshot covers {DEFAULT_CATALOG.relative_to(ROOT)}" ) return 0 if __name__ == "__main__": raise SystemExit(main()) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |