Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(models): revalidate remote catalog promptly (#993)
Call Whitecf1b4314d04e
diff --git a/docs/plans/backend-model-catalog-service.md b/docs/plans/backend-model-catalog-service.mdindex a339df86b..e19a2bb9b 100644--- a/docs/plans/backend-model-catalog-service.md+++ b/docs/plans/backend-model-catalog-service.md@@ -115,6 +115,9 @@ missing metadata but cannot replace populated values.- `snapshot()` never performs network I/O.- If the persisted remote payload is absent/stale, `snapshot()` starts onedaemon refresh thread and returns immediately.+- Successful remote checks are eligible for revalidation after 60 seconds and+ reuse same-source ETag/Last-Modified validators; a 304 advances the check+ timestamp without replacing the last-known-good catalog.- Remote payloads are strictly validated before replacing the cache.- Success/failure timestamps use separate TTLs; writes are atomic.- Responses expose `catalog_refresh_pending`. The shared TypeScript loader delivers thediff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.pyindex 5852d5807..fe5207877 100644--- a/tests/test_backend_model_catalog.py+++ b/tests/test_backend_model_catalog.py@@ -10,8 +10,9 @@ from vibe import backend_model_catalogclass _FakeResponse:- def __init__(self, payload: dict):+ def __init__(self, payload: dict, *, headers: dict[str, str] | None = None):self.payload = payload+ self.headers = headers or {}def __enter__(self):return self@@ -255,6 +256,17 @@ def test_snapshot_returns_immediately_while_remote_refresh_runs(monkeypatch, tmpassert backend_model_catalog._REMOTE_REFRESH_IN_FLIGHT is False[email protected]("timestamp_key", ["fetched_at", "checked_at"])+def test_remote_catalog_revalidates_after_one_minute(monkeypatch, timestamp_key):+ payload = {timestamp_key: 100.0, "catalog": {"schema_version": 1, "backends": {}}}++ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 159.0)+ assert backend_model_catalog._remote_cache_stale(payload) is False++ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 160.0)+ assert backend_model_catalog._remote_cache_stale(payload) is True++def test_refresh_remote_catalog_persists_validated_cache(monkeypatch, tmp_path):payload = {"schema_version": 1,@@ -268,17 +280,115 @@ def test_refresh_remote_catalog_persists_validated_cache(monkeypatch, tmp_path):monkeypatch.setattr(backend_model_catalog.urllib.request,"urlopen",- lambda request, timeout: _FakeResponse(payload),+ lambda request, timeout: _FakeResponse(+ payload,+ headers={"ETag": '"catalog-v2"', "Last-Modified": "Fri, 24 Jul 2026 18:28:54 GMT"},+ ),)+ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 200.0)catalog = backend_model_catalog.refresh_remote_catalog_now("https://example.test/catalog.json")assert backend_model_catalog.backend_model_entries("claude", catalog)[0]["id"] == "claude-fable-6"persisted = json.loads((tmp_path / "backend_model_catalog.json").read_text(encoding="utf-8"))assert persisted["catalog"] == catalog+ assert persisted["fetched_at"] == 200.0+ assert persisted["checked_at"] == 200.0+ assert persisted["etag"] == '"catalog-v2"'+ assert persisted["last_modified"] == "Fri, 24 Jul 2026 18:28:54 GMT"+ assert persisted["source_key"] == backend_model_catalog._remote_catalog_source_key(+ "https://example.test/catalog.json"+ )+ assert persisted["error"] is None+++def test_refresh_remote_catalog_uses_etag_and_preserves_cache_on_304(monkeypatch, tmp_path):+ previous_catalog = {+ "schema_version": 1,+ "backends": {"claude": {"models": [{"id": "claude-opus-5"}]}},+ }+ monkeypatch.setattr(backend_model_catalog.paths, "get_state_dir", lambda: tmp_path)+ backend_model_catalog._write_cached_remote_payload(+ {+ "fetched_at": 100.0,+ "checked_at": 150.0,+ "catalog": previous_catalog,+ "etag": '"catalog-v1"',+ "error": None,+ "source_key": backend_model_catalog._remote_catalog_source_key(+ "https://example.test/catalog.json"+ ),+ }+ )++ def not_modified(request, timeout):+ assert request.get_header("If-none-match") == '"catalog-v1"'+ assert request.get_header("Cache-control") == "no-cache"+ raise backend_model_catalog.urllib.error.HTTPError(+ request.full_url,+ 304,+ "Not Modified",+ {"ETag": '"catalog-v1"'},+ None,+ )++ monkeypatch.setattr(backend_model_catalog.urllib.request, "urlopen", not_modified)+ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 200.0)++ catalog = backend_model_catalog.refresh_remote_catalog_now("https://example.test/catalog.json")++ assert catalog == previous_catalog+ persisted = json.loads((tmp_path / "backend_model_catalog.json").read_text(encoding="utf-8"))+ assert persisted["catalog"] == previous_catalog+ assert persisted["fetched_at"] == 100.0+ assert persisted["checked_at"] == 200.0+ assert persisted["etag"] == '"catalog-v1"'+ assert persisted["source_key"] == backend_model_catalog._remote_catalog_source_key(+ "https://example.test/catalog.json"+ )assert persisted["error"] is None+def test_refresh_remote_catalog_does_not_reuse_validator_for_another_url(monkeypatch, tmp_path):+ previous_catalog = {+ "schema_version": 1,+ "backends": {"claude": {"models": [{"id": "claude-opus-4-8"}]}},+ }+ next_catalog = {+ "schema_version": 1,+ "backends": {"claude": {"models": [{"id": "claude-opus-5"}]}},+ }+ monkeypatch.setattr(backend_model_catalog.paths, "get_state_dir", lambda: tmp_path)+ backend_model_catalog._write_cached_remote_payload(+ {+ "fetched_at": 100.0,+ "checked_at": 150.0,+ "catalog": previous_catalog,+ "etag": '"old-source"',+ "source_key": backend_model_catalog._remote_catalog_source_key(+ "https://old.example.test/catalog.json"+ ),+ "error": None,+ }+ )++ def changed_source(request, timeout):+ assert request.get_header("If-none-match") is None+ return _FakeResponse(next_catalog)++ monkeypatch.setattr(backend_model_catalog.urllib.request, "urlopen", changed_source)+ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 200.0)++ catalog = backend_model_catalog.refresh_remote_catalog_now("https://new.example.test/catalog.json")++ assert catalog == next_catalog+ persisted = json.loads((tmp_path / "backend_model_catalog.json").read_text(encoding="utf-8"))+ assert "etag" not in persisted+ assert persisted["source_key"] == backend_model_catalog._remote_catalog_source_key(+ "https://new.example.test/catalog.json"+ )++def test_malformed_refresh_preserves_last_good_catalog(monkeypatch, tmp_path):previous_catalog = {"schema_version": 1,@@ -291,7 +401,16 @@ def test_malformed_refresh_preserves_last_good_catalog(monkeypatch, tmp_path):lambda request, timeout: _FakeResponse({"schema_version": 2, "models": []}),)backend_model_catalog._write_cached_remote_payload(- {"fetched_at": 100.0, "catalog": previous_catalog, "error": None}+ {+ "fetched_at": 100.0,+ "checked_at": 150.0,+ "catalog": previous_catalog,+ "etag": '"catalog-v1"',+ "error": None,+ "source_key": backend_model_catalog._remote_catalog_source_key(+ "https://example.test/catalog.json"+ ),+ })monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 200.0)monkeypatch.setattr(backend_model_catalog, "_REMOTE_REFRESH_IN_FLIGHT", True)@@ -301,6 +420,11 @@ def test_malformed_refresh_preserves_last_good_catalog(monkeypatch, tmp_path):persisted = json.loads((tmp_path / "backend_model_catalog.json").read_text(encoding="utf-8"))assert persisted["catalog"] == previous_catalogassert persisted["fetched_at"] == 100.0+ assert persisted["checked_at"] == 150.0+ assert persisted["etag"] == '"catalog-v1"'+ assert persisted["source_key"] == backend_model_catalog._remote_catalog_source_key(+ "https://example.test/catalog.json"+ )assert persisted["failed_at"] == 200.0assert "Unsupported backend model catalog schema version" in persisted["error"]diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.pyindex 8ea549104..e2f8c2707 100644--- a/vibe/backend_model_catalog.py+++ b/vibe/backend_model_catalog.py@@ -1,10 +1,12 @@from __future__ import annotations+import hashlibimport jsonimport osimport tempfileimport threadingimport time+import urllib.errorimport urllib.requestfrom pathlib import Pathfrom typing import Any, Iterable, Sequence@@ -18,7 +20,7 @@ REMOTE_CATALOG_URL_ENV = "AVIBE_BACKEND_MODEL_CATALOG_URL"DEFAULT_REMOTE_CATALOG_URL = ("https://raw.githubusercontent.com/avibe-bot/avibe/master/vibe/data/backend_models.json")-REMOTE_CATALOG_TTL_SECONDS = 6 * 60 * 60+REMOTE_CATALOG_REVALIDATE_SECONDS = 60REMOTE_CATALOG_FAILURE_TTL_SECONDS = 10 * 60REMOTE_CATALOG_TIMEOUT_SECONDS = 3.0REMOTE_CATALOG_USER_AGENT = "avibe/backend-model-catalog"@@ -115,20 +117,95 @@ def schedule_remote_catalog_refresh() -> bool:def refresh_remote_catalog_now(url: str | None = None) -> dict[str, Any]:- catalog = fetch_remote_catalog(url=url)- payload = {"fetched_at": time.time(), "catalog": catalog, "error": None}+ previous = _cached_remote_payload()+ request_url = _remote_catalog_url(url)+ source_key = _remote_catalog_source_key(request_url)+ same_source = previous.get("source_key") == source_key+ catalog, validators = _fetch_remote_catalog_response(+ url=request_url,+ etag=previous.get("etag") if same_source else None,+ last_modified=previous.get("last_modified") if same_source else None,+ )+ now = time.time()+ not_modified = catalog is None+ if not_modified:+ catalog = previous.get("catalog")+ if not isinstance(catalog, dict):+ catalog, validators = _fetch_remote_catalog_response(url=request_url)+ not_modified = False+ if not isinstance(catalog, dict):+ raise ValueError("Remote backend model catalog returned no content")++ payload = {+ "fetched_at": previous.get("fetched_at", now) if not_modified else now,+ "checked_at": now,+ "catalog": catalog,+ "error": None,+ "source_key": source_key,+ }+ for key in ("etag", "last_modified"):+ value = validators.get(key)+ if not_modified and not value:+ value = previous.get(key)+ if isinstance(value, str) and value:+ payload[key] = value_write_cached_remote_payload(payload)return catalogdef fetch_remote_catalog(url: str | None = None) -> dict[str, Any]:- request_url = (url or os.environ.get(REMOTE_CATALOG_URL_ENV) or DEFAULT_REMOTE_CATALOG_URL).strip()- request = urllib.request.Request(request_url, headers={"User-Agent": REMOTE_CATALOG_USER_AGENT})- with urllib.request.urlopen( # noqa: S310 - fixed public catalog or explicit operator override- request,- timeout=REMOTE_CATALOG_TIMEOUT_SECONDS,- ) as response:- return _normalize_catalog(json.loads(response.read().decode("utf-8")), strict=True)+ catalog, _validators = _fetch_remote_catalog_response(url=url)+ if catalog is None:+ raise ValueError("Remote backend model catalog returned no content")+ return catalog+++def _fetch_remote_catalog_response(+ url: str | None = None,+ *,+ etag: object = None,+ last_modified: object = None,+) -> tuple[dict[str, Any] | None, dict[str, str]]:+ request_url = _remote_catalog_url(url)+ headers = {+ "User-Agent": REMOTE_CATALOG_USER_AGENT,+ "Cache-Control": "no-cache",+ }+ if isinstance(etag, str) and etag:+ headers["If-None-Match"] = etag+ if isinstance(last_modified, str) and last_modified:+ headers["If-Modified-Since"] = last_modified+ request = urllib.request.Request(request_url, headers=headers)+ try:+ with urllib.request.urlopen( # noqa: S310 - fixed public catalog or explicit operator override+ request,+ timeout=REMOTE_CATALOG_TIMEOUT_SECONDS,+ ) as response:+ catalog = _normalize_catalog(json.loads(response.read().decode("utf-8")), strict=True)+ return catalog, _response_validators(response.headers)+ except urllib.error.HTTPError as exc:+ if exc.code == 304:+ return None, _response_validators(exc.headers)+ raise+++def _remote_catalog_url(url: str | None = None) -> str:+ return (url or os.environ.get(REMOTE_CATALOG_URL_ENV) or DEFAULT_REMOTE_CATALOG_URL).strip()+++def _remote_catalog_source_key(url: str) -> str:+ return hashlib.sha256(url.encode("utf-8")).hexdigest()+++def _response_validators(headers: object) -> dict[str, str]:+ if not hasattr(headers, "get"):+ return {}+ validators = {}+ for header, key in (("ETag", "etag"), ("Last-Modified", "last_modified")):+ value = headers.get(header)+ if isinstance(value, str) and value:+ validators[key] = value+ return validatorsdef backend_model_entries(backend: str, catalog: dict[str, Any] | None) -> list[dict[str, Any]]:@@ -428,14 +505,16 @@ def _cached_remote_payload() -> dict[str, Any]:def _remote_cache_stale(payload: dict[str, Any]) -> bool:fetched_at = payload.get("fetched_at")+ checked_at = payload.get("checked_at")+ last_success_at = checked_at if isinstance(checked_at, (int, float)) else fetched_atfailed_at = payload.get("failed_at")if isinstance(failed_at, (int, float)) and (- not isinstance(fetched_at, (int, float)) or float(failed_at) >= float(fetched_at)+ not isinstance(last_success_at, (int, float)) or float(failed_at) >= float(last_success_at)):return time.time() - float(failed_at) >= REMOTE_CATALOG_FAILURE_TTL_SECONDS- if not isinstance(fetched_at, (int, float)):+ if not isinstance(last_success_at, (int, float)):return True- return time.time() - float(fetched_at) >= REMOTE_CATALOG_TTL_SECONDS+ return time.time() - float(last_success_at) >= REMOTE_CATALOG_REVALIDATE_SECONDSdef _refresh_remote_catalog_worker() -> None:@@ -451,6 +530,15 @@ def _refresh_remote_catalog_worker() -> None:}if isinstance(previous.get("fetched_at"), (int, float)):payload["fetched_at"] = previous["fetched_at"]+ if isinstance(previous.get("checked_at"), (int, float)):+ payload["checked_at"] = previous["checked_at"]+ for key in ("etag", "last_modified"):+ value = previous.get(key)+ if isinstance(value, str) and value:+ payload[key] = value+ source_key = previous.get("source_key")+ if isinstance(source_key, str) and source_key:+ payload["source_key"] = source_key_write_cached_remote_payload(payload)finally:with _REMOTE_LOCK:@@ -482,10 +570,15 @@ def _read_cached_remote_payload(path: Path) -> dict[str, Any]:catalog_valid = Trueexcept ValueError:pass- for key in ("fetched_at", "failed_at"):+ for key in ("fetched_at", "checked_at", "failed_at"):value = payload.get(key)- if isinstance(value, (int, float)) and (key != "fetched_at" or catalog_valid):+ if isinstance(value, (int, float)) and (key not in {"fetched_at", "checked_at"} or catalog_valid):normalized[key] = value+ if catalog_valid:+ for key in ("etag", "last_modified", "source_key"):+ value = payload.get(key)+ if isinstance(value, str) and value:+ normalized[key] = valueerror = payload.get("error")if isinstance(error, str) or error is None:normalized["error"] = error