Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(model-hub): compose backend model catalogs (#1837)

Call Whitef5663bdd00a9
diff --git a/config/v2_config.py b/config/v2_config.py
index 8aeb19856..69a12617b 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -669,6 +669,7 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[
"routes",
"menu",
"models",
+ "removed_model_ids",
}:
return payload, False, ()
expected_menu_kind = "open" if backend == "opencode" else "fixed"
@@ -881,8 +882,9 @@ def _migrate_opencode_active_turn_timeout_on_load(payload: dict) -> dict:
def _migrate_config_payload_on_load(payload: dict) -> tuple[dict, bool, tuple[str, ...]]:
migrated, changed, warnings = _migrate_legacy_model_hub_payload(payload)
migrated = _migrate_fixed_menu_routes_on_load(migrated)
+ model_hub_changed = changed or migrated.get("model_hub") != payload.get("model_hub")
migrated = _migrate_opencode_active_turn_timeout_on_load(migrated)
- return migrated, changed, warnings
+ return migrated, model_hub_changed, warnings
# The spellings a hand-edited config may use for a boolean, both sides in one
@@ -3196,7 +3198,7 @@ _BACKEND_MODEL_OUTPUT_MODALITIES = frozenset(
@dataclass
class ModelHubBackendModelConfig:
id: str
- origin: Literal["builtin", "models_dev", "manual"] = "manual"
+ origin: Literal["builtin", "provider", "models_dev", "manual"] = "manual"
display_name: Optional[str] = None
models_dev_id: Optional[str] = None
context_window: Optional[int] = None
@@ -3249,7 +3251,7 @@ class ModelHubBackendModelConfig:
or _contains_model_hub_credential_material(model_id)
):
raise ValueError("Config 'model_hub.agents.models.id' is invalid")
- if origin not in {"builtin", "models_dev", "manual"}:
+ if origin not in {"builtin", "provider", "models_dev", "manual"}:
raise ValueError("Config 'model_hub.agents.models.origin' is invalid")
for name, value in (
("display_name", display_name),
@@ -3341,6 +3343,31 @@ class ModelHubBackendModelConfig:
}
+def normalize_storable_backend_model_text(
+ value: object,
+ *,
+ field_name: Literal["display_name", "reasoning_efforts"],
+) -> Optional[str]:
+ """Normalize one proposed metadata value through the persisted model contract."""
+
+ if not isinstance(value, str):
+ return None
+ normalized = value.strip()
+ candidate = {
+ "id": "metadata-proposal",
+ field_name: (
+ normalized if field_name == "display_name" else [normalized]
+ ),
+ }
+ try:
+ model = ModelHubBackendModelConfig.from_payload(candidate)
+ except (TypeError, ValueError):
+ return None
+ if field_name == "display_name":
+ return model.display_name
+ return model.reasoning_efforts[0]
+
+
def _default_backend_models(backend: str) -> list[ModelHubBackendModelConfig]:
if backend not in {"claude", "codex"}:
return []
@@ -3387,6 +3414,7 @@ class ModelHubAgentSupplyConfig:
routes: dict[str, ModelHubRouteConfig] = field(default_factory=dict)
menu: Optional[ModelHubMenuConfig] = None
models: list[ModelHubBackendModelConfig] = field(default_factory=list)
+ removed_model_ids: list[str] = field(default_factory=list)
@classmethod
def default(cls, backend: str, *, mode: Literal["hub", "direct"]) -> "ModelHubAgentSupplyConfig":
@@ -3425,6 +3453,7 @@ class ModelHubAgentSupplyConfig:
"routes",
"menu",
"models",
+ "removed_model_ids",
}:
raise ValueError("Config 'model_hub.agents' contains unknown fields")
raw_backend = payload.get("backend")
@@ -3457,6 +3486,20 @@ class ModelHubAgentSupplyConfig:
}
menu = ModelHubMenuConfig.from_payload(menu_payload) if menu_payload is not None else None
models_payload = payload.get("models")
+ removed_model_ids = payload.get("removed_model_ids", [])
+ if (
+ not isinstance(removed_model_ids, list)
+ or any(
+ not isinstance(model_id, str)
+ or not model_id
+ or _contains_model_hub_credential_material(model_id)
+ for model_id in removed_model_ids
+ )
+ or len(set(removed_model_ids)) != len(removed_model_ids)
+ ):
+ raise ValueError(
+ "Config 'model_hub.agents.removed_model_ids' must be a unique array of strings"
+ )
if models_payload is None:
if backend == "opencode":
legacy_ids = list(menu.checked if menu else ())
@@ -3505,6 +3548,7 @@ class ModelHubAgentSupplyConfig:
routes=routes,
menu=menu,
models=models,
+ removed_model_ids=list(removed_model_ids),
)
def to_payload(self) -> dict:
@@ -3520,6 +3564,13 @@ class ModelHubAgentSupplyConfig:
"menu": self.menu.to_payload() if self.menu else None,
}
payload["models"] = [model.to_payload() for model in self.models]
+ payload["removed_model_ids"] = list(self.removed_model_ids)
+ return payload
+
+ def to_agent_supply_payload(self) -> dict:
+ payload = self.to_payload()
+ payload.pop("models")
+ payload.pop("removed_model_ids")
return payload
diff --git a/core/controller.py b/core/controller.py
index 8e3ab2ee1..f0cf04ebd 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -82,6 +82,7 @@ logger = logging.getLogger(__name__)
_RUNTIME_WORK_SHUTDOWN_GRACE_SECONDS = 10.0
_MEMORY_SHUTDOWN_BUDGET_SECONDS = 15.0
_DISABLED_MEMORY_CLEANUP_WAIT_SECONDS = 1.0
+_MODEL_HUB_SNAPSHOT_RECONCILE_INTERVAL_SECONDS = 5 * 60
def _load_memory_capture_types() -> tuple[type, type, type]:
@@ -402,6 +403,152 @@ class Controller:
# running until backend restoration and exact reconciliation complete.
self.session_turns.reset_legacy_ownerless_status()
+ def _model_hub_snapshot_refresh_completed(self) -> None:
+ """Move a worker completion onto the controller's event loop."""
+
+ if getattr(self, "_shutdown_requested", False) or getattr(
+ self,
+ "_model_hub_snapshot_reconcile_stopping",
+ False,
+ ):
+ return
+ pending = getattr(self, "_model_hub_snapshot_refresh_pending", None)
+ if pending is None:
+ return
+ pending.set()
+ loop = getattr(self, "_loop", None)
+ if loop is None or loop.is_closed() or not loop.is_running():
+ return
+ loop.call_soon_threadsafe(self._schedule_model_hub_snapshot_reconcile)
+
+ def _schedule_model_hub_snapshot_reconcile(self) -> None:
+ if getattr(self, "_shutdown_requested", False) or getattr(
+ self,
+ "_model_hub_snapshot_reconcile_stopping",
+ False,
+ ):
+ return
+ pending = getattr(self, "_model_hub_snapshot_refresh_pending", None)
+ service = getattr(self, "model_hub_service", None)
+ if pending is None or not pending.is_set() or service is None:
+ return
+ task = getattr(self, "_model_hub_snapshot_reconcile_task", None)
+ if task is not None and not task.done():
+ return
+ pending.clear()
+
+ async def reconcile() -> None:
+ try:
+ await service.reconcile_builtin_models()
+ except Exception:
+ logger.warning(
+ "Model Hub built-in reconciliation failed after snapshot refresh",
+ exc_info=True,
+ )
+ finally:
+ self._model_hub_snapshot_reconcile_task = None
+ if (
+ pending.is_set()
+ and not getattr(self, "_shutdown_requested", False)
+ and not getattr(
+ self,
+ "_model_hub_snapshot_reconcile_stopping",
+ False,
+ )
+ ):
+ self._schedule_model_hub_snapshot_reconcile()
+
+ loop = getattr(self, "_loop", None)
+ if loop is None:
+ loop = asyncio.get_running_loop()
+ self._model_hub_snapshot_reconcile_task = loop.create_task(
+ reconcile(),
+ name="model-hub-snapshot-refresh-reconcile",
+ )
+
+ async def _model_hub_snapshot_reconcile_loop(self) -> None:
+ """Re-read cross-process snapshot inputs on the controller cadence."""
+
+ try:
+ while True:
+ interval = max(
+ 0.01,
+ float(
+ getattr(
+ self,
+ "_model_hub_snapshot_reconcile_interval_seconds",
+ _MODEL_HUB_SNAPSHOT_RECONCILE_INTERVAL_SECONDS,
+ )
+ ),
+ )
+ await asyncio.sleep(interval)
+ if getattr(self, "_shutdown_requested", False) or getattr(
+ self,
+ "_model_hub_snapshot_reconcile_stopping",
+ False,
+ ):
+ return
+ pending = getattr(
+ self,
+ "_model_hub_snapshot_refresh_pending",
+ None,
+ )
+ if pending is None:
+ return
+ pending.set()
+ self._schedule_model_hub_snapshot_reconcile()
+ finally:
+ if getattr(
+ self,
+ "_model_hub_snapshot_reconcile_loop_task",
+ None,
+ ) is asyncio.current_task():
+ self._model_hub_snapshot_reconcile_loop_task = None
+
+ def _start_model_hub_snapshot_reconcile_loop(self) -> None:
+ if (
+ getattr(self, "model_hub_service", None) is None
+ or getattr(self, "_shutdown_requested", False)
+ or getattr(self, "_model_hub_snapshot_reconcile_stopping", False)
+ ):
+ return
+ task = getattr(self, "_model_hub_snapshot_reconcile_loop_task", None)
+ if task is not None and not task.done():
+ return
+ self._model_hub_snapshot_reconcile_loop_task = asyncio.create_task(
+ self._model_hub_snapshot_reconcile_loop(),
+ name="model-hub-snapshot-reconcile-loop",
+ )
+
+ async def _stop_model_hub_snapshot_reconciliation(self) -> None:
+ """Quiesce snapshot tasks before the Model Hub service is stopped."""
+
+ self._model_hub_snapshot_reconcile_stopping = True
+ pending = getattr(self, "_model_hub_snapshot_refresh_pending", None)
+ if pending is not None:
+ pending.clear()
+
+ loop_task = getattr(
+ self,
+ "_model_hub_snapshot_reconcile_loop_task",
+ None,
+ )
+ if loop_task is not None and not loop_task.done():
+ loop_task.cancel()
+ await asyncio.gather(loop_task, return_exceptions=True)
+ self._model_hub_snapshot_reconcile_loop_task = None
+
+ reconcile_task = getattr(
+ self,
+ "_model_hub_snapshot_reconcile_task",
+ None,
+ )
+ if reconcile_task is not None and not reconcile_task.done():
+ await asyncio.gather(reconcile_task, return_exceptions=True)
+ self._model_hub_snapshot_reconcile_task = None
+ if pending is not None:
+ pending.clear()
+
def _init_model_hub(self) -> None:
"""Create the Model Hub aggregate only for an explicit release opt-in."""
@@ -410,6 +557,10 @@ class Controller:
self.model_hub_service = None
self.model_hub_turn_gateway = None
self.model_hub_runtime = None
+ self._model_hub_snapshot_refresh_pending = threading.Event()
+ self._model_hub_snapshot_reconcile_task = None
+ self._model_hub_snapshot_reconcile_loop_task = None
+ self._model_hub_snapshot_reconcile_stopping = False
if not is_model_hub_enabled():
return
@@ -419,6 +570,7 @@ class Controller:
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
from modules.agents.model_hub import ModelHubRuntimeRouter
from vibe.api import resolve_cli_paths
+ from vibe.backend_model_catalog import set_remote_catalog_refresh_completed
def default_vibe_agent_model(backend: str) -> Optional[str]:
agent = self.vibe_agent_store.get_default_agent()
@@ -529,6 +681,18 @@ class Controller:
cli_presence_refresh=refresh_cli_presence,
backend_catalog_changed=backend_catalog_changed,
)
+ set_remote_catalog_refresh_completed(
+ self._model_hub_snapshot_refresh_completed
+ )
+ try:
+ asyncio.run(
+ self.model_hub_service.reconcile_builtin_models(notify=False)
+ )
+ except Exception:
+ logger.warning(
+ "Model Hub built-in reconciliation failed during startup",
+ exc_info=True,
+ )
self.model_hub_turn_gateway = ModelHubTurnGateway(
self.model_hub_service,
language_provider=lambda: self.config.language,
@@ -2742,6 +2906,15 @@ class Controller:
except Exception as e:
logger.error("Failed to start runtime command watcher: %s", e, exc_info=True)
+ try:
+ self._start_model_hub_snapshot_reconcile_loop()
+ except Exception as e:
+ logger.error(
+ "Failed to start Model Hub snapshot reconciliation: %s",
+ e,
+ exc_info=True,
+ )
+
try:
claude_timeout, codex_timeout = self._get_idle_cleanup_timeouts()
if (claude_timeout > 0 or codex_timeout > 0) and (
@@ -3735,6 +3908,8 @@ class Controller:
if callable(drain_activity):
await drain_activity()
+ await self._stop_model_hub_snapshot_reconciliation()
+
service_stops: list[asyncio.Task[None]] = []
for service_name in (
"model_hub_service",
@@ -3769,6 +3944,7 @@ class Controller:
try:
self._loop = asyncio.new_event_loop()
asyncio.set_event_loop(self._loop)
+ self._schedule_model_hub_snapshot_reconcile()
memory_runtime = getattr(self, "memory_runtime", None)
if memory_runtime is not None:
self._start_memory_capture_adapter(memory_runtime)
diff --git a/core/handlers/model_hub/catalog_admission.py b/core/handlers/model_hub/catalog_admission.py
new file mode 100644
index 000000000..cfa7b8026
--- /dev/null
+++ b/core/handlers/model_hub/catalog_admission.py
@@ -0,0 +1,64 @@
+"""One admission boundary for generated backend-model catalog rows."""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+from typing import Any, Literal
+
+from config.v2_config import (
+ ModelHubBackendModelConfig,
+ canonical_opencode_menu_identity,
+)
+
+from .identifiers import canonical_model_id
+from .resolver import BackendName
+
+
+def backend_model_admission_error(
+ backend: BackendName | None,
+ model_id: object,
+ *,
+ claude_builtin_ids: Iterable[str] = (),
+) -> Literal["backend_model_id_invalid", "backend_model_id_prefix"] | None:
+ """Return the request-boundary error for one generated model identity."""
+
+ canonical = canonical_model_id(model_id)
+ if canonical is None or canonical != model_id:
+ return "backend_model_id_invalid"
+ if backend == "opencode":
+ try:
+ canonical_opencode_menu_identity(canonical)
+ except ValueError:
+ return "backend_model_id_invalid"
+ if (
+ backend == "claude"
+ and canonical not in set(claude_builtin_ids)
+ and not canonical.startswith(("claude-", "anthropic-"))
+ ):
+ return "backend_model_id_prefix"
+ return None
+
+
+def admissible_backend_model(
+ backend: BackendName | None,
+ model_id: object,
+ metadata: Mapping[str, Any],
+ *,
+ claude_builtin_ids: Iterable[str] = (),
+) -> ModelHubBackendModelConfig | None:
+ """Validate one producer row against identity and persisted-shape rules."""
+
+ if (
+ backend_model_admission_error(
+ backend,
+ model_id,
+ claude_builtin_ids=claude_builtin_ids,
+ )
+ is not None
+ ):
+ return None
+ try:
+ model = ModelHubBackendModelConfig.from_payload({"id": model_id, **dict(metadata)})
+ except (TypeError, ValueError):
+ return None
+ return model if model.id == model_id else None
diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.py
index ead2fe546..c908d025c 100644
--- a/core/handlers/model_hub/resolver.py
+++ b/core/handlers/model_hub/resolver.py
@@ -100,11 +100,18 @@ def source_eligible_for_backend(source: ModelHubSourceConfig, backend: str) -> b
return ModelHubConfig.source_eligible_for_backend(source, backend)
+def opencode_source_model_identity(
+ source: ModelHubSourceConfig,
+ model_id: str,
+) -> str:
+ return opencode_model_id(source.vendor, model_id)
+
+
def opencode_inventory_menu_ids(config: ModelHubConfig) -> frozenset[str]:
"""Return OpenCode identities backed by current eligible inventory."""
identities = {
- opencode_model_id(source.vendor, model.id)
+ opencode_source_model_identity(source, model.id)
for source in config.sources
if source_eligible_for_backend(source, "opencode")
for model in source.models
@@ -206,13 +213,14 @@ def matching_v1_model_id(
requested_model: str,
source: ModelHubSourceConfig,
checked_models: tuple[str, ...] = (),
+ include_manual: bool = False,
) -> str | None:
"""Return one concrete observed model for the frozen add-time matching-v1."""
observed_models = tuple(
model
for model in source.models
- if model.provenance == "discovered" and not model.retired
+ if (include_manual or model.provenance == "discovered") and not model.retired
)
if backend == "opencode":
@@ -225,7 +233,7 @@ def matching_v1_model_id(
exact = [
model.id
for model in observed_models
- if opencode_model_id(source.vendor, model.id) == requested_model
+ if opencode_source_model_identity(source, model.id) == requested_model
]
return exact[0] if len(exact) == 1 else None
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index 04bd53d61..9a5f3d22f 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -112,10 +112,18 @@ async def dispatch_model_hub_rpc(
await _refresh_agent_presence(service)
return await asyncio.to_thread(service.list_agents)
if operation == "get_agent_sources":
+ backend = payload.get("backend")
return await asyncio.to_thread(
service.get_agent_sources,
- payload.get("backend"),
+ backend,
)
+ if operation == "agent_model_candidates":
+ backend = payload.get("backend")
+ if backend in ("claude", "codex", "opencode"):
+ await _refresh_agent_presence(service, (backend,))
+ if backend != "opencode":
+ await service.reconcile_builtin_models((backend,))
+ return await asyncio.to_thread(service.agent_model_candidates, backend)
if operation == "set_agent_sources":
await _refresh_payload_backend(service, payload.get("backend"))
return await service.set_agent_sources(
@@ -135,10 +143,15 @@ async def dispatch_model_hub_rpc(
return await service.set_agent_mode(payload.get("backend"), payload.get("mode"))
if operation == "set_agent_models":
await _refresh_payload_backend(service, payload.get("backend"))
+ backend = payload.get("backend")
return await service.set_agent_models(
- payload.get("backend"),
+ backend,
payload.get("baseline"),
payload.get("models"),
+ expected_suppliers=payload.get("expected_suppliers"),
+ force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
if operation == "models_dev_matches":
return await asyncio.to_thread(
@@ -151,12 +164,6 @@ async def dispatch_model_hub_rpc(
payload.get("model_id"),
payload.get("chain"),
)
- if operation == "set_opencode_menu":
- await _refresh_agent_presence(service, ("opencode",))
- return await service.set_opencode_menu(
- payload.get("baseline"),
- payload.get("menu"),
- )
if operation == "add_custom_model":
return await service.add_custom_model(payload.get("source_id"), payload.get("model"))
if operation == "update_model_reasoning_efforts":
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index a4279795b..cdee84e5c 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -32,6 +32,7 @@ from config.v2_config import (
ModelHubSourceUsageConfig,
V2Config,
canonical_opencode_menu_identity,
+ normalize_storable_backend_model_text,
normalize_model_hub_base_url,
normalize_model_hub_vendor_id,
validate_model_hub_source_client_nonce,
@@ -63,6 +64,10 @@ from .adapter import (
validate_source_observation,
)
from .async_owner import await_owned_task
+from .catalog_admission import (
+ admissible_backend_model,
+ backend_model_admission_error,
+)
from .classification import (
ResolutionDecision,
classify_outcome,
@@ -112,7 +117,7 @@ from .resolver import (
allowed_origins,
inspect_exact_hop,
matching_v1_model_id as _matching_v1_model_id,
- opencode_inventory_menu_ids,
+ opencode_source_model_identity,
resolve_model_hub_turn,
source_after_cooldown_recovery,
source_eligible_for_backend,
@@ -122,6 +127,28 @@ from .revocations import CredentialRevocationJournal
from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, SourceIdentity, UsageWriter
CONTRACT_VERSION = 7
+
+
+def _storable_backend_model_metadata(
+ display_name: object,
+ reasoning_efforts: object,
+) -> tuple[Optional[str], list[str]]:
+ proposed_display_name = normalize_storable_backend_model_text(
+ display_name,
+ field_name="display_name",
+ )
+ proposed_efforts: list[str] = []
+ if isinstance(reasoning_efforts, (list, tuple)):
+ for effort in reasoning_efforts:
+ proposed = normalize_storable_backend_model_text(
+ effort,
+ field_name="reasoning_efforts",
+ )
+ if proposed is not None and proposed not in proposed_efforts:
+ proposed_efforts.append(proposed)
+ return proposed_display_name, proposed_efforts
+
+
AGENT_CHAIN_CONTRACT_VERSION = 7
PROBE_RESULT_CONTRACT_VERSION = 7
_REORDER_ORDER_UNSET = object()
@@ -751,6 +778,9 @@ class ModelHubService:
self._runtime_install_reconcile_lock = asyncio.Lock()
self._runtime_install_reconciled = False
self._runtime_lifecycle_lock = asyncio.Lock()
+ self._builtin_snapshot_generations: dict[BackendName, str] = {}
+ self._builtin_snapshot_cache: dict[BackendName, list[dict[str, Any]]] = {}
+ self._pending_builtin_catalog_refresh: set[BackendName] = set()
@staticmethod
def _source(config: ModelHubConfig, source_id: str) -> ModelHubSourceConfig:
@@ -1758,6 +1788,47 @@ class ModelHubService:
continue
route.hops = (*route.hops, ModelHubRouteHopConfig(source.id, matched_model))
+ def _matching_menu_model_hops(
+ self,
+ config: ModelHubConfig,
+ backend: BackendName,
+ menu_model: str,
+ ) -> tuple[ModelHubRouteHopConfig, ...]:
+ """Project matching-v1 in placement-v1 order for one menu model."""
+
+ agent = config.agents[backend]
+ source_by_id = {source.id: source for source in config.sources}
+ hops: list[ModelHubRouteHopConfig] = []
+ checked_models = self._agent_menu_model_ids(agent)
+ if menu_model not in checked_models:
+ checked_models = (*checked_models, menu_model)
+ for source_id in agent.sources.order:
+ source = source_by_id.get(source_id)
+ if source is None or not self._eligible_for_agent(source, backend):
+ continue
+ matched_model = _matching_v1_model_id(
+ backend=backend,
+ requested_model=menu_model,
+ source=source,
+ checked_models=checked_models,
+ include_manual=True,
+ )
+ if matched_model is not None:
+ hops.append(ModelHubRouteHopConfig(source.id, matched_model))
+ return tuple(hops)
+
+ def _seed_menu_model_route(
+ self,
+ config: ModelHubConfig,
+ backend: BackendName,
+ menu_model: str,
+ ) -> None:
+ """Apply matching-v1 and placement-v1 once for a newly added menu row."""
+
+ config.agents[backend].routes[menu_model] = ModelHubRouteConfig(
+ hops=self._matching_menu_model_hops(config, backend, menu_model)
+ )
+
@staticmethod
def _agent_menu_model_ids(agent: ModelHubAgentSupplyConfig) -> tuple[str, ...]:
return tuple(model.id for model in agent.models)
@@ -3687,8 +3758,7 @@ class ModelHubService:
),
}
)
- agent_payload = agent.to_payload()
- agent_payload.pop("models", None)
+ agent_payload = agent.to_agent_supply_payload()
agent_payload["routes"] = (
agent_payload["routes"] if agent.mode == "hub" else None
)
@@ -3713,6 +3783,176 @@ class ModelHubService:
"standard_vendors": standard_vendors,
}
+ def _candidate_suppliers(
+ self,
+ config: ModelHubConfig,
+ backend: BackendName,
+ candidate_id: str,
+ ) -> tuple[list[dict], Optional[str], list[str]]:
+ source_by_id = {source.id: source for source in config.sources}
+ suppliers: list[dict] = []
+ display_name: Optional[str] = None
+ reasoning_efforts: list[str] = []
+ for hop in self._matching_menu_model_hops(config, backend, candidate_id):
+ source = source_by_id[hop.source_id]
+ model = next(
+ (
+ item
+ for item in source.models
+ if item.id == hop.model_id and not item.retired
+ ),
+ None,
+ )
+ if model is None:
+ continue
+ suppliers.append(
+ {
+ "source_id": source.id,
+ "source_name": source.display_name,
+ "model_id": hop.model_id,
+ }
+ )
+ proposed_name, proposed_efforts = _storable_backend_model_metadata(
+ model.display_name,
+ model.reasoning_efforts,
+ )
+ if display_name is None and proposed_name is not None:
+ display_name = proposed_name
+ for effort in proposed_efforts:
+ if effort not in reasoning_efforts:
+ reasoning_efforts.append(effort)
+ return suppliers, display_name, reasoning_efforts
+
+ def agent_model_candidates(self, backend: str) -> dict:
+ agent_backend = cast(BackendName, backend)
+ config = self.store.load()
+ agent = self._agent(config, backend)
+ menu_models = self._catalog_models_payload(agent)
+ menu_ids = {model["id"] for model in menu_models}
+ snapshot = self._current_builtin_models(agent_backend)
+ builtin_ids: set[str] = set()
+ builtin = []
+ for item in snapshot:
+ model_id = item["id"]
+ display_name, reasoning_efforts = _storable_backend_model_metadata(
+ item.get("display_name"),
+ item.get("reasoning_efforts"),
+ )
+ admitted = admissible_backend_model(
+ agent_backend,
+ model_id,
+ {
+ "origin": "builtin",
+ "display_name": display_name,
+ "reasoning_efforts": reasoning_efforts,
+ },
+ claude_builtin_ids=_builtin_model_ids("claude"),
+ )
+ if admitted is None:
+ continue
+ builtin_ids.add(admitted.id)
+ if admitted.id in menu_ids:
+ continue
+ suppliers, _source_label, _source_efforts = self._candidate_suppliers(
+ config,
+ agent_backend,
+ admitted.id,
+ )
+ builtin.append(
+ {
+ "id": admitted.id,
+ "display_name": admitted.display_name,
+ "reasoning_efforts": admitted.reasoning_efforts,
+ "suppliers": suppliers,
+ "origin": "builtin",
+ }
+ )
+
+ provider_ids: list[str] = []
+ source_by_id = {source.id: source for source in config.sources}
+ for source_id in agent.sources.order:
+ source = source_by_id.get(source_id)
+ if source is None or not self._eligible_for_agent(source, backend):
+ continue
+ for model in source.models:
+ if model.retired:
+ continue
+ candidate_id = (
+ opencode_source_model_identity(source, model.id)
+ if backend == "opencode"
+ else model.id
+ )
+ if (
+ candidate_id in menu_ids
+ or candidate_id in builtin_ids
+ or candidate_id in provider_ids
+ ):
+ continue
+ provider_ids.append(candidate_id)
+
+ providers = []
+ for model_id in provider_ids:
+ suppliers, display_name, reasoning_efforts = self._candidate_suppliers(
+ config,
+ agent_backend,
+ model_id,
+ )
+ admitted = admissible_backend_model(
+ agent_backend,
+ model_id,
+ {
+ "origin": "provider",
+ "display_name": display_name,
+ "reasoning_efforts": reasoning_efforts,
+ },
+ claude_builtin_ids=_builtin_model_ids("claude"),
+ )
+ if admitted is None:
+ continue
+ providers.append(
+ {
+ "id": admitted.id,
+ "display_name": admitted.display_name,
+ "reasoning_efforts": admitted.reasoning_efforts,
+ "suppliers": suppliers,
+ "origin": "provider",
+ }
+ )
+ in_list = []
+ for model in menu_models:
+ suppliers, source_label, source_efforts = self._candidate_suppliers(
+ config,
+ agent_backend,
+ model["id"],
+ )
+ provider_candidate = admissible_backend_model(
+ agent_backend,
+ model["id"],
+ {
+ "origin": "provider",
+ "display_name": source_label,
+ "reasoning_efforts": source_efforts,
+ },
+ claude_builtin_ids=_builtin_model_ids("claude"),
+ )
+ in_list.append(
+ {
+ "id": model["id"],
+ "display_name": model["display_name"],
+ "reasoning_efforts": model["reasoning_efforts"],
+ "suppliers": suppliers,
+ "origin": model["origin"],
+ "group_if_removed": (
+ "builtin"
+ if model["id"] in builtin_ids
+ else "providers"
+ if suppliers and provider_candidate is not None
+ else None
+ ),
+ }
+ )
+ return {"builtin": builtin, "providers": providers, "in_list": in_list}
+
def list_agents(self) -> list[dict]:
config = self.store.load()
return [self._agent_payload(config, config.agents[backend]) for backend in ("claude", "codex", "opencode")]
@@ -3815,78 +4055,6 @@ class ModelHubService:
await self._commit_synced(previous, config)
return self._agent_payload(config, agent)
- async def set_opencode_menu(self, baseline: object, menu: object) -> dict:
- async with self._mutation_lock:
- previous = self.store.load()
- config = self._clone_config(previous)
- agent = config.agents["opencode"]
- try:
- parsed_baseline = ModelHubMenuConfig.from_payload(cast(dict, baseline))
- parsed_menu = ModelHubMenuConfig.from_payload(cast(dict, menu))
- current_menu = agent.menu or ModelHubMenuConfig()
- baseline_checked = set(parsed_baseline.checked)
- requested_checked = set(parsed_menu.checked)
- removed = baseline_checked - requested_checked
- added = [
- identifier
- for identifier in parsed_menu.checked
- if identifier not in baseline_checked
- ]
- merged_checked = [
- identifier
- for identifier in current_menu.checked
- if identifier not in removed
- ]
- present = set(merged_checked)
- for identifier in added:
- if identifier not in present:
- merged_checked.append(identifier)
- present.add(identifier)
- merged_menu = ModelHubMenuConfig(
- view=(
- parsed_menu.view
- if parsed_menu.view != parsed_baseline.view
- else current_menu.view
- ),
- checked=merged_checked,
- )
- current_models = {model.id: model for model in agent.models}
- candidate = agent.to_payload()
- candidate["menu"] = merged_menu.to_payload()
- candidate["models"] = [
- (
- current_models.get(identifier)
- or ModelHubBackendModelConfig(
- id=identifier,
- origin="manual",
- )
- ).to_payload()
- for identifier in merged_menu.checked
- ]
- merged_routes = dict(agent.routes)
- for identifier in merged_menu.checked:
- merged_routes.setdefault(identifier, ModelHubRouteConfig())
- candidate["routes"] = {
- identifier: route.to_payload()
- for identifier, route in merged_routes.items()
- }
- parsed = ModelHubAgentSupplyConfig.from_payload(
- candidate,
- expected_backend="opencode",
- )
- except (TypeError, ValueError) as exc:
- raise ModelHubError("mapping_target_unavailable") from exc
- added_to_current = set(merged_menu.checked) - set(current_menu.checked)
- if not added_to_current.issubset(opencode_inventory_menu_ids(config)):
- raise ModelHubError("mapping_target_unavailable", status=409)
- agent.menu = parsed.menu
- agent.routes = parsed.routes
- agent.models = parsed.models
- await self._commit_synced(previous, config)
- if self.backend_catalog_changed is not None:
- await self._refresh_backend_catalog("opencode")
- return self._agent_payload(config, agent)
-
@classmethod
def _parse_backend_catalog_models(
cls,
@@ -3930,6 +4098,77 @@ class ModelHubService:
raise ModelHubError("backend_model_duplicate")
return rows
+ @staticmethod
+ def _backend_model_admission_error(
+ backend: BackendName,
+ model_id: str,
+ ) -> str | None:
+ return backend_model_admission_error(
+ backend,
+ model_id,
+ claude_builtin_ids=_builtin_model_ids("claude"),
+ )
+
+ @staticmethod
+ def _parse_expected_suppliers(
+ payload: object,
+ caller_added_model_ids: Iterable[str],
+ ) -> dict[str, list[dict[str, str]]]:
+ if payload is None:
+ return {}
+ if not isinstance(payload, dict):
+ raise ModelHubError("backend_model_catalog_invalid")
+ caller_added = set(caller_added_model_ids)
+ parsed: dict[str, list[dict[str, str]]] = {}
+ for model_id, suppliers in payload.items():
+ if (
+ not isinstance(model_id, str)
+ or model_id not in caller_added
+ or not isinstance(suppliers, list)
+ ):
+ raise ModelHubError("backend_model_catalog_invalid")
+ projected: list[dict[str, str]] = []
+ for supplier in suppliers:
+ if (
+ not isinstance(supplier, dict)
+ or set(supplier) != {"source_id", "model_id"}
+ or not isinstance(supplier.get("source_id"), str)
+ or not supplier["source_id"]
+ or not isinstance(supplier.get("model_id"), str)
+ or not supplier["model_id"]
+ ):
+ raise ModelHubError("backend_model_catalog_invalid")
+ projected.append(
+ {
+ "source_id": supplier["source_id"],
+ "model_id": supplier["model_id"],
+ }
+ )
+ if len(
+ {(item["source_id"], item["model_id"]) for item in projected}
+ ) != len(projected):
+ raise ModelHubError("backend_model_catalog_invalid")
+ parsed[model_id] = projected
+ return parsed
+
+ def _project_expected_suppliers(
+ self,
+ config: ModelHubConfig,
+ backend: BackendName,
+ model_ids: Iterable[str],
+ ) -> dict[str, list[dict[str, str]]]:
+ return {
+ model_id: [
+ {"source_id": hop.source_id, "model_id": hop.model_id}
+ for hop in self._matching_menu_model_hops(
+ config,
+ backend,
+ model_id,
+ )
+ ]
+ for model_id in model_ids
+ }
+
async def _refresh_backend_catalog(self, backend: BackendName) -> None:
if self.backend_catalog_changed is None:
return
@@ -3940,11 +4179,215 @@ class ModelHubService:
except Exception as exc:
raise ModelHubError("engine_down", status=503) from exc
+ @staticmethod
+ def _insert_builtin_model(
+ agent: ModelHubAgentSupplyConfig,
+ model: ModelHubBackendModelConfig,
+ builtin_order: tuple[str, ...],
+ ) -> None:
+ """Place a new built-in relative to built-ins already in the menu."""
+
+ snapshot_index = builtin_order.index(model.id)
+ positions = {item.id: index for index, item in enumerate(agent.models)}
+ following = next(
+ (
+ positions[model_id]
+ for model_id in builtin_order[snapshot_index + 1 :]
+ if model_id in positions
+ ),
+ None,
+ )
+ if following is not None:
+ agent.models.insert(following, model)
+ return
+ preceding = next(
+ (
+ positions[model_id] + 1
+ for model_id in reversed(builtin_order[:snapshot_index])
+ if model_id in positions
+ ),
+ None,
+ )
+ agent.models.insert(
+ preceding if preceding is not None else len(agent.models),
+ model,
+ )
+
+ def _apply_builtin_reconcile(
+ self,
+ config: ModelHubConfig,
+ snapshots: Mapping[str, Mapping[str, Any]],
+ ) -> list[BackendName]:
+ changed: list[BackendName] = []
+ for backend in ("claude", "codex"):
+ agent = config.agents[backend]
+ raw_snapshot = snapshots.get(backend, {})
+ snapshot: list[ModelHubBackendModelConfig] = []
+ for item in raw_snapshot.get("models", []):
+ display_name, reasoning_efforts = _storable_backend_model_metadata(
+ item.get("display_name"),
+ item.get("reasoning_efforts"),
+ )
+ admitted = admissible_backend_model(
+ cast(BackendName, backend),
+ item.get("id"),
+ {
+ "origin": "builtin",
+ "display_name": display_name,
+ "reasoning_efforts": reasoning_efforts,
+ },
+ claude_builtin_ids=_builtin_model_ids("claude"),
+ )
+ if admitted is not None:
+ snapshot.append(admitted)
+ builtin_order = tuple(model.id for model in snapshot)
+ present = {model.id for model in agent.models}
+ removed = set(agent.removed_model_ids)
+ added = False
+ for model in snapshot:
+ model_id = model.id
+ if model_id in present or model_id in removed:
+ continue
+ self._insert_builtin_model(
+ agent,
+ model,
+ builtin_order,
+ )
+ present.add(model_id)
+ self._seed_menu_model_route(
+ config,
+ cast(BackendName, backend),
+ model_id,
+ )
+ added = True
+ if added:
+ changed.append(cast(BackendName, backend))
+ return changed
+
+ def _builtin_snapshots(
+ self,
+ backends: Iterable[BackendName] = ("claude", "codex"),
+ ) -> dict[str, dict[str, Any]]:
+ from vibe.backend_model_catalog import backend_builtin_snapshot
+
+ return {
+ backend: backend_builtin_snapshot(
+ backend,
+ cli_installed=self._cli_present(backend),
+ )
+ for backend in backends
+ if backend != "opencode"
+ }
+
+ def _reconcile_store_writable(self) -> bool:
+ try:
+ self._ensure_config_writable()
+ except ModelHubError as exc:
+ if exc.code != "config_recovery":
+ raise
+ return False
+ return True
+
+ @staticmethod
+ def _builtin_snapshot_generation(snapshot: Mapping[str, Any]) -> str:
+ generation = snapshot.get("generation")
+ if isinstance(generation, str) and generation:
+ return generation
+ content = {
+ "complete": snapshot.get("complete") is True,
+ "models": snapshot.get("models", []),
+ }
+ return hashlib.sha256(
+ json.dumps(
+ content,
+ ensure_ascii=True,
+ separators=(",", ":"),
+ sort_keys=True,
+ ).encode()
+ ).hexdigest()
+
+ def _current_builtin_models(
+ self,
+ backend: BackendName,
+ ) -> list[dict[str, Any]]:
+ cached = self._builtin_snapshot_cache.get(backend)
+ if cached is not None:
+ return cached
+ if backend == "opencode":
+ return []
+ from vibe.backend_model_catalog import backend_builtin_models
+
+ return backend_builtin_models(backend)
+
+ async def reconcile_builtin_models(
+ self,
+ backends: Iterable[BackendName] = ("claude", "codex"),
+ *,
+ notify: bool = True,
+ ) -> list[BackendName]:
+ async with self._mutation_lock:
+ selected_backends = tuple(backends)
+ previous = self.store.load()
+ snapshots = self._builtin_snapshots(selected_backends)
+ store_writable = self._reconcile_store_writable()
+ changed_snapshots = {
+ backend: snapshot
+ for backend, snapshot in snapshots.items()
+ if store_writable
+ if self._builtin_snapshot_generations.get(
+ cast(BackendName, backend)
+ )
+ != self._builtin_snapshot_generation(snapshot)
+ }
+ self._builtin_snapshot_cache.update(
+ {
+ cast(BackendName, backend): list(snapshot.get("models", []))
+ for backend, snapshot in snapshots.items()
+ }
+ )
+ changed: list[BackendName] = []
+ if changed_snapshots:
+ config = self._clone_config(previous)
+ changed = self._apply_builtin_reconcile(config, changed_snapshots)
+ if changed:
+ try:
+ await self._commit_synced(previous, config)
+ except ModelHubError as exc:
+ if exc.code != "config_recovery":
+ raise
+ return []
+ self._builtin_snapshot_generations.update(
+ {
+ cast(BackendName, backend): self._builtin_snapshot_generation(
+ snapshot
+ )
+ for backend, snapshot in changed_snapshots.items()
+ }
+ )
+ if notify:
+ self._pending_builtin_catalog_refresh.update(changed)
+ if notify:
+ pending = tuple(
+ backend
+ for backend in selected_backends
+ if backend in self._pending_builtin_catalog_refresh
+ and store_writable
+ )
+ for backend in pending:
+ await self._refresh_backend_catalog(backend)
+ self._pending_builtin_catalog_refresh.discard(backend)
+ return changed
+
async def set_agent_models(
self,
backend: str,
baseline: object,
models: object,
+ *,
+ expected_suppliers: object = None,
+ force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
) -> dict:
async with self._mutation_lock:
previous = self.store.load()
@@ -3962,39 +4405,110 @@ class ModelHubService:
current_by_id = {model.id: model for model in agent.models}
baseline_by_id = {model.id: model for model in baseline_models}
desired_by_id = {model.id: model for model in desired_models}
+ caller_added_model_ids = [
+ model.id
+ for model in desired_models
+ if model.id not in baseline_by_id
+ ]
+ parsed_expected_suppliers = self._parse_expected_suppliers(
+ expected_suppliers,
+ caller_added_model_ids,
+ )
+ agent_backend = cast(BackendName, backend)
+ builtin_ids = {
+ item["id"]
+ for item in self._current_builtin_models(agent_backend)
+ }
for model_id in desired_by_id.keys() - current_by_id.keys():
- canonical = canonical_model_id(model_id)
- if canonical is None or canonical != model_id:
- raise ModelHubError("backend_model_id_invalid")
+ admission_error = self._backend_model_admission_error(
+ agent_backend,
+ model_id,
+ )
+ if admission_error == "backend_model_id_invalid":
+ raise ModelHubError(admission_error)
for model_id, desired in desired_by_id.items():
trusted = current_by_id.get(model_id) or baseline_by_id.get(model_id)
if (
- (trusted is None and desired.origin == "builtin")
+ (
+ trusted is None
+ and desired.origin == "builtin"
+ and model_id not in builtin_ids
+ )
or (trusted is not None and desired.origin != trusted.origin)
):
raise ModelHubError("backend_model_locked", status=409)
for model_id in desired_by_id.keys() - current_by_id.keys():
- if (
- backend == "claude"
- and model_id not in _builtin_model_ids("claude")
- and not model_id.startswith(("claude-", "anthropic-"))
- ):
- raise ModelHubError("backend_model_id_prefix")
+ admission_error = self._backend_model_admission_error(
+ agent_backend,
+ model_id,
+ )
+ if admission_error is not None:
+ raise ModelHubError(admission_error)
+ projections = self._project_expected_suppliers(
+ config,
+ agent_backend,
+ parsed_expected_suppliers,
+ )
+ changed_suppliers = {
+ model_id: projections[model_id]
+ for model_id, expected in parsed_expected_suppliers.items()
+ if projections[model_id] != expected
+ }
+ if changed_suppliers:
+ raise ModelHubError(
+ "candidate_suppliers_changed",
+ status=409,
+ data={"changed": changed_suppliers},
+ )
merged_by_id = dict(current_by_id)
- for model_id in baseline_by_id.keys() - desired_by_id.keys():
+ removed_hops: list[dict] = []
+ removed_model_ids = [
+ model.id
+ for model in baseline_models
+ if model.id not in desired_by_id and model.id in current_by_id
+ ]
+ for model_id in removed_model_ids:
route = agent.routes.get(model_id)
- if route is not None and route.hops:
- raise ModelHubError(
- "backend_model_in_route",
- status=409,
- data={"model_id": model_id},
- )
current = current_by_id.get(model_id)
if current is not None and current != baseline_by_id[model_id]:
raise ModelHubError("backend_model_conflict", status=409)
+ if route is not None:
+ removed_hops.extend(
+ {
+ "backend": backend,
+ "menu_model": model_id,
+ "source_id": hop.source_id,
+ "model_id": hop.model_id,
+ "position": position,
+ }
+ for position, hop in enumerate(route.hops, start=1)
+ )
+ route.hops = ()
+
+ newly_empty_routes = frozenset(
+ (backend, item["menu_model"])
+ for item in removed_hops
+ )
+ interrupted = self._introduced_interruptions(
+ previous,
+ config,
+ newly_empty_routes=newly_empty_routes,
+ )
+ self._require_guard_plan(
+ force=force,
+ confirmed_remove_hops=confirmed_remove_hops,
+ confirmed_interruptions=confirmed_interruptions,
+ would_remove_hops=removed_hops,
+ would_interrupt=interrupted,
+ error="backend_model_in_route",
+ )
+
+ for model_id in removed_model_ids:
merged_by_id.pop(model_id, None)
agent.routes.pop(model_id, None)
+ if model_id not in agent.removed_model_ids:
+ agent.removed_model_ids.append(model_id)
for model_id, desired in desired_by_id.items():
baseline_model = baseline_by_id.get(model_id)
@@ -4059,6 +4573,19 @@ class ModelHubService:
if model.id not in ordered_ids and model.id in merged_by_id:
ordered_ids.append(model.id)
agent.models = [merged_by_id[model_id] for model_id in ordered_ids]
+ for model_id in caller_added_model_ids:
+ if model_id in agent.removed_model_ids:
+ agent.removed_model_ids = [
+ removed_id
+ for removed_id in agent.removed_model_ids
+ if removed_id != model_id
+ ]
+ if model_id not in current_by_id and model_id in merged_by_id:
+ self._seed_menu_model_route(
+ config,
+ agent_backend,
+ model_id,
+ )
if agent.backend == "opencode":
agent.menu = ModelHubMenuConfig(
view=agent.menu.view if agent.menu else "featured",
@@ -4067,10 +4594,16 @@ class ModelHubService:
await self._commit_synced(previous, config)
await self._refresh_backend_catalog(cast(BackendName, backend))
committed = self.store.load()
- return self._agent_payload(
- committed,
- self._agent(committed, backend),
- )
+ result = {
+ "agent": self._agent_payload(
+ committed,
+ self._agent(committed, backend),
+ )
+ }
+ if removed_hops:
+ result["removed_hops"] = removed_hops
+ result["interrupted"] = interrupted
+ return result
@staticmethod
def models_dev_matches(query: object) -> list[dict]:
diff --git a/docs/plans/backend-model-catalogs.md b/docs/plans/backend-model-catalogs.md
index 9079e471c..daf55870b 100644
--- a/docs/plans/backend-model-catalogs.md
+++ b/docs/plans/backend-model-catalogs.md
@@ -190,7 +190,8 @@ reads `aihub → deepseek-v3.2`. Nothing was typed except the search.
model (aggregator copies collapsed), each showing name, mono id, vendor, and context;
choosing one fills id, display name, context, output, modalities, tools, reasoning,
and efforts, all still editable; the last suggestion is always `Use "{{query}}" as the
- model ID` for an id models.dev does not know. The old `Fill from models.dev` button is
+ model ID` for an id models.dev does not know (for OpenCode it offers `custom/<query>`
+ unless the query is already an admissible `vendor/model` id). The old `Fill from models.dev` button is
retired — the typeahead is the same capability, offered before typing instead of after.
For OpenCode the filled id follows C7's provider rule.
Rules that hold across all groups: a provider chip on any row — built-in included — means
@@ -248,7 +249,9 @@ the contract guard as the test. Nothing here introduces a second vocabulary for
server's matching result differs for any listed id it commits nothing and refuses with
`409 {ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed:
{<id>: [{source_id, model_id}]}}` — its own registered response shape (with the `detail` key
- every `ModelHubError` carries), not a guard refusal, since nothing is removed or interrupted; the picker refreshes its candidates and asks again. The success response is the existing
+ every `ModelHubError` carries), not a guard refusal, since nothing is removed or interrupted; the picker then refreshes its candidates, keeps each still-offered chosen id with its new
+ suppliers, drops any id no longer offered (the changed count is the signal; no copy), and asks
+ again; unchecking a re-asked row removes it from the selection and nothing else; the picker refreshes its candidates and asks again. The success response is the existing
`{agent: AgentSupply}`.
- **C2 — Proposed values travel in the candidates read; the save is literal.** The server
proposes `display_name` and `reasoning_efforts` for every candidate (C4): for a built-in
@@ -270,7 +273,8 @@ the contract guard as the test. Nothing here introduces a second vocabulary for
nonempty `would_remove_hops` (`RouteHopRef` = `{backend, menu_model, source_id, model_id,
position}`); a retry with `force: true` echoing the plan removes the rows and their routes in
one transaction and returns `{agent, removed_hops, interrupted}`; rows with empty routes are
- removed without confirmation and return `{agent}`. Property: every response this route
+ removed without confirmation and return `{agent}`. The confirmation shows both the hops and
+ any interrupted Agents with the existing guard-impact surface and echoes both arrays. Property: every response this route
emits — the plain success, the forced success with `removed_hops` and `interrupted`, and
the refusal — validates against the response registry after the artifact changes below,
the 409 refusal alone also validates against `guard-refusal.schema.json`, and the response
@@ -282,7 +286,9 @@ the contract guard as the test. Nothing here introduces a second vocabulary for
`{id, display_name, reasoning_efforts, suppliers: [{source_id, source_name, model_id}],
origin}`. `builtin` is the merged remote + bundled + local-CLI snapshot for the backend
(served regardless of Gateway/Direct mode; empty for OpenCode) minus menu ids, removed ones
- included; `providers` is the deduplicated (question 1) inventory of the backend's ordered,
+ included, and filtered by the backend's admission rule — configured or cache-only values the
+ backend would not accept as menu ids (an `ANTHROPIC_MODEL` override, an over-long Codex id)
+ are neither candidates nor reconcile input; `providers` is the deduplicated (question 1) inventory of the backend's ordered,
configuration-eligible Sources minus menu ids and minus ids already in `builtin`, and minus
any id the backend's admission rule would reject (length, canonical form, Claude prefix,
OpenCode `vendor/model`) — a candidate is by definition addable; `in_list`
@@ -298,34 +304,22 @@ the contract guard as the test. Nothing here introduces a second vocabulary for
- **C6 — Removed ids never return on their own.** The backend catalog persists
`agents.<backend>.removed_model_ids: string[]`. Every row the user removes leaves its id in
the set, whatever the row's origin was and whether or not the backend lists the id right now;
- adding a row with that id by any path clears it. Reconcile — on startup, remote catalog
- refresh, or CLI cache change — adds each built-in snapshot id that is neither in the menu nor
- in the set, at the position question 9 defines, seeds it per C1 and C2, and invalidates the
- backend's runtime projection; it never removes a row. The picker's `builtin` group lists
- removed built-ins so they are one click away. Legacy initialization is a separate persisted
- marker, `agents.<backend>.builtin_baseline_initialized: boolean` (absent on v1 files =
- false): reconcile runs only while it is true. It becomes true once — when the snapshot is
- complete (the bundled catalog, a last-known-good remote catalog, and the local CLI cache
- when that CLI is installed have each been read at least once) — and at that moment
- `removed_model_ids` is set to its current contents ∪ (`built-in snapshot ids − menu ids`).
- Removals made while the marker is false are recorded in `removed_model_ids` immediately, like
- any other removal, and survive initialization. Until the marker is true the menu is served
- unchanged, so a partial snapshot can never be mistaken for the user's removals. Reconcile is
- controller-owned and pull-based: the controller records the generation (content hash) of the
- built-in snapshot it last reconciled against, and re-reads the snapshot inputs — bundled
- catalog, remote catalog cache file, CLI cache file — before serving any Model Hub agent read
- or mutation and at startup; a changed generation triggers reconcile in that same request.
- No cache producer (the UI process's background refresher included) has to notify the
- controller, so the two processes stay decoupled as `AGENTS.md` requires. A catalog
- created fresh under v2 is written with the marker already true and an empty removed set, so
- the pending window exists only for files that predate the marker; a fresh-install fixture is
- distinct from the v1 migration fixtures. Both fields are persisted configuration only: the
- `AgentSupply` wire projection omits them (`agent-supply.schema.json` stays closed) and the
- response guard covers that omission. Load and
- mutation fixtures cover the v1 file, the pending window, and the initialized state. This is deliberately conservative: a v1 upgrade changes nothing the user sees, and
- the price is that a built-in that entered the snapshot between the v1 save and the first v2
- load is treated as removed — recoverable from the picker, not auto-added. Claude Code's locked `default` row is not a built-in candidate and
- cannot be removed.
+ adding a row with that id by any path clears it. Reconcile — on startup and before serving
+ any Model Hub agent read or mutation, controller-owned and pull-based on the built-in
+ snapshot's generation — adds each snapshot id that is neither in the menu nor in the set,
+ at the position question 9 defines, seeds it per C1 and C2, and invalidates the backend's
+ runtime projection; it never removes a row, and it never persists or raises while the config
+ store is not writable (recovery mode serves the stored configuration unchanged). A partial
+ snapshot (remote cache or CLI cache not yet read) only means fewer built-ins are known at
+ that moment; nothing is ever tombstoned by inference, so no completeness gate exists. The
+ snapshot's CLI input is read whenever the controller's executable presence probe finds the
+ CLI, independent of `agents.<backend>.enabled`. Remote-catalog cache state (payload,
+ validators, last success, last failure/backoff) is keyed by the catalog `source_key`; a
+ record for another key is never read for the current one. A catalog file written before
+ this field existed loads with an empty set — the v1 shape shipped in no release, so there is
+ no legacy initialization, marker, or pending window. Claude Code's locked `default` row is
+ not a built-in candidate and cannot be removed. The picker's `builtin` group lists removed
+ built-ins so they are one click away.
- **C7 — models.dev read serves the editor typeahead, additively.** The existing
`GET /api/models/catalog/models-dev?query=` keeps its shipped shape — `matches`, `provider_id`,
`provider_name`, and the metadata fields — and gains: deduplication by model id, ranking
@@ -351,7 +345,8 @@ the v2 shapes on the same head.
| Artifact | Change |
| --- | --- |
-| `docs/plans/model-hub-contracts/backend-model.schema.json` and its TypeScript mirror (`ui/src/components/settings/models/types.ts`) | `origin` enum gains `provider` |
+| `docs/plans/model-hub-contracts/backend-model.schema.json` and its TypeScript mirror (`ui/src/components/settings/models/types.ts`) | `origin` enum gains `provider`; the mirror also gains the `Candidate` type, `first_party` on the models.dev match, and the guarded / `expected_suppliers` fields on the models `PUT`, with the API client's response and error projections (`modelsApi.ts`) |
+| `PUT /api/models/agents/opencode/menu` (route, `api.md` row, response-registry entry, `set_opencode_menu`, tests) | retired — no UI consumer since #1814; the models `PUT` is the single catalog mutation, so C1/C3/C6 cannot be bypassed |
| `docs/plans/model-hub-contracts/api.md` route table | `PUT /api/models/agents/<backend>/models` row: optional `force`, `would_remove_hops`, `would_interrupt`, `expected_suppliers`; refusals `backend_model_in_route`, `candidate_suppliers_changed`; success `{agent}` or `{agent, removed_hops, interrupted}`. New row `GET /api/models/agents/<backend>/models/candidates`. `GET /api/models/catalog/models-dev` row: additive `first_party`, dedupe, ranking, cap 8 |
| `docs/plans/model-hub-contracts/api-response.schema.json` | the models `PUT` accepts the forced-success shape beside `AgentResponse`; new candidates response (`Candidate` shape from C4); models-dev response gains `first_party` |
| `docs/plans/model-hub-contracts/guard-refusal.schema.json` | `error` enum gains `backend_model_in_route`; a `detail` property; the nonempty-`would_remove_hops` relation extends to `backend_model_in_route` |
@@ -361,10 +356,10 @@ the v2 shapes on the same head.
| `docs/plans/model-hub-contracts/README.md` (product model) and `docs/plans/model-hub-contracts/opencode-overlay.md` | Add Source is no longer the sole matching/placement point: a menu-model add (C1) and a reconcile add (C6) are the other one-time points; runtime still never re-matches |
| `docs/plans/model-hub-contracts/mirror-registry.json` | registers the two new error codes, the new `origin` value, and the new response shapes with their consumers |
| `vibe/i18n/*.json` and `ui/src/components/settings/models/serverCopy.ts` | `detail` keys for the two new error codes |
-| `config/v2_config.py` persisted shape | `agents.<backend>.removed_model_ids` and `agents.<backend>.builtin_baseline_initialized` (C6), with load and mutation fixtures for the v1 file, the pending window, and the initialized state |
+| `config/v2_config.py` persisted shape | `agents.<backend>.removed_model_ids` (C6); a file without the field loads with an empty set (one fixture) |
| `vibe/data/model_vendors.json` (new, versioned) | the vendor map and aggregator order C7 defines, covered by a test |
-| `docs/plans/model-hub.md` §4.2 / §4.6 and its **Guard error-plan relation** table (authoritative per `mirror-registry.json` D18) | matching-point wording (C1); removed-id, marker, and reconcile rules (C6); a new relation row for `backend_model_in_route` requiring a nonempty `would_remove_hops` plan |
-| `config/v2_config.py` → `AgentSupply` projection (`_agent_payload` / `to_payload` split) and the response guard | `removed_model_ids` and `builtin_baseline_initialized` are persisted only and never appear in any `AgentSupply` response |
+| `docs/plans/model-hub.md` §4.2 / §4.6 and its **Guard error-plan relation** table (authoritative per `mirror-registry.json` D18) | matching-point wording (C1); removed-id and reconcile rules (C6); a new relation row for `backend_model_in_route` requiring a nonempty `would_remove_hops` plan |
+| `config/v2_config.py` → `AgentSupply` projection (`_agent_payload` / `to_payload` split) and the response guard | `removed_model_ids` is persisted only and never appears in any `AgentSupply` response |
### Copy (English source; `zh.json` mirrors 1:1)
@@ -417,8 +412,8 @@ No string explains mechanism.
- Two callers adding the same id concurrently leave exactly one row and one route, matched once.
- A built-in removed while the backend had withdrawn it does not return when the backend
lists it again.
-- Loading a v1 catalog shows exactly the same menu before and after the first load, and a
- built-in the user removed under v1 does not return on its own.
+- No Model Hub read or mutation fails or writes while the config store is in recovery mode.
+- A catalog file without `removed_model_ids` loads with an empty set and reconciles normally.
- In the editor, a models.dev suggestion fills every metadata field it knows and leaves each
one editable; an id models.dev does not know can still be entered and saved.
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 115a3e4c6..8acf3c42e 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -1,15 +1,16 @@
# Model Hub contracts
Status: **FINAL shape, implementation-gated. `contract_version` is 7 (2026-09-03
-reasoning-tier provenance); 6 published 2026-08-19 usage metering; 5 published the
-2026-08-11 contract completion.**
+backend-catalog composition and reasoning-tier provenance); 6 published 2026-08-19
+usage metering; 5 published the 2026-08-11 contract completion.**
These files describe the terminal contract for Model Hub before first release. No bump
carries a data migration, compatibility reader, conversion transaction, or version
discriminator: Model Hub has not shipped, so republishing the shape converts nothing.
`contract_version` is 7 wherever a versioned object exists. The owner-approved
-pre-release network correction removes the earlier persistent network/timeout cooldown
-spelling without adding a compatibility path.
+pre-release corrections add server-owned candidate composition, one-time matching
+points, and reasoning-tier provenance while removing the earlier persistent
+network/timeout cooldown spelling, without adding compatibility paths.
`v5` is still written throughout these files and stays: it names the contract-completion
generation they were authored in, and sentences such as "Minimum v5 set" or
@@ -31,8 +32,9 @@ commit is not evidence that the complete final protocol has landed.
- Sources are upstream assets. A Source never owns ordering.
- Gateway stores one explicit Source order per backend and one exact ordered Route chain
per menu model. Neither has a `follow | custom` or other policy discriminator.
-- Add Source runs the sole placement policy once and persists its positions. Runtime
- never repeats placement, model matching, vendor matching, or substitution.
+- Add Source, a menu-model add, and a built-in reconcile add each run the same matching
+ and placement policies once and persist the accepted hops. Runtime never repeats
+ placement, model matching, vendor matching, or substitution.
- Runtime walks the stored Route hops verbatim, rechecking only whether each exact hop is
runnable now and whether a failure permits fallthrough.
- A hop whose upstream `model_id` differs from its menu model is an explicit configured
@@ -46,8 +48,8 @@ commit is not evidence that the complete final protocol has landed.
- Supply state is pull-oriented. Successful fallback is silent; Gateway and Usage are
the user-visible inspection surfaces.
-Normative routing behavior lives only in `docs/plans/model-hub.md`: §4.2 owns Add-time
-placement, §4.3 owns exact-chain execution and credential failures, §4.5 owns state,
+Normative routing behavior lives only in `docs/plans/model-hub.md`: §4.2 owns one-time
+matching and placement, §4.3 owns exact-chain execution and credential failures, §4.5 owns state,
turn copy, and guarded mutation envelopes, and §6 owns native-config import actions.
Contract prose points to those authorities and does not add branches.
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 2fb287e37..f552e7de5 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -22,9 +22,9 @@
{"method": "POST", "path": "/api/models/agents/<backend>/chains/reorder", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/claude/chains/reorder", "status": 200}},
{"method": "PATCH", "path": "/api/models/agents/<backend>/mode", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/claude/mode", "status": 200, "json": {"mode": "hub"}}},
{"method": "GET", "path": "/api/models/agents/<backend>/models", "response_schema": "AgentCatalogResponse", "exercise": {"path": "/api/models/agents/claude/models", "status": 200}},
- {"method": "PUT", "path": "/api/models/agents/<backend>/models", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/claude/models", "status": 200, "json": {"baseline": [{"id":"default","display_name":null,"origin":"builtin","models_dev_id":null,"context_window":null,"max_output_tokens":null,"input_modalities":[],"output_modalities":[],"supports_tools":null,"supports_reasoning":null,"reasoning_efforts":[],"locked":true,"routeable":false}], "models": [{"id":"default","display_name":null,"origin":"builtin","models_dev_id":null,"context_window":null,"max_output_tokens":null,"input_modalities":[],"output_modalities":[],"supports_tools":null,"supports_reasoning":null,"reasoning_efforts":[],"locked":true,"routeable":false}]}}},
+ {"method": "GET", "path": "/api/models/agents/<backend>/models/candidates", "response_schema": "AgentModelCandidatesResponse", "exercise": {"path": "/api/models/agents/claude/models/candidates", "status": 200}},
+ {"method": "PUT", "path": "/api/models/agents/<backend>/models", "response_schema": "AgentModelsResponse", "exercises": [{"path": "/api/models/agents/claude/models", "status": 200, "json": {"baseline": [{"id":"default","display_name":null,"origin":"builtin","models_dev_id":null,"context_window":null,"max_output_tokens":null,"input_modalities":[],"output_modalities":[],"supports_tools":null,"supports_reasoning":null,"reasoning_efforts":[],"locked":true,"routeable":false}], "models": [{"id":"default","display_name":null,"origin":"builtin","models_dev_id":null,"context_window":null,"max_output_tokens":null,"input_modalities":[],"output_modalities":[],"supports_tools":null,"supports_reasoning":null,"reasoning_efforts":[],"locked":true,"routeable":false}]}}, {"path": "/api/models/agents/claude/models", "status": 409, "setup": "backend_model_guard"}, {"path": "/api/models/agents/claude/models", "status": 200, "setup": "backend_model_forced_removal"}, {"path": "/api/models/agents/claude/models", "status": 409, "setup": "candidate_suppliers_guard"}]},
{"method": "GET", "path": "/api/models/catalog/models-dev?query=<text>", "response_schema": "ModelsDevResponse", "exercise": {"path": "/api/models/catalog/models-dev?query=contract-model", "status": 200}},
- {"method": "PUT", "path": "/api/models/agents/opencode/menu", "response_schema": "AgentResponse", "exercise": {"path": "/api/models/agents/opencode/menu", "status": 200, "json": {"baseline": {"view": "featured", "checked": []}, "menu": {"view": "featured", "checked": []}}}},
{"method": "GET", "path": "/api/models/agents/<backend>/chains", "response_schema": "ChainListResponse", "exercise": {"path": "/api/models/agents/claude/chains", "status": 200}},
{"method": "GET", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200}},
{"method": "PUT", "path": "/api/models/agents/<backend>/chain?model=<id>", "response_schema": "ChainMutationResponse", "exercise": {"path": "/api/models/agents/claude/chain?model=claude-opus-4-6", "status": 200, "json": {"hops": [{"source_id": "src_conform001", "model_id": "claude-opus-4-6"}]}}},
@@ -227,6 +227,54 @@
"agent": {"$ref": "#/definitions/AgentSupplyApi"}
}
},
+ "AgentModelsResponse": {
+ "oneOf": [
+ {"$ref": "#/definitions/AgentResponse"},
+ {
+ "type": "object",
+ "required": ["ok", "contract_version", "agent", "removed_hops", "interrupted"],
+ "additionalProperties": false,
+ "properties": {
+ "ok": {"const": true},
+ "contract_version": {"const": 7},
+ "agent": {"$ref": "#/definitions/AgentSupplyApi"},
+ "removed_hops": {"type": "array", "minItems": 1, "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},
+ "interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}
+ }
+ },
+ {"$ref": "model-hub/guard-refusal.schema.json"},
+ {"$ref": "#/definitions/CandidateSuppliersChangedResponse"}
+ ]
+ },
+ "ExpectedSupplier": {
+ "type": "object",
+ "required": ["source_id", "model_id"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": {"type": "string", "pattern": "^src_[a-z0-9]{8,}$"},
+ "model_id": {"type": "string", "minLength": 1}
+ }
+ },
+ "CandidateSuppliersChangedResponse": {
+ "type": "object",
+ "required": ["ok", "contract_version", "error", "detail", "changed"],
+ "additionalProperties": false,
+ "properties": {
+ "ok": {"const": false},
+ "contract_version": {"const": 7},
+ "error": {"const": "candidate_suppliers_changed"},
+ "detail": {"type": "string", "minLength": 1},
+ "changed": {
+ "type": "object",
+ "minProperties": 1,
+ "additionalProperties": {
+ "type": "array",
+ "items": {"$ref": "#/definitions/ExpectedSupplier"},
+ "uniqueItems": true
+ }
+ }
+ }
+ },
"AgentCatalogResponse": {
"type": "object",
"required": ["ok", "contract_version", "agent"],
@@ -249,6 +297,54 @@
}
}
},
+ "CandidateSupplier": {
+ "type": "object",
+ "required": ["source_id", "source_name", "model_id"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": {"type": "string", "pattern": "^src_[a-z0-9]{8,}$"},
+ "source_name": {"type": "string", "minLength": 1},
+ "model_id": {"type": "string", "minLength": 1}
+ }
+ },
+ "ModelCandidate": {
+ "type": "object",
+ "required": ["id", "display_name", "reasoning_efforts", "suppliers", "origin"],
+ "additionalProperties": false,
+ "properties": {
+ "id": {"type": "string", "minLength": 1},
+ "display_name": {"type": ["string", "null"]},
+ "reasoning_efforts": {"type": "array", "items": {"type": "string", "minLength": 1, "maxLength": 64}, "uniqueItems": true},
+ "suppliers": {"type": "array", "items": {"$ref": "#/definitions/CandidateSupplier"}, "uniqueItems": true},
+ "origin": {"enum": ["builtin", "provider", "models_dev", "manual"]},
+ "group_if_removed": {"anyOf": [{"enum": ["builtin", "providers"]}, {"type": "null"}]}
+ }
+ },
+ "AddableModelCandidate": {
+ "allOf": [
+ {"$ref": "#/definitions/ModelCandidate"},
+ {"not": {"required": ["group_if_removed"]}}
+ ]
+ },
+ "AgentModelCandidatesResponse": {
+ "type": "object",
+ "required": ["ok", "contract_version", "candidates"],
+ "additionalProperties": false,
+ "properties": {
+ "ok": {"const": true},
+ "contract_version": {"const": 7},
+ "candidates": {
+ "type": "object",
+ "required": ["builtin", "providers", "in_list"],
+ "additionalProperties": false,
+ "properties": {
+ "builtin": {"type": "array", "items": {"$ref": "#/definitions/AddableModelCandidate"}},
+ "providers": {"type": "array", "items": {"$ref": "#/definitions/AddableModelCandidate"}},
+ "in_list": {"type": "array", "items": {"$ref": "#/definitions/ModelCandidate"}}
+ }
+ }
+ }
+ },
"ModelsDevResponse": {
"type": "object",
"required": ["ok", "contract_version", "matches"],
@@ -258,13 +354,15 @@
"contract_version": {"const": 7},
"matches": {
"type": "array",
+ "maxItems": 8,
"items": {
"type": "object",
- "required": ["provider_id", "provider_name", "model_id", "models_dev_id", "display_name", "context_window", "max_output_tokens", "input_modalities", "output_modalities", "supports_tools", "supports_reasoning", "reasoning_efforts"],
+ "required": ["provider_id", "provider_name", "first_party", "model_id", "models_dev_id", "display_name", "context_window", "max_output_tokens", "input_modalities", "output_modalities", "supports_tools", "supports_reasoning", "reasoning_efforts"],
"additionalProperties": false,
"properties": {
"provider_id": {"type": "string", "minLength": 1},
"provider_name": {"type": "string", "minLength": 1},
+ "first_party": {"type": "boolean"},
"model_id": {"type": "string", "minLength": 1},
"models_dev_id": {"type": "string", "minLength": 3},
"display_name": {"type": "string", "minLength": 1},
@@ -274,7 +372,7 @@
"output_modalities": {"type": "array", "items": {"enum": ["text", "image", "audio", "video"]}, "uniqueItems": true},
"supports_tools": {"type": ["boolean", "null"]},
"supports_reasoning": {"type": ["boolean", "null"]},
- "reasoning_efforts": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}
+ "reasoning_efforts": {"type": "array", "items": {"type": "string", "minLength": 1, "maxLength": 64}, "uniqueItems": true}
}
}
}
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 8159a4814..2f89235c7 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -41,9 +41,9 @@ compatibility path.
| POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[]}` → `{agent: AgentSupply}` | With `order`, atomically stores the complete Source order and idempotently reorders every stored Route by it; with no body, applies the already stored order. In either form it adds, removes, remaps, matches, and guards nothing. The total order is defined below. |
| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. A qualifying Direct → Gateway switch atomically adopts the recognized CLI login as the first native Source; other switches create nothing. |
| GET `/api/models/agents/<backend>/models` | → `{agent: {backend, mode, catalog_models}}` | Picker-safe catalog read. It exposes no Source order, Route, or credential-bearing supplier data; editors use it as the Gateway model menu and fall back to the backend-native catalog in Direct mode, during a rolling upgrade from a pre-catalog server, or while this read is unavailable. |
-| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[]}` → `{agent: AgentSupply}` | Applies one full-list backend catalog edit with optimistic merge. The list controls Agent-visible ids, order, and capability metadata only. Removing a model with a non-empty Route is refused; this mutation never changes supplier inventory or Route hops. |
-| GET `/api/models/catalog/models-dev?query=<text>` | → `{matches: ModelsDevMatch[]}` | Read-only metadata lookup through the server-owned conditional cache. Results normalize models.dev metadata into editable BackendModel fields and never persist automatically. |
-| PUT `/api/models/agents/opencode/menu` | `{baseline: AgentMenu, menu: AgentMenu}` → `{agent: AgentSupply}` | Atomically applies the additions, removals, and optional view change between `baseline` and `menu` to the latest stored OpenCode menu. Concurrent unrelated selections survive. A newly added identifier must still be supplied by current OpenCode-eligible inventory at commit time; this includes a dormant Route alias whose saved Route retains an exact eligible inventory hop. Already checked route aliases may be preserved or removed without same-name inventory. |
+| GET `/api/models/agents/<backend>/models/candidates` | → `{candidates: {builtin: Candidate[], providers: Candidate[], in_list: Candidate[]}}` | Server-owned picker projection. It returns addable built-ins, deduplicated ordered-provider inventory, and every current menu row with the same exact supplier projection; it is independent of backend mode and contains no credentials. Only `in_list` candidates may carry optional `group_if_removed: "builtin" | "providers" | null`, naming the group where that id would be offered after removal; absence is unknown to rolling-upgrade clients. |
+| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[], expected_suppliers?: {<id>: [{source_id, model_id}]}, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409`, stale-candidate `409`, `{agent: AgentSupply}`, or `{agent: AgentSupply, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` | Applies one full-list backend catalog edit with optimistic merge. Each caller addition still absent from the latest list is matched once against complete non-retired inventory in stored eligible Source order. A listed supplier-projection mismatch refuses atomically with the separate exact shape `{ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed}`; a concurrently added row keeps its existing Route. A routeful removal uses the exact echoed-plan guard and then atomically removes its Route; empty-route removal is ordinary success. Supplier inventory remains unchanged. |
+| GET `/api/models/catalog/models-dev?query=<text>` | → `{matches: ModelsDevMatch[]}` | Read-only metadata lookup through the server-owned conditional cache. Results keep the shipped provider fields, deduplicate aggregator copies by model id, rank first-party matches first, add `first_party`, cap results at 8, and never persist automatically. |
| GET `/api/models/agents/<backend>/chains` | → `{chains: AgentChain[]}` | Hub only. Returns the complete Overview model set in menu order, followed by a selected model or configured Route not already present. All members share one config snapshot and observation time. Direct returns the documented `direct_mode` error. |
| GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. |
| PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | Replaces the exact Source/model pairs in submitted order after validating new or changed pairs; the handler never reads `sources.order`, and the submitted `hops` carry no Source-order semantics. It is the `mutation.route_replace` row of the authoritative mutation matrix. A visible noninterrupting hop removal is ordinary success; only a resulting protected-supply interruption enters the guard. |
@@ -1136,7 +1136,8 @@ Minimum v5 set:
`source_not_found`, `flow_not_found`, `flow_expired`, `discovery_failed`,
`invalid_source_order`, `source_create_in_progress`, `source_nonce_conflict`, `source_last_supplier`,
`source_in_route_chain`,
-`source_model_in_route_chain`, `mode_switch_blocked`, `engine_down`,
+`source_model_in_route_chain`, `backend_model_in_route`,
+`candidate_suppliers_changed`, `mode_switch_blocked`, `engine_down`,
`runtime_platform_unsupported`, `reauth_confirmation_required`,
`native_source_already_exists`, `native_login_in_progress`,
`migration_item_conflict`, `source_model_tiers_managed`, `turn_not_found`,
@@ -1157,8 +1158,8 @@ Boundary-only action-refusal values cover operations the UI already does not off
a script or regression can call directly. `reauth_confirmation_required` is API/test-
only truth: it has no product copy key or rendering slot.
-The top-level guard vocabulary remains exactly `source_last_supplier |
-source_in_route_chain | source_model_in_route_chain`; a changed confirmation plan returns
+The top-level cascade-guard vocabulary is `source_last_supplier |
+source_in_route_chain | source_model_in_route_chain | backend_model_in_route`; a changed confirmation plan returns
the same family with newly recomputed arrays rather than a parallel discriminator.
Removed: `invalid_priority_order`.
@@ -1178,7 +1179,8 @@ contract harness and API-boundary tests enforce:
<!-- authority-consumer: runtime.health ok degraded down not_installed installing not_started -->
<!-- authority-consumer: runtime.install_error runtime_platform_unsupported -->
<!-- authority-consumer: source.create_nonce nonce.in_flight nonce.released nonce.committed -->
-<!-- authority-consumer: guard.error source_last_supplier source_in_route_chain source_model_in_route_chain -->
+<!-- authority-consumer: guard.error backend_model_in_route source_last_supplier source_in_route_chain source_model_in_route_chain -->
+<!-- authority-consumer: candidate.error candidate_suppliers_changed -->
<!-- authority-consumer: guard.decision guard_decision.unforced_no_impact guard_decision.unforced_confirmation guard_decision.forced_no_impact guard_decision.forced_confirmed guard_decision.forced_unconfirmed -->
<!-- authority-consumer: oauth.start_nonce oauth_nonce.released oauth_nonce.in_flight oauth_nonce.committed -->
<!-- authority-consumer: oauth.terminal oauth_terminal.flow_only oauth_terminal.create_success oauth_terminal.reauth_success oauth_terminal.materialization_interrupted oauth_terminal.materialization_plain_error -->
diff --git a/docs/plans/model-hub-contracts/backend-model.schema.json b/docs/plans/model-hub-contracts/backend-model.schema.json
index 5bc112ed2..6554587ba 100644
--- a/docs/plans/model-hub-contracts/backend-model.schema.json
+++ b/docs/plans/model-hub-contracts/backend-model.schema.json
@@ -31,7 +31,7 @@
"description": "Optional human-readable label. The backend id remains the routing identity."
},
"origin": {
- "enum": ["builtin", "models_dev", "manual"],
+ "enum": ["builtin", "provider", "models_dev", "manual"],
"description": "How this row was first created. User edits remain authoritative regardless of origin."
},
"models_dev_id": {
diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.json
index 5e399ba6e..33fd90c7e 100644
--- a/docs/plans/model-hub-contracts/guard-refusal.schema.json
+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json
@@ -2,13 +2,14 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/guard-refusal.schema.json",
"title": "GuardRefusal",
- "$comment": "<!-- authority-consumer: guard.error_plan guard_error.source_in_route_chain guard_error.source_model_in_route_chain guard_error.source_last_supplier -->",
- "description": "The shared HTTP 409 envelope for a guarded Model Hub mutation with a nonempty current guarded-impact plan. A forced retry confirms this plan by echoing would_remove_hops and would_interrupt unchanged; the server recomputes the plan and commits only when both arrays match exactly.",
+ "$comment": "<!-- authority-consumer: guard.error_plan guard_error.backend_model_in_route guard_error.source_in_route_chain guard_error.source_model_in_route_chain guard_error.source_last_supplier -->",
+ "description": "The shared HTTP 409 envelope for a guarded Model Hub mutation. Every refusal carries the current nonempty impact plan.",
"type": "object",
"required": [
"ok",
"contract_version",
"error",
+ "detail",
"would_remove_hops",
"would_interrupt"
],
@@ -32,7 +33,8 @@
"error": {
"enum": [
"source_in_route_chain",
- "source_model_in_route_chain"
+ "source_model_in_route_chain",
+ "backend_model_in_route"
]
}
},
@@ -65,10 +67,12 @@
"enum": [
"source_last_supplier",
"source_in_route_chain",
- "source_model_in_route_chain"
+ "source_model_in_route_chain",
+ "backend_model_in_route"
],
- "description": "Existing lead guard code selected by the Source-mutation matrix. A changed plan returns the same top-level guard error family with the newly recomputed arrays."
+ "description": "A cascade mutation returns its recomputed impact plan."
},
+ "detail": { "type": "string", "minLength": 1 },
"would_remove_hops": {
"type": "array",
"items": { "$ref": "#/definitions/RouteHopRef" },
@@ -115,6 +119,7 @@
"ok": false,
"contract_version": 7,
"error": "source_model_in_route_chain",
+ "detail": "modelHub.errors.source_model_in_route_chain",
"would_remove_hops": [
{
"backend": "claude",
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.json
index f7772ba72..aa2b725c0 100644
--- a/docs/plans/model-hub-contracts/mirror-registry.json
+++ b/docs/plans/model-hub-contracts/mirror-registry.json
@@ -324,6 +324,39 @@
}
}
]
+ },
+ {
+ "id": "M9",
+ "vocabulary": "backend model creation origins",
+ "rule": "equality",
+ "sets": [
+ {
+ "schema": "backend-model.schema.json",
+ "paths": ["/properties/origin"]
+ },
+ {
+ "schema": "api-response.schema.json",
+ "paths": ["/definitions/ModelCandidate/properties/origin"]
+ }
+ ]
+ },
+ {
+ "id": "M10",
+ "vocabulary": "candidate removal destination to creation origin",
+ "rule": "mapping",
+ "home": {
+ "schema": "api-response.schema.json",
+ "path": "/definitions/ModelCandidate/properties/group_if_removed/anyOf/0"
+ },
+ "target": {
+ "schema": "api-response.schema.json",
+ "path": "/definitions/ModelCandidate/properties/origin",
+ "exclude": ["models_dev", "manual"]
+ },
+ "mapping": {
+ "builtin": "builtin",
+ "providers": "provider"
+ }
}
],
"decision_tables": [
@@ -797,6 +830,48 @@
"prefix": "oauth_terminal."
}
]
+ },
+ {
+ "id": "D24",
+ "domain": "stale candidate error code",
+ "authority": {
+ "kind": "schema_vocabulary",
+ "schema": "api-response.schema.json",
+ "paths": ["/definitions/CandidateSuppliersChangedResponse/properties/error"]
+ },
+ "consumers": [
+ {
+ "kind": "marker_tail",
+ "file": "docs/plans/model-hub-contracts/api.md",
+ "marker": "authority-consumer: candidate.error "
+ },
+ {
+ "kind": "marker_tail",
+ "file": "ui/src/components/settings/models/serverCopy.ts",
+ "marker": "authority-consumer: candidate.error "
+ }
+ ]
+ },
+ {
+ "id": "D25",
+ "domain": "backend model route guard UI copy",
+ "authority": {
+ "kind": "schema_vocabulary",
+ "schema": "guard-refusal.schema.json",
+ "paths": ["/properties/error"],
+ "exclude": [
+ "source_last_supplier",
+ "source_in_route_chain",
+ "source_model_in_route_chain"
+ ]
+ },
+ "consumers": [
+ {
+ "kind": "marker_tail",
+ "file": "ui/src/components/settings/models/serverCopy.ts",
+ "marker": "authority-consumer: catalog.guard.error "
+ }
+ ]
}
],
"ownership_checks": [
diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.md
index 61b6a3cf7..de5c8708c 100644
--- a/docs/plans/model-hub-contracts/opencode-overlay.md
+++ b/docs/plans/model-hub-contracts/opencode-overlay.md
@@ -38,8 +38,8 @@ requirements.
## Add-time matching (`matching-v1`)
-OpenCode matching occurs only while adding a Source, after its protocol and inventory
-have been observed. An exact checked identifier wins. Otherwise a bare model id is
+OpenCode matching occurs once while adding a Source, adding a menu model, or reconciling
+a newly available built-in, using the inventory owned by that write. An exact checked identifier wins. Otherwise a bare model id is
accepted only when exactly one checked identifier ends with `/<bare>`; zero matches and
ambiguous matches are left unconfigured. The stored Route carries the concrete upstream
model id and this normalization is never repeated by runtime or refresh.
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index 368c62e68..b517ad039 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -417,12 +417,14 @@ order and applies it to existing Routes without changing their hop membership or
mappings. There is no backend Source-order policy discriminator
and no per-model route policy. Runtime executes the exact hop order stored for each model.
-Matching is an **Add Source write-time operation**. After connectivity, protocol, and
-inventory have been observed, the add transaction proposes exact Source/model matches,
-writes the accepted hops, and returns their visible positions. A later refresh,
-restart, health change, catalog change, or turn never repeats matching. Users maintain
-the persisted chains directly: add or remove a hop, move it, or edit its explicit
-upstream `model_id` mapping.
+Matching has exactly three one-time write points. Add Source matches the discovered
+inventory observed by that transaction and appends accepted hops. A backend menu-model
+add matches that one new row against the complete non-retired inventory (discovered and
+manual) of configuration-eligible Sources in the backend's stored Source order, then
+writes accepted hops in that order. A built-in reconcile add uses that same menu-model
+match and seeds the built-in snapshot's label and reasoning efforts. A later refresh,
+restart, health change, or turn never repeats any match for an existing row. Users maintain persisted chains directly after creation:
+add or remove a hop, move it, or edit its explicit upstream `model_id` mapping.
Cancellation of Source creation has one commit boundary. Before the durable Source
commit, AC-26's transient-reference cleanup and pending-revocation accounting complete
@@ -441,10 +443,11 @@ user setting, or persisted policy discriminator.
**Current policy value (`placement-v1`).** Append a newly added Source to each
configuration-eligible backend Source order, and append every accepted exact match to
-that menu model's current Route-chain tail. This is only the current policy value, not
+that menu model's current Route-chain tail. For a newly added menu model, write one
+accepted hop per supplier in the already stored Source order. This is only the current policy value, not
an API, UI, or acceptance invariant. A later version may choose a better visible
position from model fit or a fixed Source-reliability priority, but it must still run
-only during Add Source, persist the chosen position, and leave runtime to execute that
+only at one of the three one-time write points, persist the chosen position, and leave runtime to execute that
configuration verbatim. There is no “new Source not enabled” state or prompt, and the
UI never uses position to distinguish new from old.
@@ -473,11 +476,11 @@ assembles the returned AgentSupply. An existing native Source, an absent or
unrecognized login, or another mode transition creates nothing. Repetition cannot
create a second native Source.
-**Current matching value (`matching-v1`).** Add Source uses the same observed-inventory
-matching semantics that preceded the configured-chain freeze, then persists the concrete
-upstream id in the Route hop. It runs once, after connectivity, protocol, and inventory
-observation, and is never re-run by refresh, restart, catalog changes, health changes, or
-turn execution.
+**Current matching value (`matching-v1`).** Add Source uses the discovered inventory
+observed by that transaction. A menu-model add uses the same matcher, including the
+Claude alias rule, over each ordered eligible Source's complete non-retired inventory.
+All three persist the concrete upstream id in the Route hop. Matching runs once for each add
+and is never re-run by refresh, restart, health changes, or turn execution.
| Backend/source case | Candidate set | Accepted match and tie-break |
| --- | --- | --- |
@@ -1234,6 +1237,7 @@ the other array remains a complete projection and may independently be empty or
| --- | --- | --- | --- |
| `guard_error.source_in_route_chain` | `source_in_route_chain` | `would_remove_hops` | `would_interrupt` remains complete |
| `guard_error.source_model_in_route_chain` | `source_model_in_route_chain` | `would_remove_hops` | `would_interrupt` remains complete |
+| `guard_error.backend_model_in_route` | `backend_model_in_route` | `would_remove_hops` | `would_interrupt` remains complete |
| `guard_error.source_last_supplier` | `source_last_supplier` | `would_interrupt` | `would_remove_hops` remains complete |
**Source-mutation envelope matrix (authoritative and exhaustive; owner rulings
@@ -1385,10 +1389,34 @@ order alone leaves every Route byte-identical. A per-model Route PUT is instead
user-authored `hops` replacement: its handler does not read `sources.order`, even when the
client used its already-held Source-order projection as a local draft-sorting aid.
-`hops` may be empty and is always present. A newly introduced menu model starts with an
-empty route; catalog expansion and inventory refresh do not retroactively match it.
-Only Add Source's one-time match or an explicit user edit changes the array. Hop order,
-Source identity, and model mapping are user-visible configuration.
+`hops` may be empty and is always present. A newly introduced menu model runs
+`matching-v1` once at that write and starts empty only when no ordered Source supplies it.
+Refresh, restart, health changes, and turns do not retroactively match it. Only either
+add-time match, an explicit user edit, or a confirmed guarded cascade changes the array.
+Hop order, Source identity, and model mapping are user-visible configuration.
+
+The full-list model PUT keeps its three-way merge. Caller additions are the ids in the
+desired list but not its baseline; only one still absent from the latest stored list is
+seeded, so a concurrently added row and its Route survive untouched. For caller additions,
+the optional `expected_suppliers` map echoes the picker's ordered `(source_id, model_id)`
+projection. The server recomputes every listed projection before staging the mutation. Any
+difference refuses the whole write with `candidate_suppliers_changed` and a `changed` map
+containing the current projections for the differing ids.
+
+Backend catalogs also persist `removed_model_ids: string[]`. Removing any row adds its id
+to the set; explicitly adding that id removes it. A catalog written without this field
+loads with an empty set and reconciles normally. The controller re-reads the bundled
+catalog, remote cache file, and installed CLI cache before every Model Hub agent read or
+mutation and at startup. CLI cache participation follows the controller's executable
+presence probe independently of backend enablement. It records the content-hash generation
+it last reconciled, so a changed generation is applied within that request without any
+notification from the UI process. A partial snapshot only exposes fewer built-ins at that
+moment; it never infers a removal or tombstone. Each snapshot change adds, but never
+removes, missing built-ins not in the set, in snapshot order among built-ins already present
+(or at the menu tail when none remain), seeds snapshot label and reasoning efforts, and
+runs the same one-time menu-add match. Remote-catalog payload, validators, success, failure,
+and backoff state are keyed by the configured catalog source. Claude's locked `default` row
+is excluded.
A write validates every newly introduced or changed exact pair before commit. An exact
pair already present in the persisted array may be retained or reordered even when a
@@ -1711,9 +1739,9 @@ directions into questions that later lanes must answer before writing mechanical
- [ ] §4.1 exposes exactly `anthropic | openai_responses | openai_chat`, retains Chat
Completions, and shows Auto detect plus those three protocol choices before
observation; an ambiguous Auto result requires one concrete choice to retry.
-- [ ] §4.2 alone owns Add Source placement: every accepted match is persisted at one
- deterministic policy-chosen position that is visible and adjustable; no later
- path reruns placement, and no UI test infers newness from position.
+- [ ] §4.2 alone owns one-time placement: Add Source, menu-model add, and built-in
+ reconcile persist every accepted match at one deterministic policy-chosen position;
+ no runtime path reruns placement, and no UI test infers newness from position.
- [ ] §4.4 allows every hub-held subscription to serve every backend while retaining
native CLI's sanctioned-backend binding.
- [ ] §4.3 is the document's only configured-chain execution algorithm: it reads stored
diff --git a/tests/fixtures/model_hub/backend_catalog_without_removed_ids.json b/tests/fixtures/model_hub/backend_catalog_without_removed_ids.json
new file mode 100644
index 000000000..99117527f
--- /dev/null
+++ b/tests/fixtures/model_hub/backend_catalog_without_removed_ids.json
@@ -0,0 +1,32 @@
+{
+ "backend": "codex",
+ "mode": "hub",
+ "menu_kind": "fixed",
+ "sources": {
+ "order": []
+ },
+ "routes": {
+ "gpt-kept": {
+ "hops": []
+ }
+ },
+ "menu": null,
+ "models": [
+ {
+ "id": "gpt-kept",
+ "display_name": "GPT Kept",
+ "origin": "builtin",
+ "models_dev_id": null,
+ "context_window": null,
+ "max_output_tokens": null,
+ "input_modalities": [],
+ "output_modalities": [],
+ "supports_tools": null,
+ "supports_reasoning": null,
+ "reasoning_efforts": [
+ "low",
+ "high"
+ ]
+ }
+ ]
+}
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index a558360b3..bf02b3dd7 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -112,6 +112,12 @@ scenarios:
kind: determinism
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_match_002_matching_tie_break_is_independent_of_inventory_order
+ - id: MH-MENU-ADD-001
+ name: Adding a provider menu model seeds every overlapping supplier in Source order
+ status: covered
+ kind: mutation
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_menu_add_001_seeds_overlapping_suppliers_in_source_order
- id: MH-SRC-DELETE-001
name: Source deletion removes every reference while preserving survivor order
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
index 0d1a354ec..b60d49b80 100644
--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
@@ -49,10 +49,7 @@ def _route_pairs(
backend: str,
menu_model: str,
) -> tuple[tuple[str, str], ...]:
- return tuple(
- (hop.source_id, hop.model_id)
- for hop in config.agents[backend].routes[menu_model].hops
- )
+ return tuple((hop.source_id, hop.model_id) for hop in config.agents[backend].routes[menu_model].hops)
def test_mh_s1_001_runtime_resolution_keeps_the_persisted_hop_identity() -> None:
@@ -76,9 +73,7 @@ def test_mh_s1_001_runtime_resolution_keeps_the_persisted_hop_identity() -> None
changed = round_trip(config)
changed.sources[0].state.status = "needs_action"
- changed.sources[0].state.detail_key = (
- "models.source.needs_action.credential_revoked"
- )
+ changed.sources[0].state.detail_key = "models.source.needs_action.credential_revoked"
changed.sources[1].models.append(source_model("catalog-only-new-model"))
after = resolve_model_hub_turn(
changed,
@@ -87,20 +82,10 @@ def test_mh_s1_001_runtime_resolution_keeps_the_persisted_hop_identity() -> None
now=datetime(2030, 8, 1, tzinfo=timezone.utc),
)
- assert (
- before.source_model_ids
- == after.source_model_ids
- == _route_pairs(config, "claude", menu_model)
- )
- assert tuple(
- (item.source_id, item.model_id) for item in after.inspected_hops
- ) == before.source_model_ids
- assert {item.id for item in after.candidates} <= {
- source_id for source_id, _ in before.source_model_ids
- }
- assert after.target_model in {
- model_id for _, model_id in before.source_model_ids
- }
+ assert before.source_model_ids == after.source_model_ids == _route_pairs(config, "claude", menu_model)
+ assert tuple((item.source_id, item.model_id) for item in after.inspected_hops) == before.source_model_ids
+ assert {item.id for item in after.candidates} <= {source_id for source_id, _ in before.source_model_ids}
+ assert after.target_model in {model_id for _, model_id in before.source_model_ids}
def test_mh_config_001_chain_is_the_persisted_artifact_until_explicit_edit(
@@ -141,17 +126,16 @@ def test_mh_config_001_chain_is_the_persisted_artifact_until_explicit_edit(
},
)
)
- assert [
- (hop["source_id"], hop["model_id"]) for hop in result["chain"]["chain"]
- ] == [(second.id, menu_model), (first.id, menu_model)]
+ assert [(hop["source_id"], hop["model_id"]) for hop in result["chain"]["chain"]] == [
+ (second.id, menu_model),
+ (first.id, menu_model),
+ ]
assert _route_pairs(round_trip(store.load()), "claude", menu_model) == (
(second.id, menu_model),
(first.id, menu_model),
)
assert adapter.observation_calls == []
- assert adapter.discovery_calls == [
- (first.vendor, first.protocol, first.base_url, first.credential_ref)
- ]
+ assert adapter.discovery_calls == [(first.vendor, first.protocol, first.base_url, first.credential_ref)]
def test_mh_match_001_add_source_persists_and_reports_each_exact_position(
@@ -194,21 +178,13 @@ def test_mh_match_001_add_source_persists_and_reports_each_exact_position(
)
added_id = result["source"]["id"]
route = store.load().agents["claude"].routes[menu_model]
- positions = {
- (hop.source_id, hop.model_id): index
- for index, hop in enumerate(route.hops, start=1)
- }
- returned = {
- (item["source_id"], item["model_id"]): item["position"]
- for item in result["added_to"]
- }
+ positions = {(hop.source_id, hop.model_id): index for index, hop in enumerate(route.hops, start=1)}
+ returned = {(item["source_id"], item["model_id"]): item["position"] for item in result["added_to"]}
assert returned
assert all(item["source_id"] == added_id for item in result["added_to"])
assert returned == {pair: positions[pair] for pair in returned}
- assert result["adopted_by"] == [
- {"backend": "claude", "menu_model": menu_model}
- ]
+ assert result["adopted_by"] == [{"backend": "claude", "menu_model": menu_model}]
assert store.load().agents["claude"].sources.order[-1] == added_id
assert adapter.revoked == adapter.provisioned_transient
@@ -216,10 +192,7 @@ def test_mh_match_001_add_source_persists_and_reports_each_exact_position(
asyncio.run(service.refresh_source(added_id))
restarted = service_for(tmp_path / "restart", store, adapter)
assert _route_pairs(store.load(), "claude", menu_model) == persisted_after_add
- assert (
- _route_pairs(round_trip(restarted.store.load()), "claude", menu_model)
- == persisted_after_add
- )
+ assert _route_pairs(round_trip(restarted.store.load()), "claude", menu_model) == persisted_after_add
assert len(adapter.observation_calls) == 1
@@ -265,6 +238,74 @@ def test_mh_match_002_matching_tie_break_is_independent_of_inventory_order() ->
assert set(first_order.values()) == {"claude-opus-4-6-20260115"}
+def test_mh_menu_add_001_seeds_overlapping_suppliers_in_source_order(
+ tmp_path: Path,
+) -> None:
+ """MH-MENU-ADD-001: one menu add persists the complete ordered supplier projection."""
+
+ model_id = "overlapping-provider-model"
+ first = source(
+ "src_menuadd01",
+ [source_model(model_id, provenance="discovered")],
+ vendor="openai",
+ protocol="openai_responses",
+ )
+ second = source(
+ "src_menuadd02",
+ [source_model(model_id, provenance="manual")],
+ vendor="custom",
+ protocol="openai_chat",
+ )
+ config = config_with_sources([first, second], backend="codex")
+ config.agents["codex"].sources.order = [second.id, first.id]
+ store = MemoryModelHubStore(config)
+ service = service_for(tmp_path, store, ModelHubScenarioAdapter())
+ baseline = service.backend_catalog_models("codex")
+ before = store.load().to_payload()
+ added = {
+ "id": model_id,
+ "display_name": "Overlapping provider model",
+ "origin": "provider",
+ "models_dev_id": None,
+ "context_window": None,
+ "max_output_tokens": None,
+ "input_modalities": [],
+ "output_modalities": [],
+ "supports_tools": None,
+ "supports_reasoning": None,
+ "reasoning_efforts": [],
+ "locked": False,
+ "routeable": True,
+ }
+
+ asyncio.run(
+ service.set_agent_models(
+ "codex",
+ baseline,
+ [*baseline, added],
+ expected_suppliers={
+ model_id: [
+ {"source_id": second.id, "model_id": model_id},
+ {"source_id": first.id, "model_id": model_id},
+ ]
+ },
+ )
+ )
+
+ after = store.load().to_payload()
+ assert _route_pairs(store.load(), "codex", model_id) == (
+ (second.id, model_id),
+ (first.id, model_id),
+ )
+ assert after["sources"] == before["sources"]
+ assert after["agents"]["codex"]["sources"] == before["agents"]["codex"]["sources"]
+ assert {key: value for key, value in after["agents"]["codex"]["routes"].items() if key != model_id} == before[
+ "agents"
+ ]["codex"]["routes"]
+ assert after["agents"]["claude"] == before["agents"]["claude"]
+ assert after["agents"]["opencode"] == before["agents"]["opencode"]
+
+
def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_order(
tmp_path: Path,
) -> None:
@@ -296,10 +337,7 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ord
agent.menu.checked = [opencode_model]
agent.models = [ModelHubBackendModelConfig(id=opencode_model)]
agent.routes[menu_model] = ModelHubRouteConfig(
- hops=tuple(
- ModelHubRouteHopConfig(item.id, upstream_model)
- for item in (first, doomed, last)
- )
+ hops=tuple(ModelHubRouteHopConfig(item.id, upstream_model) for item in (first, doomed, last))
)
store = MemoryModelHubStore(config)
adapter = ModelHubScenarioAdapter()
@@ -325,10 +363,7 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ord
("opencode", opencode_model),
):
assert doomed.id not in store.load().agents[backend].sources.order
- assert [
- hop.source_id
- for hop in store.load().agents[backend].routes[menu_model].hops
- ] == [first.id, last.id]
+ assert [hop.source_id for hop in store.load().agents[backend].routes[menu_model].hops] == [first.id, last.id]
assert round_trip(store.load()).to_payload() == store.load().to_payload()
assert adapter.revoked == [doomed.credential_ref]
@@ -373,11 +408,7 @@ def test_mh_supply_gap_001_empty_chain_remains_visible_after_inventory_loss(
"position": 1,
}
]
- model_supply = next(
- row
- for row in service.list_agents()[0]["model_supply"]
- if row["model_id"] == menu_model
- )
+ model_supply = next(row for row in service.list_agents()[0]["model_supply"] if row["model_id"] == menu_model)
assert model_supply["chain_length"] == 0
assert service.agent_chain("claude", menu_model)["chain"] == []
@@ -451,9 +482,7 @@ def test_mh_protocol_001_saved_protocol_is_response_observed_and_transient_state
def test_mh_protocol_002_contract_exposes_only_the_three_authoritative_transports() -> None:
"""MH-PROTOCOL-002: the schema and adapter authority have one exact protocol vocabulary."""
- schema = json.loads(
- Path("docs/plans/model-hub-contracts/source.schema.json").read_text()
- )
+ schema = json.loads(Path("docs/plans/model-hub-contracts/source.schema.json").read_text())
schema_protocols = tuple(schema["properties"]["protocol"]["enum"])
assert schema_protocols == SOURCE_PROTOCOLS
assert len(schema_protocols) == len(set(schema_protocols))
@@ -490,9 +519,7 @@ def test_mh_protocol_003_manual_selection_requires_matching_response_proof(
)
assert created["source"]["protocol"] == "openai_responses"
- assert adapter.observation_calls == [
- ("custom", "https://relay.example/v1", ("openai_responses",))
- ]
+ assert adapter.observation_calls == [("custom", "https://relay.example/v1", ("openai_responses",))]
assert adapter.revoked == adapter.provisioned_transient
mismatch_store = MemoryModelHubStore(config_with_sources([]))
@@ -601,9 +628,7 @@ def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_
persisted_sources = {item.id: item.to_payload() for item in reloaded.sources}
response_sources = {}
for item in result["sources"]:
- persisted = json.loads(
- json.dumps({key: value for key, value in item.items() if key != "adopted_by"})
- )
+ persisted = json.loads(json.dumps({key: value for key, value in item.items() if key != "adopted_by"}))
for model in persisted["models"]:
if model.get("retired") is False:
model.pop("retired")
@@ -616,6 +641,5 @@ def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_
assert set(_route_pairs(reloaded, "claude", menu_model)) == {
(position["source_id"], position["model_id"])
for position in result["added_to"]
- if position["backend"] == "claude"
- and position["menu_model"] == menu_model
+ if position["backend"] == "claude" and position["menu_model"] == menu_model
}
diff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.py
index e4675de96..76dbe1571 100644
--- a/tests/test_backend_model_catalog.py
+++ b/tests/test_backend_model_catalog.py
@@ -30,10 +30,24 @@ class _FakeResponse:
def _reset_remote_cache(monkeypatch):
backend_model_catalog._REMOTE_MEMORY_CACHE.clear()
monkeypatch.setattr(backend_model_catalog, "_REMOTE_REFRESH_IN_FLIGHT", False)
+ monkeypatch.setattr(backend_model_catalog, "_REMOTE_REFRESH_COMPLETED", None)
yield
backend_model_catalog._REMOTE_MEMORY_CACHE.clear()
+def _persisted_remote_records(tmp_path: Path) -> dict[str, dict]:
+ payload = json.loads(
+ (tmp_path / "backend_model_catalog.json").read_text(encoding="utf-8")
+ )
+ assert payload["cache_version"] == 2
+ return payload["sources"]
+
+
+def _persisted_remote_record(tmp_path: Path, url: str) -> dict:
+ source_key = backend_model_catalog._remote_catalog_source_key(url)
+ return _persisted_remote_records(tmp_path)[source_key]
+
+
def test_reasoning_effort_authorities_are_ordered_and_complete() -> None:
assert backend_model_catalog.REASONING_EFFORT_VOCABULARY == (
"minimal",
@@ -197,9 +211,7 @@ def test_codex_hub_catalog_projects_custom_backend_models_from_native_shape():
"input_modalities": ["text", "image"],
"supports_image_detail_original": True,
"default_reasoning_level": "medium",
- "supported_reasoning_levels": [
- {"effort": "medium", "description": "Medium"}
- ],
+ "supported_reasoning_levels": [{"effort": "medium", "description": "Medium"}],
"use_responses_lite": True,
"multi_agent_version": "v1",
"tool_mode": "code_mode_only",
@@ -219,9 +231,7 @@ def test_codex_hub_catalog_projects_custom_backend_models_from_native_shape():
}
]
- payload = json.loads(
- backend_model_catalog._codex_hub_catalog_bytes(raw, configured)
- )
+ payload = json.loads(backend_model_catalog._codex_hub_catalog_bytes(raw, configured))
assert payload["client_version"] == "0.149.1"
assert payload["models"] == [
@@ -269,13 +279,9 @@ def test_codex_hub_catalog_does_not_inherit_native_model_metadata_for_custom_row
"input_modalities": ["text", "image"],
"supports_image_detail_original": True,
"default_reasoning_level": "medium",
- "supported_reasoning_levels": [
- {"effort": "medium", "description": "Medium"}
- ],
+ "supported_reasoning_levels": [{"effort": "medium", "description": "Medium"}],
"additional_speed_tiers": ["fast"],
- "service_tiers": [
- {"id": "priority", "name": "Fast", "description": "Native"}
- ],
+ "service_tiers": [{"id": "priority", "name": "Fast", "description": "Native"}],
"supports_search_tool": True,
"shell_type": "unified_exec",
"support_verbosity": True,
@@ -300,9 +306,7 @@ def test_codex_hub_catalog_does_not_inherit_native_model_metadata_for_custom_row
assert custom["shell_type"] == "unified_exec"
assert custom["truncation_policy"] == {"mode": "tokens", "limit": 10_000}
assert custom["input_modalities"] == ["text"]
- assert custom["supported_reasoning_levels"] == [
- {"effort": "none", "description": "None"}
- ]
+ assert custom["supported_reasoning_levels"] == [{"effort": "none", "description": "None"}]
assert custom["support_verbosity"] is False
assert custom["experimental_supported_tools"] == []
for key in (
@@ -441,9 +445,7 @@ def test_codex_hub_catalog_can_disable_and_restore_native_reasoning():
)["models"][0]
assert disabled["default_reasoning_level"] == "none"
- assert disabled["supported_reasoning_levels"] == [
- {"effort": "none", "description": "None"}
- ]
+ assert disabled["supported_reasoning_levels"] == [{"effort": "none", "description": "None"}]
assert restored["default_reasoning_level"] == "low"
assert restored["supported_reasoning_levels"] == [
{"effort": "low", "description": "Low"},
@@ -566,17 +568,13 @@ def test_codex_hub_catalog_preparation_exports_current_binary(monkeypatch, tmp_p
assert exported.name.startswith("standard-responses-")
assert calls == [("codex", None)]
- assert json.loads(exported.read_text(encoding="utf-8"))["models"][0][
- "use_responses_lite"
- ] is False
+ assert json.loads(exported.read_text(encoding="utf-8"))["models"][0]["use_responses_lite"] is False
def test_codex_hub_catalog_failure_cannot_select_a_previous_generation(monkeypatch, tmp_path):
runtime_dir = tmp_path / "runtime"
monkeypatch.setattr(backend_model_catalog.paths, "get_runtime_dir", lambda: runtime_dir)
- previous = backend_model_catalog._publish_codex_hub_catalog(
- b'{"client_version":"old","models":[{"slug":"old"}]}'
- )
+ previous = backend_model_catalog._publish_codex_hub_catalog(b'{"client_version":"old","models":[{"slug":"old"}]}')
def fail_export(*_args, **_kwargs):
raise RuntimeError("export failed")
@@ -594,12 +592,8 @@ def test_codex_hub_catalog_generations_are_content_addressed(monkeypatch, tmp_pa
runtime_dir = tmp_path / "runtime"
monkeypatch.setattr(backend_model_catalog.paths, "get_runtime_dir", lambda: runtime_dir)
- first = backend_model_catalog._publish_codex_hub_catalog(
- b'{"models":[{"slug":"gpt-first"}]}'
- )
- second = backend_model_catalog._publish_codex_hub_catalog(
- b'{"models":[{"slug":"gpt-second"}]}'
- )
+ first = backend_model_catalog._publish_codex_hub_catalog(b'{"models":[{"slug":"gpt-first"}]}')
+ second = backend_model_catalog._publish_codex_hub_catalog(b'{"models":[{"slug":"gpt-second"}]}')
assert first != second
assert json.loads(first.read_text(encoding="utf-8"))["models"][0]["slug"] == "gpt-first"
@@ -741,9 +735,14 @@ def test_claude_snapshot_merges_configured_custom_models(monkeypatch, tmp_path):
assert "custom-fast-model" in snapshot["models"]
assert snapshot["models"][:2] == ["claude-fable-5-1", "claude-fable-5"]
assert snapshot["model_labels"]["claude-fable-5-1"] == "claude-fable-5-1 [1M]"
- assert [
- option["value"] for option in snapshot["reasoning_options"]["claude-fable-5-1"]
- ] == ["__default__", "low", "medium", "high", "xhigh", "max"]
+ assert [option["value"] for option in snapshot["reasoning_options"]["claude-fable-5-1"]] == [
+ "__default__",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ ]
assert snapshot["model_labels"]["claude-opus-5"] == "claude-opus-5 [1M]"
assert snapshot["model_labels"]["claude-opus-4-6"] == "claude-opus-4-6 [1M]"
@@ -761,11 +760,7 @@ def test_remote_hidden_tombstone_overrides_stale_local_visible(monkeypatch, tmp_
"load_cached_remote_catalog",
lambda **kwargs: {
"schema_version": 1,
- "backends": {
- "codex": {
- "models": [{"id": "retired-model", "visibility": "hidden"}]
- }
- },
+ "backends": {"codex": {"models": [{"id": "retired-model", "visibility": "hidden"}]}},
},
)
monkeypatch.setattr(backend_model_catalog, "load_bundled_catalog", lambda: {})
@@ -804,7 +799,13 @@ def test_snapshot_returns_immediately_while_remote_refresh_runs(monkeypatch, tmp
@pytest.mark.parametrize("timestamp_key", ["fetched_at", "checked_at"])
def test_remote_catalog_revalidates_after_five_minutes(monkeypatch, timestamp_key):
- payload = {timestamp_key: 100.0, "catalog": {"schema_version": 1, "backends": {}}}
+ payload = {
+ timestamp_key: 100.0,
+ "catalog": {"schema_version": 1, "backends": {}},
+ "source_key": backend_model_catalog._remote_catalog_source_key(
+ backend_model_catalog.DEFAULT_REMOTE_CATALOG_URL
+ ),
+ }
monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 399.0)
assert backend_model_catalog._remote_cache_stale(payload) is False
@@ -816,11 +817,7 @@ def test_remote_catalog_revalidates_after_five_minutes(monkeypatch, timestamp_ke
def test_refresh_remote_catalog_persists_validated_cache(monkeypatch, tmp_path):
payload = {
"schema_version": 1,
- "backends": {
- "claude": {
- "models": [{"id": "claude-fable-6", "reasoning_efforts": ["low", "max"]}]
- }
- },
+ "backends": {"claude": {"models": [{"id": "claude-fable-6", "reasoning_efforts": ["low", "max"]}]}},
}
monkeypatch.setattr(backend_model_catalog.paths, "get_state_dir", lambda: tmp_path)
monkeypatch.setattr(
@@ -836,15 +833,15 @@ def test_refresh_remote_catalog_persists_validated_cache(monkeypatch, tmp_path):
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"))
+ persisted = _persisted_remote_record(
+ tmp_path,
+ "https://example.test/catalog.json",
+ )
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
@@ -861,9 +858,7 @@ def test_refresh_remote_catalog_uses_etag_and_preserves_cache_on_304(monkeypatch
"catalog": previous_catalog,
"etag": '"catalog-v1"',
"error": None,
- "source_key": backend_model_catalog._remote_catalog_source_key(
- "https://example.test/catalog.json"
- ),
+ "source_key": backend_model_catalog._remote_catalog_source_key("https://example.test/catalog.json"),
}
)
@@ -884,14 +879,14 @@ def test_refresh_remote_catalog_uses_etag_and_preserves_cache_on_304(monkeypatch
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"))
+ persisted = _persisted_remote_record(
+ tmp_path,
+ "https://example.test/catalog.json",
+ )
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
@@ -911,9 +906,7 @@ def test_refresh_remote_catalog_does_not_reuse_validator_for_another_url(monkeyp
"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"
- ),
+ "source_key": backend_model_catalog._remote_catalog_source_key("https://old.example.test/catalog.json"),
"error": None,
}
)
@@ -928,19 +921,26 @@ def test_refresh_remote_catalog_does_not_reuse_validator_for_another_url(monkeyp
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(
+ records = _persisted_remote_records(tmp_path)
+ old_key = backend_model_catalog._remote_catalog_source_key(
+ "https://old.example.test/catalog.json"
+ )
+ new_key = backend_model_catalog._remote_catalog_source_key(
"https://new.example.test/catalog.json"
)
+ assert records[old_key]["etag"] == '"old-source"'
+ assert "etag" not in records[new_key]
+ assert records[new_key]["catalog"] == next_catalog
def test_malformed_refresh_preserves_last_good_catalog(monkeypatch, tmp_path):
+ source_url = "https://example.test/catalog.json"
previous_catalog = {
"schema_version": 1,
"backends": {"claude": {"models": [{"id": "claude-fable-6"}]}},
}
monkeypatch.setattr(backend_model_catalog.paths, "get_state_dir", lambda: tmp_path)
+ monkeypatch.setenv(backend_model_catalog.REMOTE_CATALOG_URL_ENV, source_url)
monkeypatch.setattr(
backend_model_catalog.urllib.request,
"urlopen",
@@ -953,9 +953,7 @@ def test_malformed_refresh_preserves_last_good_catalog(monkeypatch, tmp_path):
"catalog": previous_catalog,
"etag": '"catalog-v1"',
"error": None,
- "source_key": backend_model_catalog._remote_catalog_source_key(
- "https://example.test/catalog.json"
- ),
+ "source_key": backend_model_catalog._remote_catalog_source_key(source_url),
}
)
monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 200.0)
@@ -963,16 +961,40 @@ def test_malformed_refresh_preserves_last_good_catalog(monkeypatch, tmp_path):
backend_model_catalog._refresh_remote_catalog_worker()
- persisted = json.loads((tmp_path / "backend_model_catalog.json").read_text(encoding="utf-8"))
+ persisted = _persisted_remote_record(tmp_path, source_url)
assert persisted["catalog"] == previous_catalog
assert 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.0
assert "Unsupported backend model catalog schema version" in persisted["error"]
+ source_key = backend_model_catalog._remote_catalog_source_key(source_url)
+ current = backend_model_catalog._read_cached_remote_payload(
+ backend_model_catalog.get_cached_catalog_path(),
+ source_key=source_key,
+ )
+ assert backend_model_catalog._remote_cache_stale(
+ current,
+ source_key=source_key,
+ ) is False
+
+
+def test_refresh_worker_notifies_controller_after_completion(monkeypatch):
+ first_url = "https://first.example.test/catalog.json"
+ first_key = backend_model_catalog._remote_catalog_source_key(first_url)
+ completed = []
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "refresh_remote_catalog_now",
+ lambda _url: {},
+ )
+ backend_model_catalog.set_remote_catalog_refresh_completed(
+ lambda: completed.append(backend_model_catalog._REMOTE_REFRESH_IN_FLIGHT)
+ )
+
+ backend_model_catalog._refresh_remote_catalog_worker(first_url, first_key)
+
+ assert completed == [False]
def test_fetch_remote_catalog_rejects_invalid_model_entries(monkeypatch):
@@ -1034,10 +1056,7 @@ def test_fetch_remote_catalog_rejects_unknown_backend(monkeypatch):
def test_bundled_codex_56_efforts_include_ultra():
snapshot = backend_model_catalog.backend_model_snapshot("codex", schedule_refresh=False)
- values = {
- entry["value"]
- for entry in snapshot["reasoning_options"]["gpt-5.6-terra"]
- }
+ values = {entry["value"] for entry in snapshot["reasoning_options"]["gpt-5.6-terra"]}
assert "ultra" in values
@@ -1052,12 +1071,290 @@ def test_codex_catalog_readers_expand_codex_home(monkeypatch, tmp_path):
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.setenv("CODEX_HOME", "~/codex-state")
- assert backend_model_catalog._read_codex_models_cache() == [
- {"id": "gpt-expanded", "visibility": "list"}
- ]
+ assert backend_model_catalog._read_codex_models_cache() == [{"id": "gpt-expanded", "visibility": "list"}]
assert backend_model_catalog._read_codex_config_models()[0]["id"] == "gpt-configured"
+def test_backend_builtin_models_merge_backend_snapshots_but_exclude_user_config(
+ monkeypatch,
+):
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_cached_remote_payload",
+ lambda: {"catalog": {}},
+ )
+ monkeypatch.setattr(backend_model_catalog, "_read_complete_catalog", lambda _path: {})
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_read_codex_models_cache_with_status",
+ lambda: ([], True),
+ )
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_codex_sources",
+ lambda *_args: [
+ ("remote", [{"id": "gpt-remote", "label": "GPT Remote"}]),
+ ("bundled", [{"id": "gpt-bundled", "reasoning_efforts": ["high"]}]),
+ ("local", [{"id": "gpt-local"}]),
+ ("legacy", [{"id": "gpt-legacy"}]),
+ ("config", [{"id": "gpt-user-configured"}]),
+ ],
+ )
+
+ snapshot = backend_model_catalog.backend_builtin_models(
+ "codex",
+ schedule_refresh=False,
+ )
+
+ assert [item["id"] for item in snapshot] == [
+ "gpt-remote",
+ "gpt-bundled",
+ "gpt-local",
+ "gpt-legacy",
+ ]
+ assert snapshot[0]["display_name"] == "GPT Remote"
+ assert snapshot[1]["reasoning_efforts"] == ["high"]
+ assert snapshot[2]["reasoning_efforts"] == [
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ ]
+
+
+def test_builtin_snapshot_requires_each_catalog_once_when_cli_is_installed(
+ monkeypatch,
+):
+ reads = {"remote": 0, "bundled": 0, "local": 0}
+
+ def remote(_path, **_kwargs):
+ reads["remote"] += 1
+ return {
+ "catalog": {},
+ "source_key": backend_model_catalog._remote_catalog_source_key(
+ backend_model_catalog.DEFAULT_REMOTE_CATALOG_URL
+ ),
+ }
+
+ def bundled(_path):
+ reads["bundled"] += 1
+ return {}
+
+ def local():
+ reads["local"] += 1
+ return [], False
+
+ monkeypatch.setattr(backend_model_catalog, "_read_cached_remote_payload", remote)
+ monkeypatch.setattr(backend_model_catalog, "_read_complete_catalog", bundled)
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_read_codex_models_cache_with_status",
+ local,
+ )
+
+ snapshot = backend_model_catalog.backend_builtin_snapshot(
+ "codex",
+ cli_installed=True,
+ schedule_refresh=False,
+ )
+
+ assert snapshot["complete"] is False
+ assert reads == {"remote": 1, "bundled": 1, "local": 1}
+
+
+def test_builtin_snapshot_does_not_require_cli_cache_when_cli_is_absent(monkeypatch):
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_read_cached_remote_payload",
+ lambda _path, **_kwargs: {
+ "catalog": {},
+ "source_key": backend_model_catalog._remote_catalog_source_key(
+ backend_model_catalog.DEFAULT_REMOTE_CATALOG_URL
+ ),
+ },
+ )
+ monkeypatch.setattr(backend_model_catalog, "_read_complete_catalog", lambda _path: {})
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_read_codex_models_cache_with_status",
+ lambda: ([], False),
+ )
+
+ snapshot = backend_model_catalog.backend_builtin_snapshot(
+ "codex",
+ cli_installed=False,
+ schedule_refresh=False,
+ )
+
+ assert snapshot["complete"] is True
+
+
+def test_builtin_snapshot_rejects_remote_cache_from_previous_url(
+ monkeypatch,
+ tmp_path,
+):
+ old_url = "https://old.example.test/catalog.json"
+ new_url = "https://new.example.test/catalog.json"
+ refreshes = []
+ monkeypatch.setattr(backend_model_catalog.paths, "get_state_dir", lambda: tmp_path)
+ monkeypatch.setenv(backend_model_catalog.REMOTE_CATALOG_URL_ENV, old_url)
+ backend_model_catalog._write_cached_remote_payload(
+ {
+ "catalog": {
+ "schema_version": 1,
+ "backends": {
+ "codex": {"models": [{"id": "gpt-from-old-source"}]}
+ },
+ },
+ "checked_at": 100.0,
+ "error": None,
+ }
+ )
+ monkeypatch.setenv(backend_model_catalog.REMOTE_CATALOG_URL_ENV, new_url)
+ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 101.0)
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "schedule_remote_catalog_refresh",
+ lambda: refreshes.append(True) or True,
+ )
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_read_complete_catalog",
+ lambda _path: {},
+ )
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_read_codex_models_cache_with_status",
+ lambda: ([], False),
+ )
+
+ snapshot = backend_model_catalog.backend_builtin_snapshot(
+ "codex",
+ cli_installed=False,
+ )
+
+ assert snapshot["complete"] is False
+ assert "gpt-from-old-source" not in {
+ item["id"] for item in snapshot["models"]
+ }
+ assert refreshes == [True]
+ assert set(_persisted_remote_records(tmp_path)) == {
+ backend_model_catalog._remote_catalog_source_key(old_url)
+ }
+
+
+def test_source_switch_is_not_suppressed_by_previous_source_failure(
+ monkeypatch,
+ tmp_path,
+):
+ old_url = "https://old.example.test/catalog.json"
+ new_url = "https://new.example.test/catalog.json"
+ refreshes = []
+ monkeypatch.setattr(backend_model_catalog.paths, "get_state_dir", lambda: tmp_path)
+ monkeypatch.setenv(backend_model_catalog.REMOTE_CATALOG_URL_ENV, old_url)
+ backend_model_catalog._write_cached_remote_payload(
+ {
+ "catalog": {
+ "schema_version": 1,
+ "backends": {
+ "codex": {"models": [{"id": "gpt-from-old-source"}]}
+ },
+ },
+ "fetched_at": 100.0,
+ "checked_at": 150.0,
+ "failed_at": 200.0,
+ "error": "old source failed",
+ }
+ )
+ monkeypatch.setenv(backend_model_catalog.REMOTE_CATALOG_URL_ENV, new_url)
+ monkeypatch.setattr(backend_model_catalog.time, "time", lambda: 201.0)
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "schedule_remote_catalog_refresh",
+ lambda: refreshes.append(True) or True,
+ )
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_read_complete_catalog",
+ lambda _path: {},
+ )
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_read_codex_models_cache_with_status",
+ lambda: ([], False),
+ )
+
+ snapshot = backend_model_catalog.backend_builtin_snapshot(
+ "codex",
+ cli_installed=False,
+ )
+
+ assert snapshot["complete"] is False
+ assert "gpt-from-old-source" not in {
+ item["id"] for item in snapshot["models"]
+ }
+ assert refreshes == [True]
+ current_key = backend_model_catalog._remote_catalog_source_key(new_url)
+ assert backend_model_catalog._read_cached_remote_payload(
+ backend_model_catalog.get_cached_catalog_path(),
+ source_key=current_key,
+ ) == {}
+
+
+def test_builtin_snapshot_rereads_remote_cache_file_and_changes_generation(
+ monkeypatch,
+ tmp_path,
+):
+ remote_path = tmp_path / "backend_model_catalog.json"
+ bundled = {"schema_version": 1, "backends": {"claude": {"models": []}, "codex": {"models": []}}}
+ monkeypatch.setattr(backend_model_catalog, "get_cached_catalog_path", lambda: remote_path)
+ monkeypatch.setattr(backend_model_catalog, "_read_complete_catalog", lambda _path: bundled)
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_read_codex_models_cache_with_status",
+ lambda: ([], True),
+ )
+
+ def write_remote(model_id):
+ remote_path.write_text(
+ json.dumps(
+ {
+ "source_key": backend_model_catalog._remote_catalog_source_key(
+ backend_model_catalog.DEFAULT_REMOTE_CATALOG_URL
+ ),
+ "catalog": {
+ "schema_version": 1,
+ "backends": {
+ "claude": {"models": []},
+ "codex": {"models": [{"id": model_id}]},
+ },
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ write_remote("gpt-file-generation-one")
+ first = backend_model_catalog.backend_builtin_snapshot("codex", schedule_refresh=False)
+ source_key = backend_model_catalog._remote_catalog_source_key(
+ backend_model_catalog.DEFAULT_REMOTE_CATALOG_URL
+ )
+ backend_model_catalog._REMOTE_MEMORY_CACHE[source_key] = {
+ "source_key": source_key,
+ "catalog": {
+ "schema_version": 1,
+ "backends": {"codex": {"models": [{"id": "gpt-stale"}]}},
+ },
+ }
+ write_remote("gpt-file-generation-two")
+ second = backend_model_catalog.backend_builtin_snapshot("codex", schedule_refresh=False)
+
+ assert first["generation"] != second["generation"]
+ assert first["models"][0]["id"] == "gpt-file-generation-one"
+ assert second["models"][0]["id"] == "gpt-file-generation-two"
+
+
def test_parse_toml_falls_back_to_tomli_when_tomllib_is_unavailable(monkeypatch):
real_import = builtins.__import__
fallback = SimpleNamespace(loads=lambda raw: {"model": "gpt-python-310"})
@@ -1071,6 +1368,4 @@ def test_parse_toml_falls_back_to_tomli_when_tomllib_is_unavailable(monkeypatch)
monkeypatch.setattr(builtins, "__import__", fake_import)
- assert backend_model_catalog._parse_toml('model = "gpt-python-310"') == {
- "model": "gpt-python-310"
- }
+ assert backend_model_catalog._parse_toml('model = "gpt-python-310"') == {"model": "gpt-python-310"}
diff --git a/tests/test_controller_model_hub_gate.py b/tests/test_controller_model_hub_gate.py
index 37316783b..ffc73a5fd 100644
--- a/tests/test_controller_model_hub_gate.py
+++ b/tests/test_controller_model_hub_gate.py
@@ -39,9 +39,11 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
import core.handlers.model_hub as model_hub
import core.handlers.model_hub.turn_gateway as turn_gateway
import modules.agents.model_hub as agent_model_hub
- from vibe import api
+ from vibe import api, backend_model_catalog
- service = object()
+ service = SimpleNamespace(
+ reconcile_builtin_models=AsyncMock(return_value=[]),
+ )
calls = []
class Gateway:
@@ -66,6 +68,12 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
monkeypatch.setattr(model_hub, "create_default_service", create_service)
monkeypatch.setattr(turn_gateway, "ModelHubTurnGateway", Gateway)
monkeypatch.setattr(agent_model_hub, "ModelHubRuntimeRouter", Router)
+ refresh_callbacks = []
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "set_remote_catalog_refresh_completed",
+ refresh_callbacks.append,
+ )
presence_probes = []
probe_failure = [False]
block_full_probe = [False]
@@ -91,6 +99,8 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
monkeypatch.setattr(api, "resolve_cli_paths", resolve_cli_paths)
controller = Controller.__new__(Controller)
controller.config = SimpleNamespace(language="zh")
+ controller._loop = None
+ controller._shutdown_requested = False
controller.vibe_agent_store = SimpleNamespace(
get_default_agent=lambda: SimpleNamespace(
backend="codex",
@@ -108,6 +118,8 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
assert captured["requested_model_override"]("claude") is None
assert captured["cli_present_override"]("codex") is True
assert captured["cli_present_override"]("claude") is False
+ service.reconcile_builtin_models.assert_awaited_once_with(notify=False)
+ assert refresh_callbacks == [controller._model_hub_snapshot_refresh_completed]
assert presence_probes == [(["claude", "codex", "opencode"], False)]
probe_failure[0] = True
captured["cli_presence_refresh"](True, ("opencode",))
@@ -134,6 +146,16 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
("router", service, controller.model_hub_turn_gateway),
]
+ refresh_callbacks[0]()
+
+ async def drain_refresh() -> None:
+ controller._loop = asyncio.get_running_loop()
+ controller._schedule_model_hub_snapshot_reconcile()
+ await controller._model_hub_snapshot_reconcile_task
+
+ asyncio.run(drain_refresh())
+ assert service.reconcile_builtin_models.await_count == 2
+
runtime_config = object()
latest = SimpleNamespace(
model_hub=SimpleNamespace(
@@ -171,6 +193,84 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
controller.agent_service.refresh_runtime_config.assert_not_awaited()
+async def test_controller_periodic_tick_reconciles_cross_process_snapshot_changes():
+ reconciled = asyncio.Event()
+
+ async def reconcile_builtin_models():
+ reconciled.set()
+ return []
+
+ controller = Controller.__new__(Controller)
+ controller.model_hub_service = SimpleNamespace(
+ reconcile_builtin_models=reconcile_builtin_models,
+ )
+ controller._loop = asyncio.get_running_loop()
+ controller._shutdown_requested = False
+ controller._model_hub_snapshot_refresh_pending = threading.Event()
+ controller._model_hub_snapshot_reconcile_task = None
+ controller._model_hub_snapshot_reconcile_loop_task = None
+ controller._model_hub_snapshot_reconcile_stopping = False
+ controller._model_hub_snapshot_reconcile_interval_seconds = 0.01
+
+ controller._start_model_hub_snapshot_reconcile_loop()
+ await asyncio.wait_for(reconciled.wait(), 1)
+ controller._shutdown_requested = True
+ await controller._stop_model_hub_snapshot_reconciliation()
+
+ assert controller._model_hub_snapshot_reconcile_loop_task is None
+ assert controller._model_hub_snapshot_reconcile_task is None
+
+
+async def test_controller_shutdown_joins_reconcile_and_rejects_late_completion():
+ reconcile_started = asyncio.Event()
+ release_reconcile = asyncio.Event()
+ service_stopped = asyncio.Event()
+ calls = []
+
+ async def reconcile_builtin_models():
+ calls.append("reconcile")
+ reconcile_started.set()
+ await release_reconcile.wait()
+ return []
+
+ async def stop():
+ calls.append("stop")
+ service_stopped.set()
+
+ controller = Controller.__new__(Controller)
+ controller.model_hub_service = SimpleNamespace(
+ reconcile_builtin_models=reconcile_builtin_models,
+ stop=stop,
+ )
+ controller.runtime_work_supervisor = None
+ controller._runtime_work_tokens = []
+ controller._shutdown_tainted = False
+ controller._loop = asyncio.get_running_loop()
+ controller._shutdown_requested = False
+ controller._model_hub_snapshot_refresh_pending = threading.Event()
+ controller._model_hub_snapshot_reconcile_task = None
+ controller._model_hub_snapshot_reconcile_loop_task = None
+ controller._model_hub_snapshot_reconcile_stopping = False
+
+ controller._model_hub_snapshot_refresh_completed()
+ await asyncio.wait_for(reconcile_started.wait(), 1)
+
+ controller._shutdown_requested = True
+ shutdown = asyncio.create_task(controller._stop_runtime_work_stack())
+ await asyncio.sleep(0)
+ controller._model_hub_snapshot_refresh_completed()
+ release_reconcile.set()
+ await asyncio.wait_for(service_stopped.wait(), 1)
+ await shutdown
+
+ assert calls == ["reconcile", "stop"]
+ assert not controller._model_hub_snapshot_refresh_pending.is_set()
+ assert controller._model_hub_snapshot_reconcile_task is None
+ assert controller._model_hub_snapshot_reconcile_loop_task is None
+
+
@pytest.mark.parametrize("backend", ["claude", "codex", "opencode"])
def test_disabled_controller_resolver_is_direct_without_loading_model_hub_config(
monkeypatch,
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index a7d29f2e8..7237fea83 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -329,6 +329,7 @@ def test_advertised_capability_namespaces_cover_current_and_future_routes() -> N
("GET", "/api/models/agents/codex/chains"),
("PUT", "/api/models/agents/codex/chain"),
("PUT", "/api/models/agents/codex/models"),
+ ("GET", "/api/models/agents/codex/models/candidates"),
("GET", "/api/models/catalog/models-dev"),
("PUT", "/api/global-prompts"),
("POST", "/api/projects"),
@@ -516,6 +517,7 @@ def test_agents_page_load_reads_are_admitted_for_every_rank_that_sees_the_page()
def test_backend_catalog_surface_follows_the_agent_management_boundary() -> None:
catalog_surface = (
("GET", "/api/models/agents/claude/models", "editor"),
+ ("GET", "/api/models/agents/claude/models/candidates", "member"),
("PUT", "/api/models/agents/claude/models", "member"),
("GET", "/api/models/catalog/models-dev", "member"),
)
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 7964af6ae..ab213b502 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -40,6 +40,7 @@ from core.handlers.model_hub.adapter import (
SOURCE_PROTOCOLS,
SourceObservation,
)
+from core.handlers.model_hub.catalog_admission import admissible_backend_model
from core.handlers.model_hub.errors import ModelDiscoveryError
from core.handlers.model_hub.identifiers import MODEL_ID_MAX_LENGTH
from core.handlers.model_hub.events import BoundedEventLog, ResolutionEvent
@@ -65,9 +66,7 @@ from vibe.ui_server import app
CONTRACTS = Path("docs/plans/model-hub-contracts")
SOURCE_EDIT_VALIDATION_CASES = json.loads(
- Path("tests/fixtures/model_hub_source_edit_validation.json").read_text(
- encoding="utf-8"
- )
+ Path("tests/fixtures/model_hub_source_edit_validation.json").read_text(encoding="utf-8")
)
@@ -82,6 +81,9 @@ def _schema(name: str) -> dict:
API_RESPONSE_CONTRACT = _schema("api-response.schema.json")
API_RESPONSE_ROUTES = API_RESPONSE_CONTRACT["x-model-hub-routes"]
+API_RESPONSE_EXERCISES = [
+ (route, exercise) for route in API_RESPONSE_ROUTES for exercise in route.get("exercises", [route.get("exercise")])
+]
def _assert_valid(name: str, payload: dict) -> None:
@@ -217,9 +219,7 @@ class FakeAdapter:
):
self.credential_count += 1
replacement_ref = f"cred_test{self.credential_count:03d}"
- self.retargeted_credentials.append(
- (credential_ref, vendor, protocol, base_url, replacement_ref)
- )
+ self.retargeted_credentials.append((credential_ref, vendor, protocol, base_url, replacement_ref))
return replacement_ref
async def credential_supports_refresh(self, credential_ref):
@@ -375,18 +375,13 @@ def _refresh_fixture_routes(config: ModelHubConfig) -> None:
by_id = {source.id: source for source in config.sources}
for backend, agent in config.agents.items():
agent.sources.order = config.recommended_source_order(backend)
- agent.routes = {
- model_id: ModelHubRouteConfig()
- for model_id in agent.routes
- }
+ agent.routes = {model_id: ModelHubRouteConfig() for model_id in agent.routes}
for source_id in agent.sources.order:
source = by_id[source_id]
for model in source.models:
if agent.menu_kind == "fixed" and model.id not in agent.routes:
continue
- if agent.menu_kind == "open" and (
- agent.menu is None or model.id not in agent.menu.checked
- ):
+ if agent.menu_kind == "open" and (agent.menu is None or model.id not in agent.menu.checked):
continue
route = agent.routes.setdefault(model.id, ModelHubRouteConfig())
route.hops = (*route.hops, ModelHubRouteHopConfig(source.id, model.id))
@@ -606,22 +601,18 @@ def test_api_response_registry_exactly_covers_contract_and_server_routes():
re.MULTILINE,
)
}
- registered = {
- (entry["method"], entry["path"])
- for entry in API_RESPONSE_ROUTES
- }
+ registered = {(entry["method"], entry["path"]) for entry in API_RESPONSE_ROUTES}
assert registered == documented, (
"api-response.schema.json must enumerate exactly the api.md route table; "
f"missing={sorted(documented - registered)}, extra={sorted(registered - documented)}"
)
- assert len(registered) == len(API_RESPONSE_ROUTES), (
- "api-response.schema.json contains duplicate endpoint entries"
- )
+ assert len(registered) == len(API_RESPONSE_ROUTES), "api-response.schema.json contains duplicate endpoint entries"
response_schemas = API_RESPONSE_CONTRACT["definitions"]
for entry in API_RESPONSE_ROUTES:
endpoint = f"{entry['method']} {entry['path']}"
- assert "exercise" in entry, f"{endpoint}: response exercise is missing"
+ exercises = entry.get("exercises", [entry.get("exercise")])
+ assert all(exercises), f"{endpoint}: response exercise is missing"
assert entry["response_schema"] in response_schemas, (
f"{endpoint}: response schema {entry['response_schema']!r} is missing"
)
@@ -632,10 +623,7 @@ def test_api_response_registry_exactly_covers_contract_and_server_routes():
if route.path.startswith("/api/models/")
for method in route.methods or ()
}
- expected = {
- (method, _canonical_contract_route(path))
- for method, path in documented
- }
+ expected = {(method, _canonical_contract_route(path)) for method, path in documented}
assert actual == expected, (
"Model Hub server routes must match api.md; "
f"missing={sorted(expected - actual)}, extra={sorted(actual - expected)}"
@@ -651,31 +639,19 @@ def test_api_response_conformance_diagnostic_names_the_offending_field(tmp_path)
}
body["agents"][0]["model_supply"][0].pop("has_runnable_hop")
validator = Draft7Validator(
- {
- "$ref": (
- "model-hub/api-response.schema.json#/definitions/"
- "AgentListResponse"
- )
- },
+ {"$ref": ("model-hub/api-response.schema.json#/definitions/AgentListResponse")},
registry=_api_response_registry(),
format_checker=FormatChecker(),
)
error = _response_validation_error(list(validator.iter_errors(body)))
- assert _response_error_path(error) == (
- "$.agents[0].model_supply[0].has_runnable_hop"
- )
+ assert _response_error_path(error) == ("$.agents[0].model_supply[0].has_runnable_hop")
def test_oauth_result_response_discriminates_terminal_intent_and_tail():
validator = Draft7Validator(
- {
- "$ref": (
- "model-hub/api-response.schema.json#/definitions/"
- "OAuthResultResponse"
- )
- },
+ {"$ref": ("model-hub/api-response.schema.json#/definitions/OAuthResultResponse")},
registry=_api_response_registry(),
format_checker=FormatChecker(),
)
@@ -683,9 +659,7 @@ def test_oauth_result_response_discriminates_terminal_intent_and_tail():
source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
for model in source["models"]:
model["retired"] = False
- source["adopted_by"] = [
- {"backend": "claude", "menu_model": "claude-opus-4-6"}
- ]
+ source["adopted_by"] = [{"backend": "claude", "menu_model": "claude-opus-4-6"}]
envelope = {"ok": True, "contract_version": CONTRACT_VERSION}
assert not list(validator.iter_errors({**envelope, "flow": flow}))
@@ -710,31 +684,22 @@ def test_oauth_result_response_discriminates_terminal_intent_and_tail():
"interrupted_pairs": [],
}
assert not list(validator.iter_errors(reauth_result))
- assert list(
- validator.iter_errors(
- {**create_result, "flow": {**success_flow, "intent": "reauth"}}
- )
- )
- assert list(
- validator.iter_errors(
- {**reauth_result, "flow": {**success_flow, "intent": "create"}}
- )
- )
+ assert list(validator.iter_errors({**create_result, "flow": {**success_flow, "intent": "reauth"}}))
+ assert list(validator.iter_errors({**reauth_result, "flow": {**success_flow, "intent": "create"}}))
@pytest.mark.parametrize(
- "route_contract",
- API_RESPONSE_ROUTES,
- ids=lambda entry: f"{entry['method']} {entry['path']}",
+ ("route_contract", "exercise"),
+ API_RESPONSE_EXERCISES,
+ ids=lambda value: (f"{value['method']} {value['path']}" if "method" in value else value.get("setup", "plain")),
)
def test_every_model_hub_endpoint_returns_its_contract_response(
monkeypatch,
tmp_path,
route_contract,
+ exercise,
):
endpoint = f"{route_contract['method']} {route_contract['path']}"
- exercise = route_contract.get("exercise")
- assert exercise is not None, f"{endpoint}: response exercise is missing"
isolated_home = tmp_path / "home"
monkeypatch.setenv("HOME", str(isolated_home))
@@ -752,7 +717,56 @@ def test_every_model_hub_endpoint_returns_its_contract_response(
"headers": csrf_headers(client, base_url),
"base_url": base_url,
}
- if "json" in exercise:
+ setup = exercise.get("setup")
+ if setup in {"backend_model_guard", "backend_model_forced_removal"}:
+ baseline = service.backend_catalog_models("claude")
+ model_id = "claude-opus-4-6"
+ request_kwargs["json"] = {
+ "baseline": baseline,
+ "models": [model for model in baseline if model["id"] != model_id],
+ }
+ if setup == "backend_model_forced_removal":
+ request_kwargs["json"].update(
+ {
+ "force": True,
+ "would_remove_hops": [
+ {
+ "backend": "claude",
+ "menu_model": model_id,
+ "source_id": "src_conform001",
+ "model_id": model_id,
+ "position": 1,
+ }
+ ],
+ "would_interrupt": [{"backend": "claude", "model_id": model_id, "agents": []}],
+ }
+ )
+ elif setup == "candidate_suppliers_guard":
+ baseline = service.backend_catalog_models("claude")
+ model_id = "claude-provider-candidate"
+ request_kwargs["json"] = {
+ "baseline": baseline,
+ "models": [
+ *baseline,
+ {
+ "id": model_id,
+ "display_name": None,
+ "origin": "provider",
+ "models_dev_id": None,
+ "context_window": None,
+ "max_output_tokens": None,
+ "input_modalities": [],
+ "output_modalities": [],
+ "supports_tools": None,
+ "supports_reasoning": None,
+ "reasoning_efforts": [],
+ "locked": False,
+ "routeable": True,
+ },
+ ],
+ "expected_suppliers": {model_id: [{"source_id": "src_conform001", "model_id": model_id}]},
+ }
+ elif "json" in exercise:
request_kwargs["json"] = exercise["json"]
response = getattr(client, route_contract["method"].lower())(
@@ -765,22 +779,21 @@ def test_every_model_hub_endpoint_returns_its_contract_response(
)
validator = Draft7Validator(
- {
- "$ref": (
- "model-hub/api-response.schema.json#/definitions/"
- f"{route_contract['response_schema']}"
- )
- },
+ {"$ref": (f"model-hub/api-response.schema.json#/definitions/{route_contract['response_schema']}")},
registry=_api_response_registry(),
format_checker=FormatChecker(),
)
errors = list(validator.iter_errors(body))
if errors:
error = _response_validation_error(errors)
- pytest.fail(
- f"{endpoint}: response field {_response_error_path(error)}: "
- f"{error.message}"
- )
+ pytest.fail(f"{endpoint}: response field {_response_error_path(error)}: {error.message}")
+ agent_payloads = []
+ if isinstance(body.get("agent"), dict):
+ agent_payloads.append(body["agent"])
+ if isinstance(body.get("agents"), list):
+ agent_payloads.extend(item for item in body["agents"] if isinstance(item, dict))
+ for agent_payload in agent_payloads:
+ assert "removed_model_ids" not in agent_payload
def test_default_service_uses_real_engine_adapter(monkeypatch, tmp_path):
@@ -812,6 +825,27 @@ def test_default_service_uses_real_native_oauth_adapter(monkeypatch, tmp_path):
assert service.native_oauth_adapter._agent_auth_service is agent_auth_service
+def test_default_service_leaves_startup_reconcile_to_controller(monkeypatch):
+ calls = []
+
+ async def record_reconcile(_service, *_args, **_kwargs):
+ calls.append(True)
+
+ monkeypatch.setattr(
+ ModelHubService,
+ "reconcile_builtin_models",
+ record_reconcile,
+ )
+
+ service = create_default_service(
+ adapter=FakeAdapter(),
+ native_oauth_adapter=FakeAdapter(),
+ )
+
+ assert isinstance(service, ModelHubService)
+ assert calls == []
+
+
def test_runtime_status_observes_engine_without_starting_it(tmp_path):
class LifecycleAdapter(FakeAdapter):
def __init__(self):
@@ -1439,9 +1473,7 @@ def test_api_key_create_route_persists_client_nonce_for_list_reconciliation(
assert request_body["key"] not in json.dumps(body)
listed = client.get("/api/models/sources", base_url=base_url).get_json()
- assert [source["client_nonce"] for source in listed["sources"]] == [
- request_body["client_nonce"]
- ]
+ assert [source["client_nonce"] for source in listed["sources"]] == [request_body["client_nonce"]]
@pytest.mark.parametrize(
@@ -1755,9 +1787,7 @@ def test_source_create_nonce_retains_unsettled_cleanup_until_restart(tmp_path):
adapter=restarted_adapter,
events=BoundedEventLog(tmp_path / "restarted-events.json"),
oauth_flows=OAuthFlowRegistry(tmp_path / "restarted-oauth-flows.json"),
- revocations=CredentialRevocationJournal(
- tmp_path / "restarted-revocations.json"
- ),
+ revocations=CredentialRevocationJournal(tmp_path / "restarted-revocations.json"),
)
created = await restarted.create_source(payload)
assert created["source"]["client_nonce"] == payload["client_nonce"]
@@ -1888,118 +1918,1013 @@ def test_agents_endpoint_projects_builtin_models_and_standard_vendors(tmp_path):
assert agents[backend]["builtin_models"] == expected
assert agents[backend]["standard_vendors"] is None
- assert agents["opencode"]["builtin_models"] is None
- assert agents["opencode"]["standard_vendors"] == sorted(STANDARD_OPENCODE_VENDOR_IDS)
+ assert agents["opencode"]["builtin_models"] is None
+ assert agents["opencode"]["standard_vendors"] == sorted(STANDARD_OPENCODE_VENDOR_IDS)
+
+
+def test_agents_project_one_shared_backend_catalog_contract(tmp_path):
+ service, _store, _adapter = _service(tmp_path)
+ agents = {agent["backend"]: agent for agent in service.list_agents()}
+
+ claude_models = agents["claude"]["catalog_models"]
+ assert claude_models[0] == {
+ "id": "default",
+ "display_name": None,
+ "origin": "builtin",
+ "models_dev_id": None,
+ "context_window": None,
+ "max_output_tokens": None,
+ "input_modalities": [],
+ "output_modalities": [],
+ "supports_tools": None,
+ "supports_reasoning": None,
+ "reasoning_efforts": [],
+ "locked": True,
+ "routeable": False,
+ }
+ assert all(model["locked"] is False for model in claude_models[1:])
+ assert all(model["routeable"] is True for model in claude_models[1:])
+ assert agents["codex"]["catalog_models"]
+ assert agents["opencode"]["catalog_models"] == []
+
+
+ ("backend", "model_id"),
+ (
+ ("claude", "claude-deepseek-v4"),
+ ("codex", "deepseek-v4"),
+ ("opencode", "aihub/deepseek-v4"),
+ ),
+)
+def test_backend_catalog_add_edit_and_runtime_refresh(
+ tmp_path,
+ backend,
+ model_id,
+):
+ service, store, _adapter = _service(tmp_path)
+ refreshed = []
+
+ async def refresh(changed_backend):
+ refreshed.append(changed_backend)
+
+ service.backend_catalog_changed = refresh
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == backend)
+ added = {
+ "id": model_id,
+ "display_name": "DeepSeek V4",
+ "origin": "models_dev",
+ "models_dev_id": "deepseek/deepseek-v4",
+ "context_window": 1_048_576,
+ "max_output_tokens": 131_072,
+ "input_modalities": ["text", "image"],
+ "output_modalities": ["text"],
+ "supports_tools": True,
+ "supports_reasoning": True,
+ "reasoning_efforts": ["low", "high"],
+ "locked": False,
+ "routeable": True,
+ }
+
+ response = asyncio.run(service.set_agent_models(backend, baseline, [*baseline, added]))
+
+ assert response["agent"]["catalog_models"][-1] == added
+ assert store.config.agents[backend].routes[model_id].hops == ()
+ assert refreshed == [backend]
+ if backend == "opencode":
+ assert store.config.agents[backend].menu.checked == [model_id]
+
+ edited = {**added, "display_name": "DeepSeek V4 edited", "context_window": 262_144}
+ desired_catalog = (
+ [response["agent"]["catalog_models"][0], edited, *response["agent"]["catalog_models"][1:-1]]
+ if backend == "claude"
+ else [edited, *response["agent"]["catalog_models"][:-1]]
+ )
+ edited_response = asyncio.run(
+ service.set_agent_models(
+ backend,
+ response["agent"]["catalog_models"],
+ desired_catalog,
+ )
+ )
+ assert next(model for model in edited_response["agent"]["catalog_models"] if model["id"] == model_id) == edited
+ if backend != "claude":
+ assert edited_response["agent"]["catalog_models"][0] == edited
+ assert refreshed == [backend, backend]
+
+
+def test_backend_catalog_candidates_project_builtin_provider_and_current_rows(
+ monkeypatch,
+ tmp_path,
+):
+ service, store, _adapter = _service(tmp_path)
+ overlong_effort = "x" * 65
+ first = ModelHubSourceConfig(
+ id="src_first0001",
+ kind="api_key",
+ vendor="openai",
+ display_name="First provider",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[
+ ModelHubModelConfig(
+ id="shared-provider-model",
+ provenance="discovered",
+ display_name="First label",
+ reasoning_efforts=["low"],
+ ),
+ ModelHubModelConfig(
+ id="new-provider-model",
+ provenance="discovered",
+ display_name="First proposal",
+ reasoning_efforts=["low"],
+ ),
+ ],
+ credential_ref="cred_first0001",
+ )
+ second = ModelHubSourceConfig(
+ id="src_second001",
+ kind="api_key",
+ vendor="custom",
+ display_name="Second provider",
+ protocol="openai_chat",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[
+ ModelHubModelConfig(
+ id="shared-provider-model",
+ provenance="manual",
+ display_name="Second label",
+ reasoning_efforts=["high", overlong_effort],
+ ),
+ ModelHubModelConfig(
+ id="new-provider-model",
+ provenance="manual",
+ display_name=" ",
+ reasoning_efforts=[" ", " high ", overlong_effort],
+ ),
+ ],
+ credential_ref="cred_second001",
+ )
+ store.config.sources = [first, second]
+ agent = store.config.agents["codex"]
+ agent.sources.order = [second.id, first.id]
+ agent.models.append(
+ ModelHubBackendModelConfig(
+ id="shared-provider-model",
+ origin="provider",
+ display_name="Saved label",
+ )
+ )
+ legacy_overlong_id = "x" * (MODEL_ID_MAX_LENGTH + 1)
+ agent.models.append(
+ ModelHubBackendModelConfig(
+ id=legacy_overlong_id,
+ origin="manual",
+ )
+ )
+ agent.routes["shared-provider-model"] = ModelHubRouteConfig()
+ agent.routes[legacy_overlong_id] = ModelHubRouteConfig()
+ agent.removed_model_ids.extend(["gpt-restorable", "gpt-withdrawn"])
+ existing_builtin_id = agent.models[0].id
+ monkeypatch.setattr(
+ service,
+ "_current_builtin_models",
+ lambda _backend: [
+ {"id": existing_builtin_id},
+ {
+ "id": "gpt-restorable",
+ "display_name": " GPT Restorable ",
+ "reasoning_efforts": [" low ", " ", overlong_effort],
+ },
+ ],
+ )
+
+ candidates = service.agent_model_candidates("codex")
+
+ assert candidates["builtin"] == [
+ {
+ "id": "gpt-restorable",
+ "display_name": "GPT Restorable",
+ "reasoning_efforts": ["low"],
+ "suppliers": [],
+ "origin": "builtin",
+ }
+ ]
+ current = next(item for item in candidates["in_list"] if item["id"] == "shared-provider-model")
+ assert current == {
+ "id": "shared-provider-model",
+ "display_name": "Saved label",
+ "reasoning_efforts": [],
+ "suppliers": [
+ {
+ "source_id": second.id,
+ "source_name": second.display_name,
+ "model_id": "shared-provider-model",
+ },
+ {
+ "source_id": first.id,
+ "source_name": first.display_name,
+ "model_id": "shared-provider-model",
+ },
+ ],
+ "origin": "provider",
+ "group_if_removed": "providers",
+ }
+ assert candidates["providers"] == [
+ {
+ "id": "new-provider-model",
+ "display_name": "First proposal",
+ "reasoning_efforts": ["high", "low"],
+ "suppliers": [
+ {
+ "source_id": second.id,
+ "source_name": second.display_name,
+ "model_id": "new-provider-model",
+ },
+ {
+ "source_id": first.id,
+ "source_name": first.display_name,
+ "model_id": "new-provider-model",
+ },
+ ],
+ "origin": "provider",
+ }
+ ]
+ assert len(candidates["in_list"]) == len(service.backend_catalog_models("codex"))
+ assert next(
+ item for item in candidates["in_list"] if item["id"] == existing_builtin_id
+ )["group_if_removed"] == "builtin"
+ assert next(
+ item for item in candidates["in_list"] if item["id"] == legacy_overlong_id
+ )["group_if_removed"] is None
+ assert all("group_if_removed" not in item for item in candidates["builtin"])
+ assert all("group_if_removed" not in item for item in candidates["providers"])
+ assert legacy_overlong_id in {item["id"] for item in candidates["in_list"]}
+ assert "gpt-withdrawn" not in {item["id"] for group in candidates.values() for item in group}
+ validator = Draft7Validator(
+ {"$ref": ("model-hub/api-response.schema.json#/definitions/AgentModelCandidatesResponse")},
+ registry=_api_response_registry(),
+ format_checker=FormatChecker(),
+ )
+ assert not list(
+ validator.iter_errors(
+ {
+ "ok": True,
+ "contract_version": CONTRACT_VERSION,
+ "candidates": candidates,
+ }
+ )
+ )
+ rolling_upgrade = copy.deepcopy(candidates)
+ for item in rolling_upgrade["in_list"]:
+ item.pop("group_if_removed")
+ assert not list(
+ validator.iter_errors(
+ {
+ "ok": True,
+ "contract_version": CONTRACT_VERSION,
+ "candidates": rolling_upgrade,
+ }
+ )
+ )
+ invalid_group = copy.deepcopy(candidates)
+ invalid_group["builtin"][0]["group_if_removed"] = "builtin"
+ assert list(
+ validator.iter_errors(
+ {
+ "ok": True,
+ "contract_version": CONTRACT_VERSION,
+ "candidates": invalid_group,
+ }
+ )
+ )
+
+
+def test_opencode_candidates_collapse_custom_vendors_into_one_identity(tmp_path):
+ service, store, _adapter = _service(tmp_path)
+ sources = [
+ ModelHubSourceConfig(
+ id=f"src_custom00{index}",
+ kind="api_key",
+ vendor=vendor,
+ display_name=f"Relay {index}",
+ protocol="openai_chat",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id="shared-model", provenance="discovered")],
+ credential_ref=f"cred_custom00{index}",
+ )
+ for index, vendor in enumerate(("relay-a", "relay-b"), start=1)
+ ]
+ store.config.sources = sources
+ store.config.agents["opencode"].sources.order = [source.id for source in sources]
+
+ candidates = service.agent_model_candidates("opencode")
+
+ assert candidates["builtin"] == []
+ assert [item["id"] for item in candidates["providers"]] == ["custom/shared-model"]
+ assert [supplier["source_id"] for supplier in candidates["providers"][0]["suppliers"]] == [
+ source.id for source in sources
+ ]
+
+
+def test_candidates_exclude_ids_the_backend_write_would_reject(monkeypatch, tmp_path):
+ service, store, _adapter = _service(tmp_path)
+ invalid_claude_id = "not-a-claude-family"
+ too_long = "x" * (MODEL_ID_MAX_LENGTH + 1)
+ source = ModelHubSourceConfig(
+ id="src_invalid001",
+ kind="api_key",
+ vendor="custom",
+ display_name="Invalid inventory",
+ protocol="anthropic",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[
+ ModelHubModelConfig(id=invalid_claude_id, provenance="manual"),
+ ModelHubModelConfig(id=too_long, provenance="discovered"),
+ ],
+ credential_ref="cred_invalid001",
+ )
+ store.config.sources = [source]
+ store.config.agents["claude"].sources.order = [source.id]
+ monkeypatch.setattr(
+ service,
+ "_builtin_snapshots",
+ lambda _backends: {
+ "claude": {
+ "generation": "invalid-candidate-snapshot",
+ "models": [
+ {"id": invalid_claude_id},
+ {"id": too_long},
+ ],
+ }
+ },
+ )
+
+ candidates = service.agent_model_candidates("claude")
+
+ ids = {item["id"] for group in candidates.values() for item in group}
+ assert invalid_claude_id not in ids
+ assert too_long not in ids
+
+
+def test_backend_catalog_add_validates_supplier_echo_and_stores_draft_literally(
+ tmp_path,
+):
+ service, store, _adapter = _service(tmp_path)
+ model_id = "provider-model"
+ sources = [
+ ModelHubSourceConfig(
+ id=f"src_supply00{index}",
+ kind="api_key",
+ vendor="openai",
+ display_name=f"Supplier {index}",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[
+ ModelHubModelConfig(
+ id=model_id,
+ provenance="manual" if index == 2 else "discovered",
+ display_name=f"Proposed {index}",
+ reasoning_efforts=["high"],
+ )
+ ],
+ credential_ref=f"cred_supply00{index}",
+ )
+ for index in (1, 2)
+ ]
+ store.config.sources = sources
+ agent = store.config.agents["codex"]
+ agent.sources.order = [source.id for source in reversed(sources)]
+ baseline = service.backend_catalog_models("codex")
+ added = {
+ "id": model_id,
+ "display_name": None,
+ "origin": "provider",
+ "models_dev_id": None,
+ "context_window": None,
+ "max_output_tokens": None,
+ "input_modalities": [],
+ "output_modalities": [],
+ "supports_tools": None,
+ "supports_reasoning": None,
+ "reasoning_efforts": [],
+ "locked": False,
+ "routeable": True,
+ }
+ before = store.config.to_payload()
+
+ result = asyncio.run(
+ service.set_agent_models(
+ "codex",
+ baseline,
+ [*baseline, added],
+ expected_suppliers={
+ model_id: [{"source_id": source.id, "model_id": model_id} for source in reversed(sources)]
+ },
+ )
+ )
+
+ assert result["agent"]["catalog_models"][-1] == added
+ assert [(hop.source_id, hop.model_id) for hop in store.config.agents["codex"].routes[model_id].hops] == [
+ (source.id, model_id) for source in reversed(sources)
+ ]
+ after = store.config.to_payload()
+ assert after["sources"] == before["sources"]
+ assert after["agents"]["claude"] == before["agents"]["claude"]
+ assert after["agents"]["opencode"] == before["agents"]["opencode"]
+ assert {key: value for key, value in after["agents"]["codex"]["routes"].items() if key != model_id} == before[
+ "agents"
+ ]["codex"]["routes"]
+
+
+def test_backend_catalog_supplier_change_refuses_without_committing(tmp_path):
+ service, store, adapter = _service(tmp_path)
+ model_id = "provider-stale-model"
+ source = ModelHubSourceConfig(
+ id="src_stale0001",
+ kind="api_key",
+ vendor="openai",
+ display_name="Current supplier",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id=model_id, provenance="discovered")],
+ credential_ref="cred_stale0001",
+ )
+ store.config.sources = [source]
+ store.config.agents["codex"].sources.order = [source.id]
+ baseline = service.backend_catalog_models("codex")
+ added = {**baseline[0], "id": model_id, "origin": "provider"}
+ before = store.config.to_payload()
+
+ with pytest.raises(ModelHubError) as raised:
+ asyncio.run(
+ service.set_agent_models(
+ "codex",
+ baseline,
+ [*baseline, added],
+ expected_suppliers={model_id: []},
+ )
+ )
+
+ assert raised.value.code == "candidate_suppliers_changed"
+ assert raised.value.status == 409
+ assert raised.value.data == {"changed": {model_id: [{"source_id": source.id, "model_id": model_id}]}}
+ assert store.config.to_payload() == before
+ assert adapter.synced == []
+
+
+def test_concurrent_same_id_add_keeps_the_route_matched_by_the_first_writer(tmp_path):
+ service, store, _adapter = _service(tmp_path)
+ model_id = "provider-concurrent-model"
+ source = ModelHubSourceConfig(
+ id="src_concur001",
+ kind="api_key",
+ vendor="openai",
+ display_name="Concurrent supplier",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[
+ ModelHubModelConfig(id=model_id, provenance="discovered"),
+ ModelHubModelConfig(id="first-writer-target", provenance="manual"),
+ ],
+ credential_ref="cred_concur001",
+ )
+ store.config.sources = [source]
+ agent = store.config.agents["codex"]
+ agent.sources.order = [source.id]
+ baseline = service.backend_catalog_models("codex")
+ added = {**baseline[0], "id": model_id, "origin": "provider"}
+ agent.models.append(ModelHubBackendModelConfig.from_payload(added))
+ agent.routes[model_id] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "first-writer-target"),))
+
+ result = asyncio.run(
+ service.set_agent_models(
+ "codex",
+ baseline,
+ [*baseline, added],
+ expected_suppliers={model_id: [{"source_id": source.id, "model_id": model_id}]},
+ )
+ )
+
+ assert [model["id"] for model in result["agent"]["catalog_models"]].count(model_id) == 1
+ assert [(hop.source_id, hop.model_id) for hop in store.config.agents["codex"].routes[model_id].hops] == [
+ (source.id, "first-writer-target")
+ ]
+
+
+def test_builtin_reconcile_inserts_in_snapshot_order_and_preserves_every_other_row(
+ monkeypatch,
+ tmp_path,
+):
+ service, store, _adapter = _service(tmp_path)
+ refreshed = []
+
+ async def refresh(backend):
+ refreshed.append(backend)
+
+ service.backend_catalog_changed = refresh
+ agent = store.config.agents["codex"]
+ agent.models = [
+ ModelHubBackendModelConfig(id="gpt-alpha", origin="builtin"),
+ ModelHubBackendModelConfig(id="provider-row", origin="provider"),
+ ModelHubBackendModelConfig(id="models-dev-row", origin="models_dev"),
+ ModelHubBackendModelConfig(id="manual-row", origin="manual"),
+ ModelHubBackendModelConfig(id="gpt-omega", origin="builtin"),
+ ModelHubBackendModelConfig(id="gpt-withdrawn", origin="builtin"),
+ ]
+ agent.routes = {model.id: ModelHubRouteConfig() for model in agent.models}
+ agent.removed_model_ids = ["gpt-hidden"]
+ source = ModelHubSourceConfig(
+ id="src_builtin001",
+ kind="api_key",
+ vendor="openai",
+ display_name="Built-in supplier",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id="gpt-new", provenance="manual")],
+ credential_ref="cred_builtin001",
+ )
+ store.config.sources = [source]
+ agent.sources.order = [source.id]
+ snapshot = [
+ {"id": "gpt-alpha"},
+ {
+ "id": "gpt-new",
+ "display_name": " GPT New ",
+ "reasoning_efforts": [" low ", " ", "x" * 65, "high"],
+ },
+ {"id": "gpt-omega"},
+ {"id": "gpt-hidden"},
+ {"id": "x" * (MODEL_ID_MAX_LENGTH + 1)},
+ ]
+ unchanged = {model.id: model.to_payload() for model in agent.models}
+ monkeypatch.setattr(
+ service,
+ "_builtin_snapshots",
+ lambda _backends: {"codex": {"complete": True, "models": snapshot}},
+ )
+
+ changed = asyncio.run(service.reconcile_builtin_models(("codex",)))
+
+ agent = store.config.agents["codex"]
+ assert changed == ["codex"]
+ assert [model.id for model in agent.models] == [
+ "gpt-alpha",
+ "provider-row",
+ "models-dev-row",
+ "manual-row",
+ "gpt-new",
+ "gpt-omega",
+ "gpt-withdrawn",
+ ]
+ created = next(model for model in agent.models if model.id == "gpt-new")
+ assert created.display_name == "GPT New"
+ assert created.reasoning_efforts == ["low", "high"]
+ assert [(hop.source_id, hop.model_id) for hop in agent.routes["gpt-new"].hops] == [(source.id, "gpt-new")]
+ assert "gpt-hidden" not in {model.id for model in agent.models}
+ assert "x" * (MODEL_ID_MAX_LENGTH + 1) not in {model.id for model in agent.models}
+ assert {model.id: model.to_payload() for model in agent.models if model.id in unchanged} == unchanged
+ assert refreshed == ["codex"]
+
+
+def test_builtin_reconcile_is_blocked_only_by_store_writability(monkeypatch, tmp_path):
+ for store_writable in (False, True):
+ service, store, _adapter = _service(tmp_path)
+ agent = store.config.agents["codex"]
+ before = copy.deepcopy(agent.to_payload())
+ store.recovery = not store_writable
+ saves = []
+ original_save = store.save
+
+ def save(config):
+ store.ensure_writable()
+ saves.append(config.to_payload())
+ original_save(config)
+
+ monkeypatch.setattr(store, "save", save)
+ monkeypatch.setattr(
+ service,
+ "_builtin_snapshots",
+ lambda _backends: {
+ "codex": {
+ "complete": False,
+ "generation": "partial-snapshot",
+ "models": [{"id": "gpt-partial-snapshot"}],
+ }
+ },
+ )
+
+ asyncio.run(service.reconcile_builtin_models(("codex",)))
+
+ current = store.config.agents["codex"]
+ assert len(saves) == int(store_writable)
+ assert ("gpt-partial-snapshot" in {model.id for model in current.models}) is store_writable
+ if not store_writable:
+ assert current.to_payload() == before
+
+
+ "producer",
+ ("candidates_read", "reconcile_seed", "models_dev_typeahead"),
+)
+def test_model_producers_emit_admissible_backend_payloads(
+ monkeypatch,
+ tmp_path,
+ producer,
+):
+ rejected_id = "x" * (MODEL_ID_MAX_LENGTH + 1)
+ long_display_name = "Model " + "x" * 80
+ if producer == "candidates_read":
+ producer_backend = "codex"
+ service, store, _adapter = _service(tmp_path)
+ source = ModelHubSourceConfig(
+ id="src_metadata01",
+ kind="api_key",
+ vendor="openai",
+ display_name="Metadata source",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[
+ ModelHubModelConfig(
+ id="gpt-metadata-candidate",
+ provenance="manual",
+ display_name=long_display_name,
+ reasoning_efforts=[" high "],
+ ),
+ ModelHubModelConfig(
+ id=rejected_id,
+ provenance="manual",
+ display_name="Rejected candidate",
+ ),
+ ],
+ credential_ref="cred_metadata01",
+ )
+ store.config.sources = [source]
+ store.config.agents["codex"].sources.order = [source.id]
+ monkeypatch.setattr(
+ service,
+ "_builtin_snapshots",
+ lambda _backends: {
+ "codex": {"generation": "empty-candidate-snapshot", "models": []}
+ },
+ )
+ candidates = service.agent_model_candidates("codex")["providers"]
+ assert rejected_id not in {candidate["id"] for candidate in candidates}
+ candidate = next(
+ candidate
+ for candidate in candidates
+ if candidate["id"] == "gpt-metadata-candidate"
+ )
+ payload = {
+ "id": candidate["id"],
+ "origin": candidate["origin"],
+ "display_name": candidate["display_name"],
+ "reasoning_efforts": candidate["reasoning_efforts"],
+ }
+ elif producer == "reconcile_seed":
+ producer_backend = "codex"
+ service, store, _adapter = _service(tmp_path)
+ monkeypatch.setattr(
+ service,
+ "_builtin_snapshots",
+ lambda _backends: {
+ "codex": {
+ "complete": True,
+ "models": [
+ {
+ "id": "gpt-metadata-reconcile",
+ "display_name": long_display_name,
+ "reasoning_efforts": [" high "],
+ },
+ {"id": rejected_id, "display_name": "Rejected seed"},
+ ],
+ }
+ },
+ )
+ asyncio.run(service.reconcile_builtin_models(("codex",)))
+ payload = next(
+ model.to_payload()
+ for model in store.config.agents["codex"].models
+ if model.id == "gpt-metadata-reconcile"
+ )
+ assert rejected_id not in {
+ model.id for model in store.config.agents["codex"].models
+ }
+ else:
+ producer_backend = None
+ from vibe import models_dev_catalog
+
+ monkeypatch.setattr(
+ models_dev_catalog,
+ "load_models_dev_catalog",
+ lambda: {
+ "openai": {
+ "name": "OpenAI",
+ "models": {
+ "gpt-metadata-typeahead": {
+ "name": long_display_name,
+ "reasoning_options": [
+ {"type": "effort", "values": [" high "]}
+ ],
+ },
+ rejected_id: {"name": "Metadata rejected typeahead"},
+ },
+ }
+ },
+ )
+ matches = models_dev_catalog.search_models_dev("metadata")
+ assert rejected_id not in {match["model_id"] for match in matches}
+ match = next(
+ match
+ for match in matches
+ if match["model_id"] == "gpt-metadata-typeahead"
+ )
+ payload = {
+ "id": match["model_id"],
+ "origin": "models_dev",
+ "models_dev_id": match["models_dev_id"],
+ "display_name": match["display_name"],
+ "context_window": match["context_window"],
+ "max_output_tokens": match["max_output_tokens"],
+ "input_modalities": match["input_modalities"],
+ "output_modalities": match["output_modalities"],
+ "supports_tools": match["supports_tools"],
+ "supports_reasoning": match["supports_reasoning"],
+ "reasoning_efforts": match["reasoning_efforts"],
+ }
+
+ parsed = ModelHubBackendModelConfig.from_payload(payload)
+ assert parsed.display_name == long_display_name
+ assert (
+ admissible_backend_model(
+ producer_backend,
+ parsed.id,
+ {key: value for key, value in payload.items() if key != "id"},
+ )
+ is not None
+ )
+ assert parsed == ModelHubBackendModelConfig.from_payload(parsed.to_payload())
+
+
+def test_claude_reconcile_excludes_non_claude_cli_override(monkeypatch, tmp_path):
+ service, store, _adapter = _service(tmp_path)
+ monkeypatch.setattr(
+ service,
+ "_builtin_snapshots",
+ lambda _backends: {
+ "claude": {
+ "complete": True,
+ "models": [
+ {"id": "deepseek-v3.2"},
+ {"id": "claude-sonnet-9"},
+ ],
+ }
+ },
+ )
+
+ asyncio.run(service.reconcile_builtin_models(("claude",)))
+
+ model_ids = {model.id for model in store.config.agents["claude"].models}
+ assert "deepseek-v3.2" not in model_ids
+ assert "claude-sonnet-9" in model_ids
+
+
+def test_builtin_reconcile_records_generation_and_applies_a_changed_snapshot(
+ monkeypatch,
+ tmp_path,
+):
+ service, store, _adapter = _service(tmp_path)
+ existing = store.config.agents["codex"].models[0].id
+ snapshot = {
+ "codex": {
+ "complete": True,
+ "generation": "generation-one",
+ "models": [{"id": existing}],
+ }
+ }
+ applies = []
+ original_apply = service._apply_builtin_reconcile
+
+ def apply(config, snapshots):
+ applies.append(tuple(snapshots))
+ return original_apply(config, snapshots)
+
+ monkeypatch.setattr(service, "_builtin_snapshots", lambda _backends: snapshot)
+ monkeypatch.setattr(service, "_apply_builtin_reconcile", apply)
+
+ assert asyncio.run(service.reconcile_builtin_models(("codex",))) == []
+ assert asyncio.run(service.reconcile_builtin_models(("codex",))) == []
+ assert applies == [("codex",)]
+
+ snapshot["codex"] = {
+ "complete": True,
+ "generation": "generation-two",
+ "models": [{"id": existing}, {"id": "gpt-controller-refreshed"}],
+ }
+ before_read = copy.deepcopy(store.config.to_payload())
+ payload = service.get_agent_sources("codex")
+
+ assert "gpt-controller-refreshed" not in payload["builtin_models"]
+ assert store.config.to_payload() == before_read
+ assert applies == [("codex",)]
+
+ asyncio.run(service.reconcile_builtin_models(("codex",)))
+
+ assert "gpt-controller-refreshed" in {
+ model.id for model in store.config.agents["codex"].models
+ }
+ assert applies == [("codex",), ("codex",)]
+
+
+def test_candidates_read_reconciles_builtins_but_other_reads_do_not(
+ monkeypatch,
+ tmp_path,
+):
+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
+
+ service, store, _adapter = _service(tmp_path)
+ existing = store.config.agents["codex"].models[0].id
+ snapshot = {
+ "codex": {
+ "generation": "cli-generation-one",
+ "models": [{"id": existing}],
+ }
+ }
+ monkeypatch.setattr(service, "_builtin_snapshots", lambda _backends: snapshot)
+ asyncio.run(service.reconcile_builtin_models(("codex",), notify=False))
+ snapshot["codex"] = {
+ "generation": "cli-generation-two",
+ "models": [{"id": existing}, {"id": "gpt-cli-refresh"}],
+ }
+
+ asyncio.run(dispatch_model_hub_rpc(service, "list_agents", {}))
+ assert "gpt-cli-refresh" not in {
+ model.id for model in store.config.agents["codex"].models
+ }
+
+ asyncio.run(
+ dispatch_model_hub_rpc(
+ service,
+ "list_agents",
+ {"refresh_cli_presence": True},
+ )
+ )
+ assert "gpt-cli-refresh" not in {
+ model.id for model in store.config.agents["codex"].models
+ }
+
+ asyncio.run(
+ dispatch_model_hub_rpc(
+ service,
+ "agent_model_candidates",
+ {"backend": "codex"},
+ )
+ )
+ assert "gpt-cli-refresh" in {
+ model.id for model in store.config.agents["codex"].models
+ }
+
+
+def test_builtin_reconcile_loads_legacy_baseline_before_reading_snapshot(
+ monkeypatch,
+ tmp_path,
+):
+ service, store, _adapter = _service(tmp_path)
+ calls = []
+ original_load = store.load
+
+ def load():
+ calls.append("load")
+ return original_load()
+
+ def snapshots(_backends):
+ calls.append("snapshot")
+ return {"codex": {"complete": True, "models": []}}
+
+ monkeypatch.setattr(store, "load", load)
+ monkeypatch.setattr(service, "_builtin_snapshots", snapshots)
+
+ asyncio.run(service.reconcile_builtin_models(("codex",)))
+
+ assert calls[:2] == ["load", "snapshot"]
+
+
+def test_builtin_reconcile_retries_failed_runtime_refresh(
+ monkeypatch,
+ tmp_path,
+):
+ service, store, _adapter = _service(tmp_path)
+ existing = store.config.agents["codex"].models[0].id
+ monkeypatch.setattr(
+ service,
+ "_builtin_snapshots",
+ lambda _backends: {
+ "codex": {
+ "complete": True,
+ "generation": "retry-generation",
+ "models": [{"id": existing}, {"id": "gpt-refresh-retry"}],
+ }
+ },
+ )
+ attempts = []
+
+ async def refresh(backend):
+ attempts.append(backend)
+ if len(attempts) == 1:
+ raise ModelHubError("engine_down", status=503)
+ service.backend_catalog_changed = refresh
-def test_agents_project_one_shared_backend_catalog_contract(tmp_path):
- service, _store, _adapter = _service(tmp_path)
- agents = {agent["backend"]: agent for agent in service.list_agents()}
+ with pytest.raises(ModelHubError, match="engine_down"):
+ asyncio.run(service.reconcile_builtin_models(("codex",)))
- claude_models = agents["claude"]["catalog_models"]
- assert claude_models[0] == {
- "id": "default",
- "display_name": None,
- "origin": "builtin",
- "models_dev_id": None,
- "context_window": None,
- "max_output_tokens": None,
- "input_modalities": [],
- "output_modalities": [],
- "supports_tools": None,
- "supports_reasoning": None,
- "reasoning_efforts": [],
- "locked": True,
- "routeable": False,
+ assert "gpt-refresh-retry" in {
+ model.id for model in store.config.agents["codex"].models
}
- assert all(model["locked"] is False for model in claude_models[1:])
- assert all(model["routeable"] is True for model in claude_models[1:])
- assert agents["codex"]["catalog_models"]
- assert agents["opencode"]["catalog_models"] == []
+ assert asyncio.run(service.reconcile_builtin_models(("codex",))) == []
+ assert attempts == ["codex", "codex"]
- ("backend", "model_id"),
- (
- ("claude", "claude-deepseek-v4"),
- ("codex", "deepseek-v4"),
- ("opencode", "aihub/deepseek-v4"),
- ),
-)
-def test_backend_catalog_add_edit_and_runtime_refresh(
+def test_backend_catalog_mutations_leave_every_unrelated_model_shape_byte_identical(
tmp_path,
- backend,
- model_id,
):
service, store, _adapter = _service(tmp_path)
- refreshed = []
+ agent = store.config.agents["codex"]
+ seeded = [
+ ModelHubBackendModelConfig(id=f"shape-{origin}", origin=origin)
+ for origin in ("builtin", "provider", "models_dev", "manual")
+ ]
+ agent.models = seeded
+ agent.routes = {model.id: ModelHubRouteConfig() for model in seeded}
- async def refresh(changed_backend):
- refreshed.append(changed_backend)
+ def untouched_state():
+ return json.dumps(
+ {
+ "models": [
+ model.to_payload() for model in store.config.agents["codex"].models if model.id.startswith("shape-")
+ ],
+ "routes": {model.id: store.config.agents["codex"].routes[model.id].to_payload() for model in seeded},
+ "sources": [source.to_payload() for source in store.config.sources],
+ "source_order": store.config.agents["codex"].sources.to_payload(),
+ "other_agents": {
+ backend: candidate.to_payload()
+ for backend, candidate in store.config.agents.items()
+ if backend != "codex"
+ },
+ },
+ sort_keys=True,
+ separators=(",", ":"),
+ ).encode()
- service.backend_catalog_changed = refresh
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == backend
- )
- added = {
- "id": model_id,
- "display_name": "DeepSeek V4",
- "origin": "models_dev",
- "models_dev_id": "deepseek/deepseek-v4",
- "context_window": 1_048_576,
- "max_output_tokens": 131_072,
- "input_modalities": ["text", "image"],
- "output_modalities": ["text"],
- "supports_tools": True,
- "supports_reasoning": True,
- "reasoning_efforts": ["low", "high"],
- "locked": False,
- "routeable": True,
- }
+ expected_untouched = untouched_state()
+ baseline = service.backend_catalog_models("codex")
+ added = {**baseline[-1], "id": "mutation-row", "origin": "manual"}
+ created = asyncio.run(service.set_agent_models("codex", baseline, [*baseline, added]))
+ assert untouched_state() == expected_untouched
- response = asyncio.run(
- service.set_agent_models(backend, baseline, [*baseline, added])
+ edited = copy.deepcopy(created["agent"]["catalog_models"])
+ next(model for model in edited if model["id"] == "mutation-row")["display_name"] = "Edited"
+ updated = asyncio.run(
+ service.set_agent_models(
+ "codex",
+ created["agent"]["catalog_models"],
+ edited,
+ )
)
+ assert untouched_state() == expected_untouched
- assert response["catalog_models"][-1] == added
- assert store.config.agents[backend].routes[model_id].hops == ()
- assert refreshed == [backend]
- if backend == "opencode":
- assert store.config.agents[backend].menu.checked == [model_id]
-
- edited = {**added, "display_name": "DeepSeek V4 edited", "context_window": 262_144}
- desired_catalog = (
- [response["catalog_models"][0], edited, *response["catalog_models"][1:-1]]
- if backend == "claude"
- else [edited, *response["catalog_models"][:-1]]
- )
- edited_response = asyncio.run(
+ removed = [model for model in updated["agent"]["catalog_models"] if model["id"] != "mutation-row"]
+ asyncio.run(
service.set_agent_models(
- backend,
- response["catalog_models"],
- desired_catalog,
+ "codex",
+ updated["agent"]["catalog_models"],
+ removed,
)
)
- assert next(
- model
- for model in edited_response["catalog_models"]
- if model["id"] == model_id
- ) == edited
- if backend != "claude":
- assert edited_response["catalog_models"][0] == edited
- assert refreshed == [backend, backend]
+ assert untouched_state() == expected_untouched
def test_backend_catalog_refuses_model_removal_while_route_is_configured(tmp_path):
service, store, _adapter = _service(tmp_path)
backend = "codex"
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == backend
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == backend)
model_id = baseline[0]["id"]
source = ModelHubSourceConfig(
id="src_catalog01",
@@ -2018,6 +2943,10 @@ def test_backend_catalog_refuses_model_removal_while_route_is_configured(tmp_pat
store.config.agents[backend].routes[model_id] = ModelHubRouteConfig(
hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),)
)
+ before_sources = copy.deepcopy(store.config.to_payload()["sources"])
+ before_other_agents = {
+ name: copy.deepcopy(agent.to_payload()) for name, agent in store.config.agents.items() if name != backend
+ }
with pytest.raises(ModelHubError) as raised:
asyncio.run(
@@ -2030,35 +2959,53 @@ def test_backend_catalog_refuses_model_removal_while_route_is_configured(tmp_pat
assert raised.value.code == "backend_model_in_route"
assert raised.value.status == 409
+ assert raised.value.data["would_remove_hops"] == [
+ {
+ "backend": backend,
+ "menu_model": model_id,
+ "source_id": source.id,
+ "model_id": "upstream-model",
+ "position": 1,
+ }
+ ]
assert store.config.agents[backend].models[0].id == model_id
+ result = asyncio.run(
+ service.set_agent_models(
+ backend,
+ baseline,
+ baseline[1:],
+ force=True,
+ confirmed_remove_hops=raised.value.data["would_remove_hops"],
+ confirmed_interruptions=raised.value.data["would_interrupt"],
+ )
+ )
+
+ assert result["removed_hops"] == raised.value.data["would_remove_hops"]
+ assert result["interrupted"] == raised.value.data["would_interrupt"]
+ assert model_id not in store.config.agents[backend].routes
+ assert model_id in store.config.agents[backend].removed_model_ids
+ assert store.config.to_payload()["sources"] == before_sources
+ assert {
+ name: agent.to_payload() for name, agent in store.config.agents.items() if name != backend
+ } == before_other_agents
+
def test_backend_catalog_removes_model_with_empty_route(tmp_path):
service, store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "codex"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")
removed_id = baseline[0]["id"]
- response = asyncio.run(
- service.set_agent_models("codex", baseline, baseline[1:])
- )
+ response = asyncio.run(service.set_agent_models("codex", baseline, baseline[1:]))
- assert removed_id not in {
- model["id"] for model in response["catalog_models"]
- }
+ assert removed_id not in {model["id"] for model in response["agent"]["catalog_models"]}
assert removed_id not in store.config.agents["codex"].routes
+ assert removed_id in store.config.agents["codex"].removed_model_ids
def test_backend_catalog_preserves_requested_insertion_position_for_a_new_model(tmp_path):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "codex"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")
added = {
"id": "inserted-model",
"display_name": None,
@@ -2083,9 +3030,10 @@ def test_backend_catalog_preserves_requested_insertion_position_for_a_new_model(
)
)
- assert [model["id"] for model in response["catalog_models"]][
- : len(baseline) + 1
- ] == ["inserted-model", *(model["id"] for model in baseline)]
+ assert [model["id"] for model in response["agent"]["catalog_models"]][: len(baseline) + 1] == [
+ "inserted-model",
+ *(model["id"] for model in baseline),
+ ]
def test_backend_catalog_allows_editing_a_persisted_legacy_long_id(tmp_path):
@@ -2095,21 +3043,18 @@ def test_backend_catalog_allows_editing_a_persisted_legacy_long_id(tmp_path):
agent.models.append(ModelHubBackendModelConfig(id=legacy_id, origin="manual"))
agent.routes[legacy_id] = ModelHubRouteConfig()
baseline = next(
- projected["catalog_models"]
- for projected in service.list_agents()
- if projected["backend"] == "codex"
+ projected["catalog_models"] for projected in service.list_agents() if projected["backend"] == "codex"
)
desired = copy.deepcopy(baseline)
- next(model for model in desired if model["id"] == legacy_id)[
- "display_name"
- ] = "Persisted legacy model"
+ next(model for model in desired if model["id"] == legacy_id)["display_name"] = "Persisted legacy model"
response = asyncio.run(service.set_agent_models("codex", baseline, desired))
- assert next(
- model for model in response["catalog_models"] if model["id"] == legacy_id
- )["display_name"] == "Persisted legacy model"
- _assert_valid("agent-supply.schema.json", response)
+ assert (
+ next(model for model in response["agent"]["catalog_models"] if model["id"] == legacy_id)["display_name"]
+ == "Persisted legacy model"
+ )
+ _assert_valid("agent-supply.schema.json", response["agent"])
def test_backend_catalog_allows_a_persisted_legacy_claude_alias_to_round_trip(
@@ -2121,26 +3066,20 @@ def test_backend_catalog_allows_a_persisted_legacy_claude_alias_to_round_trip(
agent.models.append(ModelHubBackendModelConfig(id=legacy_id, origin="manual"))
agent.routes[legacy_id] = ModelHubRouteConfig()
baseline = next(
- projected["catalog_models"]
- for projected in service.list_agents()
- if projected["backend"] == "claude"
+ projected["catalog_models"] for projected in service.list_agents() if projected["backend"] == "claude"
)
desired = copy.deepcopy(baseline)
desired[1]["display_name"] = "Unrelated edit"
response = asyncio.run(service.set_agent_models("claude", baseline, desired))
- assert any(model["id"] == legacy_id for model in response["catalog_models"])
- assert response["catalog_models"][1]["display_name"] == "Unrelated edit"
+ assert any(model["id"] == legacy_id for model in response["agent"]["catalog_models"])
+ assert response["agent"]["catalog_models"][1]["display_name"] == "Unrelated edit"
def test_backend_catalog_rejects_a_new_id_past_the_admission_bound(tmp_path):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "codex"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")
added = {
**baseline[0],
"id": "x" * (MODEL_ID_MAX_LENGTH + 1),
@@ -2155,11 +3094,7 @@ def test_backend_catalog_rejects_a_new_id_past_the_admission_bound(tmp_path):
def test_backend_catalog_accepts_a_new_id_at_the_contract_bound(tmp_path):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "codex"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")
model_id = "x" * MODEL_ID_MAX_LENGTH
added = {
**baseline[0],
@@ -2167,40 +3102,28 @@ def test_backend_catalog_accepts_a_new_id_at_the_contract_bound(tmp_path):
"origin": "manual",
}
- response = asyncio.run(
- service.set_agent_models("codex", baseline, [*baseline, added])
- )
+ response = asyncio.run(service.set_agent_models("codex", baseline, [*baseline, added]))
- assert response["catalog_models"][-1]["id"] == model_id
+ assert response["agent"]["catalog_models"][-1]["id"] == model_id
def test_backend_catalog_merges_an_unrelated_concurrent_edit(tmp_path):
service, store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "codex"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")
assert len(baseline) >= 2
desired = copy.deepcopy(baseline)
desired[0]["display_name"] = "Caller edit"
store.config.agents["codex"].models[1].display_name = "Concurrent edit"
- response = asyncio.run(
- service.set_agent_models("codex", baseline, desired)
- )
+ response = asyncio.run(service.set_agent_models("codex", baseline, desired))
- assert response["catalog_models"][0]["display_name"] == "Caller edit"
- assert response["catalog_models"][1]["display_name"] == "Concurrent edit"
+ assert response["agent"]["catalog_models"][0]["display_name"] == "Caller edit"
+ assert response["agent"]["catalog_models"][1]["display_name"] == "Concurrent edit"
def test_backend_catalog_rejects_a_concurrent_edit_to_the_same_row(tmp_path):
service, store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "codex"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")
desired = copy.deepcopy(baseline)
desired[0]["display_name"] = "Caller edit"
store.config.agents["codex"].models[0].display_name = "Concurrent edit"
@@ -2216,30 +3139,20 @@ def test_backend_catalog_rejects_a_concurrent_edit_to_the_same_row(tmp_path):
def test_backend_catalog_is_editable_in_direct_mode(tmp_path):
service, store, _adapter = _service(tmp_path)
store.config.agents["codex"].mode = "direct"
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "codex"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")
desired = copy.deepcopy(baseline)
desired[0]["display_name"] = "Direct-mode edit"
- response = asyncio.run(
- service.set_agent_models("codex", baseline, desired)
- )
+ response = asyncio.run(service.set_agent_models("codex", baseline, desired))
- assert response["mode"] == "direct"
- assert response["routes"] is None
- assert response["catalog_models"][0]["display_name"] == "Direct-mode edit"
+ assert response["agent"]["mode"] == "direct"
+ assert response["agent"]["routes"] is None
+ assert response["agent"]["catalog_models"][0]["display_name"] == "Direct-mode edit"
def test_backend_catalog_reports_duplicate_ids(tmp_path):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "codex"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")
with pytest.raises(ModelHubError) as raised:
asyncio.run(
@@ -2255,11 +3168,7 @@ def test_backend_catalog_reports_duplicate_ids(tmp_path):
def test_codex_catalog_treats_default_as_an_ordinary_model_id(tmp_path):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "codex"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "codex")
added = {
**baseline[0],
"id": "default",
@@ -2267,29 +3176,20 @@ def test_codex_catalog_treats_default_as_an_ordinary_model_id(tmp_path):
"origin": "manual",
}
- created = asyncio.run(
- service.set_agent_models("codex", baseline, [*baseline, added])
- )
- desired = copy.deepcopy(created["catalog_models"])
- next(model for model in desired if model["id"] == "default")[
- "display_name"
- ] = "Edited default"
- edited = asyncio.run(
- service.set_agent_models("codex", created["catalog_models"], desired)
- )
+ created = asyncio.run(service.set_agent_models("codex", baseline, [*baseline, added]))
+ desired = copy.deepcopy(created["agent"]["catalog_models"])
+ next(model for model in desired if model["id"] == "default")["display_name"] = "Edited default"
+ edited = asyncio.run(service.set_agent_models("codex", created["agent"]["catalog_models"], desired))
- assert next(
- model for model in edited["catalog_models"] if model["id"] == "default"
- )["display_name"] == "Edited default"
+ assert (
+ next(model for model in edited["agent"]["catalog_models"] if model["id"] == "default")["display_name"]
+ == "Edited default"
+ )
def test_backend_catalog_rejects_client_claimed_builtin_origin(tmp_path):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "claude"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "claude")
forged = {
**baseline[1],
"id": "unprefixed-third-party-model",
@@ -2304,14 +3204,12 @@ def test_backend_catalog_rejects_client_claimed_builtin_origin(tmp_path):
@pytest.mark.parametrize(
("origin", "replacement"),
- (
- ("manual", "models_dev"),
- ("manual", "builtin"),
- ("models_dev", "manual"),
- ("models_dev", "builtin"),
- ("builtin", "manual"),
- ("builtin", "models_dev"),
- ),
+ [
+ (origin, replacement)
+ for origin in ("builtin", "provider", "models_dev", "manual")
+ for replacement in ("builtin", "provider", "models_dev", "manual")
+ if origin != replacement
+ ],
)
def test_backend_catalog_keeps_every_existing_origin_immutable(
tmp_path,
@@ -2324,14 +3222,10 @@ def test_backend_catalog_keeps_every_existing_origin_immutable(
agent.models.append(ModelHubBackendModelConfig(id=model_id, origin=origin))
agent.routes[model_id] = ModelHubRouteConfig()
baseline = next(
- projected["catalog_models"]
- for projected in service.list_agents()
- if projected["backend"] == "codex"
+ projected["catalog_models"] for projected in service.list_agents() if projected["backend"] == "codex"
)
desired = copy.deepcopy(baseline)
- next(model for model in desired if model["id"] == model_id)[
- "origin"
- ] = replacement
+ next(model for model in desired if model["id"] == model_id)["origin"] = replacement
with pytest.raises(ModelHubError) as raised:
asyncio.run(service.set_agent_models("codex", baseline, desired))
@@ -2347,21 +3241,15 @@ def test_backend_catalog_rejects_an_origin_forged_into_the_baseline(tmp_path):
agent.models.append(ModelHubBackendModelConfig(id=model_id, origin="manual"))
agent.routes[model_id] = ModelHubRouteConfig()
observed = next(
- projected["catalog_models"]
- for projected in service.list_agents()
- if projected["backend"] == "codex"
+ projected["catalog_models"] for projected in service.list_agents() if projected["backend"] == "codex"
)
forged_baseline = copy.deepcopy(observed)
forged_desired = copy.deepcopy(observed)
for catalog in (forged_baseline, forged_desired):
- next(model for model in catalog if model["id"] == model_id)[
- "origin"
- ] = "models_dev"
+ next(model for model in catalog if model["id"] == model_id)["origin"] = "models_dev"
with pytest.raises(ModelHubError) as raised:
- asyncio.run(
- service.set_agent_models("codex", forged_baseline, forged_desired)
- )
+ asyncio.run(service.set_agent_models("codex", forged_baseline, forged_desired))
assert raised.value.code == "backend_model_locked"
assert next(model for model in agent.models if model.id == model_id).origin == "manual"
@@ -2372,16 +3260,10 @@ def test_backend_catalog_restores_a_removed_claude_builtin_alias(
tmp_path,
model_id,
):
- service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "claude"
- )
+ service, store, _adapter = _service(tmp_path)
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "claude")
without_alias = [model for model in baseline if model["id"] != model_id]
- removed = asyncio.run(
- service.set_agent_models("claude", baseline, without_alias)
- )
+ removed = asyncio.run(service.set_agent_models("claude", baseline, without_alias))
restored = {
**next(model for model in baseline if model["id"] == model_id),
"origin": "manual",
@@ -2390,21 +3272,18 @@ def test_backend_catalog_restores_a_removed_claude_builtin_alias(
response = asyncio.run(
service.set_agent_models(
"claude",
- removed["catalog_models"],
- [*removed["catalog_models"], restored],
+ removed["agent"]["catalog_models"],
+ [*removed["agent"]["catalog_models"], restored],
)
)
- assert response["catalog_models"][-1] == restored
+ assert response["agent"]["catalog_models"][-1] == restored
+ assert model_id not in store.config.agents["claude"].removed_model_ids
def test_backend_catalog_still_rejects_an_unknown_unprefixed_claude_id(tmp_path):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "claude"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "claude")
unknown = {
**baseline[1],
"id": "deepseek-v4",
@@ -2421,11 +3300,7 @@ def test_backend_catalog_rejects_a_new_unprefixed_claude_id_forged_into_baseline
tmp_path,
):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "claude"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "claude")
forged = {
**baseline[1],
"id": "deepseek-v4",
@@ -2446,11 +3321,7 @@ def test_backend_catalog_rejects_a_new_unprefixed_claude_id_forged_into_baseline
def test_backend_catalog_requires_claude_locked_default_echo(tmp_path):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "claude"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "claude")
with pytest.raises(ModelHubError) as raised:
asyncio.run(service.set_agent_models("claude", baseline, baseline[1:]))
@@ -2465,11 +3336,7 @@ def test_backend_catalog_rejects_any_claude_locked_default_mutation(
mutation,
):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "claude"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "claude")
desired = copy.deepcopy(baseline)
if mutation == "edit":
desired[0]["display_name"] = "Not the server sentinel"
@@ -2487,11 +3354,7 @@ def test_backend_catalog_rejects_any_claude_locked_default_mutation(
def test_backend_catalog_reports_claude_discovery_prefix_requirement(tmp_path):
service, _store, _adapter = _service(tmp_path)
- baseline = next(
- agent["catalog_models"]
- for agent in service.list_agents()
- if agent["backend"] == "claude"
- )
+ baseline = next(agent["catalog_models"] for agent in service.list_agents() if agent["backend"] == "claude")
invalid = {
**baseline[1],
"id": "deepseek-v4",
@@ -2520,9 +3383,7 @@ def test_agents_endpoint_projects_cli_presence_from_runtime(tmp_path):
def test_agents_collection_reads_cli_presence_without_running_discovery(tmp_path):
service, _store, _adapter = _service(tmp_path)
calls = []
- service.cli_presence_refresh = lambda include_npm_global, backends: calls.append(
- (include_npm_global, backends)
- )
+ service.cli_presence_refresh = lambda include_npm_global, backends: calls.append((include_npm_global, backends))
service.cli_present_override = lambda backend: backend == "codex"
agents = {agent["backend"]: agent for agent in service.list_agents()}
@@ -2551,29 +3412,21 @@ def test_agents_endpoint_projects_exact_chain_runnability(tmp_path):
hops=(ModelHubRouteHopConfig(source.id, model_id),)
)
- supplied = {
- row["model_id"]: row
- for row in service.get_agent_sources("claude")["model_supply"]
- }
+ supplied = {row["model_id"]: row for row in service.get_agent_sources("claude")["model_supply"]}
assert supplied[model_id] == {
"model_id": model_id,
"chain_length": 1,
"has_runnable_hop": True,
}
- empty_model = next(
- model for model, row in supplied.items() if row["chain_length"] == 0
- )
+ empty_model = next(model for model, row in supplied.items() if row["chain_length"] == 0)
assert supplied[empty_model]["has_runnable_hop"] is False
source.state = ModelHubSourceStateConfig(
status="needs_action",
detail_key="models.source.needs_action.oauth_expired",
)
- blocked = {
- row["model_id"]: row
- for row in service.get_agent_sources("claude")["model_supply"]
- }
+ blocked = {row["model_id"]: row for row in service.get_agent_sources("claude")["model_supply"]}
assert blocked[model_id]["chain_length"] == 1
assert blocked[model_id]["has_runnable_hop"] is False
@@ -2633,9 +3486,7 @@ def test_agent_supply_mutation_rpc_refreshes_cli_presence_before_writing(tmp_pat
service, store, _adapter = _service(tmp_path)
calls = []
- service.cli_presence_refresh = lambda include_npm_global, backends: calls.append(
- (include_npm_global, backends)
- )
+ service.cli_presence_refresh = lambda include_npm_global, backends: calls.append((include_npm_global, backends))
service.cli_present_override = lambda backend: backend == "claude"
payload = asyncio.run(
@@ -2719,24 +3570,10 @@ def test_agent_supply_rpc_publishes_explicit_deep_discovery_after_fast_reads(
deep_release.set()
first, second, refreshed, joined = payloads
- assert (
- next(agent for agent in first if agent["backend"] == "codex")["cli_present"]
- is False
- )
- assert (
- next(agent for agent in second if agent["backend"] == "codex")["cli_present"]
- is False
- )
- assert (
- next(agent for agent in refreshed if agent["backend"] == "codex")[
- "cli_present"
- ]
- is True
- )
- assert (
- next(agent for agent in joined if agent["backend"] == "codex")["cli_present"]
- is True
- )
+ assert next(agent for agent in first if agent["backend"] == "codex")["cli_present"] is False
+ assert next(agent for agent in second if agent["backend"] == "codex")["cli_present"] is False
+ assert next(agent for agent in refreshed if agent["backend"] == "codex")["cli_present"] is True
+ assert next(agent for agent in joined if agent["backend"] == "codex")["cli_present"] is True
assert calls == [(True, None)]
@@ -2760,9 +3597,7 @@ def test_targeted_cli_refresh_does_not_wait_for_unrelated_full_inventory(tmp_pat
service.cli_presence_refresh = refresh
async def exercise() -> None:
- full = asyncio.create_task(
- model_hub_rpc._refresh_agent_presence(service)
- )
+ full = asyncio.create_task(model_hub_rpc._refresh_agent_presence(service))
assert await asyncio.to_thread(full_started.wait, 0.5)
await asyncio.wait_for(
model_hub_rpc._refresh_agent_presence(service, ("opencode",)),
@@ -2825,10 +3660,7 @@ def test_agents_route_requests_deep_presence_only_when_explicit(monkeypatch):
client = app.test_client()
assert client.get("/api/models/agents").status_code == 200
- assert (
- client.get("/api/models/agents?refresh_cli_presence=1").status_code
- == 200
- )
+ assert client.get("/api/models/agents?refresh_cli_presence=1").status_code == 200
assert calls == [False, True]
@@ -2961,9 +3793,7 @@ def test_direct_to_hub_atomically_adopts_recognized_native_login(tmp_path):
assert native.vendor == "anthropic"
assert store.config.agents["claude"].sources.order[0] == native.id
assert any(
- hop.source_id == native.id
- for route in store.config.agents["claude"].routes.values()
- for hop in route.hops
+ hop.source_id == native.id for route in store.config.agents["claude"].routes.values() for hop in route.hops
)
repeated = asyncio.run(service.set_agent_mode("claude", "hub"))
@@ -3004,15 +3834,11 @@ def test_hub_to_direct_fallback_does_not_require_engine_sync(tmp_path):
def test_public_mutation_surface_has_one_engine_projection_owner(tmp_path):
service_node = next(
node
- for node in ast.parse(
- Path("core/handlers/model_hub/service.py").read_text(encoding="utf-8")
- ).body
+ for node in ast.parse(Path("core/handlers/model_hub/service.py").read_text(encoding="utf-8")).body
if isinstance(node, ast.ClassDef) and node.name == "ModelHubService"
)
methods = {
- node.name: node
- for node in service_node.body
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
+ node.name: node for node in service_node.body if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))
}
def called_service_methods(method: ast.AST) -> set[str]:
@@ -3032,9 +3858,7 @@ def test_public_mutation_surface_has_one_engine_projection_owner(tmp_path):
calls.add("_save_config")
return calls
- call_graph = {
- name: called_service_methods(method) for name, method in methods.items()
- }
+ call_graph = {name: called_service_methods(method) for name, method in methods.items()}
def reachable(start: str) -> set[str]:
visited: set[str] = set()
@@ -3048,11 +3872,7 @@ def test_public_mutation_surface_has_one_engine_projection_owner(tmp_path):
return visited
owners = {"_commit_synced", "_save_projection_neutral"}
- public_mutations = {
- name
- for name in methods
- if not name.startswith("_") and "_save_config" in reachable(name)
- }
+ public_mutations = {name for name in methods if not name.startswith("_") and "_save_config" in reachable(name)}
assert public_mutations
assert all(reachable(name) & owners for name in public_mutations), sorted(
name for name in public_mutations if not reachable(name) & owners
@@ -3061,11 +3881,7 @@ def test_public_mutation_surface_has_one_engine_projection_owner(tmp_path):
for name, method in methods.items():
if name in owners:
continue
- parents = {
- child: parent
- for parent in ast.walk(method)
- for child in ast.iter_child_nodes(parent)
- }
+ parents = {child: parent for parent in ast.walk(method) for child in ast.iter_child_nodes(parent)}
for node in ast.walk(method):
if (
not isinstance(node, ast.Call)
@@ -3102,9 +3918,7 @@ def test_public_mutation_surface_has_one_engine_projection_owner(tmp_path):
previous = store.config
changed = service._clone_config(previous)
- changed.sources[0].models.append(
- ModelHubModelConfig(id="claude-sonnet-4-6", provenance="manual")
- )
+ changed.sources[0].models.append(ModelHubModelConfig(id="claude-sonnet-4-6", provenance="manual"))
asyncio.run(service._commit_synced(previous, changed))
@@ -3123,16 +3937,12 @@ def test_source_adoption_projection_is_sorted_by_backend_and_menu_model(tmp_path
supply_channel="hub",
billing="metered",
state=ModelHubSourceStateConfig(status="standby"),
- models=[
- ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered")
- ],
+ models=[ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered")],
credential_ref="cred_adopted001",
)
store.config.sources = [source]
store.config.agents["claude"].routes = {
- model_id: ModelHubRouteConfig(
- hops=(ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),)
- )
+ model_id: ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),))
for model_id in ("z-model", "a-model")
}
@@ -3160,9 +3970,7 @@ def test_source_adoption_projection_ignores_routes_for_direct_backends(tmp_path)
)
store.config.sources = [source]
store.config.agents["claude"].routes = {
- "claude-opus-4-6": ModelHubRouteConfig(
- hops=(ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),)
- )
+ "claude-opus-4-6": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),))
}
store.config.agents["claude"].mode = "direct"
@@ -3535,7 +4343,10 @@ def test_ui_model_hub_rpc_preserves_structured_guard_data():
@pytest.mark.parametrize(
("method", "path"),
[
- (entry["method"], entry["exercise"]["path"])
+ (
+ entry["method"],
+ entry.get("exercises", [entry.get("exercise")])[0]["path"],
+ )
for entry in API_RESPONSE_ROUTES
],
)
@@ -3587,9 +4398,7 @@ def test_disabled_model_hub_rest_surface_returns_feature_disabled_without_runtim
@pytest.mark.parametrize("method", ["get", "post"])
@pytest.mark.parametrize(("env_value", "expected"), [(None, False), ("0", False), ("1", True)])
-def test_config_capability_exactly_projects_backend_model_hub_gate(
- monkeypatch, tmp_path, method, env_value, expected
-):
+def test_config_capability_exactly_projects_backend_model_hub_gate(monkeypatch, tmp_path, method, env_value, expected):
from config.v2_config import is_model_hub_enabled
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
@@ -3621,13 +4430,9 @@ def test_final_model_hub_route_surface_has_observe_refresh_and_no_saved_test_rou
def test_models_live_api_calls_only_registered_server_routes():
- source = Path("ui/src/components/settings/models/modelsApi.ts").read_text(
- encoding="utf-8"
- )
+ source = Path("ui/src/components/settings/models/modelsApi.ts").read_text(encoding="utf-8")
live_api = source.split("export const modelsApi: ModelsApi = {", 1)[1]
- path_pattern = re.compile(
- r"'(?P<single>/api/models/[^']*)'|`(?P<template>/api/models/[^`]*)`"
- )
+ path_pattern = re.compile(r"'(?P<single>/api/models/[^']*)'|`(?P<template>/api/models/[^`]*)`")
path_matches = list(path_pattern.finditer(live_api))
assert len(path_matches) == len(re.findall(r"\bcall(?:<|\()", live_api))
@@ -3643,11 +4448,7 @@ def test_models_live_api_calls_only_registered_server_routes():
live_api[match.end() :],
re.MULTILINE,
)
- entry_tail = (
- live_api[match.end() : match.end() + next_entry.start()]
- if next_entry
- else live_api[match.end() :]
- )
+ entry_tail = live_api[match.end() : match.end() + next_entry.start()] if next_entry else live_api[match.end() :]
method_match = re.search(r"jsonInit\('(POST|PUT|PATCH|DELETE)'", entry_tail)
client_routes.add((method_match.group(1) if method_match else "GET", path))
@@ -3892,11 +4693,7 @@ def test_source_create_requires_explicit_consent_for_proven_inventory_failure(
assert adapter.revoked == ["cred_test001"]
assert catalog_index_loads == 0
- created = asyncio.run(
- service.create_source(
- {**payload, "accept_unavailable_inventory": True}
- )
- )["source"]
+ created = asyncio.run(service.create_source({**payload, "accept_unavailable_inventory": True}))["source"]
assert created["protocol"] == "anthropic"
assert [
@@ -4019,16 +4816,12 @@ def test_native_oauth_malformed_start_keeps_flow_id_when_cleanup_fails(tmp_path)
async def malformed_start(source_id, vendor):
flow = await original_start(source_id, vendor)
- return OAuthFlowState(
- **{**flow.__dict__, "source_id": "src_provider_mismatch"}
- )
+ return OAuthFlowState(**{**flow.__dict__, "source_id": "src_provider_mismatch"})
adapter.start_oauth = malformed_start
adapter.fail_cancel = True
with pytest.raises(ModelHubError) as failed:
- asyncio.run(
- service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})
- )
+ asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))
assert failed.value.code == "engine_down"
# The flow id the provider was started under stays the cleanup handle even
@@ -4039,9 +4832,7 @@ def test_native_oauth_malformed_start_keeps_flow_id_when_cleanup_fails(tmp_path)
def test_oauth_start_normalizes_vendor_before_singleton_and_adapter(tmp_path):
service, _store, adapter = _service(tmp_path)
- flow = asyncio.run(
- service.oauth_start({"vendor": " Anthropic ", "channel": "hub"})
- )["flow"]
+ flow = asyncio.run(service.oauth_start({"vendor": " Anthropic ", "channel": "hub"}))["flow"]
assert flow["vendor"] == "anthropic"
assert adapter.oauth_start_calls == [(flow["source_id"], "anthropic")]
@@ -4077,9 +4868,7 @@ def test_oauth_start_rejects_invalid_nonce_payload_before_provider(tmp_path, pay
def test_model_hub_oauth_blocks_recovery_before_external_auth(tmp_path):
service, store, adapter = _service(tmp_path)
- flow = asyncio.run(
- service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})
- )["flow"]
+ flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))["flow"]
store.recovery = True
with pytest.raises(ModelHubError) as start_error:
@@ -4088,16 +4877,12 @@ def test_model_hub_oauth_blocks_recovery_before_external_auth(tmp_path):
assert len(adapter.oauth_start_calls) == 1
with pytest.raises(ModelHubError) as submit_error:
- asyncio.run(
- service.oauth_submit({"flow_id": flow["flow_id"], "value": "auth-code"})
- )
+ asyncio.run(service.oauth_submit({"flow_id": flow["flow_id"], "value": "auth-code"}))
assert submit_error.value.code == "config_recovery"
assert adapter.secret_lengths == []
-def test_chain_route_preserves_submitted_hops_against_opposite_source_order(
- monkeypatch, tmp_path
-):
+def test_chain_route_preserves_submitted_hops_against_opposite_source_order(monkeypatch, tmp_path):
service, store, _ = _service(tmp_path)
first = asyncio.run(
_create_source(
@@ -4127,9 +4912,7 @@ def test_chain_route_preserves_submitted_hops_against_opposite_source_order(
{"source_id": second["id"], "model_id": model_id},
{"source_id": first["id"], "model_id": model_id},
]
- assert store.config.agents["claude"].sources.order == [
- hop["source_id"] for hop in reversed(hops)
- ]
+ assert store.config.agents["claude"].sources.order == [hop["source_id"] for hop in reversed(hops)]
monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
client = app.test_client()
base_url = "http://127.0.0.1:15131"
@@ -4149,15 +4932,12 @@ def test_chain_route_preserves_submitted_hops_against_opposite_source_order(
(hop["source_id"], hop["model_id"]) for hop in hops
]
assert body["chain"]["current"] == {"source_id": second["id"], "model_id": model_id}
- assert [
- (hop.source_id, hop.model_id)
- for hop in store.config.agents["claude"].routes[model_id].hops
- ] == [(hop["source_id"], hop["model_id"]) for hop in hops]
+ assert [(hop.source_id, hop.model_id) for hop in store.config.agents["claude"].routes[model_id].hops] == [
+ (hop["source_id"], hop["model_id"]) for hop in hops
+ ]
-def test_chain_route_guard_requires_and_replays_the_exact_current_plan(
- monkeypatch, tmp_path
-):
+def test_chain_route_guard_requires_and_replays_the_exact_current_plan(monkeypatch, tmp_path):
service, store, _ = _service(tmp_path)
model_id = "claude-opus-4-6"
first_id, second_id = "src_chain0101", "src_chain0102"
@@ -4199,9 +4979,7 @@ def test_chain_route_guard_requires_and_replays_the_exact_current_plan(
"position": 2,
},
]
- assert refusal["would_interrupt"] == [
- {"backend": "claude", "model_id": model_id, "agents": []}
- ]
+ assert refusal["would_interrupt"] == [{"backend": "claude", "model_id": model_id, "agents": []}]
unconfirmed = client.put(
endpoint,
@@ -4220,10 +4998,9 @@ def test_chain_route_guard_requires_and_replays_the_exact_current_plan(
assert unconfirmed.status_code == 409
assert unconfirmed.get_json()["would_remove_hops"] == refusal["would_remove_hops"]
- assert [
- (hop.source_id, hop.model_id)
- for hop in store.config.agents["claude"].routes[model_id].hops
- ] == [(hop.source_id, hop.model_id) for hop in old_hops]
+ assert [(hop.source_id, hop.model_id) for hop in store.config.agents["claude"].routes[model_id].hops] == [
+ (hop.source_id, hop.model_id) for hop in old_hops
+ ]
committed = client.put(
endpoint,
@@ -4259,9 +5036,7 @@ def test_chain_route_noninterrupting_success_is_force_invariant(monkeypatch, tmp
model_id,
)
forced_service, forced_store, _ = _service(tmp_path / "forced")
- forced_store.config = ModelHubConfig.from_payload(
- unforced_store.config.to_payload()
- )
+ forced_store.config = ModelHubConfig.from_payload(unforced_store.config.to_payload())
client = app.test_client()
base_url = "http://127.0.0.1:15131"
headers = csrf_headers(client, base_url)
@@ -4319,10 +5094,7 @@ def test_delete_guard_reports_only_routes_emptied_by_this_mutation(tmp_path):
claude = store.config.agents["claude"]
claude.sources.order = [source.id]
claude.routes = {
- **{
- model_id: ModelHubRouteConfig()
- for model_id in claude.routes
- },
+ **{model_id: ModelHubRouteConfig() for model_id in claude.routes},
"claude-opus-4-6": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),)),
"claude-sonnet-4-6": ModelHubRouteConfig(),
}
@@ -4373,7 +5145,6 @@ def test_disabled_gate_preserves_existing_model_hub_config_bytes(monkeypatch):
),
("/api/models/agents/claude/sources", "put", "invalid_source_order"),
("/api/models/agents/claude/mode", "patch", "mode_switch_blocked"),
- ("/api/models/agents/opencode/menu", "put", "mapping_target_unavailable"),
(
"/api/models/sources/src_test0001/models",
"post",
@@ -4478,10 +5249,7 @@ def test_discovered_source_model_delete_persists_retirement_tombstone(
)
assert refreshed.status_code == 200
- refreshed_models = {
- model["id"]: model
- for model in refreshed.get_json()["source"]["models"]
- }
+ refreshed_models = {model["id"]: model for model in refreshed.get_json()["source"]["models"]}
assert refreshed_models["gpt-5"]["retired"] is True
assert refreshed_models["gpt-5.1"]["retired"] is False
@@ -6259,17 +7027,12 @@ def test_credential_route_carries_body_force_override_and_structured_guard(
assert refused.status_code == 409
refusal = refused.get_json()
- route_hop_schema = _schema("guard-refusal.schema.json")["definitions"][
- "RouteHopRef"
- ]
+ route_hop_schema = _schema("guard-refusal.schema.json")["definitions"]["RouteHopRef"]
for hop in refusal["would_remove_hops"]:
Draft7Validator(route_hop_schema).validate(hop)
assert refusal["error"] == "source_model_in_route_chain"
assert refusal["would_remove_hops"]
- assert all(
- hop["source_id"] == created["id"]
- for hop in refusal["would_remove_hops"]
- )
+ assert all(hop["source_id"] == created["id"] for hop in refusal["would_remove_hops"])
assert refusal["would_interrupt"] == [
{
"backend": "claude",
@@ -6305,12 +7068,8 @@ def test_credential_route_carries_body_force_override_and_structured_guard(
)
assert stale_confirmation.status_code == 409
assert stale_confirmation.get_json()["error"] == refusal["error"]
- assert stale_confirmation.get_json()["would_remove_hops"] == refusal[
- "would_remove_hops"
- ]
- assert stale_confirmation.get_json()["would_interrupt"] == refusal[
- "would_interrupt"
- ]
+ assert stale_confirmation.get_json()["would_remove_hops"] == refusal["would_remove_hops"]
+ assert stale_confirmation.get_json()["would_interrupt"] == refusal["would_interrupt"]
committed = client.put(
f"/api/models/sources/{created['id']}/credential",
@@ -6328,8 +7087,7 @@ def test_credential_route_carries_body_force_override_and_structured_guard(
assert committed["interrupted"] == refusal["would_interrupt"]
assert committed["source"]["credential_ref"] == "cred_route_5"
removed_identities = {
- (hop["backend"], hop["menu_model"], hop["source_id"], hop["model_id"])
- for hop in committed["removed_hops"]
+ (hop["backend"], hop["menu_model"], hop["source_id"], hop["model_id"]) for hop in committed["removed_hops"]
}
assert all(
(backend, menu_model, hop.source_id, hop.model_id) not in removed_identities
@@ -6381,9 +7139,7 @@ def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):
def test_completed_hub_oauth_persists_only_a_response_proven_protocol(tmp_path):
service, store, adapter = _service(tmp_path)
- flow = asyncio.run(service.oauth_start({"vendor": "openai", "channel": "hub"}))[
- "flow"
- ]
+ flow = asyncio.run(service.oauth_start({"vendor": "openai", "channel": "hub"}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -6423,9 +7179,7 @@ def test_completed_hub_oauth_persists_only_a_response_proven_protocol(tmp_path):
def test_completed_hub_oauth_rejects_unproven_protocol_before_persistence(tmp_path):
service, store, adapter = _service(tmp_path)
- flow = asyncio.run(service.oauth_start({"vendor": "openai", "channel": "hub"}))[
- "flow"
- ]
+ flow = asyncio.run(service.oauth_start({"vendor": "openai", "channel": "hub"}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -6570,9 +7324,7 @@ def test_nonce_oauth_start_replays_cancelled_flow_until_expiry(tmp_path):
},
}
assert retained["expires_at"] == first["expires_at"]
- assert adapter.oauth_start_calls == [
- (first["source_id"], "anthropic")
- ]
+ assert adapter.oauth_start_calls == [(first["source_id"], "anthropic")]
current[0] = datetime(2026, 7, 23, 4, 15, tzinfo=timezone.utc)
fresh = asyncio.run(service.oauth_start(request))["flow"]
@@ -6680,12 +7432,9 @@ def test_oauth_start_keeps_every_owner_await_inside_the_installed_task(tmp_path)
tree = ast.parse(textwrap.dedent(inspect.getsource(ModelHubService.oauth_start)))
body = tree.body[0].body
claim = next(i for i, stmt in enumerate(body) if "claim_nonce" in ast.unparse(stmt))
- install = next(
- i for i, stmt in enumerate(body)
- if "_oauth_start_tasks[nonce_key] = task" in ast.unparse(stmt)
- )
+ install = next(i for i, stmt in enumerate(body) if "_oauth_start_tasks[nonce_key] = task" in ast.unparse(stmt))
- for stmt in body[claim + 1:install]:
+ for stmt in body[claim + 1 : install]:
if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):
# The task's own awaits are the safe ones: it is installed before it
# is awaited, and it owns the release.
@@ -6694,10 +7443,7 @@ def test_oauth_start_keeps_every_owner_await_inside_the_installed_task(tmp_path)
# No nonce, no claim — nothing for a retry to await or for a
# cancellation to leak.
continue
- waits = [
- node for node in ast.walk(stmt)
- if isinstance(node, (ast.Await, ast.AsyncWith, ast.AsyncFor))
- ]
+ waits = [node for node in ast.walk(stmt) if isinstance(node, (ast.Await, ast.AsyncWith, ast.AsyncFor))]
assert not waits, f"owner awaits before its task is installed: {ast.unparse(stmt)}"
@@ -6756,9 +7502,7 @@ def test_native_oauth_start_recovers_the_vendor_after_failure_and_cancel(tmp_pat
return await original_start(source_id, vendor)
adapter.start_oauth = blocked_start
- pending = asyncio.create_task(
- service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})
- )
+ pending = asyncio.create_task(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))
await provider_started.wait()
pending.cancel()
with pytest.raises(asyncio.CancelledError):
@@ -6766,9 +7510,7 @@ def test_native_oauth_start_recovers_the_vendor_after_failure_and_cancel(tmp_pat
release_provider.set()
await asyncio.sleep(0)
adapter.start_oauth = original_start
- recovered = await service.oauth_start(
- {"vendor": "anthropic", "channel": "native_cli"}
- )
+ recovered = await service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})
return recovered, adapter
recovered, adapter = asyncio.run(run_recovery())
@@ -7316,11 +8058,7 @@ def test_source_patch_rejects_credential_bearing_base_url(tmp_path):
@pytest.mark.parametrize(
("field", "case"),
- [
- (field, case)
- for field in ("display_names", "base_urls")
- for case in SOURCE_EDIT_VALIDATION_CASES[field]
- ],
+ [(field, case) for field in ("display_names", "base_urls") for case in SOURCE_EDIT_VALIDATION_CASES[field]],
ids=lambda value: value.get("id", value) if isinstance(value, dict) else value,
)
def test_source_edit_validation_contract_fixture(tmp_path, field, case):
@@ -7341,15 +8079,11 @@ def test_source_edit_validation_contract_fixture(tmp_path, field, case):
if not case["valid"]:
with pytest.raises(ModelHubError) as exc_info:
- asyncio.run(
- service.patch_source(source["id"], {payload_field: case["value"]})
- )
+ asyncio.run(service.patch_source(source["id"], {payload_field: case["value"]}))
assert exc_info.value.code == "discovery_failed"
return
- updated = asyncio.run(
- service.patch_source(source["id"], {payload_field: case["value"]})
- )
+ updated = asyncio.run(service.patch_source(source["id"], {payload_field: case["value"]}))
expected = case.get("normalized", case["value"])
assert updated["source"][payload_field] == expected
assert getattr(store.config.sources[0], payload_field) == expected
@@ -7758,8 +8492,7 @@ def test_base_url_change_guards_and_prunes_invalid_exact_hops(
assert committed["interrupted"] == refusal["would_interrupt"]
assert store.config.sources[0].base_url == replacement_url
removed_identities = {
- (hop["backend"], hop["menu_model"], hop["source_id"], hop["model_id"])
- for hop in committed["removed_hops"]
+ (hop["backend"], hop["menu_model"], hop["source_id"], hop["model_id"]) for hop in committed["removed_hops"]
}
assert all(
(backend, menu_model, hop.source_id, hop.model_id) not in removed_identities
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index efbbe671a..8ac726137 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -94,9 +94,7 @@ def test_protocol_vocabulary_matches_authority_and_rejects_removed_alias():
"mockData.ts",
"modelRows.test.ts",
):
- assert retired_alias not in (UI_MODEL_CONSUMERS / filename).read_text(
- encoding="utf-8"
- )
+ assert retired_alias not in (UI_MODEL_CONSUMERS / filename).read_text(encoding="utf-8")
example = copy.deepcopy(_schema("source.schema.json")["examples"][0])
example["protocol"] = retired_alias
@@ -194,9 +192,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
}
for field_name, rejected_values in invalid_fields.items():
for rejected in rejected_values:
- invalid_observation = SourceObservation(
- **{**baseline.__dict__, field_name: rejected}
- )
+ invalid_observation = SourceObservation(**{**baseline.__dict__, field_name: rejected})
with pytest.raises(ValueError):
validate_source_observation(invalid_observation)
with pytest.raises(ValidationError):
@@ -363,9 +359,7 @@ def test_persisted_model_hub_identifiers_share_the_canonical_validation_boundary
payload = ModelHubConfig().to_payload()
opencode = payload["agents"]["opencode"]
- opencode["routes"]["custom/authorization: sk-test-credential-material"] = {
- "hops": []
- }
+ opencode["routes"]["custom/authorization: sk-test-credential-material"] = {"hops": []}
with pytest.raises(ValueError):
ModelHubConfig.from_payload(payload)
@@ -511,9 +505,7 @@ def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():
for raw_example in _schema("agent-supply.schema.json")["examples"]:
example = {
- key: value
- for key, value in raw_example.items()
- if key not in {"builtin_models", "standard_vendors"}
+ key: value for key, value in raw_example.items() if key not in {"builtin_models", "standard_vendors"}
}
agent = ModelHubAgentSupplyConfig.from_payload(example)
# `builtin_models` and `standard_vendors` are read-only endpoint
@@ -525,6 +517,7 @@ def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():
"standard_vendors": raw_example.get("standard_vendors"),
}
serialized.pop("models", None)
+ serialized.pop("removed_model_ids", None)
if "routes" not in raw_example:
serialized.pop("routes", None)
if "sources" not in raw_example:
@@ -546,15 +539,11 @@ def test_source_client_nonce_round_trips_and_is_unique():
for invalid in (None, "scn_short", "SCN_01j5w8z7p4n6q2rt", "scn_01j5w8z7p4n6q2r!"):
with pytest.raises(ValueError, match="client_nonce"):
- ModelHubSourceConfig.from_payload(
- {**first_payload, "client_nonce": invalid}
- )
+ ModelHubSourceConfig.from_payload({**first_payload, "client_nonce": invalid})
second_payload = copy.deepcopy(first_payload)
second_payload["id"] = "src_relay9c2x"
- duplicate = ModelHubConfig(
- sources=[first, ModelHubSourceConfig.from_payload(second_payload)]
- )
+ duplicate = ModelHubConfig(sources=[first, ModelHubSourceConfig.from_payload(second_payload)])
with pytest.raises(ValueError, match="duplicate client nonces"):
ModelHubConfig.from_payload(duplicate.to_payload())
@@ -591,28 +580,18 @@ def test_source_create_unavailable_inventory_consent_is_explicit_and_total():
validator.validate({**clean, "accept_unavailable_inventory": invalid})
api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")
- consent_table = api_contract.split(
- "### Source-create unavailable-inventory consent", 1
- )[1].split("When `client_nonce` is present", 1)[0]
- result_rows = [
- line
- for line in consent_table.splitlines()
- if line.startswith("| Protocol ")
- ]
+ consent_table = api_contract.split("### Source-create unavailable-inventory consent", 1)[1].split(
+ "When `client_nonce` is present", 1
+ )[0]
+ result_rows = [line for line in consent_table.splitlines() if line.startswith("| Protocol ")]
assert len(result_rows) == 4
- succeeded = next(
- line for line in result_rows if "`discovery: succeeded`" in line
- )
+ succeeded = next(line for line in result_rows if "`discovery: succeeded`" in line)
assert "omitted, `false`, or `true`" in succeeded
assert "Ordinary create" in succeeded
assert "legitimately empty" in succeeded
- failed_rows = [
- line
- for line in result_rows
- if line.startswith("| Protocol proved; `discovery: failed` |")
- ]
+ failed_rows = [line for line in result_rows if line.startswith("| Protocol proved; `discovery: failed` |")]
assert len(failed_rows) == 2
rejected = next(line for line in failed_rows if "omitted or `false`" in line)
accepted = next(line for line in failed_rows if "| `true` |" in line)
@@ -623,19 +602,13 @@ def test_source_create_unavailable_inventory_consent_is_explicit_and_total():
assert "`models: []`" in accepted
assert "proved protocol" in accepted
- unproved = next(
- line for line in result_rows if line.startswith("| Protocol not proved")
- )
+ unproved = next(line for line in result_rows if line.startswith("| Protocol not proved"))
assert "omitted, `false`, or `true`" in unproved
assert "no Source is committed" in unproved
assert "cannot authorize" in unproved
- implementation_plan = (
- CONTRACTS.parent / "model-hub-implementation.md"
- ).read_text(encoding="utf-8")
- ac_54 = implementation_plan.split("### AC-54", 1)[1].split(
- "### K4 open contract-gap registry", 1
- )[0]
+ implementation_plan = (CONTRACTS.parent / "model-hub-implementation.md").read_text(encoding="utf-8")
+ ac_54 = implementation_plan.split("### AC-54", 1)[1].split("### K4 open contract-gap registry", 1)[0]
for required in (
"accept_unavailable_inventory",
"K5 round 2",
@@ -664,30 +637,32 @@ def test_per_model_route_put_does_not_consume_stored_source_order():
assert "only server-side post-creation" in source_order_contract
assert "implicitly reads and applies the stored Source order" in source_order_contract
- exact_route_contract = api_contract.split("### Exact Route-chain configuration", 1)[
- 1
- ].split("## Source creation outcome", 1)[0]
+ exact_route_contract = api_contract.split("### Exact Route-chain configuration", 1)[1].split(
+ "## Source creation outcome", 1
+ )[0]
assert "per-model PUT persists the explicit submitted order" in exact_route_contract
assert "never reads `sources.order`" in exact_route_contract
assert "request still carries only explicit `hops`" in exact_route_contract
- section_42 = model_hub_plan.split("### 4.2 Gateway strategy", 1)[1].split(
- "### 4.3 Runtime resolution", 1
- )[0]
- section_46 = model_hub_plan.split(
- "### 4.6 Configured-chain storage and mutation", 1
- )[1].split("### 4.7", 1)[0]
+ section_42 = model_hub_plan.split("### 4.2 Gateway strategy", 1)[1].split("### 4.3 Runtime resolution", 1)[0]
+ section_46 = model_hub_plan.split("### 4.6 Configured-chain storage and mutation", 1)[1].split("### 4.7", 1)[0]
for authority in (section_42, section_46):
assert "server" in authority
assert "per-model" in authority
- assert (
- "does not read `sources.order`" in authority
- or "never reads `sources.order`" in authority
- )
+ assert "does not read `sources.order`" in authority or "never reads `sources.order`" in authority
def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
- validator = Draft7Validator(_schema("guard-refusal.schema.json"))
+ schema = _schema("guard-refusal.schema.json")
+ assert schema["required"] == [
+ "ok",
+ "contract_version",
+ "error",
+ "detail",
+ "would_remove_hops",
+ "would_interrupt",
+ ]
+ validator = Draft7Validator(schema)
hop = {
"backend": "claude",
"menu_model": "claude-opus-4-6",
@@ -705,22 +680,52 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
"ok": False,
"contract_version": 7,
"error": "source_in_route_chain",
+ "detail": "modelHub.errors.source_in_route_chain",
"would_remove_hops": [hop],
"would_interrupt": [],
}
model_refusal = {**route_refusal, "error": "source_model_in_route_chain"}
+ backend_refusal = {**route_refusal, "error": "backend_model_in_route"}
supplier_refusal = {
**route_refusal,
"error": "source_last_supplier",
"would_remove_hops": [],
"would_interrupt": [gap],
}
- for payload in (route_refusal, model_refusal, supplier_refusal):
+ candidate_refusal = {
+ "ok": False,
+ "contract_version": 7,
+ "error": "candidate_suppliers_changed",
+ "detail": "modelHub.errors.candidate_suppliers_changed",
+ "changed": {
+ "claude-sonnet-4-6": [
+ {
+ "source_id": "src_anthkey01",
+ "model_id": "claude-sonnet-4-6",
+ }
+ ]
+ },
+ }
+ for payload in (
+ route_refusal,
+ model_refusal,
+ backend_refusal,
+ supplier_refusal,
+ ):
validator.validate(payload)
+ response_schema = _schema("api-response.schema.json")
+ candidate_schema = copy.deepcopy(response_schema["definitions"]["CandidateSuppliersChangedResponse"])
+ candidate_schema["properties"]["changed"]["additionalProperties"]["items"] = response_schema["definitions"][
+ "ExpectedSupplier"
+ ]
+ candidate_validator = Draft7Validator(candidate_schema)
+ candidate_validator.validate(candidate_refusal)
+
for payload in (
{**route_refusal, "would_remove_hops": [], "would_interrupt": [gap]},
{**model_refusal, "would_remove_hops": [], "would_interrupt": [gap]},
+ {**backend_refusal, "would_remove_hops": [], "would_interrupt": [gap]},
{**supplier_refusal, "would_remove_hops": [hop], "would_interrupt": []},
{**route_refusal, "would_remove_hops": [hop, hop]},
{**supplier_refusal, "would_interrupt": [gap, gap]},
@@ -728,6 +733,14 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
with pytest.raises(ValidationError):
validator.validate(payload)
+ for payload in (
+ {**candidate_refusal, "changed": {}},
+ {key: value for key, value in candidate_refusal.items() if key != "detail"},
+ {**candidate_refusal, "would_remove_hops": []},
+ ):
+ with pytest.raises(ValidationError):
+ candidate_validator.validate(payload)
+
def test_agent_supply_contract_accepts_unmapped_native_alias_selection():
payload = {
@@ -751,9 +764,7 @@ def test_agent_supply_contract_accepts_unmapped_native_alias_selection():
},
"supply_status": "ok",
"menu": None,
- "model_supply": [
- {"model_id": "claude-opus-4-5", "chain_length": 1}
- ],
+ "model_supply": [{"model_id": "claude-opus-4-5", "chain_length": 1}],
"builtin_models": ["claude-opus-4-5"],
"standard_vendors": None,
"named_agents": [],
@@ -837,9 +848,7 @@ def test_every_versioned_object_ends_at_the_terminal_version_the_code_writes():
for path in sorted(CONTRACTS.iterdir()):
if not path.is_file() or path.name.endswith(".schema.json"):
continue
- for value in re.findall(
- r"contract_version[^0-9]{0,12}(\d+)", path.read_text(encoding="utf-8")
- ):
+ for value in re.findall(r"contract_version[^0-9]{0,12}(\d+)", path.read_text(encoding="utf-8")):
stated += 1
assert int(value) == terminal, path.name
assert stated
@@ -915,16 +924,10 @@ def test_v5_mirror_registry_mutation_probes_detect_every_comparable_drift():
def test_d21_live_backoff_reason_consumers_match_authority_individually():
- registry = json.loads(
- (CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8")
- )
- decision = next(
- item for item in registry["decision_tables"] if item["id"] == "D21"
- )
+ registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))
+ decision = next(item for item in registry["decision_tables"] if item["id"] == "D21")
authority_spec = decision["authority"]
- authority = _vocabulary(
- _schema(authority_spec["schema"]), authority_spec["paths"]
- )
+ authority = _vocabulary(_schema(authority_spec["schema"]), authority_spec["paths"])
observed = []
for consumer in decision["consumers"]:
@@ -954,12 +957,8 @@ def test_d21_live_backoff_reason_consumers_match_authority_individually():
assert all(values == authority for values in observed)
mutated_probe = _schema("probe-result.schema.json")
- mutated_probe["properties"]["error"]["enum"].remove(
- "models.source.backoff.connection_failed"
- )
- probe_spec = next(
- item for item in decision["consumers"] if item["kind"] == "schema_vocabulary"
- )
+ mutated_probe["properties"]["error"]["enum"].remove("models.source.backoff.connection_failed")
+ probe_spec = next(item for item in decision["consumers"] if item["kind"] == "schema_vocabulary")
assert (
_vocabulary(
mutated_probe,
@@ -1014,13 +1013,11 @@ def test_permission_denial_contract_has_no_fallback_member():
event_schema = _schema("resolution-event.schema.json")
provenance_schema = _schema("turn-provenance.schema.json")
assert retired_reason not in event_schema["properties"]["reason"]["enum"]
- assert retired_reason not in (
- provenance_schema["properties"]["failed_attempts"]["items"]["properties"]["reason"]["enum"]
- )
- assert all(
- event.get("reason") != retired_reason
- for event in event_schema["examples"]
+ assert (
+ retired_reason
+ not in (provenance_schema["properties"]["failed_attempts"]["items"]["properties"]["reason"]["enum"])
)
+ assert all(event.get("reason") != retired_reason for event in event_schema["examples"])
assert all(
attempt.get("reason") != retired_reason
for record in provenance_schema["examples"]
@@ -1031,27 +1028,17 @@ def test_permission_denial_contract_has_no_fallback_member():
def test_oauth_nonce_explicit_cancel_totality_is_closed():
api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")
model_hub_plan = (CONTRACTS.parent / "model-hub.md").read_text(encoding="utf-8")
- implementation_plan = (
- CONTRACTS.parent / "model-hub-implementation.md"
- ).read_text(encoding="utf-8")
+ implementation_plan = (CONTRACTS.parent / "model-hub-implementation.md").read_text(encoding="utf-8")
- cancel_route = next(
- line
- for line in api_contract.splitlines()
- if "POST `/api/models/oauth/cancel`" in line
- )
+ cancel_route = next(line for line in api_contract.splitlines() if "POST `/api/models/oauth/cancel`" in line)
assert "Cancels and forgets the flow." not in api_contract
assert "committed flow with `client_nonce`" in cancel_route
assert '`state: "cancelled"`' in cancel_route
assert "existing `expires_at`" in cancel_route
assert "flow without a nonce is forgotten" in cancel_route
- api_oauth = api_contract.split("## OAuth completion", 1)[1].split(
- "## Chain and probe", 1
- )[0]
- plan_oauth = model_hub_plan.split(
- "**OAuth-start nonce state machine", 1
- )[1].split("**Protocol observation", 1)[0]
+ api_oauth = api_contract.split("## OAuth completion", 1)[1].split("## Chain and probe", 1)[0]
+ plan_oauth = model_hub_plan.split("**OAuth-start nonce state machine", 1)[1].split("**Protocol observation", 1)[0]
for section in (api_oauth, plan_oauth):
assert section.count("| `oauth_nonce.released` |") == 1
assert section.count("| `oauth_nonce.in_flight` |") == 1
@@ -1059,15 +1046,9 @@ def test_oauth_nonce_explicit_cancel_totality_is_closed():
assert "retained canceled flow" in section
assert "existing `expires_at`" in section
assert 'retained `state: "cancelled"` flow' in section
- assert "none" in next(
- line
- for line in section.splitlines()
- if line.startswith("| `oauth_nonce.committed` |")
- )
+ assert "none" in next(line for line in section.splitlines() if line.startswith("| `oauth_nonce.committed` |"))
- nonce_description = _schema("oauth-flow.schema.json")["properties"][
- "client_nonce"
- ]["description"]
+ nonce_description = _schema("oauth-flow.schema.json")["properties"]["client_nonce"]["description"]
assert "Explicit cancellation retains that committed flow" in nonce_description
assert "starts no provider on a same-tuple retry" in nonce_description
@@ -1096,16 +1077,16 @@ def test_oauth_nonce_explicit_cancel_totality_is_closed():
def test_v5_shape_amendments_reject_the_false_states_they_replace():
api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")
- credential_contract = api_contract.split(
- "## Credential replacement and reauth", 1
- )[1].split("## Source refresh and blocked-source recovery", 1)[0]
+ credential_contract = api_contract.split("## Credential replacement and reauth", 1)[1].split(
+ "## Source refresh and blocked-source recovery", 1
+ )[0]
assert "{source, recovered, interrupted_pairs}" not in credential_contract
assert '"recovered"' not in credential_contract
assert '"interrupted_pairs"' not in credential_contract
assert api_contract.count("| `oauth_terminal.reauth_success` |") == 1
- reauth_contract = api_contract.split(
- "## Credential replacement and reauth", 1
- )[1].split("## Source refresh and blocked-source recovery", 1)[0]
+ reauth_contract = api_contract.split("## Credential replacement and reauth", 1)[1].split(
+ "## Source refresh and blocked-source recovery", 1
+ )[0]
assert "Hub-channel repair does not require this acknowledgement" not in reauth_contract
assert "For both Hub OAuth and\n `native_cli` Sources" in reauth_contract
assert re.search(
@@ -1268,9 +1249,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
ordinary_backoff = next(
copy.deepcopy(example)
for example in chain_schema["examples"]
- if example["chain"]
- and example["chain"][0]["reason"]
- == "models.source.backoff.connection_failed"
+ if example["chain"] and example["chain"][0]["reason"] == "models.source.backoff.connection_failed"
)
for blocker in (
{
@@ -1293,9 +1272,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
chain_validator.validate(mislabeled_waiting)
canceled = next(
- example
- for example in _schema("turn-provenance.schema.json")["examples"]
- if example["outcome"] == "canceled"
+ example for example in _schema("turn-provenance.schema.json")["examples"] if example["outcome"] == "canceled"
)
Draft7Validator(_schema("turn-provenance.schema.json")).validate(canceled)
invented_failure = copy.deepcopy(canceled)
@@ -1316,15 +1293,17 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
"contract_version": 7,
"backend": "claude",
"model_id": "claude-opus-4-6",
- "chain": [{
- "source_id": "src_claudepro1",
- "model_id": "claude-opus-4-6",
- "channel": "native_cli",
- "health": "healthy",
- "runnable": True,
- "reason": None,
- "retry_at": None,
- }],
+ "chain": [
+ {
+ "source_id": "src_claudepro1",
+ "model_id": "claude-opus-4-6",
+ "channel": "native_cli",
+ "health": "healthy",
+ "runnable": True,
+ "reason": None,
+ "retry_at": None,
+ }
+ ],
"current": {"source_id": "src_claudepro1", "model_id": "claude-opus-4-6"},
"supply_state": "ok",
}
@@ -1339,9 +1318,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
with pytest.raises(ValidationError):
chain_validator.validate(invalid_reason)
- model_supply_validator = Draft7Validator(
- supply_schema["properties"]["model_supply"]["items"]
- )
+ model_supply_validator = Draft7Validator(supply_schema["properties"]["model_supply"]["items"])
empty_model_supply = {
"model_id": "claude-opus-4-6",
"chain_length": 0,
@@ -1349,9 +1326,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
}
model_supply_validator.validate(empty_model_supply)
with pytest.raises(ValidationError):
- model_supply_validator.validate(
- {**empty_model_supply, "has_runnable_hop": True}
- )
+ model_supply_validator.validate({**empty_model_supply, "has_runnable_hop": True})
probe_schema = _schema("probe-result.schema.json")
probe_validator = Draft7Validator(probe_schema)
@@ -1377,9 +1352,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
def test_oauth_terminal_materialization_matrix_and_handoffs_are_total():
api_contract = (CONTRACTS / "api.md").read_text(encoding="utf-8")
model_hub_plan = (CONTRACTS.parent / "model-hub.md").read_text(encoding="utf-8")
- implementation_plan = (
- CONTRACTS.parent / "model-hub-implementation.md"
- ).read_text(encoding="utf-8")
+ implementation_plan = (CONTRACTS.parent / "model-hub-implementation.md").read_text(encoding="utf-8")
mirror_registry = _schema("mirror-registry.json")
decisions = (
@@ -1389,30 +1362,22 @@ def test_oauth_terminal_materialization_matrix_and_handoffs_are_total():
"oauth_terminal.materialization_interrupted",
"oauth_terminal.materialization_plain_error",
)
- api_oauth = api_contract.split("## OAuth completion", 1)[1].split(
- "## Chain and probe", 1
+ api_oauth = api_contract.split("## OAuth completion", 1)[1].split("## Chain and probe", 1)[0]
+ plan_oauth = model_hub_plan.split("**OAuth terminal response and materialization-error matrix", 1)[1].split(
+ "**Protocol observation", 1
)[0]
- plan_oauth = model_hub_plan.split(
- "**OAuth terminal response and materialization-error matrix", 1
- )[1].split("**Protocol observation", 1)[0]
for section in (api_oauth, plan_oauth):
for decision in decisions:
assert section.count(f"| `{decision}` |") == 1
reauth_success = next(
- line
- for line in section.splitlines()
- if line.startswith("| `oauth_terminal.reauth_success` |")
+ line for line in section.splitlines() if line.startswith("| `oauth_terminal.reauth_success` |")
)
interrupted_error = next(
- line
- for line in section.splitlines()
- if line.startswith("| `oauth_terminal.materialization_interrupted` |")
+ line for line in section.splitlines() if line.startswith("| `oauth_terminal.materialization_interrupted` |")
)
plain_error = next(
- line
- for line in section.splitlines()
- if line.startswith("| `oauth_terminal.materialization_plain_error` |")
+ line for line in section.splitlines() if line.startswith("| `oauth_terminal.materialization_plain_error` |")
)
assert "may be empty" in reauth_success
assert "present and nonempty" in interrupted_error
@@ -1420,12 +1385,8 @@ def test_oauth_terminal_materialization_matrix_and_handoffs_are_total():
assert "absent" in plain_error
assert "empty placeholder" in plain_error
- d22 = next(
- rule for rule in mirror_registry["decision_tables"] if rule["id"] == "D22"
- )
- assert d22["authority"]["heading"] == (
- "OAuth terminal response and materialization-error matrix"
- )
+ d22 = next(rule for rule in mirror_registry["decision_tables"] if rule["id"] == "D22")
+ assert d22["authority"]["heading"] == ("OAuth terminal response and materialization-error matrix")
assert d22["consumers"] == [
{
"kind": "marker",
@@ -1441,9 +1402,7 @@ def test_oauth_terminal_materialization_matrix_and_handoffs_are_total():
if line.startswith("| **I3 subscription custody and native import**")
)
auth_setup_landing = next(
- line
- for line in implementation_plan.splitlines()
- if line.startswith("| `tests/scenarios/auth_setup/")
+ line for line in implementation_plan.splitlines() if line.startswith("| `tests/scenarios/auth_setup/")
)
for section in (ac_52, i3_lane, auth_setup_landing):
assert "AUTH-SETUP-109" in section
@@ -1519,9 +1478,7 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm
assert serialized_source["last_discovered_at"] == source_example["last_discovered_at"], label
assert source_state_fields == set(serialized_source["state"]), label
assert source_usage_fields == set(serialized_source["usage"]), label
- assert source_model_fields - {"retired"} == set(
- serialized_source["models"][0]
- ), label
+ assert source_model_fields - {"retired"} == set(serialized_source["models"][0]), label
assert serialized_source["models"][0].get("retired", False) is False, label
assert agent_fields == set(serialized_hub["agents"]["claude"]), label
assert agent_sources_fields == set(serialized_hub["agents"]["claude"]["sources"]), label
@@ -1535,6 +1492,30 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm
assert api.config_to_payload(updated)["model_hub"] == api_payload["model_hub"]
+def test_backend_catalog_without_removed_ids_loads_empty_set(tmp_path):
+ payload = api.config_to_payload(
+ default_config(),
+ include_secrets=True,
+ include_internal=True,
+ )
+ fixture = json.loads(
+ Path("tests/fixtures/model_hub/backend_catalog_without_removed_ids.json").read_text(
+ encoding="utf-8"
+ )
+ )
+ payload["model_hub"]["agents"]["codex"] = fixture
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+ original = config_path.read_bytes()
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert config_path.read_bytes() == original
+ agent = loaded.model_hub.agents["codex"]
+ assert agent.removed_model_ids == []
+ assert [model.to_payload() for model in agent.models] == fixture["models"]
+
+
def _legacy_model_hub_payload(current: dict) -> dict:
"""Build the persisted v3.0.9 Model Hub shape from a current fixture."""
@@ -1567,9 +1548,7 @@ def test_config_reload_migrates_v3_model_hub_shape_and_persists_backup(monkeypat
loaded = V2Config.load(config_path=config_path)
assert loaded.load_warnings == ()
- assert set(loaded.model_hub.agents["claude"].routes) == set(
- ModelHubConfig().agents["claude"].routes
- )
+ assert set(loaded.model_hub.agents["claude"].routes) == set(ModelHubConfig().agents["claude"].routes)
persisted = json.loads(config_path.read_text(encoding="utf-8"))
assert set(persisted["model_hub"]) == {"enabled", "sources", "agents"}
assert persisted["model_hub"]["enabled"] is False
@@ -1844,9 +1823,7 @@ def test_config_reload_spells_route_hops_like_the_inventory_they_name(monkeypatc
current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
current["model_hub"]["sources"] = [source]
menu_model, route = next(iter(current["model_hub"]["agents"]["claude"]["routes"].items()))
- route["hops"] = [
- {"source_id": source["id"], "model_id": model["id"]} for model in source["models"]
- ]
+ route["hops"] = [{"source_id": source["id"], "model_id": model["id"]} for model in source["models"]]
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps(current, ensure_ascii=False), encoding="utf-8")
@@ -1883,9 +1860,7 @@ def test_loading_a_persisted_config_yields_one_this_product_can_load_again(monke
current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
current["model_hub"]["sources"] = [source]
menu_model, route = next(iter(current["model_hub"]["agents"]["claude"]["routes"].items()))
- route["hops"] = [
- {"source_id": source["id"], "model_id": spelling} for spelling in (padded.strip(), padded)
- ]
+ route["hops"] = [{"source_id": source["id"], "model_id": spelling} for spelling in (padded.strip(), padded)]
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps(current, ensure_ascii=False), encoding="utf-8")
@@ -2234,9 +2209,7 @@ def test_config_reload_recovers_inner_model_hub_invariant_only(
assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
persisted = json.loads(config_path.read_text(encoding="utf-8"))["model_hub"]
if invalid_invariant == "opencode-identity":
- assert persisted["agents"]["opencode"]["models"][0]["id"] == (
- "invalid-opencode-identity"
- )
+ assert persisted["agents"]["opencode"]["models"][0]["id"] == ("invalid-opencode-identity")
else:
assert persisted["sources"] == [source]
@@ -2245,9 +2218,7 @@ def test_config_reload_allows_empty_target_on_disabled_legacy_mapping(monkeypatc
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
legacy = _legacy_model_hub_payload(payload["model_hub"])
- legacy["agents"]["claude"]["mappings"] = [
- {"builtin_id": "opus", "target_model_id": "", "enabled": False}
- ]
+ legacy["agents"]["claude"]["mappings"] = [{"builtin_id": "opus", "target_model_id": "", "enabled": False}]
payload["model_hub"] = legacy
config_path = tmp_path / "config.json"
config_path.write_text(json.dumps(payload), encoding="utf-8")
@@ -2477,15 +2448,9 @@ def test_config_reload_recovers_runtime_with_the_canonical_default(
"mutate",
[
lambda hub: hub["agents"]["claude"].update({"sources": "invalid"}),
- lambda hub: hub["agents"]["claude"].update(
- {"sources": {"policy": "custom", "order": "invalid"}}
- ),
- lambda hub: hub["agents"]["claude"].update(
- {"sources": {"order": ["src_missing001"]}}
- ),
- lambda hub: hub["agents"]["claude"].update(
- {"sources": {"policy": {}, "order": []}}
- ),
+ lambda hub: hub["agents"]["claude"].update({"sources": {"policy": "custom", "order": "invalid"}}),
+ lambda hub: hub["agents"]["claude"].update({"sources": {"order": ["src_missing001"]}}),
+ lambda hub: hub["agents"]["claude"].update({"sources": {"policy": {}, "order": []}}),
lambda hub: hub.update({"priority_order": {"invalid": True}}),
lambda hub: hub.update({"priority_order": ["src_missing001"]}),
lambda hub: hub.update({"subscription_hub_experimental": "false"}),
@@ -2535,9 +2500,7 @@ def test_config_reload_recovers_runtime_with_the_canonical_default(
}
),
lambda hub: hub["agents"]["claude"].update({"routes": "invalid"}),
- lambda hub: hub["agents"]["claude"].update(
- {"mappings": [{"builtin_id": "opus", "enabled": True}]}
- ),
+ lambda hub: hub["agents"]["claude"].update({"mappings": [{"builtin_id": "opus", "enabled": True}]}),
lambda hub: hub["agents"]["claude"].update(
{
"mappings": [
@@ -2820,12 +2783,8 @@ def test_route_hops_allow_one_source_to_supply_distinct_models():
("src_same0001", "model-a"),
("src_same0001", "model-b"),
]
- source = ModelHubSourceConfig.from_payload(
- _schema("source.schema.json")["examples"][0]
- )
- source.models.append(
- ModelHubModelConfig(id="claude-opus-4-5", provenance="manual")
- )
+ source = ModelHubSourceConfig.from_payload(_schema("source.schema.json")["examples"][0])
+ source.models.append(ModelHubModelConfig(id="claude-opus-4-5", provenance="manual"))
config = ModelHubConfig(sources=[source])
config.agents["claude"].sources.order = [source.id]
config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig.from_payload(
@@ -3005,9 +2964,7 @@ def test_persisted_hub_config_requires_explicit_complete_route_rows():
ModelHubConfig.from_payload(incomplete)
extra = json.loads(json.dumps(payload))
- extra["agents"]["claude"]["routes"]["claude-hidden-model"] = {
- "hops": []
- }
+ extra["agents"]["claude"]["routes"]["claude-hidden-model"] = {"hops": []}
with pytest.raises(ValueError, match="contains non-menu model"):
ModelHubConfig.from_payload(extra)
@@ -3037,24 +2994,18 @@ def test_persisted_hub_config_requires_explicit_complete_route_rows():
ModelHubConfig.from_payload(dynamic)
dormant = json.loads(json.dumps(payload))
- dormant["agents"]["opencode"]["routes"]["openai/dormant-model"] = {
- "hops": []
- }
+ dormant["agents"]["opencode"]["routes"]["openai/dormant-model"] = {"hops": []}
restored = ModelHubConfig.from_payload(dormant)
assert restored.agents["opencode"].models == []
assert "openai/dormant-model" in restored.agents["opencode"].routes
def test_backend_model_modalities_match_the_contract_directions():
- input_pdf = ModelHubBackendModelConfig.from_payload(
- {"id": "custom-model", "input_modalities": ["pdf"]}
- )
+ input_pdf = ModelHubBackendModelConfig.from_payload({"id": "custom-model", "input_modalities": ["pdf"]})
assert input_pdf.input_modalities == ["pdf"]
with pytest.raises(ValueError, match="output_modalities"):
- ModelHubBackendModelConfig.from_payload(
- {"id": "custom-model", "output_modalities": ["pdf"]}
- )
+ ModelHubBackendModelConfig.from_payload({"id": "custom-model", "output_modalities": ["pdf"]})
def test_config_reload_adds_bundled_routes_without_discarding_legacy_models(tmp_path):
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index adf04e429..6fe7354ea 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -2178,6 +2178,89 @@ def test_gateway_models_endpoint_serves_authenticated_backend_catalog(
asyncio.run(exercise())
+def test_runtime_resolution_sees_controller_reconcile_after_remote_catalog_refresh(
+ monkeypatch,
+ tmp_path: Path,
+) -> None:
+ from core.controller import Controller
+ from vibe import backend_model_catalog
+
+ async def exercise() -> None:
+ model_id = "gpt-runtime-refresh"
+ source = _source(
+ "src_refresh001",
+ "Refresh provider",
+ model_id=model_id,
+ )
+ service = _service(tmp_path, sources=[source])
+ for backend in ("claude", "codex"):
+ fixed_agent = service.store.config.agents[backend]
+ fixed_agent.routes = {
+ model.id: ModelHubRouteConfig() for model in fixed_agent.models
+ }
+ agent = service.store.config.agents["codex"]
+ snapshot = {
+ "codex": {
+ "generation": "stable-upstream-generation",
+ "models": [{"id": model.id} for model in agent.models],
+ }
+ }
+ monkeypatch.setattr(
+ service,
+ "_builtin_snapshots",
+ lambda _backends: snapshot,
+ )
+ await service.reconcile_builtin_models(("codex",), notify=False)
+
+ snapshot["codex"]["models"] = [
+ *snapshot["codex"]["models"],
+ {"id": model_id, "display_name": "Runtime refresh"},
+ ]
+ snapshot["codex"]["generation"] = "refreshed-upstream-generation"
+ controller = Controller.__new__(Controller)
+ controller.model_hub_service = service
+ controller._loop = asyncio.get_running_loop()
+ controller._model_hub_snapshot_refresh_pending = threading.Event()
+ controller._model_hub_snapshot_reconcile_task = None
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "_REMOTE_REFRESH_COMPLETED",
+ controller._model_hub_snapshot_refresh_completed,
+ )
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "refresh_remote_catalog_now",
+ lambda _url: {},
+ )
+
+ backend_model_catalog._refresh_remote_catalog_worker()
+ await asyncio.sleep(0)
+ reconcile_task = controller._model_hub_snapshot_reconcile_task
+ if reconcile_task is not None:
+ await reconcile_task
+
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ launch = await router.resolve(
+ "codex",
+ model_id,
+ process_scope="/repo",
+ turn_id="turn_after_catalog_refresh",
+ )
+ finally:
+ await gateway.close()
+
+ assert launch.requested_model == model_id
+ assert launch.target_model == model_id
+ assert launch.source_id == source.id
+ assert model_id in {
+ model.id for model in service.store.config.agents["codex"].models
+ }
+
+ asyncio.run(exercise())
+
+
@pytest.mark.parametrize(
("path", "body", "status", "reason"),
[
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 8b1858563..fc46d3259 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -1214,215 +1214,6 @@ def test_exact_hop_inspection_rejects_wrong_identity_and_empty_route():
assert empty.reason == "route_unconfigured"
-def test_opencode_menu_validation_rejects_noncanonical_identifier(tmp_path):
- service, store, _ = _service(tmp_path, ModelHubConfig())
- with pytest.raises(ModelHubError) as exc:
- asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": []},
- {"view": "featured", "checked": ["gpt-5"]}
- )
- )
- assert exc.value.code == "mapping_target_unavailable"
- assert store.load().agents["opencode"].menu.checked == []
-
-
-def test_opencode_menu_validation_rejects_credential_material(tmp_path):
- service, store, _ = _service(tmp_path, ModelHubConfig())
-
- with pytest.raises(ModelHubError) as exc:
- asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": []},
- {
- "view": "featured",
- "checked": ["custom/sk-test-credential-material"],
- }
- )
- )
-
- assert exc.value.code == "mapping_target_unavailable"
- assert store.load().agents["opencode"].menu.checked == []
-
-
-def test_opencode_menu_rejects_a_new_model_absent_from_current_inventory(tmp_path):
- source = _source("src_opencode01", (), vendor="openai")
- service, store, _ = _service(tmp_path, _config([source]))
-
- with pytest.raises(ModelHubError) as exc:
- asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": []},
- {"view": "featured", "checked": ["openai/removed-model"]}
- )
- )
-
- assert exc.value.code == "mapping_target_unavailable"
- assert exc.value.status == 409
- assert store.load().agents["opencode"].menu.checked == []
- assert "openai/removed-model" not in store.load().agents["opencode"].routes
-
-
-def test_opencode_menu_preserves_an_existing_route_alias_while_adding_inventory(tmp_path):
- source = _source(
- "src_opencode02",
- ("upstream-model", "new-model"),
- vendor="openai",
- )
- config = _config([source])
- opencode = config.agents["opencode"]
- opencode.menu = ModelHubMenuConfig(
- view="featured",
- checked=["openai/menu-model"],
- )
- opencode.models = [ModelHubBackendModelConfig(id="openai/menu-model")]
- opencode.routes["openai/menu-model"] = ModelHubRouteConfig(
- hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),)
- )
- service, store, _ = _service(tmp_path, config)
-
- asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": ["openai/menu-model"]},
- {
- "view": "featured",
- "checked": ["openai/menu-model", "openai/new-model"],
- }
- )
- )
-
- saved = store.load().agents["opencode"]
- assert saved.menu.checked == ["openai/menu-model", "openai/new-model"]
- assert saved.routes["openai/menu-model"].hops == (
- ModelHubRouteHopConfig(source.id, "upstream-model"),
- )
-
-
-def test_opencode_menu_hides_a_model_without_removing_its_route(tmp_path):
- source = _source("src_opencode07", ("upstream-model",), vendor="openai")
- config = _config([source])
- opencode = config.agents["opencode"]
- opencode.menu = ModelHubMenuConfig(
- view="featured",
- checked=["openai/menu-model"],
- )
- opencode.models = [ModelHubBackendModelConfig(id="openai/menu-model")]
- opencode.routes["openai/menu-model"] = ModelHubRouteConfig(
- hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),)
- )
- service, store, _ = _service(tmp_path, config)
-
- asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": ["openai/menu-model"]},
- {"view": "featured", "checked": []},
- )
- )
-
- saved = store.load().agents["opencode"]
- assert saved.menu.checked == []
- assert saved.models == []
- assert saved.routes["openai/menu-model"].hops == (
- ModelHubRouteHopConfig(source.id, "upstream-model"),
- )
-
-
-def test_opencode_menu_adds_an_inventory_model_with_an_empty_route(tmp_path):
- source = _source("src_opencode05", ("upstream-model",), vendor="openai")
- config = _config([source])
- service, store, _ = _service(tmp_path, config)
-
- asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": []},
- {"view": "featured", "checked": ["openai/upstream-model"]},
- )
- )
-
- saved = store.load().agents["opencode"]
- assert saved.menu.checked == ["openai/upstream-model"]
- assert saved.routes["openai/upstream-model"].hops == ()
-
-
-def test_opencode_menu_rejects_a_model_absent_from_inventory(tmp_path):
- source = _source("src_opencode06", (), vendor="openai")
- config = _config([source])
- service, store, _ = _service(tmp_path, config)
-
- with pytest.raises(ModelHubError) as exc:
- asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": []},
- {"view": "featured", "checked": ["openai/menu-model"]},
- )
- )
-
- assert exc.value.code == "mapping_target_unavailable"
- assert exc.value.status == 409
- assert store.load().agents["opencode"].menu.checked == []
-
-
-def test_opencode_menu_applies_local_intent_to_the_latest_saved_menu(tmp_path):
- source = _source(
- "src_opencode03",
- ("model-a", "model-b", "model-c"),
- vendor="openai",
- )
- config = _config([source])
- config.agents["opencode"].menu = ModelHubMenuConfig(
- view="featured",
- checked=["openai/model-a", "openai/model-b"],
- )
- config.agents["opencode"].models = [
- ModelHubBackendModelConfig(id="openai/model-a"),
- ModelHubBackendModelConfig(id="openai/model-b"),
- ]
- config.agents["opencode"].routes.update(
- {
- "openai/model-a": ModelHubRouteConfig(),
- "openai/model-b": ModelHubRouteConfig(),
- }
- )
- service, store, _ = _service(tmp_path, config)
-
- asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": ["openai/model-a"]},
- {
- "view": "featured",
- "checked": ["openai/model-a", "openai/model-c"],
- },
- )
- )
-
- assert store.load().agents["opencode"].menu.checked == [
- "openai/model-a",
- "openai/model-b",
- "openai/model-c",
- ]
-
-
-def test_opencode_menu_does_not_restore_a_concurrently_removed_model(tmp_path):
- source = _source(
- "src_opencode04",
- ("model-a", "model-c"),
- vendor="openai",
- )
- service, store, _ = _service(tmp_path, _config([source]))
-
- asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": ["openai/model-a"]},
- {
- "view": "featured",
- "checked": ["openai/model-a", "openai/model-c"],
- },
- )
- )
-
- assert store.load().agents["opencode"].menu.checked == ["openai/model-c"]
-
-
def test_explicit_opencode_selection_outside_menu_remains_visible(tmp_path):
config = ModelHubConfig()
config.agents["opencode"].mode = "hub"
diff --git a/tests/test_models_dev_catalog.py b/tests/test_models_dev_catalog.py
index e2ef8a588..54c3cb2e3 100644
--- a/tests/test_models_dev_catalog.py
+++ b/tests/test_models_dev_catalog.py
@@ -35,7 +35,10 @@ def _catalog():
"name": "DeepSeek V4",
"reasoning": True,
"reasoning_options": [
- {"type": "effort", "values": ["low", "high", "low"]}
+ {
+ "type": "effort",
+ "values": ["low", "x" * 65, "high", "low"],
+ }
],
"tool_call": True,
"modalities": {
@@ -67,6 +70,7 @@ def test_models_dev_search_normalizes_editable_metadata(monkeypatch, tmp_path):
{
"provider_id": "deepseek",
"provider_name": "DeepSeek",
+ "first_party": True,
"model_id": "deepseek-v4",
"models_dev_id": "deepseek/deepseek-v4",
"display_name": "DeepSeek V4",
@@ -84,6 +88,26 @@ def test_models_dev_search_normalizes_editable_metadata(monkeypatch, tmp_path):
assert cached["catalog"] == _catalog()
+def test_models_dev_search_preserves_validator_accepted_long_names(monkeypatch):
+ model_id = "m" * 80
+ display_name = "Model " + "x" * 80
+ monkeypatch.setattr(
+ models_dev_catalog,
+ "load_models_dev_catalog",
+ lambda: {
+ "provider": {
+ "name": "Provider",
+ "models": {model_id: {"name": display_name}},
+ }
+ },
+ )
+
+ match = models_dev_catalog.search_models_dev(model_id)[0]
+
+ assert match["model_id"] == model_id
+ assert match["display_name"] == display_name
+
+
def test_models_dev_search_uses_fresh_cache_without_network(monkeypatch, tmp_path):
cache_path = tmp_path / "models-dev.json"
monkeypatch.setattr(models_dev_catalog, "_cache_path", lambda: cache_path)
@@ -103,9 +127,7 @@ def test_models_dev_search_uses_fresh_cache_without_network(monkeypatch, tmp_pat
monkeypatch.setattr(models_dev_catalog.urllib.request, "urlopen", unexpected)
- assert models_dev_catalog.search_models_dev("deepseek/deepseek-v4")[0][
- "models_dev_id"
- ] == "deepseek/deepseek-v4"
+ assert models_dev_catalog.search_models_dev("deepseek/deepseek-v4")[0]["models_dev_id"] == "deepseek/deepseek-v4"
def test_models_dev_search_falls_back_to_stale_cache(monkeypatch, tmp_path):
@@ -127,9 +149,7 @@ def test_models_dev_search_falls_back_to_stale_cache(monkeypatch, tmp_path):
monkeypatch.setattr(models_dev_catalog.urllib.request, "urlopen", unavailable)
- assert models_dev_catalog.search_models_dev("DeepSeek V4")[0][
- "context_window"
- ] == 1_048_576
+ assert models_dev_catalog.search_models_dev("DeepSeek V4")[0]["context_window"] == 1_048_576
def test_models_dev_stale_cache_is_scoped_to_its_url(monkeypatch, tmp_path):
@@ -157,3 +177,142 @@ def test_models_dev_stale_cache_is_scoped_to_its_url(monkeypatch, tmp_path):
with pytest.raises(RuntimeError, match="unavailable"):
models_dev_catalog.search_models_dev("deepseek-v4")
+
+
+def test_model_vendor_map_is_versioned_unambiguous_and_ordered():
+ vendor_map = models_dev_catalog.load_model_vendor_map()
+ families = vendor_map["families"]
+ aggregators = vendor_map["aggregators"]
+
+ assert vendor_map["schema_version"] == 1
+ assert families
+ assert all(set(item) == {"prefix", "vendor_id"} and item["prefix"] and item["vendor_id"] for item in families)
+ assert len({item["prefix"] for item in families}) == len(families)
+ assert aggregators
+ assert len(set(aggregators)) == len(aggregators)
+ assert all(isinstance(provider_id, str) and provider_id for provider_id in aggregators)
+
+
+def test_models_dev_deduplicates_by_model_id_and_ranks_first_party_then_match(
+ monkeypatch,
+):
+ catalog = {
+ "openrouter": {
+ "name": "OpenRouter",
+ "models": {
+ "gpt-target": {"name": "Target proxy"},
+ "target": {"name": "Target"},
+ },
+ },
+ "openai": {
+ "name": "OpenAI",
+ "models": {"gpt-target": {"name": "GPT target"}},
+ },
+ "zeta": {
+ "name": "Zeta",
+ "models": {"target": {"name": "Target"}},
+ },
+ }
+ monkeypatch.setattr(
+ models_dev_catalog,
+ "load_models_dev_catalog",
+ lambda: catalog,
+ )
+
+ matches = models_dev_catalog.search_models_dev("target")
+
+ assert [item["model_id"] for item in matches] == ["gpt-target", "target"]
+ assert matches[0]["provider_id"] == "openai"
+ assert matches[0]["first_party"] is True
+ assert matches[1]["provider_id"] == "openrouter"
+ assert matches[1]["first_party"] is False
+
+
+def test_models_dev_openai_o_series_does_not_claim_other_o_families(monkeypatch):
+ catalog = {
+ "openrouter": {
+ "name": "OpenRouter",
+ "models": {
+ "o3-target": {"name": "O3 proxy"},
+ "olmo-target": {"name": "OLMo proxy"},
+ },
+ },
+ "openai": {
+ "name": "OpenAI",
+ "models": {
+ "o3-target": {"name": "O3 target"},
+ "olmo-target": {"name": "OLMo OpenAI copy"},
+ },
+ },
+ }
+ monkeypatch.setattr(
+ models_dev_catalog,
+ "load_models_dev_catalog",
+ lambda: catalog,
+ )
+
+ matches = {
+ item["model_id"]: item for item in models_dev_catalog.search_models_dev("target")
+ }
+
+ assert matches["o3-target"]["provider_id"] == "openai"
+ assert matches["o3-target"]["first_party"] is True
+ assert matches["olmo-target"]["provider_id"] == "openrouter"
+ assert matches["olmo-target"]["first_party"] is False
+
+
+def test_models_dev_normalizes_each_copy_before_ranking_and_deduplication(
+ monkeypatch,
+):
+ catalog = {
+ "openai": {
+ "name": "OpenAI",
+ "models": {
+ "gpt-target": {"name": " "},
+ "gpt-unusable-target": {
+ "name": "Unusable target",
+ "reasoning_options": [
+ {"type": "effort", "values": [" "]}
+ ],
+ },
+ },
+ },
+ "openrouter": {
+ "name": "OpenRouter",
+ "models": {"gpt-target": {"name": "Valid aggregator copy"}},
+ },
+ }
+ monkeypatch.setattr(
+ models_dev_catalog,
+ "load_models_dev_catalog",
+ lambda: catalog,
+ )
+
+ matches = models_dev_catalog.search_models_dev("target")
+
+ assert [item["model_id"] for item in matches] == [
+ "gpt-unusable-target",
+ "gpt-target",
+ ]
+ assert matches[0]["reasoning_efforts"] == []
+ assert matches[1]["provider_id"] == "openrouter"
+ assert matches[1]["first_party"] is False
+
+
+def test_models_dev_caps_matches_at_eight(monkeypatch):
+ catalog = {
+ "unknown": {
+ "name": "Unknown",
+ "models": {f"test-{index:02d}": {"name": f"Test {index:02d}"} for index in range(12)},
+ }
+ }
+ monkeypatch.setattr(
+ models_dev_catalog,
+ "load_models_dev_catalog",
+ lambda: catalog,
+ )
+
+ matches = models_dev_catalog.search_models_dev("test")
+
+ assert len(matches) == models_dev_catalog.MODELS_DEV_MAX_MATCHES == 8
+ assert [item["model_id"] for item in matches] == sorted(item["model_id"] for item in matches)
diff --git a/tests/test_v2_compat_platforms.py b/tests/test_v2_compat_platforms.py
index ac58be464..970744d49 100644
--- a/tests/test_v2_compat_platforms.py
+++ b/tests/test_v2_compat_platforms.py
@@ -187,6 +187,35 @@ def test_config_load_neutralizes_legacy_opencode_turn_timeout_default(
assert loaded.agents.opencode.active_turn_timeout_seconds == 0
+def test_opencode_timeout_only_migration_does_not_rewrite_model_hub_config(
+ monkeypatch, tmp_path
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from core.services.settings import default_config
+ from vibe import api
+
+ payload = api.config_to_payload(
+ default_config(),
+ include_secrets=True,
+ include_internal=True,
+ )
+ payload["agents"]["opencode"]["active_turn_timeout_seconds"] = 90 * 60
+ payload["agents"]["opencode"].pop("legacy_turn_timeout_neutralized", None)
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+ original = config_path.read_bytes()
+
+ for _ in range(2):
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.agents.opencode.active_turn_timeout_seconds == 0
+ assert loaded.agents.opencode.legacy_turn_timeout_neutralized is True
+ assert config_path.read_bytes() == original
+ assert not list(
+ config_path.parent.glob("config.json.bak-model-hub-migration-*")
+ )
+
+
def test_to_app_config_exposes_opencode_provider_and_reasoning_fields() -> None:
config = V2Config(
mode="self_host",
diff --git a/ui/src/components/settings/models/serverCopy.test.ts b/ui/src/components/settings/models/serverCopy.test.ts
index b0b48d544..b01d13330 100644
--- a/ui/src/components/settings/models/serverCopy.test.ts
+++ b/ui/src/components/settings/models/serverCopy.test.ts
@@ -161,6 +161,7 @@ describe('catalogSaveFailureKey', () => {
// service's taxonomy drift apart.
const REFUSALS = [
['backend_model_in_route', 'saveRouted'],
+ ['candidate_suppliers_changed', 'saveSuppliersChanged'],
['backend_model_conflict', 'saveConflict'],
['backend_model_id_prefix', 'saveIdPrefix'],
['backend_model_id_invalid', 'saveIdInvalid'],
diff --git a/ui/src/components/settings/models/serverCopy.ts b/ui/src/components/settings/models/serverCopy.ts
index 7855e1204..917c90450 100644
--- a/ui/src/components/settings/models/serverCopy.ts
+++ b/ui/src/components/settings/models/serverCopy.ts
@@ -111,7 +111,10 @@ export const oauthStartFailureKey = (code: string | undefined): string =>
* otherwise render to the user as a machine string.
*/
const CATALOG_SAVE_FAILURE_COPY: Readonly<Record<string, string>> = {
+ // authority-consumer: catalog.guard.error backend_model_in_route
+ // authority-consumer: candidate.error candidate_suppliers_changed
'modelHub.errors.backend_model_in_route': 'settings.models.gateway.catalog.saveRouted',
+ 'modelHub.errors.candidate_suppliers_changed': 'settings.models.gateway.catalog.saveSuppliersChanged',
'modelHub.errors.backend_model_conflict': 'settings.models.gateway.catalog.saveConflict',
'modelHub.errors.backend_model_id_prefix': 'settings.models.gateway.catalog.saveIdPrefix',
'modelHub.errors.backend_model_id_invalid': 'settings.models.gateway.catalog.saveIdInvalid',
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index e282c7ffa..55ad4b879 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -162,7 +162,7 @@ export type AgentMenu = {
// ── backend-model.schema.json ───────────────────────────────────────────
/** How the row was first created. User edits stay authoritative afterwards,
* which is why this never gates editability — only `locked` does. */
-export type BackendModelOrigin = 'builtin' | 'models_dev' | 'manual';
+export type BackendModelOrigin = 'builtin' | 'provider' | 'models_dev' | 'manual';
export const BACKEND_MODEL_INPUT_MODALITIES = ['text', 'image', 'audio', 'video', 'pdf'] as const;
export type BackendModelInputModality = (typeof BACKEND_MODEL_INPUT_MODALITIES)[number];
/** One member shorter than the input vocabulary: the schema declares no `pdf`
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 8caaf57b0..e6b2810cd 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -967,6 +967,7 @@
"saveFailed": "The model list was not saved. It was re-read from the server; check it and try again.",
"saveNotApplied": "The list was stored, but this backend did not load it, so it is not in use yet. Save again once the backend is back.",
"saveRouted": "A model you removed still has a route. The list was re-read from the server; clear the route first, then remove it.",
+ "saveSuppliersChanged": "The available providers changed. The list was re-read from the server; review the model's providers and save again.",
"saveConflict": "This list changed elsewhere while you were editing. Your changes were replayed onto the newer list; check it and save again.",
"saveIdPrefix": "Claude model IDs must start with claude- or anthropic-. Remove the model and add it again with a valid ID.",
"saveIdInvalid": "A model ID in this list is not valid for this backend. Remove the model and add it again.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index a2af38380..19ceda130 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -967,6 +967,7 @@
"saveFailed": "模型列表未保存,已重新读取服务器上的列表,请确认后重试。",
"saveNotApplied": "列表已存下,但该后端没有加载它,因此尚未生效。等后端恢复后再保存一次。",
"saveRouted": "你移除的模型仍配置了路由。已重新读取服务器上的列表,请先清空该路由再移除。",
+ "saveSuppliersChanged": "可用供应商已发生变化。已重新读取服务器上的列表,请确认模型的供应商后重新保存。",
"saveConflict": "编辑期间该列表在别处发生了变更。你的改动已重放到新列表上,请确认后重新保存。",
"saveIdPrefix": "Claude 模型 ID 必须以 claude- 或 anthropic- 开头。请移除该模型,再用合法的 ID 重新添加。",
"saveIdInvalid": "列表中有模型 ID 不适用于这个后端。请移除该模型后重新添加。",
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 15eb6a588..f45d1f6a4 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -475,9 +475,9 @@ _MEMBER_HTTP_RULES = tuple(
("PUT", r"^/api/models/agents/[^/]+/chain$"),
("GET", r"^/api/models/agents/[^/]+/sources$"),
("PUT", r"^/api/models/agents/[^/]+/sources$"),
+ ("GET", r"^/api/models/agents/[^/]+/models/candidates$"),
("PUT", r"^/api/models/agents/[^/]+/models$"),
("GET", r"^/api/models/catalog/models-dev$"),
- ("PUT", r"^/api/models/agents/opencode/menu$"),
("PATCH", r"^/api/models/agents/[^/]+/mode$"),
("POST", r"^/api/models/agents/[^/]+/chains/reorder$"),
("GET", r"^/api/models/sources$"),
diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.py
index d0438aeab..ce78d7a40 100644
--- a/vibe/backend_model_catalog.py
+++ b/vibe/backend_model_catalog.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import asyncio
import hashlib
import json
+import logging
import os
import threading
import time
@@ -10,15 +11,22 @@ import urllib.error
import urllib.request
from pathlib import Path
from types import MappingProxyType
-from typing import Any, Final, Iterable, Mapping, Sequence
+from typing import Any, Callable, Final, Iterable, Mapping, Sequence
from config import paths
from config.atomic_io import write_atomic
from core.command_runner import run_supervised_command
-from vibe.claude_model_catalog import DEFAULT_CLAUDE_MODEL_ALIASES, load_catalog_models
+from vibe.claude_model_catalog import (
+ DEFAULT_CLAUDE_MODEL_ALIASES,
+ get_catalog_path as get_claude_catalog_path,
+ load_catalog_models,
+)
from vibe.codex_config import get_codex_home
+logger = logging.getLogger(__name__)
+
+
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"
@@ -27,6 +35,7 @@ REMOTE_CATALOG_REVALIDATE_SECONDS = 5 * 60
REMOTE_CATALOG_FAILURE_TTL_SECONDS = 10 * 60
REMOTE_CATALOG_TIMEOUT_SECONDS = 3.0
REMOTE_CATALOG_USER_AGENT = "avibe/backend-model-catalog"
+REMOTE_CATALOG_CACHE_VERSION = 2
CODEX_HUB_CATALOG_TIMEOUT_SECONDS = 15.0
CODEX_HUB_CATALOG_MAX_BYTES = 8 * 1024 * 1024
@@ -98,7 +107,8 @@ _CODEX_CUSTOM_SCAFFOLD_KEYS = (
_REMOTE_LOCK = threading.Lock()
_REMOTE_REFRESH_IN_FLIGHT = False
-_REMOTE_MEMORY_CACHE: dict[str, Any] = {}
+_REMOTE_MEMORY_CACHE: dict[str, dict[str, Any]] = {}
+_REMOTE_REFRESH_COMPLETED: Callable[[], None] | None = None
def get_bundled_catalog_path(repo_root: Path | None = None) -> Path:
@@ -346,16 +356,29 @@ def bundled_catalog_reasoning_efforts_for_model(
return bundled_catalog_reasoning_efforts_by_model().get(model_id)
-def load_cached_remote_catalog(*, schedule_refresh: bool = True) -> dict[str, Any]:
- cached = _cached_remote_payload()
- if schedule_refresh and _remote_cache_stale(cached):
+def load_cached_remote_catalog(
+ *,
+ schedule_refresh: bool = True,
+ source_key: str | None = None,
+) -> dict[str, Any]:
+ current_source_key = source_key or _remote_catalog_source_key(
+ _remote_catalog_url()
+ )
+ cached = _cached_remote_payload(source_key=current_source_key)
+ if schedule_refresh and _remote_cache_stale(
+ cached,
+ source_key=current_source_key,
+ ):
schedule_remote_catalog_refresh()
catalog = cached.get("catalog")
return catalog if isinstance(catalog, dict) else {}
-def remote_catalog_token() -> tuple[float | None, float | None]:
- payload = _cached_remote_payload()
+def remote_catalog_token(
+ *,
+ source_key: str | None = None,
+) -> tuple[float | None, float | None]:
+ payload = _cached_remote_payload(source_key=source_key)
fetched_at = payload.get("fetched_at")
failed_at = payload.get("failed_at")
return (
@@ -364,10 +387,24 @@ def remote_catalog_token() -> tuple[float | None, float | None]:
)
-def remote_catalog_refresh_pending(since: tuple[float | None, float | None]) -> bool:
+def remote_catalog_refresh_pending(
+ since: tuple[float | None, float | None],
+ *,
+ source_key: str | None = None,
+) -> bool:
with _REMOTE_LOCK:
refresh_in_flight = _REMOTE_REFRESH_IN_FLIGHT
- return refresh_in_flight or remote_catalog_token() != since
+ return refresh_in_flight or remote_catalog_token(source_key=source_key) != since
+
+
+def set_remote_catalog_refresh_completed(
+ callback: Callable[[], None] | None,
+) -> None:
+ """Set the controller-owned completion signal for this process."""
+
+ global _REMOTE_REFRESH_COMPLETED
+ with _REMOTE_LOCK:
+ _REMOTE_REFRESH_COMPLETED = callback
def schedule_remote_catalog_refresh() -> bool:
@@ -378,8 +415,11 @@ def schedule_remote_catalog_refresh() -> bool:
return False
_REMOTE_REFRESH_IN_FLIGHT = True
+ request_url = _remote_catalog_url()
+ source_key = _remote_catalog_source_key(request_url)
thread = threading.Thread(
target=_refresh_remote_catalog_worker,
+ args=(request_url, source_key),
name="avibe-model-catalog-refresh",
daemon=True,
)
@@ -388,14 +428,13 @@ def schedule_remote_catalog_refresh() -> bool:
def refresh_remote_catalog_now(url: str | None = None) -> dict[str, Any]:
- 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
+ previous = _cached_remote_payload(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,
+ etag=previous.get("etag"),
+ last_modified=previous.get("last_modified"),
)
now = time.time()
not_modified = catalog is None
@@ -420,7 +459,7 @@ def refresh_remote_catalog_now(url: str | None = None) -> dict[str, Any]:
value = previous.get(key)
if isinstance(value, str) and value:
payload[key] = value
- _write_cached_remote_payload(payload)
+ _write_cached_remote_payload(payload, source_key=source_key)
return catalog
@@ -499,8 +538,12 @@ def backend_model_snapshot(backend: str, *, schedule_refresh: bool = True) -> di
if backend_key not in _SUPPORTED_BACKENDS:
return {"ok": False, "backend": backend_key, "error": f"unsupported backend '{backend}'"}
- refresh_token = remote_catalog_token()
- remote_catalog = load_cached_remote_catalog(schedule_refresh=schedule_refresh)
+ remote_source_key = _remote_catalog_source_key(_remote_catalog_url())
+ refresh_token = remote_catalog_token(source_key=remote_source_key)
+ remote_catalog = load_cached_remote_catalog(
+ schedule_refresh=schedule_refresh,
+ source_key=remote_source_key,
+ )
bundled_catalog = load_bundled_catalog()
if backend_key == "claude":
@@ -529,7 +572,7 @@ def backend_model_snapshot(backend: str, *, schedule_refresh: bool = True) -> di
efforts = entry.get("reasoning_efforts") or default_efforts
reasoning_options[entry["id"]] = _reasoning_option_items(efforts)
- cached_payload = _cached_remote_payload()
+ cached_payload = _cached_remote_payload(source_key=remote_source_key)
notes = []
error = cached_payload.get("error")
if isinstance(error, str) and error:
@@ -545,10 +588,123 @@ def backend_model_snapshot(backend: str, *, schedule_refresh: bool = True) -> di
"source": " + ".join(name for name, entries in sources if entries),
"live": False,
"notes": notes or None,
- "catalog_refresh_pending": remote_catalog_refresh_pending(refresh_token),
+ "catalog_refresh_pending": remote_catalog_refresh_pending(
+ refresh_token,
+ source_key=remote_source_key,
+ ),
}
+def backend_builtin_models(
+ backend: str,
+ *,
+ schedule_refresh: bool = True,
+) -> list[dict[str, Any]]:
+ """Return the backend-owned model snapshot used by Model Hub catalogs."""
+
+ return backend_builtin_snapshot(
+ backend,
+ schedule_refresh=schedule_refresh,
+ )["models"]
+
+
+def backend_builtin_snapshot(
+ backend: str,
+ *,
+ cli_installed: bool = False,
+ schedule_refresh: bool = True,
+) -> dict[str, Any]:
+ """Read every built-in source once and report whether the baseline is complete."""
+
+ backend_key = (backend or "").strip().lower()
+ if backend_key == "opencode":
+ return _versioned_builtin_snapshot(complete=True, models=[])
+ if backend_key not in _SUPPORTED_BACKENDS:
+ return _versioned_builtin_snapshot(complete=False, models=[])
+
+ remote_source_key = _remote_catalog_source_key(_remote_catalog_url())
+ cached_remote = _read_cached_remote_payload(
+ get_cached_catalog_path(),
+ source_key=remote_source_key,
+ )
+ if schedule_refresh and _remote_cache_stale(
+ cached_remote,
+ source_key=remote_source_key,
+ ):
+ schedule_remote_catalog_refresh()
+ remote_catalog = cached_remote.get("catalog")
+ remote_complete = (
+ cached_remote.get("source_key") == remote_source_key
+ and isinstance(remote_catalog, dict)
+ )
+ if not remote_complete:
+ remote_catalog = {}
+
+ bundled_catalog = _read_complete_catalog(get_bundled_catalog_path())
+ bundled_complete = isinstance(bundled_catalog, dict)
+ if not bundled_complete:
+ bundled_catalog = {}
+ if backend_key == "claude":
+ claude_catalog_present = get_claude_catalog_path().is_file()
+ local_models = load_catalog_models()
+ local_complete = not cli_installed or claude_catalog_present
+ sources = _claude_sources(
+ remote_catalog,
+ bundled_catalog,
+ local_models=local_models,
+ )[:-1]
+ blocked: set[str] = set()
+ else:
+ local_catalog, local_catalog_read = _read_codex_models_cache_with_status()
+ local_complete = not cli_installed or local_catalog_read
+ remote_entries = backend_model_entries("codex", remote_catalog)
+ blocked = {
+ entry["id"]
+ for entry in [*local_catalog, *remote_entries]
+ if _model_hidden(entry)
+ }
+ sources = _codex_sources(remote_entries, local_catalog, bundled_catalog)[:-1]
+
+ merged = merge_model_sources(sources, blocked_model_ids=blocked)
+ return _versioned_builtin_snapshot(
+ complete=bundled_complete and remote_complete and local_complete,
+ models=[
+ {
+ "id": entry["id"],
+ "display_name": (
+ entry.get("label")
+ if isinstance(entry.get("label"), str)
+ and entry["label"] != entry["id"]
+ else None
+ ),
+ "reasoning_efforts": list(
+ entry.get("reasoning_efforts")
+ or _DEFAULT_REASONING_EFFORTS[backend_key]
+ ),
+ }
+ for entry in merged
+ if not (backend_key == "claude" and entry["id"] == "default")
+ ],
+ )
+
+
+def _versioned_builtin_snapshot(
+ *,
+ complete: bool,
+ models: list[dict[str, Any]],
+) -> dict[str, Any]:
+ content = {"complete": complete, "models": models}
+ generation = hashlib.sha256(
+ json.dumps(
+ content,
+ ensure_ascii=True,
+ separators=(",", ":"),
+ sort_keys=True,
+ ).encode()
+ ).hexdigest()
+ return {**content, "generation": generation}
+
+
def catalog_reasoning_efforts_for_model(backend: str, model: str | None) -> list[str] | None:
if not model:
return None
@@ -608,11 +764,16 @@ def merge_model_sources(
def _claude_sources(
remote_catalog: dict[str, Any],
bundled_catalog: dict[str, Any],
+ *,
+ local_models: Sequence[str] | None = None,
) -> list[tuple[str, list[dict[str, Any]]]]:
from modules.agents.opencode.utils import format_claude_model_label
legacy_entries = []
- for model in [*load_catalog_models(), *DEFAULT_CLAUDE_MODEL_ALIASES]:
+ for model in [
+ *(local_models if local_models is not None else load_catalog_models()),
+ *DEFAULT_CLAUDE_MODEL_ALIASES,
+ ]:
entry = {
"id": model,
"reasoning_efforts": _legacy_claude_reasoning_efforts(model),
@@ -686,16 +847,20 @@ def _read_claude_settings_models() -> list[dict[str, Any]]:
def _read_codex_models_cache() -> list[dict[str, Any]]:
+ return _read_codex_models_cache_with_status()[0]
+
+
+def _read_codex_models_cache_with_status() -> tuple[list[dict[str, Any]], bool]:
cache_path = get_codex_home() / "models_cache.json"
try:
payload = json.loads(cache_path.read_text(encoding="utf-8"))
except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):
- return []
+ return [], False
raw_models = payload.get("models") if isinstance(payload, dict) else None
if not isinstance(raw_models, list):
- return []
+ return [], False
entries = [_normalize_model_entry(item) for item in raw_models]
- return [entry for entry in entries if entry]
+ return [entry for entry in entries if entry], True
def _read_codex_config_models() -> list[dict[str, Any]]:
@@ -762,19 +927,34 @@ def _ordered_entries(entries: Sequence[dict[str, Any]]) -> list[dict[str, Any]]:
return [entry for _, _, entry in sorted(indexed, key=lambda value: (value[0], value[1]))]
-def _cached_remote_payload() -> dict[str, Any]:
+def _cached_remote_payload(*, source_key: str | None = None) -> dict[str, Any]:
+ current_source_key = source_key or _remote_catalog_source_key(
+ _remote_catalog_url()
+ )
with _REMOTE_LOCK:
- if _REMOTE_MEMORY_CACHE:
- return dict(_REMOTE_MEMORY_CACHE)
+ cached = _REMOTE_MEMORY_CACHE.get(current_source_key)
+ if isinstance(cached, dict):
+ return dict(cached)
- payload = _read_cached_remote_payload(get_cached_catalog_path())
+ payload = _read_cached_remote_payload(
+ get_cached_catalog_path(),
+ source_key=current_source_key,
+ )
with _REMOTE_LOCK:
- _REMOTE_MEMORY_CACHE.clear()
- _REMOTE_MEMORY_CACHE.update(payload)
+ _REMOTE_MEMORY_CACHE[current_source_key] = dict(payload)
return payload
-def _remote_cache_stale(payload: dict[str, Any]) -> bool:
+def _remote_cache_stale(
+ payload: dict[str, Any],
+ *,
+ source_key: str | None = None,
+) -> bool:
+ current_source_key = source_key or _remote_catalog_source_key(
+ _remote_catalog_url()
+ )
+ if payload.get("source_key") != current_source_key:
+ return True
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_at
@@ -788,16 +968,22 @@ def _remote_cache_stale(payload: dict[str, Any]) -> bool:
return time.time() - float(last_success_at) >= REMOTE_CATALOG_REVALIDATE_SECONDS
-def _refresh_remote_catalog_worker() -> None:
+def _refresh_remote_catalog_worker(
+ request_url: str | None = None,
+ source_key: str | None = None,
+) -> None:
global _REMOTE_REFRESH_IN_FLIGHT
+ request_url = request_url or _remote_catalog_url()
+ source_key = source_key or _remote_catalog_source_key(request_url)
try:
- refresh_remote_catalog_now()
+ refresh_remote_catalog_now(request_url)
except Exception as exc:
- previous = _cached_remote_payload()
+ previous = _cached_remote_payload(source_key=source_key)
payload = {
"failed_at": time.time(),
"catalog": previous.get("catalog"),
"error": str(exc),
+ "source_key": source_key,
}
if isinstance(previous.get("fetched_at"), (int, float)):
payload["fetched_at"] = previous["fetched_at"]
@@ -807,13 +993,19 @@ def _refresh_remote_catalog_worker() -> None:
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)
+ _write_cached_remote_payload(payload, source_key=source_key)
finally:
with _REMOTE_LOCK:
_REMOTE_REFRESH_IN_FLIGHT = False
+ completed = _REMOTE_REFRESH_COMPLETED
+ if completed is not None:
+ try:
+ completed()
+ except Exception:
+ logger.warning(
+ "Backend model catalog refresh completion callback failed",
+ exc_info=True,
+ )
def _read_catalog(path: Path) -> dict[str, Any] | None:
@@ -824,15 +1016,29 @@ def _read_catalog(path: Path) -> dict[str, Any] | None:
return _normalize_catalog(payload)
-def _read_cached_remote_payload(path: Path) -> dict[str, Any]:
+def _read_complete_catalog(path: Path) -> dict[str, Any] | None:
try:
payload = json.loads(path.read_text(encoding="utf-8"))
- except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):
- return {}
+ return _normalize_catalog(payload, strict=True)
+ except (
+ FileNotFoundError,
+ OSError,
+ UnicodeError,
+ json.JSONDecodeError,
+ ValueError,
+ ):
+ return None
+
+
+def _normalize_remote_cache_record(
+ payload: object,
+ *,
+ source_key: str,
+) -> dict[str, Any]:
if not isinstance(payload, dict):
return {}
- normalized: dict[str, Any] = {}
+ normalized: dict[str, Any] = {"source_key": source_key}
catalog_valid = False
raw_catalog = payload.get("catalog")
if isinstance(raw_catalog, dict):
@@ -846,7 +1052,7 @@ def _read_cached_remote_payload(path: Path) -> dict[str, Any]:
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"):
+ for key in ("etag", "last_modified"):
value = payload.get(key)
if isinstance(value, str) and value:
normalized[key] = value
@@ -856,11 +1062,75 @@ def _read_cached_remote_payload(path: Path) -> dict[str, Any]:
return normalized
-def _write_cached_remote_payload(payload: dict[str, Any]) -> None:
- write_atomic(get_cached_catalog_path(), json.dumps(payload, indent=2, sort_keys=True) + "\n")
+def _read_remote_cache_file(path: Path) -> dict[str, Any]:
+ try:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ except (FileNotFoundError, OSError, UnicodeError, json.JSONDecodeError):
+ return {}
+ return payload if isinstance(payload, dict) else {}
+
+
+def _read_cached_remote_payload(
+ path: Path,
+ *,
+ source_key: str | None = None,
+) -> dict[str, Any]:
+ current_source_key = source_key or _remote_catalog_source_key(
+ _remote_catalog_url()
+ )
+ payload = _read_remote_cache_file(path)
+ raw_sources = payload.get("sources")
+ if isinstance(raw_sources, dict):
+ raw_record = raw_sources.get(current_source_key)
+ elif payload.get("source_key") == current_source_key:
+ raw_record = payload
+ else:
+ return {}
+ return _normalize_remote_cache_record(
+ raw_record,
+ source_key=current_source_key,
+ )
+
+
+def _write_cached_remote_payload(
+ payload: dict[str, Any],
+ *,
+ source_key: str | None = None,
+) -> None:
+ current_source_key = source_key or (
+ payload.get("source_key")
+ if isinstance(payload.get("source_key"), str) and payload["source_key"]
+ else _remote_catalog_source_key(_remote_catalog_url())
+ )
+ record = _normalize_remote_cache_record(
+ payload,
+ source_key=current_source_key,
+ )
+ stored_record = {
+ key: value for key, value in record.items() if key != "source_key"
+ }
with _REMOTE_LOCK:
- _REMOTE_MEMORY_CACHE.clear()
- _REMOTE_MEMORY_CACHE.update(payload)
+ path = get_cached_catalog_path()
+ previous = _read_remote_cache_file(path)
+ raw_sources = previous.get("sources")
+ if isinstance(raw_sources, dict):
+ stored_sources = dict(raw_sources)
+ else:
+ legacy_source_key = previous.get("source_key")
+ stored_sources = {}
+ if isinstance(legacy_source_key, str) and legacy_source_key:
+ stored_sources[legacy_source_key] = {
+ key: value
+ for key, value in previous.items()
+ if key != "source_key"
+ }
+ stored_sources[current_source_key] = stored_record
+ stored = {
+ "cache_version": REMOTE_CATALOG_CACHE_VERSION,
+ "sources": stored_sources,
+ }
+ write_atomic(path, json.dumps(stored, indent=2, sort_keys=True) + "\n")
+ _REMOTE_MEMORY_CACHE[current_source_key] = record
def _normalize_catalog(payload: object, *, strict: bool = False) -> dict[str, Any]:
diff --git a/vibe/data/model_vendors.json b/vibe/data/model_vendors.json
new file mode 100644
index 000000000..e8296b394
--- /dev/null
+++ b/vibe/data/model_vendors.json
@@ -0,0 +1,19 @@
+{
+ "schema_version": 1,
+ "families": [
+ {"prefix": "codestral-", "vendor_id": "mistral"},
+ {"prefix": "deepseek-", "vendor_id": "deepseek"},
+ {"prefix": "mistral-", "vendor_id": "mistral"},
+ {"prefix": "claude-", "vendor_id": "anthropic"},
+ {"prefix": "gemini-", "vendor_id": "google"},
+ {"prefix": "gpt-", "vendor_id": "openai"},
+ {"prefix": "grok-", "vendor_id": "xai"},
+ {"prefix": "kimi-", "vendor_id": "moonshotai"},
+ {"prefix": "glm-", "vendor_id": "zhipuai"},
+ {"prefix": "qwen", "vendor_id": "alibaba"},
+ {"prefix": "o1", "vendor_id": "openai"},
+ {"prefix": "o3", "vendor_id": "openai"},
+ {"prefix": "o4", "vendor_id": "openai"}
+ ],
+ "aggregators": ["openrouter", "together", "fireworks-ai", "groq", "deepinfra"]
+}
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 7b1095ec8..8166d7068 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -935,6 +935,7 @@
"backend_model_locked": "Claude Code Default and built-in model origins cannot be changed.",
"backend_model_in_route": "Clear this model's route before removing it from the backend model list.",
"backend_model_conflict": "This backend model changed elsewhere. Reload the list and retry.",
+ "candidate_suppliers_changed": "The available suppliers changed. Reload the model choices and confirm again.",
"models_dev_unavailable": "models.dev is unavailable. Enter the model metadata manually or retry later.",
"codex_catalog_unavailable": "Codex could not prepare the local Model Hub catalog. Retry this turn.",
"engine_down": "The local model gateway is unavailable.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 5cd38ded0..e881054b1 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -935,6 +935,7 @@
"backend_model_locked": "不能修改 Claude Code 的 Default 项或内置模型的来源类型。",
"backend_model_in_route": "请先清空该模型的路由,再从 Backend 模型列表中移除。",
"backend_model_conflict": "该 Backend 模型已在其他位置发生变更,请重新加载后再试。",
+ "candidate_suppliers_changed": "可用供应商已发生变化,请刷新模型选项后重新确认。",
"models_dev_unavailable": "models.dev 当前不可用,请手动填写模型参数或稍后重试。",
"codex_catalog_unavailable": "Codex 无法准备本地模型网关目录,请重试本回合。",
"engine_down": "本地模型网关不可用。",
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index 3a58a9d8f..5c45ad451 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -150,6 +150,9 @@ class ModelHubRemoteService:
def get_agent_sources(self, backend: str) -> dict:
return _rpc_sync("get_agent_sources", {"backend": backend})
+ def agent_model_candidates(self, backend: str) -> dict:
+ return _rpc_sync("agent_model_candidates", {"backend": backend})
+
async def set_agent_sources(self, backend: str, sources: object) -> dict:
return await _rpc(
"set_agent_sources",
@@ -170,6 +173,11 @@ class ModelHubRemoteService:
backend: str,
baseline: object,
models: object,
+ *,
+ expected_suppliers: object = None,
+ force: bool = False,
+ confirmed_remove_hops: object = None,
+ confirmed_interruptions: object = None,
) -> dict:
return await _rpc(
"set_agent_models",
@@ -177,6 +185,10 @@ class ModelHubRemoteService:
"backend": backend,
"baseline": baseline,
"models": models,
+ "expected_suppliers": expected_suppliers,
+ "force": force,
+ "would_remove_hops": confirmed_remove_hops,
+ "would_interrupt": confirmed_interruptions,
},
)
@@ -189,12 +201,6 @@ class ModelHubRemoteService:
{"backend": backend, "model_id": model_id, "chain": chain},
)
- async def set_opencode_menu(self, baseline: object, menu: object) -> dict:
- return await _rpc(
- "set_opencode_menu",
- {"baseline": baseline, "menu": menu},
- )
-
async def add_custom_model(self, source_id: object, payload: dict) -> dict:
return await _rpc(
"add_custom_model",
diff --git a/vibe/models_dev_catalog.py b/vibe/models_dev_catalog.py
index a79950545..be049adeb 100644
--- a/vibe/models_dev_catalog.py
+++ b/vibe/models_dev_catalog.py
@@ -9,10 +9,15 @@ import threading
import time
import urllib.error
import urllib.request
+from pathlib import Path
from typing import Any
from config import paths
from config.atomic_io import write_atomic
+from config.v2_config import (
+ normalize_storable_backend_model_text,
+)
+from core.handlers.model_hub.catalog_admission import admissible_backend_model
MODELS_DEV_URL_ENV = "AVIBE_MODELS_DEV_URL"
@@ -20,10 +25,56 @@ DEFAULT_MODELS_DEV_URL = "https://models.dev/api.json"
MODELS_DEV_TIMEOUT_SECONDS = 8.0
MODELS_DEV_CACHE_TTL_SECONDS = 24 * 60 * 60
MODELS_DEV_MAX_BYTES = 16 * 1024 * 1024
-MODELS_DEV_MAX_MATCHES = 20
+MODELS_DEV_MAX_MATCHES = 8
_CACHE_LOCK = threading.Lock()
+def _vendor_map_path() -> Path:
+ return Path(__file__).with_name("data") / "model_vendors.json"
+
+
+def load_model_vendor_map() -> dict[str, Any]:
+ payload = json.loads(_vendor_map_path().read_text(encoding="utf-8"))
+ if (
+ not isinstance(payload, dict)
+ or payload.get("schema_version") != 1
+ or not isinstance(payload.get("families"), list)
+ or not isinstance(payload.get("aggregators"), list)
+ ):
+ raise ValueError("model vendor map is invalid")
+ return payload
+
+
+def _first_party_vendor(
+ model_id: str,
+ vendor_map: dict[str, Any],
+) -> str | None:
+ matches = [
+ item
+ for item in vendor_map["families"]
+ if isinstance(item, dict)
+ and isinstance(item.get("prefix"), str)
+ and isinstance(item.get("vendor_id"), str)
+ and model_id.lower().startswith(item["prefix"])
+ ]
+ if not matches:
+ return None
+ return max(matches, key=lambda item: len(item["prefix"]))["vendor_id"]
+
+
+def _vendor_rank(
+ vendor_id: str,
+ *,
+ first_party_vendor: str | None,
+ aggregators: list[str],
+) -> tuple[int, int, str]:
+ if vendor_id == first_party_vendor:
+ return (0, 0, vendor_id)
+ if vendor_id in aggregators:
+ return (1, aggregators.index(vendor_id), vendor_id)
+ return (2, 0, vendor_id)
+
+
def _cache_path():
return paths.get_state_dir() / "models_dev_catalog.json"
@@ -172,7 +223,7 @@ def _match_score(
return None
-def _reasoning_efforts(model: dict[str, Any]) -> list[str]:
+def _reasoning_efforts(model: dict[str, Any]) -> list[str] | None:
options = model.get("reasoning_options")
if not isinstance(options, list):
return []
@@ -181,13 +232,19 @@ def _reasoning_efforts(model: dict[str, Any]) -> list[str]:
continue
values = option.get("values")
if isinstance(values, list):
- return list(
- dict.fromkeys(
- value
- for value in values
- if isinstance(value, str) and value
+ normalized: list[str] = []
+ for value in values:
+ if not isinstance(value, str):
+ continue
+ effort = normalize_storable_backend_model_text(
+ value,
+ field_name="reasoning_efforts",
)
- )
+ if effort is None:
+ continue
+ if effort not in normalized:
+ normalized.append(effort)
+ return normalized
return []
@@ -213,7 +270,9 @@ def _modalities(model: dict[str, Any], direction: str) -> list[str]:
def search_models_dev(query: str) -> list[dict[str, Any]]:
tokens = _search_tokens(query)
catalog = load_models_dev_catalog()
- matches: list[tuple[int, str, str, dict[str, Any]]] = []
+ vendor_map = load_model_vendor_map()
+ aggregators = vendor_map["aggregators"]
+ candidates: dict[str, list[tuple[int, str, dict[str, Any]]]] = {}
for provider_key, provider in catalog.items():
if not isinstance(provider_key, str) or not isinstance(provider, dict):
continue
@@ -243,6 +302,13 @@ def search_models_dev(query: str) -> list[dict[str, Any]]:
if isinstance(model.get("name"), str)
else model_id
)
+ display_name = normalize_storable_backend_model_text(
+ display_name,
+ field_name="display_name",
+ )
+ reasoning_efforts = _reasoning_efforts(model)
+ if display_name is None or reasoning_efforts is None:
+ continue
score = _match_score(tokens, provider_id, model_id, display_name)
if score is None:
continue
@@ -280,8 +346,63 @@ def search_models_dev(query: str) -> list[dict[str, Any]]:
if isinstance(model.get("reasoning"), bool)
else None
),
- "reasoning_efforts": _reasoning_efforts(model),
+ "reasoning_efforts": reasoning_efforts,
}
- matches.append((score, provider_id, model_id, row))
- matches.sort(key=lambda item: (item[0], item[1], item[2]))
- return [row for _score, _provider, _model, row in matches[:MODELS_DEV_MAX_MATCHES]]
+ admitted = admissible_backend_model(
+ None,
+ row["model_id"],
+ {
+ "origin": "models_dev",
+ "models_dev_id": row["models_dev_id"],
+ "display_name": row["display_name"],
+ "context_window": row["context_window"],
+ "max_output_tokens": row["max_output_tokens"],
+ "input_modalities": row["input_modalities"],
+ "output_modalities": row["output_modalities"],
+ "supports_tools": row["supports_tools"],
+ "supports_reasoning": row["supports_reasoning"],
+ "reasoning_efforts": row["reasoning_efforts"],
+ },
+ )
+ if admitted is None:
+ continue
+ row.update(
+ {
+ "model_id": admitted.id,
+ "models_dev_id": admitted.models_dev_id,
+ "display_name": admitted.display_name,
+ "context_window": admitted.context_window,
+ "max_output_tokens": admitted.max_output_tokens,
+ "input_modalities": admitted.input_modalities,
+ "output_modalities": admitted.output_modalities,
+ "supports_tools": admitted.supports_tools,
+ "supports_reasoning": admitted.supports_reasoning,
+ "reasoning_efforts": admitted.reasoning_efforts,
+ }
+ )
+ candidates.setdefault(admitted.id, []).append((score, provider_id, row))
+
+ matches: list[tuple[bool, int, str, str, dict[str, Any]]] = []
+ for model_id, copies in candidates.items():
+ first_party_vendor = _first_party_vendor(model_id, vendor_map)
+ _score, _vendor_id, row = min(
+ copies,
+ key=lambda item: _vendor_rank(
+ item[1],
+ first_party_vendor=first_party_vendor,
+ aggregators=aggregators,
+ ),
+ )
+ first_party = row["provider_id"] == first_party_vendor
+ row["first_party"] = first_party
+ matches.append(
+ (
+ not first_party,
+ min(item[0] for item in copies),
+ row["display_name"].lower(),
+ model_id,
+ row,
+ )
+ )
+ matches.sort(key=lambda item: item[:-1])
+ return [row for *_, row in matches[:MODELS_DEV_MAX_MATCHES]]
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 37d214576..377d98b8e 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -4676,40 +4676,49 @@ async def model_hub_agent_models_put(backend):
try:
payload = _model_hub_json_object("mapping_target_unavailable")
- agent = await _model_hub_service().set_agent_models(
+ if set(payload) - {
+ "baseline",
+ "models",
+ "expected_suppliers",
+ "force",
+ "would_remove_hops",
+ "would_interrupt",
+ }:
+ raise ModelHubError("mapping_target_unavailable")
+ result = await _model_hub_service().set_agent_models(
backend,
payload.get("baseline"),
payload.get("models"),
+ expected_suppliers=payload.get("expected_suppliers"),
+ force=payload.get("force") is True,
+ confirmed_remove_hops=payload.get("would_remove_hops"),
+ confirmed_interruptions=payload.get("would_interrupt"),
)
- return _model_hub_success(agent=agent)
+ return _model_hub_success(**result)
except ModelHubError as exc:
return _model_hub_error(exc)
[email protected]("/api/models/catalog/models-dev", methods=["GET"])
-def model_hub_models_dev_get():
[email protected]("/api/models/agents/<backend>/models/candidates", methods=["GET"])
+def model_hub_agent_model_candidates_get(backend):
from core.handlers.model_hub import ModelHubError
try:
- matches = _model_hub_service().models_dev_matches(
- request.args.get("query"),
- )
- return _model_hub_success(matches=matches)
+ candidates = _model_hub_service().agent_model_candidates(backend)
+ return _model_hub_success(candidates=candidates)
except ModelHubError as exc:
return _model_hub_error(exc)
[email protected]("/api/models/agents/opencode/menu", methods=["PUT"])
-async def model_hub_opencode_menu_put():
[email protected]("/api/models/catalog/models-dev", methods=["GET"])
+def model_hub_models_dev_get():
from core.handlers.model_hub import ModelHubError
try:
- payload = _model_hub_json_object("mapping_target_unavailable")
- agent = await _model_hub_service().set_opencode_menu(
- payload.get("baseline"),
- payload.get("menu"),
+ matches = _model_hub_service().models_dev_matches(
+ request.args.get("query"),
)
- return _model_hub_success(agent=agent)
+ return _model_hub_success(matches=matches)
except ModelHubError as exc:
return _model_hub_error(exc)