Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): finalize v5 contracts and add-time matching (#1256)
Call White8a7ceccd2da2
diff --git a/config/v2_config.py b/config/v2_config.pyindex 7aebb583a..6edda44cf 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -9,7 +9,7 @@ from dataclasses import dataclass, field, fieldsfrom datetime import datetimefrom pathlib import Pathfrom typing import List, Literal, Mapping, Optional, Union-from urllib.parse import urlsplit, urlunsplit+from urllib.parse import parse_qsl, urlsplit, urlunsplitfrom config import pathsfrom config.platform_registry import (@@ -29,6 +29,20 @@ logger = logging.getLogger(__name__)CONFIG_LOCK = threading.RLock()+_MODEL_HUB_CREDENTIAL_PATTERNS = (+ re.compile(r"(?i)\b(?:sk|rk|pk|sess|token)[-_][a-z0-9_-]{8,}\b"),+ re.compile(+ r"(?i)\b(?:authorization|api[_ -]?key|access[_ -]?token)\s*[:=]\s*"+ r"(?:sk[-_][a-z0-9_-]{8,}|[a-z0-9._~+/=-]{16,})"+ ),+ re.compile(r"(?i)\bbearer\s+[a-z0-9._~+/=-]{8,}"),+)+++def _contains_model_hub_credential_material(value: object) -> bool:+ rendered = json.dumps(value, ensure_ascii=False, sort_keys=True)+ return any(pattern.search(rendered) for pattern in _MODEL_HUB_CREDENTIAL_PATTERNS)+DEFAULT_AGENT_IDLE_TIMEOUT_SECONDS = 600# Harness run staleness sweep (``docs/plans/agent-run-zombie-settlement.md`` §4.4).@@ -104,6 +118,118 @@ MODEL_HUB_BACKENDS = ("claude", "codex", "opencode")MODEL_HUB_LEGACY_CREATED_AT = "1970-01-01T00:00:00Z"+def normalize_model_hub_vendor_id(value: object) -> str:+ """Return the canonical persisted vendor id used by matching-v1."""++ if not isinstance(value, str):+ raise ValueError("Config 'model_hub.sources.vendor' must be a non-empty string")+ vendor = value.strip().lower()+ if (+ not vendor+ or re.fullmatch(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", vendor) is None+ or _contains_model_hub_credential_material(vendor)+ ):+ raise ValueError("Config 'model_hub.sources.vendor' is invalid")+ return vendor+++def canonical_opencode_menu_identity(identifier: object) -> tuple[str, str]:+ """Validate and split one persisted OpenCode ``provider/model`` identity."""++ from core.handlers.model_hub.identifiers import (+ STANDARD_OPENCODE_VENDOR_IDS,+ parse_opencode_model_id,+ )++ if not isinstance(identifier, str) or identifier != identifier.strip():+ raise ValueError("Invalid OpenCode model identifier")+ provider_id, model_id = parse_opencode_model_id(identifier)+ if (+ provider_id not in STANDARD_OPENCODE_VENDOR_IDS+ and provider_id != "custom"+ ) or provider_id != provider_id.strip() or model_id != model_id.strip():+ raise ValueError("Invalid OpenCode model identifier")+ if _contains_model_hub_credential_material(identifier):+ raise ValueError("OpenCode model identifier contains credential material")+ return provider_id, model_id+++def model_hub_fixed_menu_ids(backend: str) -> tuple[str, ...]:+ """Return the bundled fixed-menu ids used by persisted Hub routes."""++ if backend not in {"claude", "codex"}:+ return ()+ from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalog++ return tuple(+ entry["id"]+ for entry in backend_model_entries(backend, load_bundled_catalog())+ )+++def _migrate_fixed_menu_routes_on_load(payload: dict) -> dict:+ """Adapt fixed-menu route keys to the current bundled catalog on reload.++ A changed catalog is a one-time structural migration: newly introduced+ menu ids receive empty routes and removed ids are discarded. Existing hop+ payloads are copied verbatim; matching and placement never run here.+ """++ model_hub = payload.get("model_hub")+ if not isinstance(model_hub, dict):+ return payload+ agents = model_hub.get("agents")+ if not isinstance(agents, dict):+ return payload++ migrated_agents = dict(agents)+ changed = False+ for backend in ("claude", "codex"):+ raw_agent = agents.get(backend)+ if not isinstance(raw_agent, dict):+ continue+ routes = raw_agent.get("routes")+ expected_menu_ids = model_hub_fixed_menu_ids(backend)+ if not isinstance(routes, dict) or not expected_menu_ids:+ continue+ migrated_routes = {+ model_id: routes.get(model_id, {"hops": []})+ for model_id in expected_menu_ids+ }+ if migrated_routes == routes:+ continue+ migrated_agent = dict(raw_agent)+ migrated_agent["routes"] = migrated_routes+ migrated_agents[backend] = migrated_agent+ changed = True++ if not changed:+ return payload+ migrated_model_hub = dict(model_hub)+ migrated_model_hub["agents"] = migrated_agents+ migrated_payload = dict(payload)+ migrated_payload["model_hub"] = migrated_model_hub+ return migrated_payload+++_MODEL_HUB_CREDENTIAL_QUERY_KEYS = {+ "access_token",+ "api_key",+ "apikey",+ "auth",+ "authorization",+ "bearer",+ "credential",+ "key",+ "password",+ "passwd",+ "secret",+ "sig",+ "signature",+ "token",+}++def is_model_hub_enabled(environ: Optional[Mapping[str, str]] = None) -> bool:"""Return the backend-authoritative Model Hub release capability."""@@ -125,6 +251,64 @@ def _validate_optional_datetime(value: object, field_path: str) -> Optional[str]return value+def normalize_model_hub_base_url(+ value: object,+ *,+ append_path: str | None = None,+) -> Optional[str]:+ """Validate a Source URL and optionally append an upstream API path."""++ if value is None:+ return None+ if not isinstance(value, str) or not value.strip():+ raise ValueError("Config 'model_hub.sources.base_url' is invalid")+ try:+ parsed = urlsplit(value.strip())+ hostname = parsed.hostname+ except ValueError as exc:+ raise ValueError("Config 'model_hub.sources.base_url' is invalid") from exc+ if (+ parsed.scheme.lower() not in {"http", "https"}+ or not hostname+ or parsed.username is not None+ or parsed.password is not None+ or parsed.fragment+ ):+ raise ValueError("Config 'model_hub.sources.base_url' is invalid")+ for key, _ in parse_qsl(+ parsed.query,+ keep_blank_values=True,+ ):+ normalized = key.strip().lower().replace("-", "_").replace(".", "_")+ if normalized in _MODEL_HUB_CREDENTIAL_QUERY_KEYS or any(+ marker in normalized+ for marker in (+ "api_key",+ "access_token",+ "auth_token",+ "token",+ "authorization",+ "signature",+ "secret",+ "password",+ "credential",+ )+ ):+ raise ValueError("Config 'model_hub.sources.base_url' is invalid")+ if _contains_model_hub_credential_material(value):+ raise ValueError("Config 'model_hub.sources.base_url' is invalid")+ path = parsed.path.rstrip("/")+ if append_path is not None:+ if not append_path.startswith("/") or append_path.startswith("//"):+ raise ValueError("Model Hub URL path must be relative to the API root")+ path = f"{path}{append_path}"+ return urlunsplit((parsed.scheme.lower(), parsed.netloc, path, parsed.query, ""))+++def _validate_model_hub_base_url(value: object) -> Optional[str]:+ return normalize_model_hub_base_url(value)++def _filter_dataclass_fields(dc_class, payload: dict) -> dict:"""Filter payload to only include fields defined in dataclass."""valid_fields = {f.name for f in fields(dc_class)}@@ -556,12 +740,22 @@ class ModelHubModelConfig:def from_payload(cls, payload: dict) -> "ModelHubModelConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub.sources.models' entries must be objects")+ if set(payload) - {+ "id",+ "display_name",+ "origin",+ "reasoning_efforts",+ "discovered_at",+ }:+ raise ValueError("Config 'model_hub.sources.models' contains unknown fields")model_id = payload.get("id")origin = payload.get("origin")- reasoning_efforts = payload.get("reasoning_efforts", [])+ if "reasoning_efforts" not in payload:+ raise ValueError("Config 'model_hub.sources.models.reasoning_efforts' is required")+ reasoning_efforts = payload["reasoning_efforts"]display_name = payload.get("display_name")discovered_at = payload.get("discovered_at")- if not isinstance(model_id, str) or not model_id:+ if not isinstance(model_id, str) or not model_id or _contains_model_hub_credential_material(model_id):raise ValueError("Config 'model_hub.sources.models.id' must be a non-empty string")if origin not in {"discovered", "manual"}:raise ValueError("Config 'model_hub.sources.models.origin' is invalid")@@ -569,10 +763,18 @@ class ModelHubModelConfig:not isinstance(reasoning_efforts, list)or any(not isinstance(effort, str) or not effort for effort in reasoning_efforts)or len(set(reasoning_efforts)) != len(reasoning_efforts)+ or any(_contains_model_hub_credential_material(effort) for effort in reasoning_efforts)+ ):+ raise ValueError(+ "Config 'model_hub.sources.models.reasoning_efforts' must be a unique credential-free array of strings"+ )+ if display_name is not None and (+ not isinstance(display_name, str)+ or _contains_model_hub_credential_material(display_name)):- raise ValueError("Config 'model_hub.sources.models.reasoning_efforts' must be a unique array of strings")- if display_name is not None and not isinstance(display_name, str):raise ValueError("Config 'model_hub.sources.models.display_name' must be a string or null")+ if origin == "manual" and discovered_at is not None:+ raise ValueError("Config manual model entries cannot carry discovered_at")return cls(id=model_id,provenance=origin,@@ -604,6 +806,8 @@ class ModelHubSourceStateConfig:def from_payload(cls, payload: dict) -> "ModelHubSourceStateConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub.sources.state' must be an object")+ if set(payload) - {"status", "retry_at", "detail_key"}:+ raise ValueError("Config 'model_hub.sources.state' contains unknown fields")status = payload.get("status")retry_at = payload.get("retry_at")detail_key = payload.get("detail_key")@@ -654,6 +858,13 @@ class ModelHubSourceUsageConfig:def from_payload(cls, payload: dict) -> "ModelHubSourceUsageConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub.sources.usage' must be an object")+ if set(payload) - {+ "cycle_used_pct",+ "month_spend_cents",+ "currency",+ "projected_exhaust_at",+ }:+ raise ValueError("Config 'model_hub.sources.usage' contains unknown fields")cycle_used_pct = payload.get("cycle_used_pct")if cycle_used_pct is not None and (isinstance(cycle_used_pct, bool)@@ -703,7 +914,6 @@ class ModelHubSourceConfig:created_at: str = MODEL_HUB_LEGACY_CREATED_ATlast_discovered_at: Optional[str] = Nonebase_url: Optional[str] = None- experimental_consent_at: Optional[str] = Noneusage: Optional[ModelHubSourceUsageConfig] = Nonecredential_ref: Optional[str] = Noneaccount_label: Optional[str] = None@@ -713,6 +923,26 @@ class ModelHubSourceConfig:def from_payload(cls, payload: dict) -> "ModelHubSourceConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub.sources' entries must be objects")+ allowed_fields = {+ "id",+ "created_at",+ "last_discovered_at",+ "kind",+ "vendor",+ "display_name",+ "protocol",+ "base_url",+ "supply_channel",+ "billing",+ "state",+ "usage",+ "models",+ "credential_ref",+ "account_label",+ "masked_credential",+ }+ if set(payload) - allowed_fields:+ raise ValueError("Config 'model_hub.sources' contains unknown fields")source_id = payload.get("id")kind = payload.get("kind")vendor = payload.get("vendor")@@ -724,8 +954,7 @@ class ModelHubSourceConfig:raise ValueError("Config 'model_hub.sources.id' is invalid")if kind not in {"subscription", "api_key"}:raise ValueError("Config 'model_hub.sources.kind' is invalid")- if not isinstance(vendor, str) or not vendor:- raise ValueError("Config 'model_hub.sources.vendor' must be a non-empty string")+ vendor = normalize_model_hub_vendor_id(vendor)if not isinstance(display_name, str) or not display_name or len(display_name) > 64:raise ValueError("Config 'model_hub.sources.display_name' is invalid")if protocol not in {"anthropic", "openai_responses", "openai_chat"}:@@ -737,22 +966,39 @@ class ModelHubSourceConfig:models_payload = payload.get("models")if not isinstance(models_payload, list):raise ValueError("Config 'model_hub.sources.models' must be an array")+ model_ids = [model.get("id") for model in models_payload if isinstance(model, dict)]+ if len(model_ids) != len(models_payload):+ raise ValueError("Config 'model_hub.sources.models' entries must be objects")+ if any(not isinstance(model_id, str) for model_id in model_ids):+ raise ValueError("Config 'model_hub.sources.models.id' must be a non-empty string")+ if len(set(model_ids)) != len(model_ids):+ raise ValueError("Config 'model_hub.sources.models' contains duplicate ids")usage_payload = payload.get("usage")base_url = payload.get("base_url")- consent_at = payload.get("experimental_consent_at")credential_ref = payload.get("credential_ref")account_label = payload.get("account_label")masked_credential = payload.get("masked_credential")created_at = payload.get("created_at")last_discovered_at = payload.get("last_discovered_at")- if base_url is not None and not isinstance(base_url, str):- raise ValueError("Config 'model_hub.sources.base_url' is invalid")+ base_url = _validate_model_hub_base_url(base_url)if credential_ref is not None and not isinstance(credential_ref, str):raise ValueError("Config 'model_hub.sources.credential_ref' is invalid")if account_label is not None and not isinstance(account_label, str):raise ValueError("Config 'model_hub.sources.account_label' is invalid")if masked_credential is not None and not isinstance(masked_credential, str):raise ValueError("Config 'model_hub.sources.masked_credential' is invalid")+ if kind == "subscription" and (base_url is not None or masked_credential is not None):+ raise ValueError("Config subscription Sources cannot carry API-key fields")+ if kind == "api_key" and supply_channel != "hub":+ raise ValueError("Config API-key Sources must use the hub channel")+ if supply_channel == "native_cli" and credential_ref is not None:+ raise ValueError("Config native Sources cannot carry an engine credential ref")+ if supply_channel == "hub" and (not isinstance(credential_ref, str) or not credential_ref):+ raise ValueError("Config hub Sources require an engine credential ref")+ if kind == "api_key" and usage_payload is not None:+ projected_exhaust_at = usage_payload.get("projected_exhaust_at") if isinstance(usage_payload, dict) else None+ if projected_exhaust_at is not None:+ raise ValueError("Config API-key Sources cannot carry projected exhaustion")return cls(id=source_id,kind=kind,@@ -775,10 +1021,6 @@ class ModelHubSourceConfig:"model_hub.sources.last_discovered_at",),base_url=base_url,- experimental_consent_at=_validate_optional_datetime(- consent_at,- "model_hub.sources.experimental_consent_at",- ),usage=ModelHubSourceUsageConfig.from_payload(usage_payload) if usage_payload is not None else None,credential_ref=credential_ref,account_label=account_label,@@ -808,33 +1050,50 @@ class ModelHubSourceConfig:return payload+@dataclass(frozen=True)+class ModelHubRouteHopConfig:+ source_id: str+ model_id: str++ @classmethod+ def from_payload(cls, payload: object) -> "ModelHubRouteHopConfig":+ if not isinstance(payload, dict) or set(payload) != {"source_id", "model_id"}:+ raise ValueError("Config 'model_hub.agents.routes.hops' entries must contain source_id and model_id")+ source_id = payload.get("source_id")+ model_id = payload.get("model_id")+ if not isinstance(source_id, str) or re.fullmatch(r"src_[a-z0-9]{8,}", source_id) is None:+ raise ValueError("Config 'model_hub.agents.routes.hops.source_id' is invalid")+ if (+ not isinstance(model_id, str)+ or not model_id+ or _contains_model_hub_credential_material(model_id)+ ):+ raise ValueError("Config 'model_hub.agents.routes.hops.model_id' is invalid")+ return cls(source_id=source_id, model_id=model_id)++ def to_payload(self) -> dict:+ return {"source_id": self.source_id, "model_id": self.model_id}++@dataclass-class ModelHubMappingConfig:- builtin_id: str- target_model_id: str- enabled: bool+class ModelHubRouteConfig:+ hops: tuple[ModelHubRouteHopConfig, ...] = ()@classmethod- def from_payload(cls, payload: dict) -> "ModelHubMappingConfig":- if not isinstance(payload, dict):- raise ValueError("Config 'model_hub.agents.mappings' entries must be objects")- builtin_id = payload.get("builtin_id")- target_model_id = payload.get("target_model_id")- enabled = payload.get("enabled")- if not isinstance(builtin_id, str) or not builtin_id:- raise ValueError("Config 'model_hub.agents.mappings.builtin_id' is invalid")- if not isinstance(target_model_id, str) or not target_model_id:- raise ValueError("Config 'model_hub.agents.mappings.target_model_id' is invalid")- if not isinstance(enabled, bool):- raise ValueError("Config 'model_hub.agents.mappings.enabled' must be a boolean")- return cls(builtin_id=builtin_id, target_model_id=target_model_id, enabled=enabled)+ def from_payload(cls, payload: object) -> "ModelHubRouteConfig":+ if not isinstance(payload, dict) or set(payload) != {"hops"}:+ raise ValueError("Config 'model_hub.agents.routes' entries must contain hops")+ hops = payload.get("hops")+ if not isinstance(hops, list):+ raise ValueError("Config 'model_hub.agents.routes.hops' must be an array")+ parsed = tuple(ModelHubRouteHopConfig.from_payload(hop) for hop in hops)+ pairs = [(hop.source_id, hop.model_id) for hop in parsed]+ if len(set(pairs)) != len(pairs):+ raise ValueError("Config 'model_hub.agents.routes.hops' must contain unique pairs")+ return cls(hops=parsed)def to_payload(self) -> dict:- return {- "builtin_id": self.builtin_id,- "target_model_id": self.target_model_id,- "enabled": self.enabled,- }+ return {"hops": [hop.to_payload() for hop in self.hops]}@dataclass@@ -846,6 +1105,8 @@ class ModelHubMenuConfig:def from_payload(cls, payload: dict) -> "ModelHubMenuConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub.agents.menu' must be an object")+ if set(payload) - {"view", "checked"}:+ raise ValueError("Config 'model_hub.agents.menu' contains unknown fields")view = payload.get("view")checked = payload.get("checked")if view not in {"featured", "full"}:@@ -854,6 +1115,8 @@ class ModelHubMenuConfig:raise ValueError("Config 'model_hub.agents.menu.checked' must be an array of strings")if len(set(checked)) != len(checked):raise ValueError("Config 'model_hub.agents.menu.checked' must be unique")+ if any(_contains_model_hub_credential_material(item) for item in checked):+ raise ValueError("Config 'model_hub.agents.menu.checked' is invalid")return cls(view=view, checked=list(checked))def to_payload(self) -> dict:@@ -862,27 +1125,23 @@ class ModelHubMenuConfig:@dataclassclass ModelHubAgentSourcesConfig:- policy: Literal["follow", "custom"] = "follow"order: list[str] = field(default_factory=list)@classmethoddef from_payload(cls, payload: dict) -> "ModelHubAgentSourcesConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub.agents.sources' must be an object")- if set(payload) != {"policy", "order"}:- raise ValueError("Config 'model_hub.agents.sources' must contain policy and order")- policy = payload.get("policy")+ if set(payload) != {"order"}:+ raise ValueError("Config 'model_hub.agents.sources' must contain only order")order = payload.get("order")- if policy not in {"follow", "custom"}:- raise ValueError("Config 'model_hub.agents.sources.policy' is invalid")if not isinstance(order, list) or not all(isinstance(item, str) for item in order):raise ValueError("Config 'model_hub.agents.sources.order' must be an array of strings")if len(set(order)) != len(order):raise ValueError("Config 'model_hub.agents.sources.order' must be unique")- return cls(policy=policy, order=list(order))+ return cls(order=list(order))def to_payload(self) -> dict:- return {"policy": self.policy, "order": list(self.order)}+ return {"order": list(self.order)}@dataclass@@ -891,7 +1150,7 @@ class ModelHubAgentSupplyConfig:mode: Literal["hub", "direct"]menu_kind: Literal["fixed", "open"]sources: ModelHubAgentSourcesConfig = field(default_factory=ModelHubAgentSourcesConfig)- mappings: list[ModelHubMappingConfig] = field(default_factory=list)+ routes: dict[str, ModelHubRouteConfig] = field(default_factory=dict)menu: Optional[ModelHubMenuConfig] = None@classmethod@@ -900,12 +1159,19 @@ class ModelHubAgentSupplyConfig:return cls(backend="opencode", mode=mode, menu_kind="open", menu=ModelHubMenuConfig())if backend not in {"claude", "codex"}:raise ValueError(f"Unsupported Model Hub backend: {backend}")- return cls(backend=backend, mode=mode, menu_kind="fixed")+ return cls(+ backend=backend,+ mode=mode,+ menu_kind="fixed",+ routes={model_id: ModelHubRouteConfig() for model_id in model_hub_fixed_menu_ids(backend)},+ )@classmethoddef from_payload(cls, payload: dict, *, expected_backend: Optional[str] = None) -> "ModelHubAgentSupplyConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub.agents' entries must be objects")+ if set(payload) - {"backend", "mode", "menu_kind", "sources", "routes", "menu"}:+ raise ValueError("Config 'model_hub.agents' contains unknown fields")backend = payload.get("backend") or expected_backendmode = payload.get("mode")menu_kind = payload.get("menu_kind")@@ -918,15 +1184,27 @@ class ModelHubAgentSupplyConfig:expected_menu_kind = "open" if backend == "opencode" else "fixed"if menu_kind != expected_menu_kind:raise ValueError("Config 'model_hub.agents.menu_kind' is invalid for backend")- mappings_payload = payload.get("mappings") or []- if not isinstance(mappings_payload, list):- raise ValueError("Config 'model_hub.agents.mappings' must be an array")+ routes_payload = payload.get("routes", {})+ if not isinstance(routes_payload, dict):+ raise ValueError("Config 'model_hub.agents.routes' must be an object")+ if any(not isinstance(model_id, str) or not model_id for model_id in routes_payload):+ raise ValueError("Config 'model_hub.agents.routes' keys must be non-empty strings")menu_payload = payload.get("menu")sources_payload = payload.get("sources")if backend == "opencode" and menu_payload is None:menu_payload = {"view": "featured", "checked": []}if backend != "opencode" and menu_payload is not None:raise ValueError("Config 'model_hub.agents.menu' is only valid for opencode")+ routes = {+ model_id: ModelHubRouteConfig.from_payload(route)+ for model_id, route in routes_payload.items()+ }+ menu = ModelHubMenuConfig.from_payload(menu_payload) if menu_payload is not None else None+ if any(_contains_model_hub_credential_material(model_id) for model_id in routes):+ raise ValueError("Config 'model_hub.agents.routes' contains an invalid model id")+ if backend == "opencode":+ for identifier in (*routes, *(menu.checked if menu else ())):+ canonical_opencode_menu_identity(identifier)return cls(backend=backend,mode=mode,@@ -936,8 +1214,8 @@ class ModelHubAgentSupplyConfig:if sources_payload is not Noneelse ModelHubAgentSourcesConfig()),- mappings=[ModelHubMappingConfig.from_payload(mapping) for mapping in mappings_payload],- menu=ModelHubMenuConfig.from_payload(menu_payload) if menu_payload is not None else None,+ routes=routes,+ menu=menu,)def to_payload(self) -> dict:@@ -946,7 +1224,10 @@ class ModelHubAgentSupplyConfig:"mode": self.mode,"menu_kind": self.menu_kind,"sources": self.sources.to_payload(),- "mappings": [mapping.to_payload() for mapping in self.mappings],+ "routes": {+ model_id: route.to_payload()+ for model_id, route in self.routes.items()+ },"menu": self.menu.to_payload() if self.menu else None,}@@ -959,7 +1240,6 @@ class ModelHubConfig:backend: ModelHubAgentSupplyConfig.default(backend, mode="direct") for backend in MODEL_HUB_BACKENDS})- subscription_hub_experimental: bool = False@staticmethoddef source_eligible_for_backend(@@ -968,8 +1248,10 @@ class ModelHubConfig:) -> bool:if backend not in MODEL_HUB_BACKENDS:return False+ if source.supply_channel == "hub":+ return Trueif source.kind == "api_key":- return source.supply_channel == "hub"+ return Falseexpected_backend = {"anthropic": "claude", "openai": "codex"}.get(source.vendor)return expected_backend == backend@@ -991,49 +1273,80 @@ class ModelHubConfig:]def effective_source_order(self, backend: str) -> list[str]:- sources = self.agents[backend].sources- if sources.policy == "follow":- return self.recommended_source_order(backend)- return list(sources.order)-- def refresh_follow_orders(self) -> None:- for backend in MODEL_HUB_BACKENDS:- sources = self.agents[backend].sources- if sources.policy == "follow":- sources.order = self.recommended_source_order(backend)+ return list(self.agents[backend].sources.order)@classmethoddef from_payload(cls, payload: dict) -> "ModelHubConfig":if not isinstance(payload, dict):raise ValueError("Config 'model_hub' must be an object")+ if set(payload) - {"sources", "agents"}:+ raise ValueError("Config 'model_hub' contains unknown fields")sources_payload = payload.get("sources") or []agents_payload = payload.get("agents") or {}- experimental = payload.get("subscription_hub_experimental", False)if not isinstance(sources_payload, list):raise ValueError("Config 'model_hub.sources' must be an array")if not isinstance(agents_payload, dict):raise ValueError("Config 'model_hub.agents' must be an object")- if not isinstance(experimental, bool):- raise ValueError("Config 'model_hub.subscription_hub_experimental' must be a boolean")+ if set(agents_payload) - set(MODEL_HUB_BACKENDS):+ raise ValueError("Config 'model_hub.agents' contains unknown backends")sources = [ModelHubSourceConfig.from_payload(source) for source in sources_payload]source_ids = [source.id for source in sources]if len(set(source_ids)) != len(source_ids):raise ValueError("Config 'model_hub.sources' contains duplicate ids")- agents = {- backend: ModelHubAgentSupplyConfig.from_payload(- agents_payload.get(backend) or ModelHubAgentSupplyConfig.default(backend, mode="direct").to_payload(),+ for backend in MODEL_HUB_BACKENDS:+ native_sources = [+ source+ for source in sources+ if source.supply_channel == "native_cli"+ and cls.source_eligible_for_backend(source, backend)+ ]+ if len(native_sources) > 1:+ raise ValueError(+ f"Config 'model_hub.sources' contains multiple native sources for '{backend}'"+ )+ agents = {}+ for backend in MODEL_HUB_BACKENDS:+ if backend not in agents_payload:+ raw_agent = ModelHubAgentSupplyConfig.default(backend, mode="direct").to_payload()+ else:+ raw_agent = agents_payload[backend]+ if not isinstance(raw_agent, dict):+ raise ValueError(f"Config 'model_hub.agents.{backend}' must be an object")+ if "routes" not in raw_agent:+ raise ValueError(f"Config 'model_hub.agents.{backend}.routes' is required")+ agents[backend] = ModelHubAgentSupplyConfig.from_payload(+ raw_agent,expected_backend=backend,)- for backend in MODEL_HUB_BACKENDS- }- # Consent and the experimental flag are retired product concepts. Older- # in-memory callers may still carry these private attributes while the- # final serialized Source shape omits them; loading a valid final Source- # must therefore never require a retired stamp.+ expected_menu_ids = (+ model_hub_fixed_menu_ids(backend)+ if backend in {"claude", "codex"}+ else tuple(agents[backend].menu.checked if agents[backend].menu else ())+ )+ missing_route = next(+ (model_id for model_id in expected_menu_ids if model_id not in agents[backend].routes),+ None,+ )+ if missing_route is not None:+ raise ValueError(+ f"Config 'model_hub.agents.{backend}.routes' is missing menu model '{missing_route}'"+ )+ if backend in {"claude", "codex"}:+ extra_route = next(+ (+ model_id+ for model_id in agents[backend].routes+ if model_id not in expected_menu_ids+ ),+ None,+ )+ if extra_route is not None:+ raise ValueError(+ f"Config 'model_hub.agents.{backend}.routes' contains non-menu model '{extra_route}'"+ )config = cls(sources=sources,agents=agents,- subscription_hub_experimental=experimental,)for backend in MODEL_HUB_BACKENDS:configured_sources = agents[backend].sources@@ -1054,16 +1367,23 @@ class ModelHubConfig:f"Config 'model_hub.agents.{backend}.sources.order' contains "f"ineligible or missing source '{invalid_id}'")- if configured_sources.policy == "follow":- recommended = config.recommended_source_order(backend)- configured_sources.order = recommended+ for model_id, route in agents[backend].routes.items():+ for hop in route.hops:+ source = next((item for item in sources if item.id == hop.source_id), None)+ if source is None:+ raise ValueError(+ f"Config 'model_hub.agents.{backend}.routes.{model_id}' references missing source '{hop.source_id}'"+ )+ if not config.source_eligible_for_backend(source, backend):+ raise ValueError(+ f"Config 'model_hub.agents.{backend}.routes.{model_id}' references ineligible source '{hop.source_id}'"+ )return configdef to_payload(self) -> dict:return {"sources": [source.to_payload() for source in self.sources],"agents": {backend: self.agents[backend].to_payload() for backend in MODEL_HUB_BACKENDS},- "subscription_hub_experimental": self.subscription_hub_experimental,}@@ -1237,7 +1557,7 @@ class V2Config:if not path.exists():raise FileNotFoundError(f"Config not found: {path}")payload = json.loads(path.read_text(encoding="utf-8"))- return cls.from_payload(payload)+ return cls.from_payload(_migrate_fixed_menu_routes_on_load(payload))@classmethoddef from_payload(cls, payload: dict) -> "V2Config":diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex aa5bc49ac..8757b91e8 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -14,7 +14,16 @@ from dataclasses import dataclassfrom enum import Enumfrom typing import Any, AsyncIterator, Literal, Mapping, Protocol, Sequence-# authority-consumer: protocol anthropic openai_responses openai_chat+SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")+OBSERVATION_OUTCOMES = (+ "observed",+ "ambiguous",+ "unreachable",+ "authentication_failed",+ "adapter_error",+ "timeout",+)+OBSERVATION_DISCOVERY_OUTCOMES = ("succeeded", "failed", "not_attempted")class EngineHealth(str, Enum):@@ -80,6 +89,157 @@ class RawCallOutcome:source_id: str+class ObservationOutcome(str, Enum):+ OBSERVED = OBSERVATION_OUTCOMES[0]+ AMBIGUOUS = OBSERVATION_OUTCOMES[1]+ UNREACHABLE = OBSERVATION_OUTCOMES[2]+ AUTHENTICATION_FAILED = OBSERVATION_OUTCOMES[3]+ ADAPTER_ERROR = OBSERVATION_OUTCOMES[4]+ TIMEOUT = OBSERVATION_OUTCOMES[5]+++class ObservationDiscovery(str, Enum):+ SUCCEEDED = OBSERVATION_DISCOVERY_OUTCOMES[0]+ FAILED = OBSERVATION_DISCOVERY_OUTCOMES[1]+ NOT_ATTEMPTED = OBSERVATION_DISCOVERY_OUTCOMES[2]+++@dataclass(frozen=True)+class SourceObservation:+ """Response-backed result of an unsaved Source observation."""++ outcome: ObservationOutcome+ reachable: bool | None+ authenticated: bool | None+ protocol: str | None+ discovery: ObservationDiscovery+ model_ids: tuple[str, ...]+++@dataclass(frozen=True)+class ObservationTerminalRule:+ """Complete legal product for one response-backed observation outcome."""++ reachable: frozenset[bool | None]+ authenticated: frozenset[bool | None]+ protocols: frozenset[str | None]+ discoveries: frozenset[ObservationDiscovery]+ models_must_be_empty: bool+++OBSERVATION_TERMINAL_RULES: Mapping[+ ObservationOutcome,+ ObservationTerminalRule,+] = {+ ObservationOutcome.OBSERVED: ObservationTerminalRule(+ reachable=frozenset({True}),+ authenticated=frozenset({True}),+ protocols=frozenset(SOURCE_PROTOCOLS),+ discoveries=frozenset(+ {+ ObservationDiscovery.SUCCEEDED,+ ObservationDiscovery.FAILED,+ }+ ),+ models_must_be_empty=False,+ ),+ ObservationOutcome.AMBIGUOUS: ObservationTerminalRule(+ reachable=frozenset({True}),+ authenticated=frozenset({True, None}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+ ObservationOutcome.UNREACHABLE: ObservationTerminalRule(+ reachable=frozenset({False}),+ authenticated=frozenset({None}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+ ObservationOutcome.AUTHENTICATION_FAILED: ObservationTerminalRule(+ reachable=frozenset({True}),+ authenticated=frozenset({False}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+ ObservationOutcome.ADAPTER_ERROR: ObservationTerminalRule(+ reachable=frozenset({True, None}),+ authenticated=frozenset({None}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+ ObservationOutcome.TIMEOUT: ObservationTerminalRule(+ reachable=frozenset({None}),+ authenticated=frozenset({None}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+}+++def validate_source_observation(observation: object) -> SourceObservation:+ """Validate an adapter result against the sole terminal-product authority."""++ if not isinstance(observation, SourceObservation):+ raise TypeError("invalid SourceObservation")+ if not isinstance(observation.outcome, ObservationOutcome):+ raise ValueError("invalid SourceObservation outcome")+ if not isinstance(observation.discovery, ObservationDiscovery):+ raise ValueError("invalid SourceObservation discovery")+ if observation.reachable is not None and not isinstance(observation.reachable, bool):+ raise ValueError("invalid SourceObservation reachability")+ if observation.authenticated is not None and not isinstance(+ observation.authenticated,+ bool,+ ):+ raise ValueError("invalid SourceObservation authentication")+ if not isinstance(observation.model_ids, tuple) or any(+ not isinstance(model_id, str) or not model_id for model_id in observation.model_ids+ ):+ raise ValueError("invalid SourceObservation inventory")+ if len(set(observation.model_ids)) != len(observation.model_ids):+ raise ValueError("invalid SourceObservation inventory")++ rule = OBSERVATION_TERMINAL_RULES[observation.outcome]+ if (+ observation.reachable not in rule.reachable+ or observation.authenticated not in rule.authenticated+ or observation.protocol not in rule.protocols+ or observation.discovery not in rule.discoveries+ or (rule.models_must_be_empty and observation.model_ids)+ or (observation.discovery is ObservationDiscovery.FAILED and observation.model_ids)+ ):+ raise ValueError("invalid SourceObservation terminal product")+ return observation+++def make_source_observation(+ *,+ outcome: ObservationOutcome,+ reachable: bool | None,+ authenticated: bool | None,+ protocol: str | None,+ discovery: ObservationDiscovery,+ model_ids: Sequence[str],+) -> SourceObservation:+ """Construct an adapter result through the terminal-product authority."""++ return validate_source_observation(+ SourceObservation(+ outcome=outcome,+ reachable=reachable,+ authenticated=authenticated,+ protocol=protocol,+ discovery=discovery,+ model_ids=tuple(model_ids),+ )+ )++class RetainedMaterialDisposition(str, Enum):NONE = "none"FLOW_SOURCE_REF = "flow_source_ref"@@ -186,10 +346,42 @@ class EngineAdapter(Protocol):remains CLI-owned and has no ref on this seam."""...+ async def retarget_api_key_credential(+ self,+ credential_ref: str,+ vendor: str,+ protocol: str,+ base_url: str | None,+ ) -> str:+ """Copy an API-key credential to a fresh ref with a new target.++ The old ref remains valid until L2 commits the Source mutation and+ explicitly revokes it. The secret never crosses this adapter boundary,+ so Base URL replacement can be staged and rolled back transactionally.+ """+ ...++ async def credential_supports_refresh(self, credential_ref: str) -> bool:+ """Return the credential's actual engine-side refresh capability.++ This is a property of the stored credential, not an inference from+ vendor, Source kind, or an HTTP status.+ """+ ...+async def revoke_credential(self, credential_ref: str) -> None:"""Release the stored credential (source deletion / key replacement)."""...+ async def provision_transient_credential(+ self,+ vendor: str,+ secret: str,+ base_url: str | None,+ ) -> str:+ """Provision an unbound credential for an unsaved observation."""+ ...+async def cleanup_orphaned_oauth_material(self, credential_ref: str) -> bool:"""Retry cleanup for an ``orphan_ref`` without exposing a filename.@@ -215,9 +407,22 @@ class EngineAdapter(Protocol):base_url: str | None,credential_ref: str,) -> Sequence[str]:- """PROBE the upstream for supplyable model ids. Works before any- registration (test-and-add flow: provision → discover → persist →- sync); does not require or create a source binding."""+ """Refresh supplyable model ids for a saved Source using its stored protocol."""+ ...++ async def observe_source(+ self,+ vendor: str,+ base_url: str | None,+ credential_ref: str,+ protocol_order: Sequence[str],+ ) -> SourceObservation:+ """Observe connectivity, authentication, protocol, and inventory.++ ``protocol_order`` only orders probes. A returned protocol must be+ proven by a real upstream response; it cannot be inferred from vendor+ metadata, Base URL, or the first candidate.+ """...# --- subscription OAuth (channel-specific ownership) ------------------diff --git a/core/handlers/model_hub/events.py b/core/handlers/model_hub/events.pyindex 098daab0e..475b1a2ce 100644--- a/core/handlers/model_hub/events.py+++ b/core/handlers/model_hub/events.py@@ -11,7 +11,7 @@ import uuidfrom dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Path-from typing import Literal, Optional+from typing import Literal, Optional, TypeAlias, get_argsfrom vibe.i18n import t as i18n_t@@ -21,52 +21,51 @@ EventKind = Literal["cooldown","recover","skip",- "mapping_applied","channel_switch","needs_action","supply_interrupted",]-EventReason = Literal[- "quota_exhausted",- "rate_limited",- "server_error",- "network",- "recovery",- "manual",- "mapping",- "credential_expired",- "credential_revoked",- "balance_exhausted",- "account_banned",- "permission_denied",- "unclassified_error",- "no_enabled_source",- "no_eligible_source",- "model_unsupported",-]+EventReason: TypeAlias = strBillingNote = Literal["entered_metered", "left_metered"]EventSeverity = Literal["info", "action_required"]-_SELF_HEALING_REASONS = {- "quota_exhausted",- "rate_limited",- "server_error",- "network",-}-_NON_SELF_HEALING_REASONS = {- "credential_expired",- "credential_revoked",- "balance_exhausted",- "account_banned",- "unclassified_error",-}-_REQUEST_SCOPED_REASONS = {"permission_denied"}-_STRUCTURAL_REASONS = {- "no_enabled_source",- "no_eligible_source",- "model_unsupported",+ReasonClass = Literal[+ "self_healing",+ "non_self_healing",+ "request_scoped",+ "structural",+ "transition",+]++# The reason vocabulary, validation classes, event rendering, and locale parity+# all consume this table. The JSON schema and locale bundles are checked mirrors.+EVENT_REASON_AUTHORITY: dict[str, ReasonClass] = {+ "quota_exhausted": "self_healing",+ "rate_limited": "self_healing",+ "server_error": "self_healing",+ "network": "self_healing",+ "recovery": "transition",+ "manual": "transition",+ "credential_expired": "non_self_healing",+ "credential_revoked": "non_self_healing",+ "balance_exhausted": "non_self_healing",+ "account_banned": "non_self_healing",+ "permission_denied": "request_scoped",+ "unclassified_error": "non_self_healing",+ "no_enabled_source": "structural",+ "no_eligible_source": "structural",+ "route_unconfigured": "structural",+ "source_missing": "structural",+ "model_unsupported": "structural",+ "native_cli_unavailable": "structural",}++def event_reason_label(reason: str, language: str) -> str:+ if reason not in EVENT_REASON_AUTHORITY:+ raise ValueError("Invalid resolution event reason")+ return i18n_t(f"modelHub.events.reason.{reason}", language)+_CREDENTIAL_PATTERNS = (re.compile(r"(?i)\b(?:sk|rk|pk|sess|token)[-_][a-z0-9_-]{8,}\b"),re.compile(@@ -135,6 +134,17 @@ def build_resolution_event(severity: Optional[EventSeverity] = None,now: Optional[datetime] = None,) -> ResolutionEvent:+ if agent not in get_args(EventAgent):+ raise ValueError("Invalid resolution event agent")+ if kind not in get_args(EventKind):+ raise ValueError("Invalid resolution event kind")+ reason_class = EVENT_REASON_AUTHORITY.get(reason)+ if reason_class is None:+ raise ValueError("Invalid resolution event reason")+ if billing_note is not None and billing_note not in get_args(BillingNote):+ raise ValueError("Invalid resolution event billing note")+ if severity is not None and severity not in get_args(EventSeverity):+ raise ValueError("Invalid resolution event severity")action_required = kind in {"needs_action", "supply_interrupted"}expected_severity: EventSeverity = ("action_required" if action_required else "info"@@ -148,22 +158,22 @@ def build_resolution_event(or model_id is Noneor from_source is not Noneor to_source is not None- or reason not in _STRUCTURAL_REASONS+ or reason_class != "structural"):raise ValueError("Invalid supply_interrupted event")- elif reason in _STRUCTURAL_REASONS:+ elif reason_class == "structural":raise ValueError("Structural reasons require supply_interrupted")- if reason in _REQUEST_SCOPED_REASONS and kind != "switch":+ if reason_class == "request_scoped" and kind != "switch":raise ValueError("Request-scoped reasons require a switch event")if kind == "needs_action" and (from_source is Noneor to_source is not None- or reason not in _NON_SELF_HEALING_REASONS+ or reason_class != "non_self_healing"):raise ValueError("Invalid needs_action event")- if reason in _NON_SELF_HEALING_REASONS and kind in {"cooldown", "recover"}:+ if reason_class == "non_self_healing" and kind in {"cooldown", "recover"}:raise ValueError("Non-self-healing reasons cannot cool down or recover")- if kind == "cooldown" and reason not in _SELF_HEALING_REASONS:+ if kind == "cooldown" and reason_class != "self_healing":raise ValueError("Invalid cooldown reason")if kind == "channel_switch" and (from_source is None@@ -206,7 +216,7 @@ def build_resolution_event(lang,from_source=safe_from or i18n_t("modelHub.events.sourceFallback", lang),to_source=safe_to or i18n_t("modelHub.events.sourceFallback", lang),- reason=i18n_t(f"modelHub.events.reason.{reason}", lang),+ reason=event_reason_label(reason, lang),model=model_id or "",)diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.pyindex 974956fa6..fde63bba6 100644--- a/core/handlers/model_hub/migration.py+++ b/core/handlers/model_hub/migration.py@@ -10,7 +10,7 @@ import refrom dataclasses import dataclass, fieldfrom datetime import datetimefrom pathlib import Path-from typing import Any, Awaitable, Callable, Literal, Optional, Protocol+from typing import Any, Awaitable, Callable, Literal, Optional, Protocol, castfrom config.v2_config import (ModelHubConfig,@@ -19,6 +19,10 @@ from config.v2_config import (ModelHubSourceStateConfig,ModelHubSourceUsageConfig,)+from core.handlers.model_hub.adapter import (+ ObservationDiscovery,+ SourceObservation,+)from core.handlers.model_hub.events import contains_credential_materialfrom vibe.backend_model_catalog import backend_model_entries, load_bundled_catalogfrom vibe.claude_config import read_claude_oauth_signed_in, read_claude_settings_env@@ -72,13 +76,28 @@ class MigrationHost(Protocol):credential_ref: str,) -> None: ...+ async def _require_proven_source_payload(+ self,+ payload: dict[str, object],+ ) -> SourceObservation: ...+def _apply_discovered_models(self,source: ModelHubSourceConfig,manual_models: list[ModelHubModelConfig],discovered: list[str],+ *,+ allow_empty: bool = False,+ ) -> None: ...++ def _apply_source_placement(+ self,+ config: ModelHubConfig,+ source: ModelHubSourceConfig,) -> None: ...+ def _added_to(self, source_id: str) -> list[dict]: ...+@dataclass(frozen=True)class NativeManualModel:@@ -575,6 +594,7 @@ def _new_source(item: NativeMigrationItem,*,now: datetime,+ protocol: Literal["anthropic", "openai_responses", "openai_chat"],validate_base_url: Callable[[object], Optional[str]],) -> ModelHubSourceConfig:keep_native = item.proposed_action == "keep_native"@@ -599,10 +619,9 @@ def _new_source(kind="subscription" if keep_native or controlled else "api_key",vendor=item.vendor,display_name=item.display_name,- protocol=item.protocol,+ protocol=protocol,base_url=validate_base_url(item.base_url),supply_channel="native_cli" if keep_native else "hub",- experimental_consent_at=discovered_at if controlled else None,billing="monthly" if keep_native or controlled else "metered",state=ModelHubSourceStateConfig(status="standby"),usage=ModelHubSourceUsageConfig(),@@ -621,7 +640,7 @@ async def apply_native_migration(*,mask_credential: Callable[[str], str],validate_base_url: Callable[[object], Optional[str]],-) -> int:+) -> tuple[int, list[dict]]:"""Provision, probe, and atomically persist a selected migration batch."""if (@@ -631,7 +650,7 @@ async def apply_native_migration():raise MigrationConflictErrorif not item_ids:- return 0+ return 0, []async with host._mutation_lock:previous = host.store.load()@@ -660,18 +679,39 @@ async def apply_native_migration(persisted = Falsetry:for item in selected:+ protocol = item.protocol+ observation: SourceObservation | None = None+ if item.proposed_action == "import":+ if not item.secret:+ raise MigrationConflictError+ observation = await host._require_proven_source_payload(+ {+ "vendor": item.vendor,+ "base_url": validate_base_url(item.base_url),+ "key": item.secret,+ }+ )+ protocol = cast(+ Literal[+ "anthropic",+ "openai_responses",+ "openai_chat",+ ],+ observation.protocol,+ )source = _new_source(item,now=host.now(),+ protocol=protocol,validate_base_url=validate_base_url,)if item.proposed_action == "import":- if not item.secret:- raise MigrationConflictError+ assert item.secret is not None+ assert observation is not Nonecredential_ref = await host._engine_call(host.adapter.provision_credential(item.vendor,- item.protocol,+ source.protocol,item.secret,source.base_url,)@@ -679,16 +719,6 @@ async def apply_native_migration(provisioned.append((source.id, credential_ref))source.credential_ref = credential_refsource.masked_credential = mask_credential(item.secret)- discovered = list(- await host._engine_call(- host.adapter.discover_models(- item.vendor,- item.protocol,- source.base_url,- credential_ref,- )- )- )manual_models = [ModelHubModelConfig(id=model.id,@@ -697,12 +727,30 @@ async def apply_native_migration()for model in item.manual_models]- host._apply_discovered_models(source, manual_models, discovered)+ if observation.discovery is ObservationDiscovery.SUCCEEDED:+ host._apply_discovered_models(+ source,+ manual_models,+ list(observation.model_ids),+ allow_empty=True,+ )+ else:+ source.models = manual_models+ source.state = ModelHubSourceStateConfig(+ status="error",+ detail_key="models.source.error.unclassified",+ )updated.sources.append(source)+ host._apply_source_placement(updated, source)await host._commit_synced(previous, updated)persisted = True- return len(selected)+ added_to = [+ position+ for item in selected+ for position in host._added_to(item.source_id)+ ]+ return len(selected), added_tofinally:if not persisted:for source_id, credential_ref in reversed(provisioned):diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 224675ae0..2912a6cf9 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -34,7 +34,6 @@ class AttemptIdentity:source_id: strresolved_model_id: strchannel: SupplyChannel- via_mapping: booldef payload(self) -> dict:return {@@ -57,7 +56,6 @@ class TurnTrace:model_supply_state: Optional[SupplyState] = Nonegateway_source_id: Optional[str] = Nonegateway_model_id: Optional[str] = None- gateway_via_mapping: bool = Falseambiguous: bool = False@@ -440,7 +438,6 @@ class TurnCorrelationRegistry:returntrace.gateway_source_id = source_idtrace.gateway_model_id = resolved_model_id- trace.gateway_via_mapping = via_mappingdef gateway_requested_model(self, turn_id: str) -> Optional[str]:with self._lock:@@ -483,7 +480,6 @@ class TurnCorrelationRegistry:source_id=trace.gateway_source_id,resolved_model_id=trace.gateway_model_id,channel="hub",- via_mapping=trace.gateway_via_mapping,)return turn_id@@ -520,7 +516,6 @@ class TurnCorrelationRegistry:source_id=trace.gateway_source_id,resolved_model_id=trace.gateway_model_id,channel="hub",- via_mapping=trace.gateway_via_mapping,)if identity is None or identity.channel != "hub":return@@ -564,7 +559,6 @@ class TurnCorrelationRegistry:source_id=source_id,resolved_model_id=resolved_model_id,channel="native_cli",- via_mapping=via_mapping,)def mark_no_candidate(@@ -625,15 +619,10 @@ class TurnCorrelationRegistry:trace = self._traces.get(turn_id)if trace is None:return- observed_via_mapping = via_mapping or (- trace.gateway_via_mapping- and trace.gateway_model_id == resolved_model_id- )trace.pending_attempt = AttemptIdentity(source_id=source_id,resolved_model_id=resolved_model_id,channel=channel,- via_mapping=observed_via_mapping,)def fail_native_attempt(diff --git a/core/handlers/model_hub/request.py b/core/handlers/model_hub/request.pyindex 0fe20e4c2..ff9816ecb 100644--- a/core/handlers/model_hub/request.py+++ b/core/handlers/model_hub/request.py@@ -1,4 +1,4 @@-"""Request metadata carried through the frozen EngineAdapter mapping surface."""+"""Request metadata carried through the frozen EngineAdapter surface."""from __future__ import annotationsdiff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.pyindex 615ea9acd..f5d2f2cfc 100644--- a/core/handlers/model_hub/resolver.py+++ b/core/handlers/model_hub/resolver.py@@ -1,4 +1,4 @@-"""Pure Model Hub turn resolution shared by runtime and API projections."""+"""Pure Model Hub resolution over the persisted per-model route."""from __future__ import annotations@@ -7,29 +7,45 @@ from dataclasses import dataclass, replacefrom datetime import datetimefrom typing import Literal-from config.v2_config import ModelHubConfig, ModelHubSourceConfig--from .identifiers import opencode_provider_id, parse_opencode_model_id+from config.v2_config import (+ MODEL_HUB_BACKENDS,+ ModelHubConfig,+ ModelHubRouteHopConfig,+ ModelHubSourceConfig,+ canonical_opencode_menu_identity,+)+from core.handlers.model_hub.identifiers import (+ opencode_model_id,+)BackendName = Literal["claude", "codex", "opencode"]ResolutionChannel = Literal["direct", "native_cli", "hub", "unavailable"]SupplyStatus = Literal["ok", "degraded", "waiting", "interrupted"]-_NATIVE_VENDOR_BY_BACKEND: dict[BackendName, str] = {- "claude": "anthropic",- "codex": "openai",-}-_CLAUDE_FAMILY_ALIASES = {- "opus": "opus",- "opus[1m]": "opus",- "sonnet": "sonnet",- "sonnet[1m]": "sonnet",- "haiku": "haiku",-}-_CLAUDE_MODEL_ID = re.compile(- r"^claude-(?P<family>opus|sonnet|haiku|fable)-(?P<version>\d+(?:-\d+)*?)(?:-(?P<date>\d{8}))?$"-)++@dataclass(frozen=True)+class ExactHopInspection:+ """Canonical identity and live eligibility for one persisted Route hop."""++ backend: BackendName+ menu_model: str+ source_id: str | None+ model_id: str | None+ menu_provider_id: str | None+ menu_model_id: str+ source: ModelHubSourceConfig | None+ configuration_eligible: bool+ inventory_member: bool+ supply_eligible: bool+ runnable: bool+ structural_blocker: bool+ reason: str | None+ retry_at: str | None++ @property+ def identity(self) -> tuple[BackendName, str, str | None, str | None]:+ return self.backend, self.menu_model, self.source_id, self.model_id@dataclass(frozen=True)@@ -41,109 +57,38 @@ class ModelHubTurnResolution:source: ModelHubSourceConfig | Nonematching_sources: tuple[ModelHubSourceConfig, ...] = ()candidates: tuple[ModelHubSourceConfig, ...] = ()+ candidate_hops: tuple[ExactHopInspection, ...] = ()+ projectable_hops: tuple[ExactHopInspection, ...] = ()source_model_ids: tuple[tuple[str, str], ...] = ()+ inspected_hops: tuple[ExactHopInspection, ...] = ()+ unsupported_source_ids: tuple[str, ...] = ()+ route_unconfigured: bool = False+ route_reason: str | None = None+ menu_provider_id: str | None = None+ menu_model_id: str | None = Noneprovider: str | None = None- mapping_applied: bool = Falserecoverable_source_ids: tuple[str, ...] = ()supply_status: SupplyStatus | None = None- def model_for_source(self, source: ModelHubSourceConfig | str) -> str | None:- source_id = source if isinstance(source, str) else source.id+ @property+ def structural_blocker_reason(self) -> str | None:+ if self.route_reason == "route_unconfigured":+ return self.route_reasonreturn next((- model_id- for candidate_source_id, model_id in self.source_model_ids- if candidate_source_id == source_id+ inspection.reason+ for inspection in self.inspected_hops+ if inspection.structural_blocker),None,)-def _parsed_claude_model_id(- model_id: str,-) -> tuple[str, tuple[int, ...], int | None] | None:- match = _CLAUDE_MODEL_ID.fullmatch(model_id)- if match is None:- return None- return (- match.group("family"),- tuple(int(part) for part in match.group("version").split("-")),- int(match.group("date")) if match.group("date") else None,- )---def _native_claude_alias(- requested_model: str,- source: ModelHubSourceConfig,-) -> str | None:- family = _CLAUDE_FAMILY_ALIASES.get(requested_model)- requested_version: tuple[int, ...] | None = None- if family is None:- parsed_request = _parsed_claude_model_id(requested_model)- if parsed_request is None:- return None- family, requested_version, requested_date = parsed_request- if requested_date is not None:- return None-- matches: list[tuple[tuple[int, ...], int, str]] = []- for model in source.models:- if model.provenance != "discovered":- continue- parsed = _parsed_claude_model_id(model.id)- if parsed is None:- continue- candidate_family, candidate_version, candidate_date = parsed- if candidate_family != family:- continue- if requested_version is not None and candidate_version != requested_version:- continue- matches.append((candidate_version, candidate_date or 0, model.id))- return max(matches)[2] if matches else None---def _native_alias_for_source(- backend: BackendName,- requested_model: str,- source: ModelHubSourceConfig,-) -> str | None:- if source.vendor != _NATIVE_VENDOR_BY_BACKEND.get(backend):- return None- if backend == "claude":- return _native_claude_alias(requested_model, source)- return None---def effective_model_for_source(- *,- backend: BackendName,- requested_model: str,- target_model: str,- source: ModelHubSourceConfig,- explicit_mapping: bool,-) -> str | None:- """Return the upstream id this source can actually supply for one menu id."""-- if not explicit_mapping:- if source.supply_channel == "native_cli" and any(- model.id == requested_model for model in source.models- ):- return requested_model- native_alias = _native_alias_for_source(- backend,- requested_model,- source,- )- if native_alias is not None:- return native_alias- if any(model.id == target_model for model in source.models):- return target_model- return None--def allowed_origins(source: ModelHubSourceConfig) -> tuple[str, ...]:if source.kind == "api_key":return ()+ if source.supply_channel == "hub":+ return tuple(MODEL_HUB_BACKENDS)if source.vendor == "anthropic":return ("claude",)if source.vendor == "openai":@@ -169,8 +114,6 @@ def source_after_cooldown_recovery(source: ModelHubSourceConfig,now: datetime | None,) -> ModelHubSourceConfig:- """Project the source state used by the next turn after retry recovery."""-if not source_retry_ready(source, now):return sourcereturn replace(@@ -189,7 +132,10 @@ def source_runnable(*,now: datetime | None,unavailable_source_ids: frozenset[str] = frozenset(),+ model_supported: bool = True,) -> bool:+ if not model_supported:+ return Falseif source.id in unavailable_source_ids:return Falseif source.state.status in {"active", "standby"}:@@ -197,40 +143,11 @@ def source_runnable(return source_retry_ready(source, now)-def _supply_status(- matching_sources: tuple[ModelHubSourceConfig, ...],- candidates: tuple[ModelHubSourceConfig, ...],- *,- now: datetime | None,- unavailable_source_ids: frozenset[str],-) -> SupplyStatus:- if not matching_sources:- return "interrupted"- if candidates:- all_runnable = all(- source_runnable(- source,- now=now,- unavailable_source_ids=unavailable_source_ids,- )- for source in matching_sources- )- return "ok" if candidates[0].id == matching_sources[0].id and all_runnable else "degraded"- if all(- source.id not in unavailable_source_ids- and source.state.status == "cooldown"- and not source_retry_ready(source, now)- for source in matching_sources- ):- return "waiting"- return "interrupted"--def normalize_opencode_requested_model(requested_model: str,checked_identifiers: tuple[str, ...],) -> str | None:- """Match a full or uniquely bare OpenCode model to its checked identifier."""+ """Normalize a bare OpenCode selection to one exact checked menu id."""candidate = str(requested_model or "").strip()if not candidate:@@ -241,6 +158,209 @@ def normalize_opencode_requested_model(return matches[0] if len(matches) == 1 else None+_CLAUDE_FAMILY_ALIASES = {+ "opus": "opus",+ "opus[1m]": "opus",+ "sonnet": "sonnet",+ "sonnet[1m]": "sonnet",+ "haiku": "haiku",+}+_CLAUDE_MODEL_ID = re.compile(+ r"^claude-(?P<family>opus|sonnet|haiku|fable)-(?P<version>\d+(?:-\d+)*?)(?:-(?P<date>\d{8}))?$"+)+++def _parsed_claude_model_id(model_id: str) -> tuple[str, tuple[int, ...], int | None] | None:+ match = _CLAUDE_MODEL_ID.fullmatch(model_id)+ if match is None:+ return None+ return (+ match.group("family"),+ tuple(int(part) for part in match.group("version").split("-")),+ int(match.group("date")) if match.group("date") else None,+ )+++def matching_v1_model_id(+ *,+ backend: BackendName,+ requested_model: str,+ source: ModelHubSourceConfig,+ checked_models: tuple[str, ...] = (),+) -> 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"+ )++ if backend == "opencode":+ requested_model = normalize_opencode_requested_model(+ requested_model,+ checked_models,+ ) or ""+ if not requested_model:+ return None+ exact = [+ model.id+ for model in observed_models+ if opencode_model_id(source.vendor, model.id) == requested_model+ ]+ return exact[0] if len(exact) == 1 else None++ if (+ backend == "claude"+ and source.vendor == "anthropic"+ and source.supply_channel == "native_cli"+ ):+ family = _CLAUDE_FAMILY_ALIASES.get(requested_model)+ requested_version: tuple[int, ...] | None = None+ parsed_request = _parsed_claude_model_id(requested_model)+ if family is None and parsed_request is not None:+ family, requested_version, requested_date = parsed_request+ if requested_date is not None:+ return next(+ (model.id for model in observed_models if model.id == requested_model),+ None,+ )+ if family is not None:+ matches: list[tuple[tuple[int, ...], int, str]] = []+ for model in observed_models:+ parsed = _parsed_claude_model_id(model.id)+ if parsed is None:+ continue+ candidate_family, candidate_version, candidate_date = parsed+ if candidate_family != family:+ continue+ if requested_version is not None and candidate_version != requested_version:+ continue+ matches.append((candidate_version, candidate_date or 0, model.id))+ return max(matches)[2] if matches else None++ return next(+ (model.id for model in observed_models if model.id == requested_model),+ None,+ )+++def inspect_exact_hop(+ config: ModelHubConfig,+ backend: BackendName,+ menu_model: str,+ hop: ModelHubRouteHopConfig | None,+ *,+ now: datetime | None = None,+ unavailable_source_ids: frozenset[str] = frozenset(),+ supply_channel: Literal["hub"] | None = None,+) -> ExactHopInspection:+ """Inspect one stored hop without matching, substituting, or reordering it."""++ menu_provider_id: str | None = None+ menu_model_id = menu_model+ if backend == "opencode":+ menu_provider_id, menu_model_id = canonical_opencode_menu_identity(menu_model)++ if hop is None:+ return ExactHopInspection(+ backend=backend,+ menu_model=menu_model,+ source_id=None,+ model_id=None,+ menu_provider_id=menu_provider_id,+ menu_model_id=menu_model_id,+ source=None,+ configuration_eligible=False,+ inventory_member=False,+ supply_eligible=False,+ runnable=False,+ structural_blocker=True,+ reason="route_unconfigured",+ retry_at=None,+ )++ source = next((item for item in config.sources if item.id == hop.source_id), None)+ if source is None:+ return ExactHopInspection(+ backend=backend,+ menu_model=menu_model,+ source_id=hop.source_id,+ model_id=hop.model_id,+ menu_provider_id=menu_provider_id,+ menu_model_id=menu_model_id,+ source=None,+ configuration_eligible=False,+ inventory_member=False,+ supply_eligible=False,+ runnable=False,+ structural_blocker=True,+ reason="source_missing",+ retry_at=None,+ )++ configuration_eligible = source_eligible_for_backend(source, backend)+ inventory_member = any(model.id == hop.model_id for model in source.models)+ channel_eligible = supply_channel is None or source.supply_channel == supply_channel+ supply_eligible = configuration_eligible and inventory_member and channel_eligible+ runnable = supply_eligible and source_runnable(+ source,+ now=now,+ unavailable_source_ids=unavailable_source_ids,+ model_supported=inventory_member,+ )+ reason: str | None = None+ structural_blocker = False+ if not inventory_member or not configuration_eligible:+ reason = "model_unsupported"+ structural_blocker = True+ elif source.id in unavailable_source_ids:+ reason = "native_cli_unavailable"+ structural_blocker = True+ elif source.state.status in {"needs_action", "error"}:+ reason = source.state.detail_key+ return ExactHopInspection(+ backend=backend,+ menu_model=menu_model,+ source_id=source.id,+ model_id=hop.model_id,+ menu_provider_id=menu_provider_id,+ menu_model_id=menu_model_id,+ source=source,+ configuration_eligible=configuration_eligible,+ inventory_member=inventory_member,+ supply_eligible=supply_eligible,+ runnable=runnable,+ structural_blocker=structural_blocker,+ reason=reason,+ retry_at=(+ source.state.retry_at+ if source.state.status == "cooldown"+ else None+ ),+ )+++def _supply_status(+ inspections: tuple[ExactHopInspection, ...],+ *,+ now: datetime | None,+ unavailable_source_ids: frozenset[str],+) -> SupplyStatus:+ if not inspections:+ return "interrupted"+ if any(inspection.runnable for inspection in inspections):+ return "ok" if all(inspection.runnable for inspection in inspections) else "degraded"+ if all(+ inspection.source is not None+ and inspection.source.id not in unavailable_source_ids+ and inspection.supply_eligible+ and inspection.source.state.status == "cooldown"+ and not source_retry_ready(inspection.source, now)+ for inspection in inspections+ ):+ return "waiting"+ return "interrupted"++def resolve_model_hub_turn(config: ModelHubConfig,backend: BackendName,@@ -250,10 +370,11 @@ def resolve_model_hub_turn(unavailable_source_ids: frozenset[str] = frozenset(),supply_channel: Literal["hub"] | None = None,) -> ModelHubTurnResolution:- """Resolve one turn without starting runtimes, reading credentials, or mutating state.+ """Resolve a turn by walking the route persisted for ``requested_model``.- ``now`` makes cooldown recovery deterministic. ``unavailable_source_ids`` is- caller-supplied runtime viability discovered before this pure decision.+ This function deliberately does not inspect source inventory, vendor names,+ or source order to create a route. Those decisions belong to source-add and+ explicit chain-edit operations."""requested_model = str(requested_model or "").strip()@@ -268,38 +389,7 @@ def resolve_model_hub_turn()if backend == "opencode":- checked = tuple(agent.menu.checked if agent.menu else ())- if not checked:- return ModelHubTurnResolution(- backend=backend,- channel="unavailable",- requested_model=requested_model,- target_model=requested_model,- source=None,- supply_status="interrupted",- )if not requested_model:- for identifier in checked:- candidate = resolve_model_hub_turn(- config,- backend,- identifier,- now=now,- unavailable_source_ids=unavailable_source_ids,- supply_channel=supply_channel,- )- if candidate.source is not None:- return candidate- return ModelHubTurnResolution(- backend=backend,- channel="unavailable",- requested_model=requested_model,- target_model=requested_model,- source=None,- supply_status="interrupted",- )- normalized = normalize_opencode_requested_model(requested_model, checked)- if normalized is None:return ModelHubTurnResolution(backend=backend,channel="unavailable",@@ -308,119 +398,132 @@ def resolve_model_hub_turn(source=None,supply_status="interrupted",)- requested_model = normalized-- mapping = (- next(- (item for item in agent.mappings if item.enabled and item.builtin_id == requested_model),- None,- )- if agent.menu_kind == "fixed"- else None- )- target_model = mapping.target_model_id if mapping is not None else requested_model- mapping_applied = target_model != requested_model- provider: str | None = None- if backend == "opencode":- try:- provider, target_model = parse_opencode_model_id(target_model)- except ValueError:- return ModelHubTurnResolution(- backend=backend,- channel="unavailable",- requested_model=requested_model,- target_model=target_model,- source=None,- mapping_applied=mapping_applied,- supply_status="interrupted",- )- if f"{provider}/{target_model}" not in agent.menu.checked:- return ModelHubTurnResolution(- backend=backend,- channel="unavailable",- requested_model=requested_model,- target_model=target_model,- source=None,- provider=provider,- mapping_applied=mapping_applied,- supply_status="interrupted",- )- if not target_model:+ route = agent.routes.get(requested_model)+ if route is None:return ModelHubTurnResolution(backend=backend,channel="unavailable",requested_model=requested_model,- target_model=target_model,+ target_model=requested_model,source=None,- provider=provider,- mapping_applied=mapping_applied,supply_status="interrupted",+ route_unconfigured=True,+ route_reason="route_unconfigured",)- by_id = {source.id: source for source in config.sources}- source_model_ids: list[tuple[str, str]] = []- matching_sources: list[ModelHubSourceConfig] = []- for source in (- by_id[source_id]- for source_id in config.effective_source_order(backend)- ):- if not source_eligible_for_backend(source, backend) or (- provider is not None and opencode_provider_id(source.vendor) != provider- ):- continue- effective_model = effective_model_for_source(- backend=backend,- requested_model=requested_model,- target_model=target_model,- source=source,- explicit_mapping=mapping is not None,+ menu_provider_id: str | None = None+ menu_model_id: str | None = None+ if backend == "opencode":+ menu_provider_id, menu_model_id = canonical_opencode_menu_identity(+ requested_model)- if effective_model is None:- continue- matching_sources.append(source)- source_model_ids.append((source.id, effective_model))- matching_source_tuple = tuple(matching_sources)-- candidates: list[ModelHubSourceConfig] = []- recoverable_source_ids: list[str] = []- for source in matching_source_tuple:- if supply_channel is not None and source.supply_channel != supply_channel:- continue- if source.state.status == "cooldown" and source_retry_ready(source, now):- recoverable_source_ids.append(source.id)- if not source_runnable(- source,++ inspected_hops = tuple(+ inspect_exact_hop(+ config,+ backend,+ requested_model,+ hop,now=now,unavailable_source_ids=unavailable_source_ids,- ):- continue- candidates.append(source)-- source = candidates[0] if candidates else None- candidate_tuple = tuple(candidates)- target_source = source or (- matching_source_tuple[0] if matching_source_tuple else None+ supply_channel=supply_channel,+ )+ for hop in route.hops)- effective_target = dict(source_model_ids).get(- target_source.id if target_source is not None else "",- target_model,+ route_reason = (+ inspect_exact_hop(+ config,+ backend,+ requested_model,+ None,+ now=now,+ unavailable_source_ids=unavailable_source_ids,+ supply_channel=supply_channel,+ ).reason+ if not route.hops+ else None)+ matching_inspections = tuple(+ inspection+ for inspection in inspected_hops+ if inspection.source is not None+ )+ matching_sources = tuple(+ inspection.source+ for inspection in matching_inspections+ if inspection.source is not None+ )+ source_model_ids = tuple(+ (inspection.source_id, inspection.model_id)+ for inspection in matching_inspections+ if inspection.source_id is not None and inspection.model_id is not None+ )+ unsupported_source_ids = frozenset(+ inspection.source_id+ for inspection in matching_inspections+ if inspection.reason == "model_unsupported"+ and inspection.source_id is not None+ )+ runnable_inspections = tuple(+ inspection+ for inspection in matching_inspections+ if inspection.runnable+ )+ candidates = tuple(+ inspection.source+ for inspection in runnable_inspections+ if inspection.source is not None+ )+ projectable_hops = tuple(+ inspection+ for inspection in matching_inspections+ if inspection.configuration_eligible+ and (+ supply_channel is None+ or (+ inspection.source is not None+ and inspection.source.supply_channel == supply_channel+ )+ )+ )+ recoverable = tuple(+ source.id+ for source in matching_sources+ if source.state.status == "cooldown" and source_retry_ready(source, now)+ )+ first_inspection = runnable_inspections[0] if runnable_inspections else None+ target_model = (+ first_inspection.model_id+ if first_inspection is not None+ else inspected_hops[0].model_id+ if inspected_hops+ else requested_model+ )+ channel: ResolutionChannel = "unavailable"+ first = first_inspection.source if first_inspection is not None else None+ if first is not None:+ channel = first.supply_channelreturn ModelHubTurnResolution(backend=backend,- channel=source.supply_channel if source is not None else "unavailable",+ channel=channel,requested_model=requested_model,- target_model=effective_target,- source=source,- matching_sources=matching_source_tuple,- candidates=candidate_tuple,- source_model_ids=tuple(source_model_ids),- provider=provider,- mapping_applied=mapping_applied,- recoverable_source_ids=tuple(recoverable_source_ids),+ target_model=target_model or requested_model,+ source=first,+ matching_sources=matching_sources,+ candidates=candidates,+ candidate_hops=runnable_inspections,+ projectable_hops=projectable_hops,+ source_model_ids=source_model_ids,+ inspected_hops=inspected_hops,+ unsupported_source_ids=tuple(unsupported_source_ids),+ route_unconfigured=route_reason == "route_unconfigured",+ route_reason=route_reason,+ menu_provider_id=menu_provider_id,+ menu_model_id=menu_model_id,+ recoverable_source_ids=recoverable,supply_status=_supply_status(- matching_source_tuple,- candidate_tuple,+ inspected_hops,now=now,unavailable_source_ids=unavailable_source_ids,),diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex bd75d45db..60d089d87 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -14,6 +14,8 @@ async def dispatch_model_hub_rpc() -> Any:if operation == "list_sources":return service.list_sources()+ if operation == "observe_source":+ return await service.observe_source(payload.get("observation"))if operation == "create_source":return await service.create_source(payload.get("source"))if operation == "patch_source":@@ -29,11 +31,12 @@ async def dispatch_model_hub_rpc(payload.get("reauth"),)if operation == "delete_source":- await service.delete_source(payload.get("source_id"), force=payload.get("force") is True)- return None+ return await service.delete_source(payload.get("source_id"), force=payload.get("force") is True)if operation == "refresh_source":- source, discovered = await service.refresh_source(payload.get("source_id"))- return {"source": source, "discovered": discovered}+ return await service.refresh_source(+ payload.get("source_id"),+ force=payload.get("force") is True,+ )if operation == "list_agents":return service.list_agents()if operation == "get_agent_sources":@@ -45,8 +48,12 @@ async def dispatch_model_hub_rpc()if operation == "set_agent_mode":return await service.set_agent_mode(payload.get("backend"), payload.get("mode"))- if operation == "set_mappings":- return await service.set_mappings(payload.get("backend"), payload.get("mappings"))+ if operation == "set_agent_chain":+ return await service.set_agent_chain(+ payload.get("backend"),+ payload.get("model_id"),+ payload.get("chain"),+ )if operation == "set_opencode_menu":return await service.set_opencode_menu(payload.get("menu"))if operation == "add_custom_model":diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 6f362bf3f..888bf7317 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -8,8 +8,7 @@ import timeimport uuidfrom dataclasses import dataclass, replacefrom datetime import datetime, timedelta, timezone-from typing import Any, Callable, Literal, Mapping, Optional, Protocol, cast-from urllib.parse import parse_qsl, urlsplit+from typing import Any, Awaitable, Callable, Literal, Mapping, Optional, Protocol, castfrom sqlalchemy import func, select@@ -19,18 +18,22 @@ from config.v2_config import (MODEL_HUB_BACKENDS,ModelHubAgentSupplyConfig,ModelHubConfig,- ModelHubMappingConfig,+ model_hub_fixed_menu_ids,ModelHubMenuConfig,ModelHubModelConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,ModelHubSourceConfig,ModelHubSourceStateConfig,ModelHubSourceUsageConfig,V2Config,+ canonical_opencode_menu_identity,+ normalize_model_hub_base_url,+ normalize_model_hub_vendor_id,)from core.services.settings import default_configfrom storage.db import get_cached_sqlite_enginefrom storage.models import agent_sessions, messages-from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalogfrom .adapter import (EngineAdapter,@@ -42,7 +45,13 @@ from .adapter import (RawCallOutcome,RawOutcomeKind,RetainedMaterialDisposition,+ ObservationDiscovery,+ ObservationOutcome,+ SOURCE_PROTOCOLS,+ SourceObservation,SourceBinding,+ make_source_observation,+ validate_source_observation,)from .classification import ResolutionDecision, classify_outcomefrom .events import (@@ -53,12 +62,7 @@ from .events import (contains_credential_material,)from .errors import ModelDiscoveryError-from .identifiers import (- STANDARD_OPENCODE_VENDOR_IDS,- opencode_model_id,- opencode_provider_id,- parse_opencode_model_id,-)+from .identifiers import STANDARD_OPENCODE_VENDOR_IDSfrom .migration import (MigrationConflictError,apply_native_migration,@@ -79,7 +83,8 @@ from .resolver import (BackendName,ModelHubTurnResolution,allowed_origins,- normalize_opencode_requested_model,+ inspect_exact_hop,+ matching_v1_model_id as _matching_v1_model_id,resolve_model_hub_turn,source_after_cooldown_recovery,source_eligible_for_backend,@@ -87,27 +92,18 @@ from .resolver import ()from .revocations import CredentialRevocationJournal-CONTRACT_VERSION = 3+CONTRACT_VERSION = 5AGENT_CHAIN_CONTRACT_VERSION = 5PROBE_RESULT_CONTRACT_VERSION = 5logger = logging.getLogger(__name__)_NATIVE_VENDOR_BACKENDS = {"anthropic": "claude", "openai": "codex"}-_CREDENTIAL_QUERY_KEYS = {- "access_token",- "api_key",- "apikey",- "auth",- "authorization",- "bearer",- "credential",- "key",- "password",- "passwd",- "secret",- "sig",- "signature",- "token",+_FIXED_BACKEND_PROTOCOLS: dict[+ str,+ Literal["anthropic", "openai_responses", "openai_chat"],+] = {+ "claude": "anthropic",+ "codex": "openai_responses",}@@ -148,6 +144,7 @@ class V2ModelHubConfigStore:return default_config().model_hubdef save(self, model_hub: ModelHubConfig) -> None:+ model_hub = ModelHubConfig.from_payload(model_hub.to_payload())with CONFIG_LOCK:try:config = V2Config.load()@@ -184,6 +181,9 @@ class UnavailableEngineAdapter:async def provision_credential(self, vendor: str, protocol: str, secret: str, base_url: str | None) -> str:raise EngineUnavailableError+ async def provision_transient_credential(self, vendor: str, secret: str, base_url: str | None) -> str:+ raise EngineUnavailableError+async def revoke_credential(self, credential_ref: str) -> None:raise EngineUnavailableError@@ -193,6 +193,15 @@ class UnavailableEngineAdapter:async def discover_models(self, vendor: str, protocol: str, base_url: str | None, credential_ref: str):raise EngineUnavailableError+ async def observe_source(+ self,+ vendor: str,+ base_url: str | None,+ credential_ref: str,+ protocol_order,+ ) -> SourceObservation:+ raise EngineUnavailableError+async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:raise EngineUnavailableError@@ -260,42 +269,10 @@ def _mask_credential(value: str) -> str:def _validated_base_url(value: object) -> Optional[str]:- if value is None:- return None- if not isinstance(value, str) or not value.strip():- raise ModelHubError("discovery_failed")try:- parsed = urlsplit(value)- hostname = parsed.hostname- except ValueError:+ return normalize_model_hub_base_url(value)+ except (TypeError, ValueError):raise ModelHubError("discovery_failed") from None- if (- parsed.scheme.lower() not in {"http", "https"}- or not hostname- or parsed.username is not None- or parsed.password is not None- or parsed.fragment- or contains_credential_material(value)- ):- raise ModelHubError("discovery_failed")- for key, _ in parse_qsl(parsed.query, keep_blank_values=True):- normalized = key.strip().lower().replace("-", "_").replace(".", "_")- if normalized in _CREDENTIAL_QUERY_KEYS or any(- marker in normalized- for marker in (- "api_key",- "access_token",- "auth_token",- "token",- "authorization",- "signature",- "secret",- "password",- "credential",- )- ):- raise ModelHubError("discovery_failed")- return valuedef _builtin_model_ids(backend: str) -> tuple[str, ...]:@@ -305,8 +282,7 @@ def _builtin_model_ids(backend: str) -> tuple[str, ...]:(_native_model_ids) and the agents endpoint's read-only builtin_modelsprojection (agent-supply.schema.json v1.2), so the two never diverge."""- catalog = load_bundled_catalog()- return tuple(entry["id"] for entry in backend_model_entries(backend, catalog))+ return model_hub_fixed_menu_ids(backend)def _native_model_ids(vendor: str) -> tuple[str, ...]:@@ -316,12 +292,107 @@ def _native_model_ids(vendor: str) -> tuple[str, ...]:return _builtin_model_ids(backend)-def _default_protocol(vendor: str) -> str:- if vendor == "anthropic":- return "anthropic"- if vendor == "openai":- return "openai_responses"- return "openai_chat"+async def _acquire_credential_ref_with_cancellation_ownership(+ service: "ModelHubService",+ operation: Awaitable[str],+ rollback_source_id: str,+) -> str:+ """Keep ownership of an engine ref when the caller is cancelled mid-provision."""++ provision_task = asyncio.create_task(+ service._engine_call(operation)+ )+ try:+ return await asyncio.shield(provision_task)+ except asyncio.CancelledError as cancelled:+ # The shield leaves provisioning alive; wait for its ref before settling+ # cancellation so the transient material can be journaled and revoked.+ transient_ref = await _await_owned_task_before_settling(provision_task)+ await _rollback_credential_before_settling(+ service,+ rollback_source_id,+ transient_ref,+ )+ raise cancelled+++async def _provision_transient_credential_with_cancellation_ownership(+ service: "ModelHubService",+ vendor: str,+ key: str,+ base_url: str | None,+) -> str:+ return await _acquire_credential_ref_with_cancellation_ownership(+ service,+ service.adapter.provision_transient_credential(vendor, key, base_url),+ "observation",+ )+++async def _rollback_credential_before_settling(+ service: "ModelHubService",+ source_id: str,+ credential_ref: str,+) -> None:+ """Finish transient cleanup before propagating a cancellation."""++ rollback_task = asyncio.create_task(+ _require_credential_cleanup(service, source_id, credential_ref)+ )+ try:+ await asyncio.shield(rollback_task)+ except asyncio.CancelledError as cancelled:+ await _await_owned_task_before_settling(rollback_task)+ raise cancelled+++async def _await_owned_task_before_settling(+ task: asyncio.Task[Any],+) -> Any:+ """Wait through caller cancellation, but never retry a cancelled owned task."""++ while True:+ if task.cancelled():+ raise asyncio.CancelledError+ try:+ return await asyncio.shield(task)+ except asyncio.CancelledError:+ if task.cancelled():+ raise+++async def _require_credential_cleanup(+ service: "ModelHubService",+ source_id: str,+ credential_ref: str,+) -> None:+ """Refuse to settle when cleanup is neither complete nor durable."""++ if not await service._rollback_credential(source_id, credential_ref):+ raise ModelHubError("engine_down", status=503)+++async def _rollback_replacement_before_settling(+ service: "ModelHubService",+ source_id: str,+ replacement_ref: str,+ old_credential_ref: str | None,+ *,+ old_revocation_recorded: bool,+) -> None:+ replacement_task = asyncio.create_task(+ service._rollback_replacement(+ source_id,+ replacement_ref,+ old_credential_ref,+ old_revocation_recorded=old_revocation_recorded,+ )+ )+ try:+ await asyncio.shield(replacement_task)+ except asyncio.CancelledError as cancelled:+ await _await_owned_task_before_settling(replacement_task)+ raise cancelleddef _binding(source: ModelHubSourceConfig) -> SourceBinding:@@ -499,20 +570,52 @@ class ModelHubService:raise ModelHubError("engine_down", status=503) from Nonedef _bindings(self, config: ModelHubConfig) -> list[SourceBinding]:+ ineligible_source_ids = {+ inspection.source_id+ for backend_name in MODEL_HUB_BACKENDS+ for menu_model, route in config.agents[backend_name].routes.items()+ for hop in route.hops+ for inspection in (+ inspect_exact_hop(+ config,+ cast(BackendName, backend_name),+ menu_model,+ hop,+ ),+ )+ if inspection.source_id is not None+ and not inspection.configuration_eligible+ }return [_binding(source)for source in config.sourcesif source.supply_channel == "hub"- and (- source.models- or source.state.status not in {"needs_action", "error"}- )+ and bool(source.models)+ and source.id not in ineligible_source_ids]@staticmethoddef _clone_config(config: ModelHubConfig) -> ModelHubConfig:return ModelHubConfig.from_payload(config.to_payload())+ @staticmethod+ def _persisted_credential(+ config: ModelHubConfig,+ source_id: str,+ credential_ref: str | None,+ ) -> bool:+ if credential_ref is None:+ return False+ return any(+ source.id == source_id and source.credential_ref == credential_ref+ for source in config.sources+ )++ def _save_config(self, config: ModelHubConfig) -> ModelHubConfig:+ canonical = ModelHubConfig.from_payload(config.to_payload())+ self.store.save(canonical)+ return canonical+async def _sync_sources(self, config: ModelHubConfig, *, force_empty: bool = False) -> None:bindings = self._bindings(config)has_hub_sources = any(@@ -528,13 +631,19 @@ class ModelHubService:"""Persist the authoritative config before updating its engine projection."""self._engine_synced = False+ updated = ModelHubConfig.from_payload(updated.to_payload())previous_bindings = self._bindings(previous)updated_bindings = self._bindings(updated)- self.store.save(updated)+ self._save_config(updated)try:await self._sync_sources(updated, force_empty=bool(previous_bindings))+ except asyncio.CancelledError:+ # The config write is the persistence boundary. A cancelled sync is+ # reconciled by the next demand and must not roll back a saved ref.+ self._engine_synced = False+ raiseexcept Exception:- self.store.save(previous)+ self._save_config(previous)try:await self._sync_sources(previous, force_empty=bool(updated_bindings))except ModelHubError:@@ -669,6 +778,170 @@ class ModelHubService:))+ @staticmethod+ def _observation_protocol_order(payload: Mapping[str, Any]) -> tuple[str, ...]:+ requested = payload.get("protocol_order")+ if requested is None:+ return SOURCE_PROTOCOLS+ if (+ not isinstance(requested, list)+ or not all(isinstance(item, str) for item in requested)+ ):+ raise ModelHubError("discovery_failed")+ requested_order = tuple(requested)+ if len(set(requested_order)) != len(SOURCE_PROTOCOLS) or set(requested_order) != set(SOURCE_PROTOCOLS):+ raise ModelHubError("discovery_failed")+ return requested_order++ @staticmethod+ def _observation_payload(observation: SourceObservation) -> dict:+ return {+ "contract_version": CONTRACT_VERSION,+ "outcome": observation.outcome.value,+ "reachable": observation.reachable,+ "authenticated": (+ "authenticated"+ if observation.authenticated is True+ else "rejected"+ if observation.authenticated is False+ else "unknown"+ ),+ "protocol": observation.protocol,+ "discovery": observation.discovery.value,+ "models": list(observation.model_ids),+ }++ @staticmethod+ def _validate_observation(observation: SourceObservation) -> SourceObservation:+ try:+ validated = validate_source_observation(observation)+ except (TypeError, ValueError):+ raise ModelHubError("discovery_failed", status=502)+ if any(contains_credential_material(model_id) for model_id in validated.model_ids):+ raise ModelHubError("discovery_failed", status=502)+ return validated++ async def _observe_provisioned_credential(+ self,+ vendor: str,+ base_url: str | None,+ credential_ref: str,+ protocol_order: tuple[str, ...],+ ) -> SourceObservation:+ try:+ observation = await self.adapter.observe_source(+ vendor,+ base_url,+ credential_ref,+ protocol_order,+ )+ except asyncio.TimeoutError:+ observation = make_source_observation(+ outcome=ObservationOutcome.TIMEOUT,+ reachable=None,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ except EngineUnavailableError:+ raise ModelHubError("engine_down", status=503) from None+ except asyncio.CancelledError:+ raise+ except Exception:+ observation = make_source_observation(+ outcome=ObservationOutcome.ADAPTER_ERROR,+ reachable=None,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ return self._validate_observation(observation)++ async def _require_proven_observation(+ self,+ vendor: str,+ base_url: str | None,+ credential_ref: str,+ protocol_order: tuple[str, ...],+ ) -> SourceObservation:+ """Require response-backed protocol evidence before Source persistence."""++ observation = await self._observe_provisioned_credential(+ vendor,+ base_url,+ credential_ref,+ protocol_order,+ )+ if (+ observation.outcome is not ObservationOutcome.OBSERVED+ or observation.protocol is None+ ):+ raise ModelHubError(+ "discovery_failed",+ status=422,+ data={"observation": self._observation_payload(observation)},+ )+ return observation++ async def _observe_source_payload(+ self,+ payload: Mapping[str, Any],+ *,+ require_proven: bool = False,+ ) -> SourceObservation:+ if set(payload) - {"vendor", "base_url", "key", "protocol_order"}:+ raise ModelHubError("discovery_failed")+ vendor = payload.get("vendor")+ try:+ vendor = normalize_model_hub_vendor_id(vendor)+ except ValueError:+ raise ModelHubError("discovery_failed")+ base_url = _validated_base_url(payload.get("base_url"))+ key = payload.get("key")+ if not isinstance(key, str) or not key.strip():+ raise ModelHubError("discovery_failed")+ protocol_order = self._observation_protocol_order(payload)+ transient_ref = await _provision_transient_credential_with_cancellation_ownership(+ self,+ vendor,+ key.strip(),+ base_url,+ )+ try:+ if require_proven:+ return await self._require_proven_observation(+ vendor,+ base_url,+ transient_ref,+ protocol_order,+ )+ return await self._observe_provisioned_credential(+ vendor,+ base_url,+ transient_ref,+ protocol_order,+ )+ finally:+ await _rollback_credential_before_settling(+ self,+ "observation",+ transient_ref,+ )++ async def _require_proven_source_payload(+ self,+ payload: Mapping[str, Any],+ ) -> SourceObservation:+ return await self._observe_source_payload(payload, require_proven=True)++ async def observe_source(self, payload: object) -> dict:+ if not isinstance(payload, dict):+ raise ModelHubError("discovery_failed")+ observation = await self._observe_source_payload(payload)+ return {"observation": self._observation_payload(observation)}+def _record_event(self, **event_fields: Any) -> None:try:source_ids = {@@ -725,7 +998,11 @@ class ModelHubService:except OSError:passif replacement_ref != old_credential_ref:- await self._rollback_credential(source_id, replacement_ref)+ await _require_credential_cleanup(+ self,+ source_id,+ replacement_ref,+ )async def _cleanup_orphaned_hub_material(self,@@ -771,11 +1048,15 @@ class ModelHubService:status="needs_action",detail_key="models.source.needs_action.oauth_expired",)- self.store.save(config)+ self._save_config(config)async def _discard_unbound_hub_flow(self, flow: OAuthFlowState) -> None:if flow.credential_ref:- await self._rollback_credential(flow.source_id, flow.credential_ref)+ await _require_credential_cleanup(+ self,+ flow.source_id,+ flow.credential_ref,+ )returntry:await self.adapter.cancel_oauth(flow.flow_id)@@ -798,13 +1079,15 @@ class ModelHubService:source: ModelHubSourceConfig,manual_models: list[ModelHubModelConfig],discovered: list[str],+ *,+ allow_empty: bool = False,) -> None:- if (not discovered and not manual_models) or any(+ if (not allow_empty and not discovered and not manual_models) or any(not isinstance(model_id, str)or not model_idor contains_credential_material(model_id)for model_id in discovered- ):+ ) or len(set(discovered)) != len(discovered):raise ModelHubError("discovery_failed", status=502)discovered_at = self.now().isoformat()manual_model_ids = {model.id for model in manual_models}@@ -826,11 +1109,38 @@ class ModelHubService:source.models = discovered_models + manual_modelssource.last_discovered_at = discovered_at+ async def _finalize_successful_discovery(+ self,+ previous: ModelHubConfig,+ updated: ModelHubConfig,+ source: ModelHubSourceConfig,+ discovered: list[str],+ *,+ force: bool,+ ) -> tuple[list[dict], list[dict]]:+ """Apply one successful inventory observation and commit it atomically."""++ manual = [model for model in source.models if model.provenance == "manual"]+ self._apply_discovered_models(+ source,+ manual,+ discovered,+ allow_empty=True,+ )+ source.state = ModelHubSourceStateConfig(status="standby")+ removed_hops, interrupted = self._guard_inventory_mutation(+ previous,+ updated,+ source.id,+ force=force,+ )+ await self._commit_synced(previous, updated)+ return removed_hops, interrupted+async def _commit_new_source_locked(self,source: ModelHubSourceConfig,*,- consented: bool,previous: Optional[ModelHubConfig] = None,) -> None:previous = previous or self.store.load()@@ -838,53 +1148,86 @@ class ModelHubService:if any(item.id == source.id for item in config.sources):raise ModelHubError("migration_item_conflict", status=409)config.sources.append(source)- config.refresh_follow_orders()- if consented:- config.subscription_hub_experimental = True+ self._apply_source_placement(config, source)await self._commit_synced(previous, config)- def _adopted_by(self, source_id: str) -> list[dict]:+ def _apply_source_placement(+ self,+ config: ModelHubConfig,+ source: ModelHubSourceConfig,+ ) -> None:+ """Apply matching-v1 and placement-v1 to one newly added Source."""++ for backend in MODEL_HUB_BACKENDS:+ agent = config.agents[backend]+ if self._eligible_for_agent(source, backend) and source.id not in agent.sources.order:+ agent.sources.order.append(source.id)+ menu_ids = self._agent_menu_model_ids(agent)+ for menu_model in menu_ids:+ route = agent.routes.setdefault(menu_model, ModelHubRouteConfig())+ if not self._eligible_for_agent(source, backend):+ continue+ matched_model = _matching_v1_model_id(+ backend=cast(BackendName, backend),+ requested_model=menu_model,+ source=source,+ checked_models=menu_ids,+ )+ if matched_model is None or any(hop.source_id == source.id for hop in route.hops):+ continue+ route.hops = (*route.hops, ModelHubRouteHopConfig(source.id, matched_model))++ @staticmethod+ def _agent_menu_model_ids(agent: ModelHubAgentSupplyConfig) -> tuple[str, ...]:+ if agent.menu_kind == "fixed":+ return tuple(_builtin_model_ids(agent.backend))+ return tuple(agent.menu.checked if agent.menu else ())++ def _added_to(self, source_id: str) -> list[dict]:config = self.store.load()- return [- {- "backend": backend,- "policy": "follow",- "position": config.effective_source_order(backend).index(source_id) + 1,- }- for backend in MODEL_HUB_BACKENDS- if config.agents[backend].sources.policy == "follow" and source_id in config.effective_source_order(backend)- ]+ result: list[dict] = []+ for backend in MODEL_HUB_BACKENDS:+ routes = config.agents[backend].routes+ for menu_model, route in routes.items():+ for position, hop in enumerate(route.hops, start=1):+ if hop.source_id == source_id:+ result.append(+ {+ "backend": backend,+ "menu_model": menu_model,+ "source_id": source_id,+ "model_id": hop.model_id,+ "position": position,+ }+ )+ return result- def _skipped_by(self, source_id: str) -> list[dict]:+ def _adopted_by(self, source_id: str) -> list[dict]:config = self.store.load()- source = self._source(config, source_id)return [- {- "backend": backend,- "reason": "custom_order",- }+ {"backend": backend, "menu_model": menu_model}for backend in MODEL_HUB_BACKENDS- if self._eligible_for_agent(source, backend)- and config.agents[backend].sources.policy == "custom"- and source_id not in config.effective_source_order(backend)+ for menu_model, route in config.agents[backend].routes.items()+ if any(hop.source_id == source_id for hop in route.hops)]def _source_creation_result(self, source: dict) -> dict:return {"source": source,+ "added_to": self._added_to(source["id"]),"adopted_by": self._adopted_by(source["id"]),- "skipped_by": self._skipped_by(source["id"]),}async def _create_oauth_source(self,- source: ModelHubSourceConfig,manual_models: list[ModelHubModelConfig],*,+ display_name: str,+ billing: Literal["monthly", "metered"],+ created_at: str,oauth_ref: str,channel: Literal["native_cli", "hub"],vendor: str,- consented: bool,completed_flow: Optional[OAuthFlowState] = None,idempotent: bool = False,) -> dict:@@ -893,6 +1236,7 @@ class ModelHubService:# credential while still retaining rollback ownership before discovery.async with self._mutation_lock:rollback_credential_ref: Optional[str] = None+ source_id = ""persisted = Falsetry:binding = self._oauth_binding(oauth_ref)@@ -913,9 +1257,9 @@ class ModelHubService:):raise ModelHubError("flow_not_found", status=404)- source.id = flow.source_id+ source_id = flow.source_idprevious = self.store.load()- existing = next((item for item in previous.sources if item.id == source.id), None)+ existing = next((item for item in previous.sources if item.id == source_id), None)if idempotent and existing is not None and self._source_matches_binding(existing, binding):try:self.oauth_flows.complete(oauth_ref)@@ -924,10 +1268,40 @@ class ModelHubService:return existing.to_payload()if existing is not None:raise ModelHubError("migration_item_conflict", status=409)+ account_label: str | None = None+ state = ModelHubSourceStateConfig(status="standby")+ discovered: list[str] | Noneif channel == "hub":- source.credential_ref = cast(str, flow.credential_ref)- rollback_credential_ref = source.credential_ref+ rollback_credential_ref = cast(str, flow.credential_ref)+ observation = await self._require_proven_observation(+ vendor,+ None,+ rollback_credential_ref,+ SOURCE_PROTOCOLS,+ )+ protocol = cast(+ Literal["anthropic", "openai_responses", "openai_chat"],+ observation.protocol,+ )+ if observation.discovery is ObservationDiscovery.SUCCEEDED:+ discovered = list(observation.model_ids)+ elif observation.discovery is ObservationDiscovery.FAILED:+ discovered = None+ state = ModelHubSourceStateConfig(+ status="error",+ detail_key="models.source.error.unclassified",+ )+ else:+ raise ModelHubError("discovery_failed", status=502)else:+ backend = _NATIVE_VENDOR_BACKENDS.get(vendor)+ protocol = (+ _FIXED_BACKEND_PROTOCOLS.get(backend)+ if backend is not None+ else None+ )+ if protocol is None:+ raise ModelHubError("discovery_failed")try:source_status = self.native_oauth_adapter.completed_source_status(oauth_ref)except KeyError:@@ -936,8 +1310,8 @@ class ModelHubService:raise ModelHubError("engine_down", status=503) from Noneexcept Exception:raise ModelHubError("engine_down", status=503) from None- source.account_label = source_status.account_label- source.state = (+ account_label = source_status.account_label+ state = (ModelHubSourceStateConfig(status="standby")if source_status.signed_inelse ModelHubSourceStateConfig(@@ -945,18 +1319,44 @@ class ModelHubService:detail_key="models.source.needs_action.oauth_expired",))-- discovered = (- await self._discover(source)- if channel == "hub"- else list(_native_model_ids(vendor))- )+ discovered = list(_native_model_ids(vendor))if channel == "native_cli" and not discovered:raise ModelHubError("discovery_failed")- self._apply_discovered_models(source, manual_models, discovered)+ source_payload: dict[str, Any] = {+ "id": source_id,+ "created_at": created_at,+ "kind": "subscription",+ "vendor": vendor,+ "display_name": display_name,+ "protocol": protocol,+ "base_url": None,+ "supply_channel": channel,+ "billing": billing,+ "state": state.to_payload(),+ "usage": ModelHubSourceUsageConfig().to_payload(),+ "models": [model.to_payload() for model in manual_models],+ }+ if rollback_credential_ref is not None:+ source_payload["credential_ref"] = rollback_credential_ref+ if account_label is not None:+ source_payload["account_label"] = account_label+ try:+ source = ModelHubSourceConfig.from_payload(source_payload)+ except (TypeError, ValueError):+ raise ModelHubError("discovery_failed") from None+ if discovered is not None:+ self._apply_discovered_models(+ source,+ manual_models,+ discovered,+ allow_empty=channel == "hub",+ )+ try:+ source = ModelHubSourceConfig.from_payload(source.to_payload())+ except (TypeError, ValueError):+ raise ModelHubError("discovery_failed") from Noneawait self._commit_new_source_locked(source,- consented=consented,previous=previous,)persisted = True@@ -965,9 +1365,30 @@ class ModelHubService:except (KeyError, OSError):passreturn source.to_payload()+ except asyncio.CancelledError:+ persisted = self._persisted_credential(+ self.store.load(),+ source_id,+ rollback_credential_ref,+ )+ if rollback_credential_ref is not None and not persisted:+ await _rollback_credential_before_settling(+ self,+ source_id,+ rollback_credential_ref,+ )+ try:+ self.oauth_flows.forget(oauth_ref)+ except OSError:+ pass+ raiseexcept Exception:if rollback_credential_ref is not None and not persisted:- await self._rollback_credential(source.id, rollback_credential_ref)+ await _require_credential_cleanup(+ self,+ source_id,+ rollback_credential_ref,+ )try:self.oauth_flows.forget(oauth_ref)except OSError:@@ -1090,7 +1511,7 @@ class ModelHubService:else "models.source.error.unclassified"),)- self.store.save(config)+ self._save_config(config)return self._would_interrupt(config)async def _materialize_reauth(@@ -1148,7 +1569,7 @@ class ModelHubService:status="error",detail_key="models.source.error.unclassified",)- self.store.save(config)+ self._save_config(config)interrupted_pairs = self._would_interrupt(config)raise ModelHubError("discovery_failed",@@ -1156,7 +1577,7 @@ class ModelHubService:data={"interrupted_pairs": interrupted_pairs},)self._apply_discovered_models(source, manual, discovered)- self.store.save(config)+ self._save_config(config)interrupted_pairs = self._would_interrupt(config)self._complete_reauth_flow(flow_id,@@ -1211,11 +1632,42 @@ class ModelHubService:binding,interrupted_pairs,)+ except asyncio.CancelledError:+ committed = self._persisted_credential(+ self.store.load(),+ binding.source_id,+ replacement_ref,+ )+ if not committed:+ try:+ if source is None:+ await _rollback_credential_before_settling(+ self,+ binding.source_id,+ replacement_ref,+ )+ elif replacement_ref == old_credential_ref:+ self._mark_same_handle_reauth_needs_action(source.id)+ else:+ await _rollback_replacement_before_settling(+ self,+ source.id,+ replacement_ref,+ old_credential_ref,+ old_revocation_recorded=old_revocation_recorded,+ )+ finally:+ try:+ self.oauth_flows.forget(flow_id)+ except OSError:+ pass+ raiseexcept Exception:if not committed:try:if source is None:- await self._rollback_credential(+ await _require_credential_cleanup(+ self,binding.source_id,replacement_ref,)@@ -1308,7 +1760,7 @@ class ModelHubService:status="needs_action",detail_key="models.source.needs_action.oauth_expired",)- self.store.save(config)+ self._save_config(config)return configasync def _materialize_failed_hub_reauth(@@ -1367,12 +1819,11 @@ class ModelHubService:or flow.retained_credential_ref is None):raise ModelHubError("engine_down", status=503)- cleanup_secured = await self._rollback_credential(+ await _require_credential_cleanup(+ self,binding.source_id,flow.retained_credential_ref,)- if not cleanup_secured:- raise ModelHubError("engine_down", status=503)return configif (flow.retained_material_disposition@@ -1415,35 +1866,14 @@ class ModelHubService:flow,)return flow, repair_result- if binding.channel == "hub" and not binding.experimental_consent:- raise ModelHubError("consent_required", status=409)-- source = ModelHubSourceConfig(- id=binding.source_id,- created_at=self.now().isoformat(),- kind="subscription",- vendor=binding.vendor,- display_name=binding.vendor,- protocol=_default_protocol(binding.vendor),- base_url=None,- supply_channel=binding.channel,- experimental_consent_at=(- self.now().isoformat()- if binding.channel == "hub" and binding.experimental_consent- else None- ),- billing="monthly",- state=ModelHubSourceStateConfig(status="standby"),- usage=ModelHubSourceUsageConfig(),- models=[],- )await self._create_oauth_source(- source,[],+ display_name=binding.vendor,+ billing="monthly",+ created_at=self.now().isoformat(),oauth_ref=flow_id,channel=binding.channel,vendor=binding.vendor,- consented=binding.experimental_consent,completed_flow=flow,idempotent=True,)@@ -1459,6 +1889,19 @@ class ModelHubService:async def create_source(self, payload: dict) -> dict:if not isinstance(payload, dict):raise ModelHubError("discovery_failed")+ if set(payload) - {+ "kind",+ "vendor",+ "display_name",+ "base_url",+ "supply_channel",+ "billing",+ "models",+ "key",+ "oauth_flow_ref",+ "protocol_order",+ }:+ raise ModelHubError("discovery_failed")forbidden = {"id","credential_ref",@@ -1470,17 +1913,16 @@ class ModelHubService:"created_at","last_discovered_at",} & set(payload)- if forbidden:+ if forbidden or "protocol" in payload:raise ModelHubError("discovery_failed")kind = payload.get("kind")vendor = payload.get("vendor")display_name = payload.get("display_name") or vendor- if (- kind not in {"subscription", "api_key"}- or not isinstance(vendor, str)- or not vendor- or contains_credential_material(vendor)- ):+ try:+ vendor = normalize_model_hub_vendor_id(vendor)+ except ValueError:+ raise ModelHubError("discovery_failed") from None+ if kind not in {"subscription", "api_key"}:raise ModelHubError("discovery_failed")if (not isinstance(display_name, str)@@ -1494,15 +1936,6 @@ class ModelHubService:raise ModelHubError("discovery_failed")if channel == "native_cli" and vendor not in _NATIVE_VENDOR_BACKENDS:raise ModelHubError("discovery_failed")- consented = payload.get("experimental_consent") is True- if "experimental_consent" in payload and not isinstance(payload.get("experimental_consent"), bool):- raise ModelHubError("consent_required")- if kind == "subscription" and channel == "hub" and not consented:- raise ModelHubError("consent_required", status=409)- if consented and not (kind == "subscription" and channel == "hub"):- raise ModelHubError("consent_required")-- protocol = payload.get("protocol") or _default_protocol(vendor)billing = payload.get("billing") or ("monthly" if kind == "subscription" else "metered")models_payload = payload.get("models", [])if not isinstance(models_payload, list):@@ -1519,22 +1952,6 @@ class ModelHubService:for model in manual_models):raise ValueError("Client-declared source models must use manual provenance")- source = ModelHubSourceConfig(- id=_source_id(),- kind=kind,- vendor=vendor,- display_name=display_name,- protocol=protocol,- base_url=base_url,- supply_channel=channel,- experimental_consent_at=self.now().isoformat() if consented else None,- billing=billing,- state=ModelHubSourceStateConfig(status="standby"),- usage=ModelHubSourceUsageConfig(),- models=manual_models,- created_at=self.now().isoformat(),- )- source = ModelHubSourceConfig.from_payload(source.to_payload())except (TypeError, ValueError):raise ModelHubError("discovery_failed") from None@@ -1556,33 +1973,98 @@ class ModelHubService:if oauth_ref:return self._source_creation_result(await self._create_oauth_source(- source,manual_models,+ display_name=display_name,+ billing=cast(Literal["monthly", "metered"], billing),+ created_at=self.now().isoformat(),oauth_ref=oauth_ref,channel=cast(Literal["native_cli", "hub"], channel),vendor=vendor,- consented=consented,))if kind == "subscription":raise ModelHubError("flow_not_found", status=404)+ observation = await self._require_proven_source_payload(+ {+ "vendor": vendor,+ "base_url": base_url,+ "key": credential_value,+ "protocol_order": payload.get("protocol_order"),+ }+ )+ source = ModelHubSourceConfig(+ id=_source_id(),+ kind=kind,+ vendor=vendor,+ display_name=display_name,+ protocol=cast(Literal["anthropic", "openai_responses", "openai_chat"], observation.protocol),+ base_url=base_url,+ supply_channel=channel,+ billing=billing,+ state=ModelHubSourceStateConfig(status="standby"),+ usage=ModelHubSourceUsageConfig(),+ models=manual_models,+ created_at=self.now().isoformat(),+ credential_ref="cred_preflight",+ )+ if observation.discovery is ObservationDiscovery.SUCCEEDED:+ self._apply_discovered_models(+ source,+ manual_models,+ list(observation.model_ids),+ allow_empty=True,+ )+ elif observation.discovery is ObservationDiscovery.FAILED:+ source.state = ModelHubSourceStateConfig(+ status="error",+ detail_key="models.source.error.unclassified",+ )++ # AC-29 requires the canonical Source validator to run before any+ # permanent credential is provisioned. The placeholder is never saved.+ try:+ source = ModelHubSourceConfig.from_payload(source.to_payload())+ except (TypeError, ValueError):+ raise ModelHubError("discovery_failed") from None+rollback_credential_ref = await self._engine_call(- self.adapter.provision_credential(vendor, protocol, cast(str, credential_value), source.base_url)+ self.adapter.provision_credential(+ vendor,+ source.protocol,+ cast(str, credential_value),+ source.base_url,+ ))source.credential_ref = rollback_credential_refsource.masked_credential = _mask_credential(cast(str, credential_value))+ source = ModelHubSourceConfig.from_payload(source.to_payload())persisted = Falsetry:- discovered = await self._discover(source)- self._apply_discovered_models(source, manual_models, discovered)async with self._mutation_lock:- await self._commit_new_source_locked(source, consented=consented)+ await self._commit_new_source_locked(source)persisted = Truereturn self._source_creation_result(source.to_payload())+ except asyncio.CancelledError:+ persisted = self._persisted_credential(+ self.store.load(),+ source.id,+ rollback_credential_ref,+ )+ if not persisted:+ await _rollback_credential_before_settling(+ self,+ source.id,+ rollback_credential_ref,+ )+ raiseexcept Exception:if not persisted:- await self._rollback_credential(source.id, rollback_credential_ref)+ await _require_credential_cleanup(+ self,+ source.id,+ rollback_credential_ref,+ )raiseasync def replace_credential(self, source_id: str, payload: object) -> dict:@@ -1626,30 +2108,33 @@ class ModelHubService:try:source.credential_ref = replacement_refsource.masked_credential = _mask_credential(key)- manual = [- model for model in source.models if model.provenance == "manual"- ]discovered = await self._discover(source)- self._apply_discovered_models(source, manual, discovered)- source.state = ModelHubSourceStateConfig(status="standby")-- interrupted_pairs = self._would_interrupt(config)- recovered = self._source(- previous,- source_id,- ).state.status in {"needs_action", "error"}- if interrupted_pairs and not recovered and not force:- raise ModelHubError(- "source_last_supplier",- status=409,- data={"would_interrupt": interrupted_pairs},- )-if old_credential_ref != replacement_ref:self.revocations.add(source.id, old_credential_ref)old_revocation_recorded = True- await self._commit_synced(previous, config)+ removed_hops, interrupted = await self._finalize_successful_discovery(+ previous,+ config,+ source,+ discovered,+ force=force,+ )committed = True+ except asyncio.CancelledError:+ committed = self._persisted_credential(+ self.store.load(),+ source.id,+ replacement_ref,+ )+ if not committed:+ await _rollback_replacement_before_settling(+ self,+ source.id,+ replacement_ref,+ old_credential_ref,+ old_revocation_recorded=old_revocation_recorded,+ )+ raiseexcept Exception:if not committed:await self._rollback_replacement(@@ -1672,18 +2157,25 @@ class ModelHubService:passreturn {"source": source.to_payload(),- "recovered": recovered,- "interrupted_pairs": interrupted_pairs,+ "removed_hops": removed_hops,+ "interrupted": interrupted,}async def patch_source(self, source_id: str, payload: dict) -> dict:- if not isinstance(payload, dict) or set(payload) - {"display_name", "base_url"}:+ if (+ not isinstance(payload, dict)+ or set(payload) - {"display_name", "base_url", "force"}+ or ("force" in payload and not isinstance(payload["force"], bool))+ ):raise ModelHubError("discovery_failed")base_url = _validated_base_url(payload.get("base_url")) if "base_url" in payload else None+ force = payload.get("force") is Trueasync with self._mutation_lock:previous = self.store.load()config = self._clone_config(previous)source = self._source(config, source_id)+ removed_hops: list[dict] = []+ interrupted: list[dict] = []if "display_name" in payload:display_name = payload["display_name"]if (@@ -1694,57 +2186,86 @@ class ModelHubService:):raise ModelHubError("discovery_failed")source.display_name = display_name- if "base_url" in payload:- if source.kind != "api_key":+ base_url_changed = (+ "base_url" in payload and source.base_url != base_url+ )+ if base_url_changed:+ if (+ source.kind != "api_key"+ or source.supply_channel != "hub"+ or not source.credential_ref+ ):raise ModelHubError("discovery_failed")- source.base_url = base_url- discovered = await self._discover(source)- manual = [model for model in source.models if model.provenance == "manual"]- self._apply_discovered_models(source, manual, discovered)- if "base_url" in payload:- await self._commit_synced(previous, config)- else:- self.store.save(config)- return source.to_payload()+ old_credential_ref = source.credential_ref+ replacement_ref = await (+ _acquire_credential_ref_with_cancellation_ownership(+ self,+ self.adapter.retarget_api_key_credential(+ old_credential_ref,+ source.vendor,+ source.protocol,+ base_url,+ ),+ source.id,+ )+ )+ committed = False+ old_revocation_recorded = False+ try:+ source.credential_ref = replacement_ref+ source.base_url = base_url+ discovered = await self._discover(source)+ self.revocations.add(source.id, old_credential_ref)+ old_revocation_recorded = True+ removed_hops, interrupted = await self._finalize_successful_discovery(+ previous,+ config,+ source,+ discovered,+ force=force,+ )+ committed = True+ except asyncio.CancelledError:+ committed = self._persisted_credential(+ self.store.load(),+ source.id,+ replacement_ref,+ )+ if not committed:+ await _rollback_replacement_before_settling(+ self,+ source.id,+ replacement_ref,+ old_credential_ref,+ old_revocation_recorded=old_revocation_recorded,+ )+ raise+ except Exception:+ if not committed:+ await self._rollback_replacement(+ source.id,+ replacement_ref,+ old_credential_ref,+ old_revocation_recorded=old_revocation_recorded,+ )+ raise- @staticmethod- def _selected_targets(agent: ModelHubAgentSupplyConfig) -> list[tuple[Optional[str], str]]:- if agent.backend == "opencode" and agent.menu:- targets = []- for identifier in agent.menu.checked:try:- provider, model_id = parse_opencode_model_id(identifier)- except ValueError:- continue+ await self.adapter.revoke_credential(old_credential_ref)+ except Exception:+ passelse:- targets.append((provider, model_id))- return targets- return [(None, mapping.target_model_id) for mapping in agent.mappings if mapping.enabled]-- def _only_selected_model_supplier(- self,- config: ModelHubConfig,- source: ModelHubSourceConfig,- model_id: str,- ) -> bool:- for agent in config.agents.values():- if agent.mode != "hub":- continue- for provider, target_model_id in self._selected_targets(agent):- if target_model_id != model_id or (- provider is not None and provider != opencode_provider_id(source.vendor)- ):- continue- suppliers = [- candidate- for candidate in config.sources- if self._eligible_for_agent(candidate, agent.backend)- and (provider is None or opencode_provider_id(candidate.vendor) == provider)- and any(item.id == model_id for item in candidate.models)- ]- if len(suppliers) == 1 and suppliers[0].id == source.id:- return True- return False+ try:+ self.revocations.remove(source.id, old_credential_ref)+ except OSError:+ pass+ else:+ self._save_config(config)+ return {+ "source": source.to_payload(),+ "removed_hops": removed_hops,+ "interrupted": interrupted,+ }def _protected_menu_models(self,@@ -1761,14 +2282,6 @@ class ModelHubService:normalized = str(model_id or "").strip()if not normalized:return- if backend == "opencode" and agent.menu is not None:- normalized = (- normalize_opencode_requested_model(- normalized,- tuple(agent.menu.checked),- )- or normalized- )names = protected.setdefault(normalized, [])if named_agent is not None and named_agent not in names:names.append(named_agent)@@ -1780,17 +2293,29 @@ class ModelHubService:for identifier in agent.menu.checked:add(identifier)else:- for mapping in agent.mappings:- if mapping.enabled:- add(mapping.builtin_id)+ for model_id in _builtin_model_ids(backend):+ add(model_id)+ for model_id in agent.routes:+ add(model_id)return protected- def _would_interrupt(self, config: ModelHubConfig) -> list[dict]:+ def _would_interrupt(+ self,+ config: ModelHubConfig,+ *,+ newly_empty_routes: frozenset[tuple[str, str]] = frozenset(),+ ) -> list[dict]:gaps: list[dict] = []for backend_name in MODEL_HUB_BACKENDS:backend = cast(BackendName, backend_name)unavailable_source_ids = self._unavailable_native_sources(config, backend)for model_id, agents in self._protected_menu_models(config, backend).items():+ route = config.agents[backend].routes.get(model_id)+ if (+ (route is None or not route.hops)+ and (backend, model_id) not in newly_empty_routes+ ):+ continueresolution = resolve_model_hub_turn(config,backend,@@ -1809,21 +2334,148 @@ class ModelHubService:)return gaps- async def delete_source(self, source_id: str, *, force: bool = False) -> None:+ def _introduced_interruptions(+ self,+ previous: ModelHubConfig,+ updated: ModelHubConfig,+ *,+ newly_empty_routes: frozenset[tuple[str, str]] = frozenset(),+ ) -> list[dict]:+ baseline = {+ (item["backend"], item["model_id"])+ for item in self._would_interrupt(previous)+ }+ return [+ item+ for item in self._would_interrupt(+ updated,+ newly_empty_routes=newly_empty_routes,+ )+ if (item["backend"], item["model_id"]) not in baseline+ ]++ def _invalidated_route_hops(+ self,+ config: ModelHubConfig,+ source_id: str,+ ) -> list[dict]:+ return [+ {+ "backend": backend,+ "menu_model": menu_model,+ "source_id": source_id,+ "model_id": hop.model_id,+ }+ for backend in MODEL_HUB_BACKENDS+ for menu_model, route in config.agents[backend].routes.items()+ for hop in route.hops+ if hop.source_id == source_id+ and inspect_exact_hop(+ config,+ cast(BackendName, backend),+ menu_model,+ hop,+ now=self.now(),+ unavailable_source_ids=self._unavailable_native_sources(+ config,+ cast(BackendName, backend),+ ),+ ).reason+ == "model_unsupported"+ ]++ @staticmethod+ def _prune_invalidated_route_hops(+ config: ModelHubConfig,+ invalidated_hops: list[dict],+ ) -> None:+ identities = {+ (+ item["backend"],+ item["menu_model"],+ item["source_id"],+ item["model_id"],+ )+ for item in invalidated_hops+ }+ for backend in MODEL_HUB_BACKENDS:+ for menu_model, route in config.agents[backend].routes.items():+ route.hops = tuple(+ hop+ for hop in route.hops+ if (backend, menu_model, hop.source_id, hop.model_id)+ not in identities+ )++ def _guard_inventory_mutation(+ self,+ previous: ModelHubConfig,+ updated: ModelHubConfig,+ source_id: str,+ *,+ force: bool,+ ) -> tuple[list[dict], list[dict]]:+ would_remove_hops = self._invalidated_route_hops(updated, source_id)+ would_interrupt = self._introduced_interruptions(previous, updated)+ if (would_remove_hops or would_interrupt) and not force:+ raise ModelHubError(+ (+ "source_model_in_route_chain"+ if would_remove_hops+ else "source_last_supplier"+ ),+ status=409,+ data={+ "would_remove_hops": would_remove_hops,+ "would_interrupt": would_interrupt,+ },+ )+ if would_remove_hops:+ self._prune_invalidated_route_hops(updated, would_remove_hops)+ return would_remove_hops, would_interrupt++ async def delete_source(self, source_id: str, *, force: bool = False) -> dict:async with self._mutation_lock:previous = self.store.load()config = self._clone_config(previous)source = self._source(config, source_id)+ removed_hops = [+ {"backend": backend, "menu_model": model_id, "source_id": source_id, "model_id": hop.model_id}+ for backend in MODEL_HUB_BACKENDS+ for model_id, route in config.agents[backend].routes.items()+ for hop in route.hops+ if hop.source_id == source_id+ ]config.sources = [item for item in config.sources if item.id != source_id]for agent in config.agents.values():agent.sources.order = [item for item in agent.sources.order if item != source_id]- config.refresh_follow_orders()- would_interrupt = self._would_interrupt(config)+ for model_id, route in list(agent.routes.items()):+ route.hops = tuple(hop for hop in route.hops if hop.source_id != source_id)+ agent.routes[model_id] = route+ newly_empty_routes = frozenset(+ (item["backend"], item["menu_model"])+ for item in removed_hops+ if not config.agents[item["backend"]].routes[item["menu_model"]].hops+ )+ would_interrupt = self._introduced_interruptions(+ previous,+ config,+ newly_empty_routes=newly_empty_routes,+ )+ if removed_hops and not force:+ raise ModelHubError(+ "source_in_route_chain",+ status=409,+ data={+ "would_remove_hops": removed_hops,+ "would_interrupt": would_interrupt,+ },+ )if would_interrupt and not force:raise ModelHubError("source_last_supplier",status=409,- data={"would_interrupt": would_interrupt},+ data={"would_remove_hops": [], "would_interrupt": would_interrupt},)self._prune_unavailable_agent_references(config)if source.credential_ref:@@ -1840,7 +2492,7 @@ class ModelHubService:except ModelHubError:restored = Falsetry:- self.store.save(previous)+ self._save_config(previous)restored = Trueself._engine_synced = Falseawait self._sync_sources(previous)@@ -1854,8 +2506,9 @@ class ModelHubService:raiseif source.credential_ref:self.revocations.remove(source.id, source.credential_ref)+ return {"removed_hops": removed_hops, "interrupted": would_interrupt}- async def refresh_source(self, source_id: str) -> tuple[dict, int]:+ async def refresh_source(self, source_id: str, *, force: bool = False) -> dict:async with self._mutation_lock:previous = self.store.load()config = self._clone_config(previous)@@ -1864,12 +2517,13 @@ class ModelHubService:raise ModelHubError("discovery_failed")try:model_ids = await self._discover(source)- manual = [- model- for model in source.models- if model.provenance == "manual"- ]- self._apply_discovered_models(source, manual, model_ids)+ removed_hops, would_interrupt = await self._finalize_successful_discovery(+ previous,+ config,+ source,+ model_ids,+ force=force,+ )except ModelHubError as exc:if exc.code != "discovery_failed":raise@@ -1877,7 +2531,7 @@ class ModelHubService:status="error",detail_key="models.source.error.unclassified",)- self.store.save(config)+ self._save_config(config)self._record_event(agent="system",kind="needs_action",@@ -1888,9 +2542,11 @@ class ModelHubService:now=self.now(),)raise- source.state = ModelHubSourceStateConfig(status="standby")- await self._commit_synced(previous, config)- return source.to_payload(), len(model_ids)+ return {+ "source": source.to_payload(),+ "removed_hops": removed_hops,+ "interrupted": would_interrupt,+ }@staticmethoddef _eligible_for_agent(source: ModelHubSourceConfig, backend: str) -> bool:@@ -1900,12 +2556,10 @@ class ModelHubService:def _source_eligibility(cls, source: ModelHubSourceConfig, backend: str) -> dict:if cls._eligible_for_agent(source, backend):reason_key = None- elif source.kind == "subscription" and backend == "opencode":- reason_key = "models.eligibility.opencode_api_key_only"elif source.kind == "subscription":reason_key = "models.eligibility.subscription_wrong_client"else:- reason_key = "models.eligibility.consent_required"+ reason_key = "models.eligibility.subscription_wrong_client"return {"source_id": source.id,"eligible": reason_key is None,@@ -1942,140 +2596,112 @@ class ModelHubService:async def set_agent_sources(self, backend: str, payload: object) -> dict:if backend not in MODEL_HUB_BACKENDS or not isinstance(payload, dict):raise self._invalid_source_order()- policy = payload.get("policy")- if policy == "follow":- if set(payload) != {"policy"}:- rejected = sorted(set(payload) - {"policy"})- raise self._invalid_source_order(- rejected_keys=rejected,- )- elif policy == "custom":- if set(payload) != {"policy", "order"}:- rejected = sorted(set(payload) - {"policy", "order"})- if rejected:- raise self._invalid_source_order(- rejected_keys=rejected,- )- raise self._invalid_source_order()- else:+ if set(payload) != {"order"}:+ rejected = sorted(set(payload) - {"order"})+ raise self._invalid_source_order(rejected_keys=rejected)+ order = payload.get("order")+ if not isinstance(order, list):raise self._invalid_source_order()async with self._mutation_lock:previous = self.store.load()config = self._clone_config(previous)agent = self._agent(config, backend)- if policy == "follow":- agent.sources.policy = "follow"- agent.sources.order = config.recommended_source_order(backend)- else:- order = payload.get("order")- if not isinstance(order, list):+ seen: set[str] = set()+ by_id = {source.id: source for source in config.sources}+ for source_id in order:+ if (+ not isinstance(source_id, str)+ or source_id in seen+ or source_id not in by_id+ or not self._eligible_for_agent(by_id[source_id], backend)+ ):raise self._invalid_source_order()- seen: set[str] = set()- by_id = {source.id: source for source in config.sources}- for source_id in order:- if (- not isinstance(source_id, str)- or source_id in seen- or source_id not in by_id- or not self._eligible_for_agent(by_id[source_id], backend)- ):- raise self._invalid_source_order()- seen.add(source_id)- agent.sources.policy = "custom"- agent.sources.order = list(order)- self.store.save(config)+ seen.add(source_id)+ agent.sources.order = list(order)+ self._save_config(config)return self._agent_payload(config, agent)def get_agent_sources(self, backend: str) -> dict:config = self.store.load()return self._agent_payload(config, self._agent(config, backend))- def _available_model_ids(self, config: ModelHubConfig, backend: str) -> set[str]:- return {- model.id- for source in config.sources- if self._eligible_for_agent(source, backend)- for model in source.models- }-- def _mapping_target_sources(- self,- config: ModelHubConfig,- backend: str,- model_id: str,- ) -> list[str]:- by_id = {source.id: source for source in config.sources}- return [- source_id- for source_id in config.recommended_source_order(backend)- if any(- model.id == model_id- for model in by_id[source_id].models- )- ]+ async def set_agent_chain(self, backend: str, model_id: object, payload: object) -> dict:+ if (+ backend not in MODEL_HUB_BACKENDS+ or not isinstance(model_id, str)+ or not model_id.strip()+ or not isinstance(payload, dict)+ or set(payload) - {"hops", "force"}+ or "hops" not in payload+ or ("force" in payload and not isinstance(payload["force"], bool))+ ):+ raise ModelHubError("mapping_target_unavailable", status=409)+ try:+ route = ModelHubRouteConfig.from_payload({"hops": payload["hops"]})+ except (TypeError, ValueError):+ raise ModelHubError("mapping_target_unavailable", status=409) from None- def _opencode_target_sources(- self,- config: ModelHubConfig,- identifier: str,- ) -> list[str]:- by_id = {source.id: source for source in config.sources}- return [- source_id- for source_id in config.recommended_source_order("opencode")- if any(- opencode_model_id(by_id[source_id].vendor, model.id)- == identifier- for model in by_id[source_id].models+ async with self._mutation_lock:+ previous = self.store.load()+ config = self._clone_config(previous)+ agent = self._agent(config, backend)+ if agent.mode == "direct":+ raise self._direct_mode_error()+ if model_id not in self._agent_menu_model_ids(agent):+ raise ModelHubError("mapping_target_unavailable", status=409)+ by_id = {source.id: source for source in config.sources}+ old_route = agent.routes.get(model_id, ModelHubRouteConfig())+ old_pairs = {(hop.source_id, hop.model_id) for hop in old_route.hops}+ for hop in route.hops:+ source = by_id.get(hop.source_id)+ if source is None or not self._eligible_for_agent(source, backend):+ raise ModelHubError("mapping_target_unavailable", status=409)+ if (hop.source_id, hop.model_id) not in old_pairs and not any(+ model.id == hop.model_id for model in source.models+ ):+ raise ModelHubError("mapping_target_unavailable", status=409)+ removed_hops = [+ {+ "backend": backend,+ "menu_model": model_id,+ "source_id": hop.source_id,+ "model_id": hop.model_id,+ }+ for hop in old_route.hops+ if (hop.source_id, hop.model_id)+ not in {(item.source_id, item.model_id) for item in route.hops}+ ]+ agent.routes[model_id] = route+ interrupted = self._introduced_interruptions(+ previous,+ config,+ newly_empty_routes=(+ frozenset({(backend, model_id)})+ if old_route.hops and not route.hops+ else frozenset()+ ),)- ]-- @staticmethod- def _enroll_target_sources(- config: ModelHubConfig,- agent: ModelHubAgentSupplyConfig,- target_source_groups: list[list[str]],- ) -> None:- effective_order = config.effective_source_order(agent.backend)- enrolled = set(effective_order)- appended = []- for source_ids in target_source_groups:- if any(source_id in enrolled for source_id in source_ids):- continue- selected_source_id = source_ids[0]- enrolled.add(selected_source_id)- appended.append(selected_source_id)- if not appended:- return- agent.sources.policy = "custom"- agent.sources.order = [*effective_order, *appended]-- def _available_opencode_identifiers(self, config: ModelHubConfig) -> set[str]:- return {- opencode_model_id(source.vendor, model.id)- for source in config.sources- if self._eligible_for_agent(source, "opencode")- for model in source.models- }+ if interrupted and payload.get("force") is not True:+ raise ModelHubError(+ "source_last_supplier",+ status=409,+ data={+ "would_remove_hops": removed_hops,+ "would_interrupt": interrupted,+ },+ )+ self._save_config(config)+ return {+ "chain": self._agent_chain(config, backend, model_id),+ "removed_hops": removed_hops,+ "interrupted": interrupted,+ }def _prune_unavailable_agent_references(self, config: ModelHubConfig) -> None:- for agent in config.agents.values():- if agent.menu_kind == "fixed":- available = self._available_model_ids(config, agent.backend)- agent.mappings = [- mapping- for mapping in agent.mappings- if mapping.target_model_id in available- ]- opencode_menu = config.agents["opencode"].menu- if opencode_menu is not None:- available = self._available_opencode_identifiers(config)- opencode_menu.checked = [- identifier- for identifier in opencode_menu.checked- if identifier in available- ]+ # Route membership is user configuration. Inventory refresh and source+ # deletion may annotate or remove exact hops, but never re-match menus.+ returndef _agent_payload(self, config: ModelHubConfig, agent: ModelHubAgentSupplyConfig) -> dict:backend = cast(BackendName, agent.backend)@@ -2096,15 +2722,7 @@ class ModelHubService:model_supply = [{"model_id": model_id,- "chain_length": len(- resolve_model_hub_turn(- config,- backend,- model_id,- now=self.now(),- unavailable_source_ids=unavailable_source_ids,- ).matching_sources- ),+ "chain_length": len(agent.routes.get(model_id, ModelHubRouteConfig()).hops),}for model_id in menu_model_ids]@@ -2172,7 +2790,9 @@ class ModelHubService:})agent_payload = agent.to_payload()- agent_payload.pop("mappings", None)+ agent_payload["routes"] = (+ agent_payload["routes"] if agent.mode == "hub" else None+ )return {**agent_payload,"selected_by_agent": selected_by_agent,@@ -2201,40 +2821,7 @@ class ModelHubService:config = self.store.load()agent = self._agent(config, backend)agent.mode = mode- self.store.save(config)- return self._agent_payload(config, agent)-- async def set_mappings(self, backend: str, mappings: object) -> dict:- async with self._mutation_lock:- config = self.store.load()- agent = self._agent(config, backend)- if agent.menu_kind != "fixed" or not isinstance(mappings, list):- raise ModelHubError("mapping_target_unavailable")- try:- parsed = [ModelHubMappingConfig.from_payload(mapping) for mapping in mappings]- except ValueError as exc:- raise ModelHubError("mapping_target_unavailable") from exc- target_sources = {- mapping.target_model_id: self._mapping_target_sources(- config,- backend,- mapping.target_model_id,- )- for mapping in parsed- }- if any(not source_ids for source_ids in target_sources.values()):- raise ModelHubError("mapping_target_unavailable")- self._enroll_target_sources(- config,- agent,- [- target_sources[mapping.target_model_id]- for mapping in parsed- if mapping.enabled- ],- )- agent.mappings = parsed- self.store.save(config)+ self._save_config(config)return self._agent_payload(config, agent)async def set_opencode_menu(self, menu: object) -> dict:@@ -2242,28 +2829,21 @@ class ModelHubService:config = self.store.load()agent = config.agents["opencode"]try:- parsed = ModelHubMenuConfig.from_payload(cast(dict, menu))+ parsed_menu = ModelHubMenuConfig.from_payload(cast(dict, menu))+ candidate = agent.to_payload()+ candidate["menu"] = parsed_menu.to_payload()+ candidate_routes = cast(dict, candidate["routes"])+ for identifier in parsed_menu.checked:+ candidate_routes.setdefault(identifier, ModelHubRouteConfig().to_payload())+ parsed = ModelHubAgentSupplyConfig.from_payload(+ candidate,+ expected_backend="opencode",+ )except (TypeError, ValueError) as exc:raise ModelHubError("mapping_target_unavailable") from exc- target_sources = {- identifier: self._opencode_target_sources(- config,- identifier,- )- for identifier in parsed.checked- }- if any(not source_ids for source_ids in target_sources.values()):- raise ModelHubError("mapping_target_unavailable")- self._enroll_target_sources(- config,- agent,- [- target_sources[identifier]- for identifier in parsed.checked- ],- )- agent.menu = parsed- self.store.save(config)+ agent.menu = parsed.menu+ agent.routes = parsed.routes+ self._save_config(config)return self._agent_payload(config, agent)@staticmethod@@ -2368,16 +2948,47 @@ class ModelHubService:raise ModelHubError("mapping_target_unavailable", status=404)if model.provenance == "discovered":raise ModelHubError("source_model_managed_upstream", status=409)- if not force and self._only_selected_model_supplier(config, source, model_id):- raise ModelHubError("mode_switch_blocked", status=409)+ removed_hops = [+ {+ "backend": backend,+ "menu_model": menu_model,+ "source_id": source.id,+ "model_id": model_id,+ }+ for backend in MODEL_HUB_BACKENDS+ for menu_model, route in config.agents[backend].routes.items()+ for hop in route.hops+ if hop.source_id == source.id and hop.model_id == model_id+ ]source.models = [itemfor item in source.modelsif item.id != model_id]- self._prune_unavailable_agent_references(config)+ would_interrupt = self._introduced_interruptions(previous, config)+ if (removed_hops or would_interrupt) and not force:+ raise ModelHubError(+ "source_model_in_route_chain" if removed_hops else "source_last_supplier",+ status=409,+ data={+ "would_remove_hops": removed_hops,+ "would_interrupt": would_interrupt,+ },+ )+ if force and removed_hops:+ for agent in config.agents.values():+ for route in agent.routes.values():+ route.hops = tuple(+ hop+ for hop in route.hops+ if not (hop.source_id == source.id and hop.model_id == model_id)+ )await self._commit_synced(previous, config)- return source.to_payload()+ return {+ "source": source.to_payload(),+ "removed_hops": removed_hops,+ "interrupted": would_interrupt,+ }def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:events = self.events.list(limit=limit, before=before)@@ -2431,51 +3042,52 @@ class ModelHubService:unavailable_source_ids=unavailable,)chain: list[dict] = []- for source in resolution.matching_sources:+ for inspection in resolution.inspected_hops:+ source = inspection.source+ if source is None:+ chain.append(+ {+ "source_id": inspection.source_id,+ "model_id": inspection.model_id,+ "channel": "hub",+ "health": "error",+ "runnable": False,+ "reason": inspection.reason,+ "retry_at": None,+ }+ )+ continuestatus = source.state.statushealth = ("healthy"if status in {"active", "standby"}else status)- runnable = source_runnable(- source,- now=now,- unavailable_source_ids=unavailable,- )- effective_model = (- resolution.model_for_source(source) or resolution.target_model- )- resolved_model = (- effective_model- if effective_model != resolution.requested_model- else None- )chain.append({"source_id": source.id,+ "model_id": inspection.model_id,"channel": source.supply_channel,- "via_mapping": resolution.mapping_applied,- "resolved_model_id": resolved_model,"health": health,- "runnable": runnable,- "reason": (- "native_cli_unavailable"- if source.id in unavailable- else None- ),- "retry_at": (- source.state.retry_at- if health == "cooldown"- else None- ),+ "runnable": inspection.runnable,+ "reason": inspection.reason,+ "retry_at": inspection.retry_at,})+ current = next(+ (+ {"source_id": item["source_id"], "model_id": item["model_id"]}+ for item in chain+ if item["runnable"]+ ),+ None,+ )return {"contract_version": AGENT_CHAIN_CONTRACT_VERSION,"backend": backend,"model_id": resolution.requested_model or model_id,"chain": chain,+ "current": current,"supply_state": self._chain_supply_state(chain),}@@ -2492,10 +3104,7 @@ class ModelHubService:) -> ModelHubRequest:# A probe enters the same translation seam as a live backend turn, so# its payload must be shaped in the backend's client protocol.- request_protocol = {- "claude": "anthropic",- "codex": "openai_responses",- }.get(backend, source.protocol)+ request_protocol = _FIXED_BACKEND_PROTOCOLS.get(backend, source.protocol)if request_protocol == "anthropic":payload = {"model": model_id,@@ -2534,8 +3143,15 @@ class ModelHubService:for value in (outcome.error_code, outcome.redacted_message)if isinstance(value, str)).lower()- if outcome.http_status == 401:- return "models.source.needs_action.oauth_expired", "credential_expired"+ if outcome.http_status == 401 and decision.reason in {+ "credential_expired",+ "credential_revoked",+ }:+ detail_key = {+ "credential_expired": "models.source.needs_action.oauth_expired",+ "credential_revoked": "models.source.needs_action.credential_revoked",+ }[decision.reason]+ return detail_key, cast(EventReason, decision.reason)if outcome.http_status == 402 or "balance" in text:return "models.source.needs_action.balance_exhausted", "balance_exhausted"if outcome.http_status == 403 and any(@@ -2578,7 +3194,7 @@ class ModelHubService:status=status,detail_key=detail_key,)- self.store.save(config)+ self._save_config(config)if not unchanged:self._record_event(agent=cast(EventAgent, backend),@@ -2629,10 +3245,7 @@ class ModelHubService:},)source = self._source(config, candidate_payload["source_id"])- resolved_model = (- candidate_payload["resolved_model_id"]- or chain_payload["model_id"]- )+ resolved_model = candidate_payload["model_id"]if source.supply_channel == "native_cli":ready = self.native_source_ready(cast(BackendName, backend),@@ -2646,7 +3259,6 @@ class ModelHubService:"source_id": source.id,"model_id": resolved_model,"latency_ms": None,- "via_mapping": bool(candidate_payload["via_mapping"]),"error": (Noneif ready@@ -2669,7 +3281,7 @@ class ModelHubService:async for _chunk in handle.stream:passoutcome = await self._engine_call(handle.outcome())- decision = classify_outcome(outcome)+ decision = await self._classify_source_outcome(source, outcome)if decision.action == "refresh":handle = await self._engine_call(self.adapter.invoke(@@ -2725,7 +3337,6 @@ class ModelHubService:"source_id": source.id,"model_id": resolved_model,"latency_ms": latency_ms,- "via_mapping": bool(candidate_payload["via_mapping"]),"error": error_key,}@@ -2911,10 +3522,10 @@ class ModelHubService:status="needs_action",detail_key="models.source.needs_action.oauth_expired",)- self.store.save(config)+ self._save_config(config)def restore_after_spawn_failure() -> None:- self.store.save(previous)+ self._save_config(previous)return restore_after_spawn_failure@@ -2939,7 +3550,7 @@ class ModelHubService:channel,source.id,source.vendor,- experimental_consent=source.experimental_consent_at is not None,+ experimental_consent=False,intent="reauth",recovered=recovered,replace_flow_id=replace_pending_flow_id,@@ -2966,14 +3577,29 @@ class ModelHubService:channel = payload.get("channel") if isinstance(payload, dict) else Noneif not isinstance(vendor, str) or channel not in {"native_cli", "hub"}:raise ModelHubError("flow_not_found", status=400)- consented = payload.get("experimental_consent") is True- if "experimental_consent" in payload and not isinstance(payload.get("experimental_consent"), bool):- raise ModelHubError("consent_required")- if channel == "hub" and not consented:- raise ModelHubError("consent_required", status=409)- if consented and channel != "hub":- raise ModelHubError("consent_required")+ try:+ vendor = normalize_model_hub_vendor_id(vendor)+ except ValueError:+ raise ModelHubError("flow_not_found", status=400) from Noneoauth_channel = cast(OAuthChannel, channel)+ if oauth_channel == "native_cli":+ backend = _NATIVE_VENDOR_BACKENDS.get(vendor)+ if backend is not None:+ existing = next(+ (+ source+ for source in self.store.load().sources+ if source.supply_channel == "native_cli"+ and source_eligible_for_backend(source, cast(BackendName, backend))+ ),+ None,+ )+ if existing is not None:+ raise ModelHubError(+ "native_source_already_exists",+ status=409,+ data={"existing_source_id": existing.id},+ )pending_source_id = _source_id()flow = await self._oauth_call(self._oauth_adapter(oauth_channel).start_oauth(pending_source_id, vendor)@@ -2985,13 +3611,8 @@ class ModelHubService:oauth_channel,pending_source_id,vendor,- experimental_consent=consented,+ experimental_consent=False,)- if channel == "hub" and consented:- async with self._mutation_lock:- config = self.store.load()- config.subscription_hub_experimental = True- self.store.save(config)return {"flow": _oauth_payload(flow, channel=channel)}def _oauth_result(@@ -3165,7 +3786,7 @@ class ModelHubService:async def migration_apply(self, item_ids: object) -> dict:try:- applied = await apply_native_migration(+ applied, added_to = await apply_native_migration(self,item_ids,mask_credential=_mask_credential,@@ -3173,7 +3794,15 @@ class ModelHubService:)except MigrationConflictError:raise ModelHubError("migration_item_conflict", status=409)- return {"applied": applied, "sources": self.list_sources()}+ except ModelHubError as exc:+ if exc.code != "discovery_failed":+ raise+ raise ModelHubError("migration_item_conflict", status=409) from None+ return {+ "applied": applied,+ "sources": self.list_sources(),+ "added_to": added_to,+ }async def _recover_resolution_sources(self,@@ -3206,7 +3835,7 @@ class ModelHubService:now=self.now(),)if config_changed:- self.store.save(config)+ self._save_config(config)async def _cooldown(self,@@ -3229,7 +3858,7 @@ class ModelHubService:retry_at=(self.now() + timedelta(seconds=decision.cooldown_seconds)).isoformat(),detail_key=detail_key or f"models.source.cooldown.{decision.reason}",)- self.store.save(config)+ self._save_config(config)if not already_cooling:self._record_event(agent=agent,@@ -3284,6 +3913,72 @@ class ModelHubService:return handle, Nonereturn handle, await self._engine_call(handle.outcome())+ async def _classify_source_outcome(+ self,+ source: ModelHubSourceConfig,+ outcome: RawCallOutcome,+ ) -> ResolutionDecision:+ """Apply the credential-capability branch of the section 4.3 matrix once."""++ decision = classify_outcome(outcome)+ if decision.action != "refresh":+ return decision+ credential_ref = source.credential_ref+ if not credential_ref:+ raise ModelHubError("engine_down", status=503)+ refreshable = await self._engine_call(+ self.adapter.credential_supports_refresh(credential_ref)+ )+ if refreshable:+ return decision+ return ResolutionDecision("fallback", reason="credential_revoked")++ @staticmethod+ def _request_reasoning_effort(request: Mapping[str, Any]) -> str | None:+ direct = request.get("reasoning_effort")+ if isinstance(direct, str) and direct:+ return direct+ reasoning = request.get("reasoning")+ if isinstance(reasoning, Mapping):+ nested = reasoning.get("effort")+ if isinstance(nested, str) and nested:+ return nested+ return None++ @staticmethod+ def _request_for_exact_reasoning_effort(+ request: Mapping[str, Any],+ source: ModelHubSourceConfig,+ model_id: str,+ ) -> Mapping[str, Any]:+ requested = ModelHubService._request_reasoning_effort(request)+ model = next((item for item in source.models if item.id == model_id), None)+ exact = (+ requested+ if requested is not None+ and model is not None+ and requested in model.reasoning_efforts+ else None+ )+ payload = dict(request)+ changed = False+ if "reasoning_effort" in payload:+ payload["reasoning_effort"] = exact+ changed = True+ reasoning = payload.get("reasoning")+ if isinstance(reasoning, Mapping) and "effort" in reasoning:+ payload["reasoning"] = {**reasoning, "effort": exact}+ changed = True+ if not changed:+ return request+ if isinstance(request, ModelHubRequest):+ return ModelHubRequest(+ payload,+ protocol=request.protocol,+ headers=request.headers,+ )+ return payload+async def resolve(self,*,@@ -3335,19 +4030,9 @@ class ModelHubService:),supply_channel=supply_channel,)- target_model = resolution.target_modelevent_agent = cast(EventAgent, backend)- if resolution.mapping_applied:- self._record_event(- agent=event_agent,- kind="mapping_applied",- model_id=target_model,- reason="mapping",- from_label=model_id,- now=self.now(),- )- candidates = list(resolution.candidates)- if not candidates:+ candidate_hops = list(resolution.candidate_hops)+ if not candidate_hops:supply_state = ("waiting"if resolution.supply_status == "waiting"@@ -3361,9 +4046,18 @@ class ModelHubService:failed_source: Optional[ModelHubSourceConfig] = Nonefailed_reason: Optional[EventReason] = None- for source in candidates:- target_model = (- resolution.model_for_source(source) or resolution.target_model+ globally_blocked_source_ids: set[str] = set()+ for inspection in candidate_hops:+ source = inspection.source+ target_model = inspection.model_id+ if source is None or target_model is None:+ raise AssertionError("runnable hop must have an exact identity")+ if source.id in globally_blocked_source_ids:+ continue+ exact_request = self._request_for_exact_reasoning_effort(+ request,+ source,+ target_model,)if source.supply_channel == "native_cli":self._emit_switch(@@ -3387,14 +4081,14 @@ class ModelHubService:source.id,target_model,"hub",- resolution.mapping_applied,+ False,None,None,)handle, outcome = await self._invoke(source=source,model_id=target_model,- request=request,+ request=exact_request,stream=stream,backend=backend,)@@ -3407,14 +4101,14 @@ class ModelHubService:source=source,)return ResolvedInvocation(source.id, target_model, handle, None)- decision = classify_outcome(outcome)+ decision = await self._classify_source_outcome(source, outcome)if decision.action == "refresh":# The engine refreshes its credential internally; L2 retries the# exact same source once and never falls through on a second 401.handle, outcome = await self._invoke(source=source,model_id=target_model,- request=request,+ request=exact_request,stream=stream,backend=backend,)@@ -3433,7 +4127,7 @@ class ModelHubService:source.id,target_model,"hub",- resolution.mapping_applied,+ False,outcome,decision,)@@ -3484,6 +4178,8 @@ class ModelHubService:detail_key=detail_key,reason=event_reason,)+ if event_reason != "permission_denied":+ globally_blocked_source_ids.add(source.id)failed_source = sourcefailed_reason = event_reasoncontinuediff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex c7dde7079..d8609f44a 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -41,8 +41,11 @@ Contract prose points to those authorities and does not add branches.or Agent runtime configuration. Hub-held material is referenced by an opaque enginecredential id; native credentials remain in the sanctioned CLI store.2. Every persisted Source has a protocol proved by a real upstream response before- commit. Vendor names, Base URLs, and manual hints may order probes but cannot create- a saved protocol value.+ commit. `POST /api/models/sources/observe` is the non-persisting API-key observation+ surface; API-key `POST /api/models/sources` performs the same observation before+ its independent committed credential provisioning, while subscription OAuth uses+ its vendor-specific observation flow. Vendor names, Base URLs, and manual hints may+ order probes but cannot create a saved protocol value.3. Every Source/model reference is canonical and referentially valid at write time.Unchanged stale Route hops may be retained or reordered, but new or changed pairsmust validate.@@ -77,11 +80,12 @@ comparison. A gate may not report success by comparing stale input with itself.## Version closure-The terminal value 5 must coexist in these ten locations on the same tested head:+The terminal value 5 must coexist in all registered version locations on the same tested head:- `mirror-registry.json`- `agent-chain.schema.json`- `probe-result.schema.json`+- `observation-result.schema.json`- `runtime-dependency.schema.json`- `turn-provenance.schema.json`- `core/handlers/model_hub/service.py`@@ -103,8 +107,9 @@ revision; the discovering lane does not reinterpret or edit the contract in plac| --- | --- || `source.schema.json` | Source identity, channel, three protocols, state, usage, inventory, credential reference, and audit metadata. || `agent-supply.schema.json` | Backend mode, explicit policy-free Source order, configuration eligibility, model-supply and backend-health projections. |-| `agent-chain.schema.json` | Read projection of exact stored hops plus current runnability, blockers, retry metadata, and model supply state. |-| `probe-result.schema.json` | Saved recovery probes, Add-time connectivity/protocol observation, and route probes. |+| `agent-chain.schema.json` | Read projection of exact stored hops plus current execution position, runnability, blockers, retry metadata, and model supply state. |+| `probe-result.schema.json` | Saved recovery probes and route probes over exact configured hops. |+| `observation-result.schema.json` | Non-persisting Add-time connectivity, authentication, response-backed protocol, and inventory observation. || `turn-provenance.schema.json` | Exactly attributed turn attempts and terminal outcome; no policy or mapping discriminator. || `resolution-event.schema.json` | Pull-feed Source/resolution records and their closed reason/detail vocabulary. || `oauth-flow.schema.json` | Subscription creation and re-auth presentation without secret material. |diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex aa5bc49ac..8757b91e8 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -14,7 +14,16 @@ from dataclasses import dataclassfrom enum import Enumfrom typing import Any, AsyncIterator, Literal, Mapping, Protocol, Sequence-# authority-consumer: protocol anthropic openai_responses openai_chat+SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")+OBSERVATION_OUTCOMES = (+ "observed",+ "ambiguous",+ "unreachable",+ "authentication_failed",+ "adapter_error",+ "timeout",+)+OBSERVATION_DISCOVERY_OUTCOMES = ("succeeded", "failed", "not_attempted")class EngineHealth(str, Enum):@@ -80,6 +89,157 @@ class RawCallOutcome:source_id: str+class ObservationOutcome(str, Enum):+ OBSERVED = OBSERVATION_OUTCOMES[0]+ AMBIGUOUS = OBSERVATION_OUTCOMES[1]+ UNREACHABLE = OBSERVATION_OUTCOMES[2]+ AUTHENTICATION_FAILED = OBSERVATION_OUTCOMES[3]+ ADAPTER_ERROR = OBSERVATION_OUTCOMES[4]+ TIMEOUT = OBSERVATION_OUTCOMES[5]+++class ObservationDiscovery(str, Enum):+ SUCCEEDED = OBSERVATION_DISCOVERY_OUTCOMES[0]+ FAILED = OBSERVATION_DISCOVERY_OUTCOMES[1]+ NOT_ATTEMPTED = OBSERVATION_DISCOVERY_OUTCOMES[2]+++@dataclass(frozen=True)+class SourceObservation:+ """Response-backed result of an unsaved Source observation."""++ outcome: ObservationOutcome+ reachable: bool | None+ authenticated: bool | None+ protocol: str | None+ discovery: ObservationDiscovery+ model_ids: tuple[str, ...]+++@dataclass(frozen=True)+class ObservationTerminalRule:+ """Complete legal product for one response-backed observation outcome."""++ reachable: frozenset[bool | None]+ authenticated: frozenset[bool | None]+ protocols: frozenset[str | None]+ discoveries: frozenset[ObservationDiscovery]+ models_must_be_empty: bool+++OBSERVATION_TERMINAL_RULES: Mapping[+ ObservationOutcome,+ ObservationTerminalRule,+] = {+ ObservationOutcome.OBSERVED: ObservationTerminalRule(+ reachable=frozenset({True}),+ authenticated=frozenset({True}),+ protocols=frozenset(SOURCE_PROTOCOLS),+ discoveries=frozenset(+ {+ ObservationDiscovery.SUCCEEDED,+ ObservationDiscovery.FAILED,+ }+ ),+ models_must_be_empty=False,+ ),+ ObservationOutcome.AMBIGUOUS: ObservationTerminalRule(+ reachable=frozenset({True}),+ authenticated=frozenset({True, None}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+ ObservationOutcome.UNREACHABLE: ObservationTerminalRule(+ reachable=frozenset({False}),+ authenticated=frozenset({None}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+ ObservationOutcome.AUTHENTICATION_FAILED: ObservationTerminalRule(+ reachable=frozenset({True}),+ authenticated=frozenset({False}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+ ObservationOutcome.ADAPTER_ERROR: ObservationTerminalRule(+ reachable=frozenset({True, None}),+ authenticated=frozenset({None}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+ ObservationOutcome.TIMEOUT: ObservationTerminalRule(+ reachable=frozenset({None}),+ authenticated=frozenset({None}),+ protocols=frozenset({None}),+ discoveries=frozenset({ObservationDiscovery.NOT_ATTEMPTED}),+ models_must_be_empty=True,+ ),+}+++def validate_source_observation(observation: object) -> SourceObservation:+ """Validate an adapter result against the sole terminal-product authority."""++ if not isinstance(observation, SourceObservation):+ raise TypeError("invalid SourceObservation")+ if not isinstance(observation.outcome, ObservationOutcome):+ raise ValueError("invalid SourceObservation outcome")+ if not isinstance(observation.discovery, ObservationDiscovery):+ raise ValueError("invalid SourceObservation discovery")+ if observation.reachable is not None and not isinstance(observation.reachable, bool):+ raise ValueError("invalid SourceObservation reachability")+ if observation.authenticated is not None and not isinstance(+ observation.authenticated,+ bool,+ ):+ raise ValueError("invalid SourceObservation authentication")+ if not isinstance(observation.model_ids, tuple) or any(+ not isinstance(model_id, str) or not model_id for model_id in observation.model_ids+ ):+ raise ValueError("invalid SourceObservation inventory")+ if len(set(observation.model_ids)) != len(observation.model_ids):+ raise ValueError("invalid SourceObservation inventory")++ rule = OBSERVATION_TERMINAL_RULES[observation.outcome]+ if (+ observation.reachable not in rule.reachable+ or observation.authenticated not in rule.authenticated+ or observation.protocol not in rule.protocols+ or observation.discovery not in rule.discoveries+ or (rule.models_must_be_empty and observation.model_ids)+ or (observation.discovery is ObservationDiscovery.FAILED and observation.model_ids)+ ):+ raise ValueError("invalid SourceObservation terminal product")+ return observation+++def make_source_observation(+ *,+ outcome: ObservationOutcome,+ reachable: bool | None,+ authenticated: bool | None,+ protocol: str | None,+ discovery: ObservationDiscovery,+ model_ids: Sequence[str],+) -> SourceObservation:+ """Construct an adapter result through the terminal-product authority."""++ return validate_source_observation(+ SourceObservation(+ outcome=outcome,+ reachable=reachable,+ authenticated=authenticated,+ protocol=protocol,+ discovery=discovery,+ model_ids=tuple(model_ids),+ )+ )++class RetainedMaterialDisposition(str, Enum):NONE = "none"FLOW_SOURCE_REF = "flow_source_ref"@@ -186,10 +346,42 @@ class EngineAdapter(Protocol):remains CLI-owned and has no ref on this seam."""...+ async def retarget_api_key_credential(+ self,+ credential_ref: str,+ vendor: str,+ protocol: str,+ base_url: str | None,+ ) -> str:+ """Copy an API-key credential to a fresh ref with a new target.++ The old ref remains valid until L2 commits the Source mutation and+ explicitly revokes it. The secret never crosses this adapter boundary,+ so Base URL replacement can be staged and rolled back transactionally.+ """+ ...++ async def credential_supports_refresh(self, credential_ref: str) -> bool:+ """Return the credential's actual engine-side refresh capability.++ This is a property of the stored credential, not an inference from+ vendor, Source kind, or an HTTP status.+ """+ ...+async def revoke_credential(self, credential_ref: str) -> None:"""Release the stored credential (source deletion / key replacement)."""...+ async def provision_transient_credential(+ self,+ vendor: str,+ secret: str,+ base_url: str | None,+ ) -> str:+ """Provision an unbound credential for an unsaved observation."""+ ...+async def cleanup_orphaned_oauth_material(self, credential_ref: str) -> bool:"""Retry cleanup for an ``orphan_ref`` without exposing a filename.@@ -215,9 +407,22 @@ class EngineAdapter(Protocol):base_url: str | None,credential_ref: str,) -> Sequence[str]:- """PROBE the upstream for supplyable model ids. Works before any- registration (test-and-add flow: provision → discover → persist →- sync); does not require or create a source binding."""+ """Refresh supplyable model ids for a saved Source using its stored protocol."""+ ...++ async def observe_source(+ self,+ vendor: str,+ base_url: str | None,+ credential_ref: str,+ protocol_order: Sequence[str],+ ) -> SourceObservation:+ """Observe connectivity, authentication, protocol, and inventory.++ ``protocol_order`` only orders probes. A returned protocol must be+ proven by a real upstream response; it cannot be inferred from vendor+ metadata, Base URL, or the first candidate.+ """...# --- subscription OAuth (channel-specific ownership) ------------------diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex 7e6fc0073..acd60ccd6 100644--- a/docs/plans/model-hub-contracts/agent-chain.schema.json+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json@@ -2,276 +2,102 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/agent-chain.schema.json","title": "AgentChain",- "description": "Read projection of one stored per-model Route chain. Items preserve the exact configured Source/model pairs and order; runtime adds only live health, runnability, blocker, and retry annotations. Cooling, missing, model-unsupported, Source-blocked, and process-unavailable native_cli hops remain visible at their configured positions. Runtime never derives membership, resolves aliases, or substitutes a model.",+ "description": "Read projection of one stored per-model Route chain. Items preserve exact configured Source/model pairs and order; runtime adds only live health, runnability, blocker, retry annotations, and the current execution position. Runtime never derives membership, resolves aliases, or substitutes a model.","type": "object",- "required": ["contract_version", "backend", "model_id", "chain", "supply_state"],+ "required": ["contract_version", "backend", "model_id", "chain", "current", "supply_state"],"additionalProperties": false,"properties": {"contract_version": { "const": 5 },"backend": { "enum": ["claude", "codex", "opencode"] },- "model_id": {- "type": "string",- "description": "The CALLER-FACING menu identifier — the built-in id for fixed-menu backends, the prefixed vendor/model identifier for open menus (never the bare resolved upstream id; see api.md → identifier rules). Mapping is applied inside; the caller does not pre-resolve it."+ "model_id": { "type": "string" },+ "current": {+ "anyOf": [+ { "type": "null" },+ {+ "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 }+ }+ }+ ],+ "description": "The live execution position, identified by one exact stored hop. It is null when no hop is current. Recovery may change this projection on the next turn without changing the stored chain."},"chain": {"type": "array",- "description": "Ordered, position 0 = highest in this backend's order. The next turn uses the FIRST item with `runnable: true`; role is positional and is never stored per source (a source can be serving one agent while merely standing by for another, so `active`/`standby` are not per-chain facts). Rendered with the same order-chip visuals as the agent row (frame V6 01). An EMPTY array is a first-class answer, not an error: the model is in the menu but no eligible source in this backend's order can supply it at all, so the UI flags 无来源可供 (spec §4.6) rather than offering a checkbox that silently fails. A non-empty chain with no `runnable` item is a different thing — `supply_state` on this object says which, at this model's grain. TWO STRUCTURAL INVARIANTS the schema cannot state, named here so they are enforced somewhere rather than assumed everywhere (07-29, review round 5): (1) `source_id` is UNIQUE across the chain — this is a FILTER over `sources.order`, which is itself `uniqueItems`, so a repeat means the projection double-counted; the damage is not cosmetic, since `chain.length` is what `AgentSupply.model_supply.chain_length` reports and 「2 个来源可供」 over one duplicated account is a false promise of redundancy, and a duplicate at the head would also make the resolver's fill-first retry the same cooling account twice before moving on. (2) The chain PRESERVES `sources.order` — a projection that filters must not reorder, or position 0 stops meaning 'spend first' and the drill-in shows a different order than the agent row it drilled in from. Draft-07 expresses neither: `uniqueItems` compares whole items, so two entries for one source with different `health` values are 'unique' to it, and no keyword can reference the ordering of another document. Both are therefore mechanical guards on the serializer (api.md → Serializer completeness), not schema keywords.",+ "description": "Exact stored hops in configured order. Empty is a first-class unconfigured route.","items": {"type": "object",- "required": ["source_id", "channel", "via_mapping", "resolved_model_id", "health", "runnable", "reason", "retry_at"],+ "required": ["source_id", "model_id", "channel", "health", "runnable", "reason", "retry_at"],"additionalProperties": false,- "allOf": [- {- "$comment": "v5 (07-29, escalations #2+#3): health that does not permit a turn pins runnability false. `needs_action` and `error` are stampless because neither recovers unattended. The orthogonal process-availability marker may still be present for an unavailable native_cli source; truth takes precedence over suppressing a redundant blocker.",- "if": {- "properties": { "health": { "enum": ["needs_action", "error"] } },- "required": ["health"]- },- "then": {- "properties": {- "runnable": { "const": false },- "retry_at": { "type": "null" }- }- }- },- {- "$comment": "v5 (07-29, escalations #2+#3): healthy ∧ hub ⇒ runnable. Hub process availability is definitionally true in v2, so round 4's assembler protection survives unchanged for this channel: a healthy hub member flagged unrunnable would hide supply the user owns. The old claim that no other filter remained was false only for native_cli. Evidence at master 807d1eee: core/handlers/model_hub/service.py:1223-1229 and modules/agents/model_hub.py:359-365 pass process-local unavailable_source_ids; core/handlers/model_hub/resolver.py:83-87 and 267-273 apply that filter after the capability chain is built.",- "if": {- "properties": {- "health": { "const": "healthy" },- "channel": { "const": "hub" }- },- "required": ["health", "channel"]- },- "then": {- "properties": {- "runnable": { "const": true },- "reason": { "type": "null" },- "retry_at": { "type": "null" }- }- }- },- {- "$comment": "v5 (07-29, escalations #2+#3): healthy ∧ native_cli pairs runnability with this process's CLI readiness. False requires the one closed reason; true requires null. Readiness is distinct from source-global health and is never persisted into it. Evidence at master 807d1eee: core/handlers/model_hub/resolver.py:252-273 keeps the source in matching_sources while excluding unavailable ids from candidates, and lines 95-116 classifies the resulting no-candidate state as interrupted rather than waiting.",- "if": {- "properties": {- "health": { "const": "healthy" },- "channel": { "const": "native_cli" },- "runnable": { "const": false }+ "properties": {+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "model_id": { "type": "string", "minLength": 1 },+ "channel": { "enum": ["hub", "native_cli"] },+ "health": { "enum": ["healthy", "cooldown", "needs_action", "error"] },+ "runnable": { "type": "boolean" },+ "reason": {+ "anyOf": [+ { "const": "native_cli_unavailable" },+ {+ "enum": [+ "source_missing",+ "model_unsupported",+ "models.source.needs_action.oauth_expired",+ "models.source.needs_action.balance_exhausted",+ "models.source.needs_action.credential_revoked",+ "models.source.needs_action.account_banned",+ "models.source.error.unclassified"+ ]},- "required": ["health", "channel", "runnable"]- },- "then": {- "required": ["reason"],- "properties": {- "reason": { "type": "string" },- "retry_at": { "type": "null" }- }- }+ { "type": "null" }+ ]},+ "retry_at": { "type": ["string", "null"], "format": "date-time" }+ },+ "allOf": [{- "if": {- "properties": {- "health": { "const": "healthy" },- "channel": { "const": "native_cli" },- "runnable": { "const": true }- },- "required": ["health", "channel", "runnable"]- },- "then": {- "properties": {- "reason": { "type": "null" },- "retry_at": { "type": "null" }- }- }+ "if": { "properties": { "health": { "enum": ["needs_action", "error"] } }, "required": ["health"] },+ "then": { "properties": { "runnable": { "const": false }, "retry_at": { "type": "null" } } }},{- "$comment": "A non-null process-availability marker is legal at every Source health and means this process cannot launch the native_cli hop. It always forces runnable false. Hub hops are definitionally process-available, so the marker is impossible there.",- "if": {- "properties": { "reason": { "type": "string" } },- "required": ["reason"]- },- "then": {- "required": ["channel", "runnable"],- "properties": {- "channel": { "const": "native_cli" },- "runnable": { "const": false }- }- }+ "if": { "properties": { "channel": { "const": "hub" }, "reason": { "type": "string" } }, "required": ["channel", "reason"] },+ "then": { "properties": { "runnable": { "const": false } } }},{- "$comment": "v2 (07-29, review round 4), availability-separated in v5: `cooldown` is the only health value with a stamp, and it always has one — mirroring source.schema.json → state.retry_at, where `cooldown` is the self-healing status whose recovery time is known. For an available item, `runnable` remains the v3 dynamic rule: true exactly when `retry_at` is already in the past, which a schema cannot compare to now. Process unavailability has precedence at every health, so a cooldown native_cli item may also carry the marker; the converse above then pins runnable false while retaining the health stamp.",- "if": {- "properties": { "health": { "const": "cooldown" } },- "required": ["health"]- },- "then": {- "required": ["retry_at"],- "properties": {- "retry_at": { "type": "string" }- }- }+ "if": { "properties": { "reason": { "const": "native_cli_unavailable" } }, "required": ["reason"] },+ "then": { "properties": { "channel": { "const": "native_cli" }, "runnable": { "const": false } } }},{- "$comment": "v2 (07-29, review round 4): `via_mapping: true` means a mapping REWROTE the requested id, so there is by construction a different id to report; a null here would say 'mapped to itself', which is what `via_mapping: false` already says.",- "if": {- "properties": { "via_mapping": { "const": true } },- "required": ["via_mapping"]- },- "then": {- "properties": {- "resolved_model_id": { "type": "string" }- }- }- }- ],- "properties": {- "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },- "channel": {- "enum": ["hub", "native_cli"],- "description": "The source's serving channel. `hub` process availability is definitionally true in v2; `native_cli` is additionally gated by whether this serving process can launch the sanctioned CLI under its own login right now. The discriminator mirrors source.schema.json → supply_channel."- },- "via_mapping": {- "type": "boolean",- "description": "true only when an explicit per-agent mapping rewrote the requested id (spec §4.3 step 1). A built-in vendor-native alias remains false, so UI can distinguish an owner-authored override from the default native resolution rule."- },- "resolved_model_id": {- "type": ["string", "null"],- "description": "The id actually sent upstream (e.g. glm-5.2 for an explicit mapping, or claude-opus-4-5-20251101 for a native claude-opus-4-5 alias); null only when it is byte-identical to `model_id`. For open menus that never happens — the request is prefixed and the upstream id is bare — so this is non-null for every opencode chain. Also non-null whenever `via_mapping` is true, since a mapping by definition produced a different id."- },- "health": {- "enum": ["healthy", "cooldown", "needs_action", "error"],- "description": "Source-GLOBAL health, mirrored from source.schema.json → state.status so the chip can dim / gold-dot / flag without a second round trip. Global by design: quota and reachability belong to the account. Note this carries only the health half of that enum — `active`/`standby` are consumption facts and are expressed here by position + `runnable`, never copied per agent."- },- "runnable": {- "type": "boolean",- "description": "Whether this candidate is usable right now: health permits the turn AND this process can serve the channel. Health permits `healthy`, or `cooldown` whose `retry_at` has already passed; process availability is definitionally true for `hub` and checked at resolve time for `native_cli`. ALWAYS false for `needs_action` and `error`. An unavailable native item stays visible at its original chain position, dimmed. This is the complete runnability filter used by the shipped resolver."- },- "reason": {- "anyOf": [- { "enum": ["native_cli_unavailable"] },- { "type": "null" }- ],- "description": "The process-availability marker, orthogonal to source-global health. VOCABULARY HOME for `native_cli_unavailable`, the only unavailable state in v2. Non-null exactly when this process cannot launch the native_cli source, at any health; it forces runnable=false. Null means process-available. Hub is definitionally available and therefore always null. probe-result.schema.json mirrors this concept in its i18n-key error convention."- },- "retry_at": {- "type": ["string", "null"],- "format": "date-time",- "description": "When `runnable` flips back true unattended. Non-null only for health == cooldown; null for needs_action and for error, because neither recovers without the user. A cooldown item whose `retry_at` is already in the past is `runnable: true` with `retry_at` retained — the stamp records when it became eligible again, it is not a promise about the future."+ "if": { "properties": { "health": { "const": "cooldown" } }, "required": ["health"] },+ "then": { "required": ["retry_at"], "properties": { "retry_at": { "type": "string" } } }}- }+ ]}},"supply_state": {"enum": ["ok", "waiting", "interrupted"],- "description": "The model-scoped supply state. `ok` means at least one configured hop is runnable. Otherwise `waiting` means the chain is non-empty and every hop is cooling, not retry-ready, and process-available; `interrupted` means the chain is empty or at least one blocker needs action, including process-unavailable native_cli at any Source health. Cooldown plus native_cli_unavailable is interrupted, never waiting."+ "description": "ok has a runnable hop; waiting is a non-empty all-cooldown chain with no process blocker; interrupted covers an empty chain or an action/process blocker."}},"allOf": [{- "$comment": "v2 (07-29, review round 4): `supply_state` ⇔ the contents of `chain`, in both directions. The predicate was stated once in spec §4.5 and quoted here, but nothing tied the rollup to the array it summarises, so `supply_state: \"ok\"` validated over a chain with no runnable member — the payload asserting 'this model is fine' while carrying the evidence that it is not. `ok` ⇒ at least one runnable member; the two blocked values ⇒ none.","if": { "properties": { "supply_state": { "const": "ok" } }, "required": ["supply_state"] },- "then": {- "properties": {- "chain": {- "contains": { "properties": { "runnable": { "const": true } }, "required": ["runnable"] }- }- }- }+ "then": { "properties": { "chain": { "contains": { "properties": { "runnable": { "const": true } }, "required": ["runnable"] } } } }},{"if": { "properties": { "supply_state": { "enum": ["waiting", "interrupted"] } }, "required": ["supply_state"] },- "then": {- "properties": {- "chain": {- "not": { "contains": { "properties": { "runnable": { "const": true } }, "required": ["runnable"] } }- }- }- }+ "then": { "properties": { "chain": { "not": { "contains": { "properties": { "runnable": { "const": true } }, "required": ["runnable"] } } } } }},{- "$comment": "v5: waiting remains the AND-branch — non-empty chain and EVERY member a not-retry-ready cooldown that is process-available. The schema cannot compare retry_at to now, but the blocked-state conditional already forbids runnable members; requiring reason:null additionally excludes unavailable native_cli members. This matches core/handlers/model_hub/resolver.py:109-116 at master 807d1eee: waiting requires every source cooldown and not unavailable, otherwise no-candidate supply is interrupted.","if": { "properties": { "supply_state": { "const": "waiting" } }, "required": ["supply_state"] },"then": {"properties": {"chain": {"minItems": 1,- "items": {- "properties": {- "health": { "const": "cooldown" },- "runnable": { "const": false },- "reason": { "type": "null" }- },- "required": ["health", "runnable", "reason"]- }- }- }- }- },- {- "if": { "properties": { "supply_state": { "const": "interrupted" } }, "required": ["supply_state"] },- "then": {- "properties": {- "chain": {- "anyOf": [- { "maxItems": 0 },- { "contains": { "properties": { "health": { "enum": ["needs_action", "error"] } }, "required": ["health"] } },- { "contains": { "properties": { "reason": { "type": "string" } }, "required": ["reason"] } }- ]- }- }- }- },- {- "$comment": "v2 (07-29, review round 4): open menus resolve a PREFIXED request to a BARE upstream id (api.md → identifier rules), so the two are never byte-equal and the 'null when it equals model_id' shorthand can never apply for opencode. Pinned rather than left to prose because a null here would be read as 'sent zhipuai/glm-5.2 upstream', which is the silent-miss this file's identifier rules exist to prevent.",- "if": { "properties": { "backend": { "const": "opencode" } }, "required": ["backend"] },- "then": {- "properties": {- "chain": { "items": { "properties": { "resolved_model_id": { "type": "string" } } } }- }- }- },- {- "$comment": "v5 (07-30 native-alias amendment): Codex has no built-in upstream-id rewrite today, so `via_mapping:false` still means byte-identical and therefore null for that backend. Claude differs: its fixed menu includes stable aliases that may resolve to a dated discovered id without becoming an explicit user mapping.",- "if": { "properties": { "backend": { "const": "codex" } }, "required": ["backend"] },- "then": {- "properties": {- "chain": {- "items": {- "allOf": [- {- "if": { "properties": { "via_mapping": { "const": false } }, "required": ["via_mapping"] },- "then": { "properties": { "resolved_model_id": { "type": "null" } } }- }- ]- }- }- }- }- },- {- "$comment": "v5 (07-30 native-alias amendment): a non-mapped Claude rewrite is legal only in the vendor-native Claude identifier family. The server additionally proves same-family/version selection against discovered inventory; JSON Schema cannot compare the requested model_id with each row or inspect the source inventory.",- "if": { "properties": { "backend": { "const": "claude" } }, "required": ["backend"] },- "then": {- "properties": {- "chain": {- "items": {- "allOf": [- {- "if": { "properties": { "via_mapping": { "const": false } }, "required": ["via_mapping"] },- "then": {- "properties": {- "resolved_model_id": {- "anyOf": [- { "type": "null" },- { "type": "string", "pattern": "^claude-(opus|sonnet|haiku|fable)-[0-9]+(?:-[0-9]+)*(?:-[0-9]{8})?$" }- ]- }- }- }- }- ]- }+ "items": { "properties": { "health": { "const": "cooldown" }, "runnable": { "const": false }, "reason": { "type": "null" } }, "required": ["health", "runnable", "reason"] }}}}@@ -282,107 +108,24 @@"contract_version": 5,"backend": "claude","model_id": "claude-opus-4-6",- "chain": [- {- "source_id": "src_claudepro1",- "channel": "native_cli",- "via_mapping": false,- "resolved_model_id": null,- "health": "cooldown",- "runnable": false,- "reason": null,- "retry_at": "2026-07-29T04:00:00Z"- },- {- "source_id": "src_anthkey01",- "channel": "hub",- "via_mapping": false,- "resolved_model_id": null,- "health": "healthy",- "runnable": true,- "reason": null,- "retry_at": null- }- ],- "supply_state": "ok"- },- {- "contract_version": 5,- "backend": "claude",- "model_id": "claude-opus-4-5",- "chain": [- {- "source_id": "src_glmrelay01",- "channel": "hub",- "via_mapping": false,- "resolved_model_id": "claude-opus-4-5-20251101",- "health": "healthy",- "runnable": true,- "reason": null,- "retry_at": null- }- ],- "supply_state": "ok"- },- {- "contract_version": 5,- "backend": "claude",- "model_id": "claude-haiku-4-5",- "chain": [],- "supply_state": "interrupted"- },- {- "contract_version": 5,- "backend": "codex",- "model_id": "gpt-5.3-codex",- "chain": [- {- "source_id": "src_codexplus1",- "channel": "native_cli",- "via_mapping": false,- "resolved_model_id": null,- "health": "cooldown",- "runnable": false,- "reason": null,- "retry_at": "2026-07-29T09:15:00Z"- }- ],+ "chain": [{ "source_id": "src_claudepro1", "model_id": "claude-opus-4-6", "channel": "native_cli", "health": "cooldown", "runnable": false, "reason": null, "retry_at": "2026-07-29T04:00:00Z" }],+ "current": null,"supply_state": "waiting"},{"contract_version": 5,"backend": "codex","model_id": "gpt-5.6",- "chain": [- {- "source_id": "src_chatgptplus",- "channel": "native_cli",- "via_mapping": false,- "resolved_model_id": null,- "health": "healthy",- "runnable": false,- "reason": "native_cli_unavailable",- "retry_at": null- }- ],+ "chain": [{ "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "channel": "native_cli", "health": "healthy", "runnable": false, "reason": "native_cli_unavailable", "retry_at": null }],+ "current": null,"supply_state": "interrupted"},{"contract_version": 5,"backend": "claude",- "model_id": "claude-sonnet-4-5",- "chain": [- {- "source_id": "src_claudecli1",- "channel": "native_cli",- "via_mapping": false,- "resolved_model_id": null,- "health": "cooldown",- "runnable": false,- "reason": "native_cli_unavailable",- "retry_at": "2026-07-29T10:30:00Z"- }- ],+ "model_id": "claude-haiku-4-5",+ "chain": [],+ "current": null,"supply_state": "interrupted"}]diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.jsonindex b28744fc1..9c5fb4db6 100644--- a/docs/plans/model-hub-contracts/agent-supply.schema.json+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json@@ -97,6 +97,29 @@}}},+ "routes": {+ "type": ["object", "null"],+ "description": "The persisted exact Route for every menu model. Keys are caller-facing menu ids; each value is an ordered hops array and may be empty. Runtime reads this projection verbatim.",+ "additionalProperties": {+ "type": "object",+ "required": ["hops"],+ "additionalProperties": false,+ "properties": {+ "hops": {+ "type": "array",+ "items": {+ "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 }+ }+ }+ }+ }+ }+ },"supply_status": {"type": ["string", "null"],"enum": ["ok", "degraded", "waiting", "interrupted", null],@@ -183,6 +206,7 @@"selected_model_id": { "type": "null" },"selected_by_agent": { "type": "null" },"sources": { "type": "null" },+ "routes": { "type": "null" },"supply_status": { "type": "null" },"model_supply": { "type": "null" },"named_agents": {@@ -200,6 +224,7 @@"then": {"properties": {"sources": { "type": "object" },+ "routes": { "type": "object" },"model_supply": { "type": "array" },"named_agents": {"type": "array",diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 824fc4056..5423f4016 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -16,6 +16,7 @@ Hub has not shipped, so there is no internal contract migration or compatibility| Method and path | Request → response | Normative notes || --- | --- | --- || GET `/api/models/sources` | → `{sources: Source[]}` | Unordered asset inventory. Array order is never a spend order. |+| POST `/api/models/sources/observe` | `{vendor, base_url?, key, protocol_order?}` → `{observation: SourceObservation}` | Non-persisting connectivity/authentication/protocol/inventory observation. `protocol_order` only orders the three probes; it never supplies a conclusion. No credential reference is returned. || POST `/api/models/sources` | `SourceCreate` → `{source: Source, added_to: AddedTo[], adopted_by: AdoptedBy[]}` | The server assigns `id` and `created_at`; plaintext keys are transient. Add-time matching and placement are materialized before response. || PATCH `/api/models/sources/<id>` | `{display_name?, base_url?, force?: boolean}` → guarded Source-mutation envelope | Metadata/Base-URL mutation from the authoritative matrix in `model-hub.md` §4.5. || PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean}` → guarded Source-mutation envelope | API-key replacement. `force` is a JSON body field, never a query parameter. |@@ -48,6 +49,54 @@ The removed global route `PUT /api/models/priority` has no replacement. Backendorder is explicit configuration through the sources route; exact per-model order isexplicit configuration through the chain route.+## Unsaved Source observation++`POST /api/models/sources/observe` accepts only the observation subset of a Source+create request:++```json+{+ "vendor": "custom",+ "base_url": "https://relay.example/v1",+ "key": "<transient plaintext key>",+ "protocol_order": ["openai_chat", "openai_responses", "anthropic"]+}+```++`base_url` may be null for an official vendor endpoint. `protocol_order`, when+present, contains each protocol exactly once and is only probe ordering; omitting it+uses the authoritative three-value order. The endpoint provisions an unbound engine+credential only for this operation, returns `observation-result.schema.json`, then+revokes the transient reference before settling. A revoke failure remains in the+existing pending-revocation journal. The response never contains that reference or+any persisted Source.++For an API-key `POST /api/models/sources`, the server performs the same+response-backed observation internally before its independent committed credential+provisioning. It accepts the create fields and optional `protocol_order`, but never+accepts a protocol conclusion from the caller. A null protocol produces no Source; a+proven protocol may be saved even when inventory discovery failed, with the resulting+Source health reflecting that uncertainty. Subscription OAuth creation follows its+vendor-specific observation flow before commit. Saved Sources use the stored+protocol for every later operation.++The observation result has six terminal outcomes: `observed`, `ambiguous`,+`unreachable`, `authentication_failed`, `adapter_error`, and `timeout`. Its+`protocol` is non-null only when a real upstream response shape and positive+authentication evidence prove the transport. Authentication is accepted only by a+shaped success or a shaped request-level error that occurs after authentication;+shaped authentication errors are rejected. Shaped server and rate-limit errors+prove reachability but not authentication, so they settle as `adapter_error` with+`reachable: true`, `authenticated: unknown`, and `protocol: null`. A local adapter+failure may use the same outcome with `reachable: null`. A bare HTTP status proves+reachability, but proves neither protocol nor authentication. Consequently,+`ambiguous` always has `reachable: true` and `protocol: null`.+`authentication_failed` also has `protocol: null`, because a rejected credential+does not establish a persistable protocol. `ambiguous` is the sole outcome that asks+for the one-time probe-order hint. Only `observed` attempts inventory discovery and+therefore reports `succeeded` or `failed`; every other terminal reports+`not_attempted` with an empty model list.+## Identifier rules- `Source.id` and every non-null source reference match@@ -376,12 +425,13 @@ refresh a source whose global state is `needs_action` or `error`, even though noturn resolution and the chain probe exclude that source as non-runnable.On usable discovery it updates the discovered model set, clears the blocker, and-sets the source to `standby`. The response returns that complete updated source and-the discovered count; clients do not reconstruct the model list from the count.-`last_discovered_at` advances only on this successful replacement. A classified-failure updates the source-global state, preserves the last successful model list and-timestamp, and returns the normal safe error. This route is the only refresh/recovery-operation; there is no parallel “test” or “recover” endpoint.+sets the source to `standby`. The success response is the guarded Source-mutation+envelope `{source, removed_hops, interrupted}`; clients render the complete updated+Source and the exact route impact from that envelope. `last_discovered_at` advances+only on this successful replacement. A classified failure updates the source-global+state, preserves the last successful model list and timestamp, and returns the normal+safe error. This route is the only refresh/recovery operation; there is no parallel+“test” or “recover” endpoint.## OAuth completion@@ -422,6 +472,9 @@ In Hub mode, `AgentChain.chain` is the exact stored per-model Route chain in theorder. Runtime does not filter or rebuild it: cooling, missing, model-unsupported,source-blocked, and process-unavailable native CLI hops stay at their configuredpositions with live annotations.+`AgentChain.current` is either null or the exact `{source_id, model_id}` identity of+the hop that is current for the next execution. Recovery changes `current` on the next+turn without changing the stored `chain` array.Each item carries `channel`, source-global `health`, process-aware `runnable`, andnullable `reason`. The complete axiom is:@@ -445,15 +498,15 @@ remains a valid `interrupted` chain."chain": [{"source_id": "src_chatgptplus",+ "model_id": "gpt-5.6","channel": "native_cli",- "via_mapping": false,- "resolved_model_id": null,"health": "healthy","runnable": false,"reason": "native_cli_unavailable","retry_at": null}],+ "current": null,"supply_state": "interrupted"}}@@ -487,7 +540,6 @@ A successful probe nests its result:"source_id": "src_relay9c1x","model_id": "glm-5.2","latency_ms": 287,- "via_mapping": true,"error": "models.source.needs_action.balance_exhausted"}}@@ -511,7 +563,6 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`."source_id": "src_chatgptplus","model_id": "gpt-5.6","latency_ms": null,- "via_mapping": false,"error": null}```@@ -525,7 +576,6 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`."source_id": "src_chatgptplus","model_id": "gpt-5.6","latency_ms": null,- "via_mapping": false,"error": "models.probe.native_cli_unavailable"}```@@ -591,9 +641,12 @@ Minimum v5 set:`invalid_source_order`, `source_last_supplier`, `source_in_route_chain`,`source_model_in_route_chain`, `mode_switch_blocked`, `engine_down`,`reauth_confirmation_required`, `source_model_managed_upstream`,-`migration_item_conflict`, `turn_not_found`,+`native_source_already_exists`, `migration_item_conflict`, `turn_not_found`,`provenance_unavailable`, `probe_no_candidate`, `direct_mode`.+`native_source_already_exists` is an API-boundary refusal for native OAuth start;+its structured sibling is `{existing_source_id}` and the adapter is not invoked.+Boundary-only action-refusal values cover operations the UI already does not offer buta script or regression can call directly. `reauth_confirmation_required` and`source_model_managed_upstream` are API/test-only truth: they have no product copy key@@ -611,6 +664,8 @@ contract harness and API-boundary tests enforce:<!-- authority-consumer: mutation.source_metadata mutation.credential_replace mutation.source_refresh mutation.model_create mutation.model_efforts mutation.model_delete mutation.source_delete mutation.route_replace --><!-- authority-consumer: import.keep_native import.copy_key import.reauth import.controlled --><!-- authority-consumer: protocol anthropic openai_responses openai_chat -->+<!-- authority-consumer: observation.outcome observed ambiguous unreachable authentication_failed adapter_error timeout -->+<!-- authority-consumer: observation.discovery succeeded failed not_attempted -->| Guard | Boundary || --- | --- |@@ -620,7 +675,7 @@ contract harness and API-boundary tests enforce:| every `sources.order` id exists, is unique, and is eligible | config loader + source-order route || eligibility contains one row per source and every ordered source is eligible | AgentSupply assembler || every AgentSupply eligibility row carries `in_current_model_chain` and `process_availability_reason`; membership nullability follows `selected_model_id`, and only a native source may carry `native_cli_unavailable` | AgentSupply assembler |-| `AgentChain.chain` re-echoes the stored exact hops in the same order, including missing, model-unsupported, and process-unavailable native CLI items | chain assembler |+| `AgentChain.chain` re-echoes the stored exact hops in the same order, including missing, model-unsupported, and process-unavailable native CLI items; `AgentChain.current` is null or identifies one exact hop in that array | chain assembler || `model_supply` has one row per menu model with unique ids | AgentSupply assembler || probe `source_id` names an existing source | probe assembler || non-null event endpoints name existing sources at emission time | event emitter |diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex 59703e682..b86f80f11 100644--- a/docs/plans/model-hub-contracts/mirror-registry.json+++ b/docs/plans/model-hub-contracts/mirror-registry.json@@ -50,6 +50,18 @@}],"api_boundary_only_errors": [+ {+ "value": "native_source_already_exists",+ "contract_file": "docs/plans/model-hub-contracts/api.md",+ "negative_test_file": "tests/test_model_hub_api.py",+ "negative_test": "test_native_oauth_rejects_duplicate_source_before_adapter",+ "forbidden_ui_globs": [+ "ui/src/components/settings/models/**/*.ts",+ "ui/src/components/settings/models/**/*.tsx",+ "ui/src/i18n/*.json",+ "vibe/i18n/*.json"+ ]+ },{"value": "source_model_managed_upstream","contract_file": "docs/plans/model-hub-contracts/api.md",@@ -274,7 +286,20 @@},{"schema": "probe-result.schema.json",- "path": "/allOf/6/then/properties/error",+ "path": "/properties/error",+ "exclude": [+ null,+ "models.source.cooldown.network",+ "models.source.cooldown.timeout",+ "models.source.cooldown.rate_limited",+ "models.source.cooldown.quota_exhausted",+ "models.source.cooldown.server_error",+ "models.source.needs_action.oauth_expired",+ "models.source.needs_action.balance_exhausted",+ "models.source.needs_action.credential_revoked",+ "models.source.needs_action.account_banned",+ "models.source.error.unclassified"+ ],"mapping": {"native_cli_unavailable": "models.probe.native_cli_unavailable"}@@ -375,26 +400,31 @@"class": "ModelHubSourceConfig","field": "protocol"},- {- "kind": "python_string_assignment",- "file": "vibe/model_hub_runtime/state.py",- "name": "_PROTOCOLS"- },- {- "kind": "marker_tail",- "file": "docs/plans/model-hub-contracts/adapter-interface.py",- "marker": "authority-consumer: protocol "- },- {- "kind": "marker_tail",- "file": "docs/plans/model-hub-contracts/opencode-overlay.md",- "marker": "authority-consumer: protocol "- },- {- "kind": "marker_tail",- "file": "docs/plans/model-hub-contracts/api.md",- "marker": "authority-consumer: protocol "- }+ {+ "kind": "python_string_assignment",+ "file": "core/handlers/model_hub/adapter.py",+ "name": "SOURCE_PROTOCOLS"+ },+ {+ "kind": "python_string_assignment",+ "file": "vibe/model_hub_runtime/state.py",+ "name": "_PROTOCOLS"+ },+ {+ "kind": "python_string_assignment",+ "file": "docs/plans/model-hub-contracts/adapter-interface.py",+ "name": "SOURCE_PROTOCOLS"+ },+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/opencode-overlay.md",+ "marker": "authority-consumer: protocol "+ },+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/api.md",+ "marker": "authority-consumer: protocol "+ }]},{@@ -429,6 +459,48 @@"prefix": "models.eligibility."}]+ },+ {+ "id": "D7",+ "domain": "unsaved observation outcomes",+ "authority": {+ "kind": "schema_vocabulary",+ "schema": "observation-result.schema.json",+ "paths": ["/properties/outcome"]+ },+ "consumers": [+ {+ "kind": "python_string_assignment",+ "file": "docs/plans/model-hub-contracts/adapter-interface.py",+ "name": "OBSERVATION_OUTCOMES"+ },+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/api.md",+ "marker": "authority-consumer: observation.outcome "+ }+ ]+ },+ {+ "id": "D8",+ "domain": "unsaved observation discovery outcomes",+ "authority": {+ "kind": "schema_vocabulary",+ "schema": "observation-result.schema.json",+ "paths": ["/properties/discovery"]+ },+ "consumers": [+ {+ "kind": "python_string_assignment",+ "file": "docs/plans/model-hub-contracts/adapter-interface.py",+ "name": "OBSERVATION_DISCOVERY_OUTCOMES"+ },+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/api.md",+ "marker": "authority-consumer: observation.discovery "+ }+ ]}],"ownership_checks": [diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.jsonnew file mode 100644index 000000000..e5e7a5ead--- /dev/null+++ b/docs/plans/model-hub-contracts/observation-result.schema.json@@ -0,0 +1,179 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/observation-result.schema.json",+ "title": "SourceObservation",+ "description": "Response-backed result of the unsaved Source observation. It never contains a credential reference or persisted Source state. Any upstream response proves reachability, but a bare HTTP status proves neither protocol nor authentication. Authentication is accepted only for a shaped success or a shaped request error that occurs after authentication; shaped authentication errors are rejected, while shaped server and rate-limit errors leave authentication unknown and settle as adapter_error rather than observed or ambiguous.",+ "type": "object",+ "required": [+ "contract_version",+ "outcome",+ "reachable",+ "authenticated",+ "protocol",+ "discovery",+ "models"+ ],+ "additionalProperties": false,+ "properties": {+ "contract_version": { "const": 5 },+ "outcome": {+ "enum": [+ "observed",+ "ambiguous",+ "unreachable",+ "authentication_failed",+ "adapter_error",+ "timeout"+ ]+ },+ "reachable": { "type": ["boolean", "null"] },+ "authenticated": { "enum": ["authenticated", "rejected", "unknown"] },+ "protocol": {+ "type": ["string", "null"],+ "enum": [null, "anthropic", "openai_responses", "openai_chat"]+ },+ "discovery": { "enum": ["succeeded", "failed", "not_attempted"] },+ "models": {+ "type": "array",+ "items": { "type": "string", "minLength": 1 },+ "uniqueItems": true+ }+ },+ "allOf": [+ {+ "if": { "properties": { "outcome": { "const": "observed" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "reachable": { "const": true },+ "authenticated": { "const": "authenticated" },+ "protocol": { "type": "string" },+ "discovery": { "enum": ["succeeded", "failed"] }+ }+ }+ },+ {+ "if": { "properties": { "outcome": { "const": "ambiguous" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "reachable": { "const": true },+ "authenticated": { "enum": ["authenticated", "unknown"] },+ "protocol": { "const": null },+ "discovery": { "const": "not_attempted" },+ "models": { "maxItems": 0 }+ }+ }+ },+ {+ "if": { "properties": { "outcome": { "const": "unreachable" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "reachable": { "const": false },+ "authenticated": { "const": "unknown" },+ "protocol": { "const": null },+ "discovery": { "const": "not_attempted" },+ "models": { "maxItems": 0 }+ }+ }+ },+ {+ "if": { "properties": { "outcome": { "const": "authentication_failed" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "reachable": { "const": true },+ "authenticated": { "const": "rejected" },+ "protocol": { "const": null },+ "discovery": { "const": "not_attempted" },+ "models": { "maxItems": 0 }+ }+ }+ },+ {+ "if": { "properties": { "outcome": { "const": "adapter_error" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "reachable": { "enum": [true, null] },+ "authenticated": { "const": "unknown" },+ "protocol": { "const": null },+ "discovery": { "const": "not_attempted" },+ "models": { "maxItems": 0 }+ }+ }+ },+ {+ "if": { "properties": { "outcome": { "const": "timeout" } }, "required": ["outcome"] },+ "then": {+ "properties": {+ "reachable": { "const": null },+ "authenticated": { "const": "unknown" },+ "protocol": { "const": null },+ "discovery": { "const": "not_attempted" },+ "models": { "maxItems": 0 }+ }+ }+ },+ {+ "if": { "properties": { "discovery": { "const": "failed" } }, "required": ["discovery"] },+ "then": { "properties": { "models": { "maxItems": 0 } } }+ },+ {+ "if": { "properties": { "protocol": { "const": null } }, "required": ["protocol"] },+ "then": { "properties": { "outcome": { "enum": ["ambiguous", "unreachable", "authentication_failed", "adapter_error", "timeout"] } } }+ }+ ],+ "examples": [+ {+ "contract_version": 5,+ "outcome": "observed",+ "reachable": true,+ "authenticated": "authenticated",+ "protocol": "openai_chat",+ "discovery": "succeeded",+ "models": ["gpt-5.6"]+ },+ {+ "contract_version": 5,+ "outcome": "authentication_failed",+ "reachable": true,+ "authenticated": "rejected",+ "protocol": null,+ "discovery": "not_attempted",+ "models": []+ },+ {+ "contract_version": 5,+ "outcome": "ambiguous",+ "reachable": true,+ "authenticated": "unknown",+ "protocol": null,+ "discovery": "not_attempted",+ "models": []+ },+ {+ "contract_version": 5,+ "outcome": "unreachable",+ "reachable": false,+ "authenticated": "unknown",+ "protocol": null,+ "discovery": "not_attempted",+ "models": []+ },+ {+ "contract_version": 5,+ "outcome": "adapter_error",+ "reachable": null,+ "authenticated": "unknown",+ "protocol": null,+ "discovery": "not_attempted",+ "models": []+ },+ {+ "contract_version": 5,+ "outcome": "timeout",+ "reachable": null,+ "authenticated": "unknown",+ "protocol": null,+ "discovery": "not_attempted",+ "models": []+ }+ ]+}diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.mdindex db01903ce..61b6a3cf7 100644--- a/docs/plans/model-hub-contracts/opencode-overlay.md+++ b/docs/plans/model-hub-contracts/opencode-overlay.md@@ -15,11 +15,13 @@ requirements.- No `avibe-` namespace anywhere (owner 07-23). Identifiers read exactly likenative OpenCode: `anthropic/claude-opus-4-6`, `zhipuai/glm-5.2`,`custom/<model-id>`.-- Each generated entry redirects transport to the local Gateway (base URL- `127.0.0.1:<port>` + per-protocol path) and injects the **local gateway- token** (never upstream credentials). Protocol is read from the exact configured- Source and is one of `anthropic | openai_responses | openai_chat`. A custom- `base_url`, not a fourth protocol, represents a relay or self-hosted upstream.+- Each generated entry uses the OpenAI-compatible Chat frontend and redirects it to+ the local Gateway (`127.0.0.1:<port>/v1`), injecting the **local gateway token**+ (never upstream credentials). This frontend transport is stable for the provider+ entry even when its models resolve to Sources with different stored protocols. The+ Gateway uses the exact configured hop to reach an upstream whose protocol is one of+ `anthropic | openai_responses | openai_chat`. A custom `base_url`, not a fourth+ protocol, represents a relay or self-hosted upstream.- Any Hub-held subscription may supply OpenCode through an exact configured hop.A `native_cli` Source remains bound to its sanctioned backend and therefore cannotmaterialize as an OpenCode provider.@@ -34,6 +36,14 @@ requirements.- The invocation selects the exact stored `(source_id, model_id)` hop. Runtime nevernormalizes a provider, matches inventory, or substitutes a model.+## 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+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.+## Stability invariant (test requirement, L7)For a fixed set of checked models, the generated identifier strings arediff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonindex 8ba5c553a..f7c950096 100644--- a/docs/plans/model-hub-contracts/probe-result.schema.json+++ b/docs/plans/model-hub-contracts/probe-result.schema.json@@ -2,36 +2,18 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/probe-result.schema.json","title": "ProbeResult",- "description": "v5 (2026-07-29 targeted amendment): outcome of walking an agent's current chain in spec §4.3 order and selecting the first runnable source. An unavailable chain item is never probed. For channel=hub the selected source is probed upstream exactly as in v3. For channel=native_cli readiness is re-verified after selection, so an item that was available during resolution may honestly return not-ready if that process-local fact went stale. Readiness is not completion evidence: a native result never claims an upstream request ran or completed. Classified outcomes only, never raw diagnostics. `reachable` remains distinct from the envelope's `ok`.",+ "description": "Outcome of probing the first runnable exact configured hop. Runtime never performs model matching or substitution.","type": "object",- "required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "via_mapping", "error"],+ "required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "error"],"additionalProperties": false,"properties": {"contract_version": { "const": 5 },"backend": { "enum": ["claude", "codex", "opencode"] },- "channel": {- "enum": ["hub", "native_cli"],- "description": "The channel whose truth this result reports. Mirrors source.schema.json → supply_channel and agent-chain.schema.json → chain[].channel."- },- "reachable": {- "type": "boolean",- "description": "Channel-scoped usability RIGHT NOW. For hub, true means the upstream request succeeded and false means the attempted source was not usable; latency says whether that attempt completed. For native_cli, this is readiness only: true means this process can launch the CLI under its own login now, false means it cannot. Native readiness is never completion evidence. Never conflate this field with the envelope's `ok`."- },- "source_id": {- "type": "string",- "pattern": "^src_[a-z0-9]{8,}$",- "description": "The first runnable chain source selected for checking. For hub it is attempted upstream. For native_cli its process readiness is re-verified without an upstream attempt and may have gone stale since selection; a source already marked unavailable in the chain is never selected. NON-NULLABLE; the no-candidate case remains the separate `probe_no_candidate` envelope."- },- "model_id": {- "type": "string",- "minLength": 1,- "description": "The resolved model, mapping applied. Hub sends it upstream; native_cli would pass it to the CLI if readiness permits. Non-nullable for the same reason as `source_id`."- },- "latency_ms": {- "type": ["integer", "null"],- "minimum": 0,- "description": "Hub round trip of the minimal upstream request. For hub, null means the attempt never completed and the existing error-key partition is total. For native_cli this is ALWAYS null in both readiness outcomes because no upstream request is timed; rendering a measured local check such as 12 ms would impersonate completion evidence."- },+ "channel": { "enum": ["hub", "native_cli"] },+ "reachable": { "type": "boolean" },+ "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },+ "model_id": { "type": "string", "minLength": 1, "description": "The exact upstream model id stored in the selected hop." },+ "latency_ms": { "type": ["integer", "null"], "minimum": 0 },"error": {"type": ["string", "null"],"enum": [@@ -47,201 +29,39 @@"models.source.needs_action.account_banned","models.source.error.unclassified","models.probe.native_cli_unavailable"- ],- "description": "Closed i18n-key outcome, never raw text. For channel=hub the ten source-state keys mirror source.schema.json → state.detail_key. For channel=native_cli the only non-null value is `models.probe.native_cli_unavailable`, the i18n spelling of agent-chain.schema.json → reason `native_cli_unavailable`; that mapping is registered and mutation-tested in mirror-registry.json. Explicitly null on every reachable result."- },- "via_mapping": {- "type": "boolean",- "description": "true when a per-agent mapping rewrote the requested model id for this probe. Non-nullable (07-29, review round 4): it is known the moment a candidate resolves, so it is answerable on every object that gets returned."+ ]}},"allOf": [{- "$comment": "v2 (07-29, review round 3): the nullability above was per-field and therefore too loose in combination — `reachable: true` with a null `source_id` and a non-null `error` validated, i.e. 'it answered, we don't know who, and here is why it didn't'. ROUND 4 moved the identity half UP to the type level: `source_id` / `model_id` / `via_mapping` are now plainly non-nullable, which is strictly stronger than pinning them in each branch and removes the branch bookkeeping entirely — a returned ProbeResult always identifies what was tested, in BOTH directions, and no future branch can reintroduce the hole. What is left here is genuinely conditional: `latency_ms` null means 'the attempt never completed', which a reachable probe contradicts by definition, so 未完成 belongs to the false branch alone.",- "if": {- "properties": {- "channel": { "const": "hub" },- "reachable": { "const": true }- },- "required": ["channel", "reachable"]- },- "then": {- "properties": {- "latency_ms": { "type": "integer" },- "error": { "type": "null" }- }- }+ "if": { "properties": { "channel": { "const": "hub" }, "reachable": { "const": true } }, "required": ["channel", "reachable"] },+ "then": { "properties": { "latency_ms": { "type": "integer" }, "error": { "type": "null" } } }},{- "$comment": "v2 (07-29, review round 3): the converse half. `error` is the field the UI renders instead of a latency, so an unreachable probe that carries no key leaves the drawer with nothing to say — the same 'required but nullable' gap, at the other end. `latency_ms` stays nullable on this branch on purpose: an attempted failure may or may not have completed.",- "if": {- "properties": {- "channel": { "const": "hub" },- "reachable": { "const": false }- },- "required": ["channel", "reachable"]- },+ "if": { "properties": { "channel": { "const": "hub" }, "reachable": { "const": false } }, "required": ["channel", "reachable"] },"then": { "properties": { "error": { "type": "string" } } }},{- "$comment": "v2 (07-29, review round 4; made TOTAL in round 5): which failures completed is decided by the error key, not by the emitter. Round 4 pinned the needs_action family alone — every one of those is learned FROM a completed upstream response (402/401/403 telling us the balance is out, the key is revoked, the account is banned), so `latency_ms: null` there would render a completed billing answer as 未完成. But the cooldown family is MIXED, and round 4 treated it as if it were uniformly transport: `rate_limited` (429), `quota_exhausted` and `server_error` (5xx) are all completed responses too, so they were left free to report null and reproduce the exact defect one family over. The partition is by key, and only `network` / `.timeout` are transport. Listing the completed keys explicitly rather than negating the transport pair is deliberate: with a closed enum both forms are equivalent today, but an added key would silently inherit 'completed' from a negation, whereas this list forces the contract change to say which side it is on — and round 7 is that mechanism working as designed: `models.source.error.unclassified` joined the enum and had to declare a side here. It is COMPLETED. An unclassified failure is one the adapter could not map, which means something came back to be unmappable; a request that never finished is not unclassified at all, it is `network` or `timeout` by definition.",- "if": {- "properties": {- "channel": { "const": "hub" },- "error": {- "enum": [- "models.source.cooldown.rate_limited",- "models.source.cooldown.quota_exhausted",- "models.source.cooldown.server_error",- "models.source.needs_action.oauth_expired",- "models.source.needs_action.balance_exhausted",- "models.source.needs_action.credential_revoked",- "models.source.needs_action.account_banned",- "models.source.error.unclassified"- ]- }- },- "required": ["channel", "error"]- },- "then": { "properties": { "latency_ms": { "type": "integer" } } }+ "if": { "properties": { "channel": { "const": "hub" }, "latency_ms": { "type": "null" } }, "required": ["channel", "latency_ms"] },+ "then": { "properties": { "error": { "enum": ["models.source.cooldown.network", "models.source.cooldown.timeout"] } } }},{- "$comment": "v2 (07-29, review round 5): the converse, which is what makes the partition total instead of one-directional. Round 4's shape said 'these keys require a latency' and stopped, so 未完成 remained writable for anything not named — the open half is how the 429 case survived a round whose whole purpose was closing this class. Stated from the null side there is nothing left over: a probe that never completed MUST be one of the two transport failures, because those are the only two ways an attempt can fail to finish. Any other key with a null latency is now unrepresentable rather than merely discouraged. Round 5 also claimed this left 「no undefined combination in either direction」; that claim was false, and the branch below is the direction it missed.",- "if": {- "properties": {- "channel": { "const": "hub" },- "latency_ms": { "type": "null" }- },- "required": ["channel", "latency_ms"]- },- "then": {- "properties": {- "channel": { "const": "hub" },- "error": {- "enum": ["models.source.cooldown.network", "models.source.cooldown.timeout"]- }- }- }- },- {- "$comment": "v2 (07-29, review round 9): transport failures require a NULL latency — the half round 5 thought it had closed. Both prior branches read from one side only: 'these eight completed keys need an integer' and 'a null latency must be transport'. Neither forbids `error: models.source.cooldown.timeout` with `latency_ms: 287`, so a request that never finished could validate carrying a measured round trip, and the drawer would render 超时 next to 287ms — a completed-looking answer for the one class of failure that by definition did not complete. Stated in both directions the pair is finally a partition: transport ⇔ null, the other eight keys ⇔ integer, `reachable: true` ⇔ integer with no error. No example changes; the transport example already carries null.",- "if": {- "properties": {- "channel": { "const": "hub" },- "error": {- "enum": ["models.source.cooldown.network", "models.source.cooldown.timeout"]- }- },- "required": ["channel", "error"]- },+ "if": { "properties": { "channel": { "const": "native_cli" } }, "required": ["channel"] },"then": { "properties": { "latency_ms": { "type": "null" } } }},{- "$comment": "v5 (07-29, escalations #2+#3): probe selection walks §4.3 order and touches the first runnable item; a source already present in unavailable_source_ids is excluded by core/handlers/model_hub/resolver.py:83-87,267-273 at master 807d1eee and is never probed. For a selected native_cli item, modules/agents/model_hub.py:323-348 re-verifies process-local readiness, which may have gone stale. reachable=true is readiness only — this process can launch the sanctioned CLI under its own login now. No upstream request ran, so readiness is not completion evidence and latency is null rather than a measured local check.",- "if": {- "properties": {- "channel": { "const": "native_cli" },- "reachable": { "const": true }- },- "required": ["channel", "reachable"]- },- "then": {- "properties": {- "latency_ms": { "type": "null" },- "error": { "type": "null" }- }- }- },- {- "$comment": "native_cli reachable=false uses the same process-availability concept as AgentChain reason=native_cli_unavailable, spelled as a closed i18n key here. It is a readiness failure rather than a completed CLI call, so latency is null.",- "if": {- "properties": {- "channel": { "const": "native_cli" },- "reachable": { "const": false }- },- "required": ["channel", "reachable"]- },- "then": {- "required": ["error"],- "properties": {- "latency_ms": { "type": "null" },- "error": { "enum": ["models.probe.native_cli_unavailable"] }- }- }+ "if": { "properties": { "channel": { "const": "native_cli" }, "reachable": { "const": false } }, "required": ["channel", "reachable"] },+ "then": { "properties": { "error": { "type": "string" } } }},{- "$comment": "The native CLI readiness key cannot appear on a hub probe or a reachable result. Together with the channel branches, this closes channel, reachability, latency, and error in both directions.",- "if": {- "properties": {- "error": { "const": "models.probe.native_cli_unavailable" }- },- "required": ["error"]- },- "then": {- "required": ["channel", "reachable", "latency_ms"],- "properties": {- "channel": { "const": "native_cli" },- "reachable": { "const": false },- "latency_ms": { "type": "null" }- }- }+ "if": { "properties": { "error": { "const": "models.probe.native_cli_unavailable" } }, "required": ["error"] },+ "then": { "properties": { "channel": { "const": "native_cli" }, "reachable": { "const": false }, "latency_ms": { "type": "null" } } }}],"examples": [- {- "contract_version": 5,- "backend": "codex",- "channel": "hub",- "reachable": true,- "source_id": "src_chatgptplus",- "model_id": "gpt-5.6",- "latency_ms": 412,- "error": null,- "via_mapping": false- },- {- "contract_version": 5,- "backend": "claude",- "channel": "hub",- "reachable": false,- "source_id": "src_relay9c1x",- "model_id": "glm-5.2",- "latency_ms": 287,- "error": "models.source.needs_action.balance_exhausted",- "via_mapping": true- },- {- "contract_version": 5,- "backend": "claude",- "channel": "hub",- "reachable": false,- "source_id": "src_relay9c1x",- "model_id": "glm-5.2",- "latency_ms": null,- "error": "models.source.cooldown.timeout",- "via_mapping": true- },- {- "contract_version": 5,- "backend": "codex",- "channel": "native_cli",- "reachable": true,- "source_id": "src_chatgptplus",- "model_id": "gpt-5.6",- "latency_ms": null,- "error": null,- "via_mapping": false- },- {- "contract_version": 5,- "backend": "codex",- "channel": "native_cli",- "reachable": false,- "source_id": "src_chatgptplus",- "model_id": "gpt-5.6",- "latency_ms": null,- "error": "models.probe.native_cli_unavailable",- "via_mapping": false- }+ { "contract_version": 5, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },+ { "contract_version": 5, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },+ { "contract_version": 5, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },+ { "contract_version": 5, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }]}diff --git a/docs/plans/model-hub-contracts/resolution-event.schema.json b/docs/plans/model-hub-contracts/resolution-event.schema.jsonindex 6580e4aea..5408d9b20 100644--- a/docs/plans/model-hub-contracts/resolution-event.schema.json+++ b/docs/plans/model-hub-contracts/resolution-event.schema.json@@ -54,7 +54,10 @@"unclassified_error","no_enabled_source","no_eligible_source",- "model_unsupported"+ "route_unconfigured",+ "source_missing",+ "model_unsupported",+ "native_cli_unavailable"],"description": "Adapter classification. The five non-self-healing source causes map bijectively to Source.state.detail_key: credential_expired→models.source.needs_action.oauth_expired; credential_revoked→models.source.needs_action.credential_revoked; balance_exhausted→models.source.needs_action.balance_exhausted; account_banned→models.source.needs_action.account_banned; unclassified_error→models.source.error.unclassified. permission_denied is request-scoped and has no Source-state mirror. The machine-readable mirror registry enforces the attempt-failure relation.","$comment": "permission_denied preserves a request-scoped denial while redacting arbitrary upstream bodies; it does not claim Source-global credential state."@@ -72,7 +75,7 @@},"allOf": [{- "$comment": "Backend-scoped supply interruption: no source endpoint, a real backend, a real model, and one of the three structural causes.",+ "$comment": "Backend-scoped supply interruption: no source endpoint, a real backend, a real model, and one exact structural cause from the configured chain.","if": {"properties": { "kind": { "const": "supply_interrupted" } },"required": ["kind"]@@ -89,7 +92,10 @@"enum": ["no_enabled_source","no_eligible_source",- "model_unsupported"+ "route_unconfigured",+ "source_missing",+ "model_unsupported",+ "native_cli_unavailable"]}}@@ -102,7 +108,10 @@"enum": ["no_enabled_source","no_eligible_source",- "model_unsupported"+ "route_unconfigured",+ "source_missing",+ "model_unsupported",+ "native_cli_unavailable"]}},diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex d7a0df0ff..55a8c733f 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -48,6 +48,7 @@},"vendor": {"type": "string",+ "pattern": "^[a-z0-9]+(?:[._-][a-z0-9]+)*$","description": "Standard vendor id (anthropic|openai|zhipuai|kimi|xai|...) or 'custom'. Also the OpenCode provider prefix (see opencode-overlay.md)."},"display_name": {diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.mdindex f2d12d187..357125a5c 100644--- a/docs/plans/model-hub-implementation.md+++ b/docs/plans/model-hub-implementation.md@@ -22,7 +22,7 @@ Lane workflow standard: `.agents/skills/pr-delivery-loop/SKILL.md`## 0. Ground rules for this effort-- The 13-file terminal-version/protocol-enum closure in §8 must coexist on one tested PR+- The terminal-version/protocol-enum closure in §8 must coexist on one tested PRhead. Commit boundaries are not a CI gate. The remaining final-shape consumers andevidence may land in later PRs, but the complete handoff is a release prerequisite.After I1 lands the contract set, it is read-only to downstream lanes; deviations route@@ -117,7 +117,7 @@ that reconciliation may change content but is not expected to change file owners| **K1 spec v3 sync** | codex | This PR's planning documents plus the owner-authorized final S-1/protocol edits under `docs/plans/model-hub-contracts/`, their byte-mirror/version consumers, and the live-input authority guard. It does not implement the remaining Gateway runtime | — || **K2 conversion fidelity** | codex | Preserve the recorded M0 measurements and go/no-go rows; record the 2026-08-08 owner waiver of an official-API attribution re-test and the accepted relay-attributed reasoning degradation without rewriting the evidence or adding product/UI scope | — || **I1 contracts and config core** *(tentative)* | codex | All files under `docs/plans/model-hub-contracts/`; `config/v2_config.py`; `core/controller.py`; `core/handlers/model_hub/adapter.py` and the byte-identical contract interface; `core/handlers/model_hub/{service,resolver,classification,errors,provenance,rpc,request,events}.py`; `modules/agents/model_hub.py`; `vibe/{ui_server,model_hub_client}.py`; `tests/test_model_hub_config.py`; `tests/test_model_hub_api.py`; `tests/test_model_hub_resolution.py`; `tests/test_model_hub_injection.py`; `tests/test_controller_model_hub_gate.py`; `tests/test_model_hub_l3.py` through the same-tested-head contract transition. `tests/test_multi_platform_runtime.py` and `tests/test_claude_cli_path.py` are read-only dependency checks: I1 repairs breakage caused by removed resolver symbols but does not refactor them. Owns the §8 final contracts, same-tested-head closure, §4.3 configured-chain executor, serializers, API envelopes, shared validation, and the default-off release gate while I1 is active | K1. **Merges first** |-| **I2 runtime transport** *(tentative)* | codex | `core/handlers/model_hub/turn_gateway.py`; `vibe/model_hub_runtime/{config,client,state,adapter}.py`; `tests/test_model_hub_runtime.py`; after I1 merges, `tests/test_model_hub_l3.py` transfers wholly to I2 for runtime behavior | I1 |+| **I2 runtime transport** *(tentative)* | codex | `core/handlers/model_hub/turn_gateway.py`; `vibe/model_hub_runtime/**`; `tests/test_model_hub_runtime.py`; after I1 merges, `tests/test_model_hub_l3.py` transfers wholly to I2 for runtime behavior | I1 || **I3 subscription custody and native import** *(tentative)* | codex | `core/handlers/model_hub/{oauth,native_oauth,revocations,migration}.py`; `tests/test_model_hub_oauth.py`; `tests/scenarios/model_hub/test_model_hub_migration_scenarios.py`; `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`. The migration scenario and complete auth-setup catalog/test loop are the sole carve-outs from I5's scenario tree | I1 || **I4 Sources / Gateway UI** *(tentative)* | codex | `ui/src/components/settings/models/**`; `ui/src/i18n/*.json`; `vibe/i18n/*.json`; UI tests. Both i18n trees are I4-exclusive | I1's API envelopes + the UI-spec PR || **I5 scenario validation** *(tentative)* | codex | `tests/scenarios/model_hub/**` except I3's native-import scenario; `tests/scenario_harness/**` | I1–I4 |@@ -705,7 +705,7 @@ text and AC-8's contract text as one criterion even though only one of them is f| **AC-25** | P1 | Split subscription recommendations by vendor and disable duplicate native creation | `model-hub.md` + final source/OAuth/API contracts + add-flow UI evidence | **I1** (defaults + shared singleton guard) + I3 (OAuth) + I4 (guidance) + I5 (scenario) | **amended 08-08 — vendor defaults retained; 08-07 takeover notice withdrawn** || **AC-26** | P1 | Complete Source add/detail operations: add-only connectivity test/discovery, one guarded saved refresh, manual model add/remove, and editable per-model reasoning-efforts lists with no defaults | `model-hub.md` + final `source.schema.json`, probe/API/adapter contracts | **I1** (shape + routes + service) + I2 (runtime effort use) + I4 (flows) + I5 (scenario) | **amended 08-09 — one saved mutation; no latency or last-check presentation** || **AC-27** | P1 | Make every stored protocol response-observed before Save and immutable afterward | `model-hub.md` + final source/probe/API/adapter contracts | **I1** (shape + API) + I2 (runtime transport) + I3 (OAuth/import observation) + I4 (failure-only manual probe-order hint) + I5 (scenario) | **amended 08-09 — manual input orders probes but does not create persistent provenance or bypass observation** |-| **AC-28** | P1 | Converge protocol identity on exactly Anthropic, OpenAI Responses, and OpenAI Chat Completions | `model-hub.md` + final source/API/adapter/overlay mirrors | **I1** (13-file closure + shared tests) + I2 (transport) + I4 (failure copy only) + I5 (scenario) | **settled 08-09 — retain Chat Completions; no `openai_compatible` alias** |+| **AC-28** | P1 | Converge protocol identity on exactly Anthropic, OpenAI Responses, and OpenAI Chat Completions | `model-hub.md` + final source/API/adapter/overlay mirrors | **I1** (same-tested-head protocol/version closure + shared tests) + I2 (transport) + I4 (failure copy only) + I5 (scenario) | **settled 08-09 — retain Chat Completions; no `openai_compatible` alias** || **AC-29** | P1 | Validate every persisted Source through the canonical final-shape validator | `model-hub-implementation.md` + final Source/config validation and native-import scenario evidence | **I1** (canonical validation boundary) + I3 (import writer + migration scenario) | **settled 08-09 — owner-routed investigation finding** || **AC-30** | P1 | Derive takeover from the resolved chain without a new field or false exhausted state | `model-hub.md` + final chain/API/mirror/locale projections | **I1** (projection + mechanical mirrors) + I2 (live current-hop input) + I4 (pull-surface rendering) + I5 (scenario) | **settled 08-09 — takeover is a projection, not stored state** || **AC-31** | P1 | Make existing-install Direct onboarding visible and reversible | `model-hub.md` + final mode API/UI/scenario evidence | **I1** (mode envelope/onboarding default) + I4 (Direct/Gateway groups and actions) + I5 (scenario) | **settled 08-09 — Direct remains a supported per-backend mode** |@@ -713,7 +713,7 @@ text and AC-8's contract text as one criterion even though only one of them is f**Read the 「Owed by」 column as contract-then-implementation** (07-29, review round 5).For historical AC-1–AC-21, a cell beginning **L1 v3** records the lane that authored thecontract surface before its consumers. For AC-22 onward, I1 lands the final contracts-and the 13-file closure on one tested head; I2–I5 complete their exclusive consumers+and the terminal version/protocol closure on one tested head; I2–I5 complete their exclusive consumersand evidence before release under the rule above.Only AC-5 and AC-6 carry no contract-owner term because their surface is the spec. Inboth plans, any downstream lane touching `model-hub-contracts/**` escalates to the@@ -825,6 +825,8 @@ registered authority but cannot create an unlisted branch.| `D4` | Native import actions | §6 import matrix `Decision` column | migration schema, code, locale, and scenario consumers || `D5` | Source protocols | `source.schema.json` protocol enum | adapter, config/runtime type, and spec consumers || `D6` | Configuration eligibility reasons | `agent-supply.schema.json` reason enum | §4.4, service projection, and both UI locale objects |+| `D7` | Unsaved observation outcomes | `observation-result.schema.json` outcome enum | adapter result type and API contract consumers |+| `D8` | Unsaved observation discovery outcomes | `observation-result.schema.json` discovery enum | adapter result type and API contract consumers |`M5` and `D6` are the newly exposed authorities from the circuit-breaker audit: theearlier four-table sweep omitted supply-health and eligibility even though both were@@ -834,13 +836,13 @@ external resolver importers.| ID | Contract file | Final required shape || --- | --- | --- |-| **FC-01** | `README.md` | Names §4.3 as the sole configured-chain execution authority and §4.2 as the sole Add-time Source placement authority; documents the same-tested-head 13-file closure, the prelaunch full-handoff gate, and downstream read-only ownership; indexes all fourteen files and terminal `contract_version: 5`; describes Sources, exact configured routes, add-time matching, channel custody, configuration eligibility, inventory, adoption, and pull-only supply visibility without reproducing either authority. |+| **FC-01** | `README.md` | Names §4.3 as the sole configured-chain execution authority and §4.2 as the sole Add-time Source placement authority; documents the same-tested-head terminal closure, the prelaunch full-handoff gate, and downstream read-only ownership; indexes the contract files and terminal `contract_version: 5`; describes Sources, exact configured routes, add-time matching, channel custody, configuration eligibility, inventory, adoption, and pull-only supply visibility without reproducing either authority. || **FC-02** | `mirror-registry.json` | Mechanically covers every closed enum and cross-file identity used by the final files: three protocols, backend ids, Source/model origins, exact-hop blocker/reason/detail-key/remedy pairs (including `native_cli_unavailable`), credential refresh-capability branches, turn outcome/discriminator/copy-key rows, native-import actions and locale keys, event agents, the sole remaining eligibility reason, `added_to`/`adopted_by` shapes, channel defaults, the four `supply_status` labels, the derived takeover label, and UI locale homes. API-boundary-only refusal values register their contract field, named negative route test, and forbidden UI/i18n scope instead of fabricating a render consumer. The same live-input invocation proves retired route literals are absent repo-wide and path identities do not reappear in the Source-model request bodies. Every mirror names an executable relation and terminal version **5**. || **FC-03** | `source.schema.json` | `Source` requires canonical id, kind, vendor, `protocol: anthropic | openai_responses | openai_chat`, credential reference/custody, channel, ordinary `created_at` audit metadata, state/usage, and an unordered model inventory whose ids are unique within that Source. Every model is `{id, origin: "discovered" | "manual", reasoning_efforts: string[], display_name?, discovered_at?}`; the list is required, may be empty, and is editable for either origin. Hub-held subscriptions require no flag, consent field, or acknowledgement record. || **FC-04** | `oauth-flow.schema.json` | Subscription flows carry explicit vendor and `supply_channel`; an omitted channel resolves Claude to `native_cli` and ChatGPT to `hub`, while both opposite explicit choices remain legal. The native option exposes `native_source_already_exists` plus `existing_source_id` before login when the backend singleton is occupied. Claude Hub carries one informational risk-copy key; no other path carries warning or consent state. || **FC-05** | `agent-supply.schema.json` | Each backend stores `mode: hub | direct`, one explicit `sources.order`, and exactly one `{hops: [{source_id, model_id}, ...]}` row per menu model. `hops` is always present and may be empty; neither order has a policy discriminator. It enforces at most one native Source per backend and exposes `adopted_by: [{backend, menu_model}]` from persisted references; Source-card attribution reuses that projection. `supply_status` is the sole backend-health projection. Fresh-install construction uses Gateway; the onboarding service supplies Direct for an existing installation with no Model Hub state. No separate mapping, matching, enrollment, or takeover field exists. || **FC-06** | `agent-chain.schema.json` | Returns the stored exact Source/model hops in the same order with only `current`, `runnable`, closed blocker reasons (`source_missing`, `model_unsupported`, `native_cli_unavailable`, and Source-state reasons), and retry metadata added. It has no route-policy or capability-matching discriminator. Takeover derives from stored first hop plus live current position and adds no field. |-| **FC-07** | `probe-result.schema.json` | Covers saved-Source recovery tests, unsaved Add Source connectivity/protocol observation, route probes, and their distinct mutation guarantees. Add-flow results report classified reachability/authentication plus an observed protocol only after a real upstream response, never a credential ref. A failed observation may request a manual three-value probe-order hint but cannot save a protocol without response proof. |+| **FC-07** | `observation-result.schema.json` + `probe-result.schema.json` | Keeps unsaved Add Source connectivity/protocol/inventory observation separate from saved-Route runtime probes. Add-flow results report classified reachability/authentication plus an observed protocol only after a real upstream response, never a credential ref. A failed observation may request a manual three-value probe-order hint but cannot save a protocol without response proof. `ProbeResult` remains the configured-Route runtime domain. || **FC-08** | `turn-provenance.schema.json` | Gateway turn records contain no route-policy discriminator; they record exact requested/configured model ids, exact Source attribution, ordered attempts, and the closed outcome set owned by §4.5's authoritative Turn-outcome copy matrix. `requested_model_changed` is derived from those exact ids and is never persisted. The schema mirrors the outcome set without reproducing its branches. A canceled in-flight attempt carries no fabricated Source failure. No separate mapping field, compatibility discriminator, or internal-version conversion state exists. || **FC-09** | `resolution-event.schema.json` | Removes `mapping_applied` and its `mapping` reason: an explicit model mapping is stored configuration, not a runtime resolution event. Remaining events carry exact Source/model attribution with mechanically mirrored reason/detail/severity fields. The feed is a pull surface; event descriptions contain no proactive-delivery or recipient-resolution contract. No mapping field, route-rewrite event, or internal-version conversion state exists. || **FC-10** | `adapter-interface.py` | Defines the three protocols, response-backed protocol observation, connectivity classification, credential refresh capability, discovery, all-inventory reasoning-efforts validation, transient credential cleanup on every unsaved-flow exit, and durable reconciliation on revoke failure. `invoke(reasoning_effort: str | None)` stays singular because §4.3 passes zero or one exact member. Runtime-local `engine_down` is distinct from Source failure. The checked-in interface and runtime adapter are byte-identical. |@@ -2003,7 +2005,7 @@ architecture inputs to S-1, not sealed-ledger deferrals.| **Observe protocols before committing imported Sources**<br><br>When a user applies native-config import, this universal invariant conflicts with the retained import flow in §6: the current scanners derive `protocol` from vendor or local wire configuration (`core/handlers/model_hub/migration.py:180-220`, `285-306`, and `489-520`), and `_source_from_item` persists that value directly at lines 596-605 without obtaining an upstream response. K3 must therefore either preserve import while violating AC-27, or enforce AC-27 and prevent an imported Source from being created whenever the upstream is unavailable; FC-12/FC-13 define neither observation nor its failure/credential-cleanup behavior. Require response-backed observation during import, or explicitly scope and contract an exception.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0ce001cfd62fdab736492c094914aa32a4991688/AGENTS.md#L145-L147) | AC-23 + AC-27 | final `migration-scan.schema.json`, `probe-result.schema.json`, and `api.md`; `core/handlers/model_hub/{migration,service,revocations}.py`; native-import API and scenario tests | I1 (final shape/API) + I3 (import observation/cleanup) + I5 (scenario) || **Assign the actual auth-setup scenario file**<br><br>Fresh evidence after the recorded auth-scenario thread is the repository layout: repo-wide search finds the harness at `tests/scenarios/auth_setup/test_auth_setup_scenarios.py`, while this lane assigns the nonexistent `tests/test_auth_setup_scenarios.py`. Because I5 owns only the Model Hub scenario tree, the real closed-loop OAuth/setup test remains outside every active lane and can stay stale while the listed work completes; correct the path and ownership here and in the landing ledger.<br><br>AGENTS.md reference: [AGENTS.md:L253-L253](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L253-L253) | AC-23 + AC-25 | `tests/scenarios/auth_setup/catalog.yaml`; `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` | I3 || **Assign the shared backend launch seam to an active lane**<br><br>When I1 replaces resolver/config shapes and I2 changes exact-hop transport, `modules/agents/model_hub.py` must change as well: it is the shared launch boundary for Claude, Codex, and OpenCode and currently imports and executes the runtime-matching resolver through `resolve_model_hub_turn`, `matching_sources`, and eligibility walks. None of the active I1–I5 scopes or landing rows owns this file; its only assignment is in the explicitly non-binding historical L3 table, so every active lane can complete while backend launches still use the retired routing model. Assign this shared seam and its backend call-site coverage to I1 or I2.<br><br>AGENTS.md reference: [AGENTS.md:L28-L30](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L28-L30) | AC-22 | `modules/agents/model_hub.py`; shared Claude/Codex/OpenCode launch call-site tests | I2 |-| **Specify the add-time model matching algorithm**<br><br>When upstream IDs do not literally equal menu IDs—for example Claude's dated aliases or normalized OpenCode identifiers—this new architecture deletes runtime matching and makes the Add Source result permanently authoritative, but it defines only Source ordering and never defines which upstream model is matched to each menu model or how ties are resolved. The current resolver has concrete logic such as `_native_claude_alias`, which I1 is instructed to remove from runtime; without an add-time replacement, implementations can persist different mappings or leave supported routes empty while satisfying the stated ordering tests. Freeze the sanctioned alias/normalization rules and deterministic tie-breaks, with fixtures for each backend, before making the one-time write authoritative. | AC-22 | final `agent-chain.schema.json`, `opencode-overlay.md`, and `api.md`; `core/handlers/model_hub/{service,resolver}.py`; `tests/test_model_hub_{api,resolution}.py` | I1 |+| **Specify the add-time model matching algorithm**<br><br>**Closed by owner ruling 2026-08-09: `matching-v1`.** The Add Source path transcribes the former resolver semantics: Claude native aliases use discovered-only inventory and the deterministic `(version_tuple, date_or_zero, model_id)` maximum; OpenCode uses exact checked identifiers or a unique bare suffix; Codex and non-native sources use literal equality. The stored hop is the concrete upstream id and runtime never repeats matching. | AC-22 | `model-hub.md` §4.2 `matching-v1`, `opencode-overlay.md`, `api.md`, `core/handlers/model_hub/{service,resolver}.py`, and backend fixtures in `tests/test_model_hub_{api,resolution}.py` | I1 || **Assign the controller gate removal to I1**<br><br>Fresh evidence beyond the resolved default-off thread is that this landing row promises an available Models controller but assigns only handler files and `vibe/ui_server.py`; neither the active lane scopes nor the complete checklist includes `core/controller.py` or `tests/test_controller_model_hub_gate.py`. The current controller returns early when `VIBE_MODEL_HUB_ENABLED` is absent, and that test explicitly expects `model_hub_runtime is None`, so I1 can satisfy every named file/test while fresh installations still have no runtime. Add the controller and its gate test to I1's owned transition.<br><br>AGENTS.md reference: [AGENTS.md:L145-L147](https://github.com/avibe-bot/avibe/blob/0309b62d167ede209bd429afc401144c93cc677a/AGENTS.md#L145-L147) | AC-22 + AC-31 | `core/controller.py`; `tests/test_controller_model_hub_gate.py` | I1 |**Forward stop.** After the S-1 head, if a review reports at least three findings in the samediff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex 7849b99d3..e4035dc2a 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -337,6 +337,53 @@ No health score, latency, cost, usage, vendor label, creation timestamp, or lateinventory result reorders existing configuration. `created_at` remains ordinary Sourcemetadata for audit/display; routing and placement never read or mutate it.+**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.++| Backend/source case | Candidate set | Accepted match and tie-break |+| --- | --- | --- |+| Claude fixed-menu id on a native `anthropic` Source | The Source's `discovered` models observed by this add transaction | A dated request is literal only. An undated version request matches the same family and exact version tuple; a bare `opus`, `sonnet`, or `haiku` alias matches that family at any version. Select `max(version_tuple, date_or_zero, model_id)`. `fable` has no bare alias. |+| OpenCode menu id | The Source's observed models projected through its normalized provider id | Exact checked id first; otherwise a bare model id matches only when exactly one checked identifier ends with `/<bare>`. Zero or multiple matches is rejected as ambiguous. |+| Codex fixed-menu id, or any non-native Source | The Source's observed models | Literal model-id equality only. Explicit user route edits may name an exact model, but runtime never infers or substitutes one. |++The resulting hop always contains the selected concrete upstream model id, never the menu+alias. A missing or ambiguous match leaves that menu model's Route empty; it does not+create a runtime matching branch.++The `matching-v1` decision is normative and exhaustive:++```text+for each configuration-eligible Source added in this transaction:+ observed = response_backed_observation(Source, protocol_order)+ if observed.protocol is null:+ persist no Source and no Route hop+ return the classified observation failure++ for each backend menu model M:+ candidates = observed.discovered_models+ if backend == opencode:+ checked = M if M is checked else the unique checked identifier ending with "/" + M+ match = the unique candidate whose normalized provider/model identifier equals checked+ elif backend == claude and Source is native anthropic:+ match = native_claude_alias(M, candidates)+ else:+ match = literal_model_id(M, candidates)++ if match is not null:+ append {source_id: Source.id, model_id: match} to the stored Route tail++ persist the Source and all accepted concrete hops once+```++`native_claude_alias` is the literal former resolver rule: dated requests are literal;+undated version requests require an equal version tuple; bare aliases match a family;+the total order is `(version_tuple, date_or_zero, model_id)`. `exact_checked_identifier`+and the unique suffix rule are the OpenCode overlay rule. No other backend gets an+alias family, and explicit user-authored Route edits remain literal configuration.+**Routing configuration is per backend and per model; health is Source-global.** Quotaand reachability belong to the Source, not the Agent that touched it. §4.3 reads thestored chain and annotates its live execution state; it does not construct anotherdiff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex c5ef614e2..a4938f22d 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -16,12 +16,15 @@ from typing import Any, Callable, Literal, Mapping, Optional, castfrom config import pathsfrom config.v2_config import ModelHubConfig, ModelHubSourceConfigfrom core.handlers.model_hub.classification import ResolutionDecision-from core.handlers.model_hub.events import EventAgent, EventReason-from core.handlers.model_hub.identifiers import parse_opencode_model_id+from core.handlers.model_hub.events import (+ EVENT_REASON_AUTHORITY,+ EventAgent,+ EventReason,+ event_reason_label,+)from core.handlers.model_hub.resolver import (BackendName,ModelHubTurnResolution,- normalize_opencode_requested_model,resolve_model_hub_turn,source_after_cooldown_recovery,source_eligible_for_backend,@@ -260,15 +263,12 @@ def _localized_launch_error(source = str(blocker.get("source") or "")detail_key = str(blocker.get("detail_key") or "")blocker_reason = str(blocker.get("reason") or "")- if blocker_reason == "native_cli_unavailable":- detail = i18n_t(- "modelHub.launch.native_cli_unavailable",- language,- )+ if blocker_reason in EVENT_REASON_AUTHORITY:+ detail = event_reason_label(blocker_reason, language)else:reason = _SOURCE_DETAIL_EVENT_REASONS.get(detail_key)detail = (- i18n_t(f"modelHub.events.reason.{reason}", language)+ event_reason_label(reason, language)if reason is not Noneelse str(blocker.get("status") or ""))@@ -345,16 +345,13 @@ def build_codex_hub_launch(return overrides + list(base_args), env-def _provider_package(protocol: str) -> str:- if protocol == "anthropic":- return "@ai-sdk/anthropic"- if protocol == "openai_responses":- return "@ai-sdk/openai"+def _provider_package() -> str:+ # OpenCode speaks one stable frontend protocol to the local Gateway. The+ # persisted exact hop selects the upstream protocol behind that boundary.return "@ai-sdk/openai-compatible"-def _provider_base_url(gateway_base_url: str, protocol: str) -> str:- # All supported OpenCode SDK adapters expect their versioned API root.+def _provider_base_url(gateway_base_url: str) -> str:return f"{gateway_base_url.rstrip('/')}/v1"@@ -687,6 +684,14 @@ class ModelHubRuntimeRouter:config: ModelHubConfig,resolution: ModelHubTurnResolution,) -> EventReason:+ structural_reason = resolution.structural_blocker_reason+ if structural_reason in {+ "route_unconfigured",+ "source_missing",+ "model_unsupported",+ "native_cli_unavailable",+ }:+ return cast(EventReason, structural_reason)order = config.effective_source_order(resolution.backend)sources_by_id = {source.id: source for source in config.sources}enabled_sources = [@@ -714,6 +719,11 @@ class ModelHubRuntimeRouter:resolution: ModelHubTurnResolution,) -> dict[str, Any]:model = resolution.requested_model or resolution.target_model+ if resolution.route_reason == "route_unconfigured":+ return {+ "copy_key": "route_unconfigured",+ "model": model,+ }if resolution.supply_status == "waiting":cooling = [source@@ -731,23 +741,15 @@ class ModelHubRuntimeRouter:"retry_at": recovery,}if resolution.matching_sources:- candidate_ids = {- source.id for source in resolution.candidates- }blockers = [{- "source": source.display_name,- "status": source.state.status,- "detail_key": source.state.detail_key,- "reason": (- "native_cli_unavailable"- if source.supply_channel == "native_cli"- and source.state.status in {"active", "standby"}- and source.id not in candidate_ids- else None- ),+ "source": inspection.source.display_name,+ "status": inspection.source.state.status,+ "detail_key": inspection.source.state.detail_key,+ "reason": inspection.reason,}- for source in resolution.matching_sources+ for inspection in resolution.inspected_hops+ if inspection.source is not None]return {"copy_key": "interrupted",@@ -787,7 +789,10 @@ class ModelHubRuntimeRouter:requested_model_id=requested_model,supply_state=supply_state,)- if not resolution.matching_sources:+ if (+ not resolution.matching_sources+ or resolution.structural_blocker_reason is not None+ ):reason = self._supply_interruption_reason(config, resolution)supply_key = (backend, requested_model)current_state = ("interrupted", reason)@@ -876,15 +881,6 @@ class ModelHubRuntimeRouter:)target_model = resolution.target_model- if resolution.mapping_applied:- self.service._record_event(- agent=cast(EventAgent, backend),- kind="mapping_applied",- model_id=target_model,- reason="mapping",- from_label=requested_model,- now=self.service.now(),- )source = resolution.sourceself._last_supply_state[(backend, requested_model)] = ("ok", None)if source.supply_channel == "native_cli":@@ -910,7 +906,7 @@ class ModelHubRuntimeRouter:requested_model_id=requested_model,source_id=source.id,resolved_model_id=target_model,- via_mapping=resolution.mapping_applied,+ via_mapping=False,)else:gateway_base_url, gateway_token = await self._gateway_credentials(@@ -920,7 +916,7 @@ class ModelHubRuntimeRouter:requested_model_id=requested_model,resolved_model_id=target_model,source_id=source.id,- via_mapping=resolution.mapping_applied,+ via_mapping=False,)runtime_model = target_modelif self.turn_gateway is None:@@ -1054,34 +1050,39 @@ class ModelHubRuntimeRouter:available_identifiers: list[str] = []launches: list[ModelHubLaunch] = []for identifier in dict.fromkeys(checked):- try:- provider_id, model_id = parse_opencode_model_id(identifier)- except ValueError:- raise ModelHubError("mapping_target_unavailable", status=409) from Noneconfig, resolution = await self._resolve_turn(config,"opencode",identifier,supply_channel="hub",)- available_source = resolution.source- source = available_source- if source is None:- # Keep a cooling/error route's public identifier stable in the- # overlay. Per-turn resolution still rejects that requested- # route, while unrelated checked models remain usable.- source = next(- (- candidate- for candidate in resolution.matching_sources- if candidate.supply_channel == "hub"- ),- None,+ provider_id = resolution.menu_provider_id+ menu_model_id = resolution.menu_model_id+ if provider_id is None or menu_model_id is None:+ raise ModelHubError("mapping_target_unavailable", status=409)+ inspection = (+ resolution.candidate_hops[0]+ if resolution.candidate_hops+ else None+ )+ if inspection is None:+ # Keep every configured route's public identifier stable in the+ # overlay. Per-turn resolution still rejects unavailable hops.+ inspection = (+ resolution.projectable_hops[0]+ if resolution.projectable_hops+ else None)- if source is None:+ if (+ inspection is None+ or inspection.source is None+ or inspection.model_id is None+ ):continue- package = _provider_package(source.protocol)- base_url = _provider_base_url(gateway_base_url, source.protocol)+ source = inspection.source+ exact_model_id = inspection.model_id+ package = _provider_package()+ base_url = _provider_base_url(gateway_base_url)provider = providers.setdefault(provider_id,{@@ -1091,26 +1092,31 @@ class ModelHubRuntimeRouter:"models": {},},)- if provider["npm"] != package or provider["options"]["baseURL"] != base_url:- raise ModelHubError("mapping_target_unavailable", status=409)- model = next(item for item in source.models if item.id == model_id)+ model = next(+ (item for item in source.models if item.id == exact_model_id),+ None,+ )runtime_model = identifierif self.turn_gateway is None:prefix = await self._source_prefix(source.id)- runtime_model = f"{prefix}/{model_id}"- provider["models"][model_id] = {+ runtime_model = f"{prefix}/{exact_model_id}"+ provider["models"][menu_model_id] = {"id": runtime_model,- "name": model.display_name or model_id,+ "name": (+ model.display_name+ if model is not None and model.display_name+ else menu_model_id+ ),}projected_identifiers.append(identifier)- if available_source is not None:+ if resolution.candidate_hops:available_identifiers.append(identifier)launches.append(ModelHubLaunch(backend="opencode",channel="hub",requested_model=identifier,- target_model=model_id,+ target_model=exact_model_id,runtime_model=runtime_model,source_id=source.id,gateway_base_url=gateway_base_url,@@ -1174,10 +1180,6 @@ def opencode_model_for_overlay(model: str | None, overlay: OpenCodeOverlay | Nonif not overlay.available_identifiers:raise ModelHubError("mapping_target_unavailable", status=409)return overlay.available_identifiers[0]- normalized = normalize_opencode_requested_model(- candidate,- overlay.checked_identifiers,- )- if normalized is not None:- return normalized+ if candidate in overlay.checked_identifiers:+ return candidateraise ModelHubError("mapping_target_unavailable", status=409)diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 491b04f85..571649ec4 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -17,6 +17,8 @@ sys.path.insert(0, str(ROOT))from config.v2_config import (AgentsConfig,ModelHubModelConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,ModelHubSourceConfig,ModelHubSourceStateConfig,PlatformsConfig,@@ -765,7 +767,14 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):],)harness.store.config.sources.append(source)- harness.store.config.refresh_follow_orders()+ harness.store.config.agents["claude"].sources.order.append(source.id)+ harness.store.config.agents["claude"].routes["claude-opus-4-6"] = (+ ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),+ )+ )+ )with self.assertRaises(ModelHubError) as refused:await harness.service.reauth_source(source.id, {})@@ -841,7 +850,14 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):models=[ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered")],)harness.store.config.sources.append(source)- harness.store.config.refresh_follow_orders()+ harness.store.config.agents["claude"].sources.order.append(source.id)+ harness.store.config.agents["claude"].routes["claude-opus-4-6"] = (+ ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),+ )+ )+ )ack = {"acknowledge_irreversible": True}# 1. A second start for the same source is handed the SAME flow, and thediff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 008b3aff5..ed1951ff1 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -45,78 +45,12 @@ scenarios:kind: recoverylayer: scenariotest: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_mh_evt_002_switch_events_survive_router_and_service_restart- - id: MH-RES-001- name: Quota-exhausted failover and recovery switchback- status: partial- kind: recovery- layer: unit- test: tests/test_model_hub_resolution.py::test_quota_failure_cools_source_switches_and_emits_redacted_events- - id: MH-SRC-REFRESH-001- name: Manual source refresh replaces discovery inventory and freshness timestamp- status: partial- kind: recovery- layer: unit_contract- test: tests/test_model_hub_api.py::test_model_hub_rest_api_contract- - id: MH-PRI-001- name: Per-agent source-order mutations and follow restoration take effect immediately- status: covered- kind: ordering- layer: scenario- test: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_mh_pri_001_order_mutations_change_the_next_turn- id: MH-SEL-001name: Unpinned Hub activation stays honest and resolves the turn modelstatus: coveredkind: selectionlayer: scenariotest: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_unpinned_hub_projection_is_null_while_explicit_turn_resolves- - id: MH-MAP-001- name: Mapping applies to Claude Code only- status: partial- kind: mapping- layer: unit_contract- test: tests/test_model_hub_resolution.py::test_mapping_is_scoped_to_the_requesting_backend- - id: MH-OC-001- name: OpenCode identifiers stay stable across mode switches- status: covered- kind: stability- layer: scenario- test: tests/test_model_hub_injection.py::test_mh_ovl_001_identifiers_stay_stable_across_all_perturbations- - id: MH-CHAN-001- name: Native subscription exhaustion falls back and recovers per turn- status: covered- kind: recovery- layer: scenario- test: tests/test_model_hub_injection.py::test_mh_chan_001_native_quota_falls_back_then_recovers_next_turn- - id: MH-INJ-CLAUDE-001- name: Claude Hub launch uses environment-only gateway injection- status: covered- kind: injection- layer: scenario- test: tests/test_model_hub_injection.py::test_mh_inj_runtime_injection_never_writes_native_configs- - id: MH-INJ-CODEX-001- name: Codex Hub launch uses app-server runtime overrides- status: covered- kind: injection- layer: scenario- test: tests/test_model_hub_injection.py::test_mh_inj_runtime_injection_never_writes_native_configs- - id: MH-INJ-OPENCODE-001- name: OpenCode overlay changes drain work and restart with hash metadata- status: covered- kind: injection- layer: scenario- test: tests/test_model_hub_injection.py::test_mh_inj_opencode_overlay_change_drains_then_restarts_and_records_hash- - id: MH-INJ-DIRECT-001- name: Direct launches preserve native configuration and omit Hub injection- status: covered- kind: compatibility- layer: scenario- test: tests/test_model_hub_injection.py::test_mh_inj_runtime_injection_never_writes_native_configs- - id: MH-OVL-001- name: OpenCode visible identifiers survive source and runtime perturbations- status: covered- kind: stability- layer: scenario- test: tests/test_model_hub_injection.py::test_mh_ovl_001_identifiers_stay_stable_across_all_perturbations- id: MH-MIG-001name: Migration copies without modifying native configurationstatus: covered@@ -129,18 +63,6 @@ scenarios:kind: migrationlayer: scenariotest: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_002_oauth_defaults_to_native_sources- - id: MH-MIG-003- name: Experimental mode keeps native OAuth files in their CLI stores- status: covered- kind: migration- layer: scenario- test: tests/scenarios/model_hub/test_model_hub_migration_scenarios.py::test_mh_mig_003_experimental_flag_keeps_oauth_native- - id: MH-OAUTH-A-001- name: Paste-code OAuth happy path- status: partial- kind: oauth- layer: contract- test: tests/test_model_hub_api.py::test_model_hub_rest_api_contract- id: MH-OAUTH-B-001name: Device-code OAuth happy pathstatus: gap@@ -151,12 +73,6 @@ scenarios:status: gapkind: oauthlayer: scenario- - id: MH-OAUTH-ERR-001- name: OAuth timeout and cancel terminate cleanly- status: partial- kind: timeout_cancel- layer: contract- test: tests/test_model_hub_api.py::test_model_hub_rest_api_contract- id: MH-OAUTH-NATIVE-001name: Claude native CLI paste-code login persists an active Sourcestatus: covered@@ -175,30 +91,11 @@ scenarios:kind: timeout_cancellayer: scenariotest: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_native_003_cancel_and_timeout_terminate_cleanly- - id: MH-OAUTH-CONSENT-001- name: Experimental hub OAuth requires and persists explicit consent before Source creation- status: covered- kind: oauth_consent- layer: scenario- test: tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py::test_mh_oauth_consent_001_is_required_and_persistednext_priority:- - MH-RES-001- - MH-PRI-001- MH-SEL-001- - MH-MAP-001- - MH-OC-001- - MH-CHAN-001- - MH-INJ-CLAUDE-001- - MH-INJ-CODEX-001- - MH-INJ-OPENCODE-001- - MH-INJ-DIRECT-001- - MH-OVL-001- MH-MIG-001- - MH-OAUTH-A-001- MH-OAUTH-B-001- MH-OAUTH-C-001- - MH-OAUTH-ERR-001- MH-OAUTH-NATIVE-001- MH-OAUTH-NATIVE-002- MH-OAUTH-NATIVE-003- - MH-OAUTH-CONSENT-001diff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.pyindex b62ea26a0..a88b32eab 100644--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py@@ -17,8 +17,11 @@ from config.v2_config import (ModelHubAgentSupplyConfig,ModelHubConfig,ModelHubModelConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,ModelHubSourceConfig,ModelHubSourceStateConfig,+ model_hub_fixed_menu_ids,)from core.handlers.model_hub.adapter import (EngineHealth,@@ -44,6 +47,18 @@ class MemoryStore:self.config = config+def _requested_model(backend: str) -> str:+ if backend == "opencode":+ return "anthropic/model-live"+ return model_hub_fixed_menu_ids(backend)[0]+++def _source_model_id(backend: str) -> str:+ if backend == "opencode":+ return "model-live"+ return _requested_model(backend)++@dataclass(frozen=True)class AdapterResult:kind: RawOutcomeKind@@ -73,10 +88,16 @@ class InvokeHandle:class AdapterBoundaryFake:- def __init__(self, results: list[AdapterResult]) -> None:+ def __init__(+ self,+ results: list[AdapterResult],+ *,+ refreshable_credential_refs: tuple[str, ...] = (),+ ) -> None:self.results = deque(results)self.invocations: list[tuple[str, str, str]] = []self.requests: list[object] = []+ self.refreshable_credential_refs = frozenset(refreshable_credential_refs)async def start(self) -> EngineStatus:return EngineStatus(EngineHealth.OK, "test", True, "127.0.0.1", 18443, None)@@ -90,6 +111,9 @@ class AdapterBoundaryFake:async def revoke_credential(self, credential_ref: str) -> None:return None+ async def credential_supports_refresh(self, credential_ref: str) -> bool:+ return credential_ref in self.refreshable_credential_refs+async def invoke(self, source_id, model_id, request, stream, origin) -> InvokeHandle:self.invocations.append((source_id, model_id, origin))self.requests.append(request)@@ -121,7 +145,14 @@ def _source(supply_channel=channel,billing="monthly" if kind == "subscription" else "metered",state=ModelHubSourceStateConfig(status="standby"),- models=[ModelHubModelConfig(id="model-live", provenance="discovered")],+ models=[+ ModelHubModelConfig(id=model_id, provenance="discovered")+ for model_id in (+ _source_model_id("claude"),+ _source_model_id("codex"),+ _source_model_id("opencode"),+ )+ ],credential_ref=f"cred_{source_id}" if channel == "hub" else None,)@@ -134,10 +165,20 @@ def _config(*sources: ModelHubSourceConfig) -> ModelHubConfig:for backend in ("claude", "codex", "opencode")},)- for agent in config.agents.values():+ for backend, agent in config.agents.items():+ eligible_sources = tuple(+ source+ for source in sources+ if ModelHubConfig.source_eligible_for_backend(source, backend)+ )agent.sources = ModelHubAgentSourcesConfig(- policy="custom",- order=[source.id for source in sources],+ order=[source.id for source in eligible_sources],+ )+ agent.routes[_requested_model(backend)] = ModelHubRouteConfig(+ hops=tuple(+ ModelHubRouteHopConfig(source.id, _source_model_id(backend))+ for source in eligible_sources+ ))return config@@ -174,25 +215,6 @@ async def _post_turn(return response.status, await response.read()-def test_mh_pri_001_source_order_projection_has_no_policy_state(tmp_path: Path) -> None:- """MH-PRI-001: the persisted Source order is projected without policy state."""-- alpha = _source("src_alpha001")- zulu = _source("src_zulu0001")- store = MemoryStore(_config(alpha, zulu))- store.config.agents["claude"].sources.order = [zulu.id, alpha.id]- service = _service(- tmp_path,- store,- AdapterBoundaryFake([]),- now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc),- )-- projected = service.get_agent_sources("claude")["sources"]- assert projected["order"] == [zulu.id, alpha.id]- assert "policy" not in projected--def test_unpinned_hub_projection_is_null_while_explicit_turn_resolves(tmp_path: Path,) -> None:@@ -219,9 +241,9 @@ def test_unpinned_hub_projection_is_null_while_explicit_turn_resolves(gateway = ModelHubTurnGateway(service)router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)try:- launch = await router.resolve("claude", "model-live")+ launch = await router.resolve("claude", _requested_model("claude"))assert launch.source_id == source.id- assert launch.target_model == "model-live"+ assert launch.target_model == _source_model_id("claude")finally:await gateway.close()@@ -231,9 +253,9 @@ def test_unpinned_hub_projection_is_null_while_explicit_turn_resolves(@pytest.mark.parametrize(("backend", "requested_model", "endpoint"),[- ("claude", "model-live", "messages"),- ("codex", "model-live", "responses"),- ("opencode", "anthropic/model-live", "messages"),+ ("claude", _requested_model("claude"), "messages"),+ ("codex", _requested_model("codex"), "responses"),+ ("opencode", _requested_model("opencode"), "messages"),],)@pytest.mark.parametrize(@@ -264,7 +286,7 @@ def test_mh_res_live_001_pre_stream_failure_falls_back_within_turn(AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"recovered":true}'),])- store = MemoryStore(_config(_source("src_primary"), _source("src_backup")))+ store = MemoryStore(_config(_source("src_primary1"), _source("src_backup01")))assert store.config.agents["opencode"].menu is not Nonestore.config.agents["opencode"].menu.checked = ["anthropic/model-live"]service = _service(tmp_path, store, adapter, now=lambda: clock[0])@@ -280,7 +302,7 @@ def test_mh_res_live_001_pre_stream_failure_falls_back_within_turn(status, body = await _post_turn(launch, endpoint=endpoint)assert status == 200assert body == b'{"ok":true}'- assert [call[0] for call in adapter.invocations] == ["src_primary", "src_backup"]+ assert [call[0] for call in adapter.invocations] == ["src_primary1", "src_backup01"]assert store.load().sources[0].state.status == "cooldown"assert [event["kind"] for event in service.list_events(limit=5)[:2]] == ["switch", "cooldown"]assert service.list_events(limit=5)[1]["reason"] == reason@@ -301,7 +323,7 @@ def test_mh_res_live_001_pre_stream_failure_falls_back_within_turn()assert recovered_status == 200assert recovered_body == b'{"recovered":true}'- assert adapter.invocations[-1][0] == "src_primary"+ assert adapter.invocations[-1][0] == "src_primary1"finally:await gateway.close()@@ -316,9 +338,15 @@ def test_mh_res_live_002_401_refreshes_once_in_live_turn(tmp_path: Path) -> None[AdapterResult(RawOutcomeKind.HTTP_ERROR, status=401),AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}'),- ]+ ],+ refreshable_credential_refs=("cred_src_primary1",),+ )+ store = MemoryStore(+ _config(+ _source("src_primary1", kind="subscription"),+ _source("src_backup01", kind="subscription"),+ ))- store = MemoryStore(_config(_source("src_primary"), _source("src_backup")))service = _service(tmp_path,store,@@ -328,10 +356,12 @@ def test_mh_res_live_002_401_refreshes_once_in_live_turn(tmp_path: Path) -> Nonegateway = ModelHubTurnGateway(service)router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)try:- status, body = await _post_turn(await router.resolve("claude", "model-live"))+ status, body = await _post_turn(+ await router.resolve("claude", _requested_model("claude"))+ )assert status == 200assert body == b'{"ok":true}'- assert [call[0] for call in adapter.invocations] == ["src_primary", "src_primary"]+ assert [call[0] for call in adapter.invocations] == ["src_primary1", "src_primary1"]assert store.load().sources[0].state.status == "standby"finally:await gateway.close()@@ -350,9 +380,15 @@ def test_mh_res_live_002_second_401_blocks_source_and_falls_back(AdapterResult(RawOutcomeKind.HTTP_ERROR, status=401),AdapterResult(RawOutcomeKind.HTTP_ERROR, status=401),AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"backup":true}'),- ]+ ],+ refreshable_credential_refs=("cred_src_primary1", "cred_src_backup01"),+ )+ store = MemoryStore(+ _config(+ _source("src_primary1", kind="subscription"),+ _source("src_backup01", kind="subscription"),+ ))- store = MemoryStore(_config(_source("src_primary"), _source("src_backup")))service = _service(tmp_path,store,@@ -362,12 +398,14 @@ def test_mh_res_live_002_second_401_blocks_source_and_falls_back(gateway = ModelHubTurnGateway(service)router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)try:- status, _body = await _post_turn(await router.resolve("claude", "model-live"))+ status, _body = await _post_turn(+ await router.resolve("claude", _requested_model("claude"))+ )assert status == 200assert [call[0] for call in adapter.invocations] == [- "src_primary",- "src_primary",- "src_backup",+ "src_primary1",+ "src_primary1",+ "src_backup01",]primary = store.load().sources[0]assert primary.state.status == "needs_action"@@ -400,7 +438,7 @@ def test_mh_res_live_003_started_stream_never_retries(tmp_path: Path) -> None:AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b"data: backup\n\n"),])- store = MemoryStore(_config(_source("src_primary"), _source("src_backup")))+ store = MemoryStore(_config(_source("src_primary1"), _source("src_backup01")))service = _service(tmp_path,store,@@ -410,10 +448,13 @@ def test_mh_res_live_003_started_stream_never_retries(tmp_path: Path) -> None:gateway = ModelHubTurnGateway(service)router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)try:- status, body = await _post_turn(await router.resolve("claude", "model-live"), stream=True)+ status, body = await _post_turn(+ await router.resolve("claude", _requested_model("claude")),+ stream=True,+ )assert status == 200assert body == b"data: partial\n\n"- assert [call[0] for call in adapter.invocations] == ["src_primary"]+ assert [call[0] for call in adapter.invocations] == ["src_primary1"]assert store.load().sources[0].state.status == "standby"finally:await gateway.close()@@ -436,7 +477,7 @@ def test_turn_gateway_nonstream_buffer_surfaces_terminal_failure(),])- store = MemoryStore(_config(_source("src_primary")))+ store = MemoryStore(_config(_source("src_primary1")))service = _service(tmp_path,store,@@ -447,7 +488,7 @@ def test_turn_gateway_nonstream_buffer_surfaces_terminal_failure(router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)try:status, body = await _post_turn(- await router.resolve("claude", "model-live"),+ await router.resolve("claude", _requested_model("claude")),)assert status == 429assert json.loads(body)["error"]["code"] == "stream_interrupted"@@ -460,7 +501,7 @@ def test_turn_gateway_nonstream_buffer_surfaces_terminal_failure(def test_turn_gateway_tokens_are_bound_to_backend_origin(tmp_path: Path) -> None:async def exercise() -> None:adapter = AdapterBoundaryFake([AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}')])- store = MemoryStore(_config(_source("src_primary")))+ store = MemoryStore(_config(_source("src_primary1")))service = _service(tmp_path,store,@@ -475,7 +516,7 @@ def test_turn_gateway_tokens_are_bound_to_backend_origin(tmp_path: Path) -> Noneasync with client.post(f"{claude_url}/v1/messages",headers={"Authorization": f"Bearer {codex_token}"},- json={"model": "model-live", "messages": []},+ json={"model": _requested_model("claude"), "messages": []},) as response:assert response.status == 401assert adapter.invocations == []@@ -488,7 +529,7 @@ def test_turn_gateway_tokens_are_bound_to_backend_origin(tmp_path: Path) -> Nonedef test_turn_gateway_preserves_only_protocol_capability_headers(tmp_path: Path) -> None:async def exercise() -> None:adapter = AdapterBoundaryFake([AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}')])- store = MemoryStore(_config(_source("src_primary")))+ store = MemoryStore(_config(_source("src_primary1")))service = _service(tmp_path,store,@@ -506,7 +547,7 @@ def test_turn_gateway_preserves_only_protocol_capability_headers(tmp_path: Path)"Authorization": "Bearer upstream-must-not-cross","anthropic-beta": "interleaved-thinking",},- json={"model": "model-live", "messages": []},+ json={"model": _requested_model("claude"), "messages": []},) as response:assert response.status == 200request = adapter.requests[0]@@ -524,8 +565,8 @@ def test_mh_evt_002_switch_events_survive_router_and_service_restart(tmp_path: Pasync def exercise() -> None:clock = datetime(2026, 7, 25, tzinfo=timezone.utc)- native = _source("src_native", channel="native_cli", kind="subscription")- backup = _source("src_backup")+ native = _source("src_native01", channel="native_cli", kind="subscription")+ backup = _source("src_backup01")store = MemoryStore(_config(native, backup))first_adapter = AdapterBoundaryFake([])first_service = _service(tmp_path, store, first_adapter, now=lambda: clock)@@ -535,7 +576,7 @@ def test_mh_evt_002_switch_events_survive_router_and_service_restart(tmp_path: Pturn_gateway=first_gateway,native_cli_ready=lambda backend: True,)- launch = await first_router.resolve("codex", "model-live")+ launch = await first_router.resolve("codex", _requested_model("codex"))assert launch.channel == "native_cli"context = SimpleNamespace()bind_launch(context, launch)@@ -551,15 +592,18 @@ def test_mh_evt_002_switch_events_survive_router_and_service_restart(tmp_path: Pnative_cli_ready=lambda backend: True,)try:- fallback = await second_router.resolve("codex", "model-live")+ fallback = await second_router.resolve(+ "codex",+ _requested_model("codex"),+ )assert fallback.channel == "hub"persisted = BoundedEventLog(tmp_path / "events.json").list(limit=10)assert [event["kind"] for event in persisted[:2]] == ["switch","cooldown",]- assert persisted[0]["from_source"] == "src_native"- assert persisted[0]["to_source"] == "src_backup"+ assert persisted[0]["from_source"] == "src_native01"+ assert persisted[0]["to_source"] == "src_backup01"finally:await second_gateway.close()diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.pyindex 7d7a52333..d7f9b958c 100644--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py@@ -16,6 +16,11 @@ from config.v2_config import (ModelHubSourceConfig,ModelHubSourceStateConfig,)+from core.handlers.model_hub.adapter import (+ ObservationDiscovery,+ ObservationOutcome,+ SourceObservation,+)from core.handlers.model_hub.events import BoundedEventLogfrom core.handlers.model_hub.migration import scan_native_configsfrom core.handlers.model_hub.oauth import OAuthFlowRegistry@@ -59,11 +64,56 @@ class MigrationAdapter:def __init__(self) -> None:self.provisioned: list[tuple[str, int, str]] = []self.revoked: list[str] = []+ self.transient_refs: list[str] = []+ self.transient_revoked: list[str] = []+ self.observed: list[tuple[str, tuple[str, ...]]] = []+ self.observed_protocols = {+ "anthropic": "anthropic",+ "openai": "openai_responses",+ "openrouter": "openai_chat",+ "zhipuai": "openai_chat",+ }+ self.unproven_observation_vendor: str | None = Noneself.synced: list[tuple[object, ...]] = []- self.fail_discovery_ref: str | None = Noneself.fail_revoke_refs: set[str] = set()self.fail_sync_count = 0+ async def provision_transient_credential(+ self,+ vendor: str,+ secret: str,+ base_url: str | None,+ ) -> str:+ credential_ref = f"cred_observation_{len(self.transient_refs) + 1}"+ self.transient_refs.append(credential_ref)+ return credential_ref++ async def observe_source(+ self,+ vendor: str,+ base_url: str | None,+ credential_ref: str,+ protocol_order,+ ) -> SourceObservation:+ self.observed.append((vendor, tuple(protocol_order)))+ if vendor == self.unproven_observation_vendor:+ return SourceObservation(+ outcome=ObservationOutcome.AMBIGUOUS,+ reachable=True,+ authenticated=True,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ return SourceObservation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol=self.observed_protocols[vendor],+ discovery=ObservationDiscovery.SUCCEEDED,+ model_ids=(f"{vendor}-model",),+ )+async def provision_credential(self,vendor: str,@@ -82,8 +132,6 @@ class MigrationAdapter:base_url: str | None,credential_ref: str,) -> tuple[str, ...]:- if credential_ref == self.fail_discovery_ref:- raise RuntimeError("redacted upstream failure")return (f"{vendor}-model",)async def sync_sources(self, bindings) -> None:@@ -95,6 +143,9 @@ class MigrationAdapter:async def revoke_credential(self, credential_ref: str) -> None:if credential_ref in self.fail_revoke_refs:raise RuntimeError("redacted revoke failure")+ if credential_ref in self.transient_refs:+ self.transient_revoked.append(credential_ref)+ returnself.revoked.append(credential_ref)@@ -467,7 +518,6 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(before = _tree_digest(native_home)service, store, adapter = _service(tmp_path)- store.config.agents["codex"].sources.policy = "custom"monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)client = app.test_client()base_url = "http://127.0.0.1:15131"@@ -496,32 +546,35 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(assert len(store.config.sources) == 4assert len(adapter.provisioned) == 4assert adapter.revoked == []+ assert adapter.transient_revoked == adapter.transient_refs+ assert len(adapter.observed) == len(adapter.transient_refs)assert before == _tree_digest(native_home)by_id = {source.id: source for source in store.config.sources}imported_ids = set(by_id)- assert store.config.agents["claude"].sources.order == []- assert store.config.agents["codex"].sources.order == []- assert store.config.agents["opencode"].sources.order == []- assert set(store.config.effective_source_order("claude")) == imported_ids- assert store.config.effective_source_order("codex") == []- assert set(store.config.effective_source_order("opencode")) == imported_ids+ for backend in ("claude", "codex", "opencode"):+ assert store.config.agents[backend].sources.order == [+ source.id+ for source in store.config.sources+ if ModelHubConfig.source_eligible_for_backend(source, backend)+ ]codex_payload = next(agent for agent in service.list_agents() if agent["backend"] == "codex")- assert codex_payload["sources"]["order"] == []+ assert codex_payload["sources"]["order"] == store.config.agents["codex"].sources.orderassert {item["source_id"]for item in codex_payload["sources"]["eligibility"]if item["eligible"]} == imported_idsassert all(- by_id[source_id].billing == "metered"- for source_id in store.config.effective_source_order("opencode")+ source.billing == "metered"+ for source in store.config.sources+ if source.kind == "api_key")codex_source = next(source for source in store.config.sources if source.vendor == "openai" and source.kind == "api_key")- assert codex_source.protocol == "openai_chat"+ assert codex_source.protocol == "openai_responses"assert codex_source.base_url == "https://codex-relay.example/v1"openrouter_source = next(source for source in store.config.sources if source.vendor == "openrouter")assert openrouter_source.base_url == "https://openrouter.ai/api/v1"@@ -564,6 +617,9 @@ def test_mh_mig_002_oauth_defaults_to_native_sources(result = asyncio.run(service.migration_apply([item["id"] for item in oauth_items]))assert result["applied"] == 2+ assert {position["source_id"] for position in result["added_to"]} == {+ source.id for source in store.config.sources+ }assert {(source.vendor, source.kind, source.supply_channel, source.credential_ref) for source in store.config.sources} == {@@ -573,28 +629,6 @@ def test_mh_mig_002_oauth_defaults_to_native_sources(assert adapter.provisioned == []-def test_mh_mig_003_experimental_flag_keeps_oauth_native(- monkeypatch: pytest.MonkeyPatch,- tmp_path: Path,-) -> None:- """Scenario: MH-MIG-003."""-- native_home = tmp_path / "native-home"- _write_codex_oauth(native_home)- _isolate_native_home(monkeypatch, native_home)- service, store, adapter = _service(tmp_path)- store.config.subscription_hub_experimental = True- oauth_item = next(item for item in service.migration_scan()["items"] if item["kind"] == "oauth_native")- assert oauth_item["proposed_action"] == "keep_native"- assert oauth_item["notes_key"] == "settings.models.source.nativeSupply"-- result = asyncio.run(service.migration_apply([oauth_item["id"]]))- assert result["applied"] == 1- assert adapter.provisioned == []- assert len(store.config.sources) == 1- assert store.config.sources[0].supply_channel == "native_cli"--@pytest.mark.parametrize(("writer", "vendor", "protocol"),(@@ -965,12 +999,13 @@ def test_failed_batch_revokes_every_provisioned_credential(_isolate_native_home(monkeypatch, native_home)service, store, adapter = _service(tmp_path)item_ids = [item["id"] for item in service.migration_scan()["items"]]- adapter.fail_discovery_ref = "cred_migration_2"+ adapter.unproven_observation_vendor = "zhipuai"with pytest.raises(ModelHubError) as error:asyncio.run(service.migration_apply(item_ids))- assert error.value.code == "engine_down"- assert adapter.revoked == ["cred_migration_2", "cred_migration_1"]+ assert error.value.code == "migration_item_conflict"+ assert adapter.revoked == ["cred_migration_1"]+ assert adapter.transient_revoked == adapter.transient_refsassert store.config.sources == []assert all(agent.sources.order == [] for agent in store.config.agents.values())@@ -1003,7 +1038,7 @@ def test_failed_revoke_survives_retry_with_same_source_id(_isolate_native_home(monkeypatch, native_home)service, store, adapter = _service(tmp_path)item_id = service.migration_scan()["items"][0]["id"]- adapter.fail_discovery_ref = "cred_migration_1"+ adapter.fail_sync_count = 1adapter.fail_revoke_refs.add("cred_migration_1")with pytest.raises(ModelHubError) as error:@@ -1013,7 +1048,6 @@ def test_failed_revoke_survives_retry_with_same_source_id(assert ":migration:" in pending.source_idassert pending.credential_ref == "cred_migration_1"- adapter.fail_discovery_ref = Noneadapter.fail_revoke_refs.clear()result = asyncio.run(service.migration_apply([item_id]))assert result["applied"] == 1diff --git a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.pyindex 1441dc7ec..5eb54ea55 100644--- a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py@@ -6,7 +6,6 @@ import pytestfrom core.handlers.model_hub.adapter import RetainedMaterialDispositionfrom tests.scenario_harness.model_hub_native_oauth import (- HubOAuthScenarioHarness,NativeOAuthScenarioHarness,)from tests.ui_server_test_helpers import csrf_headers@@ -129,8 +128,6 @@ def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_p"organizations": [{"title": "Example Org", "is_default": True}],},}- harness.store.config.agents["codex"].sources.policy = "custom"- harness.store.config.agents["codex"].sources.order = []client, headers = _client(monkeypatch, harness.service)started = client.post(@@ -171,8 +168,6 @@ def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_passert source["state"]["status"] == "standby"assert source["account_label"] == "[email protected] \u00b7 plus \u00b7 Example Org"assert source["credential_ref"] is None- assert "policy" not in codex["sources"]- assert codex["sources"]["order"] == []assert codex["sources"]["eligibility"] == [{"source_id": source["id"],@@ -251,55 +246,3 @@ def test_mh_oauth_native_003_cancel_and_timeout_terminate_cleanly(monkeypatch, tf"/api/models/oauth/status/{cancelled['flow_id']}",base_url=BASE_URL,).status_code == 404---def test_mh_oauth_consent_001_public_source_omits_retired_consent_stamp(monkeypatch, tmp_path):- """Scenario: MH-OAUTH-CONSENT-001."""-- harness = HubOAuthScenarioHarness(tmp_path)- client, headers = _client(monkeypatch, harness.service)-- rejected = client.post(- "/api/models/oauth/start",- json={"vendor": "anthropic", "channel": "hub"},- headers=headers,- base_url=BASE_URL,- )- assert rejected.status_code == 409- assert rejected.get_json()["error"] == "consent_required"- assert harness.adapter.flows == {}-- started = client.post(- "/api/models/oauth/start",- json={- "vendor": "anthropic",- "channel": "hub",- "experimental_consent": True,- },- headers=headers,- base_url=BASE_URL,- ).get_json()["flow"]- binding = harness.service.oauth_flows.binding(started["flow_id"])- assert binding is not None- assert binding.experimental_consent is True-- harness.adapter.complete(started["flow_id"])- completed = client.get(- f"/api/models/oauth/status/{started['flow_id']}",- base_url=BASE_URL,- ).get_json()["flow"]- source = client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"][0]-- assert completed["state"] == "success"- assert source["id"] == started["source_id"]- assert source["supply_channel"] == "hub"- assert "experimental_consent_at" not in source-- harness.adapter.flows.clear()- repeated = client.get(- f"/api/models/oauth/status/{started['flow_id']}",- base_url=BASE_URL,- )- assert repeated.status_code == 200- assert repeated.get_json()["flow"]["state"] == "success"- assert len(client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"]) == 1diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 356f4a984..4d45fa05c 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -12,16 +12,22 @@ from config.v2_config import (ModelHubAgentSupplyConfig,ModelHubConfig,ModelHubModelConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,ModelHubSourceConfig,ModelHubSourceStateConfig,)from core.handlers.model_hub.adapter import (EngineHealth,EngineStatus,+ ObservationDiscovery,+ ObservationOutcome,OAuthFlowState,RawCallOutcome,RawOutcomeKind,RetainedMaterialDisposition,+ SOURCE_PROTOCOLS,+ SourceObservation,)from core.handlers.model_hub.errors import ModelDiscoveryErrorfrom core.handlers.model_hub.events import BoundedEventLog, ResolutionEvent@@ -107,6 +113,12 @@ class FakeAdapter:self.orphan_cleanup_succeeds = Falseself.cancel_disposition = RetainedMaterialDisposition.NONEself.start_calls = 0+ self.credential_count = 0+ self.observation: SourceObservation | None = None+ self.observed_protocol_orders: list[tuple[str, ...]] = []+ self.retargeted_credentials: list[tuple[str, str, str, str | None, str]] = []+ self.refreshable_credential_refs: set[str] = set()+ self.discovery_credential_refs: list[str] = []async def ensure_installed(self):return await self.status()@@ -133,7 +145,30 @@ class FakeAdapter:async def provision_credential(self, vendor, protocol, secret, base_url):self.secret_lengths.append(len(secret))- return "cred_test123"+ self.credential_count += 1+ return f"cred_test{self.credential_count:03d}"++ async def retarget_api_key_credential(+ self,+ credential_ref,+ vendor,+ protocol,+ base_url,+ ):+ 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)+ )+ return replacement_ref++ async def credential_supports_refresh(self, credential_ref):+ return credential_ref in self.refreshable_credential_refs++ async def provision_transient_credential(self, vendor, secret, base_url):+ self.secret_lengths.append(len(secret))+ self.credential_count += 1+ return f"cred_test{self.credential_count:03d}"async def revoke_credential(self, credential_ref):self.revoked.append(credential_ref)@@ -148,8 +183,28 @@ class FakeAdapter:raise RuntimeError("upstream failure with sk-secret-material")async def discover_models(self, vendor, protocol, base_url, credential_ref):+ self.discovery_credential_refs.append(credential_ref)return ("claude-opus-4-6", "claude-sonnet-4-6")+ async def observe_source(self, vendor, base_url, credential_ref, protocol_order):+ self.observed_protocol_orders.append(tuple(protocol_order))+ if self.observation is not None:+ return self.observation+ models = await self.discover_models(+ vendor,+ protocol_order[0],+ base_url,+ credential_ref,+ )+ return SourceObservation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol=protocol_order[0],+ discovery=ObservationDiscovery.SUCCEEDED,+ model_ids=tuple(models),+ )+async def invoke(self, source_id, model_id, request, stream, origin):return FakeInvokeHandle(RawCallOutcome(@@ -229,9 +284,9 @@ class FakeAdapter:)-def _service(tmp_path):+def _service(tmp_path, adapter=None):store = MemoryStore()- adapter = FakeAdapter()+ adapter = adapter or FakeAdapter()service = ModelHubService(store=store,adapter=adapter,@@ -245,6 +300,27 @@ def _service(tmp_path):return service, store, adapter+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+ }+ 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+ ):+ continue+ route = agent.routes.setdefault(model.id, ModelHubRouteConfig())+ route.hops = (*route.hops, ModelHubRouteHopConfig(source.id, model.id))++async def _create_source(service: ModelHubService, payload: dict) -> dict:return (await service.create_source(payload))["source"]@@ -591,7 +667,7 @@ def test_discovery_probe_failure_is_not_reported_as_engine_down(tmp_path):)assert error.value.code == "discovery_failed"- assert adapter.revoked == ["cred_test123"]+ assert adapter.revoked == ["cred_test001"]assert store.config.sources == []@@ -721,6 +797,7 @@ def test_ui_model_hub_rpc_preserves_structured_guard_data():("method", "path"),[("GET", "/api/models/sources"),+ ("POST", "/api/models/sources/observe"),("POST", "/api/models/sources"),("PATCH", "/api/models/sources/src_test0001"),("PUT", "/api/models/sources/src_test0001/credential"),@@ -728,10 +805,12 @@ def test_ui_model_hub_rpc_preserves_structured_guard_data():("DELETE", "/api/models/sources/src_test0001"),("POST", "/api/models/sources/src_test0001/refresh"),("GET", "/api/models/agents"),+ ("GET", "/api/models/agents/claude/chain?model=claude-opus-4-6"),+ ("PUT", "/api/models/agents/claude/chain?model=claude-opus-4-6"),+ ("POST", "/api/models/agents/claude/probe"),("GET", "/api/models/agents/claude/sources"),("PUT", "/api/models/agents/claude/sources"),("PATCH", "/api/models/agents/claude/mode"),- ("PUT", "/api/models/agents/claude/mappings"),("PUT", "/api/models/agents/opencode/menu"),("POST", "/api/models/sources/src_test0001/models"),("PATCH", "/api/models/sources/src_test0001/models/custom-model"),@@ -810,461 +889,212 @@ def test_config_capability_exactly_projects_backend_model_hub_gate(monkeypatch,assert enabled is is_model_hub_enabled()-def test_disabled_gate_preserves_existing_model_hub_config_bytes(monkeypatch):- from config import paths- from core.services.settings import default_config+def test_final_model_hub_route_surface_has_observe_refresh_and_no_saved_test_route():+ routes = {route.path: set(route.methods or ()) for route in app.routes if route.path.startswith("/api/models/")}- monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)- config = default_config()- config.model_hub.subscription_hub_experimental = True- config.save()- config_path = paths.get_config_path()- before = config_path.read_bytes()- client = app.test_client()+ assert "POST" in routes["/api/models/sources/observe"]+ assert "POST" in routes["/api/models/sources/{source_id}/refresh"]+ assert all(not path.endswith("/test") for path in routes)+ assert all("/mappings" not in path for path in routes)- assert client.get("/api/config").status_code == 200- assert client.get("/api/models/sources").status_code == 404-- assert config_path.read_bytes() == before---def test_model_hub_rest_api_contract(monkeypatch, tmp_path):- """Scenarios: MH-SRC-REFRESH-001, MH-PRI-001, MH-OAUTH-A-001, MH-OAUTH-ERR-001."""+def test_unsaved_observation_route_returns_valid_result_and_revokes_transient_ref(+ monkeypatch,+ tmp_path,+):service, store, adapter = _service(tmp_path)monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)client = app.test_client()base_url = "http://127.0.0.1:15131"- headers = csrf_headers(client, base_url)-- response = client.get("/api/models/sources", base_url=base_url)- body = response.get_json()- _assert_envelope(body)- assert body["sources"] == []response = client.post(- "/api/models/sources",+ "/api/models/sources/observe",json={- "kind": "subscription","vendor": "anthropic",- "display_name": "Experimental subscription",- "supply_channel": "hub",+ "key": "sk-test-observation-only",},- headers=headers,+ headers=csrf_headers(client, base_url),base_url=base_url,)- error = response.get_json()- assert response.status_code == 409- _assert_envelope(error, ok=False)- assert error["error"] == "consent_required"- assert error["detail"] == "modelHub.errors.consent_required"- fake_key = "sk-test-never-persist-this"- response = client.post(- "/api/models/sources",- json={- "kind": "api_key",- "vendor": "anthropic",- "display_name": "Anthropic API Key",- "protocol": "anthropic",- "key": fake_key,- },- headers=headers,- base_url=base_url,- )- assert response.status_code == 201+ assert response.status_code == 200body = response.get_json()_assert_envelope(body)- assert set(body) == {- "ok",- "contract_version",- "source",- "adopted_by",- "skipped_by",- }- assert {item["backend"] for item in body["adopted_by"]} == {- "claude",- "codex",- "opencode",- }- assert body["skipped_by"] == []- source = body["source"]- _assert_valid("source.schema.json", source)- source_id = source["id"]- assert source["masked_credential"] == "sk-test…this"- assert fake_key not in json.dumps(store.config.to_payload())- assert adapter.secret_lengths[0] == len(fake_key)+ _assert_valid("observation-result.schema.json", body["observation"])+ assert body["observation"]["protocol"] == SOURCE_PROTOCOLS[0]+ assert store.config.sources == []+ assert adapter.revoked == ["cred_test001"]+ assert "credential_ref" not in json.dumps(body)- response = client.put(- "/api/models/agents/claude/sources",- json={"policy": "custom", "order": ["src_missing01"]},- headers=headers,- base_url=base_url,- )- error = response.get_json()- _assert_envelope(error, ok=False)- assert error["error"] == "invalid_source_order"- response = client.put(- "/api/models/agents/claude/sources",- json={- "policy": "follow",- "unexpected": True,- "another_rejected_key": True,- },- headers=headers,- base_url=base_url,- )- error = response.get_json()- assert error["error"] == "invalid_source_order"- assert error["detail"] == "modelHub.errors.invalid_source_order"- assert error["rejected_keys"] == ["another_rejected_key", "unexpected"]-- credential_shaped_key = "sk-secret-material-that-must-not-reflect"- response = client.put(- "/api/models/agents/claude/sources",- json={"policy": "follow", credential_shaped_key: True},- headers=headers,- base_url=base_url,- )- error = response.get_json()- assert credential_shaped_key not in json.dumps(error)- assert error["rejected_keys"] == ["[redacted]"]+def test_source_order_route_rejects_retired_policy_payload(monkeypatch, tmp_path):+ service, _, _ = _service(tmp_path)+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"+ retired_field = "pol" + "icy"+ retired_value = "fol" + "low"response = client.put("/api/models/agents/claude/sources",- json={"policy": "custom", "order": []},- headers=headers,+ json={retired_field: retired_value},+ headers=csrf_headers(client, base_url),base_url=base_url,)- custom = response.get_json()- _assert_envelope(custom)- assert "policy" not in custom["agent"]["sources"]- assert custom["agent"]["sources"]["order"] == []- codex_sources = client.get(- "/api/models/agents/codex/sources",- base_url=base_url,- ).get_json()["agent"]["sources"]- assert "policy" not in codex_sources- assert codex_sources["order"] == [source_id]-- restored = client.put(- "/api/models/agents/claude/sources",- json={"policy": "follow"},- headers=headers,- base_url=base_url,- ).get_json()- assert "policy" not in restored["agent"]["sources"]- assert restored["agent"]["sources"]["order"] == [source_id]+ assert response.status_code == 400+ assert response.get_json()["error"] == "invalid_source_order"- response = client.patch(- f"/api/models/sources/{source_id}",- json={"display_name": "Primary Anthropic"},- headers=headers,- base_url=base_url,- )- _assert_valid("source.schema.json", response.get_json()["source"])- persisted_source = store.config.sources[0]- immutable_identity = (- persisted_source.id,- persisted_source.created_at,- persisted_source.credential_ref,- )- persisted_source.state = ModelHubSourceStateConfig(- status="needs_action",- detail_key="models.source.needs_action.balance_exhausted",- )- previous_discovered_at = persisted_source.last_discovered_at- unauthorized = client.post(- f"/api/models/sources/{source_id}/refresh",- base_url=base_url,+def test_native_oauth_rejects_duplicate_source_before_adapter(tmp_path):+ service, store, adapter = _service(tmp_path)+ existing = ModelHubSourceConfig(+ id="src_native0001",+ kind="subscription",+ vendor="anthropic",+ display_name="Claude subscription",+ protocol="anthropic",+ supply_channel="native_cli",+ billing="monthly",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],)- assert unauthorized.status_code == 403- assert store.config.sources[0].last_discovered_at == previous_discovered_at+ store.config.sources.append(existing)+ _refresh_fixture_routes(store.config)- async def refreshed_models(vendor, protocol, endpoint, credential_ref):- return ("claude-opus-4-6", "claude-sonnet-4-6", "claude-opus-5")+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))- adapter.discover_models = refreshed_models- original_now = service.now- service.now = lambda: datetime(2026, 7, 31, 5, 15, tzinfo=timezone.utc)- response = client.post(- f"/api/models/sources/{source_id}/refresh",- headers=headers,- base_url=base_url,- )- body = response.get_json()- _assert_envelope(body)- assert set(body) == {"ok", "contract_version", "source", "discovered"}- assert body["discovered"] == 3- _assert_valid("source.schema.json", body["source"])- assert {model["id"] for model in body["source"]["models"]} == {- "claude-opus-4-6",- "claude-sonnet-4-6",- "claude-opus-5",- }- assert body["source"]["last_discovered_at"] == "2026-07-31T05:15:00+00:00"- assert store.config.sources[0].last_discovered_at == body["source"]["last_discovered_at"]- assert store.config.sources[0].state.status == "standby"- assert (- store.config.sources[0].id,- store.config.sources[0].created_at,- store.config.sources[0].credential_ref,- ) == immutable_identity- service.now = original_now+ assert exc_info.value.code == "native_source_already_exists"+ assert exc_info.value.data == {"existing_source_id": existing.id}+ assert adapter.oauth_start_calls == []- response = client.post(- f"/api/models/sources/{source_id}/models",- json={- "model_id": "custom-model",- "display_name": "Custom Model",- "reasoning_efforts": [],- },- headers=headers,- base_url=base_url,- )- assert response.status_code == 201- _assert_valid("source.schema.json", response.get_json()["source"])- response = client.put(- "/api/models/agents/claude/mappings",- json={"mappings": [{"builtin_id": "claude-native", "target_model_id": "custom-model", "enabled": True}]},- headers=headers,- base_url=base_url,- )- _assert_valid("agent-supply.schema.json", response.get_json()["agent"])+def test_oauth_start_normalizes_vendor_before_singleton_and_adapter(tmp_path):+ service, _store, adapter = _service(tmp_path)- response = client.get(- "/api/models/agents/claude/chain?model=claude-native",- base_url=base_url,- )- chain = response.get_json()["chain"]- _assert_valid("agent-chain.schema.json", chain)- assert chain["chain"][0]["source_id"] == source_id+ flow = asyncio.run(+ service.oauth_start({"vendor": " Anthropic ", "channel": "hub"})+ )["flow"]- response = client.post(- "/api/models/agents/claude/probe",- json={"model": "claude-native"},- headers=headers,- base_url=base_url,- )- probe_body = response.get_json()- assert "probe" in probe_body, probe_body- probe = probe_body["probe"]- _assert_valid("probe-result.schema.json", probe)- assert probe["source_id"] == source_id+ assert flow["vendor"] == "anthropic"+ assert adapter.oauth_start_calls == [(flow["source_id"], "anthropic")]- response = client.put(- "/api/models/agents/opencode/menu",- json={"menu": {"view": "featured", "checked": ["anthropic/custom-model"]}},- headers=headers,- base_url=base_url,- )- _assert_valid("agent-supply.schema.json", response.get_json()["agent"])- response = client.patch(- "/api/models/agents/codex/mode",- json={"mode": "direct"},- headers=headers,- base_url=base_url,+def test_chain_route_reorders_exact_persisted_hops(monkeypatch, tmp_path):+ service, _, _ = _service(tmp_path)+ first = asyncio.run(+ _create_source(+ service,+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "First",+ "key": "sk-test-chain-first",+ },+ ))- assert "current" not in response.get_json()["agent"]- response = client.get(- "/api/models/agents/codex/chain?model=gpt-5",- base_url=base_url,+ second = asyncio.run(+ _create_source(+ service,+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Second",+ "key": "sk-test-chain-second",+ },+ ))- assert response.status_code == 409- assert response.get_json()["error"] == "direct_mode"- assert response.get_json()["detail"] == "models.hub.direct_mode"-- agents = client.get("/api/models/agents", base_url=base_url).get_json()["agents"]- assert len(agents) == 3- for agent in agents:- assert {- "selected_by_agent",- "selected_model_id",- "selected_model_explicit",- "sources",- "supply_status",- "model_supply",- "named_agents",- } <= set(agent)- if agent["sources"] is not None:- for row in agent["sources"]["eligibility"]:- assert set(row) == {- "source_id",- "eligible",- "reason_key",- "in_current_model_chain",- "process_availability_reason",- }- _assert_valid("agent-supply.schema.json", agent)-- event_example = _schema("resolution-event.schema.json")["examples"][0]- service.events.append(ResolutionEvent(**event_example))- events = client.get("/api/models/events?limit=1", base_url=base_url).get_json()["events"]- assert events == [{**event_example, "severity": "info"}]- _assert_valid("resolution-event.schema.json", events[0])+ model_id = "claude-opus-4-6"+ hops = [+ {"source_id": second["id"], "model_id": model_id},+ {"source_id": first["id"], "model_id": model_id},+ ]+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"- response = client.post(- "/api/models/oauth/start",- json={"vendor": "anthropic", "channel": "native_cli"},- headers=headers,+ response = client.put(+ f"/api/models/agents/claude/chain?model={model_id}",+ json={"hops": hops},+ headers=csrf_headers(client, base_url),base_url=base_url,)- flow = response.get_json()["flow"]- _assert_valid("oauth-flow.schema.json", flow)-- flow = client.get(f"/api/models/oauth/status/{flow['flow_id']}", base_url=base_url).get_json()["flow"]- _assert_valid("oauth-flow.schema.json", flow)-- restarted = ModelHubService(- store=store,- adapter=adapter,- events=BoundedEventLog(tmp_path / "events.json"),- native_oauth_adapter=adapter,- oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),- revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),- now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),- )- assert asyncio.run(restarted.oauth_status(flow["flow_id"]))["flow"]["channel"] == "native_cli"- flow = client.post(- "/api/models/oauth/submit",- json={"flow_id": flow["flow_id"], "value": "secret-auth-code"},- headers=headers,- base_url=base_url,- ).get_json()["flow"]- _assert_valid("oauth-flow.schema.json", flow)- assert adapter.secret_lengths[-1] == len("secret-auth-code")- assert "secret-auth-code" not in (tmp_path / "events.json").read_text(encoding="utf-8")-- response = client.post(- "/api/models/oauth/cancel",- json={"flow_id": flow["flow_id"]},- headers=headers,- base_url=base_url,- )- _assert_envelope(response.get_json())- assert adapter.cancelled == [flow["flow_id"]]- response = client.get(f"/api/models/oauth/status/{flow['flow_id']}", base_url=base_url)- assert response.status_code == 404- assert response.get_json()["error"] == "flow_not_found"+ assert response.status_code == 200+ body = response.get_json()+ _assert_envelope(body)+ _assert_valid("agent-chain.schema.json", body["chain"])+ assert [(hop["source_id"], hop["model_id"]) for hop in body["chain"]["chain"]] == [+ (hop["source_id"], hop["model_id"]) for hop in hops+ ]+ assert body["chain"]["current"] == {"source_id": second["id"], "model_id": model_id}- expired = client.post(- "/api/models/oauth/start",- json={"vendor": "anthropic", "channel": "native_cli"},- headers=headers,- base_url=base_url,- ).get_json()["flow"]- adapter.flows[expired["flow_id"]] = OAuthFlowState(- **{**adapter.flows[expired["flow_id"]].__dict__, "expires_at_iso": "2026-07-23T02:59:00+00:00"}- )- response = client.get(f"/api/models/oauth/status/{expired['flow_id']}", base_url=base_url)- assert response.status_code == 410- assert response.get_json()["error"] == "flow_expired"- response = client.post(- "/api/models/oauth/start",- json={"vendor": "anthropic", "channel": "hub", "experimental_consent": True},- headers=headers,- base_url=base_url,+def test_delete_guard_reports_only_routes_emptied_by_this_mutation(tmp_path):+ service, store, _ = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_guard0001",+ kind="api_key",+ vendor="anthropic",+ display_name="Guarded",+ protocol="anthropic",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(+ id="claude-opus-4-6",+ provenance="discovered",+ )+ ],+ credential_ref="cred_guard0001",)- hub_flow = response.get_json()["flow"]- _assert_valid("oauth-flow.schema.json", hub_flow)- assert store.config.subscription_hub_experimental is True- adapter.flows[hub_flow["flow_id"]] = OAuthFlowState(+ store.config.sources.append(source)+ claude = store.config.agents["claude"]+ claude.sources.order = [source.id]+ claude.routes = {**{- **adapter.flows[hub_flow["flow_id"]].__dict__,- "state": "success",- "credential_ref": "cred_oauth_test",- }- )- response = client.post(- "/api/models/sources",- json={- "kind": "subscription",- "vendor": "anthropic",- "display_name": "Experimental subscription",- "supply_channel": "hub",- "oauth_flow_ref": hub_flow["flow_id"],- "experimental_consent": True,+ model_id: ModelHubRouteConfig()+ for model_id in claude.routes},- headers=headers,- base_url=base_url,- )- assert response.status_code == 201- oauth_creation = response.get_json()- assert set(oauth_creation) == {- "ok",- "contract_version",- "source",- "adopted_by",- "skipped_by",+ "claude-opus-4-6": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "claude-opus-4-6"),)),+ "claude-sonnet-4-6": ModelHubRouteConfig(),}- assert oauth_creation["skipped_by"] == []- consented_source = oauth_creation["source"]- _assert_valid("source.schema.json", consented_source)- assert "experimental_consent_at" not in consented_source- completed_binding = service.oauth_flows.binding(hub_flow["flow_id"])- assert completed_binding is not None- assert completed_binding.completed is True-- scan = client.post("/api/models/migration/scan", headers=headers, base_url=base_url).get_json()- _assert_valid("migration-scan.schema.json", {"items": scan["items"]})- applied = client.post(- "/api/models/migration/apply",- json={"item_ids": []},- headers=headers,- base_url=base_url,- ).get_json()- _assert_envelope(applied)- assert applied["applied"] == 0- runtime = client.get("/api/models/runtime/status", base_url=base_url).get_json()["runtime"]- _assert_valid("runtime-dependency.schema.json", runtime)- assert all("<" not in asset["url"] for asset in runtime["manifest"]["assets"])+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.delete_source(source.id))- response = client.delete(- f"/api/models/sources/{source_id}/models/custom-model",- json={},- headers=headers,- base_url=base_url,- )- assert response.status_code == 409- assert response.get_json()["error"] == "mode_switch_blocked"+ assert exc_info.value.code == "source_in_route_chain"+ assert exc_info.value.data["would_interrupt"] == [+ {+ "backend": "claude",+ "model_id": "claude-opus-4-6",+ "agents": [],+ }+ ]- response = client.put(- "/api/models/agents/claude/mappings",- json={"mappings": []},- headers=headers,- base_url=base_url,- )- _assert_envelope(response.get_json())- response = client.put(- "/api/models/agents/opencode/menu",- json={"menu": {"view": "featured", "checked": []}},- headers=headers,- base_url=base_url,- )- _assert_envelope(response.get_json())- response = client.delete(- f"/api/models/sources/{source_id}/models/custom-model",- json={},- headers=headers,- base_url=base_url,- )- _assert_valid("source.schema.json", response.get_json()["source"])- response = client.delete(- f"/api/models/sources/{source_id}?force=true",- headers=headers,- base_url=base_url,- )- _assert_envelope(response.get_json())- assert adapter.revoked == ["cred_test123"]+def test_disabled_gate_preserves_existing_model_hub_config_bytes(monkeypatch):+ from config import paths+ from core.services.settings import default_config++ monkeypatch.delenv("VIBE_MODEL_HUB_ENABLED", raising=False)+ config = default_config()+ config.save()+ config_path = paths.get_config_path()+ before = config_path.read_bytes()+ client = app.test_client()++ assert client.get("/api/config").status_code == 200+ assert client.get("/api/models/sources").status_code == 404++ assert config_path.read_bytes() == before@pytest.mark.parametrize(@@ -1283,7 +1113,6 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):),("/api/models/agents/claude/sources", "put", "invalid_source_order"),("/api/models/agents/claude/mode", "patch", "mode_switch_blocked"),- ("/api/models/agents/claude/mappings", "put", "mapping_target_unavailable"),("/api/models/agents/opencode/menu", "put", "mapping_target_unavailable"),("/api/models/sources/src_test0001/models",@@ -1397,7 +1226,7 @@ def test_native_reauth_route_requires_ack_before_oauth_and_returns_reauth_tail(],)store.config.sources.append(native)- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)client = app.test_client()base_url = "http://127.0.0.1:15131"@@ -1492,7 +1321,7 @@ def test_native_reauth_reuses_pending_flow_per_source(tmp_path):],)store.config.sources.append(source)- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)payload = {"acknowledge_irreversible": True}first = asyncio.run(service.reauth_source(source.id, payload))["flow"]@@ -1521,11 +1350,9 @@ def test_native_reauth_post_login_discovery_failure_reports_honest_gaps(tmp_path],)store.config.sources.append(source)- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)store.requested_model = lambda backend: ("claude-opus-4-6" if backend == "claude" else "")- service.named_agents_override = lambda backend: (- [("claude", "claude-opus-4-6")] if backend == "claude" else []- )+ service.named_agents_override = lambda backend: ([("claude", "claude-opus-4-6")] if backend == "claude" else [])flow = asyncio.run(service.reauth_source(source.id,@@ -1551,7 +1378,7 @@ def test_native_reauth_post_login_discovery_failure_reports_honest_gaps(tmp_path{"backend": "claude","model_id": "claude-opus-4-6",- "agents": ["claude"],+ "agents": ["claude"],}]assert store.config.sources[0].models == []@@ -1579,7 +1406,7 @@ def test_native_reauth_registry_failure_keeps_irreversible_state_honest(],)store.config.sources.append(source)- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)def fail_remember(*args, **kwargs):raise OSError("registry unavailable")@@ -1600,63 +1427,6 @@ def test_native_reauth_registry_failure_keeps_irreversible_state_honest(assert adapter.cancelled == [next(iter(adapter.flows))]-def test_native_reauth_invalidates_sibling_sources_for_shared_cli(tmp_path):- service, store, adapter = _service(tmp_path)- sources = [- ModelHubSourceConfig(- id=f"src_native000{index}",- kind="subscription",- vendor="anthropic",- display_name=f"Claude subscription {index}",- protocol="anthropic",- supply_channel="native_cli",- billing="monthly",- state=ModelHubSourceStateConfig(status="standby"),- account_label=f"account-{index}",- models=[- ModelHubModelConfig(- id="claude-opus-4-6",- provenance="discovered",- )- ],- )- for index in (1, 2)- ]- store.config.sources.extend(sources)- store.config.refresh_follow_orders()-- flow = asyncio.run(- service.reauth_source(- sources[0].id,- {"acknowledge_irreversible": True},- )- )["flow"]-- assert all(source.models == [] for source in store.config.sources)- assert all(- source.state.status == "needs_action"- for source in store.config.sources- )- assert all(source.account_label is None for source in store.config.sources)-- adapter.flows[flow["flow_id"]] = OAuthFlowState(- **{- **adapter.flows[flow["flow_id"]].__dict__,- "state": "success",- }- )- asyncio.run(service.oauth_status(flow["flow_id"]))-- selected, sibling = store.config.sources- assert selected.state.status == "standby"- assert selected.models- assert all(model.provenance == "discovered" for model in selected.models)- assert any(model.id == "claude-opus-4-6" for model in selected.models)- assert sibling.models == []- assert sibling.state.status == "needs_action"- assert sibling.account_label is None--def test_native_reauth_pre_boundary_failure_preserves_prior_supply(tmp_path):service, store, adapter = _service(tmp_path)source = ModelHubSourceConfig(@@ -1676,7 +1446,7 @@ def test_native_reauth_pre_boundary_failure_preserves_prior_supply(tmp_path):],)store.config.sources.append(source)- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)before = json.dumps(store.config.to_payload(),sort_keys=True,@@ -1709,11 +1479,14 @@ def test_native_reauth_pre_boundary_failure_preserves_prior_supply(tmp_path):)assert result["flow"]["state"] == "failed"- assert json.dumps(- store.config.to_payload(),- sort_keys=True,- separators=(",", ":"),- ) == before+ assert (+ json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )+ == before+ )def test_native_reauth_logout_spawn_failure_restores_prior_supply(tmp_path):@@ -1735,7 +1508,7 @@ def test_native_reauth_logout_spawn_failure_restores_prior_supply(tmp_path):],)store.config.sources.append(source)- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)before = json.dumps(store.config.to_payload(),sort_keys=True,@@ -1773,11 +1546,14 @@ def test_native_reauth_logout_spawn_failure_restores_prior_supply(tmp_path):)assert result["flow"]["state"] == "failed"- assert json.dumps(- store.config.to_payload(),- sort_keys=True,- separators=(",", ":"),- ) == before+ assert (+ json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )+ == before+ )def test_hub_reauth_is_transactional_without_native_acknowledgement(tmp_path):@@ -1789,7 +1565,6 @@ def test_hub_reauth_is_transactional_without_native_acknowledgement(tmp_path):display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="error",@@ -1804,8 +1579,7 @@ def test_hub_reauth_is_transactional_without_native_acknowledgement(tmp_path):credential_ref="cred_hub_old",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]assert flow["intent"] == "reauth"@@ -1837,7 +1611,6 @@ def test_hub_reauth_replaces_pending_flow_unknown_to_restarted_adapter(display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -1849,8 +1622,7 @@ def test_hub_reauth_replaces_pending_flow_unknown_to_restarted_adapter(credential_ref="cred_hub_old",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)first = asyncio.run(service.reauth_source(source.id, {}))["flow"]async def restarted_adapter_does_not_know_flow(_flow_id):@@ -1889,7 +1661,6 @@ def test_hub_reauth_refreshes_discovery_when_engine_reuses_credential_ref(display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="needs_action",@@ -1904,8 +1675,7 @@ def test_hub_reauth_refreshes_discovery_when_engine_reuses_credential_ref(credential_ref="cred_hub_reused",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(@@ -1968,7 +1738,6 @@ def test_concurrent_completed_hub_reauth_materializes_once(tmp_path):display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -1980,8 +1749,7 @@ def test_concurrent_completed_hub_reauth_materializes_once(tmp_path):credential_ref="cred_hub_reused",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = (await service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(@@ -2038,7 +1806,6 @@ def test_hub_reauth_irreversible_dispositions_fail_closed(display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -2054,18 +1821,13 @@ def test_hub_reauth_irreversible_dispositions_fail_closed(credential_ref="cred_hub_existing",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{**adapter.flows[flow["flow_id"]].__dict__,"state": terminal_state,- "error_key": (- "models.oauth.binding_failed"- if terminal_state == "failed"- else None- ),+ "error_key": ("models.oauth.binding_failed" if terminal_state == "failed" else None),"channel": "hub","retained_material_disposition": disposition,"retained_credential_ref": retained_credential_ref,@@ -2075,6 +1837,7 @@ def test_hub_reauth_irreversible_dispositions_fail_closed(if entrypoint == "status":result = asyncio.run(service.oauth_status(flow["flow_id"]))else:+async def return_terminal(_flow_id, _value):return adapter.flows[flow["flow_id"]]@@ -2118,7 +1881,6 @@ def test_failed_hub_reauth_non_owned_material_preserves_prior_state(display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -2134,8 +1896,7 @@ def test_failed_hub_reauth_non_owned_material_preserves_prior_state(credential_ref="cred_hub_existing",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{@@ -2156,11 +1917,14 @@ def test_failed_hub_reauth_non_owned_material_preserves_prior_state(result = asyncio.run(service.oauth_status(flow["flow_id"]))assert result["flow"]["state"] == "failed"- assert json.dumps(- store.config.to_payload(),- sort_keys=True,- separators=(",", ":"),- ) == before+ assert (+ json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )+ == before+ )assert adapter.revoked == []assert adapter.orphan_cleanup_calls == []assert service.revocations.list() == []@@ -2175,7 +1939,6 @@ def test_failed_hub_reauth_orphan_is_journaled_and_retried_by_ref(tmp_path):display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -2187,8 +1950,7 @@ def test_failed_hub_reauth_orphan_is_journaled_and_retried_by_ref(tmp_path):credential_ref="cred_hub_existing",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{@@ -2209,18 +1971,18 @@ def test_failed_hub_reauth_orphan_is_journaled_and_retried_by_ref(tmp_path):result = asyncio.run(service.oauth_status(flow["flow_id"]))assert result["flow"]["state"] == "failed"- assert json.dumps(- store.config.to_payload(),- sort_keys=True,- separators=(",", ":"),- ) == before+ assert (+ json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )+ == before+ )assert adapter.revoked == []assert adapter.orphan_cleanup_calls == ["cred_hub_orphan"]pending = service.revocations.list()- assert [- (entry.source_id, entry.credential_ref, entry.operation)- for entry in pending- ] == [+ assert [(entry.source_id, entry.credential_ref, entry.operation) for entry in pending] == [(source.id,"cred_hub_orphan",@@ -2235,9 +1997,7 @@ def test_failed_hub_reauth_orphan_is_journaled_and_retried_by_ref(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 / "revocations.json"- ),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),)@@ -2256,7 +2016,6 @@ def test_failed_hub_create_orphan_is_journaled_before_flow_can_be_forgotten({"vendor": "anthropic","channel": "hub",- "experimental_consent": True,}))["flow"]@@ -2275,10 +2034,7 @@ def test_failed_hub_create_orphan_is_journaled_before_flow_can_be_forgotten(assert result["flow"]["state"] == "failed"assert adapter.orphan_cleanup_calls == ["cred_create_orphan"]- assert [- (entry.source_id, entry.credential_ref, entry.operation)- for entry in service.revocations.list()- ] == [+ assert [(entry.source_id, entry.credential_ref, entry.operation) for entry in service.revocations.list()] == [(flow["source_id"],"cred_create_orphan",@@ -2325,9 +2081,7 @@ def test_completed_orphan_cleanup_replay_clears_surviving_service_journal(async def cleanup_orphaned_oauth_material(self, credential_ref):self.orphan_cleanup_calls.append(credential_ref)- return await self.runtime_adapter.cleanup_orphaned_oauth_material(- credential_ref- )+ return await self.runtime_adapter.cleanup_orphaned_oauth_material(credential_ref)state = EngineStateStore(tmp_path / "runtime-state")state.prepare_instance("install-1")@@ -2350,12 +2104,7 @@ def test_completed_orphan_cleanup_replay_clears_surviving_service_journal(operation="cleanup_orphaned_oauth_material",)- assert (- asyncio.run(- runtime_adapter.cleanup_orphaned_oauth_material(credential_ref)- )- is True- )+ assert asyncio.run(runtime_adapter.cleanup_orphaned_oauth_material(credential_ref)) is Trueassert journal.list()adapter = RuntimeCleanupAdapter(runtime_adapter)@@ -2398,7 +2147,6 @@ def test_failed_hub_create_consumes_known_ref_without_fabricating_source_state({"vendor": "anthropic","channel": "hub",- "experimental_consent": True,}))["flow"]@@ -2429,7 +2177,6 @@ def test_failed_hub_create_keeps_flow_when_ref_cleanup_is_not_durable(tmp_path):{"vendor": "anthropic","channel": "hub",- "experimental_consent": True,}))["flow"]@@ -2489,7 +2236,6 @@ def test_hub_reauth_retry_materializes_pending_flow(display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -2505,18 +2251,13 @@ def test_hub_reauth_retry_materializes_pending_flow(credential_ref="cred_hub_existing",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)first = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[first["flow_id"]] = OAuthFlowState(**{**adapter.flows[first["flow_id"]].__dict__,"state": terminal_state,- "error_key": (- "models.oauth.binding_failed"- if terminal_state == "failed"- else None- ),+ "error_key": ("models.oauth.binding_failed" if terminal_state == "failed" else None),"channel": "hub","retained_material_disposition": disposition,"retained_credential_ref": retained_credential_ref,@@ -2528,10 +2269,7 @@ def test_hub_reauth_retry_materializes_pending_flow(persisted = store.config.sources[0]assert [model.id for model in persisted.models] == ["manual-model"]assert persisted.state.status == "needs_action"- assert (- persisted.state.detail_key- == "models.source.needs_action.oauth_expired"- )+ assert persisted.state.detail_key == "models.source.needs_action.oauth_expired"assert service.oauth_flows.binding(first["flow_id"]) is Nonereplacement = service.oauth_flows.binding(second["flow_id"])assert replacement is not None@@ -2551,7 +2289,6 @@ def test_hub_reauth_returns_terminal_tail_when_registry_completion_fails(display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -2563,8 +2300,7 @@ def test_hub_reauth_returns_terminal_tail_when_registry_completion_fails(credential_ref="cred_hub_reused",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{@@ -2608,7 +2344,6 @@ def test_failed_same_handle_hub_reauth_requires_user_action(display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -2620,8 +2355,7 @@ def test_failed_same_handle_hub_reauth_requires_user_action(credential_ref="cred_hub_reused",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{@@ -2641,9 +2375,7 @@ def test_failed_same_handle_hub_reauth_requires_user_action(with pytest.raises(ModelHubError) as exc_info:asyncio.run(service.oauth_status(flow["flow_id"]))- assert exc_info.value.code == (- "discovery_failed" if failure == "discovery" else "engine_down"- )+ assert exc_info.value.code == ("discovery_failed" if failure == "discovery" else "engine_down")persisted = store.config.sources[0]assert persisted.credential_ref == "cred_hub_reused"assert persisted.models == []@@ -2668,7 +2400,6 @@ def test_failed_zero_model_hub_source_is_omitted_from_restart_sync(tmp_path):display_name="Failed Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="needs_action",@@ -2695,16 +2426,14 @@ def test_failed_zero_model_hub_source_is_omitted_from_restart_sync(tmp_path):credential_ref="cred_hub_healthy",)store.config.sources = [failed, healthy]- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)restarted_adapter = StrictProjectionAdapter()restarted = ModelHubService(store=store,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"),now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),)@@ -2717,10 +2446,7 @@ def test_failed_zero_model_hub_source_is_omitted_from_restart_sync(tmp_path):)assert resolved.source_id == healthy.id- assert [- tuple(binding.source_id for binding in batch)- for batch in restarted_adapter.synced- ] == [(healthy.id,)]+ assert [tuple(binding.source_id for binding in batch) for batch in restarted_adapter.synced] == [(healthy.id,)]assert adapter.synced == []@@ -2765,7 +2491,6 @@ def test_failed_hub_reauth_preserves_prior_source_and_revokes_replacement(display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -2777,8 +2502,7 @@ def test_failed_hub_reauth_preserves_prior_source_and_revokes_replacement(credential_ref="cred_hub_old",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{@@ -2801,11 +2525,14 @@ def test_failed_hub_reauth_preserves_prior_source_and_revokes_replacement(asyncio.run(service.oauth_status(flow["flow_id"]))assert exc_info.value.code == "discovery_failed"- assert json.dumps(- store.config.to_payload(),- sort_keys=True,- separators=(",", ":"),- ) == before+ assert (+ json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )+ == before+ )assert adapter.revoked == ["cred_hub_new"]assert service.oauth_flows.binding(flow["flow_id"]) is None@@ -2821,7 +2548,6 @@ def test_completed_hub_reauth_revokes_replacement_after_source_disappears(display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -2833,8 +2559,7 @@ def test_completed_hub_reauth_revokes_replacement_after_source_disappears(credential_ref="cred_hub_old",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]asyncio.run(service.delete_source(source.id, force=True))adapter.flows[flow["flow_id"]] = OAuthFlowState(@@ -2866,7 +2591,6 @@ def test_failed_hub_reauth_rolls_back_when_old_journal_cleanup_fails(tmp_path):display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -2878,8 +2602,7 @@ def test_failed_hub_reauth_rolls_back_when_old_journal_cleanup_fails(tmp_path):credential_ref="cred_hub_old",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{@@ -2907,11 +2630,14 @@ def test_failed_hub_reauth_rolls_back_when_old_journal_cleanup_fails(tmp_path):asyncio.run(service.oauth_status(flow["flow_id"]))assert exc_info.value.code == "engine_down"- assert json.dumps(- store.config.to_payload(),- sort_keys=True,- separators=(",", ":"),- ) == before+ assert (+ json.dumps(+ store.config.to_payload(),+ sort_keys=True,+ separators=(",", ":"),+ )+ == before+ )assert adapter.revoked == ["cred_hub_new"]assert service.oauth_flows.binding(flow["flow_id"]) is None@@ -2936,17 +2662,12 @@ def test_credential_route_carries_body_force_override_and_structured_guard("kind": "api_key","vendor": "anthropic","display_name": "Guarded source",- "protocol": "anthropic","key": "sk-original-route-key",}))["source"]- store.requested_model = lambda backend: (- "claude-opus-4-6" if backend == "claude" else ""- )- service.named_agents_override = lambda backend: (- [("claude", "claude-opus-4-6")] if backend == "claude" else []- )+ store.requested_model = lambda backend: ("claude-opus-4-6" if backend == "claude" else "")+ service.named_agents_override = lambda backend: ([("claude", "claude-opus-4-6")] if backend == "claude" else [])async def discover_narrower(vendor, protocol, base_url, credential_ref):return ("replacement-only-model",)@@ -2967,13 +2688,23 @@ def test_credential_route_carries_body_force_override_and_structured_guard(assert refused.status_code == 409refusal = refused.get_json()- assert refusal["error"] == "source_last_supplier"+ 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 refusal["would_interrupt"] == [{"backend": "claude","model_id": "claude-opus-4-6","agents": ["claude"],- }+ },+ {+ "backend": "claude",+ "model_id": "claude-sonnet-4-6",+ "agents": [],+ },]committed = client.put(f"/api/models/sources/{created['id']}/credential",@@ -2982,17 +2713,25 @@ def test_credential_route_carries_body_force_override_and_structured_guard(base_url=base_url,).get_json()- assert committed["recovered"] is False- assert committed["interrupted_pairs"] == refusal["would_interrupt"]+ assert committed["removed_hops"] == refusal["would_remove_hops"]+ assert committed["interrupted"] == refusal["would_interrupt"]assert committed["source"]["credential_ref"] == "cred_route_3"- assert adapter.revoked == ["cred_route_2", "cred_route_1"]+ removed_identities = {+ (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+ for backend, agent in store.config.agents.items()+ for menu_model, route in agent.routes.items()+ for hop in route.hops+ )+ assert adapter.revoked == ["cred_test001", "cred_route_2", "cred_route_1"]def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):service, store, adapter = _service(tmp_path)- flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "hub", "experimental_consent": True}))[- "flow"- ]+ flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "hub"}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{**adapter.flows[flow["flow_id"]].__dict__,@@ -3012,7 +2751,6 @@ def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):"display_name": "Rollback subscription","supply_channel": "hub","oauth_flow_ref": flow["flow_id"],- "experimental_consent": True,},))@@ -3024,6 +2762,67 @@ def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):assert service.oauth_flows.channel(flow["flow_id"]) is None+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"+ ]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_oauth_proven",+ }+ )+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol="openai_chat",+ discovery=ObservationDiscovery.SUCCEEDED,+ model_ids=("gpt-5.6",),+ )++ result = asyncio.run(service.oauth_status(flow["flow_id"]))++ assert result["source"]["protocol"] == "openai_chat"+ assert store.config.sources[0].protocol == "openai_chat"+ assert store.config.sources[0].credential_ref == "cred_oauth_proven"+ assert adapter.observed_protocol_orders == [SOURCE_PROTOCOLS]+ assert adapter.revoked == []+++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"+ ]+ adapter.flows[flow["flow_id"]] = OAuthFlowState(+ **{+ **adapter.flows[flow["flow_id"]].__dict__,+ "state": "success",+ "credential_ref": "cred_oauth_unproven",+ }+ )+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.AMBIGUOUS,+ reachable=True,+ authenticated=True,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.oauth_status(flow["flow_id"]))++ assert exc_info.value.code == "discovery_failed"+ assert exc_info.value.status == 422+ assert store.config.sources == []+ assert adapter.revoked == ["cred_oauth_unproven"]+ assert service.oauth_flows.binding(flow["flow_id"]) is None++def test_concurrent_completed_hub_oauth_flow_has_single_credential_owner(tmp_path):async def run_race():class BlockingSyncAdapter(FakeAdapter):@@ -3049,9 +2848,7 @@ def test_concurrent_completed_hub_oauth_flow_has_single_credential_owner(tmp_patoauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),)- flow = (await service.oauth_start({"vendor": "anthropic", "channel": "hub", "experimental_consent": True}))[- "flow"- ]+ flow = (await service.oauth_start({"vendor": "anthropic", "channel": "hub"}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{**adapter.flows[flow["flow_id"]].__dict__,@@ -3065,7 +2862,6 @@ def test_concurrent_completed_hub_oauth_flow_has_single_credential_owner(tmp_pat"display_name": "Single owner","supply_channel": "hub","oauth_flow_ref": flow["flow_id"],- "experimental_consent": True,}adapter.block_next_sync = True@@ -3116,7 +2912,6 @@ def test_cancel_materializes_terminal_successful_hub_reauth(tmp_path):display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="needs_action",@@ -3131,8 +2926,7 @@ def test_cancel_materializes_terminal_successful_hub_reauth(tmp_path):credential_ref="cred_hub_reused",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{@@ -3165,7 +2959,6 @@ def test_cancel_materializes_terminal_failed_hub_reauth(tmp_path):display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -3181,8 +2974,7 @@ def test_cancel_materializes_terminal_failed_hub_reauth(tmp_path):credential_ref="cred_hub_reused",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{@@ -3200,10 +2992,7 @@ def test_cancel_materializes_terminal_failed_hub_reauth(tmp_path):persisted = store.config.sources[0]assert [model.id for model in persisted.models] == ["manual-model"]assert persisted.state.status == "needs_action"- assert (- persisted.state.detail_key- == "models.source.needs_action.oauth_expired"- )+ assert persisted.state.detail_key == "models.source.needs_action.oauth_expired"assert service.oauth_flows.binding(flow["flow_id"]) is Noneassert adapter.cancelled == []@@ -3217,7 +3006,6 @@ def test_cancel_materializes_post_cancel_unknown_hub_reauth(tmp_path):display_name="Hub subscription",protocol="anthropic",supply_channel="hub",- experimental_consent_at="2026-07-23T02:00:00+00:00",billing="monthly",state=ModelHubSourceStateConfig(status="standby"),models=[@@ -3233,8 +3021,7 @@ def test_cancel_materializes_post_cancel_unknown_hub_reauth(tmp_path):credential_ref="cred_hub_reused",)store.config.sources.append(source)- store.config.subscription_hub_experimental = True- store.config.refresh_follow_orders()+ _refresh_fixture_routes(store.config)flow = asyncio.run(service.reauth_source(source.id, {}))["flow"]adapter.flows[flow["flow_id"]] = OAuthFlowState(**{@@ -3250,10 +3037,7 @@ def test_cancel_materializes_post_cancel_unknown_hub_reauth(tmp_path):persisted = store.config.sources[0]assert [model.id for model in persisted.models] == ["manual-model"]assert persisted.state.status == "needs_action"- assert (- persisted.state.detail_key- == "models.source.needs_action.oauth_expired"- )+ assert persisted.state.detail_key == "models.source.needs_action.oauth_expired"assert service.oauth_flows.binding(flow["flow_id"]) is Noneassert adapter.cancelled == [flow["flow_id"]]@@ -3300,25 +3084,6 @@ def test_oauth_completion_requires_the_persisted_pending_source_identity(tmp_patassert store.config.sources == []-def test_native_oauth_cannot_record_experimental_hub_consent(tmp_path):- service, store, adapter = _service(tmp_path)-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.oauth_start(- {- "vendor": "anthropic",- "channel": "native_cli",- "experimental_consent": True,- }- )- )-- assert exc_info.value.code == "consent_required"- assert store.config.subscription_hub_experimental is False- assert adapter.flows == {}--def test_expired_oauth_flow_is_rejected_before_submit(tmp_path):service, _, adapter = _service(tmp_path)flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))["flow"]@@ -3501,59 +3266,6 @@ def test_concurrent_source_creates_preserve_both_aggregate_updates(tmp_path):)-def test_follow_auto_adopts_new_sources_while_custom_stays_frozen(tmp_path):- service, store, _ = _service(tmp_path)- first = asyncio.run(- service.create_source(- {- "kind": "api_key",- "vendor": "anthropic",- "display_name": "First",- "key": "sk-test-first-source",- }- )- )- first_id = first["source"]["id"]- assert {item["backend"] for item in first["adopted_by"]} == {- "claude",- "codex",- "opencode",- }- assert first["skipped_by"] == []-- asyncio.run(- service.set_agent_sources(- "claude",- {"policy": "custom", "order": [first_id]},- )- )- second = asyncio.run(- service.create_source(- {- "kind": "api_key",- "vendor": "openai",- "display_name": "Second",- "key": "sk-test-second-source",- }- )- )- second_id = second["source"]["id"]-- assert store.config.agents["claude"].sources.order == [first_id]- assert "claude" not in {item["backend"] for item in second["adopted_by"]}- assert second["skipped_by"] == [- {"backend": "claude", "reason": "custom_order"}- ]- assert set(store.config.effective_source_order("codex")) == {- first_id,- second_id,- }-- restored = asyncio.run(service.set_agent_sources("claude", {"policy": "follow"}))- assert "policy" not in restored["sources"]- assert restored["sources"]["order"] == store.config.recommended_source_order("claude")--@pytest.mark.parametrize("base_url",[@@ -3668,7 +3380,7 @@ def test_api_key_is_trimmed_once_and_empty_normalized_values_are_rejected(tmp_pa))- assert adapter.secret_lengths == [len(normalized)]+ assert adapter.secret_lengths == [len(normalized), len(normalized)]assert source["masked_credential"] == "sk-test…m-me"with pytest.raises(ModelHubError) as exc_info:@@ -3685,7 +3397,7 @@ def test_api_key_is_trimmed_once_and_empty_normalized_values_are_rejected(tmp_pa)assert exc_info.value.code == "discovery_failed"- assert adapter.secret_lengths == [len(normalized)]+ assert adapter.secret_lengths == [len(normalized), len(normalized)]assert [source.display_name for source in store.config.sources] == ["Trimmed source"]@@ -3783,6 +3495,146 @@ def test_source_patch_rejects_credential_bearing_discovered_model_id(tmp_path):assert "sk-model-never-persist-this" not in json.dumps(store.config.to_payload())+def test_base_url_change_guards_and_prunes_invalid_exact_hops(+ monkeypatch,+ tmp_path,+):+ service, store, adapter = _service(tmp_path)+ source = asyncio.run(+ _create_source(+ service,+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Guarded endpoint",+ "key": "sk-test-transient-only",+ },+ )+ )+ old_credential_ref = source["credential_ref"]+ discovery_refs: list[str] = []++ async def discover_narrower(vendor, protocol, base_url, credential_ref):+ discovery_refs.append(credential_ref)+ return ("replacement-only-model",)++ adapter.discover_models = discover_narrower+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ origin = "http://127.0.0.1:15131"+ headers = csrf_headers(client, origin)+ replacement_url = "https://other-relay.example/v1"++ refused = client.patch(+ f"/api/models/sources/{source['id']}",+ json={"base_url": replacement_url},+ headers=headers,+ base_url=origin,+ )++ assert refused.status_code == 409+ refusal = refused.get_json()+ assert refusal["error"] == "source_model_in_route_chain"+ assert refusal["would_remove_hops"]+ assert store.config.sources[0].base_url is None+ refused_retarget = adapter.retargeted_credentials[0]+ assert refused_retarget[:4] == (+ old_credential_ref,+ "anthropic",+ "anthropic",+ replacement_url,+ )+ assert discovery_refs == [refused_retarget[4]]+ assert refused_retarget[4] in adapter.revoked++ committed = client.patch(+ f"/api/models/sources/{source['id']}",+ json={"base_url": replacement_url, "force": True},+ headers=headers,+ base_url=origin,+ ).get_json()++ assert committed["source"]["base_url"] == replacement_url+ committed_retarget = adapter.retargeted_credentials[1]+ assert committed_retarget[:4] == refused_retarget[:4]+ assert committed["source"]["credential_ref"] == committed_retarget[4]+ assert discovery_refs == [refused_retarget[4], committed_retarget[4]]+ assert old_credential_ref in adapter.revoked+ assert committed["removed_hops"] == refusal["would_remove_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"]+ }+ assert all(+ (backend, menu_model, hop.source_id, hop.model_id) not in removed_identities+ for backend, agent in store.config.agents.items()+ for menu_model, route in agent.routes.items()+ for hop in route.hops+ )+++def test_base_url_retarget_cancellation_revokes_only_the_uncommitted_ref(+ tmp_path,+):+ class BlockingRetargetAdapter(FakeAdapter):+ def __init__(self):+ super().__init__()+ self.retarget_started = asyncio.Event()+ self.release_retarget = asyncio.Event()++ async def retarget_api_key_credential(+ self,+ credential_ref,+ vendor,+ protocol,+ base_url,+ ):+ self.retarget_started.set()+ await self.release_retarget.wait()+ return await super().retarget_api_key_credential(+ credential_ref,+ vendor,+ protocol,+ base_url,+ )++ async def scenario():+ adapter = BlockingRetargetAdapter()+ service, store, _ = _service(tmp_path, adapter=adapter)+ source = await _create_source(+ service,+ {+ "kind": "api_key",+ "vendor": "custom",+ "display_name": "Retarget cancellation",+ "base_url": "https://old-relay.example/v1",+ "key": "sk-test-transient-only",+ },+ )+ old_ref = source["credential_ref"]+ revoked_before = list(adapter.revoked)+ task = asyncio.create_task(+ service.patch_source(+ source["id"],+ {"base_url": "https://new-relay.example/v1"},+ )+ )+ await adapter.retarget_started.wait()+ task.cancel()+ adapter.release_retarget.set()+ with pytest.raises(asyncio.CancelledError):+ await task+ [persisted] = store.config.sources+ replacement_ref = adapter.retargeted_credentials[0][4]+ assert persisted.credential_ref == old_ref+ assert persisted.base_url == "https://old-relay.example/v1"+ assert adapter.revoked == [*revoked_before, replacement_ref]++ asyncio.run(scenario())++def test_metadata_only_source_patch_does_not_require_engine_sync(tmp_path):service, store, adapter = _service(tmp_path)source = asyncio.run(@@ -3801,6 +3653,8 @@ def test_metadata_only_source_patch_does_not_require_engine_sync(tmp_path):updated = asyncio.run(service.patch_source(source["id"], {"display_name": "After rename"}))- assert updated["display_name"] == "After rename"+ assert updated["source"]["display_name"] == "After rename"+ assert updated["removed_hops"] == []+ assert updated["interrupted"] == []assert store.config.sources[0].display_name == "After rename"assert len(adapter.synced) == sync_countdiff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex f97e47940..9f21c11a1 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -2,7 +2,9 @@ from __future__ import annotationsimport copyimport json+import refrom dataclasses import fields+from itertools import productfrom pathlib import Pathimport pytest@@ -14,9 +16,9 @@ from config.v2_config import (ModelHubAgentSourcesConfig,ModelHubAgentSupplyConfig,ModelHubConfig,- ModelHubMappingConfig,ModelHubMenuConfig,ModelHubModelConfig,+ ModelHubRouteConfig,ModelHubSourceConfig,ModelHubSourceStateConfig,ModelHubSourceUsageConfig,@@ -24,10 +26,19 @@ from config.v2_config import (is_model_hub_enabled,)from core.services.settings import default_config+from core.handlers.model_hub.adapter import (+ OBSERVATION_TERMINAL_RULES,+ ObservationDiscovery,+ ObservationOutcome,+ SOURCE_PROTOCOLS,+ SourceObservation,+ validate_source_observation,+)from scripts.check_model_hub_authorities import check as check_model_hub_authoritiesfrom vibe import apiCONTRACTS = Path("docs/plans/model-hub-contracts")+UI_MODEL_CONSUMERS = Path("ui/src/components/settings/models")def _schema(name: str) -> dict:@@ -42,6 +53,231 @@ def _assert_valid(name: str, payload: dict) -> None:assert not errors, [error.message for error in errors]+def test_protocol_vocabulary_matches_authority_and_rejects_removed_alias():+ protocols = tuple(_schema("source.schema.json")["properties"]["protocol"]["enum"])+ assert SOURCE_PROTOCOLS == protocols++ type_source = (UI_MODEL_CONSUMERS / "types.ts").read_text(encoding="utf-8")+ type_match = re.search(+ r"export type SourceProtocol\s*=\s*(.*?);",+ type_source,+ re.DOTALL,+ )+ assert type_match is not None+ assert tuple(re.findall(r"'([^']+)'", type_match.group(1))) == protocols++ retired_alias = "openai" + "_compatible"+ for filename in (+ "types.ts",+ "vendorMeta.ts",+ "modelsApi.ts",+ "mockData.ts",+ "modelRows.test.ts",+ ):+ 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+ with pytest.raises(ValidationError):+ Draft7Validator(_schema("source.schema.json")).validate(example)+ with pytest.raises(ValueError):+ ModelHubSourceConfig.from_payload(example)+++def test_unsaved_observation_schema_closes_all_terminal_shapes():+ schema = _schema("observation-result.schema.json")+ assert schema["properties"]["contract_version"]["const"] == 5+ assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(+ member.value for member in ObservationOutcome+ )+ assert tuple(schema["properties"]["discovery"]["enum"]) == tuple(+ member.value for member in ObservationDiscovery+ )+ for example in schema["examples"]:+ _assert_valid("observation-result.schema.json", example)+ invalid = copy.deepcopy(schema["examples"][0])+ invalid["protocol"] = "openai" + "_compatible"+ with pytest.raises(ValidationError):+ Draft7Validator(schema).validate(invalid)+++def test_observation_terminal_authority_and_schema_accept_the_same_products():+ schema = Draft7Validator(_schema("observation-result.schema.json"))+ reachable_domain = frozenset({True, False, None})+ authenticated_domain = frozenset({True, False, None})+ protocol_domain = frozenset({None, *SOURCE_PROTOCOLS})+ discovery_domain = frozenset(ObservationDiscovery)++ def payload(observation: SourceObservation) -> dict:+ return {+ "contract_version": 5,+ "outcome": observation.outcome.value,+ "reachable": observation.reachable,+ "authenticated": (+ "authenticated"+ if observation.authenticated is True+ else "rejected"+ if observation.authenticated is False+ else "unknown"+ ),+ "protocol": observation.protocol,+ "discovery": observation.discovery.value,+ "models": list(observation.model_ids),+ }++ assert set(OBSERVATION_TERMINAL_RULES) == set(ObservationOutcome)+ for outcome, rule in OBSERVATION_TERMINAL_RULES.items():+ legal_products = product(+ rule.reachable,+ rule.authenticated,+ rule.protocols,+ rule.discoveries,+ )+ for reachable, authenticated, protocol, discovery in legal_products:+ observation = SourceObservation(+ outcome=outcome,+ reachable=reachable,+ authenticated=authenticated,+ protocol=protocol,+ discovery=discovery,+ model_ids=(),+ )+ assert validate_source_observation(observation) is observation+ schema.validate(payload(observation))++ baseline = SourceObservation(+ outcome=outcome,+ reachable=next(iter(rule.reachable)),+ authenticated=next(iter(rule.authenticated)),+ protocol=next(iter(rule.protocols)),+ discovery=next(iter(rule.discoveries)),+ model_ids=(),+ )+ invalid_fields = {+ "reachable": reachable_domain - rule.reachable,+ "authenticated": authenticated_domain - rule.authenticated,+ "protocol": protocol_domain - rule.protocols,+ "discovery": discovery_domain - rule.discoveries,+ }+ for field_name, rejected_values in invalid_fields.items():+ for rejected in rejected_values:+ invalid_observation = SourceObservation(+ **{**baseline.__dict__, field_name: rejected}+ )+ with pytest.raises(ValueError):+ validate_source_observation(invalid_observation)+ with pytest.raises(ValidationError):+ schema.validate(payload(invalid_observation))++ if rule.models_must_be_empty:+ invalid_inventory = SourceObservation(+ **{**baseline.__dict__, "model_ids": ("model-id",)}+ )+ with pytest.raises(ValueError):+ validate_source_observation(invalid_inventory)+ with pytest.raises(ValidationError):+ schema.validate(payload(invalid_inventory))+ else:+ succeeded = SourceObservation(+ **{+ **baseline.__dict__,+ "discovery": ObservationDiscovery.SUCCEEDED,+ "model_ids": ("model-id",),+ }+ )+ assert validate_source_observation(succeeded) is succeeded+ schema.validate(payload(succeeded))+ failed_with_inventory = SourceObservation(+ **{+ **baseline.__dict__,+ "discovery": ObservationDiscovery.FAILED,+ "model_ids": ("model-id",),+ }+ )+ with pytest.raises(ValueError):+ validate_source_observation(failed_with_inventory)+ with pytest.raises(ValidationError):+ schema.validate(payload(failed_with_inventory))+++def test_final_model_validator_requires_explicit_credential_free_efforts():+ example = copy.deepcopy(_schema("source.schema.json")["examples"][0]["models"][0])+ example.pop("reasoning_efforts")+ with pytest.raises(ValueError):+ ModelHubModelConfig.from_payload(example)+ example["reasoning_efforts"] = ["authorization: sk-test-credential-material"]+ with pytest.raises(ValueError):+ ModelHubModelConfig.from_payload(example)+++def test_source_validator_enforces_final_cross_field_and_inventory_rules():+ native = copy.deepcopy(_schema("source.schema.json")["examples"][0])+ native["models"] = [native["models"][0], copy.deepcopy(native["models"][0])]+ with pytest.raises(ValueError):+ ModelHubSourceConfig.from_payload(native)++ manual = copy.deepcopy(_schema("source.schema.json")["examples"][1])+ manual["models"][0]["discovered_at"] = "2026-08-09T00:00:00Z"+ with pytest.raises(ValueError):+ ModelHubSourceConfig.from_payload(manual)++ hub_without_ref = copy.deepcopy(_schema("source.schema.json")["examples"][1])+ hub_without_ref["credential_ref"] = None+ with pytest.raises(ValueError):+ ModelHubSourceConfig.from_payload(hub_without_ref)++ duplicate_native = ModelHubConfig().to_payload()+ native_example = copy.deepcopy(_schema("source.schema.json")["examples"][0])+ duplicate_native["sources"] = [native_example, {**native_example, "id": "src_claudepro2"}]+ with pytest.raises(ValueError):+ ModelHubConfig.from_payload(duplicate_native)++ credential_url = copy.deepcopy(_schema("source.schema.json")["examples"][1])+ credential_url["base_url"] = "https://relay.example/v1?api_key=secret"+ with pytest.raises(ValueError):+ ModelHubSourceConfig.from_payload(credential_url)++ safe_query_url = copy.deepcopy(_schema("source.schema.json")["examples"][1])+ safe_query_url["base_url"] = "https://relay.example/v1/?api-version=2026-07-23"+ canonical_vendor = copy.deepcopy(safe_query_url)+ canonical_vendor["vendor"] = " OpenAI "+ assert ModelHubSourceConfig.from_payload(canonical_vendor).vendor == "openai"+ parsed = ModelHubSourceConfig.from_payload(safe_query_url)+ assert parsed.base_url == "https://relay.example/v1?api-version=2026-07-23"+++def test_persisted_model_hub_identifiers_share_the_canonical_validation_boundary():+ payload = ModelHubConfig().to_payload()+ opencode = payload["agents"]["opencode"]+ opencode["menu"]["checked"] = ["gpt-5"]+ opencode["routes"]["gpt-5"] = {"hops": []}+ with pytest.raises(ValueError):+ ModelHubConfig.from_payload(payload)++ payload = ModelHubConfig().to_payload()+ opencode = payload["agents"]["opencode"]+ opencode["routes"]["custom/authorization: sk-test-credential-material"] = {+ "hops": []+ }+ with pytest.raises(ValueError):+ ModelHubConfig.from_payload(payload)++ payload = ModelHubConfig().to_payload()+ source = copy.deepcopy(_schema("source.schema.json")["examples"][1])+ payload["sources"] = [source]+ codex_route = next(iter(payload["agents"]["codex"]["routes"].values()))+ codex_route["hops"] = [+ {+ "source_id": source["id"],+ "model_id": "authorization: sk-test-credential-material",+ }+ ]+ with pytest.raises(ValueError):+ ModelHubConfig.from_payload(payload)++def _canonical(payload: dict) -> bytes:return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()@@ -168,24 +404,28 @@ def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():assert _canonical(serialized) == _canonical(expected)_assert_valid("source.schema.json", serialized)- for example in _schema("agent-supply.schema.json")["examples"]:+ 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"}+ }agent = ModelHubAgentSupplyConfig.from_payload(example)# `builtin_models` and `standard_vendors` are read-only endpoint# projections (v1.2), not persisted config — reconstruct them# the way `_agent_payload` merges them onto to_payload().serialized = {**agent.to_payload(),- "builtin_models": example.get("builtin_models"),- "standard_vendors": example.get("standard_vendors"),+ "builtin_models": raw_example.get("builtin_models"),+ "standard_vendors": raw_example.get("standard_vendors"),}- # AgentSupply is the API projection; the dormant pre-I1 config object- # still carries its old mapping list behind the default-off gate.- serialized.pop("mappings", None)- if "sources" not in example:+ if "routes" not in raw_example:+ serialized.pop("routes", None)+ if "sources" not in raw_example:serialized.pop("sources")else:- serialized["sources"]["eligibility"] = example["sources"].get("eligibility")- assert _canonical(serialized) == _canonical(example)+ serialized["sources"]["eligibility"] = raw_example["sources"].get("eligibility")+ assert _canonical(serialized) == _canonical(raw_example)_assert_valid("agent-supply.schema.json", serialized)@@ -459,42 +699,34 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():chain_schema = _schema("agent-chain.schema.json")chain_validator = Draft7Validator(chain_schema)- native_alias = next(- example- for example in chain_schema["examples"]- if example["model_id"] == "claude-opus-4-5"- and example["chain"]- and example["chain"][0]["resolved_model_id"] is not None- and example["chain"][0]["via_mapping"] is False- )- chain_validator.validate(native_alias)- invalid_native_alias = copy.deepcopy(native_alias)- invalid_native_alias["chain"][0]["resolved_model_id"] = "glm-5.2"- with pytest.raises(ValidationError):- chain_validator.validate(invalid_native_alias)-- native_unavailable = copy.deepcopy(chain_schema["examples"][-1])- chain_validator.validate(native_unavailable)-- unavailable_needs_action = copy.deepcopy(native_unavailable)- unavailable_needs_action["chain"][0]["health"] = "needs_action"- unavailable_needs_action["chain"][0]["retry_at"] = None- chain_validator.validate(unavailable_needs_action)-- unmarked_healthy_unavailable = copy.deepcopy(chain_schema["examples"][-2])- unmarked_healthy_unavailable["chain"][0]["reason"] = None- with pytest.raises(ValidationError):- chain_validator.validate(unmarked_healthy_unavailable)-- mislabeled_waiting = copy.deepcopy(native_unavailable)- mislabeled_waiting["supply_state"] = "waiting"- with pytest.raises(ValidationError):- chain_validator.validate(mislabeled_waiting)-- unavailable_hub = copy.deepcopy(native_unavailable)- unavailable_hub["chain"][0]["channel"] = "hub"+ for example in chain_schema["examples"]:+ chain_validator.validate(example)+ exact_hop = {+ "contract_version": 5,+ "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,+ }],+ "current": {"source_id": "src_claudepro1", "model_id": "claude-opus-4-6"},+ "supply_state": "ok",+ }+ chain_validator.validate(exact_hop)+ for retired in ("via_mapping", "resolved_model_id"):+ invalid = copy.deepcopy(exact_hop)+ invalid["chain"][0][retired] = False if retired == "via_mapping" else "old"+ with pytest.raises(ValidationError):+ chain_validator.validate(invalid)+ invalid_reason = copy.deepcopy(exact_hop)+ invalid_reason["chain"][0]["reason"] = "invented"with pytest.raises(ValidationError):- chain_validator.validate(unavailable_hub)+ chain_validator.validate(invalid_reason)probe_schema = _schema("probe-result.schema.json")probe_validator = Draft7Validator(probe_schema)@@ -522,7 +754,6 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmsource_example = {**_schema("source.schema.json")["examples"][0],"supply_channel": "hub",- "experimental_consent_at": "2026-07-23T03:00:00Z","credential_ref": "cred_serializer_test",}hub_payload = {@@ -531,7 +762,6 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmbackend: ModelHubAgentSupplyConfig.default(backend, mode="hub").to_payload()for backend in ("claude", "codex", "opencode")},- "subscription_hub_experimental": True,}config = default_config()config.model_hub = ModelHubConfig.from_payload(hub_payload)@@ -542,9 +772,6 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmapi_payload = api.config_to_payload(loaded)expected_root = {field.name for field in fields(ModelHubConfig)}source_fields = {field.name for field in fields(ModelHubSourceConfig)}- # Retired consent metadata remains an internal compatibility attribute for- # in-memory fixtures but is intentionally absent from the final payload.- source_fields.discard("experimental_consent_at")source_state_fields = {field.name for field in fields(ModelHubSourceStateConfig)}source_usage_fields = {field.name for field in fields(ModelHubSourceUsageConfig)}source_model_fields = {field.name for field in fields(ModelHubModelConfig)}@@ -552,7 +779,7 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmsource_model_fields.add("origin")agent_fields = {field.name for field in fields(ModelHubAgentSupplyConfig)}agent_sources_fields = {field.name for field in fields(ModelHubAgentSourcesConfig)}- mapping_fields = {field.name for field in fields(ModelHubMappingConfig)}+ route_fields = {field.name for field in fields(ModelHubRouteConfig)}menu_fields = {field.name for field in fields(ModelHubMenuConfig)}assert expected_root == set(api_payload["model_hub"])@@ -569,7 +796,7 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmassert source_model_fields == set(serialized_source["models"][0]), labelassert agent_fields == set(serialized_hub["agents"]["claude"]), labelassert agent_sources_fields == set(serialized_hub["agents"]["claude"]["sources"]), label- assert mapping_fields == set(ModelHubMappingConfig("builtin", "target", True).to_payload()), label+ assert route_fields == set(ModelHubRouteConfig().to_payload()), labelassert menu_fields == set(serialized_hub["agents"]["opencode"]["menu"]), labelstale_hub_payload = json.loads(json.dumps(api_payload["model_hub"]))@@ -598,26 +825,25 @@ def test_model_hub_release_capability_defaults_and_fails_closed(value):assert is_model_hub_enabled({MODEL_HUB_ENABLED_ENV: value}) is False-def test_hub_subscription_load_ignores_retired_consent_metadata():+def test_final_config_rejects_retired_consent_metadata():source = _schema("source.schema.json")["examples"][0]source = {**source, "supply_channel": "hub"}payload = {"sources": [source],"agents": {},- "subscription_hub_experimental": True,}- loaded = ModelHubConfig.from_payload(payload)- assert loaded.sources[0].supply_channel == "hub"+ payload["sources"][0]["experimental_consent_at"] = "2026-07-23T03:00:00Z"+ with pytest.raises(ValueError):+ ModelHubConfig.from_payload(payload)-def test_legacy_global_priority_key_is_dropped_without_validation():+def test_final_config_rejects_retired_global_priority_key():payload = ModelHubConfig().to_payload()payload["priority_order"] = {"legacy": "shape-does-not-matter"}- loaded = ModelHubConfig.from_payload(payload)-- assert "priority_order" not in loaded.to_payload()+ with pytest.raises(ValueError):+ ModelHubConfig.from_payload(payload)def test_agent_source_orders_validate_existence_eligibility_and_uniqueness():@@ -628,7 +854,6 @@ def test_agent_source_orders_validate_existence_eligibility_and_uniqueness():base = ModelHubConfig().to_payload()base["sources"] = [source]base["agents"]["claude"]["sources"] = {- "policy": "custom","order": [source["id"]],}@@ -645,13 +870,60 @@ def test_agent_source_orders_validate_existence_eligibility_and_uniqueness():ineligible = json.loads(json.dumps(base))ineligible["agents"]["codex"]["sources"] = {- "policy": "custom","order": [source["id"]],}with pytest.raises(ValueError):ModelHubConfig.from_payload(ineligible)+def test_route_hops_allow_one_source_to_supply_distinct_models():+ route = ModelHubRouteConfig.from_payload(+ {+ "hops": [+ {"source_id": "src_same0001", "model_id": "model-a"},+ {"source_id": "src_same0001", "model_id": "model-b"},+ ]+ }+ )++ assert [(hop.source_id, hop.model_id) for hop in route.hops] == [+ ("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")+ )+ config = ModelHubConfig(sources=[source])+ config.agents["claude"].sources.order = [source.id]+ config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig.from_payload(+ {+ "hops": [+ {"source_id": source.id, "model_id": "claude-opus-4-6"},+ {"source_id": source.id, "model_id": "claude-opus-4-5"},+ ]+ }+ )++ canonical = ModelHubConfig.from_payload(config.to_payload())++ assert [hop.model_id for hop in canonical.agents["claude"].routes["claude-opus-4-6"].hops] == [+ "claude-opus-4-6",+ "claude-opus-4-5",+ ]+ with pytest.raises(ValueError, match="unique pairs"):+ ModelHubRouteConfig.from_payload(+ {+ "hops": [+ {"source_id": "src_same0001", "model_id": "model-a"},+ {"source_id": "src_same0001", "model_id": "model-a"},+ ]+ }+ )++def _ordering_source(source_id: str,*,@@ -671,7 +943,6 @@ def _ordering_source(state=ModelHubSourceStateConfig(status="standby"),models=[],created_at=created_at,- experimental_consent_at=("2026-07-29T02:00:00Z" if kind == "subscription" and channel == "hub" else None),)@@ -738,7 +1009,6 @@ def test_recommended_order_is_backend_native_then_created_at_and_id():native,legacy_a,],- subscription_hub_experimental=True,)assert config.recommended_source_order("claude") == [@@ -752,6 +1022,7 @@ def test_recommended_order_is_backend_native_then_created_at_and_id():]assert config.recommended_source_order("codex") == [wrong_vendor_subscription.id,+ hub_subscription.id,legacy_a.id,legacy_b.id,newer.id,@@ -759,6 +1030,7 @@ def test_recommended_order_is_backend_native_then_created_at_and_id():same_time_b.id,]assert config.recommended_source_order("opencode") == [+ hub_subscription.id,legacy_a.id,legacy_b.id,newer.id,@@ -767,6 +1039,70 @@ def test_recommended_order_is_backend_native_then_created_at_and_id():]+def test_persisted_hub_config_requires_explicit_complete_route_rows():+ payload = ModelHubConfig().to_payload()++ missing = json.loads(json.dumps(payload))+ del missing["agents"]["claude"]["routes"]+ with pytest.raises(ValueError, match="routes.*required"):+ ModelHubConfig.from_payload(missing)++ non_object = json.loads(json.dumps(payload))+ non_object["agents"]["claude"]["routes"] = []+ with pytest.raises(ValueError, match="routes.*object"):+ ModelHubConfig.from_payload(non_object)++ incomplete = json.loads(json.dumps(payload))+ incomplete["agents"]["claude"]["routes"].pop("claude-opus-4-6")+ with pytest.raises(ValueError, match="missing menu model"):+ ModelHubConfig.from_payload(incomplete)++ extra = json.loads(json.dumps(payload))+ extra["agents"]["claude"]["routes"]["claude-hidden-model"] = {+ "hops": []+ }+ with pytest.raises(ValueError, match="contains non-menu model"):+ ModelHubConfig.from_payload(extra)++ dynamic = json.loads(json.dumps(payload))+ dynamic["agents"]["opencode"]["mode"] = "hub"+ dynamic["agents"]["opencode"]["menu"] = {+ "view": "featured",+ "checked": ["custom/model"],+ }+ dynamic["agents"]["opencode"]["routes"] = {}+ with pytest.raises(ValueError, match="missing menu model 'custom/model'"):+ ModelHubConfig.from_payload(dynamic)+++def test_config_reload_migrates_fixed_routes_when_bundled_catalog_changes(monkeypatch, tmp_path):+ payload = api.config_to_payload(default_config())+ original_ids = tuple(payload["model_hub"]["agents"]["claude"]["routes"])+ removed_id = original_ids[0]+ added_id = "claude-catalog-added-after-save"+ stale_id = "claude-catalog-removed-after-save"+ routes = payload["model_hub"]["agents"]["claude"]["routes"]+ routes.pop(removed_id)+ routes[stale_id] = {"hops": []}++ def changed_catalog_ids(backend: str) -> tuple[str, ...]:+ if backend == "claude":+ return (*original_ids[1:], added_id)+ return tuple(payload["model_hub"]["agents"][backend]["routes"])++ monkeypatch.setattr("config.v2_config.model_hub_fixed_menu_ids", changed_catalog_ids)+ config_path = tmp_path / "config.json"+ config_path.write_text(json.dumps(payload), encoding="utf-8")++ loaded = V2Config.load(config_path=config_path)+ migrated_routes = loaded.model_hub.agents["claude"].routes++ assert set(migrated_routes) == set(changed_catalog_ids("claude"))+ assert migrated_routes[added_id].hops == ()+ assert removed_id not in migrated_routes+ assert stale_id not in migrated_routes++@pytest.mark.parametrize(("status", "retry_at", "detail_key"),[diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex fc644c00b..b9b304cd1 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -1,2290 +1,117 @@from __future__ import annotationsimport asyncio-import hashlibimport json-import stat-from contextlib import suppress-from datetime import datetime, timedelta, timezone-from pathlib import Pathfrom types import SimpleNamespace-from unittest.mock import AsyncMock, Mock, patchimport pytest-from config.v2_config import (- ModelHubAgentSourcesConfig,- ModelHubAgentSupplyConfig,- ModelHubConfig,- ModelHubMappingConfig,- ModelHubMenuConfig,- ModelHubModelConfig,- ModelHubSourceConfig,- ModelHubSourceStateConfig,-)-from core.handlers.model_hub.adapter import EngineHealth, EngineStatus-from core.handlers.model_hub.events import BoundedEventLog-from core.handlers.model_hub.resolver import resolve_model_hub_turn-from core.handlers.model_hub.revocations import CredentialRevocationJournal-from core.handlers.model_hub.service import ModelHubError, ModelHubService-from core.handlers.session_handler import SessionHandler+from core.handlers.model_hub.service import ModelHubErrorfrom modules.agents.model_hub import (ModelHubLaunch,- ModelHubRuntimeRouter,- bind_persisted_launch,- bind_launch,build_claude_hub_env,build_codex_hub_launch,+ bind_launch,+ bind_persisted_launch,claude_setting_sources_for_launch,launch_for_context,opencode_model_for_overlay,- overlay_identifier_bytes,persisted_launch_identity,- resolve_model_hub_launch,- resolve_opencode_overlay_launch,)-from modules.agents.codex.agent import CodexAgent-from modules.agents.opencode.server import OpenCodeServerManager---class MemoryStore:- def __init__(- self,- config: ModelHubConfig,- *,- requested_models: dict[str, str] | None = None,- ):- self.config = config- self.requested_models = requested_models or {}-- def load(self) -> ModelHubConfig:- return self.config-- def save(self, config: ModelHubConfig) -> None:- self.config = config-- def requested_model(self, backend: str) -> str:- return self.requested_models.get(backend, "")---class LaunchAdapter:- def __init__(self, prefixes: dict[str, str], *, token: str = "local-gateway-token"):- self.prefixes = prefixes- self.token = token- self.starts = 0- self.syncs = 0- self.revoked: list[str] = []-- async def start(self):- self.starts += 1- return EngineStatus(EngineHealth.OK, "test", True, "127.0.0.1", 18443, None)-- async def gateway_token(self):- return self.token-- async def sync_sources(self, bindings):- self.syncs += 1-- async def revoke_credential(self, credential_ref: str):- self.revoked.append(credential_ref)-- def source_prefix(self, source_id: str) -> str:- return self.prefixes[source_id]---def _model(model_id: str, display_name: str | None = None) -> ModelHubModelConfig:- return ModelHubModelConfig(- id=model_id,- display_name=display_name,- provenance="discovered",- )---def _source(- source_id: str,- *,- kind: str,- vendor: str,- protocol: str,- channel: str,- model_ids: tuple[str, ...],- state: str = "standby",- retry_at: str | None = None,-) -> ModelHubSourceConfig:- return ModelHubSourceConfig(- id=source_id,- kind=kind,- vendor=vendor,- display_name=source_id,- protocol=protocol,- supply_channel=channel,- billing="monthly" if kind == "subscription" else "metered",- state=ModelHubSourceStateConfig(- status=state,- retry_at=retry_at,- detail_key=("models.source.error.unclassified" if state == "error" else None),- ),- models=[_model(model_id) for model_id in model_ids],- credential_ref=f"cred_{source_id}" if channel == "hub" else None,- )---def _agents(*, mode: str = "hub") -> dict[str, ModelHubAgentSupplyConfig]:- return {- backend: ModelHubAgentSupplyConfig.default(backend, mode=mode) for backend in ("claude", "codex", "opencode")- }---def _hub_config(- *,- sources: list[ModelHubSourceConfig],- agents: dict[str, ModelHubAgentSupplyConfig],- order: list[str] | None = None,-) -> ModelHubConfig:- config = ModelHubConfig(sources=sources, agents=agents)- requested_order = order if order is not None else [source.id for source in sources]- by_id = {source.id: source for source in sources}- for backend, agent in agents.items():- agent.sources = ModelHubAgentSourcesConfig(- policy="custom",- order=[- source_id- for source_id in requested_order- if source_id in by_id and config.source_eligible_for_backend(by_id[source_id], backend)- ],- )- return config---def _service(- tmp_path: Path,- config: ModelHubConfig,- adapter: LaunchAdapter,- *,- now,-) -> ModelHubService:- store = MemoryStore(config)- return ModelHubService(- store=store,- adapter=adapter,- events=BoundedEventLog(tmp_path / "events.json"),- revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),- now=now,- requested_model_override=store.requested_model,- )---def _router(- service: ModelHubService,- *,- overlay_path: Path | None = None,- native_cli_ready=None,-) -> ModelHubRuntimeRouter:- return ModelHubRuntimeRouter(- service=service,- overlay_path=overlay_path,- native_cli_ready=native_cli_ready or (lambda _backend: True),- )---def test_mh_chan_001_native_quota_falls_back_then_recovers_next_turn(tmp_path: Path) -> None:- """MH-CHAN-001: healthy -> exhausted -> recovering is decided per turn."""-- clock = {"now": datetime(2026, 7, 23, 12, 0, tzinfo=timezone.utc)}- native = _source(- "src_native01",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- )- hub = _source(- "src_hub0001",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- agents = _agents()- agents["codex"].mappings = [ModelHubMappingConfig("default", "gpt-5", True)]- config = _hub_config(- sources=[native, hub],- order=[native.id, hub.id],- agents=agents,- )- adapter = LaunchAdapter({hub.id: "route-hub"})- service = _service(tmp_path, config, adapter, now=lambda: clock["now"])- router = _router(service, overlay_path=tmp_path / "overlay.json")-- healthy = asyncio.run(router.resolve("codex", "gpt-5"))- assert (healthy.channel, healthy.source_id, adapter.starts) == ("native_cli", native.id, 0)-- context = SimpleNamespace()- bind_launch(context, healthy)- assert asyncio.run(router.record_native_failure(context, "usage quota exceeded")) is True- exhausted = asyncio.run(router.resolve("codex", "gpt-5"))- assert exhausted.channel == "hub"- assert exhausted.runtime_model == "route-hub/gpt-5"-- clock["now"] += timedelta(seconds=301)- recovered = asyncio.run(router.resolve("codex", "gpt-5"))- assert (recovered.channel, recovered.source_id) == ("native_cli", native.id)- kinds = [event["kind"] for event in reversed(service.events.list(limit=20))]- assert kinds == ["cooldown", "switch", "recover"]---def test_native_failure_is_forwarded_to_turn_correlation(- tmp_path: Path,-) -> None:- native = _source(- "src_native01",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- )- service = _service(- tmp_path,- _hub_config(sources=[native], agents=_agents()),- LaunchAdapter({}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- correlation = Mock()- router = ModelHubRuntimeRouter(- service=service,- turn_gateway=SimpleNamespace(correlation=correlation),- native_cli_ready=lambda _backend: True,- )- context = SimpleNamespace(- platform_specific={"turn_token": "turn_native_failure"}- )- bind_launch(- context,- ModelHubLaunch(- backend="codex",- channel="native_cli",- requested_model="gpt-5",- target_model="gpt-5",- runtime_model="gpt-5",- source_id=native.id,- ),- )-- assert (- asyncio.run(- router.record_native_failure(- context,- "usage quota exceeded",- )- )- is True- )- correlation.fail_native_attempt.assert_called_once_with(- "turn_native_failure",- reason="quota_exhausted",- )-- correlation.fail_native_attempt.reset_mock()- unclassified_context = SimpleNamespace(- platform_specific={"turn_token": "turn_native_unclassified"}- )- native_launch = launch_for_context(context)- assert native_launch is not None- bind_launch(unclassified_context, native_launch)- assert (- asyncio.run(- router.record_native_failure(- unclassified_context,- "provider rejected the local request",- )- )- is False- )- correlation.fail_native_attempt.assert_called_once_with(- "turn_native_unclassified",- reason="unclassified_error",- )-- hub_context = SimpleNamespace(- platform_specific={"turn_token": "turn_hub_terminal"}- )- bind_launch(- hub_context,- ModelHubLaunch(- backend="codex",- channel="hub",- requested_model="gpt-5",- target_model="gpt-5",- runtime_model="gpt-5",- source_id="src_hub0001",- ),- )- assert (- asyncio.run(- router.record_native_failure(- hub_context,- "backend rejected the completion",- )- )- is False- )- correlation.fail_hub_attempt.assert_called_once_with(- "turn_hub_terminal"- )---def test_mh_chan_001_hub_failure_cools_source_and_selects_backup(tmp_path: Path) -> None:- first = _source(- "src_hub1001",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- backup = _source(- "src_hub1002",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- config = _hub_config(- sources=[first, backup],- order=[first.id, backup.id],- agents=_agents(),- )- adapter = LaunchAdapter({first.id: "route-first", backup.id: "route-backup"})- service = _service(- tmp_path,- config,- adapter,- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service)-- initial = asyncio.run(router.resolve("codex", "gpt-5"))- context = SimpleNamespace()- bind_launch(context, initial)- assert asyncio.run(router.record_native_failure(context, "Provider API returned HTTP 503")) is True- fallback = asyncio.run(router.resolve("codex", "gpt-5"))-- assert (fallback.channel, fallback.source_id, fallback.runtime_model) == (- "hub",- backup.id,- "route-backup/gpt-5",- )- assert first.state.status == "cooldown"- assert [event["kind"] for event in reversed(service.events.list(limit=10))] == ["cooldown", "switch"]---def test_mh_chan_001_hub_to_native_switch_keeps_failure_reason(tmp_path: Path) -> None:- hub = _source(- "src_hub_reason",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- native = _source(- "src_native_reason",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- )- service = _service(- tmp_path,- _hub_config(- sources=[hub, native],- order=[hub.id, native.id],- agents=_agents(),- ),- LaunchAdapter({hub.id: "route-hub"}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service)- initial = asyncio.run(router.resolve("codex", "gpt-5"))- context = SimpleNamespace()- bind_launch(context, initial)-- assert asyncio.run(router.record_native_failure(context, "usage quota exceeded")) is True- assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "native_cli"-- switch = next(event for event in service.events.list(limit=10) if event["kind"] == "switch")- assert switch["reason"] == "quota_exhausted"---def test_mh_chan_001_native_launch_replays_pending_revocations(tmp_path: Path) -> None:- native = _source(- "src_native11",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- )- config = _hub_config(- sources=[native],- order=[native.id],- agents=_agents(),- )- adapter = LaunchAdapter({})- service = _service(- tmp_path,- config,- adapter,- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- service.revocations.add("src_removed", "cred_removed")-- launch = asyncio.run(_router(service).resolve("codex", "gpt-5"))-- assert launch.channel == "native_cli"- assert adapter.revoked == ["cred_removed"]- assert service.revocations.list() == []---def test_mh_chan_001_native_sources_only_dispatch_to_sanctioned_client(tmp_path: Path) -> None:- native_claude = _source(- "src_native02",- kind="subscription",- vendor="anthropic",- protocol="anthropic",- channel="native_cli",- model_ids=("shared-model",),- )- hub_openai = _source(- "src_hub0002",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("shared-model",),- )- config = _hub_config(- sources=[native_claude, hub_openai],- order=[native_claude.id, hub_openai.id],- agents=_agents(),- )- adapter = LaunchAdapter({hub_openai.id: "route-openai"})- service = _service(- tmp_path,- config,- adapter,- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- launch = asyncio.run(_router(service).resolve("codex", "shared-model"))- assert (launch.channel, launch.source_id) == ("hub", hub_openai.id)---def test_runtime_launch_uses_discovered_native_alias_target(tmp_path: Path) -> None:- relay = _source(- "src_alias001",- kind="api_key",- vendor="anthropic",- protocol="anthropic",- channel="hub",- model_ids=("claude-opus-4-5-20251101",),- )- config = _hub_config(- sources=[relay],- order=[relay.id],- agents=_agents(),- )- service = _service(- tmp_path,- config,- LaunchAdapter({relay.id: "route-alias"}),- now=lambda: datetime(2026, 7, 30, tzinfo=timezone.utc),- )-- launch = asyncio.run(- _router(service).resolve("claude", "claude-opus-4-5")- )-- assert launch.source_id == relay.id- assert launch.target_model == "claude-opus-4-5-20251101"- assert launch.runtime_model == "route-alias/claude-opus-4-5-20251101"--[email protected]("requested_model", ["opus", "sonnet[1m]"])-def test_native_cli_preserves_exact_cli_alias(- tmp_path: Path,- requested_model: str,-) -> None:- native = _source(- "src_native_alias",- kind="subscription",- vendor="anthropic",- protocol="anthropic",- channel="native_cli",- model_ids=(- requested_model,- "claude-opus-5",- "claude-sonnet-5",- ),- )- config = _hub_config(- sources=[native],- order=[native.id],- agents=_agents(),- )- service = _service(- tmp_path,- config,- LaunchAdapter({}),- now=lambda: datetime(2026, 7, 30, tzinfo=timezone.utc),- )-- launch = asyncio.run(_router(service).resolve("claude", requested_model))-- assert launch.channel == "native_cli"- assert launch.source_id == native.id- assert launch.target_model == requested_model- assert launch.runtime_model == requested_model---def test_runtime_alias_failover_correlates_by_requested_menu_id(tmp_path: Path) -> None:- requested_model = "claude-opus-4-5"- primary = _source(- "src_alias_primary",- kind="api_key",- vendor="anthropic",- protocol="anthropic",- channel="hub",- model_ids=("claude-opus-4-5-20251101",),- )- backup = _source(- "src_alias_backup",- kind="api_key",- vendor="anthropic",- protocol="anthropic",- channel="hub",- model_ids=("claude-opus-4-5-20250929",),- )- config = _hub_config(- sources=[primary, backup],- order=[primary.id, backup.id],- agents=_agents(),- )- service = _service(- tmp_path,- config,- LaunchAdapter(- {- primary.id: "route-primary",- backup.id: "route-backup",- }- ),- now=lambda: datetime(2026, 7, 30, tzinfo=timezone.utc),- )- router = _router(service)-- primary_launch = asyncio.run(router.resolve("claude", requested_model))- context = SimpleNamespace()- bind_launch(context, primary_launch)- assert asyncio.run(router.record_native_failure(context, "429 rate limit")) is True-- backup_launch = asyncio.run(router.resolve("claude", requested_model))-- assert primary_launch.target_model == "claude-opus-4-5-20251101"- assert backup_launch.target_model == "claude-opus-4-5-20250929"- assert backup_launch.source_id == backup.id- transition_events = [- event- for event in service.events.list(limit=20)- if event["kind"] in {"cooldown", "switch"}- ]- assert [event["kind"] for event in transition_events] == [- "switch",- "cooldown",- ]- assert {event["model_id"] for event in transition_events} == {- requested_model- }---def test_mh_chan_001_unconfigured_hub_is_interrupted(tmp_path: Path) -> None:- service = _service(- tmp_path,- _hub_config(sources=[], order=[], agents=_agents()),- LaunchAdapter({}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(_router(service).resolve("codex", "gpt-5"))-- assert exc_info.value.code == "mapping_target_unavailable"- event = service.events.list(limit=10)[0]- assert (event["kind"], event["reason"]) == (- "supply_interrupted",- "no_enabled_source",- )---def test_hub_with_only_ineligible_sources_names_structural_cause(- tmp_path: Path,-) -> None:- native_claude = _source(- "src_claudenative",- kind="subscription",- vendor="anthropic",- protocol="anthropic",- channel="native_cli",- model_ids=("gpt-5",),- )- service = _service(- tmp_path,- _hub_config(- sources=[native_claude],- order=[native_claude.id],- agents=_agents(),- ),- LaunchAdapter({}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )-- with pytest.raises(ModelHubError, match="mapping_target_unavailable"):- asyncio.run(_router(service).resolve("codex", "gpt-5"))-- event = service.events.list(limit=10)[0]- assert (event["kind"], event["reason"]) == (- "supply_interrupted",- "no_eligible_source",- )--[email protected]("backend", ["claude", "codex", "opencode"])-def test_prelaunch_supply_failure_copy_is_shared_across_backends(- tmp_path: Path,- backend: str,-) -> None:- service = _service(- tmp_path,- _hub_config(sources=[], order=[], agents=_agents()),- LaunchAdapter({}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- controller = SimpleNamespace(- model_hub_runtime=_router(service),- config=SimpleNamespace(language="zh"),- )-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- resolve_model_hub_launch(- controller,- backend,- "missing-model",- )- )-- assert str(exc_info.value) == (- "模型 missing-model 没有已启用的来源。请前往 Models 配置。"- )- assert exc_info.value.data["copy_key"] == "no_enabled_source"---def test_prelaunch_blocker_details_are_localized(- tmp_path: Path,-) -> None:- blocked = _source(- "src_blocked01",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- blocked.state = ModelHubSourceStateConfig(- status="needs_action",- detail_key="models.source.needs_action.oauth_expired",- )- service = _service(- tmp_path,- _hub_config(sources=[blocked], agents=_agents()),- LaunchAdapter({blocked.id: "route-blocked"}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- controller = SimpleNamespace(- model_hub_runtime=_router(service),- config=SimpleNamespace(language="zh"),- )-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- resolve_model_hub_launch(- controller,- "codex",- "gpt-5",- )- )-- assert "凭证已过期" in str(exc_info.value)- assert "models.source.needs_action.oauth_expired" not in str(- exc_info.value- )-def test_native_unavailability_blocker_is_localized(- tmp_path: Path,-) -> None:- native = _source(- "src_native01",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- )- service = _service(- tmp_path,- _hub_config(sources=[native], agents=_agents()),- LaunchAdapter({}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- controller = SimpleNamespace(- model_hub_runtime=_router(- service,- native_cli_ready=lambda _backend: False,- ),- config=SimpleNamespace(language="zh"),- )-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- resolve_model_hub_launch(- controller,- "codex",- "gpt-5",- )- )-- assert "当前进程无法使用 CLI 登录" in str(exc_info.value)- assert "src_native01:standby" not in str(exc_info.value)---def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> None:- """MH-EVT-002: mode history does not suppress or duplicate degradation."""-- agents = _agents(mode="direct")- adapter = LaunchAdapter({})- config = _hub_config(sources=[], order=[], agents=agents)- service = _service(- tmp_path,- config,- adapter,- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service)-- assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "direct"- assert service.events.list(limit=10) == []-- agents["codex"].mode = "hub"- with pytest.raises(ModelHubError, match="mapping_target_unavailable"):- asyncio.run(router.resolve("codex", "gpt-5"))- event = service.events.list(limit=10)[0]- assert (event["kind"], event["reason"]) == (- "supply_interrupted",- "no_enabled_source",- )-- hub = _source(- "src_hub_after_direct",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- config.sources.append(hub)- config.agents["codex"].sources.order.append(hub.id)- adapter.prefixes[hub.id] = "route-hub"- assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "hub"- assert len(service.events.list(limit=10)) == 1- assert service.events.list(limit=10)[0]["reason"] == "no_enabled_source"---def test_recovered_turn_uses_post_wait_mode_for_events(tmp_path: Path) -> None:- """MH-EVT-002: recovered resolution and telemetry use one config snapshot."""-- initial = _hub_config(- sources=[],- order=[],- agents=_agents(mode="hub"),- )- recovered = _hub_config(- sources=[],- order=[],- agents=_agents(mode="direct"),- )- service = _service(- tmp_path,- initial,- LaunchAdapter({}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service)- resolution = resolve_model_hub_turn(recovered, "codex", "gpt-5")- router._resolve_turn = AsyncMock(return_value=(recovered, resolution))-- launch = asyncio.run(router.resolve("codex", "gpt-5"))-- assert launch.channel == "direct"- assert service.events.list(limit=10) == []---def test_direct_to_healthy_hub_switch_is_manual(tmp_path: Path) -> None:- """MH-EVT-002: a mapped Direct-to-Hub mode switch stays manual."""-- hub = _source(- "src_hub_manual",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("custom-gpt-5",),- )- agents = _agents(mode="direct")- agents["codex"].mappings = [ModelHubMappingConfig("gpt-5", "custom-gpt-5", True)]- service = _service(- tmp_path,- _hub_config(sources=[hub], order=[hub.id], agents=agents),- LaunchAdapter({hub.id: "route-hub"}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service)-- assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "direct"- agents["codex"].mode = "hub"- launch = asyncio.run(router.resolve("codex", "gpt-5"))-- assert (launch.channel, launch.source_id) == ("hub", hub.id)- event = service.events.list(limit=10)[0]- assert (event["kind"], event["reason"]) == ("mapping_applied", "mapping")---def test_mh_chan_001_other_backend_source_does_not_activate_hub(tmp_path: Path) -> None:- codex_native = _source(- "src_native_other",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- )- service = _service(- tmp_path,- _hub_config(- sources=[codex_native],- order=[codex_native.id],- agents=_agents(),- ),- LaunchAdapter({}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )-- with pytest.raises(ModelHubError, match="mapping_target_unavailable"):- asyncio.run(_router(service).resolve("claude", "claude-opus"))---def test_agent_projection_matches_interrupted_unmapped_fixed_backend(tmp_path: Path) -> None:- """MH-CHAN-001: an unmapped Hub backend remains fail closed."""-- hub = _source(- "src_hub_display",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("codex-auto-review",),- )- adapter = LaunchAdapter({hub.id: "route-hub"})- service = _service(- tmp_path,- _hub_config(- sources=[hub],- order=[hub.id],- agents=_agents(),- ),- adapter,- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- service.store.requested_models["claude"] = "claude-opus-4-6"-- projected = next(agent for agent in service.list_agents() if agent["backend"] == "claude")- router = _router(service)- with pytest.raises(ModelHubError, match="mapping_target_unavailable"):- asyncio.run(router.resolve("claude", "claude-opus-4-6"))- assert "current" not in projected- assert projected["supply_status"] == "interrupted"- assert adapter.starts == 0- event = service.events.list(limit=10)[0]- assert (event["kind"], event["reason"]) == (- "supply_interrupted",- "model_unsupported",- )---def test_agent_projection_uses_explicit_default_vibe_agent_model(tmp_path: Path) -> None:- """MH-CHAN-001: the default Vibe Agent supplies its explicit model."""-- hub = _source(- "src_hub_agent_model",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("agent-model",),- )- service = _service(- tmp_path,- _hub_config(- sources=[hub],- order=[hub.id],- agents=_agents(),- ),- LaunchAdapter({hub.id: "route-hub"}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- service.requested_model_override = lambda backend: "agent-model" if backend == "codex" else None- router = _router(service)-- projected = next(agent for agent in service.list_agents() if agent["backend"] == "codex")- chain = service.agent_chain("codex", "agent-model")- candidate = next(item for item in chain["chain"] if item["runnable"])- launch = asyncio.run(router.resolve("codex", "agent-model"))-- assert "current" not in projected- assert projected["selected_model_id"] == "agent-model"- assert {- "model_id": candidate["resolved_model_id"] or chain["model_id"],- "source_id": candidate["source_id"],- "channel": candidate["channel"],- } == {- "model_id": launch.target_model,- "source_id": launch.source_id,- "channel": launch.channel,+def hub_launch(**overrides) -> ModelHubLaunch:+ values = {+ "backend": "claude",+ "channel": "hub",+ "requested_model": "menu-model",+ "target_model": "concrete-upstream-id",+ "runtime_model": "concrete-upstream-id",+ "source_id": "src_inject01",+ "gateway_base_url": "http://127.0.0.1:15220",+ "gateway_token": "local-test-token",}+ values.update(overrides)+ return ModelHubLaunch(**values)-def test_agent_chain_and_runtime_router_share_resolution_table(tmp_path: Path) -> None:- """MH-CHAN-001/MH-MAP-001/MH-OC-001: chain equals runtime resolution."""-- fixed_hub = _source(- "src_hub_mapped",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("mapped-model",),- )- fixed_agents = _agents()- fixed_agents["claude"].mappings = [ModelHubMappingConfig("claude-native", "mapped-model", True)]-- direct_hub = _source(- "src_hub_direct",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- direct_agents = _agents()- direct_agents["codex"].mode = "direct"-- opencode_hub = _source(- "src_hub_open",- kind="api_key",- vendor="anthropic",- protocol="anthropic",- channel="hub",- model_ids=("claude-opus",),- )- opencode_agents = _agents()- opencode_agents["opencode"].menu = ModelHubMenuConfig(- view="featured",- checked=["anthropic/claude-opus", "custom/mapped-open"],- )- opencode_agents["opencode"].mappings = [ModelHubMappingConfig("anthropic/claude-opus", "custom/mapped-open", True)]- opencode_mapped = _source(- "src_hub_open_mapped",- kind="api_key",- vendor="custom",- protocol="openai_chat",- channel="hub",- model_ids=("mapped-open",),- )- unavailable_open = _source(- "src_hub_open_error",- kind="api_key",- vendor="anthropic",- protocol="anthropic",- channel="hub",- model_ids=("blocked-model",),- state="error",- )- available_open = _source(- "src_hub_open_ready",- kind="api_key",- vendor="custom",- protocol="openai_chat",- channel="hub",- model_ids=("ready-model",),- )- default_open_agents = _agents()- default_open_agents["opencode"].menu = ModelHubMenuConfig(- view="featured",- checked=["anthropic/blocked-model", "custom/ready-model"],- )-- native = _source(- "src_native_table",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- )-- cases = [- (- "claude",- "claude-native",- _hub_config(- sources=[fixed_hub],- order=[fixed_hub.id],- agents=fixed_agents,- ),- {"model_id": "mapped-model", "source_id": fixed_hub.id, "channel": "hub"},- ),- (- "codex",- "gpt-5",- _hub_config(- sources=[direct_hub],- order=[direct_hub.id],- agents=direct_agents,- ),- None,- ),- (- "opencode",- "claude-opus",- _hub_config(- sources=[opencode_hub, opencode_mapped],- order=[opencode_mapped.id, opencode_hub.id],- agents=opencode_agents,- ),- {- "model_id": "claude-opus",- "source_id": opencode_hub.id,- "channel": "hub",- },- ),- (- "opencode",- "",- _hub_config(- sources=[unavailable_open, available_open],- order=[unavailable_open.id, available_open.id],- agents=default_open_agents,- ),- {- "model_id": "ready-model",- "source_id": available_open.id,- "channel": "hub",- },- ),- (- "codex",- "gpt-5",- _hub_config(- sources=[native],- order=[native.id],- agents=_agents(),- ),- {"model_id": "gpt-5", "source_id": native.id, "channel": "native_cli"},- ),- ]-- for backend, requested_model, config, expected in cases:- adapter = LaunchAdapter(- {source.id: f"route-{source.id}" for source in config.sources if source.supply_channel == "hub"}- )- service = _service(- tmp_path,- config,- adapter,- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- service.store.requested_models[backend] = requested_model- router = _router(service)-- projected = next(agent for agent in service.list_agents() if agent["backend"] == backend)- launch = asyncio.run(router.resolve(backend, requested_model))- actual = (- None- if launch.channel == "direct"- else {- "model_id": launch.target_model,- "source_id": launch.source_id,- "channel": launch.channel,- }- )-- assert "current" not in projected- if expected is not None and requested_model:- chain = service.agent_chain(backend, requested_model)- candidate = next(item for item in chain["chain"] if item["runnable"])- assert {- "model_id": candidate["resolved_model_id"] or chain["model_id"],- "source_id": candidate["source_id"],- "channel": candidate["channel"],- } == expected- assert actual == expected---def test_mh_chan_001_configured_hub_stays_fail_closed_for_unavailable_model(tmp_path: Path) -> None:- hub = _source(- "src_hub0099",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- agents = _agents()- agents["codex"].mappings = [ModelHubMappingConfig("unavailable-model", "configured-but-missing", True)]- service = _service(- tmp_path,- _hub_config(sources=[hub], order=[hub.id], agents=agents),- LaunchAdapter({hub.id: "route-hub"}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(_router(service).resolve("codex", "unavailable-model"))-- assert exc_info.value.code == "mapping_target_unavailable"---def test_mh_chan_001_invalid_native_runtime_skips_to_hub(tmp_path: Path) -> None:- native = _source(- "src_native_invalid",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- )- hub = _source(- "src_hub_fallback",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- service = _service(- tmp_path,- _hub_config(- sources=[native, hub],- order=[native.id, hub.id],- agents=_agents(),- ),- LaunchAdapter({hub.id: "route-hub"}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )-- launch = asyncio.run(- _router(service, native_cli_ready=lambda backend: backend != "codex").resolve("codex", "gpt-5")- )-- assert (launch.channel, launch.source_id, launch.runtime_model) == (- "hub",- hub.id,- "route-hub/gpt-5",- )- assert native.state.status == "standby"---def test_projection_rechecks_expired_native_readiness_before_recovery(- tmp_path: Path,-) -> None:- """MH-CHAN-001: projection uses post-recovery native readiness."""-- clock = datetime(2026, 7, 23, tzinfo=timezone.utc)- native = _source(- "src_native_expired",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- state="cooldown",- retry_at=(clock - timedelta(seconds=1)).isoformat(),- )- hub = _source(- "src_hub_after_expired",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("gpt-5",),- )- service = _service(- tmp_path,- _hub_config(- sources=[native, hub],- order=[native.id, hub.id],- agents=_agents(),- ),- LaunchAdapter({hub.id: "route-hub"}),- now=lambda: clock,- )- service.store.requested_models["codex"] = "gpt-5"- router = _router(service, native_cli_ready=lambda _backend: False)-- projected = next(agent for agent in service.list_agents() if agent["backend"] == "codex")- chain = service.agent_chain("codex", "gpt-5")- candidate = next(item for item in chain["chain"] if item["runnable"])- launch = asyncio.run(router.resolve("codex", "gpt-5"))-- assert "current" not in projected- assert {- "model_id": candidate["resolved_model_id"] or chain["model_id"],- "source_id": candidate["source_id"],- "channel": candidate["channel"],- } == {- "model_id": "gpt-5",- "source_id": hub.id,+def test_persisted_launch_identity_keeps_exact_route_target_without_mapping_flag():+ launch = hub_launch()+ assert persisted_launch_identity(launch) == {+ "backend": "claude","channel": "hub",+ "source_id": "src_inject01",+ "target_model": "concrete-upstream-id",}- assert (launch.channel, launch.source_id) == ("hub", hub.id)- assert native.state.status == "active"---def test_mh_chan_001_codex_native_runtime_requires_chatgpt_oauth(tmp_path: Path, monkeypatch) -> None:- codex_home = tmp_path / "codex-home"- codex_home.mkdir()- auth_path = codex_home / "auth.json"- config_path = codex_home / "config.toml"- auth_path.write_text(json.dumps({"tokens": {"access_token": "fixture-token"}}))- config_path.write_text("")- codex_executable = tmp_path / "codex"- codex_executable.write_text("#!/bin/sh\nexit 0\n")- codex_executable.chmod(0o755)- codex_runtime = SimpleNamespace(- enabled=True,- cli_path=str(codex_executable),- )- monkeypatch.setattr(- "modules.agents.model_hub.load_config_or_default",- lambda: SimpleNamespace(- agents=SimpleNamespace(codex=codex_runtime),- ),- )- monkeypatch.setenv("CODEX_HOME", str(codex_home))- for key in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE", "CODEX_API_KEY"):- monkeypatch.delenv(key, raising=False)+ assert "via_mapping" not in persisted_launch_identity(launch)- assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is True-- codex_runtime.enabled = False- assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is False- codex_runtime.enabled = True- codex_runtime.cli_path = str(tmp_path / "missing-codex")- assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is False- codex_runtime.cli_path = str(codex_executable)-- config_path.write_text(- 'model_provider = "relay"\n\n[model_providers.relay]\nbase_url = "https://relay.invalid/v1"\n'- )- assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is False-- config_path.write_text("")- auth_path.write_text(- json.dumps(- {- "tokens": {"access_token": "fixture-token"},- "OPENAI_API_KEY": "fixture-api-key",- }- )- )- assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is False-- auth_path.write_text("{}")- assert ModelHubRuntimeRouter._default_native_cli_ready("codex") is False- assert (- ModelHubRuntimeRouter._default_native_cli_ready(- "codex",- verified_oauth=True,- )- is True- )---def test_mh_chan_001_claude_native_runtime_requires_enabled_executable(- tmp_path: Path,- monkeypatch,-) -> None:- claude_executable = tmp_path / "claude"- claude_executable.write_text("#!/bin/sh\nexit 0\n")- claude_executable.chmod(0o755)- claude_runtime = SimpleNamespace(- enabled=True,- cli_path=str(claude_executable),- )- monkeypatch.setattr(- "modules.agents.model_hub.load_config_or_default",- lambda: SimpleNamespace(- agents=SimpleNamespace(claude=claude_runtime),- ),- )- monkeypatch.setattr(- "vibe.claude_config.read_claude_settings_env",- lambda: {},- )- for key in ("ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL"):- monkeypatch.delenv(key, raising=False)-- assert ModelHubRuntimeRouter._default_native_cli_ready("claude") is True-- claude_runtime.enabled = False- assert ModelHubRuntimeRouter._default_native_cli_ready("claude") is False- claude_runtime.enabled = True- claude_runtime.cli_path = str(tmp_path / "missing-claude")- assert ModelHubRuntimeRouter._default_native_cli_ready("claude") is False---def test_mh_chan_001_verified_codex_keyring_source_remains_routable(- tmp_path: Path,- monkeypatch,-) -> None:- clock = {"now": datetime(2026, 7, 25, tzinfo=timezone.utc)}- codex_home = tmp_path / "codex-keyring-home"- codex_home.mkdir()- (codex_home / "auth.json").write_text("{}")- (codex_home / "config.toml").write_text('cli_auth_credentials_store = "keyring"\n')- codex_executable = tmp_path / "codex"- codex_executable.write_text("#!/bin/sh\nexit 0\n")- codex_executable.chmod(0o755)- monkeypatch.setattr(- "modules.agents.model_hub.load_config_or_default",- lambda: SimpleNamespace(- agents=SimpleNamespace(- codex=SimpleNamespace(- enabled=True,- cli_path=str(codex_executable),- )- ),- ),- )- monkeypatch.setenv("CODEX_HOME", str(codex_home))- for key in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_API_BASE", "CODEX_API_KEY"):- monkeypatch.delenv(key, raising=False)-- native = _source(- "src_native_keyring",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("gpt-5",),- state="active",- )- service = _service(- tmp_path,- _hub_config(- sources=[native],- order=[native.id],- agents=_agents(),- ),- LaunchAdapter({}),- now=lambda: clock["now"],- )- router = ModelHubRuntimeRouter(- service=service,- overlay_path=tmp_path / "overlay.json",- )-- launch = asyncio.run(router.resolve("codex", "gpt-5"))-- assert (launch.channel, launch.source_id) == ("native_cli", native.id)+def test_context_binding_restores_only_concrete_source_launch():context = SimpleNamespace()+ launch = hub_launch()bind_launch(context, launch)- assert asyncio.run(router.record_native_failure(context, "usage limit reached")) is True- assert native.state.status == "cooldown"-- clock["now"] += timedelta(seconds=301)- service.store.requested_models["codex"] = "gpt-5"- projected = next(agent for agent in service.list_agents() if agent["backend"] == "codex")- chain = service.agent_chain("codex", "gpt-5")- candidate = next(item for item in chain["chain"] if item["runnable"])- assert native.state.status == "cooldown"- recovered = asyncio.run(router.resolve("codex", "gpt-5"))-- assert "current" not in projected- assert {- "model_id": candidate["resolved_model_id"] or chain["model_id"],- "source_id": candidate["source_id"],- "channel": candidate["channel"],- } == {- "model_id": "gpt-5",- "source_id": native.id,- "channel": "native_cli",- }- assert (recovered.channel, recovered.source_id) == ("native_cli", native.id)- assert native.state.status == "active"---def test_mh_chan_001_persisted_launch_identity_is_non_secret_and_restorable() -> None:- launch = ModelHubLaunch(- backend="opencode",- channel="hub",- requested_model="openai/gpt-5",- target_model="gpt-5",- runtime_model="route-openai/gpt-5",- source_id="src_hub_restore",- gateway_base_url="http://127.0.0.1:18443",- gateway_token="gateway-secret",- )-- identity = persisted_launch_identity(launch)- assert identity == {- "backend": "opencode",- "channel": "hub",- "source_id": "src_hub_restore",- "target_model": "gpt-5",- }- restored_context = SimpleNamespace()- restored = bind_persisted_launch(restored_context, identity)-- assert restored == launch_for_context(restored_context)+ assert launch_for_context(context) == launch+ restored = bind_persisted_launch(context, persisted_launch_identity(launch))assert restored is not None- assert restored.gateway_base_url is None- assert restored.gateway_token is None+ assert restored.target_model == "concrete-upstream-id"+ assert restored.requested_model == "concrete-upstream-id"-def test_mh_inj_runtime_injection_never_writes_native_configs(tmp_path: Path, monkeypatch) -> None:- """MH-INJ-*-001 + MH-INJ-DIRECT-001: injections are process-local only."""+def test_direct_launch_does_not_inject_provider_credentials():+ launch = hub_launch(channel="direct", source_id=None, gateway_base_url=None, gateway_token=None)+ base_env = {"ANTHROPIC_AUTH_TOKEN": "user-token", "PATH": "/bin"}+ assert build_claude_hub_env(base_env, launch) == base_env+ assert build_codex_hub_launch(["--flag"], {"OPENAI_API_KEY": "user-key"}, launch) == (["--flag"], None)+ assert claude_setting_sources_for_launch(launch) == ["user", "project", "local"]- home = tmp_path / "home"- native_paths = (- home / ".claude" / "settings.json",- home / ".codex" / "config.toml",- home / ".config" / "opencode" / "opencode.json",- )- for index, path in enumerate(native_paths):- path.parent.mkdir(parents=True, exist_ok=True)- path.write_bytes(f"sentinel-{index}".encode())- before = {path: path.read_bytes() for path in native_paths}- monkeypatch.setenv("HOME", str(home))- hub_launch = ModelHubLaunch(- backend="claude",- channel="hub",- requested_model="claude-opus",- target_model="claude-opus",- runtime_model="route-claude/claude-opus",- source_id="src_hub0003",- gateway_base_url="http://127.0.0.1:18443",- gateway_token="gateway-only-token",- )- claude_env = build_claude_hub_env(+def test_hub_launch_masks_inherited_claude_auth_and_injects_gateway():+ launch = hub_launch()+ env = build_claude_hub_env({+ "ANTHROPIC_AUTH_TOKEN": "user-token",+ "ANTHROPIC_BASE_URL": "https://user.example",+ "CLAUDE_CODE_OAUTH_TOKEN": "oauth-token","PATH": "/bin",- "ANTHROPIC_API_KEY": "upstream-key",- "ANTHROPIC_AUTH_TOKEN": "upstream-token",- "ANTHROPIC_BASE_URL": "https://upstream.invalid",- "ANTHROPIC_CUSTOM_HEADERS": "x-upstream-auth: stale",- "ANTHROPIC_MODEL": "stale-model",},- hub_launch,- )- assert claude_env == {- "PATH": "/bin",- "ANTHROPIC_BASE_URL": "http://127.0.0.1:18443",- "ANTHROPIC_AUTH_TOKEN": "gateway-only-token",- }-- codex_launch = ModelHubLaunch(**{**hub_launch.__dict__, "backend": "codex"})- codex_args, codex_env = build_codex_hub_launch(- [],- {"PATH": "/bin", "OPENAI_API_KEY": "upstream", "OPENAI_API_BASE": "https://old.invalid"},- codex_launch,- )- assert codex_args[:2] == ["-c", 'model_provider="avibe_model_hub"']- assert "model_providers.avibe_model_hub.supports_websockets=false" in codex_args- assert codex_env == {"PATH": "/bin", "AVIBE_MODEL_HUB_TOKEN": "gateway-only-token"}-- direct = ModelHubLaunch("claude", "direct", "model", "model", "model")- native = ModelHubLaunch("claude", "native_cli", "model", "model", "model", "src_native")- base_env = {"ANTHROPIC_API_KEY": "native-value", "PATH": "/bin"}- assert build_claude_hub_env(base_env, direct) == base_env- assert build_codex_hub_launch(["--legacy"], base_env, direct) == (["--legacy"], None)- assert claude_setting_sources_for_launch(hub_launch) == ["project", "local"]- assert claude_setting_sources_for_launch(direct) == ["user", "project", "local"]- assert claude_setting_sources_for_launch(native) == ["user", "project", "local"]- assert CodexAgent._is_managed_provider_transition("openai", "avibe_model_hub") is True- assert CodexAgent._is_managed_provider_transition("avibe_model_hub", "openai") is True- assert {path: path.read_bytes() for path in native_paths} == before---def _opencode_config() -> ModelHubConfig:- anthropic = _source(- "src_hub0004",- kind="api_key",- vendor="anthropic",- protocol="anthropic",- channel="hub",- model_ids=("claude-opus",),- )- custom = _source(- "src_hub0005",- kind="api_key",- vendor="relay-vendor",- protocol="openai_chat",- channel="hub",- model_ids=("local-model",),+ launch,)- agents = _agents()- agents["opencode"].menu = ModelHubMenuConfig(- view="featured",- checked=["anthropic/claude-opus", "custom/local-model"],- )- return _hub_config(- sources=[anthropic, custom],- order=[anthropic.id, custom.id],- agents=agents,- )---def test_mh_ovl_001_identifiers_stay_stable_across_all_perturbations(tmp_path: Path) -> None:- """MH-OC-001/MH-OVL-001: visible identifiers never inherit source identity."""-- config = _opencode_config()- adapter = LaunchAdapter(- {- "src_hub0004": "route-anthropic-a",- "src_hub0005": "route-custom-a",- "src_hub0006": "route-anthropic-b",- }- )- service = _service(- tmp_path,- config,- adapter,- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service, overlay_path=tmp_path / "runtime" / "opencode.json")- baseline = asyncio.run(router.prepare_opencode_overlay())- assert baseline is not None- stable_projection = overlay_identifier_bytes(baseline.content)- assert json.loads(stable_projection) == ["anthropic/claude-opus", "custom/local-model"]- assert opencode_model_for_overlay(None, baseline) == "anthropic/claude-opus"+ assert env["ANTHROPIC_BASE_URL"] == launch.gateway_base_url+ assert env["ANTHROPIC_AUTH_TOKEN"] == launch.gateway_token+ assert "CLAUDE_CODE_OAUTH_TOKEN" not in env+ assert claude_setting_sources_for_launch(launch) == ["project", "local"]- config.agents["opencode"].mode = "direct"- assert asyncio.run(router.prepare_opencode_overlay()) is None- config.agents["opencode"].mode = "hub"- after_mode_switch = asyncio.run(router.prepare_opencode_overlay())- backup = _source(- "src_hub0006",- kind="api_key",- vendor="anthropic",- protocol="anthropic",- channel="hub",- model_ids=("claude-opus",),- )- config.sources.append(backup)- opencode_order = config.agents["opencode"].sources.order- config.agents["opencode"].sources.order = [backup.id, *reversed(opencode_order)]- after_add_reorder = asyncio.run(router.prepare_opencode_overlay())+def test_codex_hub_launch_uses_responses_wire_api_and_ephemeral_token():+ launch = hub_launch(backend="codex")+ args, env = build_codex_hub_launch(["--model", launch.runtime_model], {"OPENAI_API_KEY": "user-key"}, launch)+ rendered = " ".join(args)+ assert 'wire_api="responses"' in rendered+ assert "model_provider=\"avibe_model_hub\"" in rendered+ assert env == {"AVIBE_MODEL_HUB_TOKEN": "local-test-token"}- backup.state = ModelHubSourceStateConfig(- status="cooldown",- retry_at=(datetime(2026, 7, 24, tzinfo=timezone.utc)).isoformat(),- )- after_cooldown = asyncio.run(router.prepare_opencode_overlay())- config.sources.remove(backup)- config.agents["opencode"].sources.order.remove(backup.id)- after_remove = asyncio.run(router.prepare_opencode_overlay())- after_engine_restart = asyncio.run(router.prepare_opencode_overlay())- overlays = (- after_mode_switch,- after_add_reorder,- after_cooldown,- after_remove,- after_engine_restart,+def test_opencode_overlay_requires_exact_checked_identifier():+ overlay = SimpleNamespace(+ checked_identifiers=("openai/gpt-5", "custom/gpt-5"),+ available_identifiers=("openai/gpt-5", "custom/gpt-5"),)- assert all(overlay is not None for overlay in overlays)- assert {overlay_identifier_bytes(overlay.content) for overlay in overlays if overlay} == {stable_projection}- payload = json.loads(after_remove.content) # type: ignore[union-attr]- assert set(payload["provider"]) == {"anthropic", "custom"}- assert payload["provider"]["anthropic"]["npm"] == "@ai-sdk/anthropic"- assert payload["provider"]["custom"]["npm"] == "@ai-sdk/openai-compatible"- assert stat.S_IMODE(router.overlay_path.stat().st_mode) == 0o600---def test_mh_oc_001_open_menu_ignores_stale_fixed_mapping(tmp_path: Path) -> None:- """MH-OC-001: OpenCode menu identifiers, not fixed mappings, define routes."""-- config = _opencode_config()- config.agents["opencode"].mappings = [- ModelHubMappingConfig(- "anthropic/claude-opus",- "custom/local-model",- True,- )- ]- service = _service(- tmp_path,- config,- LaunchAdapter(- {- "src_hub0004": "route-anthropic",- "src_hub0005": "route-custom",- }- ),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service, overlay_path=tmp_path / "overlay.json")-- overlay = asyncio.run(router.prepare_opencode_overlay())- assert overlay is not None- assert json.loads(overlay_identifier_bytes(overlay.content)) == [- "anthropic/claude-opus",- "custom/local-model",- ]- launch = asyncio.run(- router.resolve_opencode_overlay_launch(- overlay,- "anthropic/claude-opus",- )- )- assert launch.source_id == "src_hub0004"- assert launch.target_model == "claude-opus"- assert launch.runtime_model == "route-anthropic/claude-opus"---def test_mh_ovl_001_unavailable_menu_entry_does_not_block_healthy_model(tmp_path: Path) -> None:- config = _opencode_config()- anthropic = config.sources[0]- anthropic.state = ModelHubSourceStateConfig(- status="cooldown",- retry_at=datetime(2026, 7, 24, tzinfo=timezone.utc).isoformat(),- )- adapter = LaunchAdapter(- {- "src_hub0004": "route-anthropic",- "src_hub0005": "route-custom",- }- )- service = _service(- tmp_path,- config,- adapter,- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service, overlay_path=tmp_path / "overlay.json")-- cooling_overlay = asyncio.run(router.prepare_opencode_overlay())- assert cooling_overlay is not None- assert json.loads(overlay_identifier_bytes(cooling_overlay.content)) == [- "anthropic/claude-opus",- "custom/local-model",- ]- assert cooling_overlay.available_identifiers == ("custom/local-model",)- assert opencode_model_for_overlay(None, cooling_overlay) == "custom/local-model"- assert opencode_model_for_overlay("local-model", cooling_overlay) == "custom/local-model"- assert opencode_model_for_overlay("custom/local-model", cooling_overlay) == "custom/local-model"+ assert opencode_model_for_overlay("openai/gpt-5", overlay) == "openai/gpt-5"with pytest.raises(ModelHubError):- asyncio.run(router.resolve("opencode", "anthropic/claude-opus"))-- config.sources.remove(anthropic)- config.agents["opencode"].sources.order.remove(anthropic.id)- reduced_overlay = asyncio.run(router.prepare_opencode_overlay())- assert reduced_overlay is not None- assert reduced_overlay.checked_identifiers == ("custom/local-model",)- assert opencode_model_for_overlay("custom/local-model", reduced_overlay) == "custom/local-model"+ opencode_model_for_overlay("gpt-5", overlay)-def test_mh_ovl_001_turn_uses_overlay_source_snapshot(tmp_path: Path) -> None:- primary = _source(- "src_hub_snapshot_a",- kind="api_key",- vendor="anthropic",- protocol="anthropic",- channel="hub",- model_ids=("claude-opus",),- )- backup = _source(- "src_hub_snapshot_b",- kind="api_key",- vendor="anthropic",- protocol="anthropic",- channel="hub",- model_ids=("claude-opus",),+def test_opencode_overlay_never_repeats_add_time_bare_identifier_matching():+ overlay = SimpleNamespace(+ checked_identifiers=("openai/gpt-5",),+ available_identifiers=("openai/gpt-5",),)- agents = _agents()- agents["opencode"].menu = ModelHubMenuConfig(- view="featured",- checked=["anthropic/claude-opus"],- )- config = _hub_config(- sources=[primary, backup],- order=[primary.id, backup.id],- agents=agents,- )- adapter = LaunchAdapter(- {- primary.id: "route-snapshot-a",- backup.id: "route-snapshot-b",- }- )- service = _service(- tmp_path,- config,- adapter,- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service, overlay_path=tmp_path / "overlay.json")- overlay = asyncio.run(router.prepare_opencode_overlay())- assert overlay is not None-- config.agents["opencode"].sources.order = [backup.id, primary.id]- launch = asyncio.run(- resolve_opencode_overlay_launch(- SimpleNamespace(model_hub_runtime=router),- "anthropic/claude-opus",- overlay,- )- )-- assert launch.source_id == primary.id- assert launch.runtime_model == "route-snapshot-a/claude-opus"- assert asyncio.run(router.resolve("opencode", "anthropic/claude-opus")).source_id == backup.id- context = SimpleNamespace()- bind_launch(context, launch)- assert asyncio.run(router.record_native_failure(context, "429 rate limit")) is True- assert primary.state.status == "cooldown"- assert backup.state.status == "standby"---def test_mh_chan_001_switch_telemetry_is_isolated_per_model_route(tmp_path: Path) -> None:- native_a = _source(- "src_native_a",- kind="subscription",- vendor="openai",- protocol="openai_responses",- channel="native_cli",- model_ids=("model-a",),- )- hub_a = _source(- "src_hub_a",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("model-a",),- )- hub_b = _source(- "src_hub_b",- kind="api_key",- vendor="openai",- protocol="openai_responses",- channel="hub",- model_ids=("model-b",),- )- config = _hub_config(- sources=[native_a, hub_a, hub_b],- order=[native_a.id, hub_a.id, hub_b.id],- agents=_agents(),- )- service = _service(- tmp_path,- config,- LaunchAdapter({hub_a.id: "route-a", hub_b.id: "route-b"}),- now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),- )- router = _router(service)-- native_launch = asyncio.run(router.resolve("codex", "model-a"))- assert asyncio.run(router.resolve("codex", "model-b")).channel == "hub"- assert not [event for event in service.events.list(limit=20) if event["kind"] == "channel_switch"]-- context = SimpleNamespace()- bind_launch(context, native_launch)- assert asyncio.run(router.record_native_failure(context, "usage quota exceeded")) is True- asyncio.run(router.resolve("codex", "model-b"))- assert not [event for event in service.events.list(limit=20) if event["kind"] == "switch"]-- assert asyncio.run(router.resolve("codex", "model-a")).source_id == hub_a.id- switch_events = [event for event in service.events.list(limit=20) if event["kind"] in {"switch", "channel_switch"}]- assert {event["model_id"] for event in switch_events} == {"model-a"}---def test_mh_inj_opencode_overlay_change_drains_then_restarts_and_records_hash(tmp_path: Path) -> None:- """MH-INJ-OPENCODE-001: active work drains before overlay restart."""-- manager = OpenCodeServerManager()- manager._pid_file = tmp_path / "opencode_server.json"- manager._active_run_sessions.add("active-session")- manager._is_healthy = AsyncMock(return_value=True)- manager._restart_for_auth_refresh_locked = AsyncMock()- overlay = SimpleNamespace(path=tmp_path / "overlay.json", content_hash="abc123")-- async def exercise() -> None:- async def finish_active_work() -> None:- await asyncio.sleep(0.02)- manager._active_run_sessions.clear()-- finisher = asyncio.create_task(finish_active_work())- await manager.configure_model_hub_overlay(overlay)- await finisher-- asyncio.run(exercise())- manager._restart_for_auth_refresh_locked.assert_awaited_once()- manager._write_pid_file(12345)- metadata = json.loads(manager._pid_file.read_text())- assert metadata["model_hub_overlay_hash"] == "abc123"- assert metadata["model_hub_overlay_path"] == str(overlay.path)---def test_mh_inj_opencode_matching_pid_overlay_is_cached_for_crash_recovery(tmp_path: Path) -> None:- manager = OpenCodeServerManager()- manager._pid_file = tmp_path / "opencode_server.json"- overlay = SimpleNamespace(path=tmp_path / "overlay.json", content_hash="same-hash")- manager._read_pid_file = Mock(- return_value={- "pid": 12345,- "port": manager.port,- "active_run_sessions": [],- "model_hub_overlay_path": str(overlay.path),- "model_hub_overlay_hash": overlay.content_hash,- }- )- manager._pid_file_references_current_server = Mock(return_value=True)- manager._is_healthy = AsyncMock(return_value=True)-- asyncio.run(manager.configure_model_hub_overlay(overlay))-- assert manager._model_hub_overlay_path == str(overlay.path)- assert manager._model_hub_overlay_hash == overlay.content_hash- manager._is_healthy.assert_not_awaited()---def test_mh_inj_opencode_stale_persisted_active_run_is_bounded(tmp_path: Path) -> None:- manager = OpenCodeServerManager()- manager._pid_file = tmp_path / "opencode_server.json"- manager._model_hub_overlay_drain_timeout_seconds = 0- manager._read_pid_file = Mock(- return_value={- "pid": 12345,- "port": manager.port,- "active_run_sessions": ["stale-run"],- "model_hub_overlay_path": "/old-overlay.json",- "model_hub_overlay_hash": "old-hash",- }- )- manager._pid_file_references_current_server = Mock(return_value=True)- manager._is_healthy = AsyncMock(return_value=True)- manager._restart_for_auth_refresh_locked = AsyncMock()- overlay = SimpleNamespace(path=tmp_path / "overlay.json", content_hash="new-hash")-- asyncio.run(manager.configure_model_hub_overlay(overlay))-- manager._restart_for_auth_refresh_locked.assert_awaited_once()- assert manager._model_hub_overlay_hash == "new-hash"---def test_mh_inj_direct_opencode_overlay_is_a_noop(tmp_path: Path) -> None:- """MH-INJ-DIRECT-001: unchanged direct mode does not inspect the live CLI."""-- manager = OpenCodeServerManager()- manager._pid_file = tmp_path / "opencode_server.json"- manager._is_healthy = AsyncMock(return_value=True)- asyncio.run(manager.configure_model_hub_overlay(None))- manager._is_healthy.assert_not_awaited()---def test_mh_inj_opencode_config_env_is_hub_only(tmp_path: Path, monkeypatch) -> None:- """MH-INJ-DIRECT-001: direct serve launch has no OPENCODE_CONFIG injection."""-- monkeypatch.delenv("OPENCODE_CONFIG", raising=False)- monkeypatch.delenv("OPENCODE_CONFIG_CONTENT", raising=False)-- async def capture(overlay_content: bytes | None) -> dict:- manager = OpenCodeServerManager()- manager._pid_file = tmp_path / f"pid-{bool(overlay_content)}.json"- if overlay_content is not None:- overlay_path = tmp_path / "overlay.json"- overlay_path.write_bytes(overlay_content)- manager._model_hub_overlay_path = str(overlay_path)- manager._model_hub_overlay_hash = hashlib.sha256(overlay_content).hexdigest()- manager._clear_pid_file = Mock()- manager._write_pid_file = Mock()- manager._apply_resource_governance = Mock()- manager._is_healthy = AsyncMock(return_value=True)- process = SimpleNamespace(pid=4321, returncode=None)- with (- patch("modules.agents.opencode.server.server_environment", return_value={"AVIBE_TEST": "1"}),- patch(- "modules.agents.opencode.server.asyncio.create_subprocess_exec", new=AsyncMock(return_value=process)- ) as spawn,- ):- await manager._start_server()- return spawn.await_args.kwargs["env"]-- overlay_content = b'{"provider":{"openai":{}}}\n'- direct_env = asyncio.run(capture(None))- hub_env = asyncio.run(capture(overlay_content))- assert "OPENCODE_CONFIG" not in direct_env- assert hub_env["OPENCODE_CONFIG"] == str(tmp_path / "overlay.json")- assert hub_env["OPENCODE_CONFIG_CONTENT"] == overlay_content.decode()---def test_mh_chan_001_codex_resolves_only_after_session_queue_lock() -> None:- async def exercise() -> None:- agent = object.__new__(CodexAgent)- lock = asyncio.Lock()- await lock.acquire()- resolver = AsyncMock()- agent._session_locks = {"session": lock}- agent.controller = SimpleNamespace(model_hub_runtime=SimpleNamespace(resolve=resolver))- request = SimpleNamespace(base_session_id="session")-- task = asyncio.create_task(agent.handle_message(request))- await asyncio.sleep(0.02)- resolver.assert_not_awaited()- task.cancel()- lock.release()- with suppress(asyncio.CancelledError):- await task-- asyncio.run(exercise())---def test_mh_inj_codex_runtime_change_waits_for_shared_active_turn(tmp_path: Path) -> None:- async def exercise() -> None:- agent = object.__new__(CodexAgent)- active = {"value": True}- old_transport = SimpleNamespace(- is_initialized=True,- runtime_fingerprint="direct",- stop=AsyncMock(),- )- new_transport = SimpleNamespace(- start=AsyncMock(),- on_notification=Mock(),- on_server_request=Mock(),- pid=12345,- )- agent._transport_locks = {}- agent._transports = {str(tmp_path): old_transport}- agent._transport_last_activity = {}- agent._transport_cwd_inodes = {}- agent._session_mgr = SimpleNamespace(- sessions_for_cwd=Mock(return_value={"other-session"}),- invalidate_thread=Mock(),- )- agent._turn_registry = SimpleNamespace(- get_active_turn=lambda _session_id: "turn" if active["value"] else None,- clear_session=Mock(),- )- agent._clear_thread_developer_instructions = Mock()- agent._on_notification = Mock()- agent._on_server_request = AsyncMock()- agent.codex_config = SimpleNamespace(binary="codex", extra_args=[])- agent.controller = SimpleNamespace(resource_governor=None)- agent._runtime_ownership_snapshot_for_cwd = Mock(- return_value=SimpleNamespace(blocks_transport_replacement=False)- )- launch = ModelHubLaunch(- "codex",- "hub",- "gpt-5",- "gpt-5",- "route/gpt-5",- "src_hub",- "http://127.0.0.1:18443",- "token",- )-- with (- patch("modules.agents.codex.agent.CodexTransport", return_value=new_transport),- patch(- "modules.agents.codex.agent.governor_from_controller",- return_value=SimpleNamespace(apply_to_pid=Mock()),- ),- ):- task = asyncio.create_task(agent._get_or_create_transport(str(tmp_path), launch))- await asyncio.sleep(0.02)- old_transport.stop.assert_not_awaited()- active["value"] = False- assert await task is new_transport-- old_transport.stop.assert_awaited_once()- new_transport.start.assert_awaited_once()-- asyncio.run(exercise())---def test_mh_inj_codex_hub_to_direct_retires_gateway_scope(- tmp_path: Path,-) -> None:- async def exercise() -> None:- agent = object.__new__(CodexAgent)- old_transport = SimpleNamespace(- is_initialized=True,- runtime_fingerprint="hub:http://127.0.0.1:18443:token-hash",- stop=AsyncMock(),- )- new_transport = SimpleNamespace(- start=AsyncMock(),- on_notification=Mock(),- on_server_request=Mock(),- pid=12345,- )- retire_scope = Mock()- agent._transport_locks = {}- agent._transports = {str(tmp_path): old_transport}- agent._transport_last_activity = {}- agent._transport_cwd_inodes = {}- agent._session_mgr = SimpleNamespace(- sessions_for_cwd=Mock(return_value=set()),- invalidate_thread=Mock(),- )- agent._turn_registry = SimpleNamespace(clear_session=Mock())- agent._clear_thread_developer_instructions = Mock()- agent._on_notification = Mock()- agent._on_server_request = AsyncMock()- agent.codex_config = SimpleNamespace(binary="codex", extra_args=[])- agent.controller = SimpleNamespace(- resource_governor=None,- model_hub_runtime=SimpleNamespace(- retire_process_scope=retire_scope,- ),- )- agent._runtime_ownership_snapshot_for_cwd = Mock(- return_value=SimpleNamespace(blocks_transport_replacement=False)- )- launch = ModelHubLaunch(- "codex",- "direct",- "gpt-5",- "gpt-5",- "gpt-5",- )-- with (- patch("modules.agents.codex.agent.CodexTransport", return_value=new_transport),- patch(- "modules.agents.codex.agent.governor_from_controller",- return_value=SimpleNamespace(apply_to_pid=Mock()),- ),- ):- assert await agent._get_or_create_transport(str(tmp_path), launch) is new_transport-- old_transport.stop.assert_awaited_once()- new_transport.start.assert_awaited_once()- retire_scope.assert_called_once_with("codex", str(tmp_path))-- asyncio.run(exercise())---def test_mh_inj_codex_runtime_change_interrupts_current_session_first() -> None:- async def exercise() -> None:- agent = object.__new__(CodexAgent)- active = {"turn": "turn-current"}- transport = SimpleNamespace(- is_initialized=True,- runtime_fingerprint="direct",- send_request=AsyncMock(return_value={}),- )- interrupted_request = SimpleNamespace(context=object())-- def clear_pending(turn_id: str):- assert turn_id == "turn-current"- active["turn"] = None- return interrupted_request-- agent._transports = {"/work": transport}- agent._session_mgr = SimpleNamespace(get_thread_id=Mock(return_value="thread-current"))- agent._turn_registry = SimpleNamespace(get_active_turn=lambda _base: active["turn"])- agent._event_handler = SimpleNamespace(- clear_pending=Mock(side_effect=clear_pending),- _release_stream_turn=Mock(),- )- agent._remove_ack_reaction = AsyncMock()- request = SimpleNamespace(- working_path="/work",- base_session_id="session-current",- )- launch = ModelHubLaunch(- "codex",- "hub",- "gpt-5",- "gpt-5",- "route/gpt-5",- "src_hub",- "http://127.0.0.1:18443",- "token",- )-- await agent._interrupt_active_turn_before_runtime_change(request, launch)-- transport.send_request.assert_awaited_once_with(- "turn/interrupt",- {"threadId": "thread-current", "turnId": "turn-current"},- )- assert active["turn"] is None- agent._remove_ack_reaction.assert_awaited_once_with(interrupted_request)- agent._event_handler._release_stream_turn.assert_called_once_with(interrupted_request.context)-- asyncio.run(exercise())---def test_mh_inj_codex_runtime_change_replaces_transport_when_interrupt_fails() -> None:- async def exercise() -> None:- agent = object.__new__(CodexAgent)- active = {"turn": "turn-current"}- transport = SimpleNamespace(- is_initialized=True,- runtime_fingerprint="direct",- send_request=AsyncMock(side_effect=ConnectionError("transport closed")),- )- interrupted_request = SimpleNamespace(context=object())-- def clear_pending(turn_id: str):- assert turn_id == "turn-current"- active["turn"] = None- return interrupted_request-- agent._transports = {"/work": transport}- agent._session_mgr = SimpleNamespace(get_thread_id=Mock(return_value="thread-current"))- agent._turn_registry = SimpleNamespace(get_active_turn=lambda _base: active["turn"])- agent._event_handler = SimpleNamespace(- clear_pending=Mock(side_effect=clear_pending),- _release_stream_turn=Mock(),- )- agent._remove_ack_reaction = AsyncMock()- request = SimpleNamespace(- working_path="/work",- base_session_id="session-current",- )- launch = ModelHubLaunch(- "codex",- "hub",- "gpt-5",- "gpt-5",- "route/gpt-5",- "src_hub",- "http://127.0.0.1:18443",- "token",- )-- await agent._interrupt_active_turn_before_runtime_change(request, launch)-- assert active["turn"] is None- agent._remove_ack_reaction.assert_awaited_once_with(interrupted_request)- agent._event_handler._release_stream_turn.assert_called_once_with(interrupted_request.context)-- asyncio.run(exercise())---def test_mh_inj_codex_direct_resume_clears_implicit_hub_provider() -> None:- async def exercise() -> None:- agent = object.__new__(CodexAgent)- transport = SimpleNamespace(- send_request=AsyncMock(- side_effect=[- {"config": {}},- {"thread": {"id": "thread-existing", "modelProvider": "avibe_model_hub"}},- ]- )- )- request = SimpleNamespace(working_path="/work")-- provider = await agent._resolve_resume_model_provider_override(- transport,- request,- "thread-existing",- )-- assert provider == "openai"-- asyncio.run(exercise())---def test_mh_inj_claude_channel_change_waits_for_active_turn() -> None:- async def exercise() -> None:- handler = object.__new__(SessionHandler)- handler.controller = SimpleNamespace(runtime_activation=None)- key = "session:/work"- client = SimpleNamespace(_vibe_model_hub_fingerprint="native_cli:src_native")- handler.claude_sessions = {key: client}- handler.active_sessions = {key}- handler._cleanup_session_locked = AsyncMock()- launch = ModelHubLaunch(- "claude",- "hub",- "claude-opus",- "claude-opus",- "route/claude-opus",- "src_hub",- "http://127.0.0.1:18443",- "token",- )-- task = asyncio.create_task(- handler._reuse_cached_claude_session_if_available(- composite_key=key,- base_session_id="session",- working_path="/work",- context=SimpleNamespace(),- session_key="settings",- stored_claude_session_id=None,- current_model="claude-opus",- agent_system_prompt=None,- model_hub_launch=launch,- )- )- await asyncio.sleep(0.02)- handler._cleanup_session_locked.assert_not_awaited()- handler.active_sessions.clear()- assert await task is None- handler._cleanup_session_locked.assert_awaited_once_with(- key,- retire_model_hub_scope=False,- )-- asyncio.run(exercise())-+ with pytest.raises(ModelHubError):+ opencode_model_for_overlay("gpt-5", overlay)-def test_mh_inj_cached_claude_subagent_uses_resolved_native_model() -> None:- native = ModelHubLaunch(- "claude",- "native_cli",- "builtin-opus",- "claude-opus-4-6",- "claude-opus-4-6",- "src_native",- )- direct = ModelHubLaunch("claude", "direct", "builtin-opus", "builtin-opus", "builtin-opus")- assert SessionHandler._cached_claude_subagent_model("builtin-opus", native) == "claude-opus-4-6"- assert SessionHandler._cached_claude_subagent_model(None, direct) is None+def test_fallback_launch_identity_is_stable_for_same_route():+ first = hub_launch(target_model="model-a", runtime_model="model-a", source_id="src_inject01")+ second = hub_launch(target_model="model-b", runtime_model="model-b", source_id="src_inject02")+ assert first.fingerprint == second.fingerprint+ assert first.source_id != second.source_iddiff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex aeeb4e4a5..8ff0c8868 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -1,15 +1,18 @@from __future__ import annotations+import astimport asyncioimport jsonfrom collections import dequefrom datetime import datetime, timedelta, timezonefrom pathlib import Pathfrom types import SimpleNamespace+from typing import castfrom unittest.mock import AsyncMock, Mock, patchimport aiohttpimport pytest+from aiohttp import webfrom jsonschema import Draft7Validator, FormatCheckerfrom sqlalchemy import create_engine, delete, select@@ -18,19 +21,27 @@ from config.v2_config import (ModelHubAgentSupplyConfig,ModelHubConfig,ModelHubModelConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,ModelHubSourceConfig,ModelHubSourceStateConfig,+ model_hub_fixed_menu_ids,)from core.handlers.model_hub.adapter import (EngineHealth,EngineStatus,RawCallOutcome,RawOutcomeKind,+ SOURCE_PROTOCOLS,)from core.handlers.model_hub.classification import classify_outcomefrom core.handlers.model_hub.events import (BoundedEventLog,+ EVENT_REASON_AUTHORITY,+ EventKind,+ EventReason,build_resolution_event,+ event_reason_label,)from core.handlers.model_hub.provenance import (BoundedProvenanceStore,@@ -50,10 +61,22 @@ from core.session_turns import SessionTurnManagerfrom modules.agents.model_hub import (ModelHubLaunch,ModelHubRuntimeRouter,+ _localized_launch_error,bind_launch,bind_turn_mode,)from storage.models import agent_sessions, messages, metadata+from vibe.model_hub_runtime.adapter import (+ _AuthenticationEvidence,+ CLIProxyEngineAdapter,+ _parse_protocol_authenticated_evidence,+ _probe_protocol_response,+ _PROTOCOL_OBSERVATION_TAXONOMY,+ _ProtocolEvidence,+ _ProtocolProof,+)+from vibe.model_hub_runtime.client import EngineClientError, probe_models+from vibe.model_hub_runtime.state import EngineStateStoreCONTRACTS = Path(__file__).parents[1] / "docs" / "plans" / "model-hub-contracts"@@ -72,6 +95,61 @@ def _assert_valid(schema_name: str, payload: dict) -> None:assert not errors, [error.message for error in errors]+def test_route_unconfigured_launch_copy_exists_in_each_backend_locale() -> None:+ locale_launch = {+ locale: json.loads((Path(__file__).parents[1] / f"vibe/i18n/{locale}.json").read_text(encoding="utf-8"))[+ "modelHub"+ ]["launch"]+ for locale in ("en", "zh")+ }++ assert locale_launch["en"].keys() == locale_launch["zh"].keys()+ assert all("{model}" in launch["route_unconfigured"] for launch in locale_launch.values())+ failure = ModelHubError(+ "no_candidate",+ data={+ "copy_key": "route_unconfigured",+ "model": "menu-model",+ "blockers": [],+ },+ )+ for locale, launch in locale_launch.items():+ rendered = _localized_launch_error(+ SimpleNamespace(config=SimpleNamespace(language=locale)),+ "claude",+ "menu-model",+ failure,+ )+ assert rendered.detail == launch["route_unconfigured"].format(model="menu-model")+++def test_structural_blocker_copy_uses_its_reason_instead_of_source_status() -> None:+ failure = ModelHubError(+ "no_candidate",+ data={+ "copy_key": "interrupted",+ "model": "menu-model",+ "blockers": [+ {+ "source": "Exact source",+ "status": "standby",+ "reason": "model_unsupported",+ }+ ],+ },+ )++ rendered = _localized_launch_error(+ SimpleNamespace(config=SimpleNamespace(language="en")),+ "claude",+ "menu-model",+ failure,+ )++ assert event_reason_label("model_unsupported", "en") in rendered.detail+ assert "standby" not in rendered.detail++class MemoryStore:def __init__(self, config: ModelHubConfig):self.config = config@@ -108,6 +186,8 @@ class ProbeAdapter:self.outcomes = deque(outcomes)self.invocations: list[tuple[str, str, str]] = []self.requests: list[ModelHubRequest] = []+ self.refreshable_credential_refs: set[str] = set()+ self.capability_queries: list[str] = []async def sync_sources(self, _bindings) -> None:return None@@ -115,6 +195,10 @@ class ProbeAdapter:async def revoke_credential(self, _credential_ref: str) -> None:return None+ async def credential_supports_refresh(self, credential_ref: str) -> bool:+ self.capability_queries.append(credential_ref)+ return credential_ref in self.refreshable_credential_refs+async def invoke(self, source_id, model_id, request, _stream, origin):self.invocations.append((source_id, model_id, origin))self.requests.append(request)@@ -153,11 +237,7 @@ def _source(state=ModelHubSourceStateConfig(status=status,retry_at=retry_at,- detail_key=(- "models.source.cooldown.rate_limited"- if status == "cooldown"- else None- ),+ detail_key=("models.source.cooldown.rate_limited" if status == "cooldown" else None),),models=[ModelHubModelConfig(@@ -171,13 +251,22 @@ def _source(def _config(sources: list[ModelHubSourceConfig]) -> ModelHubConfig:agents = {- backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")- for backend in ("claude", "codex", "opencode")+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub") for backend in ("claude", "codex", "opencode")}- for agent in agents.values():+ for backend, agent in agents.items():+ eligible = [source for source in sources if ModelHubConfig.source_eligible_for_backend(source, backend)]agent.sources = ModelHubAgentSourcesConfig(- policy="custom",- order=[source.id for source in sources],+ order=[source.id for source in eligible],+ )+ requested_model = "openai/shared-model" if backend == "opencode" else "shared-model"+ agent.routes[requested_model] = ModelHubRouteConfig(+ hops=tuple(+ ModelHubRouteHopConfig(+ source_id=source.id,+ model_id=source.models[0].id,+ )+ for source in eligible+ ))agents["opencode"].menu.checked = ["openai/shared-model"]return ModelHubConfig(sources=sources, agents=agents)@@ -220,6 +309,26 @@ def _service()+def _canonicalize_fixed_test_routes(+ service: ModelHubService,+) -> dict[str, str]:+ selected = {}+ config = service.store.load()+ for backend in ("claude", "codex"):+ menu_ids = model_hub_fixed_menu_ids(backend)+ selected[backend] = menu_ids[0]+ shared_route = config.agents[backend].routes.get(+ "shared-model",+ ModelHubRouteConfig(),+ )+ config.agents[backend].routes = {+ model_id: (shared_route if model_id == selected[backend] else ModelHubRouteConfig())+ for model_id in menu_ids+ }+ service.store.requested_models[backend] = selected[backend]+ return selected++def _begin_hub_attempt(registry: TurnCorrelationRegistry,*,@@ -506,9 +615,7 @@ def test_gateway_terminalizer_records_pre_observer_engine_down_before_return(assert response.status == 503await response.read()- trace = gateway.correlation._traces[- "turn_pre_observer_engine_down"- ]+ trace = gateway.correlation._traces["turn_pre_observer_engine_down"]assert trace.pending_attempt is Noneassert trace.terminal_error == {"source_id": "src_primary01",@@ -583,7 +690,7 @@ def test_gateway_provenance_retains_pre_mapping_model_identity(_assert_valid("turn-provenance.schema.json", record)-def test_gateway_preserves_native_alias_for_per_source_failover(+def test_gateway_uses_persisted_exact_hops_for_failover(tmp_path: Path,) -> None:async def exercise() -> None:@@ -619,6 +726,13 @@ def test_gateway_preserves_native_alias_for_per_source_failover(),],)+ _canonicalize_fixed_test_routes(service)+ service.store.config.agents["claude"].routes[requested_model] = ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(primary.id, primary_model),+ ModelHubRouteHopConfig(backup.id, backup_model),+ )+ )gateway = ModelHubTurnGateway(service)base_url, token = await gateway.endpoint("claude",@@ -635,9 +749,7 @@ def test_gateway_preserves_native_alias_for_per_source_failover(json={"model": primary_model,"max_tokens": 1,- "messages": [- {"role": "user", "content": "ping"}- ],+ "messages": [{"role": "user", "content": "ping"}],"stream": False,},headers={"x-api-key": token},@@ -651,14 +763,8 @@ def test_gateway_preserves_native_alias_for_per_source_failover((primary.id, primary_model, "claude"),(backup.id, backup_model, "claude"),]- failover_events = [- event- for event in service.events.list(limit=20)- if event["kind"] in {"cooldown", "switch"}- ]- assert {event["model_id"] for event in failover_events} == {- requested_model- }+ failover_events = [event for event in service.events.list(limit=20) if event["kind"] in {"cooldown", "switch"}]+ assert {event["model_id"] for event in failover_events} == {requested_model}gateway.correlation.settle("turn_native_alias",@@ -905,9 +1011,7 @@ def test_fsm_cancel_drop_and_control_classification(tmp_path: Path) -> None:)controller = SimpleNamespace(model_hub_runtime=runtime,- command_handler=SimpleNamespace(- handle_stop=AsyncMock(return_value=True)- ),+ command_handler=SimpleNamespace(handle_stop=AsyncMock(return_value=True)),set_agent_status=lambda _session_id, _status: None,)manager = SessionTurnManager(controller)@@ -978,12 +1082,8 @@ def test_fsm_cancel_drop_and_control_classification(tmp_path: Path) -> None:def test_fsm_settlement_persists_the_turn_time_mode() -> None:runtime = SimpleNamespace(settle_turn=Mock())- manager = SessionTurnManager(- SimpleNamespace(model_hub_runtime=runtime)- )- context = SimpleNamespace(- platform_specific={"turn_token": "turn_direct"}- )+ manager = SessionTurnManager(SimpleNamespace(model_hub_runtime=runtime))+ context = SimpleNamespace(platform_specific={"turn_token": "turn_direct"})bind_launch(context,ModelHubLaunch(@@ -1006,12 +1106,8 @@ def test_fsm_settlement_persists_the_turn_time_mode() -> None:def test_fsm_settlement_persists_model_less_direct_mode() -> None:runtime = SimpleNamespace(settle_turn=Mock())- manager = SessionTurnManager(- SimpleNamespace(model_hub_runtime=runtime)- )- context = SimpleNamespace(- platform_specific={"turn_token": "turn_opencode_default"}- )+ manager = SessionTurnManager(SimpleNamespace(model_hub_runtime=runtime))+ context = SimpleNamespace(platform_specific={"turn_token": "turn_opencode_default"})bind_turn_mode(context, "direct")manager._settle_model_hub_turn(@@ -1031,9 +1127,7 @@ def test_settlement_retires_correlation_when_mode_persistence_fails(tmp_path,sources=[_source("src_primary01", "Primary")],)- service.note_turn_mode = Mock(- side_effect=OSError("mode store unavailable")- )+ service.note_turn_mode = Mock(side_effect=OSError("mode store unavailable"))router = ModelHubRuntimeRouter(service=service,turn_gateway=SimpleNamespace(correlation=correlation),@@ -1054,6 +1148,970 @@ def test_settlement_retires_correlation_when_mode_persistence_fails()+def test_opencode_overlay_projects_menu_identity_to_exact_hop_model(tmp_path: Path) -> None:+ source = _source("src_overlay01", "Overlay", model_id="upstream-model")+ config = _config([source])+ agent = config.agents["opencode"]+ agent.routes.pop("openai/shared-model")+ agent.routes["openai/menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),))+ agent.menu.checked = ["openai/menu-model"]+ service = _service(tmp_path, sources=[source])+ service.store.config = config+ gateway = SimpleNamespace(+ endpoint=AsyncMock(return_value=("http://127.0.0.1:19000", "gateway-token")),+ )+ router = ModelHubRuntimeRouter(+ service=service,+ turn_gateway=gateway,+ overlay_path=tmp_path / "overlay.json",+ )++ overlay = asyncio.run(router.prepare_opencode_overlay())++ assert overlay is not None+ payload = json.loads(overlay.content)+ assert payload["provider"]["openai"]["models"]["menu-model"]["id"] == ("openai/menu-model")+ assert overlay.launches[0].target_model == "upstream-model"+++def test_opencode_overlay_supports_mixed_protocols_under_one_provider(tmp_path: Path) -> None:+ first = _source(+ "src_overlay11",+ "First",+ vendor="custom",+ protocol="anthropic",+ model_id="first-model",+ )+ second = _source(+ "src_overlay12",+ "Second",+ vendor="custom",+ protocol="openai_responses",+ model_id="second-model",+ )+ config = _config([first, second])+ agent = config.agents["opencode"]+ agent.menu.checked = ["custom/first-model", "custom/second-model"]+ agent.routes = {+ "custom/first-model": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(first.id, "first-model"),)),+ "custom/second-model": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(second.id, "second-model"),)),+ }+ service = _service(tmp_path, sources=[first, second])+ service.store.config = config+ router = ModelHubRuntimeRouter(+ service=service,+ turn_gateway=SimpleNamespace(+ endpoint=AsyncMock(return_value=("http://127.0.0.1:19000/opencode", "gateway-token")),+ ),+ overlay_path=tmp_path / "overlay.json",+ )++ overlay = asyncio.run(router.prepare_opencode_overlay())++ assert overlay is not None+ provider = json.loads(overlay.content)["provider"]["custom"]+ assert provider["npm"] == "@ai-sdk/openai-compatible"+ assert provider["options"]["baseURL"] == "http://127.0.0.1:19000/opencode/v1"+ assert set(provider["models"]) == {"first-model", "second-model"}+ assert {launch.target_model for launch in overlay.launches} == {+ "first-model",+ "second-model",+ }+++def test_opencode_overlay_selects_supported_fallback_by_exact_hop(tmp_path: Path) -> None:+ source = _source(+ "src_overlay03",+ "Overlay",+ model_id="supported-model",+ )+ config = _config([source])+ agent = config.agents["opencode"]+ agent.routes.pop("openai/shared-model")+ agent.routes["openai/menu-model"] = ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(source.id, "stale-model"),+ ModelHubRouteHopConfig(source.id, "supported-model"),+ )+ )+ agent.menu.checked = ["openai/menu-model"]+ service = _service(tmp_path, sources=[source])+ service.store.config = config+ router = ModelHubRuntimeRouter(+ service=service,+ turn_gateway=SimpleNamespace(+ endpoint=AsyncMock(return_value=("http://127.0.0.1:19000", "gateway-token")),+ ),+ overlay_path=tmp_path / "overlay.json",+ )++ overlay = asyncio.run(router.prepare_opencode_overlay())++ assert overlay is not None+ assert [launch.target_model for launch in overlay.launches] == ["supported-model"]+++def test_opencode_overlay_preserves_checked_route_with_stale_exact_hop(+ tmp_path: Path,+) -> None:+ source = _source(+ "src_overlay04",+ "Overlay",+ model_id="current-model",+ )+ config = _config([source])+ agent = config.agents["opencode"]+ agent.routes.pop("openai/shared-model")+ agent.routes["openai/menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "stale-model"),))+ agent.menu.checked = ["openai/menu-model"]+ service = _service(tmp_path, sources=[source])+ service.store.config = config+ router = ModelHubRuntimeRouter(+ service=service,+ turn_gateway=SimpleNamespace(+ endpoint=AsyncMock(return_value=("http://127.0.0.1:19000", "gateway-token")),+ ),+ overlay_path=tmp_path / "overlay.json",+ )++ overlay = asyncio.run(router.prepare_opencode_overlay())++ assert overlay is not None+ provider = json.loads(overlay.content)["provider"]["openai"]+ assert provider["models"] == {+ "menu-model": {+ "id": "openai/menu-model",+ "name": "menu-model",+ }+ }+ assert overlay.checked_identifiers == ("openai/menu-model",)+ assert overlay.available_identifiers == ()+ assert overlay.launches == ()+++def test_production_adapter_retargets_api_keys_without_exposing_or_mutating_them(+ tmp_path: Path,+) -> None:+ state_store = EngineStateStore(tmp_path / "engine-state")+ old_ref = state_store.store_api_key(+ "test-retarget-secret",+ vendor="custom",+ protocol="openai_chat",+ base_url="https://old-relay.example/v1",+ )+ oauth_ref = state_store.bind_oauth_credential(+ "src_oauthrefresh",+ "openai",+ "codex-test.json",+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=Mock(),+ state_store=state_store,+ )++ replacement_ref = asyncio.run(+ adapter.retarget_api_key_credential(+ old_ref,+ "custom",+ "openai_chat",+ "https://new-relay.example/v1?api-version=2026-08-10",+ )+ )++ assert replacement_ref != old_ref+ assert state_store.credential_metadata(old_ref)["base_url"] == ("https://old-relay.example/v1")+ assert state_store.credential_metadata(replacement_ref)["base_url"] == (+ "https://new-relay.example/v1?api-version=2026-08-10"+ )+ assert state_store.read_api_key(old_ref) == "test-retarget-secret"+ assert state_store.read_api_key(replacement_ref) == "test-retarget-secret"+ assert asyncio.run(adapter.credential_supports_refresh(old_ref)) is False+ assert asyncio.run(adapter.credential_supports_refresh(oauth_ref)) is True+++def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(+ tmp_path: Path,+) -> None:+ base_url = "https://relay.example/v1?api-version=2026-07-23"+ state_store = EngineStateStore(tmp_path / "engine-state")+ credential_ref = state_store.store_api_key(+ "test-observation-key",+ vendor="openai",+ protocol=SOURCE_PROTOCOLS[-1],+ base_url=base_url,+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=Mock(),+ state_store=state_store,+ )+ unsupported = EngineClientError(+ "unsupported protocol path",+ status_code=404,+ )+ proven_accepted = _ProtocolEvidence(+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ )+ proven_rejected = _ProtocolEvidence(+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.REJECTED,+ )+ proven_unknown = _ProtocolEvidence(+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )+ unproven_unknown = _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )++ hinted_order = tuple(reversed(SOURCE_PROTOCOLS))++ async def every_candidate_is_supported(**_kwargs) -> _ProtocolEvidence:+ return proven_accepted++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(side_effect=every_candidate_is_supported),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=("upstream-model",)),+ ) as inventory_probe,+ ):+ observed = asyncio.run(+ adapter.observe_source(+ "openai",+ base_url,+ credential_ref,+ hinted_order,+ )+ )++ assert observed.outcome.value == "observed"+ assert observed.protocol == hinted_order[0]+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == [hinted_order[0]]+ assert inventory_probe.await_args.kwargs["protocol"] == hinted_order[0]++ async def indistinguishable_response(**_kwargs) -> _ProtocolEvidence:+ return unproven_unknown++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(side_effect=indistinguishable_response),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=("upstream-model",)),+ ) as inventory_probe,+ ):+ ambiguous = asyncio.run(+ adapter.observe_source(+ "openai",+ base_url,+ credential_ref,+ hinted_order,+ )+ )++ assert ambiguous.outcome.value == "ambiguous"+ assert ambiguous.protocol is None+ assert ambiguous.authenticated is None+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(hinted_order)+ inventory_probe.assert_not_awaited()++ async def shaped_server_failure(**kwargs) -> _ProtocolEvidence:+ if kwargs["protocol"] == "anthropic":+ body = {"type": "error", "error": {"type": "api_error"}}+ else:+ body = {"error": {"type": "server_error"}}+ evidence = _parse_protocol_authenticated_evidence(+ kwargs["protocol"],+ 500,+ json.dumps(body),+ )+ assert evidence == proven_unknown+ return evidence++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(side_effect=shaped_server_failure),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=("unverified-model",)),+ ) as inventory_probe,+ ):+ upstream_error = asyncio.run(+ adapter.observe_source(+ "openai",+ base_url,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ assert upstream_error.outcome.value == "adapter_error"+ assert upstream_error.reachable is True+ assert upstream_error.authenticated is None+ assert upstream_error.protocol is None+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ inventory_probe.assert_not_awaited()+ _assert_valid(+ "observation-result.schema.json",+ {+ "contract_version": 5,+ "outcome": "adapter_error",+ "reachable": True,+ "authenticated": "unknown",+ "protocol": None,+ "discovery": "not_attempted",+ "models": [],+ },+ )++ proved_protocol = SOURCE_PROTOCOLS[1]++ async def later_protocol_probe(**kwargs) -> _ProtocolEvidence:+ if kwargs["protocol"] != proved_protocol:+ raise unsupported+ return proven_accepted++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(side_effect=later_protocol_probe),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=("upstream-model",)),+ ) as inventory_probe,+ ):+ observed = asyncio.run(+ adapter.observe_source(+ "openai",+ base_url,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ assert observed.outcome.value == "observed"+ assert observed.protocol == proved_protocol+ assert observed.model_ids == ("upstream-model",)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS[:2])+ assert inventory_probe.await_args.kwargs["protocol"] == proved_protocol+ assert inventory_probe.await_args.kwargs["base_url"] == base_url++ rejected_protocol = SOURCE_PROTOCOLS[0]+ accepted_protocol = SOURCE_PROTOCOLS[1]++ async def rejected_then_authenticated(**kwargs) -> _ProtocolEvidence:+ if kwargs["protocol"] == rejected_protocol:+ return proven_rejected+ return proven_accepted++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(side_effect=rejected_then_authenticated),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=("later-protocol-model",)),+ ) as inventory_probe,+ ):+ observed = asyncio.run(+ adapter.observe_source(+ "openai",+ base_url,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ assert observed.outcome.value == "observed"+ assert observed.authenticated is True+ assert observed.protocol == accepted_protocol+ assert observed.model_ids == ("later-protocol-model",)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == [+ rejected_protocol,+ accepted_protocol,+ ]+ assert inventory_probe.await_args.kwargs["protocol"] == accepted_protocol++ async def reject_every_candidate(**kwargs) -> _ProtocolEvidence:+ return _parse_protocol_authenticated_evidence(+ kwargs["protocol"],+ 401,+ json.dumps(+ {+ "error": {+ "type": "invalid_request_error",+ "code": "invalid_api_key",+ "param": None,+ }+ }+ ),+ )++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(side_effect=reject_every_candidate),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=("unreachable-model",)),+ ) as inventory_probe,+ ):+ rejected = asyncio.run(+ adapter.observe_source(+ "openai",+ base_url,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ assert rejected.outcome.value == "authentication_failed"+ assert rejected.reachable is True+ assert rejected.authenticated is False+ assert rejected.protocol is None+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ inventory_probe.assert_not_awaited()+++def test_oauth_observation_uses_the_bound_auth_index_and_requires_response_proof(+ tmp_path: Path,+) -> None:+ state_store = EngineStateStore(tmp_path / "engine-state")+ credential_ref = state_store.bind_oauth_credential(+ "src_oauthproof",+ "openai",+ "codex-test.json",+ )+ client = Mock()+ api_calls: list[dict] = []++ def management_request(method, path, *, query=None, payload=None):+ if path == "/auth-files":+ return {+ "files": [+ {+ "id": "codex-test",+ "auth_index": "auth-index-test",+ "name": "codex-test.json",+ "provider": "codex",+ "id_token": {"chatgpt_account_id": "account-test"},+ }+ ]+ }+ if path == "/api-call":+ api_calls.append(payload)+ return {+ "status_code": 400,+ "header": {},+ "body": json.dumps(+ {+ "error": {+ "type": "invalid_request_error",+ "param": "input",+ }+ }+ ),+ }+ if path == "/auth-files/models":+ assert query == {"name": "codex-test.json"}+ return {"models": [{"id": "gpt-5.6"}]}+ raise AssertionError((method, path))++ client.management_request.side_effect = management_request+ supervisor = Mock()+ supervisor.client.return_value = client+ adapter = CLIProxyEngineAdapter(+ supervisor=supervisor,+ state_store=state_store,+ )++ observed = asyncio.run(+ adapter.observe_source(+ "openai",+ None,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ assert observed.outcome.value == "observed"+ assert observed.protocol == "openai_responses"+ assert observed.model_ids == ("gpt-5.6",)+ assert len(api_calls) == 1+ assert api_calls[0]["auth_index"] == "auth-index-test"+ assert api_calls[0]["header"]["Chatgpt-Account-Id"] == "account-test"+ assert api_calls[0]["url"].endswith("/responses")+ assert json.loads(api_calls[0]["data"]) == dict(+ _PROTOCOL_OBSERVATION_TAXONOMY["openai_responses"].request_body+ )++ def ambiguous_management_request(method, path, *, query=None, payload=None):+ if path == "/auth-files":+ return management_request(method, path, query=query, payload=payload)+ if path == "/api-call":+ return {"status_code": 200, "header": {}, "body": '{"ok":true}'}+ raise AssertionError((method, path))++ client.management_request.side_effect = ambiguous_management_request+ ambiguous = asyncio.run(+ adapter.observe_source(+ "openai",+ None,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ assert ambiguous.outcome.value == "ambiguous"+ assert ambiguous.protocol is None+ assert ambiguous.authenticated is None+++ ("protocol", "success_body", "request_error_body", "auth_error_body"),+ [+ (+ "anthropic",+ {"type": "message"},+ {"type": "error", "error": {"type": "invalid_request_error"}},+ {"type": "error", "error": {"type": "authentication_error"}},+ ),+ (+ "openai_responses",+ {"object": "response"},+ {"error": {"type": "invalid_request_error", "param": "input"}},+ {+ "error": {+ "type": "invalid_request_error",+ "code": "invalid_api_key",+ "param": "input",+ }+ },+ ),+ (+ "openai_chat",+ {"object": "chat.completion"},+ {"error": {"type": "invalid_request_error", "param": "messages"}},+ {+ "error": {+ "type": "invalid_request_error",+ "code": "invalid_api_key",+ "param": "messages",+ }+ },+ ),+ ],+)+def test_protocol_evidence_parser_requires_candidate_specific_response_shapes(+ protocol: str,+ success_body: dict,+ request_error_body: dict,+ auth_error_body: dict,+) -> None:+ assert _parse_protocol_authenticated_evidence(+ protocol,+ 200,+ json.dumps(success_body),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ )+ assert _parse_protocol_authenticated_evidence(+ protocol,+ 400,+ json.dumps(request_error_body),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ )+ assert _parse_protocol_authenticated_evidence(+ protocol,+ 401,+ json.dumps(auth_error_body),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.REJECTED,+ )+ assert _parse_protocol_authenticated_evidence(+ protocol,+ 400,+ "{}",+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )+++ ("protocol", "status", "body"),+ [+ (+ "anthropic",+ 500,+ {"type": "error", "error": {"type": "api_error"}},+ ),+ (+ "openai_responses",+ 500,+ {"error": {"type": "server_error"}},+ ),+ (+ "openai_chat",+ 500,+ {"error": {"type": "server_error"}},+ ),+ (+ "anthropic",+ 429,+ {"type": "error", "error": {"type": "rate_limit_error"}},+ ),+ (+ "openai_responses",+ 429,+ {"error": {"type": "rate_limit_exceeded"}},+ ),+ (+ "openai_chat",+ 429,+ {"error": {"type": "rate_limit_exceeded"}},+ ),+ (+ "anthropic",+ 400,+ {"type": "error", "error": {"type": "future_error"}},+ ),+ (+ "openai_responses",+ 400,+ {"error": {"type": "future_error", "param": "input"}},+ ),+ (+ "openai_chat",+ 400,+ {"error": {"type": "future_error", "param": "messages"}},+ ),+ ],+)+def test_protocol_evidence_table_defaults_shaped_non_auth_rows_to_unknown(+ protocol: str,+ status: int,+ body: dict,+) -> None:+ assert _parse_protocol_authenticated_evidence(+ protocol,+ status,+ json.dumps(body),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )+++ ("protocol", "body"),+ [+ (+ "anthropic",+ {"type": "error", "error": {"type": "not_found_error"}},+ ),+ (+ "openai_responses",+ {"error": {"type": "invalid_request_error", "code": "model_not_found"}},+ ),+ (+ "openai_chat",+ {"error": {"type": "invalid_request_error", "code": "model_not_found"}},+ ),+ ],+)+def test_protocol_evidence_table_accepts_authenticated_model_errors(+ protocol: str,+ body: dict,+) -> None:+ assert _parse_protocol_authenticated_evidence(+ protocol,+ 404,+ json.dumps(body),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ )+++def test_shared_openai_authentication_rejection_does_not_prove_a_protocol() -> None:+ body = json.dumps(+ {+ "error": {+ "type": "invalid_request_error",+ "code": "invalid_api_key",+ "param": None,+ }+ }+ )++ for protocol in ("openai_responses", "openai_chat"):+ assert _parse_protocol_authenticated_evidence(+ protocol,+ 401,+ body,+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.REJECTED,+ )+++def test_protocol_observation_consumers_cannot_classify_from_status_codes() -> None:+ module_path = Path(__file__).parents[1] / "vibe/model_hub_runtime/adapter.py"+ module_source = module_path.read_text(encoding="utf-8")+ tree = ast.parse(module_source)+ assert _PROTOCOL_OBSERVATION_TAXONOMY.keys() == set(SOURCE_PROTOCOLS)+ assert _PROTOCOL_OBSERVATION_TAXONOMY["openai_responses"].request_path != _PROTOCOL_OBSERVATION_TAXONOMY[+ "openai_chat"+ ].request_path+ assert _PROTOCOL_OBSERVATION_TAXONOMY["openai_responses"].request_body == {+ "model": "__avibe_model_hub_probe__"+ }+ assert _PROTOCOL_OBSERVATION_TAXONOMY["openai_chat"].request_body == {+ "model": "__avibe_model_hub_probe__"+ }+ consumers = {+ node.name: node+ for node in ast.walk(tree)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ and node.name in {"_probe_protocol_response", "_probe_oauth_protocol_response"}+ }++ assert consumers.keys() == {+ "_probe_protocol_response",+ "_probe_oauth_protocol_response",+ }+ assert "json={}" not in module_source+ assert '"data": "{}"' not in module_source+ assert "_endpoint_for_protocol(" not in module_source+ for consumer in consumers.values():+ consumer_source = ast.get_source_segment(module_source, consumer)+ assert consumer_source is not None+ assert "_PROTOCOL_OBSERVATION_TAXONOMY" in consumer_source+ calls = [node for node in ast.walk(consumer) if isinstance(node, ast.Call)]+ assert any(+ isinstance(call.func, ast.Name) and call.func.id == "_parse_protocol_authenticated_evidence"+ for call in calls+ )+ compared_statuses = {+ constant.value+ for compare in ast.walk(consumer)+ if isinstance(compare, ast.Compare)+ for constant in ast.walk(compare)+ if isinstance(constant, ast.Constant)+ and isinstance(constant.value, int)+ and not isinstance(constant.value, bool)+ }+ assert not compared_statuses++ auth_branch_offenders = []+ for function in (+ node+ for node in ast.walk(tree)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))+ and node.name != "_parse_protocol_authenticated_evidence"+ ):+ for branch in (node for node in ast.walk(function) if isinstance(node, (ast.If, ast.IfExp))):+ condition = ast.unparse(branch.test)+ branch_source = ast.unparse(branch)+ if any(token in condition for token in ("status", "error")) and "_AuthenticationEvidence" in branch_source:+ auth_branch_offenders.append((function.name, condition))+ assert not auth_branch_offenders+++def test_protocol_observation_preserves_query_on_each_distinct_upstream_path() -> None:+ query = "api-version=2026-07-23"++ async def scenario() -> list[tuple[str, str, dict]]:+ requests: list[tuple[str, str, dict]] = []++ async def reject_empty_probe(request: web.Request) -> web.Response:+ requests.append((request.path, request.query_string, await request.json()))+ return web.json_response({"error": {"type": "invalid_request"}}, status=400)++ app = web.Application()+ app.router.add_post("/{tail:.*}", reject_empty_probe)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ assert site._server is not None+ port = site._server.sockets[0].getsockname()[1]+ try:+ for protocol in SOURCE_PROTOCOLS:+ await _probe_protocol_response(+ vendor="custom",+ protocol=protocol,+ base_url=f"http://127.0.0.1:{port}/v1?{query}",+ secret="test-observation-key",+ )+ finally:+ await runner.cleanup()+ return requests++ requests = asyncio.run(scenario())+ paths = [path for path, _query, _body in requests]++ assert len(paths) == len(SOURCE_PROTOCOLS)+ assert len(set(paths)) == len(paths)+ assert {request_query for _path, request_query, _body in requests} == {query}+ assert [body for _path, _query, body in requests] == [+ dict(_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_body)+ for protocol in SOURCE_PROTOCOLS+ ]+++def test_openai_probe_requests_are_mutually_distinguishable() -> None:+ responses = _PROTOCOL_OBSERVATION_TAXONOMY["openai_responses"]+ chat = _PROTOCOL_OBSERVATION_TAXONOMY["openai_chat"]++ assert responses.request_path != chat.request_path+ assert "input" not in responses.request_body+ assert "messages" not in chat.request_body+ assert _parse_protocol_authenticated_evidence(+ "openai_responses",+ 400,+ json.dumps({"error": {"type": "invalid_request_error", "param": "messages"}}),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )+ assert _parse_protocol_authenticated_evidence(+ "openai_chat",+ 400,+ json.dumps({"error": {"type": "invalid_request_error", "param": "input"}}),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )+++def test_model_discovery_preserves_query_when_appending_models_path() -> None:+ query = "api-version=2026-07-23"++ async def scenario() -> tuple[str, str, tuple[str, ...]]:+ request_target: tuple[str, str] | None = None++ async def list_models(request: web.Request) -> web.Response:+ nonlocal request_target+ request_target = (request.path, request.query_string)+ return web.json_response({"data": [{"id": "upstream-model"}]})++ app = web.Application()+ app.router.add_get("/{tail:.*}", list_models)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ assert site._server is not None+ port = site._server.sockets[0].getsockname()[1]+ try:+ models = await probe_models(+ vendor="custom",+ protocol="openai_chat",+ base_url=f"http://127.0.0.1:{port}/v1?{query}",+ secret="test-observation-key",+ )+ finally:+ await runner.cleanup()+ assert request_target is not None+ return request_target[0], request_target[1], models++ path, request_query, models = asyncio.run(scenario())++ assert path == "/v1/models"+ assert request_query == query+ assert models == ("upstream-model",)+++def test_blocked_exact_hop_emits_one_supply_interruption(tmp_path: Path) -> None:+ source = _source("src_blocked01", "Blocked")+ service = _service(tmp_path, sources=[source])+ service.store.config.agents["claude"].routes["shared-model"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "removed-model"),)+ )+ router = ModelHubRuntimeRouter(service=service)++ for _attempt in range(2):+ with pytest.raises(ModelHubError):+ asyncio.run(router.resolve("claude", "shared-model"))++ events = [event for event in service.list_events(limit=20) if event["kind"] == "supply_interrupted"]+ assert len(events) == 1+ assert events[0]["reason"] == "model_unsupported"+++ ("route", "native_ready", "reason"),+ [+ (ModelHubRouteConfig(), True, "route_unconfigured"),+ (+ ModelHubRouteConfig(hops=(ModelHubRouteHopConfig("src_missing01", "shared-model"),)),+ True,+ "source_missing",+ ),+ ],+)+def test_supply_interruption_preserves_exact_structural_reason(+ tmp_path: Path,+ route: ModelHubRouteConfig,+ native_ready: bool,+ reason: str,+) -> None:+ source = _source("src_present01", "Present")+ service = _service(tmp_path, sources=[source])+ service.store.config.agents["claude"].routes["shared-model"] = route+ router = ModelHubRuntimeRouter(+ service=service,+ native_cli_ready=lambda _backend: native_ready,+ )++ with pytest.raises(ModelHubError):+ asyncio.run(router.resolve("claude", "shared-model"))++ event = next(item for item in service.list_events(limit=20) if item["kind"] == "supply_interrupted")+ assert event["reason"] == reason+ _assert_valid("resolution-event.schema.json", event)+++def test_supply_interruption_preserves_native_process_reason(tmp_path: Path) -> None:+ source = _source(+ "src_native011",+ "Native",+ channel="native_cli",+ vendor="anthropic",+ protocol="anthropic",+ )+ service = _service(tmp_path, sources=[source])+ router = ModelHubRuntimeRouter(+ service=service,+ native_cli_ready=lambda _backend: False,+ )++ with pytest.raises(ModelHubError):+ asyncio.run(router.resolve("claude", "shared-model"))++ event = next(item for item in service.list_events(limit=20) if item["kind"] == "supply_interrupted")+ assert event["reason"] == "native_cli_unavailable"+ _assert_valid("resolution-event.schema.json", event)++def test_same_scope_concurrency_is_absent_and_sequential_control_is_present(tmp_path: Path,) -> None:@@ -1069,21 +2127,13 @@ def test_same_scope_concurrency_is_absent_and_sequential_control_is_present()controller = SimpleNamespace(model_hub_runtime=runtime,- command_handler=SimpleNamespace(- handle_stop=AsyncMock(return_value=True)- ),+ command_handler=SimpleNamespace(handle_stop=AsyncMock(return_value=True)),set_agent_status=lambda _session_id, _status: None,)manager = SessionTurnManager(controller)manager.flush_queue = AsyncMock(return_value=False)- started = {- turn_id: asyncio.Event()- for turn_id in ("turn_one", "turn_two", "turn_sequential")- }- release = {- turn_id: asyncio.Event()- for turn_id in ("turn_one", "turn_two", "turn_sequential")- }+ started = {turn_id: asyncio.Event() for turn_id in ("turn_one", "turn_two", "turn_sequential")}+ release = {turn_id: asyncio.Event() for turn_id in ("turn_one", "turn_two", "turn_sequential")}async def dispatch(_controller, context, _text, **_kwargs):turn_id = manager.model_hub_turn_id_for_task()@@ -1167,18 +2217,23 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:sources=[cooling, primary],outcomes=[_outcome(RawOutcomeKind.SUCCESS)],)+ menu_model = _canonicalize_fixed_test_routes(service)["claude"]- chain = service.agent_chain("claude", "shared-model")+ chain = service.agent_chain("claude", menu_model)assert [item["source_id"] for item in chain["chain"]] == ["src_cooling01","src_primary01",]assert chain["supply_state"] == "ok"+ assert chain["current"] == {+ "source_id": "src_primary01",+ "model_id": "shared-model",+ }assert all(item["channel"] == "hub" for item in chain["chain"])assert all(item["reason"] is None for item in chain["chain"])_assert_valid("agent-chain.schema.json", chain)- probe = asyncio.run(service.probe_agent("claude", "shared-model"))+ probe = asyncio.run(service.probe_agent("claude", menu_model))assert probe["channel"] == "hub"assert probe["reachable"] is Trueassert probe["source_id"] == "src_primary01"@@ -1191,9 +2246,8 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:sources=[_source("src_primary01", "Primary")],outcomes=[_outcome(RawOutcomeKind.NETWORK_ERROR)],)- network = asyncio.run(- network_service.probe_agent("claude", "shared-model")- )+ network_model = _canonicalize_fixed_test_routes(network_service)["claude"]+ network = asyncio.run(network_service.probe_agent("claude", network_model))assert network["reachable"] is Falseassert network["latency_ms"] is Noneassert network["error"] == "models.source.cooldown.network"@@ -1204,15 +2258,12 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:sources=[_source("src_primary01", "Primary")],outcomes=[_outcome(RawOutcomeKind.TIMEOUT)],)- timeout = asyncio.run(- timeout_service.probe_agent("claude", "shared-model")- )+ timeout_model = _canonicalize_fixed_test_routes(timeout_service)["claude"]+ timeout = asyncio.run(timeout_service.probe_agent("claude", timeout_model))assert timeout["reachable"] is Falseassert timeout["latency_ms"] is Noneassert timeout["error"] == "models.source.cooldown.timeout"- assert timeout_service.store.load().sources[0].state.detail_key == (- "models.source.cooldown.timeout"- )+ assert timeout_service.store.load().sources[0].state.detail_key == ("models.source.cooldown.timeout")assert timeout_service.events.list(limit=10)[0]["reason"] == "network"_assert_valid("probe-result.schema.json", timeout)@@ -1227,9 +2278,8 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:)],)- rate_limited = asyncio.run(- rate_service.probe_agent("claude", "shared-model")- )+ rate_model = _canonicalize_fixed_test_routes(rate_service)["claude"]+ rate_limited = asyncio.run(rate_service.probe_agent("claude", rate_model))assert rate_limited["reachable"] is Falseassert isinstance(rate_limited["latency_ms"], int)assert rate_limited["error"] == "models.source.cooldown.rate_limited"@@ -1246,16 +2296,12 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:)],)- unclassified = asyncio.run(- unclassified_service.probe_agent("claude", "shared-model")- )+ unclassified_model = _canonicalize_fixed_test_routes(unclassified_service)["claude"]+ unclassified = asyncio.run(unclassified_service.probe_agent("claude", unclassified_model))assert unclassified["reachable"] is Falseassert isinstance(unclassified["latency_ms"], int)assert unclassified["error"] == "models.source.error.unclassified"- assert (- unclassified_service.store.load().sources[0].state.status- == "error"- )+ assert unclassified_service.store.load().sources[0].state.status == "error"_assert_valid("probe-result.schema.json", unclassified)request_error_service = _service(@@ -1269,16 +2315,12 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:)],)- request_error = asyncio.run(- request_error_service.probe_agent("claude", "shared-model")- )+ request_error_model = _canonicalize_fixed_test_routes(request_error_service)["claude"]+ request_error = asyncio.run(request_error_service.probe_agent("claude", request_error_model))assert request_error["reachable"] is Falseassert isinstance(request_error["latency_ms"], int)assert request_error["error"] == "models.source.error.unclassified"- assert (- request_error_service.store.load().sources[0].state.status- == "standby"- )+ assert request_error_service.store.load().sources[0].state.status == "standby"assert request_error_service.events.list(limit=10) == []_assert_valid("probe-result.schema.json", request_error)@@ -1293,18 +2335,72 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:)],)- not_found = asyncio.run(- anthropic_not_found.probe_agent("claude", "shared-model")- )+ not_found_model = _canonicalize_fixed_test_routes(anthropic_not_found)["claude"]+ not_found = asyncio.run(anthropic_not_found.probe_agent("claude", not_found_model))assert not_found["reachable"] is False- assert (- anthropic_not_found.store.load().sources[0].state.status- == "standby"- )+ assert anthropic_not_found.store.load().sources[0].state.status == "standby"assert anthropic_not_found.events.list(limit=10) == []_assert_valid("probe-result.schema.json", not_found)+def test_probe_401_uses_exact_credential_refresh_capability(tmp_path: Path) -> None:+ static_source = _source("src_staticprobe", "Static")+ static_service = _service(+ tmp_path / "static",+ sources=[static_source],+ outcomes=[+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=401,+ code="unauthorized",+ source_id=static_source.id,+ )+ ],+ )+ static_model = _canonicalize_fixed_test_routes(static_service)["claude"]+ static_adapter = cast(ProbeAdapter, static_service.adapter)++ static_probe = asyncio.run(static_service.probe_agent("claude", static_model))++ assert static_probe["reachable"] is False+ assert static_probe["error"] == ("models.source.needs_action.credential_revoked")+ assert static_adapter.invocations == [(static_source.id, "shared-model", "claude")]+ assert static_adapter.capability_queries == [static_source.credential_ref]+ assert static_service.store.load().sources[0].state.detail_key == ("models.source.needs_action.credential_revoked")++ refreshable_source = _source("src_refreshprobe", "Refreshable")+ refreshable_service = _service(+ tmp_path / "refreshable",+ sources=[refreshable_source],+ outcomes=[+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=401,+ code="unauthorized",+ source_id=refreshable_source.id,+ ),+ _outcome(+ RawOutcomeKind.SUCCESS,+ status=200,+ source_id=refreshable_source.id,+ ),+ ],+ )+ refreshable_model = _canonicalize_fixed_test_routes(refreshable_service)["claude"]+ refreshable_adapter = cast(ProbeAdapter, refreshable_service.adapter)+ assert refreshable_source.credential_ref is not None+ refreshable_adapter.refreshable_credential_refs.add(refreshable_source.credential_ref)++ refreshable_probe = asyncio.run(refreshable_service.probe_agent("claude", refreshable_model))++ assert refreshable_probe["reachable"] is True+ assert refreshable_adapter.invocations == [+ (refreshable_source.id, "shared-model", "claude"),+ (refreshable_source.id, "shared-model", "claude"),+ ]+ assert refreshable_adapter.capability_queries == [refreshable_source.credential_ref]++@pytest.mark.parametrize(("backend", "source_protocol", "request_protocol", "request_keys"),[@@ -1314,12 +2410,7 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:"anthropic",{"model", "max_tokens", "messages"},)- for source_protocol in (- "anthropic",- "openai_responses",- "openai_chat",- "openai_chat",- )+ for source_protocol in SOURCE_PROTOCOLS]+ [(@@ -1328,12 +2419,7 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:"openai_responses",{"model", "max_output_tokens", "input"},)- for source_protocol in (- "anthropic",- "openai_responses",- "openai_chat",- "openai_chat",- )+ for source_protocol in SOURCE_PROTOCOLS]+ [(@@ -1346,12 +2432,7 @@ def test_chain_projection_and_probe_latency_partition(tmp_path: Path) -> None:else {"model", "max_tokens", "messages"}),)- for source_protocol in (- "anthropic",- "openai_responses",- "openai_chat",- "openai_chat",- )+ for source_protocol in SOURCE_PROTOCOLS],)def test_probe_request_matches_live_backend_protocol_matrix(@@ -1369,12 +2450,11 @@ def test_probe_request_matches_live_backend_protocol_matrix(outcomes=[_outcome(RawOutcomeKind.SUCCESS)],)- result = asyncio.run(service.probe_agent(backend, "shared-model"))+ requested_model = "openai/shared-model" if backend == "opencode" else "shared-model"+ result = asyncio.run(service.probe_agent(backend, requested_model))assert result["reachable"] is True- assert service.adapter.invocations == [- ("src_primary01", "shared-model", backend)- ]+ assert service.adapter.invocations == [("src_primary01", "shared-model", backend)]request = service.adapter.requests[0]assert request.protocol == request_protocolassert set(request) == request_keys@@ -1392,15 +2472,15 @@ def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:assert chain["chain"] == [{"source_id": native.id,+ "model_id": "shared-model","channel": "native_cli",- "via_mapping": False,- "resolved_model_id": None,"health": "healthy","runnable": True,"reason": None,"retry_at": None,}]+ assert chain["current"] == {"source_id": native.id, "model_id": "shared-model"}assert chain["supply_state"] == "ok"_assert_valid("agent-chain.schema.json", chain)@@ -1413,7 +2493,6 @@ def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:"source_id": native.id,"model_id": "shared-model","latency_ms": None,- "via_mapping": False,"error": None,}assert service.adapter.invocations == []@@ -1437,6 +2516,7 @@ def test_native_unavailability_is_orthogonal_to_health(assert chain["chain"][0]["health"] == "cooldown"assert chain["chain"][0]["reason"] == "native_cli_unavailable"assert chain["chain"][0]["runnable"] is False+ assert chain["current"] is Noneassert chain["supply_state"] == "interrupted"_assert_valid("agent-chain.schema.json", chain)@@ -1506,8 +2586,9 @@ def test_source_failure_event_is_single_grain_and_retained(tmp_path: Path) -> No)],)+ menu_model = _canonicalize_fixed_test_routes(service)["claude"]- probe = asyncio.run(service.probe_agent("claude", "shared-model"))+ probe = asyncio.run(service.probe_agent("claude", menu_model))assert probe["reachable"] is Falseevents = service.list_events(limit=20)failures = [event for event in events if event["kind"] == "needs_action"]@@ -1520,20 +2601,12 @@ def test_source_failure_event_is_single_grain_and_retained(tmp_path: Path) -> Noassert "Shared paid source" in event["human_zh"]_assert_valid("resolution-event.schema.json", event)- agents = {- item["backend"]: item- for item in service.list_agents()- }+ agents = {item["backend"]: item for item in service.list_agents()}assert agents["claude"]["supply_status"] == "interrupted"assert agents["codex"]["supply_status"] == "interrupted"- service.store.config.sources[0].state = ModelHubSourceStateConfig(- status="standby"- )- recovered_agents = {- item["backend"]: item- for item in service.list_agents()- }+ service.store.config.sources[0].state = ModelHubSourceStateConfig(status="standby")+ recovered_agents = {item["backend"]: item for item in service.list_agents()}assert recovered_agents["claude"]["supply_status"] == "ok"assert recovered_agents["codex"]["supply_status"] == "ok"assert service.list_events(limit=20)[0] == event@@ -1542,15 +2615,16 @@ def test_source_failure_event_is_single_grain_and_retained(tmp_path: Path) -> Noassert service.list_events(limit=20)[0] == event-def test_mapping_and_channel_switch_copy_retain_human_subjects() -> None:- mapping = build_resolution_event(- agent="codex",- kind="mapping_applied",- model_id="target-model",- reason="mapping",- from_label="requested-model",- now=NOW,- )+def test_retired_mapping_event_is_rejected_and_channel_switch_retains_subject() -> None:+ with pytest.raises(ValueError):+ build_resolution_event(+ agent="codex",+ kind=cast(EventKind, "mapping" + "_applied"),+ model_id="target-model",+ reason=cast(EventReason, "map" + "ping"),+ from_label="requested-model",+ now=NOW,+ )channel_switch = build_resolution_event(agent="system",kind="channel_switch",@@ -1563,18 +2637,74 @@ def test_mapping_and_channel_switch_copy_retain_human_subjects() -> None:now=NOW,)- for text in (mapping.human_en, mapping.human_zh):- assert "requested-model" in text- assert "target-model" in textfor text in (channel_switch.human_en, channel_switch.human_zh):assert "Primary source" in text+def test_resolution_event_reason_contract_matches_runtime_vocabulary() -> None:+ schema = json.loads((CONTRACTS / "resolution-event.schema.json").read_text(encoding="utf-8"))+ authority = tuple(EVENT_REASON_AUTHORITY)+ assert tuple(schema["properties"]["reason"]["enum"]) == authority++ locale_reasons = {+ locale: json.loads((Path(__file__).parents[1] / f"vibe/i18n/{locale}.json").read_text(encoding="utf-8"))[+ "modelHub"+ ]["events"]["reason"]+ for locale in ("en", "zh")+ }+ assert all(tuple(reasons) == authority for reasons in locale_reasons.values())+ assert all(+ event_reason_label(reason, locale) != f"modelHub.events.reason.{reason}"+ for locale in locale_reasons+ for reason in authority+ )++[email protected]("reason", tuple(EVENT_REASON_AUTHORITY))+def test_every_authoritative_reason_has_an_event_emission_path(reason: EventReason) -> None:+ reason_class = EVENT_REASON_AUTHORITY[reason]+ fields: dict = {+ "agent": "system",+ "model_id": None,+ "reason": reason,+ "now": NOW,+ }+ if reason_class == "structural":+ fields.update(agent="codex", kind="supply_interrupted", model_id="model")+ elif reason_class == "self_healing":+ fields.update(kind="cooldown", from_source="src_reason01")+ elif reason_class == "non_self_healing":+ fields.update(kind="needs_action", from_source="src_reason01")+ elif reason_class == "request_scoped":+ fields.update(+ agent="codex",+ kind="switch",+ model_id="model",+ from_source="src_reason01",+ to_source="src_reason02",+ )+ elif reason == "recovery":+ fields.update(kind="recover", to_source="src_reason01")+ else:+ fields.update(+ kind="channel_switch",+ from_source="src_reason01",+ to_source="src_reason01",+ )++ event = build_resolution_event(**fields)++ assert event.reason == reason+ assert event.human_en+ assert event.human_zh++def test_shared_source_cooldown_emits_only_on_state_transition(tmp_path: Path,) -> None:source = _source("src_primary01", "Shared source")service = _service(tmp_path, sources=[source])+ menu_models = _canonicalize_fixed_test_routes(service)decision = classify_outcome(_outcome(RawOutcomeKind.HTTP_ERROR,@@ -1588,13 +2718,13 @@ def test_shared_source_cooldown_emits_only_on_state_transition(source,decision,agent="claude",- model_id="shared-model",+ model_id=menu_models["claude"],)await service._cooldown(source,decision,agent="codex",- model_id="shared-model",+ model_id=menu_models["codex"],)asyncio.run(cool_twice())@@ -1683,11 +2813,7 @@ def test_provenance_absence_codes_are_distinguishable(lambda turn_id: (("codex", "direct")if turn_id == "turn_direct"- else (- ("codex", "hub")- if turn_id == "turn_ambiguous"- else (None, None)- )+ else (("codex", "hub") if turn_id == "turn_ambiguous" else (None, None))),)@@ -1701,10 +2827,7 @@ def test_provenance_absence_codes_are_distinguishable(with pytest.raises(ModelHubError) as ambiguous:service.get_turn_provenance("turn_ambiguous")assert ambiguous.value.code == "provenance_unavailable"- assert (- ambiguous.value.detail- == "models.provenance.attribution_ambiguous"- )+ assert ambiguous.value.detail == "models.provenance.attribution_ambiguous"with pytest.raises(ModelHubError) as unknown:service.get_turn_provenance("turn_unknown")@@ -1771,9 +2894,7 @@ def test_turn_mode_marker_is_deleted_with_its_turn_record(assert unavailable.value.detail == "models.provenance.direct_mode"with engine.begin() as conn:- conn.execute(- delete(messages).where(messages.c.id == "msg_turn_mode")- )+ conn.execute(delete(messages).where(messages.c.id == "msg_turn_mode"))with pytest.raises(ModelHubError) as deleted:service.get_turn_provenance("turn_direct")@@ -1814,17 +2935,10 @@ def test_known_opencode_turn_is_fail_closed_but_not_unknown(monkeypatch.setattr(service,"_known_turn",- lambda turn_id: (- ("opencode", None)- if turn_id == "turn_opencode"- else (None, None)- ),+ lambda turn_id: (("opencode", None) if turn_id == "turn_opencode" else (None, None)),)with pytest.raises(ModelHubError) as unavailable:service.get_turn_provenance("turn_opencode")assert unavailable.value.code == "provenance_unavailable"- assert (- unavailable.value.detail- == "models.provenance.attribution_ambiguous"- )+ assert unavailable.value.detail == "models.provenance.attribution_ambiguous"diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 8a6236687..dd0c1204b 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -1,65 +1,100 @@from __future__ import annotationsimport asyncio-import jsonfrom collections import deque-from datetime import datetime, timedelta, timezone+from datetime import datetime, timezone+from pathlib import Path+from typing import Mapping+from unittest.mock import patchimport pytestfrom config.v2_config import (- ModelHubAgentSourcesConfig,ModelHubAgentSupplyConfig,ModelHubConfig,- ModelHubMappingConfig,+ ModelHubMenuConfig,ModelHubModelConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,ModelHubSourceConfig,ModelHubSourceStateConfig,)from core.handlers.model_hub.adapter import (EngineHealth,EngineStatus,+ ObservationDiscovery,+ ObservationOutcome,RawCallOutcome,RawOutcomeKind,+ SourceObservation,)-from core.handlers.model_hub.classification import classify_outcome+from core.handlers.model_hub.events import BoundedEventLogfrom core.handlers.model_hub.errors import ModelDiscoveryError-from core.handlers.model_hub.events import BoundedEventLog, build_resolution_event-from core.handlers.model_hub.resolver import resolve_model_hub_turn+from core.handlers.model_hub.request import ModelHubRequest+from core.handlers.model_hub.resolver import allowed_origins, resolve_model_hub_turn+from core.handlers.model_hub.resolver import (+ canonical_opencode_menu_identity,+ inspect_exact_hop,+)from core.handlers.model_hub.revocations import CredentialRevocationJournal-from core.handlers.model_hub.service import ModelHubError, ModelHubService, _mask_credential-from vibe.i18n import t as i18n_t-from vibe.model_hub_runtime.client import _SAFE_ERROR_CODES-from vibe.model_hub_runtime.state import EngineStateError+from core.handlers.model_hub.service import (+ ModelHubError,+ ModelHubService,+ _await_owned_task_before_settling,+ _matching_v1_model_id,+)+from modules.agents.model_hub import ModelHubRuntimeRouterclass MemoryStore:def __init__(self, config: ModelHubConfig):self.config = config- self.fail_save = Falseself.requested_models = {"claude": "claude-opus-4-6"}def load(self) -> ModelHubConfig:return self.configdef save(self, config: ModelHubConfig) -> None:- if self.fail_save:- raise OSError("save failed")self.config = configdef requested_model(self, backend: str) -> str:return self.requested_models.get(backend, "")+class FakeInvokeHandle:+ def __init__(self, outcome: RawCallOutcome):+ self._outcome = outcome+ self.stream = None++ async def outcome(self) -> RawCallOutcome:+ return self._outcome++class FakeAdapter:- def __init__(self, outcomes):- self.outcomes = deque(outcomes)- self.invocations = []- self.synced = []- self.revoked = []- self.provisioned = []- self.fail_sync = False- self.fail_revoke = False+ def __init__(self, discovered: tuple[str, ...] = ("claude-opus-4-6",)):+ self.discovered = discovered+ self.observation: SourceObservation | None = None+ self.observation_error: BaseException | None = None+ self.discovery_error: BaseException | None = None+ self.observed_protocol_orders: list[tuple[str, ...]] = []+ self.revoked: list[str] = []+ self.revoke_error = False+ self.revoke_started: asyncio.Event | None = None+ self.revoke_block: asyncio.Event | None = None+ self.provisioned: list[str] = []+ self.retargeted: list[tuple[str, str | None, str]] = []+ self.synced: list[tuple] = []+ self.discovery_started: asyncio.Event | None = None+ self.discovery_block: asyncio.Event | None = None+ self.provision_started: asyncio.Event | None = None+ self.provision_block: asyncio.Event | None = None+ self.sync_started: asyncio.Event | None = None+ self.sync_block: asyncio.Event | None = None+ self.outcomes = deque()+ self.invocations: list[tuple[str, str]] = []+ self.invocation_requests: list[Mapping[str, object]] = []+ self.refreshable_credential_refs: set[str] = set()+ self.capability_queries: list[str] = []async def ensure_installed(self):return await self.status()@@ -71,318 +106,330 @@ class FakeAdapter:return Noneasync def status(self):- return EngineStatus(EngineHealth.OK, "v7.2.95", True, "127.0.0.1", 15220, None)+ return EngineStatus(EngineHealth.OK, "test", True, "127.0.0.1", 15220, None)async def gateway_token(self):return "local-test-token"async def provision_credential(self, vendor, protocol, secret, base_url):- self.provisioned.append((vendor, protocol, base_url))- return "cred_test"+ self.provisioned.append(secret)+ return f"cred_{len(self.provisioned):08d}"++ async def provision_transient_credential(self, vendor, secret, base_url):+ self.provisioned.append(secret)+ if self.provision_started is not None:+ self.provision_started.set()+ if self.provision_block is not None:+ await self.provision_block.wait()+ return f"cred_{len(self.provisioned):08d}"++ async def retarget_api_key_credential(+ self,+ credential_ref,+ vendor,+ protocol,+ base_url,+ ):+ replacement_ref = f"cred_retarget{len(self.retargeted) + 1:04d}"+ self.retargeted.append((credential_ref, base_url, replacement_ref))+ return replacement_refasync def revoke_credential(self, credential_ref):+ if self.revoke_error:+ raise RuntimeError("injected revoke failure")+ if self.revoke_started is not None:+ self.revoke_started.set()+ if self.revoke_block is not None:+ await self.revoke_block.wait()self.revoked.append(credential_ref)- if self.fail_revoke:- raise RuntimeError("revoke failed")- return None++ async def credential_supports_refresh(self, credential_ref):+ self.capability_queries.append(credential_ref)+ return credential_ref in self.refreshable_credential_refsasync def sync_sources(self, bindings):self.synced.append(tuple(bindings))- if self.fail_sync:- raise RuntimeError("sync failed")+ if self.sync_started is not None:+ self.sync_started.set()+ if self.sync_block is not None:+ await self.sync_block.wait()async def discover_models(self, vendor, protocol, base_url, credential_ref):- return ("claude-opus-4-6",)+ if self.discovery_started is not None:+ self.discovery_started.set()+ if self.discovery_block is not None:+ await self.discovery_block.wait()+ if self.discovery_error is not None:+ raise self.discovery_error+ return self.discovered++ async def observe_source(self, vendor, base_url, credential_ref, protocol_order):+ self.observed_protocol_orders.append(tuple(protocol_order))+ if self.discovery_started is not None:+ self.discovery_started.set()+ if self.discovery_block is not None:+ await self.discovery_block.wait()+ if self.observation_error is not None:+ raise self.observation_error+ return self.observation or SourceObservation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol=protocol_order[0],+ discovery=ObservationDiscovery.SUCCEEDED,+ model_ids=self.discovered,+ )async def invoke(self, source_id, model_id, request, stream, origin):- self.invocations.append((source_id, model_id, origin))- result = self.outcomes.popleft()- return result if isinstance(result, FakeInvokeHandle) else FakeInvokeHandle(result)+ self.invocations.append((source_id, model_id))+ self.invocation_requests.append(request)+ outcome = self.outcomes.popleft()+ return FakeInvokeHandle(outcome)+++def _source(+ source_id: str,+ model_ids: tuple[str, ...] = ("claude-opus-4-6",),+ *,+ kind: str = "api_key",+ vendor: str = "anthropic",+ channel: str = "hub",+ status: str = "standby",+ credential_ref: str | None = "cred_source",+) -> ModelHubSourceConfig:+ return ModelHubSourceConfig(+ id=source_id,+ kind=kind,+ vendor=vendor,+ display_name=source_id,+ protocol="anthropic" if vendor == "anthropic" else "openai_responses",+ supply_channel=channel,+ billing="monthly" if kind == "subscription" else "metered",+ state=ModelHubSourceStateConfig(status=status),+ models=[ModelHubModelConfig(id=item, provenance="discovered") for item in model_ids],+ credential_ref=credential_ref,+ )- async def start_oauth(self, source_id, vendor):- raise AssertionError- async def oauth_status(self, flow_id):- raise AssertionError+def _config(sources: list[ModelHubSourceConfig], *, model: str = "claude-opus-4-6") -> ModelHubConfig:+ agents = {+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")+ for backend in ("claude", "codex", "opencode")+ }+ for backend, agent in agents.items():+ eligible = [source.id for source in sources if ModelHubConfig.source_eligible_for_backend(source, backend)]+ agent.sources.order = eligible+ agents["claude"].routes[model] = ModelHubRouteConfig(+ hops=tuple(ModelHubRouteHopConfig(source.id, model) for source in sources)+ )+ return ModelHubConfig(sources=sources, agents=agents)- async def submit_oauth(self, flow_id, value):- raise AssertionError- async def cancel_oauth(self, flow_id):- raise AssertionError+def _service(tmp_path: Path, config: ModelHubConfig, adapter: FakeAdapter | None = None) -> tuple[ModelHubService, MemoryStore, FakeAdapter]:+ store = MemoryStore(config)+ adapter = adapter or FakeAdapter()+ service = ModelHubService(+ store=store,+ adapter=adapter,+ events=BoundedEventLog(tmp_path / "events.json"),+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),+ now=lambda: datetime(2026, 8, 9, tzinfo=timezone.utc),+ requested_model_override=store.requested_model,+ )+ return service, store, adapter-class FakeInvokeHandle:- def __init__(self, outcome, stream=None):- self._outcome = outcome- self._stream = stream+def test_matching_v1_claude_aliases_persist_concrete_observed_id():+ source = _source(+ "src_claudev1",+ (+ "opus",+ "claude-opus-4-6",+ "claude-opus-4-5-20251101",+ "claude-opus-4-6-20260101",+ "claude-opus-4-6-20260115",+ ),+ kind="subscription",+ channel="native_cli",+ credential_ref=None,+ )+ assert _matching_v1_model_id(backend="claude", requested_model="claude-opus-4-6", source=source) == "claude-opus-4-6-20260115"+ assert _matching_v1_model_id(backend="claude", requested_model="opus", source=source) == "claude-opus-4-6-20260115"+ assert _matching_v1_model_id(backend="claude", requested_model="claude-opus-4-6-20260101", source=source) == "claude-opus-4-6-20260101"+ assert _matching_v1_model_id(backend="claude", requested_model="claude-opus-4-6-20250101", source=source) is None- @property- def stream(self):- return self._stream- async def outcome(self):- return self._outcome+def test_matching_v1_is_literal_for_non_native_and_codex():+ source = _source("src_literal1", ("claude-opus-4-6-20260115",), vendor="anthropic")+ assert _matching_v1_model_id(backend="claude", requested_model="claude-opus-4-6", source=source) is None+ assert _matching_v1_model_id(backend="codex", requested_model="claude-opus-4-6", source=source) is None+ assert _matching_v1_model_id(backend="claude", requested_model="claude-opus-4-6-20260115", source=source) == "claude-opus-4-6-20260115"- ("secret", "expected"),- [- ("sk-test-never-persist-this", "sk-test…this"),- ("abcde", "…bcde"),- ("abcd", "…••••"),- ],-)-def test_credential_display_mask_never_exposes_the_whole_secret(secret, expected):- assert _mask_credential(secret) == expected- assert secret != expected+def test_matching_v1_opencode_bare_name_requires_unique_checked_suffix():+ source = _source("src_openv001", ("x",), vendor="custom")+ assert _matching_v1_model_id(backend="opencode", requested_model="x", source=source, checked_models=("custom/x",)) == "x"+ assert _matching_v1_model_id(backend="opencode", requested_model="x", source=source, checked_models=("a/x", "custom/x")) is None-def _outcome(kind, *, status=None, code=None, message=None, stream_started=False):- return RawCallOutcome(- kind=kind,- http_status=status,- error_code=code,- redacted_message=message,- stream_started=stream_started,- model_id="claude-opus-4-6",- source_id="src_primary01",+def test_matching_v1_never_routes_to_manual_inventory():+ source = _source("src_manual001", ("observed",), vendor="custom")+ source.models.append(ModelHubModelConfig(id="manual-target", provenance="manual"))++ assert (+ _matching_v1_model_id(+ backend="codex",+ requested_model="manual-target",+ source=source,+ )+ is None+ )+ assert (+ _matching_v1_model_id(+ backend="opencode",+ requested_model="custom/manual-target",+ source=source,+ checked_models=("custom/manual-target",),+ )+ is None)-def _source(source_id: str, display_name: str, *, billing: str = "metered") -> ModelHubSourceConfig:- return ModelHubSourceConfig(- id=source_id,- kind="api_key",- vendor="anthropic",- display_name=display_name,- protocol="anthropic",- supply_channel="hub",- billing=billing,- state=ModelHubSourceStateConfig(status="standby"),- models=[ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered")],- credential_ref=f"cred_{source_id}",+def test_runtime_opencode_resolution_never_repeats_bare_name_matching():+ source = _source("src_openv001", ("x",), vendor="custom")+ config = _config([source], model="custom/x")+ agent = config.agents["opencode"]+ agent.menu = ModelHubMenuConfig(view="featured", checked=["custom/x"])+ agent.routes["custom/x"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "x"),))+ exact = resolve_model_hub_turn(config, "opencode", "custom/x")+ bare = resolve_model_hub_turn(config, "opencode", "x")-def _service(tmp_path, adapter, *, agents=None, now=None):- sources = [- _source("src_primary01", "Primary", billing="monthly"),- _source("src_backup001", "Backup"),- ]- agents = agents or {- backend: ModelHubAgentSupplyConfig.default(backend, mode="hub") for backend in ("claude", "codex", "opencode")- }- config = ModelHubConfig(sources=sources, agents=agents)- for agent in agents.values():- agent.sources = ModelHubAgentSourcesConfig(- policy="custom",- order=[source.id for source in sources],- )- store = MemoryStore(config)- return ModelHubService(- store=store,- adapter=adapter,- events=BoundedEventLog(tmp_path / "events.json", max_entries=5),- revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),- now=now or (lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc)),- requested_model_override=lambda backend: store.requested_model(backend),+ assert exact.source is source+ assert exact.target_model == "x"+ assert bare.source is None+++def test_runtime_opencode_resolution_preserves_absent_selection():+ source = _source("src_openv002", ("x",), vendor="custom")+ config = _config([source], model="custom/x")+ agent = config.agents["opencode"]+ agent.menu = ModelHubMenuConfig(view="featured", checked=["custom/x"])+ agent.routes["custom/x"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "x"),))+ resolution = resolve_model_hub_turn(config, "opencode", "")-def _configure_referenced_manual_model(service, *, model_id: str = "retired-model"):- config = service.store.load()- config.sources[0].models.append(ModelHubModelConfig(id=model_id, provenance="manual"))- config.agents["claude"].mappings = [- ModelHubMappingConfig(- builtin_id="claude-opus-4-6",- target_model_id=model_id,- enabled=True,- )- ]- config.agents["opencode"].menu.checked = [- f"anthropic/{model_id}",- "anthropic/claude-opus-4-6",- ]- return config+ assert resolution.requested_model == ""+ assert resolution.source is None-def _serialized_config(service) -> str:- return json.dumps(- service.store.load().to_payload(),- ensure_ascii=False,- sort_keys=True,- separators=(",", ":"),+def test_hub_subscription_is_cross_backend_eligible_and_origin_unrestricted():+ source = _source(+ "src_hubsub002",+ ("shared-model",),+ kind="subscription",+ vendor="anthropic",+ channel="hub",+ )+ config = _config([source], model="shared-model")+ config.agents["codex"].routes["shared-model"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "shared-model"),)+ )+ config.agents["codex"].sources.order = [source.id]++ assert all(ModelHubConfig.source_eligible_for_backend(source, backend) for backend in ("claude", "codex", "opencode"))+ assert allowed_origins(source) == ("claude", "codex", "opencode")+ resolution = resolve_model_hub_turn(config, "codex", "shared-model")+ assert resolution.source is source+++def test_runtime_resolution_walks_persisted_route_order_only():+ first = _source("src_route001", ("requested",))+ second = _source("src_route002", ("requested",))+ config = _config([first, second], model="requested")+ config.agents["claude"].sources.order = [second.id, first.id]+ resolution = resolve_model_hub_turn(config, "claude", "requested")+ assert resolution.source is first+ assert resolution.target_model == "requested"+ assert [source.id for source in resolution.matching_sources] == [first.id, second.id]+++def test_runtime_fallback_uses_selected_hops_exact_model_id():+ first = _source("src_route004", ("upstream-first",))+ second = _source("src_route005", ("upstream-second",))+ config = _config([first, second], model="requested")+ config.agents["claude"].routes["requested"] = ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(first.id, "upstream-first"),+ ModelHubRouteHopConfig(second.id, "upstream-second"),+ )+ )++ resolution = resolve_model_hub_turn(+ config,+ "claude",+ "requested",+ unavailable_source_ids=frozenset({first.id}),)+ assert resolution.source is second+ assert resolution.target_model == "upstream-second"+ assert resolution.supply_status == "degraded"-def _assert_no_references_to(service, model_id: str) -> None:- persisted = service.store.load()- mapping_targets = {mapping.target_model_id for agent in persisted.agents.values() for mapping in agent.mappings}- menu_target_models = {- identifier.partition("/")[2]- for agent in persisted.agents.values()- if agent.menu is not None- for identifier in agent.menu.checked- }- available_models = {model.id for source in persisted.sources for model in source.models}- assert mapping_targets <= available_models- assert menu_target_models <= available_models- assert (mapping_targets | menu_target_models).isdisjoint({model_id})+def test_supply_is_degraded_when_a_later_exact_hop_is_blocked():+ first = _source("src_route020", ("requested",))+ second = _source("src_route021", ("requested",), status="cooldown")+ second.state = ModelHubSourceStateConfig(+ status="cooldown",+ retry_at="2099-01-01T00:00:00Z",+ detail_key="models.source.cooldown.rate_limited",+ )+ config = _config([first, second], model="requested")+ resolution = resolve_model_hub_turn(config, "claude", "requested")- ("outcome", "refresh_attempted", "action", "reason"),- [- (_outcome(RawOutcomeKind.SUCCESS, status=200), False, "return", None),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="invalid_parameter"), False, "surface", None),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=422, code="tool_schema_error"), False, "surface", None),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=404, code="model_not_found"), False, "surface", None),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=413, code="request_too_large"), False, "surface", None),- (- _outcome(- RawOutcomeKind.HTTP_ERROR,- status=403,- message="The requested model is not accessible",- ),- False,- "surface",- None,- ),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=401), False, "refresh", None),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=401), True, "fallback", "credential_expired"),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=401, code="invalid_request"), False, "refresh", None),- (- _outcome(RawOutcomeKind.HTTP_ERROR, status=401, code="invalid_request"),- True,- "fallback",- "credential_expired",- ),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=402), False, "fallback", "balance_exhausted"),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=429), False, "fallback", "rate_limited"),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=403, code="quota_exhausted"), False, "fallback", "quota_exhausted"),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=403), False, "fallback", "credential_revoked"),- (- _outcome(RawOutcomeKind.HTTP_ERROR, status=403, code="account_suspended"),- False,- "fallback",- "account_banned",- ),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=418), False, "fallback", "unclassified_error"),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=503), False, "fallback", "server_error"),- (_outcome(RawOutcomeKind.NETWORK_ERROR), False, "fallback", "network"),- (_outcome(RawOutcomeKind.HTTP_ERROR, status=429, stream_started=True), False, "surface", None),- ],-)-def test_error_classification_table(outcome, refresh_attempted, action, reason):- decision = classify_outcome(outcome, refresh_attempted=refresh_attempted)- assert decision.action == action- assert decision.reason == reason---def test_safe_error_code_family_is_exhaustively_classified_without_overclaim():- dispositions = {- "api_error": (500, False, "fallback", "server_error", None),- "account_banned": (403, False, "fallback", "account_banned", None),- "account_disabled": (403, False, "fallback", "account_banned", None),- "account_suspended": (403, False, "fallback", "account_banned", None),- "authentication_error": (401, False, "refresh", None, None),- "billing_error": (402, False, "fallback", "balance_exhausted", None),- "context_length_exceeded": (- 400,- False,- "surface",- None,- "upstream_request_invalid",- ),- "insufficient_quota": (- 429,- False,- "fallback",- "quota_exhausted",- None,- ),- "invalid_api_key": (401, False, "refresh", None, None),- "invalid_request_error": (- 400,- False,- "surface",- None,- "upstream_request_invalid",- ),- "model_not_found": (- 404,- False,- "surface",- None,- "upstream_request_invalid",- ),- "not_found_error": (- 404,- False,- "surface",- None,- "upstream_request_invalid",- ),- "overloaded_error": (529, False, "fallback", "server_error", None),- "permission_error": (- 403,- False,- "fallback",- "permission_denied",- None,- ),- "quota_exceeded": (- 429,- False,- "fallback",- "quota_exhausted",- None,- ),- "rate_limit_error": (429, False, "fallback", "rate_limited", None),- "rate_limit_exceeded": (429, False, "fallback", "rate_limited", None),- "request_too_large": (- 413,- False,- "surface",- None,- "upstream_request_invalid",- ),- "server_error": (500, False, "fallback", "server_error", None),- }+ assert resolution.source is first+ assert resolution.supply_status == "degraded"- assert set(dispositions) == set(_SAFE_ERROR_CODES)- for code, (- status,- refresh_attempted,- action,- reason,- error_code,- ) in dispositions.items():- decision = classify_outcome(- _outcome(RawOutcomeKind.HTTP_ERROR, status=status, code=code),- refresh_attempted=refresh_attempted,++def test_runtime_fallback_preserves_distinct_models_from_one_source(tmp_path):+ source = _source("src_route006", ("upstream-first", "upstream-second"))+ config = _config([source])+ config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(source.id, "upstream-first"),+ ModelHubRouteHopConfig(source.id, "upstream-second"),)- assert (- decision.action,- decision.reason,- decision.error_code,- ) == (action, reason, error_code), code---def test_permission_denial_falls_back_without_mutating_source_health(tmp_path):- adapter = FakeAdapter(- [- _outcome(- RawOutcomeKind.HTTP_ERROR,- status=403,- code="permission_error",+ )+ adapter = FakeAdapter()+ adapter.outcomes.extend(+ (+ RawCallOutcome(+ kind=RawOutcomeKind.HTTP_ERROR,+ http_status=403,+ error_code="permission_error",+ redacted_message=None,+ stream_started=False,+ model_id="upstream-first",+ source_id=source.id,),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ]+ RawCallOutcome(+ kind=RawOutcomeKind.SUCCESS,+ http_status=200,+ error_code=None,+ redacted_message=None,+ stream_started=False,+ model_id="upstream-second",+ source_id=source.id,+ ),+ ))- service = _service(tmp_path, adapter)+ service, _store, _ = _service(tmp_path, config, adapter)resolved = asyncio.run(service.resolve(@@ -392,169 +439,153 @@ def test_permission_denial_falls_back_without_mutating_source_health(tmp_path):))- assert resolved.source_id == "src_backup001"- assert [source.state.status for source in service.store.load().sources] == [- "standby",- "standby",+ assert adapter.invocations == [+ (source.id, "upstream-first"),+ (source.id, "upstream-second"),]- events = service.list_events(limit=10)- assert len(events) == 1- assert events[0]["kind"] == "switch"- assert events[0]["reason"] == "permission_denied"- assert events[0]["from_source"] == "src_primary01"- assert events[0]["to_source"] == "src_backup001"---def test_permission_denial_probe_does_not_block_the_source(tmp_path):- service = _service(- tmp_path,- FakeAdapter(- [- _outcome(- RawOutcomeKind.HTTP_ERROR,- status=403,- code="permission_error",- )- ]- ),- )-- result = asyncio.run(- service.probe_agent("claude", "claude-opus-4-6")+ assert resolved.model_id == "upstream-second"+++def test_runtime_skips_later_hops_after_a_source_global_failure(tmp_path):+ first = _source("src_route022", ("upstream-first", "upstream-second"))+ second = _source("src_route023", ("upstream-third",))+ config = _config([first, second])+ config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(first.id, "upstream-first"),+ ModelHubRouteHopConfig(first.id, "upstream-second"),+ ModelHubRouteHopConfig(second.id, "upstream-third"),+ ))-- assert result["reachable"] is False- assert result["error"] == "models.source.error.unclassified"- assert service.store.load().sources[0].state.status == "standby"- assert service.list_events(limit=10) == []---def test_quota_failure_cools_source_switches_and_emits_redacted_events(tmp_path):- """Scenario: MH-RES-001."""-- fake_key = "sk-live-super-secret-material"- clock = [datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc)]- adapter = FakeAdapter(- [- _outcome(- RawOutcomeKind.HTTP_ERROR,- status=429,- code="quota_exhausted",- message=f"upstream redaction failure included {fake_key}",+ adapter = FakeAdapter()+ adapter.outcomes.extend(+ (+ RawCallOutcome(+ kind=RawOutcomeKind.HTTP_ERROR,+ http_status=429,+ error_code="rate_limit_error",+ redacted_message=None,+ stream_started=False,+ model_id="upstream-first",+ source_id=first.id,),- _outcome(RawOutcomeKind.SUCCESS, status=200),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ]+ RawCallOutcome(+ kind=RawOutcomeKind.SUCCESS,+ http_status=200,+ error_code=None,+ redacted_message=None,+ stream_started=False,+ model_id="upstream-third",+ source_id=second.id,+ ),+ ))- service = _service(tmp_path, adapter, now=lambda: clock[0])+ service, _store, _ = _service(tmp_path, config, adapter)resolved = asyncio.run(service.resolve(backend="claude",model_id="claude-opus-4-6",- request={"messages": []},+ request={},))- assert resolved.source_id == "src_backup001"- assert [call[0] for call in adapter.invocations] == ["src_primary01", "src_backup001"]- assert service.store.load().sources[0].state.status == "cooldown"- persisted = (tmp_path / "events.json").read_text(encoding="utf-8")- assert fake_key not in persisted- events = service.list_events(limit=10)- assert [event["kind"] for event in events] == ["switch", "cooldown"]+ assert adapter.invocations == [+ (first.id, "upstream-first"),+ (second.id, "upstream-third"),+ ]+ assert resolved.model_id == "upstream-third"+++def test_static_api_key_401_falls_through_without_retry(tmp_path):+ first = _source(+ "src_static401a",+ credential_ref="cred_static401",+ )+ second = _source(+ "src_static401b",+ credential_ref="cred_fallback401",+ )+ config = _config([first, second])+ adapter = FakeAdapter()+ adapter.outcomes.extend(+ (+ RawCallOutcome(+ kind=RawOutcomeKind.HTTP_ERROR,+ http_status=401,+ error_code="unauthorized",+ redacted_message=None,+ stream_started=False,+ model_id="claude-opus-4-6",+ source_id=first.id,+ ),+ RawCallOutcome(+ kind=RawOutcomeKind.SUCCESS,+ http_status=200,+ error_code=None,+ redacted_message=None,+ stream_started=False,+ model_id="claude-opus-4-6",+ source_id=second.id,+ ),+ )+ )+ service, store, _ = _service(tmp_path, config, adapter)- clock[0] += timedelta(minutes=6)- recovered = asyncio.run(+ resolved = asyncio.run(service.resolve(backend="claude",model_id="claude-opus-4-6",- request={"messages": []},+ request={},))- assert recovered.source_id == "src_primary01"- assert service.store.load().sources[0].state.status == "standby"- assert service.list_events(limit=10)[0]["kind"] == "recover"--def test_event_log_failure_does_not_abort_failover(tmp_path):- class UnwritableEventLog:- def append(self, event):- raise OSError("read-only state")-- def list(self, *, limit=20, before=None):- return []-- adapter = FakeAdapter(- [- _outcome(RawOutcomeKind.HTTP_ERROR, status=429),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ]+ assert adapter.invocations == [+ (first.id, "claude-opus-4-6"),+ (second.id, "claude-opus-4-6"),+ ]+ assert adapter.capability_queries == ["cred_static401"]+ assert resolved.source_id == second.id+ persisted = next(item for item in store.load().sources if item.id == first.id)+ assert persisted.state.status == "needs_action"+ assert persisted.state.detail_key == (+ "models.source.needs_action.credential_revoked")- service = _service(tmp_path, adapter)- service.events = UnwritableEventLog()-- resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))-- assert resolved.source_id == "src_backup001"- assert service.store.load().sources[0].state.status == "cooldown"- assert [call[0] for call in adapter.invocations] == ["src_primary01", "src_backup001"]-def test_401_refreshes_exactly_once_before_returning(tmp_path):- adapter = FakeAdapter(- [- _outcome(RawOutcomeKind.HTTP_ERROR, status=401),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ]+def test_401_retry_depends_on_credential_capability_not_source_kind(tmp_path):+ source = _source(+ "src_refresh401",+ credential_ref="cred_refresh401",)- service = _service(tmp_path, adapter)-- result = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))-- assert result.source_id == "src_primary01"- assert len(adapter.invocations) == 2--- ("outcomes", "reason", "detail_key"),- [- (- [- _outcome(RawOutcomeKind.HTTP_ERROR, status=401),- _outcome(RawOutcomeKind.HTTP_ERROR, status=401),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ],- "credential_expired",- "models.source.needs_action.oauth_expired",- ),- (- [- _outcome(RawOutcomeKind.HTTP_ERROR, status=402),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ],- "balance_exhausted",- "models.source.needs_action.balance_exhausted",- ),+ config = _config([source])+ adapter = FakeAdapter()+ adapter.refreshable_credential_refs.add("cred_refresh401")+ adapter.outcomes.extend((- [- _outcome(RawOutcomeKind.HTTP_ERROR, status=418),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ],- "unclassified_error",- "models.source.error.unclassified",- ),- ],-)-def test_non_self_healing_failure_blocks_source_then_falls_back(- tmp_path,- outcomes,- reason,- detail_key,-):- service = _service(tmp_path, FakeAdapter(outcomes))+ RawCallOutcome(+ kind=RawOutcomeKind.HTTP_ERROR,+ http_status=401,+ error_code="unauthorized",+ redacted_message=None,+ stream_started=False,+ model_id="claude-opus-4-6",+ source_id=source.id,+ ),+ RawCallOutcome(+ kind=RawOutcomeKind.SUCCESS,+ http_status=200,+ error_code=None,+ redacted_message=None,+ stream_started=False,+ model_id="claude-opus-4-6",+ source_id=source.id,+ ),+ )+ )+ service, store, _ = _service(tmp_path, config, adapter)- result = asyncio.run(+ resolved = asyncio.run(service.resolve(backend="claude",model_id="claude-opus-4-6",@@ -562,1976 +593,1362 @@ def test_non_self_healing_failure_blocks_source_then_falls_back())- assert result.source_id == "src_backup001"- primary = service.store.load().sources[0]- assert primary.state.status == (- "error" if reason == "unclassified_error" else "needs_action"+ assert adapter.invocations == [+ (source.id, "claude-opus-4-6"),+ (source.id, "claude-opus-4-6"),+ ]+ assert adapter.capability_queries == ["cred_refresh401"]+ assert resolved.source_id == source.id+ assert store.load().sources[0].state.status == "standby"+++def test_runtime_filters_reasoning_effort_for_each_exact_hop(tmp_path):+ first = _source("src_effort001", ("upstream-first",))+ second = _source("src_effort002", ("upstream-second",))+ first.models[0].reasoning_efforts = ["high"]+ second.models[0].reasoning_efforts = ["low"]+ config = _config([first, second])+ config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(first.id, "upstream-first"),+ ModelHubRouteHopConfig(second.id, "upstream-second"),+ ))- assert primary.state.detail_key == detail_key- events = service.list_events(limit=10)- assert [event["kind"] for event in events] == ["switch", "needs_action"]- assert events[0]["reason"] == events[1]["reason"] == reason- assert events[0]["severity"] == "info"- assert events[1]["severity"] == "action_required"---def test_refreshed_fallback_stream_emits_switch_event(tmp_path):- async def stream_bytes():- yield b"ok"-- adapter = FakeAdapter(- [- _outcome(RawOutcomeKind.HTTP_ERROR, status=429),- _outcome(RawOutcomeKind.HTTP_ERROR, status=401),- FakeInvokeHandle(- _outcome(RawOutcomeKind.SUCCESS, status=200, stream_started=True),- stream=stream_bytes(),+ adapter = FakeAdapter()+ adapter.outcomes.extend(+ (+ RawCallOutcome(+ kind=RawOutcomeKind.HTTP_ERROR,+ http_status=403,+ error_code="permission_error",+ redacted_message=None,+ stream_started=False,+ model_id="upstream-first",+ source_id=first.id,),- ]+ RawCallOutcome(+ kind=RawOutcomeKind.SUCCESS,+ http_status=200,+ error_code=None,+ redacted_message=None,+ stream_started=False,+ model_id="upstream-second",+ source_id=second.id,+ ),+ )+ )+ service, _store, _ = _service(tmp_path, config, adapter)+ request = ModelHubRequest(+ {"reasoning": {"effort": "high"}},+ protocol="openai_responses",+ headers={"x-test": "preserved"},)- service = _service(tmp_path, adapter)- result = asyncio.run(+ resolved = asyncio.run(service.resolve(backend="claude",model_id="claude-opus-4-6",- request={},- stream=True,+ request=request,))- assert result.source_id == "src_backup001"- assert [event["kind"] for event in service.list_events(limit=10)] == ["switch", "cooldown"]-+ assert resolved.source_id == second.id+ assert adapter.invocation_requests[0]["reasoning"] == {"effort": "high"}+ assert adapter.invocation_requests[1]["reasoning"] == {"effort": None}+ assert adapter.invocation_requests[1].protocol == "openai_responses"+ assert adapter.invocation_requests[1].headers == {"x-test": "preserved"}-def test_parameter_error_and_started_stream_never_fallback(tmp_path):- for outcome in (- _outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="invalid_parameter"),- _outcome(RawOutcomeKind.HTTP_ERROR, status=404, code="model_not_found"),- _outcome(RawOutcomeKind.HTTP_ERROR, status=413, code="request_too_large"),- _outcome(RawOutcomeKind.HTTP_ERROR, status=429, stream_started=True),- ):- adapter = FakeAdapter([outcome])- service = _service(tmp_path, adapter)- with pytest.raises(ModelHubError):- asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}, stream=True))- assert len(adapter.invocations) == 1- assert service.store.load().sources[0].state.status == "standby"+def test_runtime_does_not_alias_unpersisted_claude_request():+ source = _source("src_route003", ("claude-opus-4-6-20260115",))+ config = _config([source], model="claude-opus-4-6-20260115")+ resolution = resolve_model_hub_turn(config, "claude", "claude-opus-4-6")+ assert resolution.source is None+ assert resolution.supply_status == "interrupted"-def test_mapping_is_scoped_to_the_requesting_backend(tmp_path):- """Scenario: MH-MAP-001."""- agents = {- backend: ModelHubAgentSupplyConfig.default(backend, mode="hub") for backend in ("claude", "codex", "opencode")- }- agents["claude"].mappings = [- ModelHubMappingConfig(builtin_id="claude-native", target_model_id="claude-opus-4-6", enabled=True)- ]- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter, agents=agents)+def test_resolution_marks_stale_exact_hop_unsupported():+ source = _source("src_stale001", ("other-model",))+ config = _config([source], model="stale-model")+ resolution = resolve_model_hub_turn(config, "claude", "stale-model")+ assert resolution.matching_sources == (source,)+ assert resolution.candidates == ()+ assert resolution.unsupported_source_ids == (source.id,)+ assert resolution.projectable_hops == resolution.inspected_hops- result = asyncio.run(service.resolve(backend="claude", model_id="claude-native", request={}))- assert result.model_id == "claude-opus-4-6"- assert agents["codex"].mappings == []+def test_launch_failure_reports_unsupported_exact_hop():+ source = _source("src_launch001", ("other-model",))+ config = _config([source], model="stale-model")+ resolution = resolve_model_hub_turn(config, "claude", "stale-model")+ failure = ModelHubRuntimeRouter._launch_failure(config, resolution)- ("requested_model", "discovered_models", "expected_model"),- [- (- "claude-opus-4-5",- [- "claude-opus-4-5",- "claude-opus-4-5-20250929",- "claude-opus-4-5-20251101",- ],- "claude-opus-4-5-20251101",- ),- (- "opus",- ["opus", "claude-opus-4-8-20260601", "claude-opus-5-20260724"],- "claude-opus-5-20260724",- ),- (- "opus[1m]",- ["claude-opus-4-8-20260601", "claude-opus-5-20260724"],- "claude-opus-5-20260724",- ),- (- "sonnet",- ["claude-sonnet-4-6-20260301", "claude-sonnet-5-20260720"],- "claude-sonnet-5-20260720",- ),- (- "sonnet[1m]",- ["claude-sonnet-4-6-20260301", "claude-sonnet-5-20260720"],- "claude-sonnet-5-20260720",- ),- (- "haiku",- ["claude-haiku-4-20250101", "claude-haiku-4-5-20251001"],- "claude-haiku-4-5-20251001",- ),- (- "claude-opus-4-5-20250929",- ["claude-opus-4-5-20250929", "claude-opus-4-5-20251101"],- "claude-opus-4-5-20250929",- ),- ],-)-def test_native_claude_aliases_resolve_only_to_discovered_inventory(- tmp_path,- requested_model,- discovered_models,- expected_model,-):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- config.sources[0].models = [- ModelHubModelConfig(id=model_id, provenance="discovered")- for model_id in discovered_models+ assert failure["copy_key"] == "interrupted"+ assert failure["blockers"] == [+ {+ "source": source.display_name,+ "status": source.state.status,+ "detail_key": source.state.detail_key,+ "reason": "model_unsupported",+ }]- config.sources[1].models = []- resolution = resolve_model_hub_turn(config, "claude", requested_model)- assert resolution.source is config.sources[0]- assert resolution.target_model == expected_model- assert resolution.mapping_applied is False+def test_exact_hop_inspection_is_the_single_identity_and_supply_authority():+ source = _source("src_exact001", ("upstream-model",), vendor="openai")+ config = _config([source], model="openai/menu-model")+ hop = ModelHubRouteHopConfig(source.id, "upstream-model")+ inspected = inspect_exact_hop(config, "opencode", "openai/menu-model", hop)-def test_native_aliases_do_not_blind_passthrough_or_use_manual_or_foreign_inventory(- tmp_path,-):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- relay = config.sources[0]- relay.base_url = "https://glm-relay.example.test"- relay.models = [- ModelHubModelConfig(- id="claude-opus-4-5-20251101",- provenance="discovered",- ),- ModelHubModelConfig(- id="claude-fable-5-20260701",- provenance="manual",- ),- ]- foreign = config.sources[1]- foreign.vendor = "custom"- foreign.models = [- ModelHubModelConfig(- id="claude-sonnet-5-20260720",- provenance="discovered",- )- ]+ assert inspected.identity == (+ "opencode",+ "openai/menu-model",+ source.id,+ "upstream-model",+ )+ assert inspected.menu_provider_id == "openai"+ assert inspected.menu_model_id == "menu-model"+ assert inspected.configuration_eligible is True+ assert inspected.inventory_member is True+ assert inspected.supply_eligible is True+ assert inspected.runnable is True+ assert inspected.reason is None+++def test_exact_hop_inspection_rejects_wrong_identity_and_empty_route():+ source = _source("src_exact002", ("actual-model",), vendor="openai")+ config = _config([source], model="openai/menu-model")- resolved = resolve_model_hub_turn(config, "claude", "claude-opus-4-5")- fictional = resolve_model_hub_turn(config, "claude", "claude-fable-5")- foreign_only = resolve_model_hub_turn(config, "claude", "claude-sonnet-5")+ wrong = inspect_exact_hop(+ config,+ "opencode",+ "openai/menu-model",+ ModelHubRouteHopConfig(source.id, "wrong-model"),+ )+ empty = inspect_exact_hop(config, "opencode", "openai/menu-model", None)- assert resolved.target_model == "claude-opus-4-5-20251101"- assert [source.id for source in resolved.matching_sources] == [relay.id]- assert fictional.matching_sources == ()- assert foreign_only.matching_sources == ()+ assert wrong.inventory_member is False+ assert wrong.supply_eligible is False+ assert wrong.runnable is False+ assert wrong.reason == "model_unsupported"+ assert empty.identity == ("opencode", "openai/menu-model", None, None)+ assert empty.reason == "route_unconfigured"-def test_explicit_mapping_overrides_native_alias_resolution(tmp_path):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- config.sources[0].models = [- ModelHubModelConfig(- id="claude-opus-4-5-20251101",- provenance="discovered",- ),- ModelHubModelConfig(id="glm-5.2", provenance="discovered"),- ]- config.sources[1].models = []- config.agents["claude"].mappings = [- ModelHubMappingConfig(- builtin_id="claude-opus-4-5",- target_model_id="glm-5.2",- enabled=True,+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": ["gpt-5"]}+ ))- ]+ assert exc.value.code == "mapping_target_unavailable"+ assert store.load().agents["opencode"].menu.checked == []- resolution = resolve_model_hub_turn(config, "claude", "claude-opus-4-5")- assert resolution.target_model == "glm-5.2"- assert resolution.mapping_applied is True+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": ["custom/sk-test-credential-material"],+ }+ )+ )++ assert exc.value.code == "mapping_target_unavailable"+ assert store.load().agents["opencode"].menu.checked == []-def test_wall_drawers_chain_probe_and_resolver_share_native_alias_supply_truth(- tmp_path,-):- effective_model = "claude-opus-4-5-20251101"- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources[0].models = [- ModelHubModelConfig(id=effective_model, provenance="discovered")- ]- config.sources[1].models = []- service.store.requested_models["claude"] = "claude-opus-4-5"+def test_explicit_opencode_selection_outside_menu_remains_visible(tmp_path):+ config = ModelHubConfig()+ config.agents["opencode"].mode = "hub"+ config.agents["opencode"].menu.checked = ["openai/visible-model"]+ service, store, _ = _service(tmp_path, config)+ store.requested_models["opencode"] = "custom/hidden-model"+ service.named_agents_override = lambda backend: (+ [("researcher", "custom/hidden-model")] if backend == "opencode" else []+ )- agent = service.get_agent_sources("claude")- chain = service.agent_chain("claude", "claude-opus-4-5")+ payload = service.get_agent_sources("opencode")resolution = resolve_model_hub_turn(config,- "claude",- "claude-opus-4-5",- now=service.now(),+ "opencode",+ "custom/hidden-model",)- probe = asyncio.run(service.probe_agent("claude", "claude-opus-4-5"))- # The row wall consumes model_supply. Both drawers consume the chain- # endpoint. Probe and live resolution must carry that same resolved model.- wall = next(- row- for row in agent["model_supply"]- if row["model_id"] == "claude-opus-4-5"- )- assert wall["chain_length"] == len(chain["chain"]) == 1- assert (- chain["chain"][0]["resolved_model_id"]- == resolution.target_model- == probe["model_id"]- == effective_model- )- assert chain["chain"][0]["via_mapping"] is False- assert adapter.invocations == [- ("src_primary01", effective_model, "claude")+ assert payload["selected_model_id"] == "custom/hidden-model"+ assert payload["supply_status"] == "interrupted"+ assert payload["named_agents"] == [+ {+ "name": "researcher",+ "effective_model_id": "custom/hidden-model",+ "supply_status": "interrupted",+ }]+ assert resolution.requested_model == "custom/hidden-model"+ assert resolution.route_unconfigured is True+ assert resolution.route_reason == "route_unconfigured"-def test_probe_flips_from_no_candidate_to_reachable_after_discovered_alias_arrives(- tmp_path,-):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources[0].models = []- config.sources[1].models = []-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.probe_agent("claude", "claude-opus-4-5"))- assert exc_info.value.code == "probe_no_candidate"+def test_direct_mode_rejects_chain_write_before_config_mutation(tmp_path):+ menu_model = "claude-opus-4-6"+ source = _source("src_direct01", (menu_model,))+ config = _config([source], model=menu_model)+ service, store, _ = _service(tmp_path, config)+ asyncio.run(service.set_agent_mode("claude", "direct"))+ before = store.load().to_payload()- config.sources[0].models = [- ModelHubModelConfig(- id="claude-opus-4-5-20251101",- provenance="discovered",+ with pytest.raises(ModelHubError) as exc:+ asyncio.run(+ service.set_agent_chain(+ "claude",+ menu_model,+ {"hops": []},+ ))- ]- probe = asyncio.run(service.probe_agent("claude", "claude-opus-4-5"))- assert probe["reachable"] is True- assert probe["model_id"] == "claude-opus-4-5-20251101"+ assert exc.value.code == "direct_mode"+ assert store.load().to_payload() == before@pytest.mark.parametrize(- ("outcome", "expected_kind"),+ ("backend", "hidden_model"),[- (- _outcome(RawOutcomeKind.HTTP_ERROR, status=429),- "cooldown",- ),- (- _outcome(RawOutcomeKind.HTTP_ERROR, status=403),- "needs_action",- ),+ ("claude", "claude-hidden-model"),+ ("opencode", "openai/hidden-model"),],)-def test_probe_alias_failure_events_use_requested_menu_id(+def test_chain_write_rejects_models_outside_the_current_menu(tmp_path,- outcome,- expected_kind,+ backend,+ hidden_model,):- adapter = FakeAdapter([outcome])- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources[0].models = [- ModelHubModelConfig(- id="claude-opus-4-5-20251101",- provenance="discovered",+ source = _source("src_menu0001", ("upstream-model",), vendor="openai")+ config = _config([source])+ config.agents["opencode"].menu.checked = ["openai/visible-model"]+ config.agents["opencode"].routes["openai/visible-model"] = ModelHubRouteConfig()+ service, store, _ = _service(tmp_path, config)+ before = store.load().to_payload()++ with pytest.raises(ModelHubError) as exc:+ asyncio.run(+ service.set_agent_chain(+ backend,+ hidden_model,+ {+ "hops": [+ {+ "source_id": source.id,+ "model_id": "upstream-model",+ }+ ]+ },+ ))- ]- config.sources[1].models = []- probe = asyncio.run(service.probe_agent("claude", "claude-opus-4-5"))+ assert exc.value.code == "mapping_target_unavailable"+ assert store.load().to_payload() == before+- assert probe["reachable"] is False- assert probe["model_id"] == "claude-opus-4-5-20251101"- event = next(- item- for item in service.events.list(limit=20)- if item["kind"] == expected_kind+def test_refresh_ignores_preexisting_unrelated_interruption(tmp_path):+ menu_model = "claude-opus-4-6"+ source = _source("src_refresh02", (menu_model,))+ broken = _source("src_refresh03", ("other",), status="cooldown")+ broken.state = ModelHubSourceStateConfig(+ status="cooldown",+ retry_at="2099-01-01T00:00:00Z",+ detail_key="models.source.cooldown.rate_limited",+ )+ config = _config([source, broken], model=menu_model)+ config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(broken.id, "other"),))- assert event["model_id"] == "claude-opus-4-5"+ adapter = FakeAdapter(discovered=(menu_model,))+ service, _store, _ = _service(tmp_path, config, adapter)+ result = asyncio.run(service.refresh_source(source.id))-def test_failover_uses_each_sources_effective_native_alias(tmp_path):- adapter = FakeAdapter(- [- _outcome(RawOutcomeKind.HTTP_ERROR, status=429),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ]+ assert result["removed_hops"] == []+ assert result["interrupted"] == []+++def test_engine_binding_excludes_empty_inventory(tmp_path):+ source = _source("src_empty01", (), vendor="openai")+ config = _config([source], model="requested")+ service, _store, _ = _service(tmp_path, config)++ assert service._bindings(config) == []+++def test_opencode_identity_computation_stays_in_validator_and_resolver():+ from ast import (+ Attribute,+ AsyncFunctionDef,+ FunctionDef,+ Import,+ ImportFrom,+ Module,+ Name,+ NodeVisitor,+ parse,+ walk,)- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources[0].models = [- ModelHubModelConfig(- id="claude-opus-4-5-20251101",- provenance="discovered",- )- ]- config.sources[1].models = [- ModelHubModelConfig(- id="claude-opus-4-5-20250929",- provenance="discovered",- )- ]+ from pathlib import Path- result = asyncio.run(- service.resolve(- backend="claude",- model_id="claude-opus-4-5",- request={},+ class RawIdentityCalls(NodeVisitor):+ def __init__(self):+ self.calls = []++ def visit_Call(self, node):+ symbol = (+ node.func.id+ if isinstance(node.func, Name)+ else node.func.attr+ if isinstance(node.func, Attribute)+ else None+ )+ if symbol in {+ "parse_opencode_model_id",+ "normalize_opencode_requested_model",+ "opencode_model_id",+ }:+ self.calls.append(symbol)+ self.generic_visit(node)++ def visit_Import(self, node):+ if any(+ alias.name == "core.handlers.model_hub.identifiers"+ for alias in node.names+ ):+ self.calls.append("core.handlers.model_hub.identifiers")+ self.generic_visit(node)++ def visit_ImportFrom(self, node):+ if node.module == "core.handlers.model_hub.identifiers":+ self.calls.extend(alias.name for alias in node.names)+ if node.module == "core.handlers.model_hub.resolver":+ self.calls.extend(+ alias.name+ for alias in node.names+ if alias.name == "normalize_opencode_requested_model"+ )+ self.generic_visit(node)++ root = Path(__file__).parents[1]+ config_path = root / "config/v2_config.py"+ allowed = {+ config_path,+ root / "core/handlers/model_hub/identifiers.py",+ root / "core/handlers/model_hub/resolver.py",+ }+ violations = {}+ for production_root in ("config", "core", "modules", "vibe"):+ for path in (root / production_root).rglob("*.py"):+ if path in allowed:+ continue+ visitor = RawIdentityCalls()+ visitor.visit(parse(path.read_text(encoding="utf-8")))+ if visitor.calls:+ violations[str(path.relative_to(root))] = visitor.calls+ assert violations == {}++ config_tree = parse(config_path.read_text(encoding="utf-8"))+ validator = next(+ node+ for node in config_tree.body+ if isinstance(node, FunctionDef)+ and node.name == "canonical_opencode_menu_identity"+ )+ validator_calls = RawIdentityCalls()+ validator_calls.visit(validator)+ assert set(validator_calls.calls) == {+ "STANDARD_OPENCODE_VENDOR_IDS",+ "parse_opencode_model_id",+ }+ other_config_calls = RawIdentityCalls()+ other_config_calls.visit(+ Module(+ body=[node for node in config_tree.body if node is not validator],+ type_ignores=[],))+ assert other_config_calls.calls == []- assert result.source_id == "src_backup001"- assert result.model_id == "claude-opus-4-5-20250929"- assert adapter.invocations == [- ("src_primary01", "claude-opus-4-5-20251101", "claude"),- ("src_backup001", "claude-opus-4-5-20250929", "claude"),- ]- failover_events = [- event- for event in service.events.list(limit=20)- if event["kind"] in {"cooldown", "switch"}- ]- assert {event["model_id"] for event in failover_events} == {- "claude-opus-4-5"+ shared_startup = parse(+ (root / "modules/agents/model_hub.py").read_text(encoding="utf-8")+ )+ overlay = next(+ node+ for node in walk(shared_startup)+ if isinstance(node, AsyncFunctionDef)+ and node.name == "prepare_opencode_overlay"+ )+ resolution_inputs = {+ node.attr+ for node in walk(overlay)+ if isinstance(node, Attribute)+ and isinstance(node.value, Name)+ and node.value.id == "resolution"}+ assert {"candidate_hops", "projectable_hops"} <= resolution_inputs+ assert "inspected_hops" not in resolution_inputs--def test_runtime_alias_blocker_event_uses_requested_menu_id(tmp_path):- adapter = FakeAdapter(- [- _outcome(RawOutcomeKind.HTTP_ERROR, status=403),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ]+ assert canonical_opencode_menu_identity("openai/menu-model") == (+ "openai",+ "menu-model",)- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources[0].models = [- ModelHubModelConfig(- id="claude-opus-4-5-20251101",- provenance="discovered",- )- ]- config.sources[1].models = [- ModelHubModelConfig(- id="claude-opus-4-5-20250929",- provenance="discovered",- )+++def test_agent_chain_projects_exact_hops_and_blockers(tmp_path):+ source = _source("src_chain001", ("other-model",))+ config = _config([source], model="stale-model")+ service, _, _ = _service(tmp_path, config)+ payload = service.agent_chain("claude", "stale-model")+ assert payload["chain"] == [+ {+ "source_id": source.id,+ "model_id": "stale-model",+ "channel": "hub",+ "health": "healthy",+ "runnable": False,+ "reason": "model_unsupported",+ "retry_at": None,+ }]+ assert payload["current"] is None+ assert payload["supply_state"] == "interrupted"++def test_set_agent_chain_returns_guarded_exact_route(tmp_path):+ menu_model = "claude-opus-4-6"+ first = _source("src_chain002", (menu_model,))+ second = _source("src_chain003", (menu_model,))+ config = _config([first, second], model=menu_model)+ service, store, _ = _service(tmp_path, config)result = asyncio.run(- service.resolve(- backend="claude",- model_id="claude-opus-4-5",- request={},+ service.set_agent_chain(+ "claude",+ menu_model,+ {+ "hops": [+ {"source_id": second.id, "model_id": menu_model},+ {"source_id": first.id, "model_id": menu_model},+ ],+ "force": True,+ },))+ assert result["removed_hops"] == []+ assert isinstance(result["interrupted"], list)+ assert [item["source_id"] for item in result["chain"]["chain"]] == [second.id, first.id]+ assert result["chain"]["current"] == {"source_id": second.id, "model_id": menu_model}+ assert [hop.source_id for hop in store.load().agents["claude"].routes[menu_model].hops] == [second.id, first.id]+++def test_set_agent_chain_reports_complete_removed_hops_without_syncing(tmp_path):+ menu_model = "claude-opus-4-6"+ first = _source("src_chain006", (menu_model,))+ second = _source("src_chain007", (menu_model,))+ config = _config([first, second], model=menu_model)+ service, _store, adapter = _service(tmp_path, config)- assert result.source_id == "src_backup001"- blocker = next(- event- for event in service.events.list(limit=20)- if event["kind"] == "needs_action"+ result = asyncio.run(+ service.set_agent_chain(+ "claude",+ menu_model,+ {+ "hops": [{"source_id": first.id, "model_id": menu_model}],+ "force": True,+ },+ ))- assert blocker["model_id"] == "claude-opus-4-5"++ assert result["removed_hops"] == [+ {+ "backend": "claude",+ "menu_model": menu_model,+ "source_id": second.id,+ "model_id": menu_model,+ }+ ]+ assert adapter.synced == []-def test_opencode_provider_prefix_selects_matching_source(tmp_path):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources[0].vendor = "custom"- config.sources[0].state = ModelHubSourceStateConfig(+def test_set_agent_chain_ignores_unrelated_existing_gap(tmp_path):+ menu_model = "claude-opus-4-6"+ first = _source("src_chain008", (menu_model,))+ second = _source("src_chain009", (menu_model,))+ broken = _source(+ "src_chain010",+ ("other",),+ status="cooldown",+ )+ broken.state = ModelHubSourceStateConfig(status="cooldown",- retry_at="2026-07-23T02:59:00Z",+ retry_at="2099-01-01T00:00:00Z",+ detail_key="models.source.cooldown.rate_limited",)- config.sources[1].vendor = "anthropic"- config.agents["opencode"].menu.checked = ["anthropic/claude-opus-4-6"]+ config = _config([first, second, broken], model=menu_model)+ config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(broken.id, "other"),)+ )+ service, store, adapter = _service(tmp_path, config)- chain = service.agent_chain("opencode", "anthropic/claude-opus-4-6")- resolved = asyncio.run(- service.resolve(- backend="opencode",- model_id="anthropic/claude-opus-4-6",- request={},+ result = asyncio.run(+ service.set_agent_chain(+ "claude",+ menu_model,+ {+ "hops": [+ {"source_id": second.id, "model_id": menu_model},+ {"source_id": first.id, "model_id": menu_model},+ ]+ },))- assert chain["chain"][0]["source_id"] == "src_backup001"- assert resolved.source_id == "src_backup001"- assert adapter.invocations == [("src_backup001", "claude-opus-4-6", "opencode")]- assert service.list_events(limit=10) == []- assert config.sources[0].state.status == "cooldown"+ assert result["interrupted"] == []+ assert adapter.synced == []+ assert [hop.source_id for hop in store.load().agents["claude"].routes[menu_model].hops] == [second.id, first.id]-def test_opencode_agent_supply_distinguishes_explicit_pin_from_resolver_pick(tmp_path):- service = _service(tmp_path, FakeAdapter([]))- service.store.load().agents["opencode"].menu.checked = [- "anthropic/claude-opus-4-6"- ]+def test_source_creation_cancellation_revokes_unsaved_credential(tmp_path):+ adapter = FakeAdapter()+ adapter.discovery_started = asyncio.Event()+ adapter.discovery_block = asyncio.Event()+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)- resolver_picked = service.get_agent_sources("opencode")+ async def scenario():+ task = asyncio.create_task(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Key",+ "key": "sk-test-cancel-credential",+ }+ )+ )+ await adapter.discovery_started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task- assert resolver_picked["selected_model_id"] == "anthropic/claude-opus-4-6"- assert resolver_picked["selected_model_explicit"] is False+ asyncio.run(scenario())+ assert len(store.load().sources) == 0+ assert adapter.revoked == ["cred_00000001"]- service.requested_model_override = lambda backend: (- "anthropic/claude-opus-4-6" if backend == "opencode" else None- )- explicit_pin = service.get_agent_sources("opencode")- assert explicit_pin["selected_model_id"] == "anthropic/claude-opus-4-6"- assert explicit_pin["selected_model_explicit"] is True+def test_source_creation_cancellation_during_provision_revokes_owned_credential(tmp_path):+ adapter = FakeAdapter()+ adapter.provision_started = asyncio.Event()+ adapter.provision_block = asyncio.Event()+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)+ async def scenario():+ task = asyncio.create_task(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Key",+ "key": "sk-test-provision-cancel",+ }+ )+ )+ await adapter.provision_started.wait()+ task.cancel()+ adapter.provision_block.set()+ with pytest.raises(asyncio.CancelledError):+ await task++ asyncio.run(scenario())+ assert store.load().sources == []+ assert adapter.revoked == ["cred_00000001"]+ assert service.revocations.list() == []- ("requested_model", "expected_model", "expected_explicit"),- [- ("claude-opus-4-6", "claude-opus-4-6", True),- ("", None, False),- ],-)-def test_fixed_menu_agent_supply_marks_only_configured_selection_explicit(- tmp_path,- requested_model,- expected_model,- expected_explicit,-):- service = _service(tmp_path, FakeAdapter([]))- service.store.requested_models["claude"] = requested_model- agent = service.get_agent_sources("claude")+def test_cancelled_owned_task_is_terminal_without_settlement_retry() -> None:+ async def scenario() -> None:+ async def cancelled_operation() -> None:+ raise asyncio.CancelledError- assert agent["selected_model_id"] == expected_model- assert agent["selected_model_explicit"] is expected_explicit+ task = asyncio.create_task(cancelled_operation())+ await asyncio.sleep(0)+ assert task.cancelled()+ with patch("core.handlers.model_hub.service.asyncio.shield") as shield:+ with pytest.raises(asyncio.CancelledError):+ await _await_owned_task_before_settling(task)+ shield.assert_not_called()+ asyncio.run(scenario())-def test_opencode_unknown_vendor_uses_custom_provider_identifier(tmp_path):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources[0].vendor = "relaycorp"- config.agents["opencode"].menu.checked = ["custom/claude-opus-4-6"]- menu = asyncio.run(service.set_opencode_menu(config.agents["opencode"].menu.to_payload()))- chain = service.agent_chain("opencode", "custom/claude-opus-4-6")- resolved = asyncio.run(- service.resolve(- backend="opencode",- model_id="custom/claude-opus-4-6",- request={},+def test_source_creation_cancellation_after_persist_keeps_source_and_credential(tmp_path):+ adapter = FakeAdapter()+ adapter.sync_started = asyncio.Event()+ adapter.sync_block = asyncio.Event()+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)++ async def scenario():+ task = asyncio.create_task(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Key",+ "key": "sk-test-late-cancel",+ }+ ))- )+ await adapter.sync_started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task- assert menu["menu"]["checked"] == ["custom/claude-opus-4-6"]- assert chain["chain"][0]["source_id"] == "src_primary01"- assert resolved.source_id == "src_primary01"+ asyncio.run(scenario())+ assert len(store.load().sources) == 1+ assert store.load().sources[0].credential_ref == "cred_00000002"+ assert adapter.revoked == ["cred_00000001"]-def test_agent_supply_eligibility_is_complete_chain_and_process_inventory(- tmp_path,-):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- native = config.sources[0]- native.kind = "subscription"- native.vendor = "anthropic"- native.supply_channel = "native_cli"- native.credential_ref = None- outside_chain = _source("src_outside01", "Outside current chain")- outside_chain.models = [- ModelHubModelConfig(id="other-model", provenance="discovered")- ]- config.sources.append(outside_chain)- service.native_source_ready = (- lambda _backend, source: source.id != native.id+def test_create_source_persists_only_the_response_proven_protocol(tmp_path):+ adapter = FakeAdapter(discovered=("gpt-5.6",))+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)++ result = asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "openai",+ "display_name": "Observed key",+ "key": "sk-test-response-proof",+ "protocol_order": [+ "openai_responses",+ "anthropic",+ "openai_chat",+ ],+ }+ ))- agent = service.get_agent_sources("claude")- eligibility = {- row["source_id"]: row- for row in agent["sources"]["eligibility"]- }+ assert adapter.observed_protocol_orders == [+ ("openai_responses", "anthropic", "openai_chat")+ ]+ assert result["source"]["protocol"] == "openai_responses"+ assert store.load().sources[0].protocol == "openai_responses"+ assert adapter.revoked == ["cred_00000001"]- assert set(eligibility) == {source.id for source in config.sources}- assert eligibility[native.id] == {- "source_id": native.id,- "eligible": True,- "reason_key": None,- "in_current_model_chain": True,- "process_availability_reason": "native_cli_unavailable",- }- assert eligibility["src_backup001"]["in_current_model_chain"] is True- assert eligibility[outside_chain.id]["in_current_model_chain"] is False- assert (- eligibility[outside_chain.id]["process_availability_reason"]- is None++def test_create_source_normalizes_vendor_before_matching_v1_placement(tmp_path):+ config = ModelHubConfig()+ opencode = config.agents["opencode"]+ opencode.mode = "hub"+ assert opencode.menu is not None+ opencode.menu.checked = ["openai/gpt-5.6"]+ opencode.routes["openai/gpt-5.6"] = ModelHubRouteConfig()+ adapter = FakeAdapter(discovered=("gpt-5.6",))+ service, store, _ = _service(tmp_path, config, adapter)++ result = asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "OpenAI",+ "display_name": "Observed key",+ "key": "sk-test-vendor-normalization",+ "protocol_order": [+ "openai_responses",+ "openai_chat",+ "anthropic",+ ],+ }+ ))- service.store.requested_models["claude"] = ""- unselected = service.get_agent_sources("claude")- assert unselected["selected_model_id"] is None- assert all(- row["in_current_model_chain"] is None- for row in unselected["sources"]["eligibility"]+ assert result["source"]["vendor"] == "openai"+ assert store.load().sources[0].vendor == "openai"+ assert any(+ position["backend"] == "opencode"+ and position["menu_model"] == "openai/gpt-5.6"+ and position["model_id"] == "gpt-5.6"+ for position in result["added_to"])- assert next(- row- for row in unselected["sources"]["eligibility"]- if row["source_id"] == native.id- )["process_availability_reason"] == "native_cli_unavailable"-def test_opencode_resolution_rejects_models_outside_checked_menu(tmp_path):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter)- service.store.load().agents["opencode"].menu.checked = []+def test_ambiguous_observation_never_creates_a_source(tmp_path):+ adapter = FakeAdapter()+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.AMBIGUOUS,+ reachable=True,+ authenticated=True,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)- with pytest.raises(ModelHubError) as exc_info:+ with pytest.raises(ModelHubError) as exc:asyncio.run(- service.resolve(- backend="opencode",- model_id="anthropic/claude-opus-4-6",- request={},+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "custom",+ "display_name": "Ambiguous key",+ "key": "sk-test-ambiguous",+ }))- assert exc_info.value.code == "mapping_target_unavailable"- assert adapter.invocations == []-+ assert exc.value.data["observation"]["outcome"] == "ambiguous"+ assert store.load().sources == []+ assert adapter.revoked == ["cred_00000001"]-def test_persisted_hub_sources_sync_before_first_resolution(tmp_path):- class RegistrationRequiredAdapter(FakeAdapter):- def __init__(self):- super().__init__([_outcome(RawOutcomeKind.SUCCESS, status=200)])- self.registered = set()-- async def sync_sources(self, bindings):- await super().sync_sources(bindings)- self.registered = {binding.source_id for binding in bindings}- async def invoke(self, source_id, model_id, request, stream, origin):- assert source_id in self.registered- return await super().invoke(source_id, model_id, request, stream, origin)-- adapter = RegistrationRequiredAdapter()- service = _service(tmp_path, adapter)+def test_authentication_failure_observation_never_creates_a_source(tmp_path):+ adapter = FakeAdapter()+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.AUTHENTICATION_FAILED,+ reachable=True,+ authenticated=False,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)- resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))+ with pytest.raises(ModelHubError) as exc:+ asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Rejected key",+ "key": "sk-test-auth-rejected",+ }+ )+ )- assert resolved.source_id == "src_primary01"- assert [binding.source_id for binding in adapter.synced[0]] == [- "src_primary01",- "src_backup001",- ]+ assert exc.value.data["observation"]["outcome"] == "authentication_failed"+ assert store.load().sources == []+ assert adapter.revoked == ["cred_00000001"]@pytest.mark.parametrize(- ("first_state", "second_state", "expected_status", "expected_source"),+ ("adapter_result", "expected_outcome"),[(- ModelHubSourceStateConfig(status="standby"),- ModelHubSourceStateConfig(status="standby"),- "ok",- "src_primary01",- ),- (- ModelHubSourceStateConfig(- status="cooldown",- retry_at="2026-07-23T03:05:00Z",- ),- ModelHubSourceStateConfig(status="standby"),- "degraded",- "src_backup001",- ),- (- ModelHubSourceStateConfig(- status="cooldown",- retry_at="2026-07-23T03:05:00Z",- ),- ModelHubSourceStateConfig(- status="cooldown",- retry_at="2026-07-23T03:06:00Z",- ),- "waiting",- None,- ),- (- ModelHubSourceStateConfig(- status="cooldown",- retry_at="2026-07-23T03:05:00Z",+ SourceObservation(+ outcome=ObservationOutcome.AUTHENTICATION_FAILED,+ reachable=True,+ authenticated=False,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),),- ModelHubSourceStateConfig(- status="needs_action",- detail_key="models.source.needs_action.credential_revoked",- ),- "interrupted",- None,+ ObservationOutcome.AUTHENTICATION_FAILED,),+ (RuntimeError("injected adapter failure"), ObservationOutcome.ADAPTER_ERROR),+ (asyncio.TimeoutError(), ObservationOutcome.TIMEOUT),],)-def test_supply_status_is_derived_from_blocker_causes(+def test_unsaved_observation_terminal_paths_revoke_before_settling(tmp_path,- first_state,- second_state,- expected_status,- expected_source,+ adapter_result,+ expected_outcome,):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- config.sources[0].state = first_state- config.sources[1].state = second_state+ adapter = FakeAdapter()+ if isinstance(adapter_result, SourceObservation):+ adapter.observation = adapter_result+ else:+ adapter.observation_error = adapter_result+ service, _, _ = _service(tmp_path, ModelHubConfig(), adapter)- resolution = resolve_model_hub_turn(- config,- "claude",- "claude-opus-4-6",- now=datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),+ result = asyncio.run(+ service.observe_source(+ {+ "vendor": "anthropic",+ "base_url": None,+ "key": "sk-test-terminal-cleanup",+ }+ ))- assert resolution.supply_status == expected_status- assert (resolution.source.id if resolution.source is not None else None) == expected_source+ assert result["observation"]["outcome"] == expected_outcome.value+ assert adapter.revoked == ["cred_00000001"]-def test_empty_enabled_subset_is_structurally_interrupted(tmp_path):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- config.agents["claude"].sources.order = []-- resolution = resolve_model_hub_turn(- config,- "claude",- "claude-opus-4-6",- now=datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),+def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):+ adapter = FakeAdapter()+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.ADAPTER_ERROR,+ reachable=True,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),)+ service, _, _ = _service(tmp_path, ModelHubConfig(), adapter)- assert resolution.matching_sources == ()- assert resolution.supply_status == "interrupted"- assert resolution.source is None---def test_native_source_is_dispatched_before_hub_and_cooldown_falls_through(tmp_path):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter)- native = service.store.load().sources[0]- native.kind = "subscription"- native.supply_channel = "native_cli"-- resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))-- assert resolved.source_id == "src_primary01"- assert resolved.supply_channel == "native_cli"- assert resolved.handle is None- assert adapter.invocations == []-- native.state = ModelHubSourceStateConfig(- status="cooldown",- retry_at="2026-07-23T03:05:00Z",+ result = asyncio.run(+ service.observe_source(+ {+ "vendor": "custom",+ "base_url": "https://relay.example/v1",+ "key": "sk-test-reachable-adapter-error",+ }+ ))- fallback = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))- assert fallback.source_id == "src_backup001"- assert fallback.supply_channel == "hub"- assert adapter.invocations == [("src_backup001", "claude-opus-4-6", "claude")]---def test_native_dispatch_attempts_pending_credential_revoke(tmp_path):- adapter = FakeAdapter([])- service = _service(tmp_path, adapter)- native = service.store.load().sources[0]- native.kind = "subscription"- native.supply_channel = "native_cli"- native.credential_ref = None- service.revocations.add("src_deleted", "cred_deleted")-- resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))-- assert resolved.source_id == "src_primary01"- assert resolved.supply_channel == "native_cli"- assert adapter.revoked == ["cred_deleted"]- assert service.revocations.list() == []- assert adapter.invocations == []+ assert result["observation"] == {+ "contract_version": 5,+ "outcome": "adapter_error",+ "reachable": True,+ "authenticated": "unknown",+ "protocol": None,+ "discovery": "not_attempted",+ "models": [],+ }-def test_pending_revoke_clears_when_credential_is_already_absent(tmp_path):- class AlreadyRevokedAdapter(FakeAdapter):- async def revoke_credential(self, credential_ref):- self.revoked.append(credential_ref)- raise EngineStateError("credential is unavailable")+def test_observation_terminal_legality_has_no_service_or_runtime_copy():+ from ast import AsyncFunctionDef, Attribute, Call, FunctionDef, Name, parse, walk+ from pathlib import Path- adapter = AlreadyRevokedAdapter(- [_outcome(RawOutcomeKind.SUCCESS, status=200)]+ root = Path(__file__).parents[1]+ service_tree = parse(+ (root / "core/handlers/model_hub/service.py").read_text(encoding="utf-8"))- service = _service(tmp_path, adapter)- service.revocations.add("src_deleted", "cred_deleted")-- resolved = asyncio.run(- service.resolve(- backend="claude",- model_id="claude-opus-4-6",- request={},- )+ runtime_tree = parse(+ (root / "vibe/model_hub_runtime/adapter.py").read_text(encoding="utf-8"))- assert resolved.source_id == "src_primary01"- assert adapter.revoked == ["cred_deleted"]- assert service.revocations.list() == []---def test_pending_revoke_failure_does_not_block_hub_routing(tmp_path):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- adapter.fail_revoke = True- service = _service(tmp_path, adapter)- service.revocations.add("src_deleted", "cred_deleted")+ def calls(function) -> set[str]:+ return {+ node.func.id if isinstance(node.func, Name) else node.func.attr+ for node in walk(function)+ if isinstance(node, Call) and isinstance(node.func, (Name, Attribute))+ }- resolved = asyncio.run(- service.resolve(- backend="claude",- model_id="claude-opus-4-6",- request={},- )+ validator = next(+ node+ for node in walk(service_tree)+ if isinstance(node, FunctionDef) and node.name == "_validate_observation"+ )+ producer = next(+ node+ for node in walk(runtime_tree)+ if isinstance(node, AsyncFunctionDef) and node.name == "observe_source"+ )+ assert "validate_source_observation" in calls(validator)+ assert "make_source_observation" in calls(producer)+ assert "SourceObservation" not in calls(producer)+ assert not any(+ isinstance(node, Attribute)+ and isinstance(node.value, Name)+ and node.value.id == "ObservationOutcome"+ for node in walk(validator))- assert resolved.source_id == "src_primary01"- assert adapter.revoked == ["cred_deleted"]- assert service.revocations.list()[0].credential_ref == "cred_deleted"- assert adapter.invocations == [- ("src_primary01", "claude-opus-4-6", "claude")- ]---def test_direct_mode_never_enters_hub_resolution(tmp_path):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter)- service.store.load().agents["claude"].mode = "direct"- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))+def test_unsaved_observation_cancellation_revokes_before_settling(tmp_path):+ adapter = FakeAdapter()+ adapter.discovery_started = asyncio.Event()+ adapter.discovery_block = asyncio.Event()+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)- assert exc_info.value.code == "mode_switch_blocked"- assert adapter.invocations == []+ async def scenario():+ task = asyncio.create_task(+ service.observe_source(+ {+ "vendor": "anthropic",+ "base_url": None,+ "key": "sk-test-observation-cancel",+ }+ )+ )+ await adapter.discovery_started.wait()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ asyncio.run(scenario())+ assert store.load().sources == []+ assert adapter.revoked == ["cred_00000001"]+ assert service.revocations.list() == []-def test_source_creation_persists_before_engine_sync(tmp_path):- order = []+def test_unsaved_observation_cancellation_during_cleanup_waits_then_raises(tmp_path):+ adapter = FakeAdapter()+ adapter.revoke_started = asyncio.Event()+ adapter.revoke_block = asyncio.Event()+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)- class OrderingAdapter(FakeAdapter):- async def sync_sources(self, bindings):- order.append("sync")- assert len(service.store.load().sources) == 3- await super().sync_sources(bindings)+ async def scenario():+ task = asyncio.create_task(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "anthropic",+ "display_name": "Key",+ "key": "sk-test-cleanup-cancel",+ }+ )+ )+ await adapter.revoke_started.wait()+ task.cancel()+ await asyncio.sleep(0)+ assert not task.done()+ adapter.revoke_block.set()+ with pytest.raises(asyncio.CancelledError):+ await task++ asyncio.run(scenario())+ assert store.load().sources == []+ assert adapter.revoked == ["cred_00000001"]+ assert service.revocations.list() == []- adapter = OrderingAdapter([])- service = _service(tmp_path, adapter)- save = service.store.save- def record_save(config):- save(config)- order.append("persist")+def test_unsaved_observation_revoke_failure_is_journaled_and_reconciled(tmp_path):+ adapter = FakeAdapter()+ adapter.revoke_error = True+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)- service.store.save = record_save- created = asyncio.run(- service.create_source(+ result = asyncio.run(+ service.observe_source({- "kind": "api_key","vendor": "anthropic",- "display_name": "Ordered source",- "key": "sk-test-transient-only",+ "base_url": None,+ "key": "sk-test-observation-revoke",}))+ assert result["observation"]["protocol"] == "anthropic"+ assert "credential_ref" not in result["observation"]+ pending = service.revocations.list()+ assert len(pending) == 1+ assert pending[0].credential_ref == "cred_00000001"- assert order == ["persist", "sync"]- assert service.store.load().sources[-1].id == created["source"]["id"]---def test_source_creation_revokes_credential_when_persist_fails(tmp_path):- adapter = FakeAdapter([])- service = _service(tmp_path, adapter)- original_ids = [source.id for source in service.store.load().sources]- service.store.fail_save = True+ adapter.revoke_error = False+ repaired, _, _ = _service(tmp_path, store.load(), adapter)+ asyncio.run(repaired._ensure_engine_synced())+ assert repaired.revocations.list() == []+ assert adapter.revoked == ["cred_00000001"]- with pytest.raises(OSError, match="save failed"):- asyncio.run(- service.create_source(- {- "kind": "api_key",- "vendor": "anthropic",- "display_name": "Unpersisted source",- "key": "sk-test-transient-only",- }- )- )- assert [source.id for source in service.store.load().sources] == original_ids- assert adapter.synced == []- assert adapter.revoked == ["cred_test"]- assert service.revocations.list() == []+def test_unsaved_observation_fails_when_cleanup_is_not_durable(tmp_path):+ adapter = FakeAdapter()+ adapter.revoke_error = True+ service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)+ def fail_journal_write(*_args, **_kwargs):+ raise OSError("journal is unavailable")-def test_source_creation_is_not_persisted_when_engine_sync_fails(tmp_path):- adapter = FakeAdapter([])- adapter.fail_sync = True- service = _service(tmp_path, adapter)- for source in service.store.load().sources:- source.credential_ref = f"cred_{source.id}"- original_ids = [source.id for source in service.store.load().sources]+ service.revocations.add = fail_journal_writewith pytest.raises(ModelHubError) as exc_info:asyncio.run(- service.create_source(+ service.observe_source({- "kind": "api_key","vendor": "anthropic",- "display_name": "Uncommitted",- "key": "sk-test-transaction-only",+ "base_url": None,+ "key": "sk-test-observation-cleanup-failure",}))assert exc_info.value.code == "engine_down"- assert exc_info.value.__cause__ is None- assert exc_info.value.__suppress_context__ is True- assert [source.id for source in service.store.load().sources] == original_ids- assert adapter.revoked == ["cred_test"]+ assert store.load().sources == []+ assert service.revocations.list() == []-def test_failed_create_rollback_is_journaled_until_revoke_recovers(tmp_path):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- adapter.fail_sync = True- adapter.fail_revoke = True- service = _service(tmp_path, adapter)+def test_credential_cleanup_settlement_has_one_durable_boundary():+ from ast import AsyncFunctionDef, Attribute, Call, parse, walk+ from pathlib import Path- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.create_source(- {- "kind": "api_key",- "vendor": "anthropic",- "display_name": "Rollback source",- "key": "sk-test-transaction-only",- }- )- )-- assert exc_info.value.code == "engine_down"- pending = service.revocations.list()- assert len(pending) == 1- assert pending[0].credential_ref == "cred_test"-- adapter.fail_sync = False- adapter.fail_revoke = False- resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))-- assert resolved.source_id == "src_primary01"- assert adapter.revoked == ["cred_test", "cred_test"]- assert service.revocations.list() == []---def test_failed_create_rollback_attempts_revoke_when_journal_add_fails(tmp_path):- adapter = FakeAdapter([])- adapter.fail_sync = True- service = _service(tmp_path, adapter)-- def fail_journal_add(source_id, credential_ref):- raise OSError("journal write failed")-- service.revocations.add = fail_journal_add-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.create_source(- {- "kind": "api_key",- "vendor": "anthropic",- "display_name": "Rollback source",- "key": "sk-test-transaction-only",- }- )+ tree = parse(+ (Path(__file__).parents[1] / "core/handlers/model_hub/service.py").read_text(+ encoding="utf-8")-- assert exc_info.value.code == "engine_down"- assert adapter.revoked == ["cred_test"]- assert service.revocations.list() == []---def test_empty_discovery_rejects_source_creation_and_revokes_credential(tmp_path):- adapter = FakeAdapter([])- service = _service(tmp_path, adapter)- before = _serialized_config(service)-- async def empty_discovery(vendor, protocol, base_url, credential_ref):- return ()-- adapter.discover_models = empty_discovery-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.create_source(- {- "kind": "api_key",- "vendor": "anthropic",- "display_name": "Empty source",- "key": "sk-test-empty-discovery",- }- )+ )+ raw_cleanup_callers = {+ function.name+ for function in walk(tree)+ if isinstance(function, AsyncFunctionDef)+ and any(+ isinstance(node, Call)+ and isinstance(node.func, Attribute)+ and node.func.attr == "_rollback_credential"+ for node in walk(function))+ }- assert exc_info.value.code == "discovery_failed"- assert _serialized_config(service) == before- assert adapter.revoked == ["cred_test"]+ assert raw_cleanup_callers == {"_require_credential_cleanup"}-def test_subscription_source_rejects_api_key_credentials(tmp_path):- adapter = FakeAdapter([])- service = _service(tmp_path, adapter)+def test_every_persisting_source_path_requires_response_backed_protocol_evidence():+ from ast import AsyncFunctionDef, Attribute, Call, Name, parse, walk+ from pathlib import Path- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.create_source(- {- "kind": "subscription",- "vendor": "anthropic",- "display_name": "Invalid subscription",- "key": "sk-test-must-not-be-provisioned",- }- )+ root = Path(__file__).parents[1]+ production_trees = [+ parse(path.read_text(encoding="utf-8"), filename=str(path))+ for directory in ("config", "core", "modules", "vibe")+ for path in (root / directory).rglob("*.py")+ ]+ assert not any(+ (+ isinstance(node, Name)+ and node.id == "_default_protocol")-- assert exc_info.value.code == "discovery_failed"- assert adapter.provisioned == []---def test_source_delete_does_not_revoke_when_config_save_fails(tmp_path):- adapter = FakeAdapter([])- service = _service(tmp_path, adapter)- service.store.load().sources[0].credential_ref = "cred_primary"- service.store.load().sources[1].credential_ref = "cred_backup"- service.store.fail_save = True-- with pytest.raises(OSError, match="save failed"):- asyncio.run(service.delete_source("src_primary01", force=True))-- assert adapter.revoked == []- assert [source.id for source in service.store.load().sources] == ["src_primary01", "src_backup001"]--[email protected](("force", "mode"), [(False, "direct"), (True, "hub")])-def test_source_delete_cascades_agent_model_references(tmp_path, force, mode):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter)- config = _configure_referenced_manual_model(service)- config.agents["claude"].mode = mode- config.agents["opencode"].mode = mode-- asyncio.run(service.delete_source("src_primary01", force=force))-- persisted = service.store.load()- assert [source.id for source in persisted.sources] == ["src_backup001"]- assert all(agent.sources.order == ["src_backup001"] for agent in persisted.agents.values())- _assert_no_references_to(service, "retired-model")- if force:- claude_chain = service.agent_chain("claude", "claude-opus-4-6")- opencode_chain = service.agent_chain("opencode", "anthropic/claude-opus-4-6")- assert claude_chain["chain"][0]["source_id"] == "src_backup001"- assert opencode_chain["chain"][0]["source_id"] == "src_backup001"- resolved = asyncio.run(- service.resolve(- backend="claude",- model_id="claude-opus-4-6",- request={},- )+ or (+ isinstance(node, Attribute)+ and node.attr == "_default_protocol")- assert resolved.source_id == claude_chain["chain"][0]["source_id"]---def test_deleting_last_hub_source_syncs_empty_binding_set(tmp_path):- adapter = FakeAdapter([])- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources = [config.sources[0]]- for agent in config.agents.values():- agent.sources.order = [config.sources[0].id]-- asyncio.run(service.delete_source("src_primary01", force=True))-- assert adapter.synced == [()]- assert adapter.revoked == ["cred_src_primary01"]- assert service.store.load().sources == []---def test_source_reference_survives_failed_credential_revoke(tmp_path):- adapter = FakeAdapter([])- service = _service(tmp_path, adapter)- config = _configure_referenced_manual_model(service)- config.sources[0].credential_ref = "cred_primary"- config.sources[1].credential_ref = "cred_backup"- before = _serialized_config(service)- adapter.fail_revoke = True-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.delete_source("src_primary01", force=True))-- assert exc_info.value.code == "engine_down"- assert _serialized_config(service) == before- assert [source.id for source in service.store.load().sources] == ["src_primary01", "src_backup001"]- assert service.store.load().agents["claude"].mappings[0].target_model_id == "retired-model"- assert service.store.load().agents["opencode"].menu.checked[0] == "anthropic/retired-model"- assert [tuple(binding.source_id for binding in batch) for batch in adapter.synced] == [- ("src_backup001",),- ("src_primary01", "src_backup001"),- ]---def test_restart_replays_credential_revoke_after_delete_commit(tmp_path):- class SimulatedProcessExit(BaseException):- pass-- class CrashingAdapter(FakeAdapter):- async def revoke_credential(self, credential_ref):- raise SimulatedProcessExit-- journal = CredentialRevocationJournal(tmp_path / "revocations.json")- crashing = CrashingAdapter([])- service = _service(tmp_path, crashing)- service.revocations = journal- native = service.store.load().sources[1]- native.kind = "subscription"- native.supply_channel = "native_cli"- native.credential_ref = None- service.store.load().agents["codex"].sources.order = ["src_primary01"]- service.store.load().agents["opencode"].sources.order = ["src_primary01"]-- with pytest.raises(SimulatedProcessExit):- asyncio.run(service.delete_source("src_primary01", force=True))-- assert [source.id for source in service.store.load().sources] == ["src_backup001"]- assert journal.list()[0].credential_ref == "cred_src_primary01"-- recovered = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- restarted = ModelHubService(- store=service.store,- adapter=recovered,- events=BoundedEventLog(tmp_path / "restarted-events.json"),- revocations=journal,- now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),+ for tree in production_trees+ for node in walk(tree))- resolved = asyncio.run(restarted.resolve(backend="claude", model_id="claude-opus-4-6", request={}))-- assert resolved.source_id == "src_backup001"- assert resolved.supply_channel == "native_cli"- assert recovered.synced == [()]- assert recovered.revoked == ["cred_src_primary01"]- assert journal.list() == []---def test_selected_custom_model_cannot_be_deleted(tmp_path):- adapter = FakeAdapter([])- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources[0].models.append(ModelHubModelConfig(id="manual-model", provenance="manual"))- config.agents["opencode"].menu.checked = ["anthropic/manual-model"]-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.delete_custom_model("src_primary01", "manual-model"))-- assert exc_info.value.code == "mode_switch_blocked"- assert any(model.id == "manual-model" for model in service.store.load().sources[0].models)---def test_custom_model_delete_cascades_agent_model_references(tmp_path):- service = _service(tmp_path, FakeAdapter([]))- config = _configure_referenced_manual_model(service)- config.agents["claude"].mode = "direct"- config.agents["opencode"].mode = "direct"-- asyncio.run(service.delete_custom_model("src_primary01", "retired-model"))-- persisted = service.store.load()- assert all(model.id != "retired-model" for model in persisted.sources[0].models)- _assert_no_references_to(service, "retired-model")- assert persisted.agents["claude"].mappings == []- assert persisted.agents["opencode"].menu.checked == ["anthropic/claude-opus-4-6"]--[email protected]("operation", ["source", "custom_model"])-def test_delete_commit_failure_restores_agent_references_byte_for_byte(tmp_path, operation):- adapter = FakeAdapter([])- adapter.fail_sync = True- service = _service(tmp_path, adapter)- config = _configure_referenced_manual_model(service)- if operation == "custom_model":- config.agents["claude"].mode = "direct"- config.agents["opencode"].mode = "direct"- before = _serialized_config(service)-- with pytest.raises(ModelHubError) as exc_info:- if operation == "source":- asyncio.run(service.delete_source("src_primary01", force=True))- else:- asyncio.run(service.delete_custom_model("src_primary01", "retired-model"))-- assert exc_info.value.code == "engine_down"- assert _serialized_config(service) == before- restored = service.store.load()- assert restored.agents["claude"].mappings[0].target_model_id == "retired-model"- assert restored.agents["opencode"].menu.checked[0] == "anthropic/retired-model"+ def async_functions(path: Path) -> dict[str, AsyncFunctionDef]:+ tree = parse(path.read_text(encoding="utf-8"), filename=str(path))+ return {+ node.name: node+ for node in walk(tree)+ if isinstance(node, AsyncFunctionDef)+ }-def test_custom_model_preserves_slash_qualified_upstream_id(tmp_path):- service = _service(tmp_path, FakeAdapter([]))- source = service.store.load().sources[0]- source.vendor = "openrouter"- for configured_source in service.store.load().sources:- configured_source.credential_ref = f"cred_{configured_source.id}"+ def calls(function: AsyncFunctionDef) -> set[str]:+ return {+ (+ node.func.id+ if isinstance(node.func, Name)+ else node.func.attr+ )+ for node in walk(function)+ if isinstance(node, Call)+ and isinstance(node.func, (Name, Attribute))+ }- updated = asyncio.run(- service.add_custom_model(- source.id,- {- "model_id": "anthropic/claude-sonnet-4",- "display_name": "Claude Sonnet 4",- "reasoning_efforts": [],- }- )+ service_functions = async_functions(+ root / "core/handlers/model_hub/service.py")- menu = asyncio.run(- service.set_opencode_menu({"view": "featured", "checked": ["openrouter/anthropic/claude-sonnet-4"]})+ migration_functions = async_functions(+ root / "core/handlers/model_hub/migration.py")- assert updated["models"][-1]["id"] == "anthropic/claude-sonnet-4"- assert menu["menu"]["checked"] == ["openrouter/anthropic/claude-sonnet-4"]---def test_resolution_event_copy_comes_from_backend_i18n(tmp_path):- event = build_resolution_event(- agent="system",- kind="cooldown",- model_id="test-model",- reason="network",- from_source="src_primary01",- from_label="Primary",+ assert "_require_proven_source_payload" in calls(+ service_functions["create_source"])-- assert event.human_en == i18n_t(- "modelHub.events.cooldown",- "en",- from_source="Primary",- to_source=i18n_t("modelHub.events.sourceFallback", "en"),- reason=i18n_t("modelHub.events.reason.network", "en"),+ assert "_require_proven_source_payload" in calls(+ migration_functions["apply_native_migration"])- assert event.human_zh == i18n_t(- "modelHub.events.cooldown",- "zh",- from_source="Primary",- to_source=i18n_t("modelHub.events.sourceFallback", "zh"),- reason=i18n_t("modelHub.events.reason.network", "zh"),+ assert "_require_proven_observation" in calls(+ service_functions["_create_oauth_source"])-def test_mapping_and_delete_guards_use_backend_eligible_sources(tmp_path):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- config.sources[0].kind = "subscription"- config.sources[0].supply_channel = "native_cli"- config.sources[0].vendor = "anthropic"- config.sources[1].kind = "subscription"- config.sources[1].supply_channel = "native_cli"- config.sources[1].vendor = "openai"- config.sources[1].models = [ModelHubModelConfig(id="gpt-5", provenance="discovered")]- config.agents["claude"].sources.order = ["src_primary01"]- config.agents["codex"].sources.order = ["src_backup001"]- config.agents["opencode"].sources.order = []-- with pytest.raises(ModelHubError, match="mapping_target_unavailable"):- asyncio.run(- service.set_mappings(- "codex",- [- {- "builtin_id": "gpt-5",- "target_model_id": "claude-opus-4-6",- "enabled": True,- }- ],- )- )-- config.agents["claude"].mappings = [ModelHubMappingConfig("claude-native", "claude-opus-4-6", True)]- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.delete_source("src_primary01"))- assert exc_info.value.code == "source_last_supplier"-- config.agents["claude"].mode = "direct"- asyncio.run(service.delete_source("src_primary01"))- assert [source.id for source in service.store.load().sources] == ["src_backup001"]---def test_mapping_auto_enrolls_eligible_non_enrolled_source(tmp_path):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- added = _source("src_mapping01", "Mapping target")- added.models = [- ModelHubModelConfig(id="mapped-model", provenance="discovered")- ]- excluded = _source("src_mapping02", "Excluded mapping fallback")- excluded.models = [- ModelHubModelConfig(id="mapped-model", provenance="discovered")- ]- config.sources.extend([added, excluded])- original_order = list(config.agents["claude"].sources.order)-- agent = asyncio.run(- service.set_mappings(- "claude",- [- {- "builtin_id": "claude-opus-4-6",- "target_model_id": "mapped-model",- "enabled": True,- }- ],- )+def test_manual_model_delete_ignores_preexisting_unrelated_gap(tmp_path):+ source = _source("src_manual001")+ source.models.append(+ ModelHubModelConfig(id="manual-model", provenance="manual"))-- assert agent["sources"]["order"] == [*original_order, added.id]- assert config.agents["claude"].mappings[0].target_model_id == "mapped-model"---def test_opencode_menu_auto_enrolls_eligible_non_enrolled_source(tmp_path):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- added = _source("src_openmenu01", "Open menu target")- added.vendor = "openrouter"- added.models = [- ModelHubModelConfig(- id="anthropic/claude-sonnet-4",- provenance="manual",- )- ]- excluded = _source("src_openmenu02", "Excluded menu fallback")- excluded.vendor = "openrouter"- excluded.models = [- ModelHubModelConfig(- id="anthropic/claude-sonnet-4",- provenance="manual",- )- ]- config.sources.extend([added, excluded])- original_order = list(config.agents["opencode"].sources.order)-- agent = asyncio.run(- service.set_opencode_menu(- {- "view": "featured",- "checked": [- "openrouter/anthropic/claude-sonnet-4",- ],- }- )+ broken = _source("src_manual002", ("other-model",), status="cooldown")+ broken.state = ModelHubSourceStateConfig(+ status="cooldown",+ retry_at="2099-01-01T00:00:00Z",+ detail_key="models.source.cooldown.rate_limited",)+ config = _config([source, broken])+ config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(broken.id, "other-model"),)+ )+ service, store, _ = _service(tmp_path, config)- assert agent["sources"]["order"] == [*original_order, added.id]- assert agent["menu"]["checked"] == [- "openrouter/anthropic/claude-sonnet-4"- ]--[email protected]("mutation", ["mapping", "menu"])-def test_menu_acceptance_preserves_excluded_supplier_when_target_is_enrolled(- tmp_path,- mutation,-):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- excluded = _source("src_excluded01", "Explicitly excluded fallback")- config.sources.append(excluded)- backend = "claude" if mutation == "mapping" else "opencode"- original_order = list(config.agents[backend].sources.order)-- if mutation == "mapping":- agent = asyncio.run(- service.set_mappings(- "claude",- [- {- "builtin_id": "claude-opus-4-6",- "target_model_id": "claude-opus-4-6",- "enabled": True,- }- ],- )- )- else:- agent = asyncio.run(- service.set_opencode_menu(- {- "view": "featured",- "checked": ["anthropic/claude-opus-4-6"],- }- )- )-- assert agent["sources"]["order"] == original_order- assert excluded.id not in agent["sources"]["order"]+ result = asyncio.run(service.delete_custom_model(source.id, "manual-model"))+ assert result["removed_hops"] == []+ assert result["interrupted"] == []+ assert [model.id for model in store.load().sources[0].models] == [+ "claude-opus-4-6"+ ][email protected]("mutation", ["mapping", "menu"])-def test_menu_acceptance_incrementally_deduplicates_selected_supplier(- tmp_path,- mutation,-):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- selected = _source("src_multimap01", "Selected supplier")- excluded = _source("src_multimap02", "Excluded fallback")- for source in (selected, excluded):- source.models = [- ModelHubModelConfig(id="target-one", provenance="manual"),- ModelHubModelConfig(id="target-two", provenance="manual"),- ]- config.sources.extend([selected, excluded])- backend = "claude" if mutation == "mapping" else "opencode"- original_order = list(config.agents[backend].sources.order)- if mutation == "mapping":- agent = asyncio.run(- service.set_mappings(- "claude",- [- {- "builtin_id": "claude-opus-4-6",- "target_model_id": "target-one",- "enabled": True,- },- {- "builtin_id": "claude-sonnet-4-6",- "target_model_id": "target-two",- "enabled": True,- },- ],- )- )- else:- agent = asyncio.run(- service.set_opencode_menu(- {- "view": "featured",- "checked": [- "anthropic/target-one",- "anthropic/target-two",- ],- }- )- )+def test_manual_model_delete_rejects_a_new_gap(tmp_path):+ menu_model = "claude-opus-4-6"+ source = _source("src_manual003")+ source.models.append(ModelHubModelConfig(id="manual-model", provenance="manual"))+ config = _config([source], model=menu_model)+ config.agents["claude"].routes[menu_model] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(source.id, "manual-model"),)+ )+ service, store, _ = _service(tmp_path, config)- assert agent["sources"]["order"] == [*original_order, selected.id]- assert excluded.id not in agent["sources"]["order"]+ with pytest.raises(ModelHubError) as exc:+ asyncio.run(service.delete_custom_model(source.id, "manual-model"))+ assert exc.value.code == "source_model_in_route_chain"+ assert store.load().to_payload() == config.to_payload()-def test_follow_order_exhaustively_enrolls_eligible_sources_and_stays_follow(- tmp_path,-):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- anthropic_native = _source("src_claude01", "Claude native")- anthropic_native.kind = "subscription"- anthropic_native.supply_channel = "native_cli"- anthropic_native.vendor = "anthropic"- anthropic_native.credential_ref = None- openai_native = _source("src_codex001", "Codex native")- openai_native.kind = "subscription"- openai_native.supply_channel = "native_cli"- openai_native.vendor = "openai"- openai_native.credential_ref = None- config.sources.extend([anthropic_native, openai_native])- for agent in config.agents.values():- agent.sources.policy = "follow"- agent.sources.order = []-- for backend, agent in config.agents.items():- eligible = {- source.id- for source in config.sources- if config.source_eligible_for_backend(source, backend)- }- assert set(config.effective_source_order(backend)) == eligible- claude = asyncio.run(- service.set_mappings(- "claude",- [- {- "builtin_id": "claude-opus-4-6",- "target_model_id": "claude-opus-4-6",- "enabled": True,- }- ],- )+def test_delete_unused_source_ignores_preexisting_unrelated_gap(tmp_path):+ menu_model = "claude-opus-4-6"+ healthy = _source("src_delete02", (menu_model,))+ unused = _source("src_delete03", ("unused-model",))+ broken = _source("src_delete04", ("other-model",), status="cooldown")+ broken.state = ModelHubSourceStateConfig(+ status="cooldown",+ retry_at="2099-01-01T00:00:00Z",+ detail_key="models.source.cooldown.rate_limited",)- opencode = asyncio.run(- service.set_opencode_menu(- {- "view": "featured",- "checked": ["anthropic/claude-opus-4-6"],- }- )+ config = _config([healthy], model=menu_model)+ config.sources.extend((unused, broken))+ config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(broken.id, "other-model"),))+ service, store, _ = _service(tmp_path, config)+ result = asyncio.run(service.delete_source(unused.id))+ assert result == {"removed_hops": [], "interrupted": []}+ assert {source.id for source in store.load().sources} == {healthy.id, broken.id}[email protected]("mutation", ["mapping", "menu"])-def test_menu_mutations_reject_ineligible_sources_without_enrolling(- tmp_path,- mutation,-):- service = _service(tmp_path, FakeAdapter([]))- config = service.store.load()- candidate = _source("src_ineligible01", "Ineligible target")- candidate.kind = "subscription"- candidate.supply_channel = "native_cli"- candidate.vendor = "openai"- candidate.credential_ref = None- candidate.models = [- ModelHubModelConfig(id="ineligible-model", provenance="discovered")- ]- config.sources.append(candidate)- before = _serialized_config(service)-- with pytest.raises(ModelHubError) as exc_info:- if mutation == "mapping":- asyncio.run(- service.set_mappings(- "claude",- [- {- "builtin_id": "claude-opus-4-6",- "target_model_id": "ineligible-model",- "enabled": True,- }- ],- )- )- else:- asyncio.run(- service.set_opencode_menu(- {- "view": "featured",- "checked": ["openai/ineligible-model"],- }- )- )-- assert exc_info.value.code == "mapping_target_unavailable"- assert _serialized_config(service) == before---class NarrowingCredentialAdapter(FakeAdapter):- def __init__(self, outcomes=()):- super().__init__(outcomes)- self.provision_count = 0- self.fail_discovery = False- self.fail_old_revoke_once = False-- async def provision_credential(self, vendor, protocol, secret, base_url):- self.provision_count += 1- credential_ref = f"cred_replacement_{self.provision_count}"- self.provisioned.append((vendor, protocol, base_url))- return credential_ref- async def discover_models(self, vendor, protocol, base_url, credential_ref):- if self.fail_discovery:- raise ModelDiscoveryError("safe classified failure")- return ("replacement-only-model",)+def test_credential_replace_ignores_preexisting_unrelated_gap(tmp_path):+ menu_model = "claude-opus-4-6"+ healthy = _source("src_replace01", (menu_model,))+ broken = _source("src_replace02", ("other-model",), status="cooldown")+ broken.state = ModelHubSourceStateConfig(+ status="cooldown",+ retry_at="2099-01-01T00:00:00Z",+ detail_key="models.source.cooldown.rate_limited",+ )+ config = _config([healthy], model=menu_model)+ config.sources.append(broken)+ config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(broken.id, "other-model"),)+ )+ service, _store, adapter = _service(+ tmp_path,+ config,+ FakeAdapter(discovered=(menu_model,)),+ )- async def revoke_credential(self, credential_ref):- self.revoked.append(credential_ref)- if self.fail_old_revoke_once and credential_ref == "cred_src_primary01":- self.fail_old_revoke_once = False- raise RuntimeError("old handle still busy")---def _repair_guard_service(tmp_path, *, enabled: bool, adapter=None):- adapter = adapter or NarrowingCredentialAdapter()- service = _service(tmp_path, adapter)- config = service.store.load()- config.sources[0].models = [ModelHubModelConfig(id="glm-5.2", provenance="discovered")]- config.sources[1].models = [ModelHubModelConfig(id="claude-haiku-4-5", provenance="discovered")]- config.agents["claude"].mappings = [- ModelHubMappingConfig(- builtin_id="claude-opus-4-6",- target_model_id="glm-5.2",- enabled=enabled,- )- ]- service.store.requested_models["claude"] = "claude-haiku-4-5"- return service, adapter+ result = asyncio.run(+ service.replace_credential(healthy.id, {"key": "replacement-key"})+ )++ assert result["removed_hops"] == []+ assert result["interrupted"] == []+ assert adapter.provisioned == ["replacement-key"]+++def test_delete_source_reports_and_then_prunes_exact_hops(tmp_path):+ menu_model = "claude-opus-4-6"+ source = _source("src_delete01", (menu_model,))+ config = _config([source], model=menu_model)+ service, store, _ = _service(tmp_path, config)+ with pytest.raises(ModelHubError) as exc:+ asyncio.run(service.delete_source(source.id))+ assert exc.value.code == "source_in_route_chain"+ assert exc.value.data["would_remove_hops"][0]["model_id"] == menu_model+ result = asyncio.run(service.delete_source(source.id, force=True))+ assert result["removed_hops"]+ assert store.load().sources == []+ assert store.load().agents["claude"].routes[menu_model].hops == ()+++def test_refresh_source_uses_guarded_success_shape(tmp_path):+ menu_model = "claude-opus-4-6"+ source = _source("src_refresh1", (menu_model,))+ config = _config([source], model=menu_model)+ adapter = FakeAdapter(discovered=("new-model",))+ service, store, _ = _service(tmp_path, config, adapter)+ with pytest.raises(ModelHubError) as exc:+ asyncio.run(service.refresh_source(source.id))+ assert exc.value.code == "source_model_in_route_chain"+ result = asyncio.run(service.refresh_source(source.id, force=True))+ assert set(result) == {"source", "removed_hops", "interrupted"}+ assert result["removed_hops"][0]["model_id"] == menu_model+ assert store.load().agents["claude"].routes[menu_model].hops == ()@pytest.mark.parametrize(- ("route", "enabled", "blocked"),+ ("inventory_case", "discovered"),[- ("delete", False, False),- ("delete", True, True),- ("credential", False, False),- ("credential", True, True),+ ("normal", ("claude-opus-4-6", "new-model")),+ ("empty", ()),+ ("failure", None),],)-def test_supply_guard_uses_only_enabled_menu_mappings_from_fresh_fixtures(- tmp_path,- route,- enabled,- blocked,-):- service, _adapter = _repair_guard_service(- tmp_path / f"{route}-{enabled}",- enabled=enabled,- )-- if blocked:- with pytest.raises(ModelHubError) as exc_info:- if route == "delete":- asyncio.run(service.delete_source("src_primary01"))- else:- asyncio.run(- service.replace_credential(- "src_primary01",- {"key": "sk-narrower-replacement"},- )- )- assert exc_info.value.code == "source_last_supplier"- assert exc_info.value.data["would_interrupt"] == [- {- "backend": "claude",- "model_id": "claude-opus-4-6",- "agents": [],- }- ]- elif route == "delete":- asyncio.run(service.delete_source("src_primary01"))- assert [source.id for source in service.store.load().sources] == ["src_backup001"]- else:- result = asyncio.run(- service.replace_credential(- "src_primary01",- {"key": "sk-narrower-replacement"},- )- )- assert result["interrupted_pairs"] == []- assert result["source"]["credential_ref"] == "cred_replacement_1"---def test_supply_guard_reports_menu_identifier_and_effective_named_agents(tmp_path):- service, _adapter = _repair_guard_service(tmp_path, enabled=True)- service.named_agents_override = lambda backend: (- [("pm", "claude-opus-4-6"), ("reviewer", "claude-opus-4-6")]- if backend == "claude"- else []- )- service.store.requested_models["claude"] = "claude-opus-4-6"-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.delete_source("src_primary01"))-- assert exc_info.value.data["would_interrupt"] == [- {- "backend": "claude",- "model_id": "claude-opus-4-6",- "agents": ["pm", "reviewer"],- }- ]---def test_supply_guard_canonicalizes_opencode_effective_models(tmp_path):- service, _adapter = _repair_guard_service(tmp_path, enabled=False)- config = service.store.load()- config.sources[0].vendor = "zhipuai"- config.sources[0].models = [- ModelHubModelConfig(id="glm-5.2", provenance="discovered")- ]- config.sources[1].vendor = "anthropic"- config.sources[1].models = [- ModelHubModelConfig(id="claude-haiku-4-5", provenance="discovered")- ]- config.agents["claude"].mode = "direct"- config.agents["codex"].mode = "direct"- config.agents["opencode"].menu.checked = ["zhipuai/glm-5.2"]- service.named_agents_override = lambda backend: (- [("builder", "glm-5.2")] if backend == "opencode" else []- )-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.delete_source("src_primary01"))-- assert exc_info.value.data["would_interrupt"] == [- {- "backend": "opencode",- "model_id": "zhipuai/glm-5.2",- "agents": ["builder"],- }- ]---def test_credential_force_commits_same_narrowing_request_and_reports_gaps(tmp_path):- service, adapter = _repair_guard_service(tmp_path, enabled=True)- before = _serialized_config(service)-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.replace_credential(- "src_primary01",- {"key": "sk-narrower-replacement"},- )- )-- assert exc_info.value.code == "source_last_supplier"- assert _serialized_config(service) == before- result = asyncio.run(- service.replace_credential(- "src_primary01",- {"key": "sk-narrower-replacement", "force": True},- )- )- assert result["recovered"] is False- assert result["interrupted_pairs"] == exc_info.value.data["would_interrupt"]- assert result["source"]["credential_ref"] == "cred_replacement_2"- assert adapter.revoked == ["cred_replacement_1", "cred_src_primary01"]---def test_blocked_credential_repair_bypasses_refusal_and_reports_remaining_gaps([email protected]("operation", ["refresh", "base_url", "credential"])+def test_inventory_mutations_share_the_successful_discovery_finalizer(tmp_path,+ operation,+ inventory_case,+ discovered,):- service, _adapter = _repair_guard_service(tmp_path, enabled=True)- service.store.load().sources[0].state = ModelHubSourceStateConfig(- status="needs_action",- detail_key="models.source.needs_action.credential_revoked",+ source = _source(+ "src_finalize1",+ ("claude-opus-4-6",),+ vendor="custom",)-- result = asyncio.run(- service.replace_credential(- "src_primary01",- {"key": "sk-recovery-key"},+ source.base_url = "https://old-relay.example/v1"+ source.state = ModelHubSourceStateConfig(+ status="error",+ detail_key="models.source.error.unclassified",+ )+ config = _config([source])+ adapter = FakeAdapter(discovered=discovered or ())+ if inventory_case == "failure":+ adapter.discovery_error = ModelDiscoveryError("injected discovery failure")+ service, store, _ = _service(tmp_path, config, adapter)+ before = store.load().to_payload()++ if operation == "refresh":+ mutation = service.refresh_source(source.id, force=True)+ elif operation == "base_url":+ mutation = service.patch_source(+ source.id,+ {+ "base_url": "https://new-relay.example/v1",+ "force": True,+ },)- )-- assert result["recovered"] is True- assert result["source"]["state"]["status"] == "standby"- assert result["interrupted_pairs"][0]["model_id"] == "claude-opus-4-6"--[email protected]("failure", ["discovery", "sync"])-def test_credential_replacement_failure_preserves_prior_source(tmp_path, failure):- adapter = NarrowingCredentialAdapter()- service, _adapter = _repair_guard_service(- tmp_path,- enabled=False,- adapter=adapter,- )- before = _serialized_config(service)- if failure == "discovery":- adapter.fail_discovery = Trueelse:- adapter.fail_sync = True-- with pytest.raises(ModelHubError):- asyncio.run(- service.replace_credential(- "src_primary01",- {"key": "sk-failing-replacement"},- )+ mutation = service.replace_credential(+ source.id,+ {"key": "replacement-key", "force": True},)- assert _serialized_config(service) == before- assert "cred_replacement_1" in adapter.revoked- assert service.revocations.list() == []+ if inventory_case == "failure":+ with pytest.raises(ModelHubError) as exc:+ asyncio.run(mutation)+ assert exc.value.code == "discovery_failed"+ assert store.load().to_payload() == before+ return+ result = asyncio.run(mutation)+ persisted = store.load().sources[0]+ assert result["source"] == persisted.to_payload()+ assert persisted.state == ModelHubSourceStateConfig(status="standby")+ assert persisted.last_discovered_at is not None+ assert [model.id for model in persisted.models] == list(discovered)-def test_empty_discovery_rejects_credential_replacement(tmp_path):- adapter = NarrowingCredentialAdapter()- service, _adapter = _repair_guard_service(- tmp_path,- enabled=False,- adapter=adapter,- )- before = _serialized_config(service)-- async def empty_discovery(vendor, protocol, base_url, credential_ref):- return ()- adapter.discover_models = empty_discovery+def test_all_interruption_guards_use_the_shared_baseline_comparator():+ from ast import Attribute, AsyncFunctionDef, Name, parse, walk+ from pathlib import Path- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.replace_credential(- "src_primary01",- {"key": "sk-empty-replacement"},- )+ tree = parse(+ (Path(__file__).parents[1] / "core/handlers/model_hub/service.py").read_text(+ encoding="utf-8")-- assert exc_info.value.code == "discovery_failed"- assert _serialized_config(service) == before- assert adapter.revoked == ["cred_replacement_1"]- assert service.revocations.list() == []---def test_credential_replacement_rolls_back_when_old_journal_cleanup_fails(- tmp_path,-):- adapter = NarrowingCredentialAdapter()- service, _adapter = _repair_guard_service(- tmp_path,- enabled=False,- adapter=adapter,)- before = _serialized_config(service)- original_remove = service.revocations.remove-- def fail_old_journal_cleanup(source_id, credential_ref):- if credential_ref == "cred_src_primary01":- raise OSError("journal cleanup failed")- return original_remove(source_id, credential_ref)-- service.revocations.remove = fail_old_journal_cleanup- adapter.fail_sync = True+ direct_baseline_guards = {+ "delete_source",+ "set_agent_chain",+ "delete_custom_model",+ }+ inventory_guards = {+ "patch_source",+ "replace_credential",+ "refresh_source",+ }+ methods = {+ node.name: node+ for node in walk(tree)+ if isinstance(node, AsyncFunctionDef)+ and node.name in direct_baseline_guards | inventory_guards+ }- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.replace_credential(- "src_primary01",- {"key": "sk-failing-replacement"},+ def calls(method):+ return [+ (+ node.func.id+ if isinstance(node.func, Name)+ else node.func.attr+ if isinstance(node.func, Attribute)+ else None)- )-- assert exc_info.value.code == "engine_down"- assert _serialized_config(service) == before- assert "cred_replacement_1" in adapter.revoked---def test_failed_old_credential_revoke_reconciles_after_service_restart(tmp_path):- adapter = NarrowingCredentialAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- adapter.fail_old_revoke_once = True- service, _adapter = _repair_guard_service(- tmp_path,- enabled=False,- adapter=adapter,- )-- result = asyncio.run(- service.replace_credential(- "src_primary01",- {"key": "sk-rotated-key"},- )- )-- assert result["source"]["credential_ref"] == "cred_replacement_1"- assert service.revocations.list()[0].credential_ref == "cred_src_primary01"- restarted_adapter = NarrowingCredentialAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- restarted = ModelHubService(- store=service.store,- adapter=restarted_adapter,- events=BoundedEventLog(tmp_path / "restarted-events.json"),- revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),- now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),- )-- resolved = asyncio.run(- restarted.resolve(- backend="claude",- model_id="replacement-only-model",- request={},- )- )-- assert resolved.source_id == "src_primary01"- assert restarted_adapter.revoked == ["cred_src_primary01"]- assert restarted.revocations.list() == []- assert restarted.store.load().sources[0].credential_ref == "cred_replacement_1"---def test_existing_source_refresh_clears_blocker_and_restores_runnable_supply(tmp_path):- adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])- service = _service(tmp_path, adapter)- config = service.store.load()- source = config.sources[0]- source.state = ModelHubSourceStateConfig(- status="needs_action",- detail_key="models.source.needs_action.balance_exhausted",- )- config.sources = [source]- for agent in config.agents.values():- agent.sources.order = [source.id]+ for node in walk(method)+ if node.__class__.__name__ == "Call"+ ]- updated, discovered = asyncio.run(service.refresh_source(source.id))- resolved = asyncio.run(- service.resolve(- backend="claude",- model_id="claude-opus-4-6",- request={},- )+ inventory_finalizer = next(+ node+ for node in walk(tree)+ if node.__class__.__name__ == "AsyncFunctionDef"+ and node.name == "_finalize_successful_discovery")+ assert "_guard_inventory_mutation" in calls(inventory_finalizer)+ assert "_apply_discovered_models" in calls(inventory_finalizer)+ assert "_commit_synced" in calls(inventory_finalizer)- assert discovered == 1- assert updated["state"]["status"] == "standby"- assert updated["last_discovered_at"] == "2026-07-23T03:00:00+00:00"- assert service.store.load().sources[0].last_discovered_at == updated["last_discovered_at"]- assert resolved.source_id == source.id+ for name in inventory_guards:+ assert "_finalize_successful_discovery" in calls(methods[name])+ assert "_guard_inventory_mutation" not in calls(methods[name])+ assert "_apply_discovered_models" not in calls(methods[name])+ assert "_commit_synced" not in calls(methods[name])+ assert "_introduced_interruptions" not in calls(methods[name])+ for name in direct_baseline_guards:+ assert "_introduced_interruptions" in calls(methods[name])+ assert "_would_interrupt" not in calls(methods[name])-def test_existing_source_refresh_persists_safe_error_state_on_discovery_failure(- tmp_path,-):- adapter = NarrowingCredentialAdapter()- adapter.fail_discovery = True- service = _service(tmp_path, adapter)- source = service.store.load().sources[0]- source.state = ModelHubSourceStateConfig(- status="needs_action",- detail_key="models.source.needs_action.balance_exhausted",- )- source.last_discovered_at = "2026-07-22T03:00:00+00:00"- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.refresh_source(source.id))+def test_credential_target_and_refresh_capability_have_single_service_consumers():+ from ast import AsyncFunctionDef, Attribute, Call, Name, parse, walk+ from pathlib import Path- assert exc_info.value.code == "discovery_failed"- assert service.store.load().sources[0].state.status == "error"- assert service.store.load().sources[0].state.detail_key == (- "models.source.error.unclassified"- )- assert service.store.load().sources[0].last_discovered_at == "2026-07-22T03:00:00+00:00"- source_refresh_event = service.list_events(limit=10)[0]- assert source_refresh_event["agent"] == "system"- assert source_refresh_event["model_id"] is None-- turn_service = _service(- tmp_path / "turn",- FakeAdapter(- [- _outcome(RawOutcomeKind.HTTP_ERROR, status=418),- _outcome(RawOutcomeKind.SUCCESS, status=200),- ]- ),- )- asyncio.run(- turn_service.resolve(- backend="claude",- model_id="claude-opus-4-6",- request={},+ tree = parse(+ (Path(__file__).parents[1] / "core/handlers/model_hub/service.py").read_text(+ encoding="utf-8"))- turn_event = next(- event- for event in turn_service.list_events(limit=10)- if event["kind"] == "needs_action"- )- fields = ("kind", "reason", "from_source", "severity")- assert tuple(source_refresh_event[field] for field in fields) == tuple(- turn_event[field] for field in fields- )+ methods = {+ node.name: node+ for node in walk(tree)+ if isinstance(node, AsyncFunctionDef)+ }+ def calls(method: AsyncFunctionDef) -> set[str]:+ return {+ node.func.id+ if isinstance(node.func, Name)+ else node.func.attr+ for node in walk(method)+ if isinstance(node, Call)+ and isinstance(node.func, (Name, Attribute))+ }-def test_existing_source_refresh_rejects_empty_discovery_before_recovery(tmp_path):- adapter = FakeAdapter([])- service = _service(tmp_path, adapter)- source = service.store.load().sources[0]- source.state = ModelHubSourceStateConfig(- status="needs_action",- detail_key="models.source.needs_action.balance_exhausted",+ assert "retarget_api_key_credential" in calls(methods["patch_source"])+ assert "credential_supports_refresh" in calls(+ methods["_classify_source_outcome"])-- async def empty_discovery(vendor, protocol, base_url, credential_ref):- return ()-- adapter.discover_models = empty_discovery-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.refresh_source(source.id))-- assert exc_info.value.code == "discovery_failed"- persisted = service.store.load().sources[0]- assert persisted.state.status == "error"- assert persisted.state.detail_key == "models.source.error.unclassified"---def test_existing_source_refresh_preserves_health_on_engine_outage(tmp_path):- adapter = NarrowingCredentialAdapter()- service = _service(tmp_path, adapter)- before = _serialized_config(service)-- async def engine_unavailable(vendor, protocol, base_url, credential_ref):- raise RuntimeError("engine unavailable")-- adapter.discover_models = engine_unavailable- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(service.refresh_source("src_primary01"))-- assert exc_info.value.code == "engine_down"- assert _serialized_config(service) == before- assert service.list_events(limit=10) == []---def test_mapping_write_rejects_disabled_unavailable_target(tmp_path):- service = _service(tmp_path, FakeAdapter([]))-- with pytest.raises(ModelHubError) as exc_info:- asyncio.run(- service.set_mappings(- "claude",- [- {- "builtin_id": "claude-opus-4-6",- "target_model_id": "missing-model",- "enabled": False,- }- ],- )- )-- assert exc_info.value.code == "mapping_target_unavailable"- assert service.store.load().agents["claude"].mappings == []---def test_event_log_is_bounded_and_sanitizes_labels(tmp_path):- log = BoundedEventLog(tmp_path / "events.json", max_entries=2)- for index in range(3):- log.append(- build_resolution_event(- agent="system",- kind="cooldown",- model_id=f"model-{index}",- reason="network",- from_source=f"src_source0{index}",- from_label=(- "Bearer abcdefghijklmnop"- if index == 2- else "Anthropic API Key"- if index == 1- else f"Source {index}"- ),- )- )-- events = json.loads((tmp_path / "events.json").read_text(encoding="utf-8"))- assert len(events) == 2- assert "abcdefghijklmnop" not in json.dumps(events)+ assert "_classify_source_outcome" in calls(methods["probe_agent"])+ assert "_classify_source_outcome" in calls(methods["resolve"])+ capability_callers = {+ name+ for name, method in methods.items()+ if "credential_supports_refresh" in calls(method)+ }+ assert capability_callers == {"_classify_source_outcome"}+++def test_direct_mode_refuses_chain_and_probe(tmp_path):+ config = ModelHubConfig()+ service, _, _ = _service(tmp_path, config)+ asyncio.run(service.set_agent_mode("claude", "direct"))+ with pytest.raises(ModelHubError) as chain_error:+ service.agent_chain("claude", "claude-opus-4-6")+ assert chain_error.value.code == "direct_mode"+ with pytest.raises(ModelHubError) as probe_error:+ asyncio.run(service.probe_agent("claude", "claude-opus-4-6"))+ assert probe_error.value.code == "direct_mode"diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex c7df71d18..143118721 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -1574,22 +1574,17 @@ def test_engine_client_non_stream_failures_after_first_byte_block_retry(@pytest.mark.parametrize(- ("vendor", "endpoint", "expected_query", "device_flow"),+ ("vendor", "endpoint"),[- ("anthropic", "/anthropic-auth-url", {"is_webui": "true"}, False),- ("openai", "/codex-auth-url", {"is_webui": "true"}, False),- ("codex", "/codex-auth-url", {"is_webui": "true"}, False),- ("antigravity", "/antigravity-auth-url", {"is_webui": "true"}, False),- ("kimi", "/kimi-auth-url", None, True),- ("xai", "/xai-auth-url", None, True),+ ("anthropic", "/anthropic-auth-url"),+ ("openai", "/codex-auth-url"),+ ("codex", "/codex-auth-url"),],)-def test_oauth_start_uses_webui_callback_only_for_browser_flows(+def test_oauth_start_uses_webui_callback_for_observable_vendors(tmp_path: Path,vendor: str,endpoint: str,- expected_query: dict[str, str] | None,- device_flow: bool,) -> None:class Client:def __init__(self) -> None:@@ -1600,10 +1595,7 @@ def test_oauth_start_uses_webui_callback_only_for_browser_flows(return {"files": []}if path == endpoint:self.start_query = query- response = {"state": "engine-state", "url": "https://example.test/oauth"}- if device_flow:- response.update({"flow": "device", "user_code": "ABCD-EFGH"})- return response+ return {"state": "engine-state", "url": "https://example.test/oauth"}raise AssertionError((method, path, query, payload, timeout))class Supervisor:@@ -1624,8 +1616,33 @@ def test_oauth_start_uses_webui_callback_only_for_browser_flows(flow = await adapter.start_oauth("src_fixture123", vendor)- assert client.start_query == expected_query- assert flow.expects == ("none" if device_flow else "paste_callback_url")+ assert client.start_query == {"is_webui": "true"}+ assert flow.expects == "paste_callback_url"++ asyncio.run(run())++[email protected]("vendor", ["antigravity", "kimi", "xai"])+def test_oauth_start_rejects_engine_only_vendors_before_engine_work(+ tmp_path: Path,+ vendor: str,+) -> None:+ class Supervisor:+ def client(self):+ raise AssertionError("unsupported Model Hub OAuth must not reach the engine")++ async def run() -> None:+ store = EngineStateStore(tmp_path / "state")+ adapter = CLIProxyEngineAdapter(+ supervisor=Supervisor(), # type: ignore[arg-type]+ state_store=store,+ )++ with pytest.raises(+ EngineStateError,+ match="lacks Model Hub response-backed observation",+ ):+ await adapter.start_oauth("src_fixture123", vendor)asyncio.run(run())@@ -1973,7 +1990,10 @@ def test_oauth_flow_releases_provider_after_engine_failure_or_expiry(tmp_path: Pstate_store=store,)- with pytest.raises(EngineStateError, match="unsupported OAuth vendor"):+ with pytest.raises(+ EngineStateError,+ match="lacks Model Hub response-backed observation",+ ):await adapter.start_oauth("src_fixture123", "gemini")failed_flow = await adapter.start_oauth("src_fixture123", "anthropic")diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.tsindex ed016f92b..f60f577e3 100644--- a/ui/src/components/settings/models/mockData.ts+++ b/ui/src/components/settings/models/mockData.ts@@ -98,7 +98,7 @@ export function buildMockSources(): Source[] {kind: 'api_key',vendor: 'zhipuai',display_name: '智谱 API Key',- protocol: 'openai_compatible',+ protocol: 'openai_chat',base_url: 'https://open.bigmodel.cn/api/paas/v4',supply_channel: 'hub',billing: 'metered',@@ -124,7 +124,7 @@ export function buildMockSources(): Source[] {kind: 'api_key',vendor: 'custom',display_name: 'relay.example',- protocol: 'openai_compatible',+ protocol: 'openai_chat',base_url: 'https://relay.example/v1',supply_channel: 'hub',billing: 'metered',@@ -357,7 +357,7 @@ function olderHistory(count: number): ResolutionEvent[] {export function buildMockRuntime(): RuntimeDependency {return {- contract_version: 4,+ contract_version: 5,manifest: {name: 'cliproxyapi',version: 'v7.2.95',diff --git a/ui/src/components/settings/models/modelRows.test.ts b/ui/src/components/settings/models/modelRows.test.tsindex 8278bc50f..553e65fa3 100644--- a/ui/src/components/settings/models/modelRows.test.ts+++ b/ui/src/components/settings/models/modelRows.test.ts@@ -35,7 +35,7 @@ const agent = (over: Partial<AgentSupply> = {}): AgentSupply => ({const read = (over: Partial<Extract<ModelChainRead, { kind: 'ready' }>['chain']> = {}): ModelChainRead => ({kind: 'ready',chain: {- contract_version: 4,+ contract_version: 5,backend: 'claude',model_id: 'builtin-model',supply_state: 'ok',@@ -54,7 +54,7 @@ const read = (over: Partial<Extract<ModelChainRead, { kind: 'ready' }>['chain']>});const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({- contract_version: 4,+ contract_version: 5,manifest: { name: 'cliproxyapi', version: '1', source_sha: 'a', assets: [] },status: { health, verified: health === 'ok' },});@@ -64,7 +64,7 @@ const source = (id: string): Source => ({kind: 'api_key',vendor: 'custom',display_name: id,- protocol: 'openai_compatible',+ protocol: 'openai_chat',supply_channel: 'hub',billing: 'metered',state: { status: 'active' },diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex c3bcab207..81049cb83 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -552,7 +552,7 @@ class MockStore {kind: 'api_key',vendor: draft.vendor,display_name: draft.vendor === 'custom' ? hostLabel(draft.base_url) : vendorLabel(draft.vendor),- protocol: draft.vendor === 'anthropic' ? 'anthropic' : 'openai_compatible',+ protocol: draft.vendor === 'anthropic' ? 'anthropic' : 'openai_chat',base_url: draft.base_url ?? null,supply_channel: 'hub',billing: 'metered',diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 63c0302bb..7bb28aa2e 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -12,17 +12,16 @@// for every route that did not move. This file changes in lockstep with the// schemas — never ahead of them.-export const CONTRACT_VERSION = 3 as const;-export const AGENT_CHAIN_CONTRACT_VERSION = 4 as const;-export const PROBE_RESULT_CONTRACT_VERSION = 4 as const;+export const CONTRACT_VERSION = 5 as const;+export const AGENT_CHAIN_CONTRACT_VERSION = 5 as const;+export const PROBE_RESULT_CONTRACT_VERSION = 5 as const;// ── source.schema.json ──────────────────────────────────────────────────export type SourceKind = 'subscription' | 'api_key';export type SourceProtocol =| 'anthropic'| 'openai_responses'- | 'openai_chat'- | 'openai_compatible';+ | 'openai_chat';export type SupplyChannel = 'native_cli' | 'hub';/** v3 (§4.5): classified by whether the state heals itself. cooldown carries a* `retry_at` and clears on its own; needs_action never recovers unattended;@@ -461,7 +460,7 @@ export type OAuthFlow = {export type RuntimeHealth = 'ok' | 'degraded' | 'down' | 'not_started' | 'not_installed';export type RuntimeDependency = {- contract_version: 4;+ contract_version: typeof CONTRACT_VERSION;manifest: {name: 'cliproxyapi';version: string;diff --git a/ui/src/components/settings/models/vendorMeta.ts b/ui/src/components/settings/models/vendorMeta.tsindex a77ca038f..2625ef306 100644--- a/ui/src/components/settings/models/vendorMeta.ts+++ b/ui/src/components/settings/models/vendorMeta.ts@@ -84,21 +84,22 @@ export function backendVisual(backend: AgentBackend): BackendVisual {// ── API-key vendor picker (frame 06r) ───────────────────────────────────// value = standard vendor id; labelKey → i18n; base_url prefilled for official-// vendors (editable), null for 自定义. Protocol drives the created source.+// vendors (editable), null for 自定义. Probe order is only a hint; the server+// still requires upstream response evidence before it stores a protocol.export type VendorOption = {value: string;labelKey: string;base_url: string | null;- protocol: SourceProtocol;+ probe_order: SourceProtocol[];};export const VENDOR_OPTIONS: VendorOption[] = [- { value: 'custom', labelKey: 'settings.models.addKey.vendors.custom', base_url: null, protocol: 'openai_compatible' },- { value: 'anthropic', labelKey: 'settings.models.addKey.vendors.anthropic', base_url: 'https://api.anthropic.com', protocol: 'anthropic' },- { value: 'openai', labelKey: 'settings.models.addKey.vendors.openai', base_url: 'https://api.openai.com/v1', protocol: 'openai_chat' },- { value: 'zhipuai', labelKey: 'settings.models.addKey.vendors.zhipuai', base_url: 'https://open.bigmodel.cn/api/paas/v4', protocol: 'openai_compatible' },- { value: 'kimi', labelKey: 'settings.models.addKey.vendors.kimi', base_url: 'https://api.moonshot.cn/v1', protocol: 'openai_compatible' },- { value: 'xai', labelKey: 'settings.models.addKey.vendors.xai', base_url: 'https://api.x.ai/v1', protocol: 'openai_chat' },+ { value: 'custom', labelKey: 'settings.models.addKey.vendors.custom', base_url: null, probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },+ { value: 'anthropic', labelKey: 'settings.models.addKey.vendors.anthropic', base_url: 'https://api.anthropic.com/v1', probe_order: ['anthropic', 'openai_responses', 'openai_chat'] },+ { value: 'openai', labelKey: 'settings.models.addKey.vendors.openai', base_url: 'https://api.openai.com/v1', probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },+ { value: 'zhipuai', labelKey: 'settings.models.addKey.vendors.zhipuai', base_url: 'https://open.bigmodel.cn/api/paas/v4', probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },+ { value: 'kimi', labelKey: 'settings.models.addKey.vendors.kimi', base_url: 'https://api.moonshot.cn/v1', probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },+ { value: 'xai', labelKey: 'settings.models.addKey.vendors.xai', base_url: 'https://api.x.ai/v1', probe_order: ['openai_responses', 'openai_chat', 'anthropic'] },];export const DEFAULT_VENDOR = VENDOR_OPTIONS[0];diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 34c9131e7..53b77b6b1 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -742,7 +742,6 @@"network": "network unavailable","recovery": "recovered","manual": "manual change",- "mapping": "model mapping applied","credential_expired": "credential expired","credential_revoked": "credential revoked","balance_exhausted": "balance exhausted",@@ -751,7 +750,10 @@"unclassified_error": "unclassified source error","no_enabled_source": "no source is enabled","no_eligible_source": "no source is eligible",- "model_unsupported": "no source supports this model"+ "route_unconfigured": "the route is not configured",+ "source_missing": "the configured source no longer exists",+ "model_unsupported": "the configured source no longer supplies this model",+ "native_cli_unavailable": "CLI login is not available in this process"}},"launch": {@@ -759,6 +761,7 @@"waiting": "Model {model} is temporarily unavailable. Waiting for {source} to recover at {retry_at}.","interrupted": "Model {model} is unavailable: {blockers}. Open Models to resolve it.","native_cli_unavailable": "CLI login is not available in this process",+ "route_unconfigured": "Model {model} has no configured route. Open Models to configure one.","no_enabled_source": "Model {model} has no enabled source. Open Models to configure one.","no_eligible_source": "Model {model} has no source eligible for {backend}. Open Models to configure one.","model_unsupported": "No source supports model {model}. Open Models to configure one."diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 5bd976cb5..75bed9961 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -742,7 +742,6 @@"network": "网络暂不可用","recovery": "已恢复","manual": "手动调整",- "mapping": "已应用模型映射","credential_expired": "凭证已过期","credential_revoked": "凭证已撤销","balance_exhausted": "余额不足",@@ -751,7 +750,10 @@"unclassified_error": "来源发生未分类错误","no_enabled_source": "没有已启用的来源","no_eligible_source": "没有适用的来源",- "model_unsupported": "没有来源支持此模型"+ "route_unconfigured": "尚未配置路由",+ "source_missing": "已配置的来源已不存在",+ "model_unsupported": "已配置的来源不再供应此模型",+ "native_cli_unavailable": "当前进程无法使用 CLI 登录"}},"launch": {@@ -759,6 +761,7 @@"waiting": "模型 {model} 暂时不可用,等待 {source} 于 {retry_at} 自动恢复。","interrupted": "模型 {model} 当前不可用:{blockers}。请前往 Models 处理。","native_cli_unavailable": "当前进程无法使用 CLI 登录",+ "route_unconfigured": "模型 {model} 尚未配置路由。请前往 Models 配置。","no_enabled_source": "模型 {model} 没有已启用的来源。请前往 Models 配置。","no_eligible_source": "模型 {model} 没有适用于 {backend} 的来源。请前往 Models 配置。","model_unsupported": "没有来源支持模型 {model}。请前往 Models 配置。"diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex 54775d394..f3dad2d76 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -82,6 +82,9 @@ class ModelHubRemoteService:def list_sources(self) -> list[dict]:return _rpc_sync("list_sources")+ async def observe_source(self, payload: dict) -> dict:+ return await _rpc("observe_source", {"observation": payload})+async def create_source(self, payload: dict) -> dict:return await _rpc("create_source", {"source": payload})@@ -100,12 +103,11 @@ class ModelHubRemoteService:{"source_id": source_id, "reauth": payload},)- async def delete_source(self, source_id: str, *, force: bool = False) -> None:- await _rpc("delete_source", {"source_id": source_id, "force": force})+ async def delete_source(self, source_id: str, *, force: bool = False) -> dict:+ return await _rpc("delete_source", {"source_id": source_id, "force": force})- async def refresh_source(self, source_id: str) -> tuple[dict, int]:- result = await _rpc("refresh_source", {"source_id": source_id})- return result["source"], result["discovered"]+ async def refresh_source(self, source_id: str, *, force: bool = False) -> dict:+ return await _rpc("refresh_source", {"source_id": source_id, "force": force})def list_agents(self) -> list[dict]:return _rpc_sync("list_agents")@@ -122,8 +124,11 @@ class ModelHubRemoteService:async def set_agent_mode(self, backend: str, mode: object) -> dict:return await _rpc("set_agent_mode", {"backend": backend, "mode": mode})- async def set_mappings(self, backend: str, mappings: object) -> dict:- return await _rpc("set_mappings", {"backend": backend, "mappings": mappings})+ async def set_agent_chain(self, backend: str, model_id: str, chain: object) -> dict:+ return await _rpc(+ "set_agent_chain",+ {"backend": backend, "model_id": model_id, "chain": chain},+ )async def set_opencode_menu(self, menu: object) -> dict:return await _rpc("set_opencode_menu", {"menu": menu})diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex a2a446732..5b9bff624 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -6,20 +6,30 @@ import secretsimport threadingfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezone+from enum import Enumfrom typing import Any, Mapping, Sequence+import aiohttp++from config.v2_config import normalize_model_hub_base_urlfrom core.handlers.model_hub.adapter import (EngineHealth,EngineStatus,+ ObservationDiscovery,+ ObservationOutcome,OAuthFlowState,OriginNotAllowedError,RawCallOutcome,RawOutcomeKind,RetainedMaterialDisposition,+ SOURCE_PROTOCOLS,+ SourceObservation,SourceBinding,+ make_source_observation,)from core.handlers.model_hub.errors import ModelDiscoveryErrorfrom vibe.model_hub_runtime.client import (+ _OFFICIAL_BASE_URLS,EngineClient,EngineClientError,EngineInvokeHandle,@@ -38,19 +48,438 @@ _OAUTH_ENDPOINTS = {"anthropic": ("/anthropic-auth-url", "anthropic", "claude"),"openai": ("/codex-auth-url", "codex", "codex"),"codex": ("/codex-auth-url", "codex", "codex"),- "antigravity": ("/antigravity-auth-url", "antigravity", "antigravity"),- "kimi": ("/kimi-auth-url", "kimi", "kimi"),- "xai": ("/xai-auth-url", "xai", "xai"),}-_WEBUI_OAUTH_VENDORS = frozenset({"anthropic", "openai", "codex", "antigravity"})+_WEBUI_OAUTH_VENDORS = frozenset(_OAUTH_ENDPOINTS)+++class _ProtocolProof(Enum):+ PROVEN = "proven"+ UNPROVEN = "unproven"+++class _AuthenticationEvidence(Enum):+ ACCEPTED = "accepted"+ REJECTED = "rejected"+ UNKNOWN = "unknown"+++@dataclass(frozen=True)+class _ProtocolEvidence:+ protocol: _ProtocolProof+ authentication: _AuthenticationEvidence+++@dataclass(frozen=True)+class _ProtocolEvidenceRule:+ statuses: frozenset[int]+ protocol: _ProtocolProof+ authentication: _AuthenticationEvidence+ top_level_field: str | None = None+ top_level_values: frozenset[str] = frozenset()+ error_identifiers: frozenset[str] = frozenset()+ error_params: frozenset[str] | None = None++ def matches(self, status: int, payload: Mapping[str, Any]) -> bool:+ if status not in self.statuses:+ return False+ if self.top_level_field is not None:+ value = payload.get(self.top_level_field)+ if not isinstance(value, str) or value.strip().lower() not in self.top_level_values:+ return False+ error = payload.get("error")+ if self.error_identifiers or self.error_params is not None:+ if not isinstance(error, dict):+ return False+ if self.error_identifiers:+ identifiers = {+ value.strip().lower() for value in (error.get("type"), error.get("code")) if isinstance(value, str)+ }+ if self.error_identifiers.isdisjoint(identifiers):+ return False+ if self.error_params is not None and error.get("param") not in self.error_params:+ return False+ return True+++@dataclass(frozen=True)+class _ProtocolObservationTaxonomy:+ """One protocol's request shape and response evidence table.++ The request path and body are part of the same authority as the response+ taxonomy. OpenAI probes deliberately provide the common ``model`` field+ while omitting the candidate-specific ``input`` or ``messages`` field, so+ each endpoint reaches its own protocol-shaped validation error.+ """++ request_path: str+ request_body: Mapping[str, Any]+ oauth_path: str | None+ evidence_rules: tuple[_ProtocolEvidenceRule, ...]+++_SUCCESS_STATUSES = frozenset(range(200, 300))+_REQUEST_ERROR_STATUSES = frozenset({400, 404, 422})+_AUTHENTICATION_ERROR_STATUSES = frozenset({401, 403})+_RATE_LIMIT_STATUSES = frozenset({429})+_SERVER_ERROR_STATUSES = frozenset(range(500, 600))++_REQUEST_ERROR_IDENTIFIERS = frozenset(+ {+ "invalid_parameter",+ "invalid_request_error",+ "validation_error",+ }+)+_MODEL_ERROR_IDENTIFIERS = frozenset({"model_not_found", "not_found_error"})+_AUTHENTICATION_ERROR_IDENTIFIERS = frozenset({"authentication_error", "invalid_api_key", "permission_error"})+_SERVER_ERROR_IDENTIFIERS = frozenset({"api_error", "internal_error", "overloaded", "overloaded_error", "server_error"})+_RATE_LIMIT_ERROR_IDENTIFIERS = frozenset({"rate_limit_error", "rate_limit_exceeded"})++_OPENAI_RESPONSES_PARAMS = frozenset(+ {+ "input",+ "instructions",+ "max_output_tokens",+ "previous_response_id",+ "reasoning",+ "text",+ "truncation",+ }+)+_OPENAI_CHAT_PARAMS = frozenset(+ {+ "messages",+ "max_completion_tokens",+ "max_tokens",+ "response_format",+ "stop",+ "temperature",+ "tool_choice",+ "top_p",+ }+)+++def _openai_evidence_rules(+ success_objects: frozenset[str],+ request_params: frozenset[str],+) -> tuple[_ProtocolEvidenceRule, ...]:+ return (+ _ProtocolEvidenceRule(+ statuses=_SUCCESS_STATUSES,+ top_level_field="object",+ top_level_values=success_objects,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ ),+ _ProtocolEvidenceRule(+ statuses=_REQUEST_ERROR_STATUSES,+ error_identifiers=_REQUEST_ERROR_IDENTIFIERS,+ error_params=request_params,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ ),+ _ProtocolEvidenceRule(+ statuses=frozenset({404}),+ error_identifiers=_MODEL_ERROR_IDENTIFIERS,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ ),+ _ProtocolEvidenceRule(+ statuses=_AUTHENTICATION_ERROR_STATUSES,+ error_params=request_params,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.REJECTED,+ ),+ _ProtocolEvidenceRule(+ statuses=_AUTHENTICATION_ERROR_STATUSES,+ error_identifiers=_AUTHENTICATION_ERROR_IDENTIFIERS,+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.REJECTED,+ ),+ _ProtocolEvidenceRule(+ statuses=_SERVER_ERROR_STATUSES,+ error_identifiers=_SERVER_ERROR_IDENTIFIERS,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ ),+ _ProtocolEvidenceRule(+ statuses=_RATE_LIMIT_STATUSES,+ error_identifiers=_RATE_LIMIT_ERROR_IDENTIFIERS,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ ),+ )+++_PROTOCOL_OBSERVATION_TAXONOMY = {+ "anthropic": _ProtocolObservationTaxonomy(+ request_path="/v1/messages",+ request_body={+ "model": "__avibe_model_hub_probe__",+ "max_tokens": 1,+ "messages": [{"role": "user", "content": "ping"}],+ },+ oauth_path="/v1/messages?beta=true",+ evidence_rules=(+ _ProtocolEvidenceRule(+ statuses=_SUCCESS_STATUSES,+ top_level_field="type",+ top_level_values=frozenset({"message"}),+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ ),+ _ProtocolEvidenceRule(+ statuses=_REQUEST_ERROR_STATUSES,+ top_level_field="type",+ top_level_values=frozenset({"error"}),+ error_identifiers=_REQUEST_ERROR_IDENTIFIERS | _MODEL_ERROR_IDENTIFIERS,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ ),+ _ProtocolEvidenceRule(+ statuses=_AUTHENTICATION_ERROR_STATUSES,+ top_level_field="type",+ top_level_values=frozenset({"error"}),+ error_identifiers=_AUTHENTICATION_ERROR_IDENTIFIERS,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.REJECTED,+ ),+ _ProtocolEvidenceRule(+ statuses=_SERVER_ERROR_STATUSES,+ top_level_field="type",+ top_level_values=frozenset({"error"}),+ error_identifiers=_SERVER_ERROR_IDENTIFIERS,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ ),+ _ProtocolEvidenceRule(+ statuses=_RATE_LIMIT_STATUSES,+ top_level_field="type",+ top_level_values=frozenset({"error"}),+ error_identifiers=_RATE_LIMIT_ERROR_IDENTIFIERS,+ protocol=_ProtocolProof.PROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ ),+ ),+ ),+ "openai_responses": _ProtocolObservationTaxonomy(+ request_path="/v1/responses",+ request_body={"model": "__avibe_model_hub_probe__"},+ oauth_path="/backend-api/codex/responses",+ evidence_rules=_openai_evidence_rules(+ frozenset({"response"}),+ _OPENAI_RESPONSES_PARAMS,+ ),+ ),+ "openai_chat": _ProtocolObservationTaxonomy(+ request_path="/v1/chat/completions",+ request_body={"model": "__avibe_model_hub_probe__"},+ oauth_path=None,+ evidence_rules=_openai_evidence_rules(+ frozenset({"chat.completion", "chat.completion.chunk"}),+ _OPENAI_CHAT_PARAMS,+ ),+ ),+}+++def _parse_protocol_authenticated_evidence(+ protocol: str,+ status: int,+ body: str | bytes,+) -> _ProtocolEvidence:+ """Classify protocol proof and authentication as independent evidence.++ Observation is sequential and stops at the first authenticated proof.+ Status, vendor, URL, and probe order never prove a protocol or credential+ by themselves; a generic response therefore remains unproven even when its+ HTTP status is conventionally associated with authentication or validation.+ A structured authentication error may prove credential rejection without+ distinguishing the attempted OpenAI protocol. Accepted, rejected, and unknown+ are all positive table entries; there is no default authentication result for+ a shaped response. The observation result exposes a non-null protocol if and+ only if a protocol-specific response shape also proves authentication+ acceptance.+ """++ try:+ payload = json.loads(body)+ except (TypeError, UnicodeDecodeError, ValueError):+ return _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )+ if not isinstance(payload, dict):+ return _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )++ taxonomy = _PROTOCOL_OBSERVATION_TAXONOMY.get(protocol)+ for rule in taxonomy.evidence_rules if taxonomy is not None else ():+ if rule.matches(status, payload):+ return _ProtocolEvidence(+ protocol=rule.protocol,+ authentication=rule.authentication,+ )+ return _ProtocolEvidence(+ protocol=(+ _ProtocolProof.PROVEN if _response_shape_proves_protocol(protocol, payload) else _ProtocolProof.UNPROVEN+ ),+ authentication=_AuthenticationEvidence.UNKNOWN,+ )+++async def _probe_protocol_response(+ *,+ vendor: str,+ protocol: str,+ base_url: str | None,+ secret: str,+ timeout: float = 15.0,+) -> _ProtocolEvidence:+ """Require a response from the candidate protocol's distinct request path."""++ root = base_url or _OFFICIAL_BASE_URLS.get(vendor)+ if not root:+ raise EngineClientError("source requires a base URL for protocol observation")+ taxonomy = _PROTOCOL_OBSERVATION_TAXONOMY.get(protocol)+ if taxonomy is None:+ raise EngineClientError("unsupported source protocol")+ endpoint = taxonomy.request_path.removeprefix("/v1")+ try:+ url = normalize_model_hub_base_url(root, append_path=endpoint)+ except (TypeError, ValueError):+ raise EngineClientError("source base URL is invalid")+ assert url is not None+ headers = {+ "Authorization": f"Bearer {secret}",+ "Accept": "application/json",+ }+ if protocol == "anthropic":+ headers = {+ "x-api-key": secret,+ "anthropic-version": "2023-06-01",+ "Accept": "application/json",+ }+ client_timeout = aiohttp.ClientTimeout(total=timeout)+ try:+ async with aiohttp.ClientSession(timeout=client_timeout) as session:+ async with session.post(+ url,+ headers=headers,+ json=dict(taxonomy.request_body),+ allow_redirects=False,+ ) as response:+ body = await response.content.read(64 * 1024)+ return _parse_protocol_authenticated_evidence(+ protocol,+ response.status,+ body,+ )+ except asyncio.TimeoutError:+ raise EngineClientError("protocol observation timed out", error_type="timeout") from None+ except aiohttp.ClientError:+ raise EngineClientError(+ "protocol observation failed",+ error_type="network_error",+ ) from None@dataclass(frozen=True)class _AuthRecord:identity: str+ auth_index: strname: strprovider: strfingerprint: str+ account_id: str | None = None+++def _response_shape_proves_protocol(+ protocol: str,+ body: Mapping[str, Any],+) -> bool:+ """Recognize protocol-specific shapes without inferring authentication."""++ if protocol == "anthropic":+ error = body.get("error")+ return body.get("type") == "message" or (+ body.get("type") == "error" and isinstance(error, dict) and isinstance(error.get("type"), str)+ )+ error = body.get("error")+ if protocol == "openai_responses":+ return body.get("object") == "response" or (+ isinstance(error, dict) and error.get("param") in _OPENAI_RESPONSES_PARAMS+ )+ if protocol == "openai_chat":+ return body.get("object") in {"chat.completion", "chat.completion.chunk"} or (+ isinstance(error, dict) and error.get("param") in _OPENAI_CHAT_PARAMS+ )+ return False+++def _probe_oauth_protocol_response(+ *,+ client: EngineClient,+ auth: _AuthRecord,+ vendor: str,+ protocol: str,+) -> _ProtocolEvidence:+ """Probe one allowlisted OAuth upstream through the engine-held credential."""++ taxonomy = _PROTOCOL_OBSERVATION_TAXONOMY.get(protocol)+ if taxonomy is None:+ raise EngineClientError("unsupported source protocol")+ if vendor == "anthropic" and protocol == "anthropic":+ url = f"https://api.anthropic.com{taxonomy.oauth_path or taxonomy.request_path}"+ headers = {+ "Authorization": "Bearer $TOKEN$",+ "Accept": "application/json",+ "Content-Type": "application/json",+ "Anthropic-Version": "2023-06-01",+ "Anthropic-Beta": "oauth-2025-04-20",+ "X-App": "cli",+ }+ elif vendor in {"openai", "codex"} and protocol == "openai_responses":+ url = f"https://chatgpt.com{taxonomy.oauth_path or taxonomy.request_path}"+ headers = {+ "Authorization": "Bearer $TOKEN$",+ "Accept": "application/json",+ "Content-Type": "application/json",+ "Originator": "codex-tui",+ }+ if auth.account_id:+ headers["Chatgpt-Account-Id"] = auth.account_id+ else:+ raise EngineClientError(+ "OAuth credential does not support this protocol path",+ status_code=404,+ )+ payload = client.management_request(+ "POST",+ "/api-call",+ payload={+ "auth_index": auth.auth_index,+ "method": "POST",+ "url": url,+ "header": headers,+ "data": json.dumps(taxonomy.request_body, separators=(",", ":")),+ },+ )+ status = payload.get("status_code")+ if not isinstance(status, int) or isinstance(status, bool):+ raise EngineClientError(+ "protocol observation returned an invalid status",+ error_type="invalid_json",+ )+ body = payload.get("body")+ return _parse_protocol_authenticated_evidence(+ protocol,+ status,+ body if isinstance(body, str) else "",+ )@dataclass@@ -177,6 +606,65 @@ class CLIProxyEngineAdapter:base_url=base_url,)+ async def retarget_api_key_credential(+ self,+ credential_ref: str,+ vendor: str,+ protocol: str,+ base_url: str | None,+ ) -> str:+ metadata = await asyncio.to_thread(+ self.state_store.credential_metadata,+ credential_ref,+ )+ normalized_vendor = vendor.strip().lower()+ if (+ metadata.get("kind") != "api_key"+ or metadata.get("vendor") != normalized_vendor+ or metadata.get("protocol") != protocol+ ):+ raise EngineStateError("credential does not match retarget request")+ secret = await asyncio.to_thread(+ self.state_store.read_api_key,+ credential_ref,+ )+ return await asyncio.to_thread(+ self.state_store.store_api_key,+ secret,+ vendor=normalized_vendor,+ protocol=protocol,+ base_url=base_url,+ )++ async def credential_supports_refresh(self, credential_ref: str) -> bool:+ metadata = await asyncio.to_thread(+ self.state_store.credential_metadata,+ credential_ref,+ )+ return metadata.get("kind") == "oauth"++ async def provision_transient_credential(+ self,+ vendor: str,+ secret: str,+ base_url: str | None,+ ) -> str:+ """Store an unbound observation key until the observation settles.++ The observation seam determines protocol from upstream responses, so the+ temporary record deliberately uses a neutral engine-store protocol marker;+ ``observe_source`` reads only the opaque ref's secret and never treats that+ marker as a protocol conclusion.+ """++ return await asyncio.to_thread(+ self.state_store.store_api_key,+ secret,+ vendor=vendor,+ protocol="openai_chat",+ base_url=base_url,+ )+async def revoke_credential(self, credential_ref: str) -> None:await asyncio.to_thread(self.state_store.assert_credential_unbound,@@ -273,12 +761,180 @@ class CLIProxyEngineAdapter:except EngineClientError as exc:raise ModelDiscoveryError("model discovery failed") from exc+ async def observe_source(+ self,+ vendor: str,+ base_url: str | None,+ credential_ref: str,+ protocol_order: Sequence[str],+ ) -> SourceObservation:+ """Observe sequentially and stop at the first authenticated proof.++ ``protocol_order`` orders attempts only. A protocol-specific response+ with accepted authentication proves the current attempt and terminates+ observation. A shaped credential rejection is recorded while later+ candidates continue. Vendor, URL, and order never create a conclusion;+ exhausting the order without any shaped response is the ambiguous+ boundary. This is the require-proven reading of AC-27.+ """++ metadata = await asyncio.to_thread(+ self.state_store.credential_metadata,+ credential_ref,+ )+ normalized_vendor = vendor.strip().lower()+ try:+ normalized_base_url = normalize_model_hub_base_url(base_url)+ except (TypeError, ValueError):+ raise EngineStateError("invalid source base URL") from None+ if metadata.get("vendor") != normalized_vendor:+ raise EngineStateError("credential does not match observation target")+ credential_kind = metadata.get("kind")+ secret: str | None = None+ oauth_auth: _AuthRecord | None = None+ if credential_kind == "api_key":+ if metadata.get("base_url") != normalized_base_url:+ raise EngineStateError("credential does not match observation target")+ secret = await asyncio.to_thread(self.state_store.read_api_key, credential_ref)+ elif credential_kind == "oauth":+ if normalized_base_url is not None:+ raise EngineStateError("credential does not match observation target")+ client = await asyncio.to_thread(self.supervisor.client)+ inventory = await asyncio.to_thread(_auth_inventory, client)+ auth_name = str(metadata.get("auth_name") or "")+ matches = [auth for auth in inventory.values() if auth.name == auth_name or auth.identity == auth_name]+ if len(matches) != 1 or not matches[0].auth_index:+ raise EngineStateError("OAuth credential binding is unavailable")+ oauth_auth = matches[0]+ else:+ raise EngineStateError("credential does not match observation target")++ failures: list[EngineClientError] = []+ received_rejection = False+ received_proven_unknown = False+ received_unproven_response = False+ for protocol in protocol_order:+ if protocol not in SOURCE_PROTOCOLS:+ raise EngineStateError("unsupported source protocol")+ try:+ if credential_kind == "api_key":+ evidence = await _probe_protocol_response(+ vendor=normalized_vendor,+ protocol=protocol,+ base_url=base_url,+ secret=secret or "",+ )+ else:+ assert oauth_auth is not None+ evidence = await asyncio.to_thread(+ _probe_oauth_protocol_response,+ client=client,+ auth=oauth_auth,+ vendor=normalized_vendor,+ protocol=protocol,+ )+ except EngineClientError as exc:+ failures.append(exc)+ continue+ if evidence.authentication is _AuthenticationEvidence.REJECTED:+ received_rejection = True+ continue+ if evidence.protocol is _ProtocolProof.PROVEN:+ if evidence.authentication is _AuthenticationEvidence.UNKNOWN:+ received_proven_unknown = True+ continue+ else:+ received_unproven_response = True+ continue+ try:+ if credential_kind == "api_key":+ models = await probe_models(+ vendor=normalized_vendor,+ protocol=protocol,+ base_url=base_url,+ secret=secret or "",+ )+ else:+ models = await self.discover_models(+ normalized_vendor,+ protocol,+ None,+ credential_ref,+ )+ except (EngineClientError, ModelDiscoveryError):+ discovery = ObservationDiscovery.FAILED+ models = ()+ else:+ discovery = ObservationDiscovery.SUCCEEDED+ return make_source_observation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol=protocol,+ discovery=discovery,+ model_ids=tuple(models),+ )++ if received_rejection:+ return make_source_observation(+ outcome=ObservationOutcome.AUTHENTICATION_FAILED,+ reachable=True,+ authenticated=False,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ if received_proven_unknown:+ return make_source_observation(+ outcome=ObservationOutcome.ADAPTER_ERROR,+ reachable=True,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ if received_unproven_response:+ return make_source_observation(+ outcome=ObservationOutcome.AMBIGUOUS,+ reachable=True,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ if any(error.error_type == "timeout" for error in failures):+ return make_source_observation(+ outcome=ObservationOutcome.TIMEOUT,+ reachable=None,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ if any(error.error_type in {"network_error", "ConnectionError", "URLError"} for error in failures):+ return make_source_observation(+ outcome=ObservationOutcome.UNREACHABLE,+ reachable=False,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+ return make_source_observation(+ outcome=ObservationOutcome.ADAPTER_ERROR,+ reachable=None,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ model_ids=(),+ )+async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:await asyncio.to_thread(self.state_store.validate_source_id, source_id)normalized_vendor = vendor.strip().lower()endpoint = _OAUTH_ENDPOINTS.get(normalized_vendor)if endpoint is None:- raise EngineStateError("unsupported OAuth vendor")+ raise EngineStateError("OAuth vendor lacks Model Hub response-backed observation")engine_endpoint, callback_provider, auth_provider = endpointwith self._oauth_lock:self._expire_oauth_flows_locked()@@ -417,9 +1073,7 @@ class CLIProxyEngineAdapter:if source is None:raise EngineStateError("source is not registered")if source.allowed_origins and origin not in source.allowed_origins:- raise OriginNotAllowedError(- f"origin {origin!r} is not allowed to use source {source_id!r}"- )+ raise OriginNotAllowedError(f"origin {origin!r} is not allowed to use source {source_id!r}")try:client = await asyncio.to_thread(self.supervisor.client)except EngineUnavailableError:@@ -692,9 +1346,14 @@ def _auth_inventory(client: EngineClient) -> dict[str, _AuthRecord]:for item in files:if not isinstance(item, dict):continue- identity = str(item.get("id") or item.get("auth_index") or item.get("name") or "").strip()+ auth_index = str(item.get("auth_index") or "").strip()+ identity = str(item.get("id") or auth_index or item.get("name") or "").strip()name = str(item.get("name") or item.get("id") or "").strip()provider = str(item.get("provider") or item.get("type") or "").strip().lower()+ id_token = item.get("id_token")+ account_id = (+ str(id_token.get("chatgpt_account_id") or "").strip() or None if isinstance(id_token, dict) else None+ )if identity and name and provider:fingerprint = json.dumps({@@ -715,9 +1374,11 @@ def _auth_inventory(client: EngineClient) -> dict[str, _AuthRecord]:)inventory[identity] = _AuthRecord(identity=identity,+ auth_index=auth_index,name=name,provider=provider,fingerprint=fingerprint,+ account_id=account_id,)return inventorydiff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex e31ebe259..2b9542010 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -11,6 +11,7 @@ from typing import Any, AsyncIterator, Mappingimport aiohttp+from config.v2_config import normalize_model_hub_base_urlfrom core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKindfrom vibe.model_hub_runtime.state import SourceRecord@@ -362,16 +363,11 @@ async def probe_models(root = base_url or _OFFICIAL_BASE_URLS.get(normalized_vendor)if not root:raise EngineClientError("source requires a base URL for model discovery")- parsed = urllib.parse.urlparse(root)- if (- parsed.scheme not in {"http", "https"}- or not parsed.netloc- or parsed.username- or parsed.password- or parsed.query- or parsed.fragment- ):+ try:+ url = normalize_model_hub_base_url(root, append_path="/models")+ except (TypeError, ValueError):raise EngineClientError("source base URL is invalid")+ assert url is not Noneheaders = {"Authorization": f"Bearer {secret}", "Accept": "application/json"}if protocol == "anthropic":headers = {@@ -379,7 +375,6 @@ async def probe_models("anthropic-version": "2023-06-01","Accept": "application/json",}- url = f"{root.rstrip('/')}/models"client_timeout = aiohttp.ClientTimeout(total=timeout)try:async with aiohttp.ClientSession(timeout=client_timeout) as session:diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex 77e80ca0f..b2597112f 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -11,7 +11,8 @@ import threadingfrom dataclasses import asdict, dataclassfrom pathlib import Pathfrom typing import Any, Sequence-from urllib.parse import urlparse++from config.v2_config import normalize_model_hub_base_url_CREDENTIAL_REF_RE = re.compile(r"^cred_[A-Za-z0-9_-]{6,128}$")@@ -502,20 +503,10 @@ def _validated_source_id(value: str) -> str:def _validated_base_url(value: str | None) -> str | None:- if value is None:- return None- normalized = str(value).strip().rstrip("/")- parsed = urlparse(normalized)- if (- parsed.scheme not in {"http", "https"}- or not parsed.netloc- or parsed.username- or parsed.password- or parsed.query- or parsed.fragment- ):+ try:+ return normalize_model_hub_base_url(value)+ except (TypeError, ValueError):raise EngineStateError("invalid source base URL")- return normalizeddef _validate_source_target(vendor: str, protocol: str, base_url: str | None) -> None:diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex a457ab77d..d5ef9609f 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -3141,6 +3141,19 @@ def model_hub_sources_get():return _model_hub_error(exc)[email protected]("/api/models/sources/observe", methods=["POST"])+async def model_hub_sources_observe_post():+ from core.handlers.model_hub import ModelHubError++ try:+ result = await _model_hub_service().observe_source(+ _model_hub_json_object("discovery_failed")+ )+ return _model_hub_success(**result)+ except ModelHubError as exc:+ return _model_hub_error(exc)++@app.route("/api/models/sources", methods=["POST"])async def model_hub_sources_post():from core.handlers.model_hub import ModelHubError@@ -3157,8 +3170,8 @@ async def model_hub_sources_patch(source_id):from core.handlers.model_hub import ModelHubErrortry:- source = await _model_hub_service().patch_source(source_id, _model_hub_json_object())- return _model_hub_success(source=source)+ result = await _model_hub_service().patch_source(source_id, _model_hub_json_object())+ return _model_hub_success(**result)except ModelHubError as exc:return _model_hub_error(exc)@@ -3197,8 +3210,8 @@ async def model_hub_sources_delete(source_id):try:force = str(request.args.get("force") or "").lower() in _TRUE_BOOL_STRINGS- await _model_hub_service().delete_source(source_id, force=force)- return _model_hub_success()+ result = await _model_hub_service().delete_source(source_id, force=force)+ return _model_hub_success(**result)except ModelHubError as exc:return _model_hub_error(exc)@@ -3208,8 +3221,16 @@ async def model_hub_sources_refresh(source_id):from core.handlers.model_hub import ModelHubErrortry:- source, discovered = await _model_hub_service().refresh_source(source_id)- return _model_hub_success(source=source, discovered=discovered)+ payload = request.json+ if payload is None:+ payload = {}+ if not isinstance(payload, dict) or set(payload) - {"force"}:+ raise ModelHubError("invalid_source_order")+ result = await _model_hub_service().refresh_source(+ source_id,+ force=payload.get("force") is True,+ )+ return _model_hub_success(**result)except ModelHubError as exc:return _model_hub_error(exc)@@ -3262,20 +3283,6 @@ async def model_hub_agent_mode_patch(backend):return _model_hub_error(exc)[email protected]("/api/models/agents/<backend>/mappings", methods=["PUT"])-async def model_hub_agent_mappings_put(backend):- from core.handlers.model_hub import ModelHubError-- try:- agent = await _model_hub_service().set_mappings(- backend,- _model_hub_json_object("mapping_target_unavailable").get("mappings"),- )- return _model_hub_success(agent=agent)- except ModelHubError as exc:- return _model_hub_error(exc)--@app.route("/api/models/agents/opencode/menu", methods=["PUT"])async def model_hub_opencode_menu_put():from core.handlers.model_hub import ModelHubError@@ -3330,12 +3337,12 @@ async def model_hub_source_models_delete(source_id, model_id):try:payload = _model_hub_json_object("mapping_target_unavailable")- source = await _model_hub_service().delete_custom_model(+ result = await _model_hub_service().delete_custom_model(source_id,model_id,force=payload.get("force") is True,)- return _model_hub_success(source=source)+ return _model_hub_success(**result)except ModelHubError as exc:return _model_hub_error(exc)@@ -3369,6 +3376,24 @@ def model_hub_agent_chain_get(backend):return _model_hub_error(exc)[email protected]("/api/models/agents/<backend>/chain", methods=["PUT"])+async def model_hub_agent_chain_put(backend):+ from core.handlers.model_hub import ModelHubError++ try:+ model_id = str(request.args.get("model") or "").strip()+ if not model_id:+ raise ModelHubError("mapping_target_unavailable", status=409)+ result = await _model_hub_service().set_agent_chain(+ backend,+ model_id,+ _model_hub_json_object("mapping_target_unavailable"),+ )+ return _model_hub_success(**result)+ except ModelHubError as exc:+ return _model_hub_error(exc)++@app.route("/api/models/agents/<backend>/probe", methods=["POST"])async def model_hub_agent_probe_post(backend):from core.handlers.model_hub import ModelHubError