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): search service Sources (S1a) (#2868)
Call White68a59d11e9de
diff --git a/config/v2_config.py b/config/v2_config.pyindex 2de2cc94a..f796577a3 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -207,7 +207,7 @@ def normalize_model_hub_vendor_id(value: object) -> str:def validate_model_hub_protocol_vendor(vendor: str, protocol: str) -> None:- """Keep Google's v11 explicit custom admission consistent across consumers."""+ """Validate protocol/vendor combinations that are intrinsic to persisted shapes."""if protocol == "google" and vendor != "custom":raise ValueError("Google Sources require the custom vendor")@@ -2329,7 +2329,7 @@ class ModelHubSourceConfig:kind: Literal["subscription", "api_key"]vendor: strdisplay_name: str- protocol: Literal["anthropic", "openai_responses", "openai_chat", "google"]+ protocol: Literal["anthropic", "openai_responses", "openai_chat", "google", "search"]supply_channel: Literal["native_cli", "hub"]billing: Literal["monthly", "metered"]state: ModelHubSourceStateConfig@@ -2400,6 +2400,7 @@ class ModelHubSourceConfig:"openai_responses","openai_chat","google",+ "search",}:raise ValueError("Config 'model_hub.sources.protocol' is invalid")validate_model_hub_protocol_vendor(vendor, protocol)@@ -2453,6 +2454,11 @@ class ModelHubSourceConfig: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 protocol == "search" and (+ kind != "api_key" or supply_channel != "hub" or billing != "metered"+ or models or base_url is not None+ ):+ raise ValueError("Search Sources are tool-only metered hub API keys without a base URL")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":@@ -3091,6 +3097,18 @@ def model_hub_executor_order(value: object, *, tool: str) -> tuple[str, ...]:return tuple(value)+def model_hub_service_order(value: object, *, tool: str) -> tuple[str, ...]:+ """A server-owned automatic order for tool-only search Sources."""++ if (+ not isinstance(value, list)+ or not all(is_model_hub_source_id(item) for item in value)+ or len(set(value)) != len(value)+ ):+ raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.service_order' must be distinct Source ids")+ return tuple(value)++@dataclass(frozen=True)class ModelHubImageModelChoice:"""The image model a user chose as ``image_generate``'s default."""@@ -3118,12 +3136,14 @@ class ModelHubHostedToolConfig:"""One hosted tool's user settings (``vibey-hosted-tools.md`` §3.3).``enabled`` defaults to on. ``executor_order`` (search tools) is the Source order the user wants executors- tried in, None for automatic; ``default_image`` (``image_generate``, persisted as ``default_model``) is the+ tried in, None for automatic; ``service_order`` (``web_search``) is the server-owned automatic order of+ tool-only search Sources; ``default_image`` (``image_generate``, persisted as ``default_model``) is thechosen default image model, None for the catalog default. Both are saved values, never resolved ones."""enabled: bool = Trueexecutor_order: Optional[tuple[str, ...]] = None+ service_order: Optional[tuple[str, ...]] = Nonedefault_image: Optional[ModelHubImageModelChoice] = None@classmethod@@ -3132,7 +3152,11 @@ class ModelHubHostedToolConfig:if not isinstance(payload, dict):raise ValueError(f"Config 'model_hub.hosted_tools.{tool}' must be an object")- known = {"enabled"} | ({"executor_order"} if tool in MODEL_HUB_SEARCH_TOOLS else {"default_model"})+ known = {"enabled"} | (+ ({"executor_order", "service_order"} if tool == "web_search" else {"executor_order"})+ if tool in MODEL_HUB_SEARCH_TOOLS+ else {"default_model"}+ )unknown = set(payload) - knownif unknown:logger.warning("Config 'model_hub.hosted_tools.%s' ignores unknown fields %s", tool, sorted(unknown))@@ -3142,10 +3166,12 @@ class ModelHubHostedToolConfig:# Only the fields this tool knows are read; another tool's field was ignored above. A field is decided by its# presence: the writer omits an unset one, so a present null is damage and goes through the grammar.has_order = "executor_order" in known and "executor_order" in payload+ has_service_order = "service_order" in known and "service_order" in payloadhas_default = "default_model" in known and "default_model" in payloadreturn cls(enabled=enabled,executor_order=model_hub_executor_order(payload["executor_order"], tool=tool) if has_order else None,+ service_order=model_hub_service_order(payload["service_order"], tool=tool) if has_service_order else None,default_image=(ModelHubImageModelChoice.from_payload(payload["default_model"], tool=tool) if has_default else None),@@ -3155,6 +3181,8 @@ class ModelHubHostedToolConfig:out: dict[str, Any] = {"enabled": self.enabled}if self.executor_order is not None:out["executor_order"] = list(self.executor_order)+ if self.service_order is not None:+ out["service_order"] = list(self.service_order)if self.default_image is not None:out["default_model"] = self.default_image.to_payload()return out@@ -3234,7 +3262,7 @@ class ModelHubConfig:source: ModelHubSourceConfig,backend: str,) -> bool:- if backend not in MODEL_HUB_BACKENDS:+ if backend not in MODEL_HUB_BACKENDS or source.protocol == "search":return Falseif source.supply_channel == "hub":return Truediff --git a/core/handlers/model_hub/__init__.py b/core/handlers/model_hub/__init__.pyindex c15748656..b3270d0e2 100644--- a/core/handlers/model_hub/__init__.py+++ b/core/handlers/model_hub/__init__.py@@ -8,6 +8,7 @@ from .service import (ensure_runtime_dependency,load_opencode_public_models,runtime_dependency_payload,+ search_capability_for_source,)__all__ = [@@ -18,4 +19,5 @@ __all__ = ["ensure_runtime_dependency","load_opencode_public_models","runtime_dependency_payload",+ "search_capability_for_source",]diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex 81ddde9eb..94de03c66 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -1,9 +1,12 @@-"""Model Hub EngineAdapter interface. FINAL CONTRACT v16 (2026-10-16).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v17 (2026-10-19).This file is the canonical adapter boundary and must remain byte-identical to``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:credential custody, protocol observation, model discovery, OAuth, invocation,-and cleanup. It never chooses or reorders Route hops, classifies cross-Source+and cleanup. Model protocol operations use ``MODEL_PROTOCOLS`` (the four invocable+wire protocols); ``SOURCE_PROTOCOLS`` adds the tool-only ``search`` value only for+stored/created Source shapes. It never chooses or reorders Route hops, classifies+cross-Sourcefallthrough, or exposes credential material. Contract changes route through theorchestrator and land with every affected consumer on the same tested head."""@@ -19,7 +22,12 @@ from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocfrom .stream_wire import ProtocolSSEState, ProtocolUsageReportENGINE_TRANSPORT_TIMEOUT_SECONDS: Final = 60.0-SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat", "google")+# Model invocation/observation is a narrower domain than stored Sources.+MODEL_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat", "google")+# Source persistence/admission adds the tool-only search protocol.+SOURCE_PROTOCOLS = MODEL_PROTOCOLS + ("search",)+SEARCH_RESPONSE_MAX_BYTES: Final = 8 * 1024 * 1024+SEARCH_TRANSPORT_TIMEOUT_SECONDS: Final = 30.0OBSERVATION_OUTCOMES = ("observed","ambiguous",@@ -70,13 +78,34 @@ class OAuthCredentialRejectedError(RuntimeError):"""+@dataclass(frozen=True)+class SearchResponse:+ """Bounded response from one catalog search endpoint.++ The body is opaque to this boundary. It contains no credential material;+ the adapter reads the key from custody only while making the request.+ """++ http_status: int | None+ headers: Mapping[str, str]+ body: bytes | None+ error: Literal["", "timeout", "connection", "redirect", "body_too_large", "invalid_endpoint", "cancelled"] = ""+ on_sent_fired: bool = False+ response_received_at: datetime | None = None+++@dataclass(frozen=True)+class SearchCredentialCheck:+ outcome: Literal["pass", "balance", "limit", "invalid", "unknown"]++@dataclass(frozen=True)class SourceBinding:"""Engine-side registration of one hub-channel source (projection of config)."""source_id: strvendor: str- protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "google"+ protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "google" | "search"base_url: str | None # None => vendor official defaultcredential_ref: str # opaque handle; never secret materialallowed_origins: tuple[str, ...] # agent names allowed to draw on this@@ -258,7 +287,7 @@ OBSERVATION_TERMINAL_RULES: Mapping[ObservationOutcome.OBSERVED: ObservationTerminalRule(reachable=frozenset({True}),authenticated=frozenset({True}),- protocols=frozenset(SOURCE_PROTOCOLS),+ protocols=frozenset(MODEL_PROTOCOLS),discoveries=frozenset({ObservationDiscovery.SUCCEEDED,@@ -519,8 +548,9 @@ class EngineAdapter(Protocol):auth_scheme: str | None = None,on_reserved: Callable[[str], None] | None = None,) -> str:- """Store an API-key secret in the ENGINE-OWNED credential store and- return the opaque ``credential_ref``.+ """Store an API-key secret in the Model Hub credential store. Search+ Sources use this same opaque-ref custody, but are never rendered into+ engine configuration or sent through the engine.``secret`` is transient: the adapter must never log it; L2 must neverpersist it (config stores refs only). When supplied, ``on_reserved`` is@@ -532,6 +562,36 @@ class EngineAdapter(Protocol):an explicit static transport; omission retains legacy semantics."""...+ async def check_search_credential(+ self,+ credential_ref: str,+ catalog: Mapping[str, Any],+ ) -> SearchCredentialCheck:+ """Run one catalog free check without exposing its key or response."""+ ...++ async def search(+ self,+ source_id: str,+ vendor: str,+ service_id: str,+ credential_ref: str,+ request: Mapping[str, Any],+ *,+ on_sent: Callable[[], None] | None = None,+ ) -> SearchResponse:+ """Make exactly one catalog-host search request from Model Hub custody.++ ``on_sent`` fires once after the connection (including TLS) is ready and+ immediately before aiohttp writes this request. A callback failure stops+ the request before any request bytes are sent.+ """+ ...++ async def revoke_search_credential(self, credential_ref: str) -> None:+ """Remove a search-only credential from Model Hub custody."""+ ...+async def provision_oauth_credential(self,source_id: str,@@ -673,6 +733,16 @@ class EngineAdapter(Protocol):"""...+ async def revoke_search_credential(self, credential_ref: str) -> None:+ """Retire an unbound tool-only key under durable search-only intent.++ Preserve API-key namespace and identity checks, but never access the+ model engine or its configs, even when the document is already absent+ or corrupt. The caller journals this operation before unlinking so+ replay does not infer a lost protocol from credential metadata.+ """+ ...+async def provision_transient_credential(self,vendor: str,diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex ba4998c65..56cff8d75 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -2713,7 +2713,7 @@ class TurnCorrelationRegistry:self.store.put({- "contract_version": 16,+ "contract_version": 17,"turn_id": normalized_turn_id,"ts": ts or _utc_now_iso(),"agent": trace.agent,diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.pyindex 0280e8e4a..816fae44a 100644--- a/core/handlers/model_hub/resolver.py+++ b/core/handlers/model_hub/resolver.py@@ -271,7 +271,7 @@ def source_model_retired(source: ModelHubSourceConfig, model_id: str) -> bool:def source_supports_passthrough(source: ModelHubSourceConfig) -> bool:- return source.kind == "api_key" and source.supply_channel == "hub"+ return source.kind == "api_key" and source.supply_channel == "hub" and source.protocol != "search"def effective_model_route(diff --git a/core/handlers/model_hub/revocations.py b/core/handlers/model_hub/revocations.pyindex 4c83c6345..4ce9f3927 100644--- a/core/handlers/model_hub/revocations.py+++ b/core/handlers/model_hub/revocations.py@@ -15,6 +15,7 @@ from .state_file import write_state_documentRevocationOperation = Literal["revoke_credential","revoke_api_key_credential",+ "revoke_search_credential","cleanup_orphaned_oauth_material",]_REVOCATION_OPERATIONS = frozenset(get_args(RevocationOperation))diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.pyindex 996d4efdb..bb764c39b 100644--- a/core/handlers/model_hub/rpc.py+++ b/core/handlers/model_hub/rpc.py@@ -111,6 +111,8 @@ async def dispatch_model_hub_rpc(confirmed_remove_hops=payload.get("would_remove_hops"),confirmed_interruptions=payload.get("would_interrupt"),)+ if operation == "reenable_search_source":+ return await service.reenable_search_source(payload.get("source_id"))if operation == "list_agents":if payload.get("refresh_cli_presence") is True:await _refresh_agent_presence(service)diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex f75ea0e4f..8fba27f65 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -28,6 +28,7 @@ from config.v2_config import (ModelHubConfig,is_model_hub_model_id,model_hub_fixed_menu_ids,+ ModelHubHostedToolConfig,ModelHubMenuConfig,ModelHubModelConfig,ModelHubRouteConfig,@@ -67,6 +68,7 @@ from vibe.model_hub_runtime.api_key_vendors import (api_key_vendor_catalog,catalog_api_key_vendor_label,pinned_api_key_protocol,+ search_service,)from .adapter import (@@ -87,8 +89,9 @@ from .adapter import (RuntimePlatformUnsupportedError,ObservationDiscovery,ObservationOutcome,- SOURCE_PROTOCOLS,+ MODEL_PROTOCOLS,SourceObservation,+ SearchCredentialCheck,SourceBinding,make_source_observation,validate_source_observation,@@ -238,7 +241,7 @@ from .resolver import (source_supports_passthrough,source_runnable,)-from .revocations import CredentialRevocationJournal+from .revocations import CredentialRevocationJournal, PendingCredentialRevocation, RevocationOperationfrom .retry import (RECOVERY_ADMISSION_MARGIN_SECONDS,RECOVERY_EXHAUSTED_CODE,@@ -256,7 +259,7 @@ from .usage import (local_usage_day,)-CONTRACT_VERSION = 16+CONTRACT_VERSION = 17def seeded_source_name(vendor: str) -> str:@@ -379,8 +382,8 @@ def _described_as_unfit_for_agent_turns(match: Mapping[str, Any]) -> bool:)-AGENT_CHAIN_CONTRACT_VERSION = 16-PROBE_RESULT_CONTRACT_VERSION = 16+AGENT_CHAIN_CONTRACT_VERSION = 17+PROBE_RESULT_CONTRACT_VERSION = 17_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15_SOURCE_PROBE_TIMEOUT_SECONDS = 60# Background inventory refresh. The first tick doubles as the startup delay, so@@ -760,6 +763,9 @@ class UnavailableEngineAdapter:async def revoke_api_key_credential(self, credential_ref: str) -> None:raise EngineUnavailableError+ async def revoke_search_credential(self, credential_ref: str) -> None:+ raise EngineUnavailableError+async def sync_sources(self, bindings) -> None:raise EngineUnavailableError@@ -1102,6 +1108,48 @@ def _mask_credential(value: str) -> str:return f"{normalized[:prefix_length]}…{normalized[-4:]}"+def search_capability_for_source(source: ModelHubSourceConfig) -> dict[str, Any] | None:+ """Return the bundled search service when this Source is search-capable."""+ if not source.credential_ref:+ return None+ return search_service(source.vendor, source.protocol, source.base_url)+++def _search_service_for_source(source: ModelHubSourceConfig) -> dict[str, Any] | None:+ return search_capability_for_source(source)+++def _require_search_service_for_source(source: ModelHubSourceConfig) -> dict[str, Any]:+ """A retained Source may be readable without still supporting mutations."""+ service = _search_service_for_source(source)+ if service is None:+ raise ModelHubError("discovery_failed")+ return service+++def _maintain_search_service_order(config: ModelHubConfig, source_id: str, *, add: bool) -> None:+ setting = config.hosted_tools.get("web_search")+ existing = tuple(setting.service_order or ()) if setting is not None else ()+ if add:+ if source_id in existing:+ return+ order = (*existing, source_id)+ else:+ order = tuple(item for item in existing if item != source_id)+ if setting is None:+ if not add:+ return+ setting = ModelHubHostedToolConfig()+ config.hosted_tools["web_search"] = replace(setting, service_order=order)+++def _search_check_outcome(value: object) -> Literal["pass", "balance", "limit", "invalid", "unknown"]:+ if isinstance(value, SearchCredentialCheck):+ return value.outcome+ raw = getattr(value, "outcome", value)+ return raw if raw in {"pass", "balance", "limit", "invalid", "unknown"} else "unknown"++def _validated_base_url(value: object) -> Optional[str]:try:return normalize_model_hub_base_url(value)@@ -1142,6 +1190,8 @@ async def _acquire_credential_ref_with_cancellation_ownership(service: "ModelHubService",operation: Awaitable[str],rollback_source_id: str,+ *,+ rollback_operation: RevocationOperation | None = None,) -> str:"""Keep ownership of an engine ref when the caller is cancelled mid-provision."""@@ -1158,6 +1208,7 @@ async def _acquire_credential_ref_with_cancellation_ownership(service,rollback_source_id,transient_ref,+ operation=rollback_operation,)raise cancelled@@ -1183,11 +1234,18 @@ async def _rollback_credential_before_settling(service: "ModelHubService",source_id: str,credential_ref: str,+ *,+ operation: RevocationOperation | None = None,) -> None:"""Finish transient cleanup before propagating a cancellation."""rollback_task = asyncio.create_task(- _require_credential_cleanup(service, source_id, credential_ref)+ _require_credential_cleanup(+ service,+ source_id,+ credential_ref,+ operation=operation,+ ))try:await asyncio.shield(rollback_task)@@ -1200,10 +1258,16 @@ async def _require_credential_cleanup(service: "ModelHubService",source_id: str,credential_ref: str,+ *,+ operation: RevocationOperation | None = None,) -> None:"""Refuse to settle when cleanup is neither complete nor durable."""- if not await service._rollback_credential(source_id, credential_ref):+ if not await service._rollback_credential(+ source_id,+ credential_ref,+ operation=operation,+ ):raise CredentialCleanupUnsettledError@@ -1312,7 +1376,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:manager = EngineRuntimeManager()return {- "contract_version": 16,+ "contract_version": 17,"enabled": enabled,"host_platform": status.host_platform or manager.host_platform(),"manifest": manager.contract_manifest(),@@ -1515,9 +1579,11 @@ class ModelHubService:tuple[str, str, OAuthChannel], asyncio.Task[dict]] = {}self._source_create_nonces: set[str] = set()+ self._search_reenable_trials: set[str] = set()+ self._search_reenable_trials_inflight: set[str] = set()self._next_settlement_generation = PRE_ATTEMPT_SETTLEMENT_GENERATIONself._latest_source_attempt_generation: dict[str, int] = {}- self._source_attempt_identities: dict[str, tuple] = {}+ self._source_attempt_identities: dict[str, tuple | None] = {}self._engine_synced = Falseself._engine_preparation_failed = Falseself._runtime_install_reconcile_lock = asyncio.Lock()@@ -1878,6 +1944,37 @@ class ModelHubService:return Falsereturn True+ def search_reenable_trial_armed(self, source_id: str) -> bool:+ """Return whether one process-local search trial is waiting for S2's gate."""++ return source_id in self._search_reenable_trials++ def search_reenable_trial_pending(self, source_id: str) -> bool:+ """Return whether a one-shot search trial is armed or in flight."""++ return (+ source_id in self._search_reenable_trials+ or source_id in self._search_reenable_trials_inflight+ )++ def reserve_search_reenable_trial(self, source_id: str) -> bool:+ """Atomically consume the one-shot search trial for one candidate."""++ if source_id not in self._search_reenable_trials:+ return False+ self._search_reenable_trials.remove(source_id)+ self._search_reenable_trials_inflight.add(source_id)+ return True++ def settle_search_reenable_trial(self, source_id: str) -> None:+ """Forget a trial after S2 settles its admitted search attempt."""++ self._search_reenable_trials_inflight.discard(source_id)++ def _drop_search_reenable_trial(self, source_id: str) -> None:+ self._search_reenable_trials.discard(source_id)+ self._search_reenable_trials_inflight.discard(source_id)+def _mint_settlement_generation(self) -> int:self._next_settlement_generation += 1return self._next_settlement_generation@@ -2089,65 +2186,97 @@ class ModelHubService:pending_revocations = self.revocations.list()if self._engine_synced and not pending_revocations:return- config = self.store.load()- takeover = self.migration_journal.load()- takeover_credentials = {- (credential["source_id"], credential["credential_ref"])- for credential in (takeover or {}).get("credentials", [])- }+ await self._replay_credential_revocations_locked(+ self.store.load(), pending_revocations, sync_engine=True,+ )++ async def _replay_credential_revocations_locked(+ self,+ config: ModelHubConfig,+ pending_revocations: list[PendingCredentialRevocation],+ *,+ sync_engine: bool = False,+ ) -> list[PendingCredentialRevocation]:+ """Replay with shared custody guards and return remaining unowned intents."""++ takeover = self.migration_journal.load()+ takeover_credentials = {+ (credential["source_id"], credential["credential_ref"])+ for credential in (takeover or {}).get("credentials", [])+ }+ if sync_engine:await self._sync_sources(config, force_empty=bool(pending_revocations))self._engine_synced = True- active_credentials = {- source.id: source.credential_ref for source in config.sources- }- for pending in pending_revocations:- if active_credentials.get(pending.source_id) == pending.credential_ref:- try:- self.revocations.remove(- pending.source_id,- pending.credential_ref,- )- except OSError:- pass- continue- if (pending.source_id, pending.credential_ref) in takeover_credentials:- # A prepared takeover owns refs before they appear in- # config. Other Hub consumers may reconcile between a- # failed request and recovery; they cannot revoke its grant.- continue- if pending.operation == "cleanup_orphaned_oauth_material":- try:- cleaned = (- await self.adapter.cleanup_orphaned_oauth_material(- pending.credential_ref- )- )- except Exception:- continue- if not cleaned:- continue- elif pending.operation == "revoke_api_key_credential":- try:- await self.adapter.revoke_api_key_credential(pending.credential_ref)- except Exception:- # Only successful exact-namespace cleanup establishes- # absence. Metadata errors are not retirement proof.- continue- else:- try:- await self.adapter.revoke_credential(- pending.credential_ref- )- except Exception as error:- if not self._credential_was_already_revoked(error):- continue+ active_credentials = {+ source.id: source.credential_ref for source in config.sources+ }+ for pending in pending_revocations:+ if active_credentials.get(pending.source_id) == pending.credential_ref:try:- self.revocations.remove(- pending.source_id,- pending.credential_ref,- )+ self.revocations.remove(pending.source_id, pending.credential_ref)except OSError:pass+ continue+ if (pending.source_id, pending.credential_ref) in takeover_credentials:+ # A prepared takeover owns refs before they appear in config.+ # Other consumers cannot revoke its not-yet-committed grant.+ continue+ if pending.operation == "cleanup_orphaned_oauth_material":+ try:+ cleaned = await self.adapter.cleanup_orphaned_oauth_material(pending.credential_ref)+ except Exception:+ continue+ if not cleaned:+ continue+ elif pending.operation in {"revoke_api_key_credential", "revoke_search_credential"}:+ revoker = (+ self.adapter.revoke_search_credential+ if pending.operation == "revoke_search_credential"+ else self.adapter.revoke_api_key_credential+ )+ try:+ await revoker(pending.credential_ref)+ except Exception:+ # Only successful exact-namespace cleanup establishes+ # absence. Metadata errors are not retirement proof.+ continue+ else:+ try:+ await self.adapter.revoke_credential(pending.credential_ref)+ except Exception as error:+ if not self._credential_was_already_revoked(error):+ continue+ try:+ self.revocations.remove(pending.source_id, pending.credential_ref)+ except OSError:+ pass++ # A retained intent is not necessarily failed cleanup: active Sources+ # and prepared takeovers still own their refs. Re-read after replay so+ # callers can gate new custody on the actual unowned postcondition.+ return [+ pending for pending in self.revocations.list()+ if active_credentials.get(pending.source_id) != pending.credential_ref+ and (pending.source_id, pending.credential_ref) not in takeover_credentials+ ]++ async def _require_api_key_cleanup_locked(self, config: ModelHubConfig) -> None:+ """Refuse new search custody while prior unowned API keys await cleanup."""++ try:+ pending = [+ entry for entry in self.revocations.list()+ if entry.operation in {"revoke_api_key_credential", "revoke_search_credential"}+ ]+ if not pending:+ return+ remaining = await self._replay_credential_revocations_locked(config, pending)+ except OSError:+ raise ModelHubError("engine_down", status=503) from None+ if any(entry.operation in {"revoke_api_key_credential", "revoke_search_credential"} for entry in remaining):+ # The journal owns the old ref, so a create nonce can be released,+ # but that durable ownership does not permit another credential.+ raise ModelHubError("engine_down", status=503)async def _prepare_engine_for_demand(self, *, already_synced: bool = False) -> None:try:@@ -2383,6 +2512,8 @@ class ModelHubService:*,start_engine: bool = True,) -> list[DiscoveredModel]:+ if source.protocol == "search":+ return []if not source.credential_ref:return [DiscoveredModel(id=model.id)@@ -2409,15 +2540,17 @@ class ModelHubService:pinned_protocol = pinned_api_key_protocol(vendor)if "protocol" not in payload:if pinned_protocol is not None:+ if pinned_protocol == "search":+ raise ModelHubError("discovery_failed")return (pinned_protocol,)if vendor == "custom":# Google is explicit API/config admission in v11, not a new# automatic probe or picker option. Its generation path needs# a model, which non-inference observation must not invent.- return tuple(protocol for protocol in SOURCE_PROTOCOLS if protocol != "google")+ return tuple(protocol for protocol in MODEL_PROTOCOLS if protocol != "google")raise ModelHubError("discovery_failed")requested = payload.get("protocol")- if not isinstance(requested, str) or requested not in SOURCE_PROTOCOLS:+ if not isinstance(requested, str) or requested not in MODEL_PROTOCOLS:raise ModelHubError("discovery_failed")if pinned_protocol is not None and requested != pinned_protocol:raise ModelHubError("discovery_failed")@@ -2671,16 +2804,40 @@ class ModelHubService:self,source_id: str,credential_ref: str,+ *,+ operation: RevocationOperation | None = None,) -> bool:+ source = next(+ (candidate for candidate in self.store.load().sources if candidate.id == source_id),+ None,+ )+ resolved_operation = operation or (+ "revoke_search_credential"+ if source is not None and source.protocol == "search"+ else "revoke_credential"+ )+ if resolved_operation == "revoke_search_credential":+ revoker = self.adapter.revoke_search_credential+ elif resolved_operation == "revoke_api_key_credential":+ revoker = self.adapter.revoke_api_key_credential+ else:+ revoker = self.adapter.revoke_credentialjournaled = Falsetry:- self.revocations.add(source_id, credential_ref)+ if resolved_operation == "revoke_credential":+ self.revocations.add(source_id, credential_ref)+ else:+ self.revocations.add(+ source_id,+ credential_ref,+ operation=resolved_operation,+ )except OSError:passelse:journaled = Truetry:- await self.adapter.revoke_credential(credential_ref)+ await revoker(credential_ref)except Exception:return journaledif not journaled:@@ -2954,6 +3111,8 @@ class ModelHubService:source.display_name = f"{seed[:64 - len(suffix)]}{suffix}"number += 1config.sources.append(source)+ if source.protocol == "search":+ _maintain_search_service_order(config, source.id, add=True)self._apply_source_placement(config, source)seeded = config.vibey_supply_pending and await self._seed_vibey(config)await self._commit_synced(previous, config)@@ -3100,6 +3259,8 @@ class ModelHubService:if refused:model["refused_efforts"] = refusedpayload["adopted_by"] = self._adopted_by(source.id, config)+ if source.protocol == "search":+ payload["trial_pending"] = self.search_reenable_trial_pending(source.id)return self._source_account_payload(payload)def _source_account_payload(self, payload: dict) -> dict:@@ -3214,7 +3375,7 @@ class ModelHubService:vendor,None,rollback_credential_ref,- SOURCE_PROTOCOLS,+ MODEL_PROTOCOLS,)# Completed consent supplies credential custody, not proof# that a model call works. Its vendor fixes the interface.@@ -3895,6 +4056,118 @@ class ModelHubService:config = self.store.load()return [self._source_payload(source, config) for source in config.sources]+ async def _search_free_check(+ self,+ source: ModelHubSourceConfig,+ ) -> Literal["pass", "balance", "limit", "invalid", "unknown"]:+ service = _search_service_for_source(source)+ checker = getattr(self.adapter, "check_search_credential", None)+ if service is None or not callable(checker) or not source.credential_ref:+ return "unknown"+ catalog = {"vendor": source.vendor, **service}+ try:+ result = await checker(source.credential_ref, catalog)+ except asyncio.CancelledError:+ raise+ except Exception:+ return "unknown"+ return _search_check_outcome(result)++ async def _create_search_source(+ self,+ *,+ vendor: str,+ display_name: str,+ display_name_defaulted: bool,+ client_nonce: str | None,+ key: str,+ ) -> dict:+ service = search_service(vendor, "search")+ if service is None or not service.get("tool_only"):+ raise ModelHubError("discovery_failed")+ source = ModelHubSourceConfig(+ id=_source_id(),+ kind="api_key",+ vendor=vendor,+ display_name=display_name,+ protocol="search",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[],+ created_at=self.now().isoformat(),+ client_nonce=client_nonce,+ credential_ref="cred_preflight",+ )+ source = ModelHubSourceConfig.from_payload(source.to_payload())+ nonce_claimed = False+ release_nonce = True+ try:+ async with self._mutation_lock:+ if client_nonce is not None:+ self._claim_source_create_nonce_locked(client_nonce)+ nonce_claimed = True+ # Typed cleanup is engine-free; OAuth/generic intents remain+ # with model demand. Replaying alone is not admission proof.+ await self._require_api_key_cleanup_locked(self.store.load())+ credential_ref = await _acquire_credential_ref_with_cancellation_ownership(+ self,+ self.adapter.provision_credential(vendor, "search", key, None),+ source.id,+ rollback_operation="revoke_search_credential",+ )+ persisted = False+ try:+ source.credential_ref = credential_ref+ source.masked_credential = _mask_credential(key)+ outcome = await self._search_free_check(source)+ if outcome == "invalid":+ raise ModelHubError(+ "discovery_failed",+ status=422,+ detail="modelHub.errors.authentication_failed",+ )+ if outcome in {"balance", "limit"}:+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key=(+ "models.source.needs_action.balance_exhausted"+ if outcome == "balance"+ else "models.source.needs_action.spend_limit_reached"+ ),+ )+ elif outcome == "unknown":+ self._mark_source_unverified(source)+ else:+ source.verification_pending = None+ source = ModelHubSourceConfig.from_payload(source.to_payload())+ async with self._mutation_lock:+ await self._commit_new_source_locked(+ source,+ display_name_defaulted=display_name_defaulted,+ )+ persisted = True+ return self._source_creation_result(source.to_payload())+ except asyncio.CancelledError:+ persisted = self._persisted_credential(self.store.load(), source.id, credential_ref)+ if not persisted:+ await _rollback_credential_before_settling(+ self, source.id, credential_ref, operation="revoke_search_credential",+ )+ raise+ except Exception:+ if not persisted:+ await _rollback_credential_before_settling(+ self, source.id, credential_ref, operation="revoke_search_credential",+ )+ raise+ except CredentialCleanupUnsettledError:+ release_nonce = False+ raise+ finally:+ if nonce_claimed and release_nonce:+ self._source_create_nonces.discard(cast(str, client_nonce))+async def create_source(self, payload: dict) -> dict:if not isinstance(payload, dict):raise ModelHubError("discovery_failed")@@ -4008,6 +4281,29 @@ class ModelHubService:)):raise ModelHubError("discovery_failed")+ requested_protocol = (+ payload.get("protocol")+ if "protocol" in payload+ else pinned_api_key_protocol(vendor)+ )+ if kind == "api_key" and requested_protocol == "search":+ if (+ base_url is not None+ or billing != "metered"+ or manual_models+ or bool(payload.get("save_unverified"))+ or bool(payload.get("accept_unavailable_inventory"))+ or search_service(vendor, "search") is None+ ):+ raise ModelHubError("discovery_failed")+ return await self._create_search_source(+ vendor=vendor,+ display_name=display_name,+ display_name_defaulted=display_name_defaulted,+ client_nonce=client_nonce,+ key=cast(str, credential_value),+ )+protocol_order: tuple[str, ...] | None = Noneif kind == "api_key":protocol_order = self._observation_protocols(vendor, payload)@@ -4148,11 +4444,33 @@ class ModelHubService:source.id,))- source.credential_ref = rollback_credential_ref- source.masked_credential = _mask_credential(cast(str, credential_value))- source = ModelHubSourceConfig.from_payload(source.to_payload())persisted = Falsetry:+ source.credential_ref = rollback_credential_ref+ source.masked_credential = _mask_credential(cast(str, credential_value))+ if _search_service_for_source(source) is not None:+ outcome = await self._search_free_check(source)+ if outcome == "invalid":+ raise ModelHubError(+ "discovery_failed",+ status=422,+ detail="modelHub.errors.authentication_failed",+ )+ if outcome in {"balance", "limit"}:+ source.verification_pending = None+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key=(+ "models.source.needs_action.balance_exhausted"+ if outcome == "balance"+ else "models.source.needs_action.spend_limit_reached"+ ),+ )+ elif outcome == "pass":+ source.verification_pending = None+ elif outcome == "unknown" and source.protocol == "search":+ self._mark_source_unverified(source)+ source = ModelHubSourceConfig.from_payload(source.to_payload())if save_unverified:# Inventory is useful, not admission evidence. Work on a# clone so a failed listing cannot partly replace manual@@ -4188,7 +4506,7 @@ class ModelHubService:raiseexcept Exception:if not persisted:- await _require_credential_cleanup(+ await _rollback_credential_before_settling(self,source.id,rollback_credential_ref,@@ -4201,6 +4519,103 @@ class ModelHubService:if nonce_claimed and release_nonce:self._source_create_nonces.discard(cast(str, client_nonce))+ async def _replace_search_credential_locked(+ self,+ previous: ModelHubConfig,+ config: ModelHubConfig,+ source: ModelHubSourceConfig,+ key: str,+ ) -> dict:+ service = _require_search_service_for_source(source)+ old_credential_ref = source.credential_ref+ if not old_credential_ref:+ raise ModelHubError("discovery_failed")+ await self._require_api_key_cleanup_locked(previous)+ committed = False+ old_revocation_recorded = False+ replacement_ref = await _acquire_credential_ref_with_cancellation_ownership(+ self,+ self.adapter.provision_credential(+ source.vendor,+ "search",+ key,+ None,+ ),+ source.id,+ rollback_operation="revoke_search_credential",+ )+ try:+ source.credential_ref = replacement_ref+ source.masked_credential = _mask_credential(key)+ self._mark_source_unverified(source)+ has_free_check = isinstance(service.get("free_check"), Mapping)+ outcome = await self._search_free_check(source)+ if has_free_check and outcome == "unknown":+ raise ModelHubError(+ "discovery_failed",+ status=502,+ detail="modelHub.errors.credential_replacement_unverified",+ )+ if outcome == "invalid":+ raise ModelHubError(+ "discovery_failed",+ status=422,+ detail="modelHub.errors.authentication_failed",+ )+ if outcome != "unknown":+ source.verification_pending = None+ source.state = ModelHubSourceStateConfig(status="standby")+ if outcome in {"balance", "limit"}:+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key=(+ "models.source.needs_action.balance_exhausted"+ if outcome == "balance"+ else "models.source.needs_action.spend_limit_reached"+ ),+ )+ if old_credential_ref != replacement_ref:+ self.revocations.add(+ source.id,+ old_credential_ref,+ operation="revoke_search_credential",+ )+ old_revocation_recorded = True++ await self._commit_synced(previous, config)+ 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 _rollback_replacement_before_settling(+ self, source.id, replacement_ref, old_credential_ref,+ old_revocation_recorded=old_revocation_recorded,+ )+ raise+ finally:+ # Persistence, not request success, retires the old trial. This+ # also covers cancellation after the shielded config write landed.+ if self._persisted_credential(self.store.load(), source.id, replacement_ref):+ self._drop_search_reenable_trial(source.id)+ if old_credential_ref != replacement_ref:+ try:+ await self.adapter.revoke_search_credential(old_credential_ref)+ except Exception:+ pass+ else:+ try:+ self.revocations.remove(source.id, old_credential_ref)+ except OSError:+ pass+ return {"source": self._source_payload(source), "removed_hops": [], "interrupted": []}+async def replace_credential(self, source_id: str, payload: object) -> dict:if (not isinstance(payload, dict)@@ -4228,6 +4643,15 @@ class ModelHubService:or not source.credential_ref):raise ModelHubError("discovery_failed")+ if source.protocol == "search":+ return await self._replace_search_credential_locked(+ previous,+ config,+ source,+ key,+ )+ if _search_service_for_source(source) is not None:+ self._drop_search_reenable_trial(source.id)old_credential_ref = source.credential_refauth_scheme = await self._engine_call(@@ -4248,7 +4672,33 @@ class ModelHubService:source.credential_ref = replacement_refself._mark_source_unverified(source)source.masked_credential = _mask_credential(key)- discovered = await self._discover(source)+ search_balance = False+ if _search_service_for_source(source) is not None:+ outcome = await self._search_free_check(source)+ if outcome == "invalid":+ raise ModelHubError(+ "discovery_failed",+ status=422,+ detail="modelHub.errors.authentication_failed",+ )+ source.verification_pending = None+ if outcome in {"balance", "limit"}:+ search_balance = True+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key=(+ "models.source.needs_action.balance_exhausted"+ if outcome == "balance"+ else "models.source.needs_action.spend_limit_reached"+ ),+ )+ elif outcome == "unknown":+ self._mark_source_unverified(source)+ discovered = (+ [DiscoveredModel(id=model.id) for model in source.models if not model.retired]+ if search_balance+ else await self._discover(source)+ )if old_credential_ref != replacement_ref:if any(pending.source_id == source.id@@ -4265,15 +4715,26 @@ class ModelHubService:source.id, old_credential_ref, operation="revoke_api_key_credential",)old_revocation_recorded = True- removed_hops, interrupted = await self._finalize_successful_discovery(- previous,- config,- source,- discovered,- force=force,- confirmed_remove_hops=payload.get("would_remove_hops"),- confirmed_interruptions=payload.get("would_interrupt"),- )+ if search_balance:+ removed_hops, interrupted = self._guard_inventory_mutation(+ previous,+ config,+ source.id,+ force=force,+ confirmed_remove_hops=payload.get("would_remove_hops"),+ confirmed_interruptions=payload.get("would_interrupt"),+ )+ await self._commit_synced(previous, config)+ else:+ removed_hops, interrupted = await self._finalize_successful_discovery(+ previous,+ config,+ source,+ discovered,+ force=force,+ confirmed_remove_hops=payload.get("would_remove_hops"),+ confirmed_interruptions=payload.get("would_interrupt"),+ )committed = Trueexcept asyncio.CancelledError:committed = self._persisted_credential(@@ -4336,6 +4797,8 @@ class ModelHubService:previous = self.store.load()config = self._clone_config(previous)source = self._source(config, source_id)+ if source.protocol == "search":+ _require_search_service_for_source(source)removed_hops: list[dict] = []interrupted: list[dict] = []if "display_name" in payload:@@ -4346,6 +4809,7 @@ class ModelHubService:if base_url_changed:if (source.kind != "api_key"+ or source.protocol == "search"or source.supply_channel != "hub"or not source.credential_ref):@@ -4424,6 +4888,69 @@ class ModelHubService:"interrupted": interrupted,}+ async def reenable_search_source(self, source_id: str, payload: object = None) -> dict:+ if payload not in (None, {}):+ raise ModelHubError("discovery_failed")+ async with self._mutation_lock:+ previous = self.store.load()+ config = self._clone_config(previous)+ source = self._source(config, source_id)+ if source.protocol != "search" or source.kind != "api_key":+ raise ModelHubError("discovery_failed")+ service = _require_search_service_for_source(source)+ if source.state.status != "needs_action" or source.state.detail_key not in {+ "models.source.needs_action.balance_exhausted",+ "models.source.needs_action.spend_limit_reached",+ }:+ raise ModelHubError("discovery_failed")+ if self.search_reenable_trial_pending(source.id):+ return {+ "source": self._source_payload(source, config),+ "removed_hops": [],+ "interrupted": [],+ "trial_armed": True,+ }+ trial_armed = False+ has_free_check = isinstance(service.get("free_check"), Mapping)+ if not has_free_check:+ self._search_reenable_trials.add(source.id)+ trial_armed = True+ else:+ outcome = await self._search_free_check(source)+ if outcome in {"pass", "balance", "limit"}:+ source.verification_pending = None+ if outcome == "pass":+ source.state = ModelHubSourceStateConfig(status="standby")+ self._drop_search_reenable_trial(source.id)+ elif outcome == "invalid":+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.credential_revoked",+ )+ self._drop_search_reenable_trial(source.id)+ elif outcome == "balance":+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.balance_exhausted",+ )+ self._drop_search_reenable_trial(source.id)+ elif outcome == "limit":+ source.state = ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.spend_limit_reached",+ )+ self._drop_search_reenable_trial(source.id)+ else:+ self._drop_search_reenable_trial(source.id)+ if source.state.status != "needs_action" or not trial_armed:+ await self._commit_synced(previous, config)+ return {+ "source": self._source_payload(source),+ "removed_hops": [],+ "interrupted": [],+ "trial_armed": trial_armed,+ }+def _protected_menu_models(self,config: ModelHubConfig,@@ -4742,6 +5269,8 @@ class ModelHubService:source = self._source(config, source_id)removed_hops = [item for item in self._effective_hop_refs(previous) if item["source_id"] == source_id]config.sources = [item for item in config.sources if item.id != source_id]+ if source.protocol == "search":+ _maintain_search_service_order(config, source_id, add=False)for agent in config.agents.values():agent.sources.order = [item for item in agent.sources.order if item != source_id]for model_id, route in list(agent.routes.items()):@@ -4765,17 +5294,34 @@ class ModelHubService:),)if source.credential_ref:- self.revocations.add(source.id, source.credential_ref)+ self.revocations.add(+ source.id,+ source.credential_ref,+ operation=("revoke_search_credential" if source.protocol == "search" else "revoke_credential"),+ )try:await self._commit_synced(previous, config)except Exception:if source.credential_ref:self.revocations.remove(source.id, source.credential_ref)raise+ finally:+ if not any(item.id == source_id for item in self.store.load().sources):+ self._drop_search_reenable_trial(source_id)try:if source.credential_ref:- await self._engine_call(self.adapter.revoke_credential(source.credential_ref))+ revoke = (+ self.adapter.revoke_search_credential(source.credential_ref)+ if source.protocol == "search"+ else self.adapter.revoke_credential(source.credential_ref)+ )+ await self._engine_call(revoke)except ModelHubError:+ if source.protocol == "search":+ # The config deletion is already durable. A search Source+ # has no engine binding to restore, and the journal must+ # survive any partial credential retirement for replay.+ raiserestored = Falsetry:await self._save_config(previous)@@ -4806,7 +5352,7 @@ class ModelHubService:previous = self.store.load()config = self._clone_config(previous)source = self._source(config, source_id)- if source.supply_channel == "native_cli":+ if source.supply_channel == "native_cli" or source.protocol == "search":raise ModelHubError("discovery_failed")try:model_ids = await self._discover(source)@@ -7801,6 +8347,8 @@ class ModelHubService:previous = self.store.load()config = self._clone_config(previous)source = self._source(config, str(source_id or ""))+ if source.protocol == "search":+ raise ModelHubError("mapping_target_unavailable")existing = next((model for model in source.models if model.id == model_id), None)if existing is None:model = ModelHubModelConfig(@@ -8284,6 +8832,7 @@ class ModelHubService:if (source.kind != "api_key"or source.supply_channel != "hub"+ or source.protocol == "search"or not source.credential_refor not any(model.id == model_id and not model.retired for model in source.models)):diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 7d1feab81..a7fce1816 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,6 +1,33 @@# Model Hub contracts-Status: **contract_version 16**, 2026-10-16: two non-self-healing Source causes,+Status: **contract_version 17**, 2026-10-19: search-service foundations+(`../web-search-services.md`). Tool-only Sources use `protocol: search`; the catalog,+credential custody, free checks, re-enable response and service-order persistence+ship before search execution. S1b, S2 and S3 extend this same version event only+while it is unshipped; if an RC has carried v17, the next lane opens v18 instead.+S2 activates the service reads and search chain.++Catalog metadata verified on **2026-10-20**:+- `search.auto_enroll` is explicit for model vendors with search; only DeepSeek is+ enabled automatically. S1b and S2 own the resulting settings defaults.+- Exa's `search.result.reported_cost` names `costDollars.total` with `estimate: true`.+ Its `search.request.content_max_chars` names `contents.text.maxCharacters` with+ `value: 4000`, applied only when page content is requested. Both follow the+ [Exa Search reference](https://exa.ai/docs/reference/search).+- The [DeepSeek Search reference](https://api-docs.deepseek.com/api/search) and+ [Tavily Search OpenAPI](https://docs.tavily.com/documentation/api-reference/openapi.json)+ publish no hard per-page text bound. They retain the content setting with no+ invented `content_results_max`. The adapter's hard 8 MiB response cap remains;+ an over-cap body is unreadable, not a guarantee that every legitimate page fits.+ S2 applies the design's billing, cooldown and failover rules to that outcome.+- Tavily's usage response may omit account pairs. A valid key pair with headroom+ (including `limit: null`) then passes the free credential check; it proves key+ authentication, while the first search confirms payment. A key at its limit+ still reports `limit`; malformed or half-present pairs report `unknown`.+- The query bound is 128 characters for DeepSeek only. Tavily and Exa document no+ query-length maximum, so their catalog `query_max_chars` remains null.++It builds on v16 (2026-10-16): two non-self-healing Source causes,`plan_excludes_product` (`models.source.needs_action.plan_excludes_product`), for a plan that does not include theproduct, and `spend_limit_reached` (`models.source.needs_action.spend_limit_reached`), for an account past a spend orusage limit only raising it lifts, join the resolution-event, provenance, Source, agent-chain and probe vocabularies,@@ -97,7 +124,11 @@ commit is not evidence that the complete final protocol has landed.inherited routing through the same Restore/Undo/Save flow, never empty Manual.- A hop whose upstream `model_id` differs from its menu model is an explicit configuredmapping. There is no separate mapping object or runtime mapping event.-- The protocol vocabulary is exactly `anthropic | openai_responses | openai_chat | google`.+- The Source protocol vocabulary is `anthropic | openai_responses | openai_chat | google | search`.+`MODEL_PROTOCOLS` is the four invocable model-wire protocols (`anthropic | openai_responses |+openai_chat | google`); `SOURCE_PROTOCOLS` is that tuple plus the tool-only `search` protocol.+Model observation, probes, discovery, auto-detection, provider overlays, and hop schemas use+`MODEL_PROTOCOLS`; only persisted Source and Source-create shapes use `SOURCE_PROTOCOLS`.`base_url` distinguishes official endpoints from relays and self-hosted gateways.Google is explicitly declared through API/config; the three-option UI picker andcustom Auto-detection set remain unchanged.@@ -131,11 +162,20 @@ No underlying engine expansion or OAuth alias substitution is part of this changbound credential under the fixed vendor protocol. A newly stored Hub credentialthat no add-time observation authenticated — an explicit unverified save, anative-config import, Hub OAuth admission, any credential or endpoint replacement —- carries an opaque `verification_pending` identity until an actual- matching-credential model call succeeds. Its clearing is a fresh cross-process- field mutation; model discovery never clears it. A typed Base URL never- supplies protocol ownership. Model-free validation, altered-credential controls- and publicly readable model lists do not prove authentication; on a protocol that+ carries an opaque `verification_pending` identity. Model Sources keep the+ matching-credential model-call rule: a successful model call with the same current+ credential and marker may clear it. A tool-only `search` Source never makes a model call.+ For every search-capable Source, including an official DeepSeek model Source+ saved unverified, the marker clears on an authenticated search outcome with the matching credential+ (any 200, a 402, or a catalog-named limit), or a free-check `pass`, `balance` or+ `limit` for that credential. A 200 proves authentication even when its results+ are empty or its body is unreadable. Clearing requires the same current credential+ and marker and is a fresh cross-process field mutation; `credential_generation`+ does not change. Free-check `unknown` and `invalid` leave it unchanged.+ Model discovery never clears it.+ A typed Base URL never supplies protocol ownership. For model observation,+ model-free validation, altered-credential controls and publicly readable model+ lists do not prove authentication; on a protocol thatalready has an owner, a model listing that answers the credential while refusingthe identical uncredentialed request does. See the 2026-09-07 rulingsin `docs/plans/model-hub.md` and the create/Source schemas for the complete policy.@@ -233,7 +273,7 @@ comparison. A gate may not report success by comparing stale input with itself.## Version closure-`contract_version` 16 must coexist in all registered version locations on the same tested head:+`contract_version` 17 must coexist in all registered version locations on the same tested head:- `mirror-registry.json`- `agent-chain.schema.json`@@ -269,8 +309,10 @@ persisted-shape rule that governs config files. It therefore accepts the releaseas a set ending at the terminal one, and nothing branches on which member a recordcarries.-The four-value protocol closure includes `source.schema.json`, `adapter-interface.py`,-and the byte-identical `core/handlers/model_hub/adapter.py` on the same tested head.+The five-value Source protocol closure includes `source.schema.json`, `source-create.schema.json`,+and the storage/admission constants. The model-only closure is the four-value+`source-probe-result.schema.json` protocol and its `MODEL_PROTOCOLS` consumers; search is not+admitted by observation, probes, discovery, auto-detection, provider overlays, or hop schemas.After implementation lands, these contracts are read-only for downstream lanes. Animplementation-discovered mismatch is reported to the orchestrator for a targeted@@ -280,7 +322,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac| File | Authority and consumer role || --- | --- |-| `source.schema.json` | Source identity, channel, four protocols, state, usage, inventory, credential reference, and audit metadata. |+| `source.schema.json` | Source identity, channel, five protocols, state, usage, inventory, credential reference, and audit metadata. || `source-create.schema.json` | API-key Source creation request, transient credential boundary, optional single-protocol constraint, and lost-response correlation. || `agent-supply.schema.json` | Backend mode, default Source membership/order and sparse manual intent, configuration eligibility, model-supply and backend-health projections. || `backend-model.schema.json` | Backend Agent model identity, editable capability metadata, and server-owned lock/routeability projection. |diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex 81ddde9eb..94de03c66 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -1,9 +1,12 @@-"""Model Hub EngineAdapter interface. FINAL CONTRACT v16 (2026-10-16).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v17 (2026-10-19).This file is the canonical adapter boundary and must remain byte-identical to``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:credential custody, protocol observation, model discovery, OAuth, invocation,-and cleanup. It never chooses or reorders Route hops, classifies cross-Source+and cleanup. Model protocol operations use ``MODEL_PROTOCOLS`` (the four invocable+wire protocols); ``SOURCE_PROTOCOLS`` adds the tool-only ``search`` value only for+stored/created Source shapes. It never chooses or reorders Route hops, classifies+cross-Sourcefallthrough, or exposes credential material. Contract changes route through theorchestrator and land with every affected consumer on the same tested head."""@@ -19,7 +22,12 @@ from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocfrom .stream_wire import ProtocolSSEState, ProtocolUsageReportENGINE_TRANSPORT_TIMEOUT_SECONDS: Final = 60.0-SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat", "google")+# Model invocation/observation is a narrower domain than stored Sources.+MODEL_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat", "google")+# Source persistence/admission adds the tool-only search protocol.+SOURCE_PROTOCOLS = MODEL_PROTOCOLS + ("search",)+SEARCH_RESPONSE_MAX_BYTES: Final = 8 * 1024 * 1024+SEARCH_TRANSPORT_TIMEOUT_SECONDS: Final = 30.0OBSERVATION_OUTCOMES = ("observed","ambiguous",@@ -70,13 +78,34 @@ class OAuthCredentialRejectedError(RuntimeError):"""+@dataclass(frozen=True)+class SearchResponse:+ """Bounded response from one catalog search endpoint.++ The body is opaque to this boundary. It contains no credential material;+ the adapter reads the key from custody only while making the request.+ """++ http_status: int | None+ headers: Mapping[str, str]+ body: bytes | None+ error: Literal["", "timeout", "connection", "redirect", "body_too_large", "invalid_endpoint", "cancelled"] = ""+ on_sent_fired: bool = False+ response_received_at: datetime | None = None+++@dataclass(frozen=True)+class SearchCredentialCheck:+ outcome: Literal["pass", "balance", "limit", "invalid", "unknown"]++@dataclass(frozen=True)class SourceBinding:"""Engine-side registration of one hub-channel source (projection of config)."""source_id: strvendor: str- protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "google"+ protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "google" | "search"base_url: str | None # None => vendor official defaultcredential_ref: str # opaque handle; never secret materialallowed_origins: tuple[str, ...] # agent names allowed to draw on this@@ -258,7 +287,7 @@ OBSERVATION_TERMINAL_RULES: Mapping[ObservationOutcome.OBSERVED: ObservationTerminalRule(reachable=frozenset({True}),authenticated=frozenset({True}),- protocols=frozenset(SOURCE_PROTOCOLS),+ protocols=frozenset(MODEL_PROTOCOLS),discoveries=frozenset({ObservationDiscovery.SUCCEEDED,@@ -519,8 +548,9 @@ class EngineAdapter(Protocol):auth_scheme: str | None = None,on_reserved: Callable[[str], None] | None = None,) -> str:- """Store an API-key secret in the ENGINE-OWNED credential store and- return the opaque ``credential_ref``.+ """Store an API-key secret in the Model Hub credential store. Search+ Sources use this same opaque-ref custody, but are never rendered into+ engine configuration or sent through the engine.``secret`` is transient: the adapter must never log it; L2 must neverpersist it (config stores refs only). When supplied, ``on_reserved`` is@@ -532,6 +562,36 @@ class EngineAdapter(Protocol):an explicit static transport; omission retains legacy semantics."""...+ async def check_search_credential(+ self,+ credential_ref: str,+ catalog: Mapping[str, Any],+ ) -> SearchCredentialCheck:+ """Run one catalog free check without exposing its key or response."""+ ...++ async def search(+ self,+ source_id: str,+ vendor: str,+ service_id: str,+ credential_ref: str,+ request: Mapping[str, Any],+ *,+ on_sent: Callable[[], None] | None = None,+ ) -> SearchResponse:+ """Make exactly one catalog-host search request from Model Hub custody.++ ``on_sent`` fires once after the connection (including TLS) is ready and+ immediately before aiohttp writes this request. A callback failure stops+ the request before any request bytes are sent.+ """+ ...++ async def revoke_search_credential(self, credential_ref: str) -> None:+ """Remove a search-only credential from Model Hub custody."""+ ...+async def provision_oauth_credential(self,source_id: str,@@ -673,6 +733,16 @@ class EngineAdapter(Protocol):"""...+ async def revoke_search_credential(self, credential_ref: str) -> None:+ """Retire an unbound tool-only key under durable search-only intent.++ Preserve API-key namespace and identity checks, but never access the+ model engine or its configs, even when the document is already absent+ or corrupt. The caller journals this operation before unlinking so+ replay does not infer a lost protocol from credential metadata.+ """+ ...+async def provision_transient_credential(self,vendor: str,diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex 4bd2a3a87..d702d0b4c 100644--- a/docs/plans/model-hub-contracts/agent-chain.schema.json+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json@@ -7,7 +7,7 @@"required": ["contract_version", "backend", "model_id", "manual_override", "route_origin", "chain", "current", "supply_state"],"additionalProperties": false,"properties": {- "contract_version": { "const": 16 },+ "contract_version": { "const": 17 },"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },"model_id": { "type": "string" },"manual_override": {@@ -255,7 +255,7 @@],"examples": [{- "contract_version": 16,+ "contract_version": 17,"backend": "codex","model_id": "unlisted-model","manual_override": null,@@ -265,7 +265,7 @@"supply_state": "ok"},{- "contract_version": 16,+ "contract_version": 17,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -275,7 +275,7 @@"supply_state": "ok"},{- "contract_version": 16,+ "contract_version": 17,"backend": "claude","model_id": "claude-opus-4-6","manual_override": null,@@ -285,7 +285,7 @@"supply_state": "waiting"},{- "contract_version": 16,+ "contract_version": 17,"backend": "opencode","model_id": "glm-5.2","manual_override": { "hops": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2" }] },@@ -295,7 +295,7 @@"supply_state": "waiting"},{- "contract_version": 16,+ "contract_version": 17,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -305,7 +305,7 @@"supply_state": "interrupted"},{- "contract_version": 16,+ "contract_version": 17,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -315,7 +315,7 @@"supply_state": "interrupted"},{- "contract_version": 16,+ "contract_version": 17,"backend": "claude","model_id": "claude-haiku-4-5","manual_override": null,diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.jsonindex 48e621771..b95a91dbc 100644--- a/docs/plans/model-hub-contracts/api-response.schema.json+++ b/docs/plans/model-hub-contracts/api-response.schema.json@@ -13,6 +13,7 @@{"method": "POST", "path": "/api/models/sources/<id>/reauth", "response_schema": "OAuthFlowResponse", "exercise": {"path": "/api/models/sources/src_subscribe01/reauth", "status": 200, "json": {"acknowledge_irreversible": true}}},{"method": "DELETE", "path": "/api/models/sources/<id>?force=<bool>", "response_schema": "SourceDeleteResponse", "exercise": {"path": "/api/models/sources/src_delete0001?force=false", "status": 200, "json": {}}},{"method": "POST", "path": "/api/models/sources/<id>/refresh", "response_schema": "SourceMutationResponse", "exercise": {"path": "/api/models/sources/src_conform001/refresh", "status": 200, "json": {}}},+ {"method": "POST", "path": "/api/models/sources/<id>/reenable", "response_schema": "SourceReenableResponse", "exercise": {"path": "/api/models/sources/src_searchbalance/reenable", "status": 200, "json": {}}},{"method": "POST", "path": "/api/models/sources/<id>/probe", "response_schema": "SourceProbeResponse", "exercise": {"path": "/api/models/sources/src_conform001/probe", "status": 200, "json": {"model": "claude-opus-4-6"}}},{"method": "POST", "path": "/api/models/sources/<source_id>/models", "response_schema": "SourceResponse", "exercise": {"path": "/api/models/sources/src_conform001/models", "status": 201, "json": {"model_id": "manual-contract-model", "reasoning_efforts": []}}},{"method": "PATCH", "path": "/api/models/sources/<source_id>/models/<model_id>", "response_schema": "SourceResponse", "exercise": {"path": "/api/models/sources/src_conform001/models/retire-model", "status": 200, "json": {"reasoning_efforts": ["high"]}}},@@ -60,7 +61,7 @@"required": ["ok", "contract_version", "probe"],"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"probe": {"$ref": "model-hub/source-probe-result.schema.json"}}},@@ -159,7 +160,7 @@"SuccessCore": {"properties": {"ok": {"const": true},- "contract_version": {"const": 16}+ "contract_version": {"const": 17}}},"SourceListResponse": {@@ -168,7 +169,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}}},@@ -178,7 +179,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"observation": {"$ref": "model-hub/observation-result.schema.json"}}},@@ -188,7 +189,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"source": {"$ref": "#/definitions/SourceApi"},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}@@ -200,7 +201,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"source": {"$ref": "#/definitions/SourceApi"}}},@@ -210,19 +211,37 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"source": {"$ref": "#/definitions/SourceApi"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}}},+ "SourceReenableResponse": {+ "type": "object",+ "required": ["ok", "contract_version", "source", "removed_hops", "interrupted"],+ "additionalProperties": false,+ "properties": {+ "ok": {"const": true},+ "contract_version": {"const": 17},+ "source": {+ "allOf": [+ {"$ref": "#/definitions/SourceApi"},+ {"properties": {"protocol": {"const": "search"}}}+ ]+ },+ "removed_hops": {"type": "array", "maxItems": 0},+ "interrupted": {"type": "array", "maxItems": 0},+ "trial_armed": {"type": "boolean"}+ }+ },"SourceDeleteResponse": {"type": "object","required": ["ok", "contract_version", "removed_hops", "interrupted"],"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}}@@ -233,7 +252,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}}},@@ -243,7 +262,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"agent": {"$ref": "#/definitions/AgentSupplyApi"}}},@@ -260,7 +279,7 @@],"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"agent": {"$ref": "#/definitions/AgentSupplyApi"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}@@ -285,7 +304,7 @@"additionalProperties": false,"properties": {"ok": {"const": false},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"error": {"const": "candidate_suppliers_changed"},"detail": {"type": "string", "minLength": 1},"changed": {@@ -305,7 +324,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"agent": {"type": "object","required": ["backend", "mode", "catalog_models"],@@ -406,7 +425,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"candidates": {"type": "object","required": ["builtin", "providers", "in_list"],@@ -425,7 +444,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"matches": {"type": "array","maxItems": 8,@@ -459,7 +478,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"chain": {"$ref": "model-hub/agent-chain.schema.json"}}},@@ -469,7 +488,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}}},@@ -479,7 +498,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"chain": {"$ref": "model-hub/agent-chain.schema.json"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -491,7 +510,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"probe": {"$ref": "model-hub/probe-result.schema.json"}}},@@ -501,7 +520,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}}},@@ -511,7 +530,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"usage": {"$ref": "model-hub/usage-summary.schema.json"}}},@@ -521,7 +540,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"quota": {"$ref": "model-hub/quota-summary.schema.json"}}},@@ -531,7 +550,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"hosted_tools": {"$ref": "model-hub/hosted-tools-status.schema.json"}}},@@ -541,7 +560,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -563,7 +582,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -586,7 +605,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -611,7 +630,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16}+ "contract_version": {"const": 17}}},"RuntimeApi": {@@ -633,7 +652,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"scan": {"$ref": "model-hub/migration-scan.schema.json"}}},@@ -643,7 +662,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"applied": {"type": "integer", "minimum": 0},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}@@ -655,7 +674,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}}},@@ -666,7 +685,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"provenance": {"anyOf": [{"$ref": "model-hub/turn-provenance.schema.json"},@@ -681,7 +700,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 16},+ "contract_version": {"const": 17},"runtime": {"$ref": "#/definitions/RuntimeApi"}}}diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 17a9f8b24..b9f4324bf 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -8,11 +8,11 @@ credential redaction and supply-impact confirmation rules still apply; unknownAPI siblings retain the Owner default.-Status: **Normative, `contract_version` 16** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.+Status: **Normative, `contract_version` 17** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.-Success envelope: `{ok: true, contract_version: 16, ...}`.+Success envelope: `{ok: true, contract_version: 17, ...}`.Failure envelope:-`{ok: false, contract_version: 16, error: <machine_code>, detail?: <i18n_key>}`.+`{ok: false, contract_version: 17, error: <machine_code>, detail?: <i18n_key>}`.`detail` is always a string. Structured error data lives in a named sibling.Guarded mutation refusals specialize that envelope through`guard-refusal.schema.json`; both report arrays are required and together form the plan@@ -24,7 +24,7 @@ table. The contract guard requires the two endpoint sets to be identical, requirexercised HTTP response for every registry entry, and validates that response againstthe route's named schema.-The shared envelope and every versioned nested contract carry `contract_version` 16, the+The shared envelope and every versioned nested contract carry `contract_version` 17, theterminal value. Supported persisted config shapes and historical TurnProvenanceremain readable; ephemeral envelopes use only the terminal version.@@ -47,6 +47,7 @@ runtime open. Once models are configured it participates in the runtime Stop gua| POST `/api/models/sources/<id>/reauth` | `{acknowledge_irreversible?: true}` → `{flow: OAuthFlow}` | Both Hub OAuth and `native_cli` Sources require the acknowledgement before OAuth starts. Missing or false acknowledgement returns `reauth_confirmation_required` before any adapter call. See repair rules. || DELETE `/api/models/sources/<id>?force=<bool>` | `{would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{removed_hops, interrupted}` | A confirmed delete removes the Source from every backend Source order and Route chain in one transaction. A nonempty destructive plan commits only when the body exactly echoes the current refusal plan. || POST `/api/models/sources/<id>/refresh` | `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded Source-mutation envelope | The sole saved connectivity/discovery/recovery mutation. |+| POST `/api/models/sources/<id>/reenable` | `{}` → `{source: Source, removed_hops: [], interrupted: [], trial_armed?: boolean}` | Tool-only `search` Source recovery. It advances the Source settlement generation without interrupting work. With a free check, `pass` clears the state, `invalid` moves to the existing invalid-key state, and `balance`, `limit` or `unknown` keep or reclassify the current state without arming a trial. A Source without a free check keeps persisted `needs_action` and arms a process-local one-shot trial, reported as `trial_armed: true`; `Source.trial_pending` is true while that trial is armed or in flight, and a repeated request returns the current trial without advancing the generation. S2's search gate owns its admission and settlement. No paid search is sent. || POST `/api/models/sources/<id>/probe` | `{model}` → `{probe: SourceProbeResult}` | Explicit API-key test through the managed invocation adapter, using this exact Source/model/protocol. The model must be a non-retired saved inventory row. No Agent routing, fallback, discovery, credential refresh or Source-health change. Only a successful matching credential invocation clears pending verification. Usage is metered; the total invocation deadline is 60 seconds. || POST `/api/models/sources/<source_id>/models` | `{model_id, display_name?, reasoning_efforts}` → `{source: Source}` | Creates one user-authored model entry. The Source identity comes only from the path. || PATCH `/api/models/sources/<source_id>/models/<model_id>` | `{reasoning_efforts}` → `{source: Source}` | Replaces the complete capability list only when `reasoning_efforts_source` is `user` or null, without changing identity, origin, or Routes. An `upstream` or `catalog` declaration returns HTTP 409 `source_model_tiers_managed` with its provenance in the `reasoning_efforts_source` sibling. |@@ -82,7 +83,7 @@ runtime open. Once models are configured it participates in the runtime Stop gua| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. || POST `/api/models/migration/apply` | `{item_ids: string[], clean_api_keys?: boolean}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It checks saved configuration and custody locally, copies API keys without upstream validation, upgrades an existing native subscription Source in place when present, and commits Source/Routes/backend mode atomically. API-key originals are kept unless cleanup was selected. Pre-exposure failure is reversible; post-exposure recovery is forward-only and keeps the backend blocked until terminalized. || GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |-| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 16 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 17 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. || POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. || POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent; runtime availability has no separate enable-confirmation step. Uses the existing mutation authentication and CSRF guards; status reads never start it. || POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any native backend is configured for Hub mode or Avibe has catalog models, so disabling the shared runtime cannot strand a configured route. An empty Avibe catalog does not keep the runtime open. |@@ -235,6 +236,14 @@ successful call using the same current credential and marker clears it through afresh cross-process config transaction. Newer same-credential attempts do not negatesuccess. Credential/endpoint replacement generates a new marker, including same-handleOAuth reauthentication; old calls and failed calls cannot verify that replacement.+For `protocol: "search"`, the Source is tool-only and its create transaction never performs a model observation or invocation. The catalog supplies the service endpoint and mapping; the key is provisioned into the Model Hub credential store, and a free credential check is the only upstream check. `invalid` rolls back the new credential and returns the existing create authentication failure without saving a Source; `balance` saves the Source with `state.status: "needs_action"` and `detail_key: "models.source.needs_action.balance_exhausted"`; `limit` saves it verified with `detail_key: "models.source.needs_action.spend_limit_reached"`; `pass` saves it verified; `unknown` uses the ordinary unverified-save projection. Search Sources always have `models: []`, `base_url: null`, and are absent from model routing, discovery, probes, and engine bindings. The check is never billable and is performed before the commit point.++A saved tool-only Source whose catalog service disappears still loads and is listed, but is remove-only. Credential replacement, re-enable and metadata edits return `discovery_failed`/400 before provisioning, cleanup replay, config changes or trial arming; deletion stays available. A known catalog service with `free_check: null` is different and retains the ordinary unverified-save/re-enable-trial behavior.++Before provisioning a tool-only search credential, both create and replacement replay pending typed API-key cleanup. Every new tool-only cleanup intent records `revoke_search_credential` before unlinking; its engine-free operation survives missing or corrupt credential documents and never invalidates, reloads or reaps the model engine. Ordinary API-key intents keep their existing conservative engine cleanup semantics. Remaining unowned API-key/search intents (including an unreadable journal or a failed journal removal) refuse admission with `engine_down`/503. A later retry proceeds once cleanup converges. Active Source and prepared-takeover ownership are not cleanup failures; generic/OAuth intents remain with model-demand replay. Durable rollback still releases the create nonce: it preserves cleanup ownership but is not permission to provision another credential.++DeepSeek remains an ordinary `openai_chat` Source. Its catalog search capability is not a `search` Source and does not change the model Source's protocol, inventory, or engine binding; during DeepSeek Source create, the service performs the catalog's free check before the commit point. The check may save a balance or spending-limit health state, but never invokes a paid search request.+Existing Sources lacking the optional marker retain their existing state.Completed Hub OAuth consent can likewise retain its bound credential under the fixed@@ -640,7 +649,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:```json{"ok": true,- "contract_version": 16,+ "contract_version": 17,"source": {"id": "src_anthkey01","kind": "api_key",@@ -750,7 +759,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c```json{"ok": false,- "contract_version": 16,+ "contract_version": 17,"error": "source_last_supplier","would_remove_hops": [],"would_interrupt": [@@ -805,8 +814,11 @@ nonempty, and no refused branch removes a hop.Success returns the exact envelope selected by the authoritative matrix and thebyte-identical `RouteHopRef` array from the accepted plan.+For an API-key credential replacement on a tool-only `search` Source, the replacement check is performed before the commit point. Invalid replacement material preserves the existing Source and credential; all other outcomes follow the ordinary pending-state replacement rules while the new opaque reference becomes current only after commit. The old credential reference is revoked after the replacement commit, and a pre-commit failure revokes only the new reference. Replacement and deletion retire an armed or in-flight search trial only when the Source mutation commits, including a config write that lands before request cancellation; a rollback leaves the old trial untouched.+## Credential replacement and reauth+The commit point is the single durable write that makes the replacement source statelive. Hub OAuth has an earlier credential-irreversibility boundary when new grantmaterial is written under its identity-bound stable ref; that boundary does not make@@ -886,7 +898,7 @@ API-key success:```json{"ok": true,- "contract_version": 16,+ "contract_version": 17,"source": {"id": "src_relay9c1x","kind": "api_key",@@ -897,6 +909,10 @@ API-key success:}```+## Tool-only Source recovery++`POST /api/models/sources/<id>/reenable` is the recovery mutation for a tool-only `search` Source. It advances the Source's settlement generation without interrupting work. When a free check exists, `pass` clears the state, `invalid` moves it to the existing invalid-key state, and `balance`, `limit` or `unknown` keep or reclassify the current state without arming a trial. A Source without a free check preserves persisted `needs_action` and arms an in-memory one-shot trial; `Source.trial_pending` is true while the trial is armed or in flight, and a repeated request returns the current trial without advancing the generation. The response carries `trial_armed: true` when the trial is armed, and S2's search gate admits and settles it. No paid test search is sent.+## Source refresh and blocked-source recovery`POST /api/models/sources/<id>/refresh` is an explicit source-scoped operation. It may@@ -977,7 +993,7 @@ Status and submit return the same terminal shape:```json{"ok": true,- "contract_version": 16,+ "contract_version": 17,"flow": {"flow_id": "oaf_claude01","client_nonce": "ofn_01j5w8z7p4n6q2rt",@@ -1050,9 +1066,9 @@ a valid `interrupted` chain.```json{"ok": true,- "contract_version": 16,+ "contract_version": 17,"chain": {- "contract_version": 16,+ "contract_version": 17,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -1079,7 +1095,7 @@ In Direct mode both chain and probe refuse with:```json{"ok": false,- "contract_version": 16,+ "contract_version": 17,"error": "direct_mode","detail": "models.hub.direct_mode"}@@ -1093,9 +1109,9 @@ A successful probe nests its result:```json{"ok": true,- "contract_version": 16,+ "contract_version": 17,"probe": {- "contract_version": 16,+ "contract_version": 17,"backend": "claude","channel": "hub","reachable": false,@@ -1118,7 +1134,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 16,+ "contract_version": 17,"backend": "codex","channel": "native_cli","reachable": true,@@ -1131,7 +1147,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 16,+ "contract_version": 17,"backend": "codex","channel": "native_cli","reachable": false,@@ -1147,7 +1163,7 @@ No candidate is an API error with a typed model-scoped state:```json{"ok": false,- "contract_version": 16,+ "contract_version": 17,"error": "probe_no_candidate","detail": "models.probe.no_candidate.waiting","supply": {@@ -1338,7 +1354,7 @@ The store retains at most 500 exactly attributed settled turns with its existingwrites. Ambiguous attribution remains excluded; this is not a log of every upstreamrequest. Null means no matching retained record, including eviction. A newer served,canceled or other record without a terminal error supersedes older error display.-Success uses exactly `{ok: true, contract_version: 16, provenance: TurnProvenance | null}`;+Success uses exactly `{ok: true, contract_version: 17, provenance: TurnProvenance | null}`;there is no `success` field or envelope exception.Local `engine_down` records may also contain `local_error_detail`, an OS-generated@@ -1432,7 +1448,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 16,+ "contract_version": 17,"error": "provenance_unavailable","detail": "models.provenance.direct_mode"}@@ -1441,7 +1457,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 16,+ "contract_version": 17,"error": "provenance_unavailable","detail": "models.provenance.attribution_ambiguous"}@@ -1775,7 +1791,7 @@ contract harness and API-boundary tests enforce:<!-- authority-consumer: turn.served turn.exhausted turn.request_nonfallback turn.engine_down turn.streamed_fallback turn.no_candidate.unconfigured turn.no_candidate.unlisted turn.no_candidate.blocked turn.canceled --><!-- 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 mutation.route_restore mutation.default_sources --><!-- authority-consumer: import.keep_native import.copy_key import.reauth import.controlled -->-<!-- authority-consumer: protocol anthropic openai_responses openai_chat google -->+<!-- authority-consumer: protocol anthropic openai_responses openai_chat google search --><!-- authority-consumer: observation.outcome observed ambiguous unreachable authentication_failed adapter_error timeout --><!-- authority-consumer: observation.discovery succeeded failed not_attempted --><!-- authority-consumer: runtime.health ok degraded down not_installed installing not_started -->diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.jsonindex 8ca74e059..47d636676 100644--- a/docs/plans/model-hub-contracts/guard-refusal.schema.json+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json@@ -61,7 +61,7 @@],"properties": {"ok": { "const": false },- "contract_version": { "const": 16 },+ "contract_version": { "const": 17 },"error": {"enum": ["source_last_supplier",@@ -116,7 +116,7 @@"examples": [{"ok": false,- "contract_version": 16,+ "contract_version": 17,"error": "source_model_in_route_chain","detail": "modelHub.errors.source_model_in_route_chain","would_remove_hops": [diff --git a/docs/plans/model-hub-contracts/hop-origin.schema.json b/docs/plans/model-hub-contracts/hop-origin.schema.jsonindex 2ccacbe27..5fcaff0d5 100644--- a/docs/plans/model-hub-contracts/hop-origin.schema.json+++ b/docs/plans/model-hub-contracts/hop-origin.schema.json@@ -8,7 +8,7 @@"additionalProperties": false,"properties": {"provider": { "type": "string", "minLength": 1 },- "api": { "$ref": "source.schema.json#/properties/protocol" },+ "api": { "$ref": "source-probe-result.schema.json#/properties/protocol" },"model": { "type": "string", "minLength": 1 }}}diff --git a/docs/plans/model-hub-contracts/hop-resolution.schema.json b/docs/plans/model-hub-contracts/hop-resolution.schema.jsonindex 6de2f7bfb..b61d5abce 100644--- a/docs/plans/model-hub-contracts/hop-resolution.schema.json+++ b/docs/plans/model-hub-contracts/hop-resolution.schema.json@@ -9,7 +9,7 @@"properties": {"backend": { "const": "vibey" },"requested_model": { "type": "string" },- "protocol": { "$ref": "source.schema.json#/properties/protocol" },+ "protocol": { "$ref": "source-probe-result.schema.json#/properties/protocol" },"base_url": { "type": "string", "format": "uri" },"token": { "type": "string" },"runtime_model": { "type": "string" },diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex 29571f446..fd132ae0a 100644--- a/docs/plans/model-hub-contracts/mirror-registry.json+++ b/docs/plans/model-hub-contracts/mirror-registry.json@@ -1,5 +1,5 @@{- "contract_version": 16,+ "contract_version": 17,"input_generation": {"mode": "same_run_live_files","external_snapshot": "content_fingerprint_required"@@ -63,12 +63,12 @@"allowed_property_values": [{"file": "docs/plans/model-hub-contracts/source.schema.json",- "property_path": ["allOf", 0, "then", "properties", "vendor"],+ "property_path": ["allOf", 1, "then", "properties", "vendor"],"values": ["custom"]},{"file": "docs/plans/model-hub-contracts/source-create.schema.json",- "property_path": ["allOf", 0, "then", "properties", "vendor"],+ "property_path": ["allOf", 1, "then", "properties", "vendor"],"values": ["custom"]}],@@ -596,11 +596,6 @@"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",@@ -610,17 +605,37 @@"kind": "schema_vocabulary","schema": "source-create.schema.json","paths": ["/properties/protocol"]+ }+ ]+ },+ {+ "id": "D29",+ "domain": "Model protocols",+ "authority": {+ "kind": "schema_vocabulary",+ "schema": "source-probe-result.schema.json",+ "paths": ["/properties/protocol"]+ },+ "consumers": [+ {+ "kind": "python_string_assignment",+ "file": "core/handlers/model_hub/adapter.py",+ "name": "MODEL_PROTOCOLS"},{- "kind": "schema_vocabulary",- "schema": "source-probe-result.schema.json",- "paths": ["/properties/protocol"]+ "kind": "python_string_assignment",+ "file": "docs/plans/model-hub-contracts/adapter-interface.py",+ "name": "MODEL_PROTOCOLS"},{"kind": "schema_vocabulary","schema": "observation-result.schema.json",- "paths": ["/properties/protocol"],- "exclude": [null]+ "paths": ["/properties/protocol"]+ },+ {+ "kind": "marker_tail",+ "file": "docs/plans/model-hub-contracts/opencode-overlay.md",+ "marker": "authority-consumer: protocol "}]},diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.jsonindex a4ce038c0..07b7fc7e6 100644--- a/docs/plans/model-hub-contracts/observation-result.schema.json+++ b/docs/plans/model-hub-contracts/observation-result.schema.json@@ -16,7 +16,7 @@],"additionalProperties": false,"properties": {- "contract_version": { "const": 16 },+ "contract_version": { "const": 17 },"outcome": {"enum": ["observed",@@ -150,7 +150,7 @@],"examples": [{- "contract_version": 16,+ "contract_version": 17,"outcome": "observed","reachable": true,"authenticated": "authenticated",@@ -165,7 +165,7 @@]},{- "contract_version": 16,+ "contract_version": 17,"outcome": "authentication_failed","reachable": true,"authenticated": "rejected",@@ -175,7 +175,7 @@"model_metadata": []},{- "contract_version": 16,+ "contract_version": 17,"outcome": "ambiguous","reachable": true,"authenticated": "unknown",@@ -185,7 +185,7 @@"model_metadata": []},{- "contract_version": 16,+ "contract_version": 17,"outcome": "unreachable","reachable": false,"authenticated": "unknown",@@ -195,7 +195,7 @@"model_metadata": []},{- "contract_version": 16,+ "contract_version": 17,"outcome": "adapter_error","reachable": null,"authenticated": "unknown",@@ -205,7 +205,7 @@"model_metadata": []},{- "contract_version": 16,+ "contract_version": 17,"outcome": "timeout","reachable": null,"authenticated": "unknown",diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonindex cbd6a7ae2..f6fac6280 100644--- a/docs/plans/model-hub-contracts/probe-result.schema.json+++ b/docs/plans/model-hub-contracts/probe-result.schema.json@@ -7,7 +7,7 @@"required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "error"],"additionalProperties": false,"properties": {- "contract_version": { "const": 16 },+ "contract_version": { "const": 17 },"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },"channel": { "enum": ["hub", "native_cli"] },"reachable": { "type": "boolean" },@@ -68,10 +68,10 @@}],"examples": [- { "contract_version": 16, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },- { "contract_version": 16, "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": 16, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },- { "contract_version": 16, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },- { "contract_version": 16, "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" }+ { "contract_version": 17, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },+ { "contract_version": 17, "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": 17, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },+ { "contract_version": 17, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },+ { "contract_version": 17, "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/provider-overlay.schema.json b/docs/plans/model-hub-contracts/provider-overlay.schema.jsonindex 4e33d72f1..e5278a4bd 100644--- a/docs/plans/model-hub-contracts/provider-overlay.schema.json+++ b/docs/plans/model-hub-contracts/provider-overlay.schema.json@@ -161,7 +161,7 @@"hosted_tools": {"type": "object","propertyNames": {- "$ref": "source.schema.json#/properties/protocol"+ "$ref": "source-probe-result.schema.json#/properties/protocol"},"additionalProperties": {"type": "object",diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.jsonindex 1bb9d72ff..0bf044a27 100644--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json@@ -7,7 +7,7 @@"required": ["contract_version", "manifest", "status"],"additionalProperties": false,"properties": {- "contract_version": { "const": 16 },+ "contract_version": { "const": 17 },"enabled": {"type": "boolean","description": "Persisted user intent for the managed gateway. Fresh/default configuration is true; explicit stop persists false."@@ -131,7 +131,7 @@},"examples": [{- "contract_version": 16,+ "contract_version": 17,"host_platform": "darwin-arm64","manifest": {"name": "cliproxyapi",diff --git a/docs/plans/model-hub-contracts/served-hop.schema.json b/docs/plans/model-hub-contracts/served-hop.schema.jsonindex 0514861b4..f5f878874 100644--- a/docs/plans/model-hub-contracts/served-hop.schema.json+++ b/docs/plans/model-hub-contracts/served-hop.schema.json@@ -8,7 +8,7 @@"additionalProperties": false,"properties": {"provider": { "type": "string", "minLength": 1 },- "api": { "$ref": "source.schema.json#/properties/protocol" },+ "api": { "$ref": "source-probe-result.schema.json#/properties/protocol" },"model": { "type": "string", "minLength": 1 },"source": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" }}diff --git a/docs/plans/model-hub-contracts/source-create.schema.json b/docs/plans/model-hub-contracts/source-create.schema.jsonindex f9be7cf35..59b6038a0 100644--- a/docs/plans/model-hub-contracts/source-create.schema.json+++ b/docs/plans/model-hub-contracts/source-create.schema.json@@ -7,9 +7,37 @@"required": ["vendor", "key"],"additionalProperties": false,"allOf": [+ {+ "if": { "required": ["protocol"], "properties": { "protocol": { "const": "search" } } },+ "then": {+ "required": ["vendor", "key", "protocol"],+ "properties": {+ "vendor": { "enum": ["tavily", "exa"] },+ "base_url": { "type": "null" },+ "protocol": { "const": "search" },+ "save_unverified": { "const": false },+ "accept_unavailable_inventory": { "const": false }+ }+ }+ },{"if": { "required": ["protocol"], "properties": { "protocol": { "const": "google" } } },"then": { "properties": { "vendor": { "const": "custom" } } }+ },+ {+ "if": {+ "required": ["vendor"],+ "properties": { "vendor": { "enum": ["tavily", "exa"] } }+ },+ "then": {+ "properties": {+ "vendor": { "enum": ["tavily", "exa"] },+ "base_url": { "type": "null" },+ "protocol": { "const": "search" },+ "save_unverified": { "const": false },+ "accept_unavailable_inventory": { "const": false }+ }+ }}],"properties": {@@ -39,7 +67,7 @@"description": "Transient plaintext credential. It is never returned or persisted in Source state."},"protocol": {- "enum": ["anthropic", "openai_responses", "openai_chat", "google"],+ "enum": ["anthropic", "openai_responses", "openai_chat", "google", "search"],"description": "Optional user-selected interface. When present, observation probes exactly this protocol. Omission selects the shipped vendor pin when one exists; otherwise custom Auto requires matching response proof. Explicit unverified saving requires a catalog pin or a concrete custom declaration and never guesses a protocol."},"client_nonce": {diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex 175f9e2a9..4c2c25a2c 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -22,13 +22,17 @@"verification_pending": {"type": ["string", "null"],"pattern": "^vp_[0-9a-f]{32}$",- "description": "Opaque, non-secret pending-verification identity, replaced whenever Hub credential material or endpoint is stored without an add-time observation that authenticated it, same-handle OAuth reauthentication included. Presence means nothing upstream has accepted this credential yet, independently of routing health. An invocation captures this marker before admission; any successful call with the same current credential and marker may clear it through a fresh cross-process config mutation. Later same-credential calls do not invalidate proof. Inventory never clears it. Null or omission retains legacy behavior without a retrospective verification claim."+ "description": "Opaque, non-secret pending-verification identity, replaced whenever Hub credential material or endpoint is stored without authentication evidence, same-handle OAuth reauthentication included. Presence means nothing upstream has accepted this credential yet, independently of routing health. Model Sources keep the matching-credential model-call rule: an invocation captures this marker before admission, and a successful model call with the same current credential and marker may clear it. A tool-only search Source never makes a model call. For every search-capable Source, including an official DeepSeek model Source saved unverified, the marker clears on an authenticated search outcome with the matching credential (any 200, a 402, or a catalog-named limit), or a free-check pass, balance or limit for that credential. A 200 proves authentication even when its results are empty or its body is unreadable. Clearing requires the same current credential and marker and is a fresh cross-process config mutation; credential_generation does not change. Free-check unknown and invalid leave it unchanged. Later same-credential calls do not invalidate proof. Inventory never clears it. Null or omission retains legacy behavior without a retrospective verification claim."},"credential_generation": {"type": ["string", "null"],"pattern": "^vp_[0-9a-f]{32}$","description": "Opaque, non-secret identity of the Source's latest credential or endpoint change: the verification marker that change minted, kept after verification clears verification_pending. The Source identity that evidence, retry state, a turn's native-content pin and opaque-payload binding follow includes it instead of verification_pending, so verification changes no identity and an identity never returns to one an earlier credential had, even when OAuth reauthentication keeps the credential's handle. Absent on a verified Source no such change has touched since the field existed; a Source still pending from before the field takes its verification_pending as its generation. Either way a released Source's identity is unchanged."},+ "trial_pending": {+ "type": "boolean",+ "description": "Response-only search recovery state: true while the one-shot re-enable trial is armed or its admitted request is in flight. Never persisted in model_hub.sources."+ },"id": {"type": "string","pattern": "^src_[a-z0-9]{8,}$"@@ -64,7 +68,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)."+ "description": "Normalized vendor id, including a preserved retired catalog vendor. Source reads do not re-apply catalog create admission; tool-only search creation remains limited to the shipped search vendors. Also the OpenCode provider prefix (see opencode-overlay.md)."},"display_name": {"type": "string",@@ -75,7 +79,8 @@"anthropic","openai_responses","openai_chat",- "google"+ "google",+ "search"]},"base_url": {@@ -492,7 +497,7 @@"string","null"],- "description": "Opaque handle into the engine-owned credential store; secret material never appears in a payload. Null for native_cli Sources because their credential stays in the sanctioned CLI store, and non-null for hub Sources. Re-authenticating native_cli refreshes that CLI store and leaves this null; re-authenticating a hub Source replaces the engine-held grant behind its handle."+ "description": "Opaque handle into the Model Hub credential store; secret material never appears in a payload. Null for native_cli Sources because their credential stays in the sanctioned CLI store, and non-null for hub Sources. Re-authenticating native_cli refreshes that CLI store and leaves this null; re-authenticating a hub Source replaces the Model Hub-held grant behind its handle."},"account_label": {"type": [@@ -510,6 +515,19 @@}},"allOf": [+ {+ "if": { "properties": { "protocol": { "const": "search" } }, "required": ["protocol"] },+ "then": {+ "properties": {+ "kind": { "const": "api_key" },+ "supply_channel": { "const": "hub" },+ "billing": { "const": "metered" },+ "base_url": { "type": "null" },+ "models": { "maxItems": 0 }+ }+ },+ "else": { "not": { "required": ["trial_pending"] } }+ },{"if": { "properties": { "protocol": { "const": "google" } } },"then": { "properties": { "vendor": { "const": "custom" } } }@@ -538,7 +556,7 @@}},{- "$comment": "v2 (07-29, review round 4): the api_key shape. `supply_channel: hub` is not a default here but the only possibility — `native_cli` means the sanctioned CLI holds an OAuth credential in its own store (README 07-23 ruling), and a pasted key is provisioned into the engine-owned store instead, which is the hub channel by definition. `projected_exhaust_at` is pinned null for the reason at the field itself.",+ "$comment": "v2 (07-29, review round 4): the api_key shape. `supply_channel: hub` is not a default here but the only possibility — `native_cli` means the sanctioned CLI holds an OAuth credential in its own store (README 07-23 ruling), and a pasted key is provisioned into the Model Hub credential store instead, which is the hub channel by definition. `projected_exhaust_at` is pinned null for the reason at the field itself.","if": {"properties": {"kind": {diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonindex 1160377ff..b5695ded8 100644--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json@@ -36,7 +36,7 @@"additionalProperties": false,"properties": {"contract_version": {- "enum": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],+ "enum": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],"$comment": "The only versioned object written to disk, so released versions form a set rather than a constant. Historical records validate after the existing persistence-read normalization of retired reasons; tests/fixtures/model_hub/released_v5_permission_denied.json exercises that boundary, not raw-file validation. Reading preserves the writer generation and requires no new route fields. New records carry the terminal member. Other versioned objects are ephemeral envelopes pinned to that value alone.","description": "Generation that wrote this record. Readers retain every supported released value, apply existing retired-reason normalization independently of version, and do not require route_origin or manual_override."},@@ -487,7 +487,7 @@],"examples": [{- "contract_version": 16,+ "contract_version": 17,"turn_id": "turn_01k9x2m4","ts": "2026-07-29T06:32:11Z","agent": "claude",@@ -512,7 +512,7 @@"blockers": []},{- "contract_version": 16,+ "contract_version": 17,"turn_id": "turn_01k9x33p","ts": "2026-07-29T06:41:02Z","agent": "opencode",@@ -533,7 +533,7 @@"blockers": []},{- "contract_version": 16,+ "contract_version": 17,"turn_id": "turn_01k9x3zq","ts": "2026-07-29T06:48:20Z","agent": "codex",@@ -553,7 +553,7 @@]},{- "contract_version": 16,+ "contract_version": 17,"turn_id": "turn_01k9x4b7","ts": "2026-07-29T07:02:44Z","agent": "claude",@@ -573,7 +573,7 @@"blockers": []},{- "contract_version": 16,+ "contract_version": 17,"turn_id": "turn_modelmissing01","ts": "2026-09-05T17:31:10Z","agent": "claude",@@ -595,7 +595,7 @@"blockers": []},{- "contract_version": 16,+ "contract_version": 17,"turn_id": "turn_01k9x5ca","ts": "2026-07-29T07:08:00Z","agent": "codex",diff --git a/scripts/check_model_hub_authorities.py b/scripts/check_model_hub_authorities.pyindex 489435f7e..e23858fca 100644--- a/scripts/check_model_hub_authorities.py+++ b/scripts/check_model_hub_authorities.py@@ -310,17 +310,40 @@ def _python_literal_annotation(source: AuthorityInput, spec: dict[str, Any]) ->def _python_string_assignment(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:tree = source.python_tree(spec["file"])+ assignments: dict[str, ast.AST] = {}for node in tree.body:- if not isinstance(node, (ast.Assign, ast.AnnAssign)):- continue- targets = node.targets if isinstance(node, ast.Assign) else [node.target]- if not any(isinstance(target, ast.Name) and target.id == spec["name"] for target in targets):- continue- value = node.value- if value is None:- break- return _literal_strings(value)- raise ValueError(f"assignment not found: {spec['name']}")+ if isinstance(node, ast.Assign):+ for target in node.targets:+ if isinstance(target, ast.Name):+ assignments[target.id] = node.value+ elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.value is not None:+ assignments[node.target.id] = node.value++ def evaluate(node: ast.AST, stack: set[str] | None = None) -> set[str]:+ stack = set() if stack is None else stack+ if isinstance(node, ast.Constant) and isinstance(node.value, str):+ return {node.value}+ if isinstance(node, ast.Name):+ if node.id in stack or node.id not in assignments:+ return set()+ return evaluate(assignments[node.id], {*stack, node.id})+ if isinstance(node, (ast.Tuple, ast.List, ast.Set)):+ values: set[str] = set()+ for element in node.elts:+ values |= evaluate(element, stack)+ return values+ if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):+ return evaluate(node.left, stack) | evaluate(node.right, stack)+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in {"tuple", "frozenset", "set"}:+ return evaluate(node.args[0], stack) if len(node.args) == 1 else set()+ return _literal_strings(node)++ if spec["name"] not in assignments:+ raise ValueError(f"assignment not found: {spec['name']}")+ values = evaluate(assignments[spec["name"]])+ if not values:+ raise ValueError(f"string assignment is empty: {spec['name']}")+ return valuesdef _typescript_string_union(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.pyindex 84993ea16..212a62712 100644--- a/tests/e2e/test_model_hub_runtime.py+++ b/tests/e2e/test_model_hub_runtime.py@@ -684,7 +684,7 @@ def test_a1_feature_flag_disables_the_complete_models_api(assert response.status == 404, (method, path, body)assert body == {"ok": False,- "contract_version": 16,+ "contract_version": 17,"error": "feature_disabled",}diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.pyindex de7bd59bd..3027b2ed4 100644--- a/tests/e2e/test_model_hub_sources.py+++ b/tests/e2e/test_model_hub_sources.py@@ -13,7 +13,7 @@ from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstreampytestmark = pytest.mark.e2e_model_hub-CONTRACT_VERSION = 16+CONTRACT_VERSION = 17MENU_MODEL = "claude-sonnet-4-6"SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 240136336..da3b9b71a 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -44,7 +44,7 @@ from config.v2_config import ()from tests.opencode_generation_fakes import ui_lease, lease_returningfrom core.agent_auth_service import AgentAuthService-from core.handlers.model_hub.adapter import SOURCE_PROTOCOLS+from core.handlers.model_hub.adapter import MODEL_PROTOCOLSfrom core.handlers.model_hub.service import (ModelHubError,_NATIVE_VENDOR_BACKENDS,@@ -2473,7 +2473,7 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):# a path that was never taken.self.assertEqual(harness.adapter.observation_calls,- [(vendor, None, SOURCE_PROTOCOLS)],+ [(vendor, None, MODEL_PROTOCOLS)],)# Clean: no Source, credential revoked and unjournaled, flow# forgotten so the same vendor can be started again.@@ -3860,8 +3860,8 @@ def test_catalog_api_key_setup_observe_then_create_closed_loop(monkeypatch, tmp_@pytest.mark.parametrize(("vendor", "protocol"),- [(entry.id, entry.protocol) for entry in api_key_vendor_catalog()]- + [("custom", protocol) for protocol in SOURCE_PROTOCOLS],+ [(entry.id, entry.protocol) for entry in api_key_vendor_catalog() if entry.protocol in MODEL_PROTOCOLS]+ + [("custom", protocol) for protocol in MODEL_PROTOCOLS],)@pytest.mark.parametrize("auth_before_validation", [True, False])@pytest.mark.parametrize("public_inventory", [False, True])diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.pyindex 66bbf95b6..3a5041b47 100644--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py@@ -18,6 +18,7 @@ from config.v2_config import ()from core.handlers.model_hub.adapter import (DiscoveredModel,+ MODEL_PROTOCOLS,SOURCE_PROTOCOLS,ObservationDiscovery,ObservationOutcome,@@ -643,7 +644,7 @@ def test_mh_protocol_001_saved_protocol_is_response_observed_and_transient_state))- assert observed["observation"]["protocol"] in SOURCE_PROTOCOLS+ assert observed["observation"]["protocol"] in MODEL_PROTOCOLSassert observed["observation"]["authenticated"] == "authenticated"assert store.load().sources == []assert adapter.revoked == adapter.provisioned_transientdiff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.pyindex 22dcddbc5..2a47893bc 100644--- a/tests/test_instance_authorization.py+++ b/tests/test_instance_authorization.py@@ -512,6 +512,7 @@ def test_all_registered_model_hub_routes_follow_instance_management_roles() -> Nfor method in route.methods or ()}assert len(endpoints) >= 40+ assert ("POST", "/api/models/sources/sample-1/reenable") in endpointsfor method, path in endpoints:picker = method == "GET" and re.fullmatch(r"/api/models/agents/[^/]+/models", path)minimum_role = http_authorization_policy(method, path).minimum_role@@ -542,6 +543,8 @@ def test_model_hub_unknown_siblings_remain_owner_only(method: str) -> None:"/api/models/agents/claude/future-operation",):assert http_authorization_policy(method, path).minimum_role == "owner"+ if method != "POST":+ assert http_authorization_policy(method, "/api/models/sources/src-1/reenable").minimum_role == "owner"@pytest.mark.parametrize("method", ["PATCH", "DELETE"])diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.pyindex 8006f4830..2ce3c26b2 100644--- a/tests/test_member_management_parity.py+++ b/tests/test_member_management_parity.py@@ -118,7 +118,7 @@ def test_complete_registered_api_management_inventory():for method in (getattr(route, "methods", None) or ())if method not in {"HEAD", "OPTIONS"}}- assert len(endpoints) == 289+ assert len(endpoints) == 290assert ("GET", "/api/sessions/main") in endpointsassert http_authorization_policy("POST", "/api/vault/requests/{request_id}/approve-delete").minimum_role == "editor"# Approvers still read policy and remember duration; protection fields add a service check.diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 13034029b..8536ff7a9 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -44,7 +44,8 @@ from core.handlers.model_hub.adapter import (RawOutcomeKind,RetainedMaterialDisposition,RuntimePlatformUnsupportedError,- SOURCE_PROTOCOLS,+ SearchCredentialCheck,+ MODEL_PROTOCOLS,SourceObservation,)from core.handlers.model_hub.catalog_admission import admissible_backend_model@@ -211,6 +212,7 @@ class FakeAdapter:self.retargeted_credentials: list[tuple[str, str, str, str | None, str]] = []self.refreshable_credential_refs: set[str] = set()self.discovery_credential_refs: list[str] = []+ self.search_check_outcome = "unknown"async def ensure_installed(self, *, force=False, offline=False):self.ensure_calls.append(force)@@ -286,12 +288,18 @@ class FakeAdapter:self.credential_count += 1return f"cred_test{self.credential_count:03d}"+ async def check_search_credential(self, credential_ref, catalog):+ return SearchCredentialCheck(self.search_check_outcome)+async def revoke_credential(self, credential_ref):self.revoked.append(credential_ref)async def revoke_api_key_credential(self, credential_ref):await self.revoke_credential(credential_ref)+ async def revoke_search_credential(self, credential_ref):+ await self.revoke_api_key_credential(credential_ref)+async def cleanup_orphaned_oauth_material(self, credential_ref):self.orphan_cleanup_calls.append(credential_ref)return self.orphan_cleanup_succeeds@@ -589,6 +597,21 @@ def _seed_response_conformance_service(tmp_path: Path) -> ModelHubService:models=[],credential_ref="cred_delete0001",),+ ModelHubSourceConfig(+ id="src_searchbalance",+ kind="api_key",+ vendor="tavily",+ display_name="Search balance source",+ protocol="search",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.balance_exhausted",+ ),+ models=[],+ credential_ref="cred_searchbalance",+ ),ModelHubSourceConfig(id="src_subscribe01",kind="subscription",@@ -913,6 +936,14 @@ def test_every_model_hub_endpoint_returns_its_contract_response(if errors:error = _response_validation_error(errors)pytest.fail(f"{endpoint}: response field {_response_error_path(error)}: {error.message}")+ if route_contract["path"].endswith("/reenable"):+ for trial_armed in (False, True):+ assert validator.is_valid({**body, "trial_armed": trial_armed})+ elif route_contract["response_schema"] == "SourceMutationResponse":+ for trial_armed in (False, True):+ assert not validator.is_valid({**body, "trial_armed": trial_armed}), (+ f"{endpoint}: trial_armed is exclusive to search re-enable responses"+ )agent_payloads = []if isinstance(body.get("agent"), dict):agent_payloads.append(body["agent"])@@ -1031,7 +1062,7 @@ def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):assert adapter.start_calls == 1assert store.config.enabled is Trueassert runtime["enabled"] is True- assert runtime["contract_version"] == 16+ assert runtime["contract_version"] == 17assert runtime["status"]["health"] == "ok"_assert_valid("runtime-dependency.schema.json", runtime)@@ -1338,7 +1369,7 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 16, "status": {"health": "ok"}}+ return {"contract_version": 17, "status": {"health": "ok"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1355,7 +1386,7 @@ def test_runtime_stop_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 16, "status": {"health": "not_started"}}+ return {"contract_version": 17, "status": {"health": "not_started"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1372,7 +1403,7 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 16, "status": {"health": "installing"}}+ return {"contract_version": 17, "status": {"health": "installing"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1390,7 +1421,7 @@ def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypatdef rpc(operation, payload=None):calls.append((operation, payload))return {- "contract_version": 16,+ "contract_version": 17,"changed": True,"status": {"health": "not_started", "verified": True},}@@ -1408,6 +1439,38 @@ def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypat]+def test_reenable_client_and_controller_rpc_forward_payload(monkeypatch):+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc+ from vibe import model_hub_client++ calls = []++ async def rpc(operation, payload=None):+ calls.append((operation, payload))+ return {"source": {"id": "src_search01"}}++ monkeypatch.setattr(model_hub_client, "_rpc", rpc)+ result = asyncio.run(ModelHubRemoteService().reenable_search_source("src_search01"))++ assert result == {"source": {"id": "src_search01"}}+ assert calls == [("reenable_search_source", {"source_id": "src_search01"})]++ dispatched = []++ async def service_reenable(source_id, payload=None):+ dispatched.append((source_id, payload))+ return {"source": {"id": source_id}}++ service = object.__new__(type("ServiceStub", (), {}))+ service.reenable_search_source = service_reenable+ result = asyncio.run(dispatch_model_hub_rpc(service, "reenable_search_source", {+ "source_id": "src_search01",+ }))++ assert result == {"source": {"id": "src_search01"}}+ assert dispatched == [("src_search01", None)]++def test_reorder_client_preserves_explicit_null_order(monkeypatch):from vibe import model_hub_client@@ -4810,7 +4873,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):assert response.status_code == 200assert response.get_json() == {"ok": True,- "contract_version": 16,+ "contract_version": 17,"agent": {"backend": "codex","mode": "hub",@@ -5906,7 +5969,7 @@ def test_unsaved_observation_route_returns_valid_result_and_revokes_transient_rebody = response.get_json()_assert_envelope(body)_assert_valid("observation-result.schema.json", body["observation"])- assert body["observation"]["protocol"] == SOURCE_PROTOCOLS[0]+ assert body["observation"]["protocol"] == MODEL_PROTOCOLS[0]assert store.config.sources == []assert adapter.revoked == ["cred_test001"]assert "credential_ref" not in json.dumps(body)@@ -6020,6 +6083,27 @@ def test_unsaved_observation_route_rejects_omitted_protocol_for_an_uncataloged_vassert adapter.revoked == []+def test_create_source_defaults_a_search_catalog_vendor_to_search_protocol(tmp_path):+ service, store, adapter = _service(tmp_path)++ created = asyncio.run(+ _create_source(+ service,+ {+ "kind": "api_key",+ "vendor": "tavily",+ "key": "tvly-test-create-pinned",+ },+ )+ )++ assert created["protocol"] == "search"+ assert created["models"] == []+ assert created["base_url"] is None+ assert store.config.sources[0].protocol == "search"+ assert adapter.observed_protocol_orders == []++def test_create_source_defaults_a_catalog_vendor_to_its_pinned_protocol(tmp_path):service, store, adapter = _service(tmp_path)@@ -6039,6 +6123,7 @@ def test_create_source_defaults_a_catalog_vendor_to_its_pinned_protocol(tmp_pathassert adapter.observed_protocol_orders == [("openai_chat",)]assert store.config.sources[0].protocol == "openai_chat"assert store.config.sources[0].base_url is None+ assert store.config.sources[0].verification_pending is Noneassert adapter.revoked == ["cred_test001"]@@ -6061,6 +6146,7 @@ def test_create_source_defaults_catalog_display_names_for_all_shipped_api_key_ve"kind": "api_key","vendor": vendor,"key": f"sk-test-create-{vendor}",+ **({"protocol": "search"} if expected_protocol == "search" else {}),},))@@ -6071,10 +6157,386 @@ def test_create_source_defaults_catalog_display_names_for_all_shipped_api_key_veassert store.config.sources[0].display_name == expected_display_nameassert store.config.sources[0].protocol == expected_protocolassert store.config.sources[0].base_url is None- assert adapter.observed_protocol_orders == [(expected_protocol,)]+ assert adapter.observed_protocol_orders == ([] if expected_protocol == "search" else [(expected_protocol,)])+ assert adapter.revoked == ([] if expected_protocol == "search" else ["cred_test001"])+++++def test_search_source_create_journals_cleanup_when_revocation_fails(tmp_path):+ service, store, adapter = _service(tmp_path)+ adapter.search_check_outcome = "invalid"++ async def fail_revocation(_credential_ref):+ raise OSError("credential store temporarily unavailable")++ adapter.revoke_api_key_credential = fail_revocation++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "tavily",+ "protocol": "search",+ "key": "tvly-test-journal",+ }+ )+ )++ assert exc_info.value.detail == "modelHub.errors.authentication_failed"+ assert store.config.sources == []+ entries = service.revocations._read()+ assert len(entries) == 1+ assert entries[0].credential_ref == "cred_test001"+ assert entries[0].operation == "revoke_search_credential"++def test_search_source_delete_keeps_journal_when_revocation_fails(tmp_path):+ service, store, adapter = _service(tmp_path)+ source = asyncio.run(+ _create_source(+ service,+ {"kind": "api_key", "vendor": "tavily", "protocol": "search", "key": "tvly-delete"},+ )+ )++ async def fail_revocation(_credential_ref):+ raise OSError("credential directory fsync failed")++ adapter.revoke_api_key_credential = fail_revocation++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.delete_source(source["id"]))++ assert exc_info.value.code == "engine_down"+ assert store.config.sources == []+ pending = service.revocations.list()+ assert [(entry.source_id, entry.credential_ref, entry.operation) for entry in pending] == [+ (source["id"], source["credential_ref"], "revoke_search_credential"),+ ]+ before = adapter.credential_count+ with pytest.raises(ModelHubError) as blocked:+ asyncio.run(service.create_source({"kind": "api_key", "vendor": "tavily", "key": "test-next-key"}))+ assert (blocked.value.code, blocked.value.status) == ("engine_down", 503)+ assert adapter.credential_count == before+ assert store.config.sources == []+ assert service.revocations.list() == pending++[email protected]("outcome", ["pass", "balance", "limit", "unknown", "invalid"])+def test_search_source_create_uses_only_the_free_check_transaction(tmp_path, outcome: str):+ service, store, adapter = _service(tmp_path)+ adapter.search_check_outcome = outcome++ if outcome == "invalid":+ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.create_source(+ {"kind": "api_key", "vendor": "tavily", "protocol": "search", "key": "tvly-test"}+ )+ )+ assert exc_info.value.detail == "modelHub.errors.authentication_failed"+ assert store.config.sources == []+ assert adapter.revoked == ["cred_test001"]+ return++ source = asyncio.run(+ _create_source(+ service,+ {"kind": "api_key", "vendor": "tavily", "protocol": "search", "key": "tvly-test"},+ )+ )+ assert source["models"] == []+ assert source["base_url"] is None+ assert store.config.hosted_tools["web_search"].service_order == (source["id"],)+ if outcome in {"balance", "limit"}:+ assert source["state"]["status"] == "needs_action"+ assert source["state"]["detail_key"] == (+ "models.source.needs_action.balance_exhausted"+ if outcome == "balance"+ else "models.source.needs_action.spend_limit_reached"+ )+ assert source.get("verification_pending") is None+ elif outcome == "unknown":+ assert source["verification_pending"] is not None+ else:+ assert source.get("verification_pending") is None++[email protected]("outcome", ["balance", "limit"])[email protected]("supply", ["sole", "backup", "already_blocked"])+def test_deepseek_replacement_guards_new_supply_gaps(monkeypatch, tmp_path, outcome, supply):+ save_config(tmp_path / "home")+ service, store, adapter = _service(tmp_path)+ adapter.search_check_outcome = outcome+ model_id = "deepseek-v4"+ source = ModelHubSourceConfig(+ id="src_deepseekguard",+ kind="api_key",+ vendor="deepseek",+ display_name="DeepSeek",+ protocol="openai_chat",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id=model_id, provenance="manual")],+ credential_ref="cred_original_deepseek",+ masked_credential="sk-old…test",+ last_discovered_at="2026-07-22T03:00:00+00:00",+ )+ if supply == "already_blocked":+ source.state = ModelHubSourceStateConfig(+ status="needs_action", detail_key="models.source.needs_action.balance_exhausted",+ )+ store.config.sources = [source]+ if supply == "backup":+ backup = copy.deepcopy(source)+ backup.id = "src_deepseekbackup"+ backup.credential_ref = "cred_backup_deepseek"+ store.config.sources.append(backup)+ agent = store.config.agents["codex"]+ agent.models = [ModelHubBackendModelConfig(id=model_id)]+ agent.sources.order = [item.id for item in store.config.sources]+ agent.routes = {model_id: ModelHubRouteConfig(hops=tuple(+ ModelHubRouteHopConfig(item.id, model_id) for item in store.config.sources+ ))}+ service.named_agents_override = lambda backend: [("assistant", model_id)] if backend == "codex" else []+ 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)+ endpoint = f"/api/models/sources/{source.id}/credential"+ before = copy.deepcopy(store.config.to_payload())+ expected_plan = {+ "would_remove_hops": [],+ "would_interrupt": [{"backend": "codex", "model_id": model_id, "agents": ["assistant"]}],+ }+ if supply == "sole":+ assert service.agent_chain("codex", model_id)["current"] == {+ "source_id": source.id, "model_id": model_id,+ }+ for confirmation in (+ {},+ {"force": False, **expected_plan},+ {"force": True},+ {"force": True, "would_remove_hops": [], "would_interrupt": []},+ ):+ response = client.put(endpoint, json={"key": "sk-new-test", **confirmation}, headers=headers, base_url=origin)+ assert response.status_code == 409+ refusal = response.get_json()+ _assert_valid("guard-refusal.schema.json", refusal)+ assert refusal["error"] == "source_last_supplier"+ assert {key: refusal[key] for key in expected_plan} == expected_plan+ assert store.config.to_payload() == before+ assert adapter.revoked[-1] == f"cred_test{adapter.credential_count:03d}"+ assert source.credential_ref not in adapter.revoked+ assert service.revocations.list() == []+ # A stale nonempty echo is inert when the mutation introduces no supply gap.+ response = client.put(+ endpoint, json={"key": "sk-new-test", "force": True, **expected_plan},+ headers=headers, base_url=origin,+ )+ assert response.status_code == 200+ committed = response.get_json()+ assert committed["removed_hops"] == []+ assert committed["interrupted"] == (expected_plan["would_interrupt"] if supply == "sole" else [])+ assert committed["source"]["state"]["status"] == "needs_action"+ assert committed["source"]["state"]["detail_key"] == (+ "models.source.needs_action.balance_exhausted" if outcome == "balance"+ else "models.source.needs_action.spend_limit_reached"+ )+ assert committed["source"].get("verification_pending") is None+ assert committed["source"]["credential_ref"] == f"cred_test{adapter.credential_count:03d}"+ assert committed["source"]["credential_generation"]+ assert store.config.sources[0].to_payload()["models"] == before["sources"][0]["models"]+ assert committed["source"]["last_discovered_at"] == source.last_discovered_at+ assert store.config.agents["codex"].to_payload()["routes"] == before["agents"]["codex"]["routes"]+ assert adapter.discovery_credential_refs == []+ assert adapter.revoked[-1] == source.credential_ref+ assert committed["source"]["credential_ref"] not in adapter.revoked+ assert service.revocations.list() == []+ current = service.agent_chain("codex", model_id)["current"]+ assert current == ({"source_id": "src_deepseekbackup", "model_id": model_id} if supply == "backup" else None)+++def test_search_source_replacement_unknown_keeps_old_key_and_revokes_new_ref(tmp_path):+ service, store, adapter = _service(tmp_path)+ adapter.search_check_outcome = "unknown"+ source = ModelHubSourceConfig(+ id="src_searchreplace",+ kind="api_key",+ vendor="tavily",+ display_name="Tavily",+ protocol="search",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[],+ credential_ref="cred_old_search",+ masked_credential="••••rch",+ )+ store.config.sources = [source]++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.replace_credential(source.id, {"key": "tvly-new"}))++ assert exc_info.value.code == "discovery_failed"+ assert exc_info.value.status == 502+ assert exc_info.value.detail == "modelHub.errors.credential_replacement_unverified"+ persisted = store.load().sources[0]+ assert persisted.credential_ref == "cred_old_search"+ assert persisted.masked_credential == "••••rch"assert adapter.revoked == ["cred_test001"]+ ("outcome", "detail_key", "stays_pending"),+ [+ ("pass", None, False),+ ("balance", "models.source.needs_action.balance_exhausted", False),+ ("limit", "models.source.needs_action.spend_limit_reached", False),+ ("unknown", "models.source.needs_action.balance_exhausted", True),+ ("invalid", "models.source.needs_action.credential_revoked", True),+ ],+)+def test_search_source_reenable_free_check_keeps_or_reclassifies_state(+ tmp_path,+ outcome: str,+ detail_key: str | None,+ stays_pending: bool,+):+ service, store, adapter = _service(tmp_path)+ adapter.search_check_outcome = outcome+ marker = "vp_" + "a" * 32+ source = ModelHubSourceConfig(+ id="src_searchbalance",+ kind="api_key",+ vendor="tavily",+ display_name="Tavily",+ protocol="search",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.balance_exhausted",+ ),+ models=[],+ credential_ref="cred_searchbalance",+ verification_pending=marker,+ credential_generation=marker,+ )+ store.config.sources = [source]++ result = asyncio.run(service.reenable_search_source(source.id, {}))++ assert result["trial_armed"] is False+ assert result["source"]["state"]["detail_key"] == detail_key+ assert result["source"]["state"]["status"] == ("standby" if detail_key is None else "needs_action")+ assert not service.search_reenable_trial_armed(source.id)+ persisted = store.load().sources[0]+ assert persisted.state.detail_key == detail_key+ assert result["source"].get("verification_pending") == (marker if stays_pending else None)+ assert persisted.verification_pending == (marker if stays_pending else None)+ assert result["source"]["credential_generation"] == marker+ assert persisted.credential_generation == marker+ assert persisted.credential_ref == "cred_searchbalance"++++def test_search_source_reenable_arms_without_clearing_limit(tmp_path):+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_searchtrial",+ kind="api_key",+ vendor="exa",+ display_name="Exa",+ protocol="search",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.spend_limit_reached",+ ),+ models=[],+ credential_ref="cred_searchtrial",+ )+ store.config.sources = [source]+ result = asyncio.run(service.reenable_search_source(source.id, {}))++ assert result["trial_armed"] is True+ assert result["source"]["state"]["detail_key"] == "models.source.needs_action.spend_limit_reached"+ assert result["source"]["trial_pending"] is True+ assert service.search_reenable_trial_armed(source.id)+ assert service.search_reenable_trial_pending(source.id)+ repeated = asyncio.run(service.reenable_search_source(source.id, {}))+ assert repeated["trial_armed"] is True+ assert repeated["source"]["trial_pending"] is True+ assert service.search_reenable_trial_armed(source.id)+ assert service.reserve_search_reenable_trial(source.id) is True+ assert not service.search_reenable_trial_armed(source.id)+ assert service.search_reenable_trial_pending(source.id)+ assert service.list_sources()[0]["trial_pending"] is True+ repeated_inflight = asyncio.run(service.reenable_search_source(source.id, {}))+ assert repeated_inflight["source"]["trial_pending"] is True+ service.settle_search_reenable_trial(source.id)+ assert not service.search_reenable_trial_pending(source.id)+ assert service.list_sources()[0]["trial_pending"] is False+ assert store.load().sources[0].state.detail_key == "models.source.needs_action.spend_limit_reached"+ assert adapter.search_check_outcome == "unknown"++[email protected](("method", "suffix", "payload"), [+ ("PUT", "/credential", {"key": "test-replacement-key"}),+ ("POST", "/reenable", {}),+ ("PATCH", "", {"display_name": "Renamed retired service"}),+])+def test_preserved_search_vendor_is_readable_but_remove_only(monkeypatch, tmp_path, method, suffix, payload):+ save_config(tmp_path / "home")+ service, store, adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_retiredsearch", kind="api_key", vendor="retired-search-vendor",+ display_name="Retired search vendor", protocol="search", supply_channel="hub",+ billing="metered", state=ModelHubSourceStateConfig(+ status="needs_action", detail_key="models.source.needs_action.spend_limit_reached",+ ),+ models=[], credential_ref="cred_retiredsearch",+ )+ saved = store.config.to_payload()+ saved["sources"] = [source.to_payload()]+ store.config = ModelHubConfig.from_payload(saved)+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ response = client.get("/api/models/sources")+ assert response.status_code == 200+ body = response.get_json()+ assert body["sources"][0]["vendor"] == "retired-search-vendor"+ Draft7Validator(+ {"$ref": "model-hub/api-response.schema.json#/definitions/SourceListResponse"},+ registry=_api_response_registry(), format_checker=FormatChecker(),+ ).validate(body)+ with pytest.raises(ModelHubError):+ asyncio.run(service.create_source({+ "kind": "api_key", "vendor": source.vendor, "protocol": "search", "key": "test-retired-key",+ }))+ assert adapter.credential_count == 0+ assert store.load().sources[0].vendor == source.vendor+ before = store.load().to_payload()+ headers = csrf_headers(client, "http://127.0.0.1:15131")+ rejected = getattr(client, method.lower())(+ f"/api/models/sources/{source.id}{suffix}", json=payload, headers=headers,+ )+ assert rejected.status_code == 400+ assert rejected.get_json()["error"] == "discovery_failed"+ assert store.load().to_payload() == before+ assert adapter.credential_count == 0+ assert adapter.revoked == []+ assert not service.search_reenable_trial_pending(source.id)+ assert client.delete(f"/api/models/sources/{source.id}", headers=headers).status_code == 200+ assert store.load().sources == []+ assert adapter.revoked == [source.credential_ref]+ assert adapter.synced == []++def test_create_source_rejects_wrong_protocol_for_a_catalog_vendor(tmp_path):service, store, adapter = _service(tmp_path)@@ -9007,7 +9469,7 @@ def test_completed_hub_oauth_persists_only_a_response_proven_protocol(tmp_path):store.config.sources[0].models[0].reasoning_efforts_source== "catalog")- assert adapter.observed_protocol_orders == [SOURCE_PROTOCOLS]+ assert adapter.observed_protocol_orders == [MODEL_PROTOCOLS]assert adapter.revoked == []@@ -9678,7 +10140,7 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, tassert accepted.status_code == 200runtime = accepted.get_json()["runtime"]assert adapter.start_calls == 1- assert runtime["contract_version"] == 16+ assert runtime["contract_version"] == 17_assert_valid("runtime-dependency.schema.json", runtime)diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex dee0e4299..cab2a4648 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -37,6 +37,7 @@ from core.handlers.model_hub.adapter import (OBSERVATION_TERMINAL_RULES,ObservationDiscovery,ObservationOutcome,+ MODEL_PROTOCOLS,SOURCE_PROTOCOLS,SourceObservation,validate_source_observation,@@ -88,7 +89,7 @@ def test_auto_detect_asks_for_responses_before_chat():"""auto_sequence = ModelHubService._observation_protocols("custom", {})- assert set(auto_sequence) == set(SOURCE_PROTOCOLS) - {"google"}+ assert set(auto_sequence) == set(MODEL_PROTOCOLS) - {"google"}assert ModelHubService._observation_protocols("custom", {"protocol": "google"}) == ("google",)assert len(auto_sequence) == len(set(auto_sequence))assert auto_sequence.index("openai_responses") < auto_sequence.index("openai_chat")@@ -96,7 +97,7 @@ def test_auto_detect_asks_for_responses_before_chat():def test_unsaved_observation_schema_closes_all_terminal_shapes():schema = _schema("observation-result.schema.json")- assert schema["properties"]["contract_version"]["const"] == 16+ assert schema["properties"]["contract_version"]["const"] == 17assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(member.value for member in ObservationOutcome)@@ -115,12 +116,12 @@ 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})+ protocol_domain = frozenset({None, *MODEL_PROTOCOLS})discovery_domain = frozenset(ObservationDiscovery)def payload(observation: SourceObservation) -> dict:return {- "contract_version": 16,+ "contract_version": 17,"outcome": observation.outcome.value,"reachable": observation.reachable,"authenticated": (@@ -665,6 +666,42 @@ def test_source_create_unavailable_inventory_consent_is_explicit_and_total():assert required in ac_54+def test_source_create_applies_search_constraints_to_inferred_catalog_protocols():+ validator = Draft7Validator(_schema("source-create.schema.json"))++ for vendor in ("tavily", "exa"):+ inferred = {+ "vendor": vendor,+ "key": "search-secret",+ "base_url": "https://example.com",+ "save_unverified": True,+ }+ with pytest.raises(ValidationError):+ validator.validate(inferred)++ validator.validate({"vendor": vendor, "key": "search-secret"})++[email protected]("protocol", SOURCE_PROTOCOLS)[email protected]("trial_pending", [False, True])+def test_source_contract_limits_trial_pending_to_search(protocol, trial_pending):+ validator = Draft7Validator(_schema("source.schema.json"))+ source = ModelHubSourceConfig(+ id="src_trialcontract",+ kind="api_key",+ vendor="tavily" if protocol == "search" else "custom",+ display_name="Trial contract",+ protocol=protocol,+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ credential_ref="cred_trialcontract",+ models=[],+ ).to_payload()+ validator.validate(source)+ assert validator.is_valid({**source, "trial_pending": trial_pending}) is (protocol == "search")++def test_sparse_override_contract_has_one_default_order_owner():contract = (CONTRACTS.parent / "model-hub-routing-modes.md").read_text(encoding="utf-8")assert "sources.order` is the sole backend-default" in contract@@ -700,7 +737,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():route_refusal = {"ok": False,- "contract_version": 16,+ "contract_version": 17,"error": "source_in_route_chain","detail": "modelHub.errors.source_in_route_chain","would_remove_hops": [hop],@@ -716,7 +753,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():}candidate_refusal = {"ok": False,- "contract_version": 16,+ "contract_version": 17,"error": "candidate_suppliers_changed","detail": "modelHub.errors.candidate_suppliers_changed","changed": {@@ -800,7 +837,7 @@ def test_v8_mirror_registry_is_executable_and_complete():registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))schemas = _mirror_schemas(registry)- assert registry["contract_version"] == 16+ assert registry["contract_version"] == 17ids = [entry["id"] for entry in registry["entries"]]assert idsassert len(ids) == len(set(ids))@@ -937,8 +974,8 @@ def test_model_hub_authority_closure_anchors_the_persisted_version_floor(monkeyp"kind": "contract_version_schema_drift","domain": "V1","file": "docs/plans/model-hub-contracts/turn-provenance.schema.json",- "values": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],- "expected": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],+ "values": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],+ "expected": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],} in result["findings"]@@ -1249,7 +1286,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():with pytest.raises(ValidationError):chain_validator.validate(interrupted)exact_hop = {- "contract_version": 16,+ "contract_version": 17,"backend": "claude","model_id": "claude-opus-4-6","manual_override": None,@@ -3109,6 +3146,34 @@ def test_backend_model_modalities_match_the_contract_directions():ModelHubBackendModelConfig.from_payload({"id": "custom-model", "output_modalities": ["pdf"]})+def test_config_reload_preserves_search_source_when_catalog_vendor_is_missing(tmp_path):+ payload = api.config_to_payload(default_config())+ saved_source = ModelHubSourceConfig(+ id="src_searchmissing",+ kind="api_key",+ vendor="retired-search-vendor",+ display_name="Retired Search Vendor",+ protocol="search",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[],+ credential_ref="cred_searchmissing",+ masked_credential="••••sing",+ )+ payload["model_hub"]["sources"] = [saved_source.to_payload()]+ path = tmp_path / "config.json"+ path.write_text(json.dumps(payload), encoding="utf-8")++ loaded = V2Config.load(config_path=path)++ assert loaded.load_warnings == ()+ assert loaded.recovered_sections == ()+ assert loaded.model_hub.sources[0].vendor == "retired-search-vendor"+ assert loaded.model_hub.sources[0].protocol == "search"+ assert loaded.model_hub.sources[0].models == []++def test_config_reload_preserves_legacy_routes_without_seeding_missing_models(tmp_path):payload = api.config_to_payload(default_config())claude = payload["model_hub"]["agents"]["claude"]diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex e0ea48660..f19c0a542 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -46,7 +46,7 @@ from core.handlers.model_hub.adapter import (EngineStatus,RawCallOutcome,RawOutcomeKind,- SOURCE_PROTOCOLS,+ MODEL_PROTOCOLS,SourceBinding,)from core.handlers.model_hub.classification import ResolutionDecision, classify_outcome@@ -142,6 +142,7 @@ NOW = datetime(2026, 7, 29, 12, 0, tzinfo=timezone.utc)CATALOG_API_KEY_VENDOR_PROTOCOL_CASES = tuple(pytest.param(entry.id, entry.protocol, id=entry.id)for entry in api_key_vendor_catalog()+ if entry.protocol in MODEL_PROTOCOLS)@@ -5579,7 +5580,7 @@ def test_backend_failure_keeps_the_gateway_terminal_error_no_later_request_superdef test_released_backend_rejection_records_read_unchanged(tmp_path: Path) -> None:"""Records the earlier bridge wrote stay as written: no reason or phase is re-derived on read."""released = {- "contract_version": 16,+ "contract_version": 17,"turn_id": "turn_released_rejection","ts": NOW.isoformat(),"agent": "vibey",@@ -7055,7 +7056,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(_assert_valid("observation-result.schema.json",{- "contract_version": 16,+ "contract_version": 17,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -9510,7 +9511,7 @@ def test_probe_2xx_native_auth_error_uses_classified_blocker_detail("anthropic",{"model", "max_tokens", "messages"},)- for source_protocol in SOURCE_PROTOCOLS+ for source_protocol in MODEL_PROTOCOLS]+ [(@@ -9519,7 +9520,7 @@ def test_probe_2xx_native_auth_error_uses_classified_blocker_detail("openai_responses",{"model", "max_output_tokens", "input"},)- for source_protocol in SOURCE_PROTOCOLS+ for source_protocol in MODEL_PROTOCOLS]+ [(@@ -9533,7 +9534,7 @@ def test_probe_2xx_native_auth_error_uses_classified_blocker_detail(else {"model", "max_tokens", "messages"}),)- for source_protocol in SOURCE_PROTOCOLS+ for source_protocol in MODEL_PROTOCOLS],)def test_probe_request_matches_live_backend_protocol_matrix(@@ -9589,7 +9590,7 @@ def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:probe = asyncio.run(service.probe_agent("codex", "shared-model"))assert probe == {- "contract_version": 16,+ "contract_version": 17,"backend": "codex","channel": "native_cli","reachable": True,diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.pyindex 1419bf1d1..d2a421d4b 100644--- a/tests/test_model_hub_provenance.py+++ b/tests/test_model_hub_provenance.py@@ -261,7 +261,7 @@ def test_live_recovery_snapshots_never_revive_invalid_or_terminal_owners(tmp_patdef _record(turn_id, *, backend="claude", model=MODEL, outcome="failed_terminal"):identity = {"source_id": "src_deleted01", "configured_model_id": "unknown-model", "channel": "hub"}return {- "contract_version": 16,+ "contract_version": 17,"turn_id": turn_id,"ts": "2026-09-06T00:00:00Z","agent": backend,@@ -461,6 +461,6 @@ def test_model_history_client_rpc_http_share_nullable_read_only_result(monkeypatf"/api/models/agents/claude/provenance?model={MODEL}", headers=csrf_headers(client, origin), base_url=origin)assert response.status_code == 200- assert response.get_json() == {"ok": True, "contract_version": 16, "provenance": record}+ assert response.get_json() == {"ok": True, "contract_version": 17, "provenance": record}assert store.config.to_payload() == beforeassert adapter.synced == []diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex df4f6b4db..fecd986b5 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -1808,7 +1808,7 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):)assert result["observation"] == {- "contract_version": 16,+ "contract_version": 17,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -1839,7 +1839,7 @@ def test_unknown_adapter_error_does_not_claim_connection(tmp_path):assert exc.value.code == "discovery_failed"assert exc.value.detail == "modelHub.errors.adapter_error"assert exc.value.data["observation"] == {- "contract_version": 16,+ "contract_version": 17,"outcome": "adapter_error","reachable": None,"authenticated": "unknown",diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 75d5a9a68..c4d8b6f6a 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -31,10 +31,12 @@ from core.handlers.model_hub.adapter import (EngineHealth,OAuthSubmissionRejectedError,OriginNotAllowedError,+ MODEL_PROTOCOLS,RawCallOutcome,RawOutcomeKind,RetainedMaterialDisposition,RuntimePlatformUnsupportedError,+ SearchResponse,SOURCE_PROTOCOLS,SourceBinding,)@@ -56,7 +58,12 @@ from vibe.model_hub_runtime import client as client_modulefrom vibe.model_hub_runtime import installer as runtime_installer_modulefrom vibe.model_hub_runtime import supervisor as supervisor_modulefrom vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter-from vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalog, official_models_dev_provider+from vibe.model_hub_runtime.api_key_vendors import (+ _validate_search_catalog,+ api_key_vendor_catalog,+ official_models_dev_provider,+ search_service,+)from vibe.model_hub_runtime.client import (EngineClient,EngineClientError,@@ -109,6 +116,7 @@ API_KEY_VENDOR_RUNTIME_CASES = tuple(*[pytest.param(entry.id, entry.protocol, entry.official_base_url, id=entry.id)for entry in api_key_vendor_catalog()+ if entry.protocol in MODEL_PROTOCOLS],pytest.param("codex", "openai_responses", "https://api.openai.com/v1", id="codex"),]@@ -1359,7 +1367,7 @@ def test_manifest_resolution_drives_admission_persistence_and_schema(installer=manager,state_store=EngineStateStore(tmp_path / "state"),)- projected = {"contract_version": 16, **supervisor.status()}+ projected = {"contract_version": 17, **supervisor.status()}schema = json.loads(Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(encoding="utf-8"@@ -2258,6 +2266,340 @@ def test_a_persisted_key_source_survives_a_repin_of_its_vendor(tmp_path: Path) -]+def test_search_free_check_uses_bounded_catalog_transport(monkeypatch):+ calls: dict[str, object] = {}+ caller_thread = threading.current_thread().name++ class Store:+ def read_api_key(self, credential_ref):+ calls["read_thread"] = threading.current_thread().name+ return "tvly-secret"++ def credential_metadata(self, credential_ref):+ calls["metadata_thread"] = threading.current_thread().name+ return {"vendor": "tavily"}++ class ResponseContent:+ async def iter_chunked(self, _chunk_size):+ yield b'{"key":{"usage": 1, "limit": 10}, "account":{"plan_usage": 1, "plan_limit": 10}}'++ class Response:+ status = 200+ headers = {"Content-Type": "application/json", "X-Leak": "must-not-cross"}+ content = ResponseContent()++ class Request:+ async def __aenter__(self):+ return Response()++ async def __aexit__(self, *_args):+ return None++ class Session:+ def __init__(self, **kwargs):+ calls["session_kwargs"] = kwargs++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return None++ def request(self, method, endpoint, **kwargs):+ calls["request"] = (method, endpoint, kwargs)+ return Request()++ monkeypatch.setattr(runtime_adapter_module.aiohttp, "ClientSession", Session)+ adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=Store()) # type: ignore[arg-type]+ catalog = {+ "vendor": "tavily",+ "endpoint": "https://api.tavily.com/search",+ "auth": "bearer",+ "free_check": {+ "method": "GET",+ "endpoint": "https://api.tavily.com/usage",+ "pass": {"status": 200},+ "limit": {"pairs": [+ {"usage": "key.usage", "limit": "key.limit"},+ {"usage": "account.plan_usage", "limit": "account.plan_limit"},+ {"usage": "account.paygo_usage", "limit": "account.paygo_limit"},+ ]},+ "invalid_statuses": [401],+ },+ }++ outcome = asyncio.run(adapter.check_search_credential("cred_search", catalog))++ assert outcome.outcome == "pass"+ timeout = calls["session_kwargs"]["timeout"]+ assert timeout.total == 10.0+ assert timeout.connect == 5.0+ assert calls["session_kwargs"]["trust_env"] is False+ assert calls["request"][2]["allow_redirects"] is False+ assert calls["request"][2]["headers"] == {+ "Accept": "application/json",+ "Content-Type": "application/json",+ "Authorization": "Bearer tvly-secret",+ }+ assert calls["read_thread"] != caller_thread+ assert calls["metadata_thread"] != caller_thread+++ ("body_error", "expected_error"),+ [+ (asyncio.TimeoutError(), "timeout"),+ (ValueError("body read failed"), "connection"),+ (asyncio.CancelledError(), "cancelled"),+ ],+)+def test_search_response_retains_wire_facts_after_body_read_failure(+ monkeypatch, body_error, expected_error+):+ calls: list[str] = []++ class Store:+ def read_api_key(self, _credential_ref):+ return "tvly-secret"++ def credential_metadata(self, _credential_ref):+ return {"vendor": "tavily"}++ class ResponseContent:+ async def iter_chunked(self, _chunk_size):+ raise body_error+ yield b"" # pragma: no cover++ class Response:+ status = 503+ headers = {"Content-Type": "application/json", "Retry-After": "2"}+ content = ResponseContent()++ class Request:+ def __init__(self, traces):+ self.traces = traces++ async def __aenter__(self):+ for trace in self.traces:+ for callback in trace.on_connection_create_end:+ await callback(None, None, None)+ calls.append("write")+ return Response()++ async def __aexit__(self, *_args):+ return None++ class Session:+ def __init__(self, *, trace_configs, **_kwargs):+ self.traces = trace_configs++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return None++ def request(self, _method, _endpoint, **_kwargs):+ return Request(self.traces)++ monkeypatch.setattr(runtime_adapter_module.aiohttp, "ClientSession", Session)+ adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=Store()) # type: ignore[arg-type]++ response = asyncio.run(+ adapter.search(+ "src_search",+ "tavily",+ "tavily/search",+ "cred_search",+ {"query": "hello", "max_results": 1},+ on_sent=lambda: calls.append("sent"),+ )+ )++ assert response.http_status == 503+ assert response.headers == {"Content-Type": "application/json", "Retry-After": "2"}+ assert response.response_received_at is not None+ assert response.error == expected_error+ assert response.on_sent_fired is True+ assert calls == ["sent", "write"]+++def test_search_on_sent_fires_once_after_connection_ready_before_write(monkeypatch):+ calls: list[str] = []++ class Store:+ def read_api_key(self, _credential_ref):+ return "tvly-secret"++ def credential_metadata(self, _credential_ref):+ return {"vendor": "tavily"}++ class ResponseContent:+ async def iter_chunked(self, _chunk_size):+ yield b'{"results": []}'++ class Response:+ status = 200+ headers = {}+ content = ResponseContent()++ class Request:+ def __init__(self, traces):+ self.traces = traces++ async def __aenter__(self):+ for trace in self.traces:+ for callback in trace.on_connection_create_end:+ await callback(None, None, None)+ for callback in trace.on_connection_reuseconn:+ await callback(None, None, None)+ calls.append("write")+ return Response()++ async def __aexit__(self, *_args):+ return None++ class Session:+ def __init__(self, *, trace_configs, **_kwargs):+ self.traces = trace_configs++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return None++ def request(self, _method, _endpoint, **_kwargs):+ return Request(self.traces)++ monkeypatch.setattr(runtime_adapter_module.aiohttp, "ClientSession", Session)+ adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=Store()) # type: ignore[arg-type]++ response = asyncio.run(+ adapter.search(+ "src_search",+ "tavily",+ "tavily/search",+ "cred_search",+ {"query": "hello", "max_results": 1},+ on_sent=lambda: calls.append("sent"),+ )+ )++ assert response.http_status == 200+ assert response.on_sent_fired is True+ assert calls == ["sent", "write"]+++def test_search_free_check_propagates_cancelled_transport(monkeypatch):+ adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=object()) # type: ignore[arg-type]+ service = search_service("tavily", "search")+ assert service is not None++ async def response(**_kwargs):+ return SearchResponse(401, {"Retry-After": "2"}, None, "cancelled", True)++ monkeypatch.setattr(adapter, "_search_http", response)+ with pytest.raises(asyncio.CancelledError):+ asyncio.run(+ adapter.check_search_credential(+ "cred_search",+ {"vendor": "tavily", **service},+ )+ )+++def test_tavily_free_check_classifies_reported_usage_limit(monkeypatch):+ adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=object()) # type: ignore[arg-type]+ service = search_service("tavily", "search")+ assert service is not None++ async def response(**_kwargs):+ return SearchResponse(200, {}, b'{"key":{"usage": 10, "limit": 10}, "account":{"plan_usage": 1, "plan_limit": 20}}')++ monkeypatch.setattr(adapter, "_search_http", response)+ outcome = asyncio.run(+ adapter.check_search_credential(+ "cred_search",+ {"vendor": "tavily", **service},+ )+ )++ assert outcome.outcome == "limit"+++ ("body", "expected"),+ [+ ({"key": {"usage": 1, "limit": 10}}, "pass"),+ ({"key": {"usage": 1, "limit": None}}, "pass"),+ ({"key": {"usage": 1, "limit": 10}, "account": {}}, "pass"),+ ({"key": {"usage": 10, "limit": 10}}, "limit"),+ ({"key": {"usage": 11, "limit": 10}}, "limit"),+ ({"key": {"usage": 1, "limit": None}, "account": {"plan_usage": 1, "plan_limit": 10}}, "pass"),+ ({"account": {"plan_usage": 1, "plan_limit": 10}}, "pass"),+ ({"account": {"plan_usage": 10, "plan_limit": 10, "paygo_usage": 1, "paygo_limit": 10}}, "pass"),+ ({"key": {"usage": 1, "limit": 10}, "account": {"plan_usage": 10, "plan_limit": 10}}, "limit"),+ ],+)+def test_tavily_free_check_accepts_valid_pairs_with_optional_account(monkeypatch, body, expected):+ adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=object()) # type: ignore[arg-type]+ service = search_service("tavily", "search")+ assert service is not None++ async def response(**_kwargs):+ return SearchResponse(200, {}, json.dumps(body).encode("utf-8"))++ monkeypatch.setattr(adapter, "_search_http", response)+ outcome = asyncio.run(+ adapter.check_search_credential(+ "cred_search",+ {"vendor": "tavily", **service},+ )+ )+ assert outcome.outcome == expected++ "body",+ [+ {},+ {"key": {}, "account": {}},+ {"key": {"usage": "10", "limit": 20}},+ {"key": {"usage": 1}},+ {"key": {"limit": 10}},+ {"key": {"limit": None}},+ {"key": {"usage": True, "limit": 10}},+ {"key": {"usage": 1, "limit": False}},+ {"key": {"usage": float("nan"), "limit": 10}},+ {"key": {"usage": 1, "limit": float("inf")}},+ {"key": {"usage": 1, "limit": 10}, "account": {"plan_usage": 1}},+ {"key": {"usage": 1, "limit": None}, "account": {"paygo_limit": 10}},+ {"key": {"usage": 1, "limit": 10}, "account": None},+ {"key": {"usage": 1, "limit": 10}, "account": []},+ {"key": {"usage": 1, "limit": 10}, "account": "invalid"},+ {"key": None, "account": {"plan_usage": 1, "plan_limit": 10}},+ {"account": {"plan_usage": 10, "plan_limit": 20, "paygo_usage": "10"}},+ ],+)+def test_tavily_free_check_returns_unknown_for_invalid_reported_usage_fields(monkeypatch, body):+ adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=object()) # type: ignore[arg-type]+ service = search_service("tavily", "search")+ assert service is not None++ async def response(**_kwargs):+ return SearchResponse(200, {}, json.dumps(body).encode("utf-8"))++ monkeypatch.setattr(adapter, "_search_http", response)+ outcome = asyncio.run(+ adapter.check_search_credential(+ "cred_search",+ {"vendor": "tavily", **service},+ )+ )++ assert outcome.outcome == "unknown"++def test_source_record_requires_valid_reasoning_state() -> None:payload = {"source_id": "src_fixture123",@@ -2381,6 +2723,145 @@ def test_valid_source_state_is_loaded_without_touching_the_file(]+def test_shipped_api_key_vendor_catalog_matches_its_schema() -> None:+ catalog = json.loads(Path("vibe/data/api_key_vendors.json").read_text(encoding="utf-8"))+ schema = json.loads(Path("vibe/data/api_key_vendors.schema.json").read_text(encoding="utf-8"))+ Draft7Validator(schema).validate(catalog)+++def test_exa_catalog_bounds_content_and_marks_reported_cost_as_estimate() -> None:+ service = search_service("exa", "search")+ assert service["result"]["reported_cost"] == {+ "path": "costDollars.total", "estimate": True,+ }+ assert service["request"]["content_max_chars"] == {+ "path": "contents.text.maxCharacters", "value": 4000,+ }++[email protected](("mapping", "valid"), [+ ({"path": "contents.text.maxCharacters", "value": 4000}, True),+ ({"path": "contents.text.maxCharacters", "value": 1}, True),+ ("contents.text.maxCharacters", False),+ (None, False),+ ({}, False),+ ({"path": "contents.text.maxCharacters"}, False),+ ({"value": 4000}, False),+ ({"path": "", "value": 4000}, False),+ ({"path": 1, "value": 4000}, False),+ ({"path": "contents.text.maxCharacters", "value": True}, False),+ ({"path": "contents.text.maxCharacters", "value": "4000"}, False),+ ({"path": "contents.text.maxCharacters", "value": 0}, False),+ ({"path": "contents.text.maxCharacters", "value": -1}, False),+ ({"path": "contents.text.maxCharacters", "value": 1.5}, False),+ ({"path": "contents.text.maxCharacters", "value": 4001}, False),+ ({"path": "contents.text.maxCharacters", "value": 4000, "unknown": 1}, False),+])+def test_search_content_limit_metadata_matches_schema_and_runtime(mapping, valid) -> None:+ catalog = json.loads(Path("vibe/data/api_key_vendors.json").read_text(encoding="utf-8"))+ row = next(row for row in catalog if row["id"] == "exa")+ row["search"]["request"]["content_max_chars"] = mapping+ schema = json.loads(Path("vibe/data/api_key_vendors.schema.json").read_text(encoding="utf-8"))+ assert Draft7Validator(schema).is_valid([row]) is valid+ if valid:+ assert _validate_search_catalog(row["search"], protocol="search")["request"]["content_max_chars"] == mapping+ else:+ with pytest.raises(ValueError, match="content maximum"):+ _validate_search_catalog(row["search"], protocol="search")++[email protected](("mapping", "valid"), [+ ({"path": "costDollars.total", "estimate": True}, True),+ ({"path": "costDollars.total", "estimate": False}, True),+ ("costDollars.total", False),+ (None, False),+ ({}, False),+ ({"path": "costDollars.total"}, False),+ ({"estimate": True}, False),+ ({"path": "", "estimate": True}, False),+ ({"path": 1, "estimate": True}, False),+ ({"path": "costDollars.total", "estimate": "true"}, False),+ ({"path": "costDollars.total", "estimate": 1}, False),+ ({"path": "costDollars.total", "estimate": True, "unknown": 1}, False),+])+def test_search_reported_cost_metadata_matches_schema_and_runtime(mapping, valid) -> None:+ catalog = json.loads(Path("vibe/data/api_key_vendors.json").read_text(encoding="utf-8"))+ row = next(row for row in catalog if row["id"] == "exa")+ row["search"]["result"]["reported_cost"] = mapping+ schema = json.loads(Path("vibe/data/api_key_vendors.schema.json").read_text(encoding="utf-8"))+ assert Draft7Validator(schema).is_valid([row]) is valid+ if valid:+ assert _validate_search_catalog(row["search"], protocol="search")["result"]["reported_cost"] == mapping+ else:+ with pytest.raises(ValueError, match="reported cost"):+ _validate_search_catalog(row["search"], protocol="search")++[email protected]("has_null", [False, True])+def test_vendor_catalog_keeps_absent_or_null_search_metadata_valid(has_null) -> None:+ catalog = json.loads(Path("vibe/data/api_key_vendors.json").read_text(encoding="utf-8"))+ row = next(row for row in catalog if row["id"] == "openai")+ if has_null:+ row["search"] = None+ else:+ row.pop("search", None)+ schema = json.loads(Path("vibe/data/api_key_vendors.schema.json").read_text(encoding="utf-8"))+ Draft7Validator(schema).validate([row])+ assert _validate_search_catalog(row.get("search"), protocol=row["protocol"]) is None+++def test_search_query_limits_use_only_documented_vendor_bounds() -> None:+ assert {+ entry.id: entry.search["limits"]["query_max_chars"]+ for entry in api_key_vendor_catalog() if entry.search is not None+ } == {"deepseek": 128, "tavily": None, "exa": None}+++def test_only_deepseek_search_auto_enrolls_model_sources() -> None:+ enrolled = [entry.id for entry in api_key_vendor_catalog() if entry.search and entry.search.get("auto_enroll")]+ assert enrolled == ["deepseek"]+ assert search_service("deepseek", "openai_chat")["auto_enroll"] is True+ for vendor in ("tavily", "exa"):+ assert "auto_enroll" not in search_service(vendor, "search")++[email protected]("auto_enroll", [True, False, "true", 1, None, "absent"])+def test_model_search_auto_enrollment_matches_schema_and_runtime(auto_enroll) -> None:+ catalog = json.loads(Path("vibe/data/api_key_vendors.json").read_text(encoding="utf-8"))+ row = next(row for row in catalog if row["id"] == "deepseek")+ if auto_enroll == "absent":+ del row["search"]["auto_enroll"]+ else:+ row["search"]["auto_enroll"] = auto_enroll+ schema = json.loads(Path("vibe/data/api_key_vendors.schema.json").read_text(encoding="utf-8"))+ valid = isinstance(auto_enroll, bool)+ assert Draft7Validator(schema).is_valid([row]) is valid+ if valid:+ assert _validate_search_catalog(row["search"], protocol="openai_chat")["auto_enroll"] is auto_enroll+ else:+ with pytest.raises(ValueError, match="search catalog"):+ _validate_search_catalog(row["search"], protocol="openai_chat")++[email protected]("vendor", ["deepseek", "tavily", "exa"])[email protected]("results_max", [1, 5, 100, 101, 0, -1, True, 1.5, "100", None])+def test_search_catalog_results_ceiling_matches_schema_and_runtime(vendor, results_max) -> None:+ catalog = json.loads(Path("vibe/data/api_key_vendors.json").read_text(encoding="utf-8"))+ row = next(row for row in catalog if row["id"] == vendor)+ if results_max is None:+ del row["search"]["limits"]["results_max"]+ else:+ row["search"]["limits"]["results_max"] = results_max+ schema = json.loads(Path("vibe/data/api_key_vendors.schema.json").read_text(encoding="utf-8"))+ valid = type(results_max) is int and 1 <= results_max <= 100+ assert Draft7Validator(schema).is_valid([row]) is valid+ if valid:+ assert _validate_search_catalog(row["search"], protocol=row["protocol"]) == row["search"]+ else:+ with pytest.raises(ValueError, match="results maximum"):+ _validate_search_catalog(row["search"], protocol=row["protocol"])++@pytest.mark.parametrize(("vendor", "expected_base_url"),[@@ -2453,6 +2934,7 @@ def test_openai_compatibility_engine_base_url_uses_configured_api_root([pytest.param(entry.official_base_url, entry.protocol, id=entry.id)for entry in api_key_vendor_catalog()+ if entry.protocol in MODEL_PROTOCOLS],)def test_catalog_official_base_url_composes_one_probe_endpoint(@@ -9279,7 +9761,7 @@ def test_every_oauth_start_vendor_binds_by_exactly_one_route(return {"status_code": 200, "body": json.dumps({"type": "message"})}observed: set[str] = set()- for protocol in SOURCE_PROTOCOLS:+ for protocol in MODEL_PROTOCOLS:client = Client()try:runtime_adapter_module._probe_oauth_protocol_response(@@ -9303,7 +9785,7 @@ def test_every_oauth_start_vendor_binds_by_exactly_one_route(f"{vendor} must bind by exactly one of a response probe or an engine-declared pin")if pinned is not None:- assert pinned in SOURCE_PROTOCOLS+ assert pinned in MODEL_PROTOCOLSdef test_oauth_model_discovery_accepts_engine_definition_fields(tmp_path: Path) -> None:diff --git a/tests/test_model_hub_search_custody.py b/tests/test_model_hub_search_custody.pynew file mode 100644index 000000000..8b9e663de--- /dev/null+++ b/tests/test_model_hub_search_custody.py@@ -0,0 +1,476 @@+"""Search create custody outlives failed requests without requiring model-engine demand."""++import asyncio++import pytest++from core.handlers.model_hub.adapter import SearchCredentialCheck+from core.handlers.model_hub.service import ModelHubError+from tests.test_model_hub_api import _service+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter+from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore+++NONCE = "scn_searchcleanup0001"+++class _NoModelEngine:+ def __getattr__(self, name):+ pytest.fail(f"search custody reached the model engine: {name}")+++def _draft(**changes):+ return {"kind": "api_key", "vendor": "tavily", "key": "test-search-key", "client_nonce": NONCE, **changes}++[email protected]("restart", [False, True])[email protected]("nonce", [NONCE, "scn_searchcleanup0002", None])[email protected]("failure", ["revoke", "journal_remove"])+def test_search_create_waits_for_durable_cleanup_before_new_custody(tmp_path, monkeypatch, restart, nonce, failure):+ service, store, adapter = _service(tmp_path)+ adapter.search_check_outcome = "invalid"++ async def unavailable(_ref):+ raise OSError("test credential store unavailable")++ with monkeypatch.context() as patch:+ patch.setattr(adapter, "revoke_api_key_credential", unavailable)+ with pytest.raises(ModelHubError):+ asyncio.run(service.create_source(_draft()))+ assert len(service.revocations.list()) == 1+ assert NONCE not in service._source_create_nonces # Durable cleanup releases the claim.+ assert not store.load().sources+ if restart:+ service, store, adapter = _service(tmp_path, adapter)+ operations = []+ provision = adapter.provision_credential+ revoke = adapter.revoke_api_key_credential++ async def record_provision(*args):+ operations.append("provision")+ return await provision(*args)++ async def record_revoke(ref):+ operations.append("revoke")+ return await revoke(ref)++ monkeypatch.setattr(adapter, "provision_credential", record_provision)+ monkeypatch.setattr(adapter, "revoke_api_key_credential", record_revoke)+ adapter.search_check_outcome = "pass"+ adapter.fail_sync = True # No model engine dependency for a search-only retry.+ draft = _draft(client_nonce=nonce)+ if nonce is None:+ draft.pop("client_nonce")+ pending = service.revocations.list()+ before = adapter.credential_count+ with monkeypatch.context() as patch:+ if failure == "revoke":+ patch.setattr(adapter, "revoke_api_key_credential", unavailable)+ else:+ def fail_remove(*_args):+ raise OSError("test journal removal unavailable")+ patch.setattr(service.revocations, "remove", fail_remove)+ for _ in range(2):+ with pytest.raises(ModelHubError) as blocked:+ asyncio.run(service.create_source(draft))+ assert (blocked.value.code, blocked.value.status) == ("engine_down", 503)+ assert adapter.credential_count == before+ assert service.revocations.list() == pending+ assert not service._source_create_nonces+ assert not store.load().sources+ operations.clear()+ result = asyncio.run(service.create_source(draft))+ assert operations == ["revoke", "provision"]+ assert result["source"].get("client_nonce") == nonce+ assert service.revocations.list() == []+ assert adapter.synced == []+ assert adapter.start_calls == 0+ assert adapter.ensure_calls == []+++def test_search_retry_removes_the_real_local_orphan_without_an_engine(tmp_path, monkeypatch):+ custody = EngineStateStore(tmp_path / "custody")+ real = CLIProxyEngineAdapter(supervisor=_NoModelEngine(), state_store=custody)+ old_ref = asyncio.run(real.provision_credential("tavily", "search", "test-old-key", None))+ service, store, adapter = _service(tmp_path)+ service.revocations.add("src_oldsearch01", old_ref, operation="revoke_api_key_credential")+ monkeypatch.setattr(adapter, "provision_credential", real.provision_credential)+ monkeypatch.setattr(adapter, "revoke_api_key_credential", real.revoke_api_key_credential)+ created = asyncio.run(service.create_source(_draft()))["source"]+ assert custody.credential_metadata_if_present(old_ref) is None+ assert custody.credential_metadata_if_present(created["credential_ref"]) is not None+ assert service.revocations.list() == []+ assert store.load().sources[0].credential_ref == created["credential_ref"]+ assert adapter.synced == []++[email protected]("restart", [False, True])[email protected]("failure", ["journal_remove", "after_unlink"])+def test_search_cleanup_replay_keeps_its_identity_after_unlink(tmp_path, monkeypatch, restart, failure):+ custody = EngineStateStore(tmp_path / "custody")+ real = CLIProxyEngineAdapter(supervisor=_NoModelEngine(), state_store=custody)+ service, store, adapter = _service(tmp_path)+ monkeypatch.setattr(adapter, "provision_credential", real.provision_credential)+ monkeypatch.setattr(adapter, "revoke_api_key_credential", real.revoke_api_key_credential)+ monkeypatch.setattr(adapter, "revoke_search_credential", real.revoke_search_credential, raising=False)+ adapter.search_check_outcome = "invalid"+ retire = custody.revoke_api_key_credential++ def fail_remove(*_args):+ raise OSError("test journal removal unavailable")++ def fail_after_unlink(ref):+ retire(ref)+ raise OSError("test directory flush failed after unlink")++ with monkeypatch.context() as patch:+ if failure == "journal_remove":+ patch.setattr(service.revocations, "remove", fail_remove)+ else:+ patch.setattr(custody, "revoke_api_key_credential", fail_after_unlink)+ with pytest.raises(ModelHubError) as failed:+ asyncio.run(service.create_source(_draft()))+ assert failed.value.detail == "modelHub.errors.authentication_failed"+ pending = service.revocations.list()+ assert len(pending) == 1+ assert pending[0].operation == "revoke_search_credential"+ assert custody.credential_metadata_if_present(pending[0].credential_ref) is None+ assert not store.load().sources+ if restart:+ service, store, adapter = _service(tmp_path, adapter)+ adapter.search_check_outcome = "pass"+ created = asyncio.run(service.create_source(_draft()))["source"]+ assert service.revocations.list() == []+ assert custody.credential_metadata_if_present(created["credential_ref"]) is not None+ assert store.load().sources[0].credential_ref == created["credential_ref"]+ assert adapter.synced == []++[email protected]("document", ["missing", "corrupt", "model"])+def test_search_retirement_uses_durable_intent_but_rejects_readable_model_identity(tmp_path, document):+ custody = EngineStateStore(tmp_path / "custody")+ adapter = CLIProxyEngineAdapter(supervisor=_NoModelEngine(), state_store=custody)+ vendor, protocol = ("anthropic", "anthropic") if document == "model" else ("tavily", "search")+ ref = asyncio.run(adapter.provision_credential(vendor, protocol, "test-only-key", None))+ if document == "model":+ with pytest.raises(EngineStateError, match="not a search API key"):+ asyncio.run(adapter.revoke_search_credential(ref))+ assert custody.credential_metadata_if_present(ref) is not None+ return+ if document == "missing":+ custody.revoke_api_key_credential(ref)+ else:+ (custody.root / "credentials" / f"{ref}.json").write_text("{broken", encoding="utf-8")+ asyncio.run(adapter.revoke_search_credential(ref))+ asyncio.run(adapter.revoke_search_credential(ref))+ assert custody.credential_metadata_if_present(ref) is None++[email protected]("inflight", [False, True])[email protected](("mutation", "failure"), [+ ("replace", "provision"), ("replace", "cancel_provision"),+ ("replace", "commit"), ("delete", "commit"),+ ("replace", "cancel_before_commit"), ("delete", "cancel_before_commit"),+ ("replace", "cancel_after_commit"), ("delete", "cancel_after_commit"),+ ("replace", None), ("delete", None),+])+def test_search_trial_retirement_follows_mutation_commit(tmp_path, monkeypatch, inflight, mutation, failure):+ from config.v2_config import ModelHubSourceStateConfig++ service, store, adapter = _service(tmp_path)+ created = asyncio.run(service.create_source(_draft(vendor="exa")))["source"]+ source_id = created["id"]+ store.config.sources[0].state = ModelHubSourceStateConfig(+ status="needs_action", detail_key="models.source.needs_action.spend_limit_reached",+ )+ asyncio.run(service.reenable_search_source(source_id))+ if inflight:+ assert service.reserve_search_reenable_trial(source_id)+ before = store.load().to_payload()+ commit = service._commit_synced++ async def failed_provision(*_args):+ if failure == "cancel_provision":+ raise asyncio.CancelledError+ raise ModelHubError("engine_down", status=503)++ async def failed_commit(*args, **kwargs):+ if failure == "cancel_after_commit":+ await commit(*args, **kwargs)+ if failure.startswith("cancel_"):+ raise asyncio.CancelledError+ raise ModelHubError("engine_down", status=503)++ if failure in {"provision", "cancel_provision"}:+ monkeypatch.setattr(adapter, "provision_credential", failed_provision)+ elif failure is not None:+ monkeypatch.setattr(service, "_commit_synced", failed_commit)++ async def mutate():+ if mutation == "replace":+ return await service.replace_credential(source_id, {"key": "test-replacement-key"})+ return await service.delete_source(source_id)++ if failure is None:+ asyncio.run(mutate())+ else:+ with pytest.raises(asyncio.CancelledError if failure.startswith("cancel_") else ModelHubError):+ asyncio.run(mutate())+ committed = failure in {None, "cancel_after_commit"}+ assert service.search_reenable_trial_pending(source_id) is not committed+ assert service.search_reenable_trial_armed(source_id) is (not committed and not inflight)+ if committed:+ assert store.load().to_payload() != before+ else:+ assert store.load().to_payload() == before++[email protected]("remove_fails", [False, True])[email protected]("operation", ["revoke_api_key_credential", "revoke_search_credential"])+def test_search_cleanup_admission_preserves_live_and_takeover_credentials(+ tmp_path, monkeypatch, remove_fails, operation,+):+ service, store, adapter = _service(tmp_path)+ source = asyncio.run(service.create_source(_draft()))["source"]+ service.revocations.add(source["id"], source["credential_ref"], operation=operation)+ service.revocations.add("src_takeover01", "cred_takeover01", operation=operation)+ service.revocations.add("src_oauthold01", "cred_oauthold01")+ service.revocations.add("src_oauthorphan01", "cred_oauthorphan01", operation="cleanup_orphaned_oauth_material")+ monkeypatch.setattr(service.migration_journal, "load", lambda: {+ "credentials": [{"source_id": "src_takeover01", "credential_ref": "cred_takeover01"}],+ })+ if remove_fails:+ def fail_remove(*_args):+ raise OSError("test active-intent removal unavailable")+ monkeypatch.setattr(service.revocations, "remove", fail_remove)+ async def admit():+ async with service._mutation_lock:+ await service._require_api_key_cleanup_locked(store.load())++ asyncio.run(admit())+ assert not adapter.revoked+ assert not adapter.orphan_cleanup_calls+ expected = {"cred_takeover01", "cred_oauthold01", "cred_oauthorphan01"}+ if remove_fails:+ expected.add(source["credential_ref"])+ assert {entry.credential_ref for entry in service.revocations.list()} == expected+ assert store.load().sources[0].credential_ref == source["credential_ref"]+ assert adapter.synced == []++[email protected]("outcome", ["pass", "invalid"])[email protected]("next_mutation", ["create", "replace"])+def test_search_replacement_cleanup_gates_subsequent_custody(tmp_path, monkeypatch, outcome, next_mutation):+ service, store, adapter = _service(tmp_path)+ source = asyncio.run(service.create_source(_draft()))["source"]++ async def unavailable(_ref):+ raise OSError("test retirement unavailable")++ async def mutate():+ if next_mutation == "replace":+ return await service.replace_credential(source["id"], {"key": "test-next-key"})+ return await service.create_source(_draft(client_nonce="scn_searchcleanup0002"))++ with monkeypatch.context() as patch:+ patch.setattr(adapter, "revoke_api_key_credential", unavailable)+ adapter.search_check_outcome = outcome+ if outcome == "invalid":+ with pytest.raises(ModelHubError):+ asyncio.run(service.replace_credential(source["id"], {"key": "test-replacement-key"}))+ else:+ asyncio.run(service.replace_credential(source["id"], {"key": "test-replacement-key"}))+ pending = service.revocations.list()+ assert len(pending) == 1+ assert pending[0].operation == "revoke_search_credential"+ assert pending[0].credential_ref == (source["credential_ref"] if outcome == "pass" else "cred_test002")+ before_config, before_count = store.load().to_payload(), adapter.credential_count+ adapter.search_check_outcome = "pass"+ for _ in range(2):+ with pytest.raises(ModelHubError) as blocked:+ asyncio.run(mutate())+ assert (blocked.value.code, blocked.value.status) == ("engine_down", 503)+ assert adapter.credential_count == before_count+ assert store.load().to_payload() == before_config+ assert service.revocations.list() == pending+ asyncio.run(mutate())+ assert service.revocations.list() == []+ assert adapter.credential_count == before_count + 1+ assert adapter.synced == []++[email protected]("failure", ["unreadable", "cancelled"])+def test_search_cleanup_admission_failure_releases_nonce_without_provisioning(tmp_path, monkeypatch, failure):+ service, store, adapter = _service(tmp_path)+ service.revocations.add("src_orphan01", "cred_orphan01", operation="revoke_api_key_credential")+ pending = service.revocations.list()++ def unreadable():+ raise OSError("test journal unreadable")++ async def cancelled(_ref):+ raise asyncio.CancelledError++ with monkeypatch.context() as patch:+ if failure == "unreadable":+ patch.setattr(service.revocations, "list", unreadable)+ else:+ patch.setattr(adapter, "revoke_api_key_credential", cancelled)+ with pytest.raises(ModelHubError if failure == "unreadable" else asyncio.CancelledError) as blocked:+ asyncio.run(service.create_source(_draft()))+ if failure == "unreadable":+ assert (blocked.value.code, blocked.value.status) == ("engine_down", 503)+ assert not store.load().sources+ assert not service._source_create_nonces+ assert adapter.credential_count == 0+ assert service.revocations.list() == pending+ asyncio.run(service.create_source(_draft()))+ assert service.revocations.list() == []+ assert adapter.credential_count == 1+ assert adapter.synced == []++[email protected]("outcome", ["invalid", "cancelled"])+def test_deepseek_create_free_check_is_inside_permanent_custody_rollback(tmp_path, monkeypatch, outcome):+ service, store, adapter = _service(tmp_path)++ async def check(_ref, _catalog):+ if outcome == "cancelled":+ raise asyncio.CancelledError+ return SearchCredentialCheck("invalid")++ monkeypatch.setattr(adapter, "check_search_credential", check)+ with pytest.raises(asyncio.CancelledError if outcome == "cancelled" else ModelHubError):+ asyncio.run(service.create_source(_draft(vendor="deepseek", save_unverified=True)))+ assert store.load().sources == []+ assert adapter.revoked == ["cred_test001"]+ assert service.revocations.list() == []+ assert NONCE not in service._source_create_nonces+++def test_cancelled_search_provision_journals_typed_cleanup_and_can_retry(tmp_path, monkeypatch):+ async def scenario():+ service, store, adapter = _service(tmp_path)+ provision = adapter.provision_credential+ entered, release = asyncio.Event(), asyncio.Event()++ async def blocked_provision(*args):+ ref = await provision(*args)+ entered.set()+ await release.wait()+ return ref++ async def fail_revoke(_ref):+ raise OSError("test revocation unavailable")++ with monkeypatch.context() as patch:+ patch.setattr(adapter, "provision_credential", blocked_provision)+ patch.setattr(adapter, "revoke_api_key_credential", fail_revoke)+ task = asyncio.create_task(service.create_source(_draft()))+ await entered.wait()+ task.cancel()+ release.set()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert not store.load().sources+ assert NONCE not in service._source_create_nonces+ assert [(row.credential_ref, row.operation) for row in service.revocations.list()] == [+ ("cred_test001", "revoke_search_credential"),+ ]+ await service.create_source(_draft())+ assert service.revocations.list() == []+ assert adapter.revoked == ["cred_test001"]+ assert adapter.synced == []++ asyncio.run(scenario())+++def test_search_create_drains_cleanup_despite_repeated_cancellation(tmp_path, monkeypatch):+ async def scenario():+ service, store, adapter = _service(tmp_path)+ checking, cleaning, release = asyncio.Event(), asyncio.Event(), asyncio.Event()+ revoke = adapter.revoke_api_key_credential++ async def check(*_args):+ checking.set()+ await asyncio.Event().wait()++ async def blocked_revoke(ref):+ cleaning.set()+ await release.wait()+ await revoke(ref)++ monkeypatch.setattr(adapter, "check_search_credential", check)+ monkeypatch.setattr(adapter, "revoke_api_key_credential", blocked_revoke)+ task = asyncio.create_task(service.create_source(_draft()))+ await checking.wait()+ task.cancel()+ await cleaning.wait()+ task.cancel()+ await asyncio.sleep(0)+ assert not task.done()+ assert NONCE in service._source_create_nonces+ release.set()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert NONCE not in service._source_create_nonces+ assert adapter.revoked == ["cred_test001"]+ assert service.revocations.list() == []+ assert not store.load().sources++ asyncio.run(scenario())+++def test_search_create_cancellation_after_commit_keeps_the_bound_credential(tmp_path, monkeypatch):+ service, store, adapter = _service(tmp_path)+ commit = service._commit_new_source_locked++ async def interrupted_commit(*args, **kwargs):+ await commit(*args, **kwargs)+ raise asyncio.CancelledError++ monkeypatch.setattr(service, "_commit_new_source_locked", interrupted_commit)+ with pytest.raises(asyncio.CancelledError):+ asyncio.run(service.create_source(_draft()))+ assert store.load().sources[0].credential_ref == "cred_test001"+ assert adapter.revoked == []+ assert NONCE not in service._source_create_nonces+ with pytest.raises(ModelHubError) as duplicate:+ asyncio.run(service.create_source(_draft()))+ assert duplicate.value.code == "source_nonce_conflict"+ assert adapter.credential_count == 1++[email protected]("stage", ["invalid", "cancelled", "commit"])+def test_search_create_retains_nonce_only_when_cleanup_is_not_durable(tmp_path, monkeypatch, stage):+ service, store, adapter = _service(tmp_path)+ adapter.search_check_outcome = "invalid" if stage == "invalid" else "pass"++ async def fail_revoke(_ref):+ raise OSError("test revocation unavailable")++ def fail_journal(*_args, **_kwargs):+ raise OSError("test journal unavailable")++ async def cancel_check(*_args):+ raise asyncio.CancelledError++ async def fail_commit(*_args, **_kwargs):+ raise ModelHubError("engine_down")++ monkeypatch.setattr(adapter, "revoke_api_key_credential", fail_revoke)+ monkeypatch.setattr(service.revocations, "add", fail_journal)+ if stage == "cancelled":+ monkeypatch.setattr(adapter, "check_search_credential", cancel_check)+ if stage == "commit":+ monkeypatch.setattr(service, "_commit_new_source_locked", fail_commit)+ with pytest.raises(ModelHubError) as failed:+ asyncio.run(service.create_source(_draft()))+ assert failed.value.code == "engine_down"+ assert NONCE in service._source_create_nonces+ before = adapter.credential_count+ with pytest.raises(ModelHubError) as blocked:+ asyncio.run(service.create_source(_draft()))+ assert blocked.value.code == "source_create_in_progress"+ assert adapter.credential_count == before+ assert not store.load().sourcesdiff --git a/tests/test_model_hub_source_probe.py b/tests/test_model_hub_source_probe.pyindex 6c4061e3b..eadc2ea23 100644--- a/tests/test_model_hub_source_probe.py+++ b/tests/test_model_hub_source_probe.py@@ -9,7 +9,7 @@ from unittest.mock import AsyncMockimport pytestfrom config.v2_config import ModelHubSourceStateConfig-from core.handlers.model_hub.adapter import DiscoveredModel, RawOutcomeKind, SOURCE_PROTOCOLS, SourceBinding+from core.handlers.model_hub.adapter import DiscoveredModel, MODEL_PROTOCOLS, RawOutcomeKind, SourceBindingfrom core.handlers.model_hub.classification import ResolutionDecisionfrom core.handlers.model_hub.service import ModelHubErrorfrom core.handlers.model_hub import service as service_module@@ -17,7 +17,7 @@ from tests.test_model_hub_api import FakeAdapter, FakeInvokeHandle, _servicefrom tests.test_model_hub_unverified import _draft[email protected]("protocol", SOURCE_PROTOCOLS)[email protected]("protocol", MODEL_PROTOCOLS)@pytest.mark.parametrize("listing", ["success", "empty", "invalid", "failed"])def test_save_inventory_is_ordered_optional_and_never_authenticates(tmp_path, protocol, listing):service, store, adapter = _service(tmp_path)@@ -43,7 +43,7 @@ def test_save_inventory_is_ordered_optional_and_never_authenticates(tmp_path, pradapter.observe_source.assert_not_awaited()[email protected]("protocol", SOURCE_PROTOCOLS)[email protected]("protocol", MODEL_PROTOCOLS)@pytest.mark.parametrize("kind", list(RawOutcomeKind))def test_probe_invokes_selected_source_even_without_agent_routes_and_isolates_failure(tmp_path, protocol, kind):service, store, adapter = _service(tmp_path)@@ -185,7 +185,7 @@ def test_probe_refuses_invalid_or_unknown_selection_before_runtime_work(tmp_pathadapter.invoke.assert_not_awaited()[email protected]("protocol", SOURCE_PROTOCOLS)[email protected]("protocol", MODEL_PROTOCOLS)@pytest.mark.parametrize("model_id", ["fixture:free", "../fixture", "/fixture"])@pytest.mark.parametrize("selection", ["initial", "reconciled"])def test_saved_source_probe_checks_google_path_before_engine_and_at_admission(@@ -286,7 +286,7 @@ def test_optional_discovery_preserves_manual_inventory(tmp_path, listing):assert source["verification_pending"][email protected]("protocol", SOURCE_PROTOCOLS)[email protected]("protocol", MODEL_PROTOCOLS)def test_source_probe_crosses_real_adapter_and_http_transport(tmp_path, protocol):from aiohttp import webdiff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex 51d212c2e..89572e6df 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -427,6 +427,32 @@ def _auth_status_branch(node: ast.AST) -> bool:)[email protected]("surface", ["README.md", "source.schema.json"])+def test_verification_contract_covers_every_search_capable_source(surface: str) -> None:+ # These published rules guide S2's settlement implementation. Model Sources+ # with a search API can authenticate by either kind of call; tool-only ones+ # must never need a model call to verify their credential.+ text = (ROOT / "docs/plans/model-hub-contracts" / surface).read_text(encoding="utf-8")+ if surface.endswith(".json"):+ text = json.loads(text)["properties"]["verification_pending"]["description"]+ else:+ text = text.split("## Invariants", 1)[1].split("\n3.", 1)[0]+ text = " ".join(text.replace("`", "").split())+ for clause in (+ "matching-credential model-call rule",+ "tool-only search Source never makes a model call",+ "For every search-capable Source",+ "including an official DeepSeek model Source",+ "authenticated search outcome with the matching credential",+ "any 200, a 402, or a catalog-named limit",+ "free-check pass, balance or limit",+ "same current credential and marker",+ "credential_generation does not change",+ "Free-check unknown and invalid leave it unchanged",+ ):+ assert clause in text, (surface, clause)++def test_g1_cancelled_error_has_one_boundary_owner() -> None:# A new ``except asyncio.CancelledError`` outside _handle_request must fail.tree = _tree(TURN_GATEWAY)diff --git a/tests/test_model_hub_unverified.py b/tests/test_model_hub_unverified.pyindex 638d477cc..25cbeb58c 100644--- a/tests/test_model_hub_unverified.py+++ b/tests/test_model_hub_unverified.py@@ -16,7 +16,7 @@ from core.handlers.model_hub.adapter import (ObservationOutcome,RawCallOutcome,RawOutcomeKind,- SOURCE_PROTOCOLS,+ MODEL_PROTOCOLS,SourceObservation,)from core.handlers.model_hub.service import ModelHubError, V2ModelHubConfigStore@@ -39,8 +39,8 @@ def _draft(**changes):@pytest.mark.parametrize("owner",- [{"vendor": entry.id} for entry in api_key_vendor_catalog()]- + [{"vendor": "custom", "protocol": protocol} for protocol in SOURCE_PROTOCOLS],+ [{"vendor": entry.id} for entry in api_key_vendor_catalog() if entry.protocol in MODEL_PROTOCOLS]+ + [{"vendor": "custom", "protocol": protocol} for protocol in MODEL_PROTOCOLS],)def test_save_first_uses_declared_owner_despite_unavailable_inventory(tmp_path, owner):service, store, adapter = _service(tmp_path)diff --git a/tests/test_model_hub_vibey_contract_matrix.py b/tests/test_model_hub_vibey_contract_matrix.pyindex 1199078c7..b89fb9f85 100644--- a/tests/test_model_hub_vibey_contract_matrix.py+++ b/tests/test_model_hub_vibey_contract_matrix.py@@ -48,13 +48,13 @@ def _fixture(kind):# Start from a valid native response so no Hub latency constraint can# accidentally reject the Avibe/native pairing for an unrelated cause.return {- "contract_version": 16, "backend": "claude", "channel": "native_cli", "reachable": True,+ "contract_version": 17, "backend": "claude", "channel": "native_cli", "reachable": True,"source_id": "src_fixture01", "model_id": "fixture-model", "latency_ms": None,"error": None,}if kind == "chain":return {- "contract_version": 16, "backend": "vibey", "model_id": "fixture-model",+ "contract_version": 17, "backend": "vibey", "model_id": "fixture-model","manual_override": None, "route_origin": "automatic","chain": [{"source_id": "src_fixture01", "model_id": "fixture-model", "channel": "hub","health": "healthy", "runnable": True, "reason": None, "retry_at": None}],@@ -66,7 +66,7 @@ def _fixture(kind):"proposed_action": "import", "selected": False,}return {- "contract_version": 16, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z",+ "contract_version": 17, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z","agent": "vibey", "requested_model_id": "fixture-model", "outcome": kind,"failed_attempts": [{**identity, "reason": "rate_limited"}] if kind == "exhausted" else [],"served": identity if kind == "served" else None,diff --git a/tests/test_provider_overlay.py b/tests/test_provider_overlay.pyindex 4ca244378..8b0e03707 100644--- a/tests/test_provider_overlay.py+++ b/tests/test_provider_overlay.py@@ -41,7 +41,11 @@ def _fresh_overlay():def _validator() -> Draft7Validator:schemas = [json.loads((CONTRACTS / name).read_text(encoding="utf-8"))- for name in ("provider-overlay.schema.json", "source.schema.json")+ for name in (+ "provider-overlay.schema.json",+ "source.schema.json",+ "source-probe-result.schema.json",+ )]registry = Registry().with_resources((schema["$id"], Resource.from_contents(schema)) for schema in schemasdiff --git a/ui/e2e/chat-interactions/interactions.spec.ts b/ui/e2e/chat-interactions/interactions.spec.tsindex b9bbb7cbd..5cd5f201b 100644--- a/ui/e2e/chat-interactions/interactions.spec.ts+++ b/ui/e2e/chat-interactions/interactions.spec.ts@@ -11,7 +11,7 @@ for (const lang of ['en', 'zh'] as const) {if (url.origin !== 'http://127.0.0.1:5227' || route.request().method() !== 'GET') return route.abort();if (url.pathname === `/api/models/turns/${TURN}/provenance`) {return route.fulfill({ json: { provenance: {- contract_version: 16, turn_id: TURN, agent: 'codex', requested_model_id: 'fixture-model',+ contract_version: 17, turn_id: TURN, agent: 'codex', requested_model_id: 'fixture-model',outcome: 'failed_terminal', failed_attempts: [], blockers: [],terminal_error: { source_id: 'fixture-source', configured_model_id: 'fixture-model', reason: 'engine_down' },} } });diff --git a/ui/e2e/model-catalog/gatewayFixture.tsx b/ui/e2e/model-catalog/gatewayFixture.tsxindex b401d3f2b..e07f99d0f 100644--- a/ui/e2e/model-catalog/gatewayFixture.tsx+++ b/ui/e2e/model-catalog/gatewayFixture.tsx@@ -35,13 +35,13 @@ export function GatewayFixture() {}],};const chains = Object.fromEntries(ids.map((model_id, index) => [modelChainKey(backend, model_id), readyRegion<AgentChain>({- contract_version: 16, backend, model_id, route_origin: origins[index],+ contract_version: 17, backend, model_id, route_origin: origins[index],manual_override: origins[index] === 'manual' ? { hops: [{ source_id: source.id, model_id }] } : null,current: { source_id: source.id, model_id }, supply_state: 'ok',chain: [{ source_id: source.id, model_id, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],})]));const runtime = freshRuntimeProjection(readyRegion({- contract_version: 16,+ contract_version: 17,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },}));diff --git a/ui/e2e/model-catalog/routeFixture.tsx b/ui/e2e/model-catalog/routeFixture.tsxindex e107ba732..06158443f 100644--- a/ui/e2e/model-catalog/routeFixture.tsx+++ b/ui/e2e/model-catalog/routeFixture.tsx@@ -28,7 +28,7 @@ const supply: AgentSupply = {sources: { order: sources.map((source) => source.id), eligibility: sources.map((source) => ({ source_id: source.id, eligible: true })) },};const makeChain = (hops: RouteHop[], manual: boolean): AgentChain => ({- contract_version: 16, backend, model_id: modelId,+ contract_version: 17, backend, model_id: modelId,manual_override: manual ? { hops } : null,route_origin: manual ? 'manual' : origin === 'passthrough' ? 'passthrough' : 'automatic',current: hops[0] ?? null, supply_state: hops.length ? 'ok' : 'interrupted',diff --git a/ui/e2e/model-routing-origin.spec.ts b/ui/e2e/model-routing-origin.spec.tsindex 2a8745a2a..42bdf5cac 100644--- a/ui/e2e/model-routing-origin.spec.ts+++ b/ui/e2e/model-routing-origin.spec.ts@@ -102,7 +102,7 @@ test('MH-ROUTING-007 follow-defaults switch, undo, cancel, and save preserve expwould_remove_hops: [{ backend: gateway.backend, menu_model: gateway.model, ...manual.hops[0], position: 1 }],would_interrupt: [],};- expect(await refused.json()).toMatchObject({ ok: false, contract_version: 16, error: 'source_in_route_chain', ...plan });+ expect(await refused.json()).toMatchObject({ ok: false, contract_version: 17, error: 'source_in_route_chain', ...plan });expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);// The one question is its own modal over the chain the user was editing.const guard = hub.dialogTitled(copy('guard.title.saveRoute', { menuModel: gateway.model }));diff --git a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts b/ui/e2e/onboarding-fidelity/hub-ownership.spec.tsindex 3bff6f569..b6fc7222a 100644--- a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts+++ b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts@@ -92,7 +92,7 @@ for (const width of [1200, 390]) {if (path === '/api/models/runtime/status') return answer({ok: true,runtime: {- contract_version: 16, enabled: true, host_platform: 'linux',+ contract_version: 17, enabled: true, host_platform: 'linux',manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'a'.repeat(40), assets: [] },status: { installed_version: 'fixture', verified: true, health: 'ok' },},diff --git a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.tsindex 2d8ac8ffe..4fef97275 100644--- a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts+++ b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts@@ -18,7 +18,7 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] asconst config=()=>({version:'v2',mode:'self_host',setup_completed:completed,setup_state:{needs_setup:!completed},capabilities:{model_hub:{enabled:true}},platforms:{primary:'slack',enabled:[]},runtime:{},agents:Object.fromEntries(['claude','codex','opencode'].map(b=>[b,{enabled:b!=='opencode',cli_path:b}])),agent:{default_cwd:'/fixture/work'},model_hub:{enabled:true,runtime_default_applied:true}});const source={id:'src_fixture',kind:'api_key',vendor:'openai',display_name:'Fixture source',protocol:'openai_chat',supply_channel:'hub',billing:'metered',state:{status:'active'},masked_credential:'fixture-only',models:hops.map(h=>({id:h.model_id,display_name:h.model_id==='gpt-5'?'GPT-5':undefined,origin:'discovered',reasoning_efforts:[],reasoning_efforts_source:null})),last_discovered_at:null};const supply=(b:string)=>({backend:b,cli_present:true,mode:'hub',menu_kind:'fixed',sources:{order:[source.id],eligibility:[{source_id:source.id,eligible:true}]},routes:{},builtin_models:[],catalog_models:[],menu:null,model_supply:[],named_agents:[{name:b,effective_model_id:agent(b).model,supply_status:saved[b].length?'ok':'unavailable'}],supply_status:saved[b].length?'ok':'unavailable'});- const chain=(b:string,hs=saved[b])=>({contract_version:16,backend:b,model_id:agent(b).model,manual_override:hs.length?{hops:hs}:null,route_origin:hs.length?'manual':'automatic',current:hs[0]??null,chain:hs.map(h=>({...h,channel:'hub',health:'healthy',runnable:true,reason:null,retry_at:null})),supply_state:hs.length?'ok':'unavailable'});+ const chain=(b:string,hs=saved[b])=>({contract_version:17,backend:b,model_id:agent(b).model,manual_override:hs.length?{hops:hs}:null,route_origin:hs.length?'manual':'automatic',current:hs[0]??null,chain:hs.map(h=>({...h,channel:'hub',health:'healthy',runnable:true,reason:null,retry_at:null})),supply_state:hs.length?'ok':'unavailable'});await page.addInitScript(()=>localStorage.setItem('i18nextLng','en'));await page.route(`${ORIGIN}/api/**`,async route=>{const req=route.request(),path=new URL(req.url()).pathname;@@ -34,7 +34,7 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] as}if(path==='/api/agents')return answer({ok:true,default_agent_name:defaultName,agents:[agent('claude'),agent('codex')]});if(/^\/api\/agents\/(claude|codex)$/.test(path))return answer({ok:true,agent:agent(path.split('/').at(-1)!),default_agent_name:defaultName});- if(path==='/api/models/runtime/status')return answer({ok:true,runtime:{contract_version:16,enabled:true,host_platform:'linux',manifest:{name:'cliproxyapi',resolution:'resolved',version:'fixture',source_sha:'a'.repeat(40),assets:[]},status:{installed_version:'fixture',verified:true,health:'ok'}}});+ if(path==='/api/models/runtime/status')return answer({ok:true,runtime:{contract_version:17,enabled:true,host_platform:'linux',manifest:{name:'cliproxyapi',resolution:'resolved',version:'fixture',source_sha:'a'.repeat(40),assets:[]},status:{installed_version:'fixture',verified:true,health:'ok'}}});if(path==='/api/models/sources')return answer({ok:true,sources:[source]});if(path==='/api/models/agents')return answer({ok:true,agents:[supply('claude'),supply('codex')]});if(/\/api\/models\/agents\/(claude|codex)\/chains$/.test(path)){diff --git a/ui/e2e/onboarding-fidelity/provider-support.ts b/ui/e2e/onboarding-fidelity/provider-support.tsindex 378c619a3..580a1a77b 100644--- a/ui/e2e/onboarding-fidelity/provider-support.ts+++ b/ui/e2e/onboarding-fidelity/provider-support.ts@@ -129,7 +129,7 @@ const CONFIG = {/** Installed, verified and serving: the screen's `gatewayIntent` reads `running` and* starts no install, which is the state every proof below is about something else. */const RUNTIME = {- contract_version: 16,+ contract_version: 17,enabled: true,host_platform: 'darwin',manifest: {diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.tsindex 4a0c3e316..a66628e32 100644--- a/ui/e2e/onboarding-fidelity/support.ts+++ b/ui/e2e/onboarding-fidelity/support.ts@@ -87,7 +87,7 @@ export async function serveProduct(page: Page) {const backend = new URL(route.request().url()).pathname.split('/')[4];return route.fulfill({ json: { ok: true, agent: { backend, mode: 'direct', sources: { order: [], eligibility: [] }, routes: {}, builtin_models: [], catalog_models: [], named_agents: [], menu: null, model_supply: [], supply_status: 'unavailable' } } });});- await page.route('**/api/models/runtime/status', (route) => route.fulfill({ json: { ok: true, runtime: { contract_version: 16, enabled: true, host_platform: 'linux', manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', assets: [] }, status: { installed_version: 'fixture', verified: true, health: 'ok' } } } }));+ await page.route('**/api/models/runtime/status', (route) => route.fulfill({ json: { ok: true, runtime: { contract_version: 17, enabled: true, host_platform: 'linux', manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', assets: [] }, status: { installed_version: 'fixture', verified: true, health: 'ok' } } } }));await page.route(`${ORIGIN}/status`, (route) => route.fulfill({ json: { state: 'running' } }));await page.route('**/api/backend/*/connection', (route) => route.fulfill({ json: { ok: true, backend: new URL(route.request().url()).pathname.split('/').at(-2), installed: true, enabled: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false } }));await page.route('**/api/config', (route) => route.fulfill({ json: CONFIG }));diff --git a/ui/e2e/workbench-general/geometry.spec.ts b/ui/e2e/workbench-general/geometry.spec.tsindex 8a359dcc9..e4f88f484 100644--- a/ui/e2e/workbench-general/geometry.spec.ts+++ b/ui/e2e/workbench-general/geometry.spec.ts@@ -48,7 +48,7 @@ const MODEL_HUB_AGENT = {};const MODEL_HUB_RUNTIME = {- contract_version: 16,+ contract_version: 17,enabled: true,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'f'.repeat(40), assets: [] },status: { installed_version: 'fixture', verified: true, listening: { host: '127.0.0.1', port: 43123 }, health: 'ok' },diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsxindex 9bc387d1c..6f4b3b101 100644--- a/ui/src/components/onboarding/AssistantSetup.test.tsx+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx@@ -50,7 +50,7 @@ const hubAgent = (enabled = true) => ({system_prompt: null, created_at: '', metadata: { builtin_default: true },});const hubChain = (modelId: string) => ({- contract_version: 16, backend: 'claude', model_id: 'opus-5',+ contract_version: 17, backend: 'claude', model_id: 'opus-5',manual_override: { hops: [{ source_id: 'src_a', model_id: modelId }] },route_origin: 'manual', current: { source_id: 'src_a', model_id: modelId },chain: [{ source_id: 'src_a', model_id: modelId, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],@@ -354,7 +354,7 @@ describe('assistant installation presentation', () => {mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });mock.models.listSources.mockResolvedValue([]);const chain = {- contract_version: 16, backend: 'claude', model_id: 'opus-5',+ contract_version: 17, backend: 'claude', model_id: 'opus-5',manual_override: { hops: [{ source_id: 'src_a', model_id: 'opus-5' }, { source_id: 'src_b', model_id: 'opus-5' }] },route_origin: 'manual', current: { source_id: 'src_a', model_id: 'opus-5' },chain: [diff --git a/ui/src/components/onboarding/BuiltinAssistant.test.tsx b/ui/src/components/onboarding/BuiltinAssistant.test.tsxindex b073748ce..d7a2e0dcf 100644--- a/ui/src/components/onboarding/BuiltinAssistant.test.tsx+++ b/ui/src/components/onboarding/BuiltinAssistant.test.tsx@@ -65,7 +65,7 @@ const vibeyAgent = (model: string | null) => ({system_prompt: null, created_at: '', metadata: { builtin_default: true, lock_delete: true },});const chain = (modelId: string) => ({- contract_version: 16, backend: 'vibey', model_id: modelId,+ contract_version: 17, backend: 'vibey', model_id: modelId,manual_override: null, route_origin: 'automatic', current: { source_id: 'src_openai', model_id: modelId },chain: [{ source_id: 'src_openai', model_id: modelId, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],supply_state: 'ok',diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsxindex 737c30855..25f02ea5a 100644--- a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx+++ b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx@@ -79,7 +79,7 @@ const supply = (over: Partial<AgentSupply> & { backend: AgentSupply['backend'] }});const runtimeOf = (health: RuntimeHealth, over: Partial<RuntimeDependency> = {}): RuntimeDependency => ({- contract_version: 16,+ contract_version: 17,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },status: { verified: true, health },...over,diff --git a/ui/src/components/onboarding/providers/providerStage.test.ts b/ui/src/components/onboarding/providers/providerStage.test.tsindex 25ddf6a7e..82a6083e2 100644--- a/ui/src/components/onboarding/providers/providerStage.test.ts+++ b/ui/src/components/onboarding/providers/providerStage.test.ts@@ -660,7 +660,7 @@ describe('adoptionBackend', () => {});const runtime = (health: RuntimeHealth, over: Partial<RuntimeDependency> = {}): RuntimeDependency => ({- contract_version: 16,+ contract_version: 17,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },status: { verified: true, health },...over,diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsxindex fb744afc5..cca36bc42 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx@@ -43,6 +43,7 @@ const blockedSource: Source = {id: 'src_revoked',display_name: 'Revoked key',credential_ref: 'cred_revoked',+ credential_generation: 'gen_old',state: {status: 'needs_action',retry_at: null,@@ -52,6 +53,7 @@ const blockedSource: Source = {const successfulReplacementSource = (): Source => ({...blockedSource,+ credential_generation: 'gen_new',state: { status: 'standby', retry_at: null, detail_key: null },});@@ -558,6 +560,33 @@ describe('AddApiKeyDialog · replacement', () => {},);+ it('reconciles a committed but blocked replacement by credential generation', async () => {+ const current = {+ ...blockedSource,+ credential_generation: 'gen_new',+ state: {+ status: 'needs_action' as const,+ retry_at: null,+ detail_key: 'models.source.needs_action.spend_limit_reached' as const,+ },+ };+ vi.spyOn(modelsApi, 'replaceCredential').mockRejectedValueOnce(+ new ApiCallError('bad_response', undefined, false),+ );+ const settled = neverResolvingSettlement({+ readInventory: vi.fn().mockResolvedValue({ snapshot: 2, sources: [current] }),+ });+ const { onClose } = renderReplacement(blockedSource, settled);+ const user = userEvent.setup();++ await user.type(screen.getByLabelText(/^New API key$|^新的 API Key$/i), 'sk-blocked-committed');+ await user.click(screen.getByRole('button', { name: /^Replace$|^更换$/i }));++ await waitFor(() => expect(onClose).toHaveBeenCalledOnce());+ expect(settled.source).toHaveBeenCalledWith(current);+ expect(showToast).toHaveBeenCalledWith(i18n.t('settings.models.repair.unresolved'), 'warning');+ });+it('keeps Retry when an ambiguous replacement still observes the blocked source', async () => {vi.spyOn(modelsApi, 'replaceCredential').mockRejectedValueOnce(new ApiCallError('bad_response', undefined, false),diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsxindex 63334efee..dc3467741 100644--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx@@ -63,7 +63,7 @@ const replacementToast = (source: Source, gaps: SupplyGap[] = []) =>type ReplacePhase =| { kind: 'edit' }| { kind: 'submitting' }- | { kind: 'failure'; failureClass: ModelHubFailureClass };+ | { kind: 'failure'; failureClass: ModelHubFailureClass; messageKey?: string | null };type AddApiKeyDialogProps = {open: boolean;@@ -144,10 +144,11 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {seq: ContinuationTicket,failureClass: ModelHubFailureClass,settle?: () => Promise<SourceMutationLanding>,+ messageKey?: string | null,) => {continuation.settle(seq, () => {setGuard(null);- setReplacePhase({ kind: 'failure', failureClass });+ setReplacePhase({ kind: 'failure', failureClass, messageKey });});if (settle) void settle().catch(() => undefined);}, [continuation]);@@ -218,7 +219,10 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {() => settlement.gone(latest.id, inventory),);return;- } else if (!wasBlocked(current.state)) {+ } else if (+ !wasBlocked(current.state)+ || current.credential_generation !== latest.credential_generation+ ) {publishReplacementEvidence(seq,settlement,@@ -232,7 +236,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {return;}} else settlement.release();- publishReplacementFailure(seq, failureClass);+ publishReplacementFailure(seq, failureClass, undefined, failure?.detail);}});}, [apiKey, continuation, props, publishReplacementEvidence, publishReplacementFailure, replacePhase.kind]);@@ -358,7 +362,8 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {><TriangleAlert className="model-hub-add-key-error-ink size-3.5 shrink-0" /><span className="model-hub-add-key-error-ink model-hub-add-key-strip-title">- {t(REPLACE_FAILURE_KEY[replacePhase.failureClass])}+ {serverText(t, replacePhase.messageKey, REPLACE_FAILURE_KEY[replacePhase.failureClass])+ ?? t(REPLACE_FAILURE_KEY[replacePhase.failureClass])}</span></div>)}diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex 454a5079c..97f4bd09b 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -17,7 +17,7 @@ import { freshRuntimeProjection } from './runtimeLifecycle';import type { AgentSupply, RuntimeDependency, Source } from './types';const runtime: RuntimeDependency = {- contract_version: 16,+ contract_version: 17,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },};@@ -414,7 +414,7 @@ describe('AgentCard', () => {['zh', 'Backup → claude-opus-4-6(已自动切换)', '打开 claude-opus-4-6 的路由 · Backup → claude-opus-4-6(已自动切换)'],] as const)('derives and announces takeover from the exact current hop in %s', (lng, mappingCopy, accessibleName) => {const key = modelChainKey('claude', 'claude-opus-4-6');- render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 16, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 17, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.getByText(/Backup/)).toBeTruthy();expect(screen.getByTitle(mappingCopy)).toBeTruthy();expect(screen.getByRole('button', { name: accessibleName })).toBeTruthy();@@ -434,7 +434,7 @@ describe('AgentCard', () => {sources={[source('src_b', 'Backup source')]}chains={{[key]: readyRegion({ manual_override: {hops:[{source_id:'src_b',model_id:'routed-opus'}]}, route_origin: "manual" as const,- contract_version: 16,+ contract_version: 17,backend: 'claude',model_id: 'claude-opus-4-6',current: { source_id: 'src_b', model_id: 'routed-opus' },@@ -467,7 +467,7 @@ describe('AgentCard', () => {it('does not call a later current hop takeover unless the head is unavailable for cooldown', () => {const key = modelChainKey('claude', 'claude-opus-4-6');- render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 16, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 17, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.getByText(/Backup/)).toBeTruthy();expect(screen.queryByText(/takeover/i)).toBeNull();});@@ -475,7 +475,7 @@ describe('AgentCard', () => {it('hides current and takeover projections while the runtime is stopped', () => {const key = modelChainKey('claude', 'claude-opus-4-6');const stopped = { ...runtime, status: { ...runtime.status, health: 'down' as const } };- render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 16, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 17, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.queryByText(/Backup/)).toBeNull();expect(screen.queryByText(/takeover/i)).toBeNull();@@ -487,7 +487,7 @@ describe('AgentCard', () => {const onOpenModels = vi.fn();const key = modelChainKey('claude', 'claude-opus-4-6');const directAgent: AgentSupply = { ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null };- render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 16, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 17, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.queryByText(/Adjust priority/i)).toBeNull();expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();expect(screen.queryByText(/Backup/)).toBeNull();diff --git a/ui/src/components/settings/models/ApiKeySourceForm.tsx b/ui/src/components/settings/models/ApiKeySourceForm.tsxindex dfecd4a6c..874da7942 100644--- a/ui/src/components/settings/models/ApiKeySourceForm.tsx+++ b/ui/src/components/settings/models/ApiKeySourceForm.tsx@@ -20,7 +20,7 @@ import { Input } from '@/components/ui/input';import { cn } from '@/lib/utils';import { PROTOCOL_COPY_KEYS } from './addApiKeyState';-import { API_KEY_VENDOR_PRESETS, apiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';+import { API_KEY_VENDOR_PRESETS, modelApiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';import {draftNameValid,draftProtocol,@@ -179,7 +179,7 @@ export const ApiKeySourceForm: React.FC<{}> = ({ draft, disabled, revealed, autoFocusKey, keyLabel, onChange, onToggleReveal, onSubmit }) => {const { t } = useTranslation();const vendorOptions = useVendorOptions();- const vendorPreset = apiKeyVendorPreset(draft.vendor);+ const vendorPreset = modelApiKeyVendorPreset(draft.vendor);const nameValid = draftNameValid(draft);return (diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsxindex cf48d12bf..b51cca36a 100644--- a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx+++ b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx@@ -34,7 +34,7 @@ const CLAUDE_KEY: MigrationItem = {};const RUNTIME: RuntimeDependency = {- contract_version: 16,+ contract_version: 17,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },status: { installed_version: '1', verified: true, health: 'ok' },};diff --git a/ui/src/components/settings/models/RouteCandidatePopover.tsx b/ui/src/components/settings/models/RouteCandidatePopover.tsxindex e69aa919c..1146e318f 100644--- a/ui/src/components/settings/models/RouteCandidatePopover.tsx+++ b/ui/src/components/settings/models/RouteCandidatePopover.tsx@@ -92,7 +92,7 @@ export const RouteCandidatePopover: React.FC<{else result.push({ source: item.source, items: [item] });return result;}, []);- const typedSources = sources.filter((source) => source.kind === 'api_key');+ const typedSources = sources.filter((source) => source.kind === 'api_key' && source.protocol !== 'search');const typedSource = typedSources.find((source) => source.id === customSource);const typedCandidate: RouteCandidate | null = customModel && typedSource&& customModel === customModel.trim()diff --git a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsxindex 5a549f9be..a1598f4df 100644--- a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx@@ -17,7 +17,7 @@ const sources: Source[] = ['a', 'b'].map((id) => ({}));const hops = sources.map((source) => ({ source_id: source.id, model_id: 'gpt-test' }));const makeChain = (backend: AgentSupply['backend'], routeOrigin: 'automatic' | 'passthrough' | 'manual'): AgentChain => ({- contract_version: 16, backend, model_id: 'gpt-test', route_origin: routeOrigin,+ contract_version: 17, backend, model_id: 'gpt-test', route_origin: routeOrigin,manual_override: routeOrigin === 'manual' ? { hops } : null,current: hops[0], supply_state: 'ok',chain: hops.map((hop) => ({ ...hop, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null })),diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsxindex 8b989ab5c..548af086d 100644--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx@@ -57,7 +57,7 @@ const sources: Source[] = [},];const chain: AgentChain = { manual_override: {hops:[{source_id:"src_a",model_id:"claude-opus-5"},{source_id:"src_b",model_id:"opus-5"}]}, route_origin: "manual" as const,- contract_version: 16,+ contract_version: 17,backend: "claude",model_id: "opus-5",current: { source_id: "src_b", model_id: "opus-5" },diff --git a/ui/src/components/settings/models/RouteChainDialog.tsx b/ui/src/components/settings/models/RouteChainDialog.tsxindex 33705e1bb..b99f631d5 100644--- a/ui/src/components/settings/models/RouteChainDialog.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.tsx@@ -225,7 +225,7 @@ export const RouteChainDialog: React.FC<{const addCandidates = agent ? routeCandidates(agent, sources, draft) : [];const targetSources = agent ? eligibleSources(sources, agent) : [];const canEditRoute = draft.length > 0 || addCandidates.length > 0- || targetSources.some((source) => source.kind === 'api_key');+ || targetSources.some((source) => source.kind === 'api_key' && source.protocol !== 'search');const backend = agent ? getBackendUiMeta(agent.backend).label : "";const valid = agent? validateRouteDraft(agent, sources, origin, draft)diff --git a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx b/ui/src/components/settings/models/RouteRecordedTurn.test.tsxindex 590a5c2ad..83a280612 100644--- a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx+++ b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx@@ -15,7 +15,7 @@ import { PERSISTED_TURN_CONTRACT_VERSIONS } from './types';import type { RouteHop, TurnProvenance } from './types';const record: TurnProvenance = {- contract_version: 16, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',+ contract_version: 17, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',outcome: 'failed_terminal', failed_attempts: [], served: null, canceled_attempt: null, model_supply_state: null, blockers: [],terminal_error: { source_id: 'src_historical', configured_model_id: 'historical-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false, http_status: 404, upstream_error_code: 'model_not_found' },};diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsxindex f42034002..79fb6002d 100644--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx@@ -31,7 +31,7 @@ const runtime = (? 'unresolved' as const: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;return {- contract_version: 16,+ contract_version: 17,...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),manifest: resolution === 'unresolved'? { name: 'cliproxyapi', resolution, assets: [] }diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex eda7d536b..25e8b3591 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -48,7 +48,7 @@ const manifest = {} satisfies RuntimeManifest;const runtime: RuntimeDependency = {- contract_version: 16,+ contract_version: 17,manifest,status: { installed_version: '1', verified: true, health: 'ok' },};@@ -119,7 +119,7 @@ const takeoverAgent: AgentSupply = {};const takeoverChain: AgentChain = { manual_override: {hops:[{source_id:'src_head',model_id:'gpt-5.6-sol'},{source_id:'src_relay',model_id:'gpt-5.6-sol'}]}, route_origin: "manual" as const,- contract_version: 16,+ contract_version: 17,backend: 'codex',model_id: 'gpt-5.6-sol',current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },@@ -222,7 +222,7 @@ const routedHubAgent: AgentSupply = {const routedChain: AgentChain = {manual_override: { hops: [{ source_id: retainedSource.id, model_id: routedModelId }] },route_origin: 'manual' as const,- contract_version: 16,+ contract_version: 17,backend: 'claude',model_id: routedModelId,current: { source_id: retainedSource.id, model_id: routedModelId },diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex 9ed80d7c0..8348a3ab2 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -1291,14 +1291,16 @@ describe('SourceDetailPanel', () => {...NEEDS_ACTION_DETAIL_KEYS,...ERROR_DETAIL_KEYS,];- const shapes = SOURCE_STATUSES.flatMap((status) => causes.flatMap((detail_key) => kinds.flatMap(+ const protocols: SourceProtocol[] = ['anthropic', 'search'];+ const shapes = protocols.flatMap((protocol) => SOURCE_STATUSES.flatMap((status) => causes.flatMap((detail_key) => kinds.flatMap((kind) => channels.map((supply_channel): Source => ({...source,kind,+ protocol,supply_channel,state: { status, retry_at: null, detail_key },})),- )));+ ))));const reached = new Set<RepairKind>();for (const shape of shapes) {@@ -1327,6 +1329,62 @@ describe('SourceDetailPanel', () => {// Still bounded well below a hung render.}, 15_000);+ it('runs the dedicated re-enable action for a blocked search Source', async () => {+ const blockedSearch: Source = {+ ...source,+ protocol: 'search',+ base_url: null,+ models: [],+ state: {+ status: 'needs_action',+ retry_at: null,+ detail_key: 'models.source.needs_action.balance_exhausted',+ },+ };+ const answer = { ...blockedSearch, state: { status: 'standby' as const, retry_at: null, detail_key: null } };+ const reenable = vi.spyOn(modelsApi, 'reenableSearchSource').mockResolvedValue(answer);+ const onSource = vi.fn().mockResolvedValue(undefined);+ const trackMutation: TrackSourceMutation = (work) => work(blockedSearch, settlement({ source: onSource }));++ render(<I18nextProvider i18n={i18n}><CommittedPanel source={blockedSearch} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);++ await userEvent.click(screen.getByRole('button', { name: /^Check again$|^重新检查$/i }));++ await waitFor(() => expect(reenable).toHaveBeenCalledWith(blockedSearch.id));+ expect(onSource).toHaveBeenCalledWith(answer);+ });+ it('clears the re-enable failure when an inventory read confirms success', async () => {+ const blockedSearch: Source = {+ ...source,+ protocol: 'search',+ base_url: null,+ models: [],+ state: {+ status: 'needs_action',+ retry_at: null,+ detail_key: 'models.source.needs_action.spend_limit_reached',+ },+ };+ const answer = {+ ...blockedSearch,+ trial_pending: true,+ state: { status: 'needs_action' as const, retry_at: null, detail_key: 'models.source.needs_action.spend_limit_reached' as const },+ };+ vi.spyOn(modelsApi, 'reenableSearchSource').mockRejectedValue(new ApiCallError('bad_response', undefined, false));+ const onSource = vi.fn().mockResolvedValue(undefined);+ const trackMutation: TrackSourceMutation = (work) => work(blockedSearch, settlement({+ source: onSource,+ readInventory: async () => ({ snapshot: 2, sources: [answer] }),+ }));++ render(<I18nextProvider i18n={i18n}><CommittedPanel source={blockedSearch} trackMutation={trackMutation} onReauth={noReauth} /></I18nextProvider>);++ await userEvent.click(screen.getByRole('button', { name: /^Check again$|^重新检查$/i }));++ await waitFor(() => expect(onSource).toHaveBeenCalledWith(answer));+ expect(screen.queryByText(i18n.t('settings.models.repair.failed'))).toBeNull();+ });+it('opens key replacement from the revoked hub credential repair tap', async () => {render(<I18nextProvider i18n={i18n}>diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsxindex 676266f86..8a5ce2532 100644--- a/ui/src/components/settings/models/SourceDetailPanel.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx@@ -186,9 +186,10 @@ export const SourceDetailPanel: React.FC<{const detailsHidden = useSourceDetailsHidden();const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);const { Icon, accent } = sourceVisual(source);- const [pendingAction, setPendingAction] = React.useState<'refetch' | 'add_model' | 'other' | null>(null);+ const [pendingAction, setPendingAction] = React.useState<'refetch' | 'reenable' | 'add_model' | 'other' | null>(null);const busy = pendingAction !== null;const refetching = pendingAction === 'refetch';+ const reenabling = pendingAction === 'reenable';const [testing, setTesting] = React.useState(false);const [confirmingReauth, setConfirmingReauth] = React.useState(false);const [replacingKey, setReplacingKey] = React.useState(false);@@ -197,6 +198,7 @@ export const SourceDetailPanel: React.FC<{const [guard, setGuard] = React.useState<GuardedAction | null>(null);const [result, setResult] = React.useState<{ added: string[]; removed: string[] } | null>(null);const [refetchFailed, setRefetchFailed] = React.useState(false);+ const [reenableFailed, setReenableFailed] = React.useState(false);const [removeFailure, setRemoveFailure] = React.useState<{ modelId: string; retryRead: boolean } | null>(null);const [query, setQuery] = React.useState('');const models = source.models;@@ -281,6 +283,33 @@ export const SourceDetailPanel: React.FC<{}}).finally(() => setPendingAction(null));};+ const reenable = () => {+ if (busy) return Promise.resolve();+ setReenableFailed(false);+ setPendingAction('reenable');+ return trackMutation(async (latest, settlement) => {+ try {+ await settlement.source(await modelsApi.reenableSearchSource(latest.id));+ } catch (error) {+ if (apiFailure(error)?.code === 'source_not_found') {+ await settlement.gone(latest.id);+ return;+ }+ setReenableFailed(true);+ try {+ const inventory = await settlement.readInventory();+ const current = inventory.sources.find((item) => item.id === latest.id);+ if (current) {+ if (current.state.status === 'standby' || current.trial_pending === true) setReenableFailed(false);+ await settlement.source(current);+ } else await settlement.gone(latest.id, inventory);+ } catch {+ settlement.release();+ }+ }+ }).finally(() => setPendingAction(null));+ };+/** Clear one refused effort: the next request at it tries this Source again. The answer is the Source. */const clearEffort = (modelId: string, effort: string) => {if (busy) return Promise.resolve();@@ -701,8 +730,8 @@ export const SourceDetailPanel: React.FC<{verificationPending: Boolean(source.verification_pending),});// One authority picks the remedy and another total Record names its concrete- // control. In particular, `retest` points at the existing refetch button; it is- // not a special case that can fall out of destination-completeness checks.+ // control. `retest` points at model refetch; `reenable` points at the search+ // Source's dedicated free-check/trial route.const repair = repairAction(source);const repairDestination = repair ? REPAIR_DESTINATION[repair] : null;const editDialogOpen = manageStage.kind === 'editing'@@ -730,7 +759,7 @@ export const SourceDetailPanel: React.FC<{const lastFetched = source.last_discovered_at? formatRelativeTime(source.last_discovered_at, t): t('settings.models.sourceDetail.metadata.neverFetched');- const testable = source.kind === 'api_key' && source.supply_channel === 'hub';+ const testable = source.kind === 'api_key' && source.protocol !== 'search' && source.supply_channel === 'hub';const usageSummary = adoptedBackends.length > 0? t('settings.models.sourceDetail.usageSummary', { count: source.models.length, backends: adoptedBackends.join(i18n.language.startsWith('zh') ? '、' : ', ') }): t('settings.models.gateway.modelCount', { count: source.models.length });@@ -761,10 +790,11 @@ export const SourceDetailPanel: React.FC<{<div className="min-w-0"><dt>{t('settings.models.sourceDetail.metadata.type')}</dt><dd className="truncate" title={interfaceLabel}>{interfaceLabel}</dd></div><div className="min-w-0"><dt>{t('settings.models.sourceDetail.metadata.lastFetched')}</dt><dd className="truncate">{lastFetched}</dd></div></dl>- {(result || refetchFailed || manageStage.kind === 'delete_failed') && <div className="model-hub-source-notices shrink-0 space-y-2 px-5 pt-3">+ {(result || refetchFailed || reenableFailed || manageStage.kind === 'delete_failed') && <div className="model-hub-source-notices shrink-0 space-y-2 px-5 pt-3">{result && result.removed.length > 0 && <p className="model-hub-status-gold rounded-lg border px-3 py-2 text-[11.5px]">{t('settings.models.sourceDetail.refetch.removed', { count: result.removed.length, models: result.removed.join(', ') })}</p>}{result && result.added.length === 0 && result.removed.length === 0 && <p className="model-hub-status-mint rounded-lg border px-3 py-2 text-[11.5px]">{t('settings.models.sourceDetail.refetch.unchangedOnly')}</p>}{refetchFailed && <p className="rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2 text-[11.5px] text-destructive-ink">{t('settings.models.sourceDetail.fail.refetch')}</p>}+ {reenableFailed && <p className="rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2 text-[11.5px] text-destructive-ink">{t('settings.models.repair.failed')}</p>}{manageStage.kind === 'delete_failed' && <p data-manage-failure="delete" data-manage-retry-read={String(manageStage.retryRead)} className="rounded-lg border border-destructive/25 bg-destructive/[0.08] px-3 py-2 text-[11.5px] text-destructive-ink">{t(manageStage.retryRead ? 'settings.models.sourceDetail.fail.verifyDeleteSource' : 'settings.models.sourceDetail.fail.deleteSource')} <button type="button" disabled={busy} onClick={retryDelete} className="font-semibold underline underline-offset-2">{t('settings.models.sourceDetail.retry')}</button> <button type="button" disabled={busy} onClick={manageStage.retryRead ? dismissUnresolvedManage : cancelManage} className="font-semibold underline underline-offset-2">{t(manageStage.retryRead ? 'settings.models.sourceDetail.dismissUnverified' : 'common.cancel')}</button></p>}</div>}<section className="model-hub-source-toolbar flex shrink-0 flex-col gap-2 border-b border-border px-5 py-2.5 sm:flex-row sm:items-center">@@ -776,9 +806,10 @@ export const SourceDetailPanel: React.FC<{<div className="flex shrink-0 items-center gap-2">{repairDestination === 'reauth_dialog' && <Button size="xs" className="model-hub-source-action" data-repair-kind={repair} data-repair-destination={repairDestination} disabled={busy} onClick={() => setConfirmingReauth(true)}><LogIn />{t(REPAIR_LABEL_KEY.reauth)}</Button>}{repairDestination === 'replace_key_dialog' && <Button size="xs" className="model-hub-source-action" data-repair-kind={repair} data-repair-destination={repairDestination} disabled={busy} onClick={() => setReplacingKey(true)}>{t(REPAIR_LABEL_KEY.replace_key)}</Button>}- {source.supply_channel === 'hub' && <Button variant="outline" size="xs" className="model-hub-source-action" data-repair-kind={repairDestination === 'refetch_button' ? repair : undefined} data-repair-destination={repairDestination === 'refetch_button' ? repairDestination : undefined} disabled={busy} onClick={() => void refetch()} aria-busy={refetching}>{refetching ? <Loader2 className="animate-spin" /> : <RefreshCw />}{t('settings.models.sourceDetail.action.refetch')}</Button>}+ {repairDestination === 'reenable_button' && <Button size="xs" className="model-hub-source-action" data-repair-kind={repair} data-repair-destination={repairDestination} disabled={busy} onClick={() => void reenable()} aria-busy={reenabling}>{reenabling ? <Loader2 className="animate-spin" /> : <RefreshCw />}{t(REPAIR_LABEL_KEY.reenable)}</Button>}+ {source.supply_channel === 'hub' && source.protocol !== 'search' && <Button variant="outline" size="xs" className="model-hub-source-action" data-repair-kind={repairDestination === 'refetch_button' ? repair : undefined} data-repair-destination={repairDestination === 'refetch_button' ? repairDestination : undefined} disabled={busy} onClick={() => void refetch()} aria-busy={refetching}>{refetching ? <Loader2 className="animate-spin" /> : <RefreshCw />}{t('settings.models.sourceDetail.action.refetch')}</Button>}{testable && <Button variant="outline" size="xs" className="model-hub-source-action" disabled={busy} onClick={() => setTesting(true)}><FlaskConical />{t('settings.models.sourceTest.open')}</Button>}- {source.kind === 'api_key' && <Button size="xs" className="model-hub-source-action" disabled={busy || manualDraft !== null} onClick={() => setManualDraft({ modelId: '', failed: false, retryRead: false })}><Plus />{t('settings.models.sourceDetail.action.addModel')}</Button>}+ {source.kind === 'api_key' && source.protocol !== 'search' && <Button size="xs" className="model-hub-source-action" disabled={busy || manualDraft !== null} onClick={() => setManualDraft({ modelId: '', failed: false, retryRead: false })}><Plus />{t('settings.models.sourceDetail.action.addModel')}</Button>}<SourceManageMenu source={source} busy={busy || manageStage.kind !== 'idle'} onEdit={beginEdit} onDelete={beginDelete} /></div></section>diff --git a/ui/src/components/settings/models/SourceTestDialog.test.tsx b/ui/src/components/settings/models/SourceTestDialog.test.tsxindex ecc8d66cc..3ac379adb 100644--- a/ui/src/components/settings/models/SourceTestDialog.test.tsx+++ b/ui/src/components/settings/models/SourceTestDialog.test.tsx@@ -26,7 +26,7 @@ const source: Source = {})),};const answer = (patch: Partial<SourceProbeResult> = {}): SourceProbeResult => ({- source_id: source.id, model_id: 'gpt-5.6-luna', protocol: source.protocol,+ source_id: source.id, model_id: 'gpt-5.6-luna', protocol: 'openai_chat',reachable: true, latency_ms: 123, error: null, ...patch,});const landing = (sources: Source[] = [source]): SourceMutationLandingReads => ({diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.tsindex ba0aff1b9..d1802b877 100644--- a/ui/src/components/settings/models/SupplyGraph.test.ts+++ b/ui/src/components/settings/models/SupplyGraph.test.ts@@ -7,7 +7,7 @@ import { buildSupplyRelations as buildRelations } from './supplyRelations';import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './types';const runtime: RuntimeDependency = {- contract_version: 16,+ contract_version: 17,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },};@@ -47,7 +47,7 @@ const agent: AgentSupply = {};const chain = (current: string, headHealth: AgentChain['chain'][number]['health'] = 'healthy', headRunnable = true, reason: AgentChain['chain'][number]['reason'] = null): AgentChain => ({ manual_override: {hops:[{source_id:'native',model_id:'model-a'},{source_id:'relay',model_id:'model-a'},{source_id:'unused',model_id:'model-a'}]}, route_origin: "manual" as const,- contract_version: 16,+ contract_version: 17,backend: 'claude',model_id: 'model-a',current: { source_id: current, model_id: 'model-a' },diff --git a/ui/src/components/settings/models/addApiKeyState.ts b/ui/src/components/settings/models/addApiKeyState.tsindex 75879faf0..bfbb7796a 100644--- a/ui/src/components/settings/models/addApiKeyState.ts+++ b/ui/src/components/settings/models/addApiKeyState.ts@@ -2,6 +2,7 @@ import type { TranslationKey } from '@/i18n/types';import type { SourceProtocol } from './types';export const PROTOCOL_COPY_KEYS: Record<SourceProtocol, TranslationKey> = {+ search: 'settings.models.addKey.protocol.search',google: 'settings.models.addKey.protocol.google',anthropic: 'settings.models.addKey.protocol.anthropicMessages',openai_responses: 'settings.models.addKey.protocol.openaiResponses',diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.tsindex 935abfe5e..40ca4bab6 100644--- a/ui/src/components/settings/models/apiFailure.test.ts+++ b/ui/src/components/settings/models/apiFailure.test.ts@@ -33,7 +33,7 @@ afterEach(() => {describe('apiFailure — whether the route named the failure', () => {it('posts installation to the dedicated runtime route', async () => {const runtime = {- contract_version: 16,+ contract_version: 17,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'sha', assets: [] },status: { installed_version: null, verified: false, listening: null, health: 'installing', last_check: null },} as const;diff --git a/ui/src/components/settings/models/apiKeySourceDraft.ts b/ui/src/components/settings/models/apiKeySourceDraft.tsindex 12867ed86..b1f23237a 100644--- a/ui/src/components/settings/models/apiKeySourceDraft.ts+++ b/ui/src/components/settings/models/apiKeySourceDraft.ts@@ -11,7 +11,7 @@//// Values, not a component, because a module exporting both opts out of fast// refresh — the same split `vendorMarks.ts` and `vendorGlyph.tsx` already make.-import { apiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';+import { modelApiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';import { apiFailure } from './modelsApi';import {SOURCE_DISPLAY_NAME_MAX_LENGTH,@@ -53,7 +53,7 @@ export function selectVendor(draft: ApiKeySourceDraft, vendor: string): ApiKeySoreturn {...draft,vendor,- baseUrl: apiKeyVendorPreset(vendor)?.official_base_url ?? '',+ baseUrl: modelApiKeyVendorPreset(vendor)?.official_base_url ?? '',protocol: 'openai_chat',};}@@ -61,7 +61,7 @@ export function selectVendor(draft: ApiKeySourceDraft, vendor: string): ApiKeySo/** The protocol that will actually be sent: a catalog vendor publishes one, so* for those the segmented control is a statement rather than a question. */export const draftProtocol = (draft: ApiKeySourceDraft): SourceProtocol =>- apiKeyVendorPreset(draft.vendor)?.protocol ?? draft.protocol;+ modelApiKeyVendorPreset(draft.vendor)?.protocol ?? draft.protocol;/** A name is optional; one that is only too long is not. */export const draftNameValid = (draft: ApiKeySourceDraft): boolean =>diff --git a/ui/src/components/settings/models/apiKeyVendors.test.ts b/ui/src/components/settings/models/apiKeyVendors.test.tsindex 95c29c353..0431c3231 100644--- a/ui/src/components/settings/models/apiKeyVendors.test.ts+++ b/ui/src/components/settings/models/apiKeyVendors.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from 'vitest';-import { API_KEY_VENDOR_PRESETS, apiKeyVendorPreset, CUSTOM_VENDOR } from './apiKeyVendors';+import {+ ALL_API_KEY_VENDOR_PRESETS,+ API_KEY_VENDOR_PRESETS,+ apiKeyVendorPreset,+ CUSTOM_VENDOR,+} from './apiKeyVendors';import { SOURCE_PROTOCOLS } from './types';// The dialog casts the shipped JSON to its preset type on the strength of the@@ -14,6 +19,11 @@ describe('the shipped API-key vendor catalog', () => {expect(API_KEY_VENDOR_PRESETS.length).toBeGreaterThan(0);});+ it('keeps tool-only search rows out of the generic model form', () => {+ expect(ALL_API_KEY_VENDOR_PRESETS.filter((preset) => preset.protocol === 'search')).not.toHaveLength(0);+ expect(API_KEY_VENDOR_PRESETS.every((preset) => preset.protocol !== 'search')).toBe(true);+ });+it('pins every row to an interface this UI can name', () => {for (const preset of API_KEY_VENDOR_PRESETS) {expect(SOURCE_PROTOCOLS).toContain(preset.protocol);diff --git a/ui/src/components/settings/models/apiKeyVendors.ts b/ui/src/components/settings/models/apiKeyVendors.tsindex b288c5b2a..99e9b5196 100644--- a/ui/src/components/settings/models/apiKeyVendors.ts+++ b/ui/src/components/settings/models/apiKeyVendors.ts@@ -30,10 +30,19 @@ export const CUSTOM_VENDOR = 'custom';/** Catalog order is file order. The backend ships the list already ranked, and* re-sorting it here would put the ranking in a second place. */-export const API_KEY_VENDOR_PRESETS = catalog as readonly ApiKeyVendorPreset[];+export const ALL_API_KEY_VENDOR_PRESETS = catalog as readonly ApiKeyVendorPreset[];-/** The preset a vendor id names, or `null` for 自定义 — which is also what an id- * the shipped catalog no longer carries resolves to, so a row dropped upstream- * degrades to the custom path rather than pinning a protocol nothing defines. */+/** Tool-only search rows belong to the web-search card, not the generic API-key+ * model form. Keep the generic picker dormant until that card sends the+ * tool-only request shape. */+export const API_KEY_VENDOR_PRESETS = ALL_API_KEY_VENDOR_PRESETS.filter(+ (preset) => preset.protocol !== 'search',+);++/** The full catalog lookup is also used for labels on already persisted rows. */export const apiKeyVendorPreset = (vendor: string): ApiKeyVendorPreset | null =>+ ALL_API_KEY_VENDOR_PRESETS.find((preset) => preset.id === vendor) ?? null;++/** Resolve only a model-capable row for the generic API-key form. */+export const modelApiKeyVendorPreset = (vendor: string): ApiKeyVendorPreset | null =>API_KEY_VENDOR_PRESETS.find((preset) => preset.id === vendor) ?? null;diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.tsindex 9c6c243c4..0cbf301c1 100644--- a/ui/src/components/settings/models/gatewayAdoption.test.ts+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts@@ -14,7 +14,7 @@ const agent = (mode: AgentSupply['mode']): AgentSupply => ({});const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({- contract_version: 16,+ contract_version: 17,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },});diff --git a/ui/src/components/settings/models/manage.ts b/ui/src/components/settings/models/manage.tsindex b6938acba..86d6a2bf7 100644--- a/ui/src/components/settings/models/manage.ts+++ b/ui/src/components/settings/models/manage.ts@@ -28,7 +28,10 @@ export const manageActions = (): ManageKind[] => Object.keys(MANAGE_DESTINATION)/** Only Avibe-held API-key sources own an endpoint that this editor can change. */export const canEditSourceEndpoint = (source: Source): boolean =>- source.kind === 'api_key' && source.supply_channel === 'hub' && Boolean(source.credential_ref);+ source.kind === 'api_key'+ && source.protocol !== 'search'+ && source.supply_channel === 'hub'+ && Boolean(source.credential_ref);export type SourceEditDraft = {displayName: string;diff --git a/ui/src/components/settings/models/modelRows.ts b/ui/src/components/settings/models/modelRows.tsindex a18ee6784..406ae6dde 100644--- a/ui/src/components/settings/models/modelRows.ts+++ b/ui/src/components/settings/models/modelRows.ts@@ -21,7 +21,7 @@ export const chainKeyBackend = (key: string): AgentBackend =>/** Manual inventory is a credential-backed capability; subscriptions are read-only. */export function manualModelSources(sources: Source[]): Source[] {- return sources.filter((source) => source.kind === 'api_key');+ return sources.filter((source) => source.kind === 'api_key' && source.protocol !== 'search');}/** Count suppliers from the complete route inventory, never a searched subset. */diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex a39012d0c..8462b3cc0 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -119,6 +119,8 @@ export type ModelsApi = {/** Replace the credential of a hub-channel api_key source. The normal guarded* mutation tail reports every route hop removed and model interrupted. */replaceCredential(id: string, body: CredentialReplace): Promise<CredentialReplacement>;+ /** Re-check a blocked search Source and arm a trial when it has no free check. */+ reenableSearchSource(id: string): Promise<Source>;/** Start re-authorization for a subscription source. Irreversible once it* begins, which is why the acknowledgement is sent unconditionally — the* server rejects a native source without it (`reauth_confirmation_required`).@@ -616,6 +618,7 @@ export const modelsApi: ModelsApi = {createApiKeySource: (draft) => call<SourceCreatedResponse>('/api/models/sources', jsonInit('POST', draft)).then(created),patchSource: (id, patch) => call<SourcePatchedResponse>(`/api/models/sources/${encodeURIComponent(id)}`, jsonInit('PATCH', patch)).then(sourcePatched),refreshSource: (id, confirmation) => call<SourceRefresh>(`/api/models/sources/${encodeURIComponent(id)}/refresh`, jsonInit('POST', confirmation ?? {})),+ reenableSearchSource: (id) => call<{ source: Source }>(`/api/models/sources/${encodeURIComponent(id)}/reenable`, jsonInit('POST', {})).then((r) => r.source),probeSource: (id, model) => call<{ probe: SourceProbeResult }>(`/api/models/sources/${encodeURIComponent(id)}/probe`, jsonInit('POST', { model }),).then((r) => r.probe),diff --git a/ui/src/components/settings/models/repair.test.ts b/ui/src/components/settings/models/repair.test.tsindex d2a65db68..6dea53afd 100644--- a/ui/src/components/settings/models/repair.test.ts+++ b/ui/src/components/settings/models/repair.test.ts@@ -117,6 +117,9 @@ describe('repairAction — the one tap a stopped source offers', () => {expect(repairAction(blocked('models.source.needs_action.plan_excludes_product', subscription))).toBe('retest');// So is a spend or usage limit, raised in the vendor's console.expect(repairAction(blocked('models.source.needs_action.spend_limit_reached'))).toBe('retest');+ expect(repairAction(blocked('models.source.needs_action.balance_exhausted', { protocol: 'search' }))).toBe('reenable');+ expect(repairAction(blocked('models.source.needs_action.spend_limit_reached', { protocol: 'search' }))).toBe('reenable');+ expect(repairAction(blocked('models.source.needs_action.account_banned', { protocol: 'search' }))).toBeNull();});it('treats an unclassified error as an upstream cause, not a credential one', () => {diff --git a/ui/src/components/settings/models/repair.ts b/ui/src/components/settings/models/repair.tsindex bcd660bc0..18edbeca4 100644--- a/ui/src/components/settings/models/repair.ts+++ b/ui/src/components/settings/models/repair.ts@@ -53,10 +53,15 @@ export const canReplaceKey = (source: Source): boolean =>/** `POST …/refresh` is the contract's ONE recovery endpoint (「v3 does not add a* second 'recover' endpoint」) and rejects native sources, which have nothing to* re-discover. */-export const canRetest = (source: Source): boolean => source.supply_channel === 'hub';+export const canRetest = (source: Source): boolean =>+ source.supply_channel === 'hub' && source.protocol !== 'search';++/** Search Sources have a dedicated recovery check; model refetch is forbidden for them. */+export const canReenable = (source: Source): boolean =>+ source.protocol === 'search' && source.kind === 'api_key' && source.supply_channel === 'hub';/** What a stopped row offers as its one tap. */-export type RepairKind = 'reauth' | 'replace_key' | 'retest';+export type RepairKind = 'reauth' | 'replace_key' | 'retest' | 'reenable';/** Causes whose fix is a NEW credential, held by Avibe: the grant or the key* itself stopped working, and only replacing it can help. */@@ -98,6 +103,12 @@ export function repairAction(source: Source): RepairKind | null {if (canReplaceKey(source)) return 'replace_key';return null;}+ if (canReenable(source)) {+ return source.state.detail_key === 'models.source.needs_action.balance_exhausted'+ || source.state.detail_key === 'models.source.needs_action.spend_limit_reached'+ ? 'reenable'+ : null;+ }if (canRetest(source)) return 'retest';// Native has no recovery refresh — `refresh_source` refuses `native_cli` outright — so// rules 1 and 2 together leave a stopped native row with no tap at all, its@@ -131,6 +142,7 @@ export const REPAIR_LABEL_KEY: Record<RepairKind, TranslationKey> = {reauth: 'settings.models.repair.reauth',replace_key: 'settings.models.repair.replaceKey',retest: 'settings.models.repair.retest',+ reenable: 'settings.models.repair.reenable',};/**@@ -139,12 +151,13 @@ export const REPAIR_LABEL_KEY: Record<RepairKind, TranslationKey> = {* this module exists to prevent. `retest` names the existing refetch control,* rather than being treated as an exception by the component or its test.*/-export type RepairDestination = 'reauth_dialog' | 'replace_key_dialog' | 'refetch_button';+export type RepairDestination = 'reauth_dialog' | 'replace_key_dialog' | 'refetch_button' | 'reenable_button';export const REPAIR_DESTINATION: Record<RepairKind, RepairDestination> = {reauth: 'reauth_dialog',replace_key: 'replace_key_dialog',retest: 'refetch_button',+ reenable: 'reenable_button',};/**diff --git a/ui/src/components/settings/models/routeChainDraft.ts b/ui/src/components/settings/models/routeChainDraft.tsindex aca698f8f..19f3b2861 100644--- a/ui/src/components/settings/models/routeChainDraft.ts+++ b/ui/src/components/settings/models/routeChainDraft.ts@@ -75,6 +75,7 @@ export function validateRouteDraft(const source = available.get(hop.source_id);const admitted = source && hop.model_id.trim().length > 0&& hop.model_id === hop.model_id.trim()+ && source.protocol !== 'search'&& (source.kind === 'api_key' || source.models.some((model) => model.id === hop.model_id))&& !source.models.some((model) => model.id === hop.model_id && model.retired === true);return counts.get(key)! > 1 || (!unchanged.has(key) && !admitted)diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts b/ui/src/components/settings/models/routeProjectionReconciliation.test.tsindex cae668a7d..7fcfbaae0 100644--- a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts+++ b/ui/src/components/settings/models/routeProjectionReconciliation.test.ts@@ -24,7 +24,7 @@ const source: Source = {};const report: RouteReport = {chain: {- contract_version: 16,+ contract_version: 17,backend: "claude",model_id: "模型/opus",manual_override: null,diff --git a/ui/src/components/settings/models/runtimeLifecycle.test.ts b/ui/src/components/settings/models/runtimeLifecycle.test.tsindex ef757cdf2..5281c7bd1 100644--- a/ui/src/components/settings/models/runtimeLifecycle.test.ts+++ b/ui/src/components/settings/models/runtimeLifecycle.test.ts@@ -11,7 +11,7 @@ const asset = (platform: 'darwin-arm64' | 'linux-amd64') => ({});const runtime = (resolution: 'resolved' | 'unresolved' | 'unsupported'): RuntimeDependency => ({- contract_version: 16,+ contract_version: 17,host_platform: 'darwin-arm64',manifest: resolution === 'unresolved'? { name: 'cliproxyapi', resolution, assets: [] }diff --git a/ui/src/components/settings/models/tierSuggestions.test.ts b/ui/src/components/settings/models/tierSuggestions.test.tsindex b344810ad..f383a601a 100644--- a/ui/src/components/settings/models/tierSuggestions.test.ts+++ b/ui/src/components/settings/models/tierSuggestions.test.ts@@ -7,7 +7,7 @@ import { describe, expect, it } from 'vitest';import { EFFORT_BY_BACKEND, REASONING_EFFORTS } from '@/lib/effortOptions';import { TIER_SUGGESTIONS } from './tierSuggestions';-import { SOURCE_PROTOCOLS } from './types';+import { MODEL_PROTOCOLS } from './types';const HERE = dirname(fileURLToPath(import.meta.url));const BACKEND_MODELS = resolve(HERE, '../../../../..', 'vibe/data/backend_models.json');@@ -50,7 +50,7 @@ describe('unified reasoning-effort vocabulary', () => {});it('offers one suggestion list per source protocol, drawn from the vocabulary in its order', () => {- expect(new Set(Object.keys(TIER_SUGGESTIONS))).toEqual(new Set(SOURCE_PROTOCOLS));+ expect(new Set(Object.keys(TIER_SUGGESTIONS))).toEqual(new Set(MODEL_PROTOCOLS));for (const [protocol, tiers] of Object.entries(TIER_SUGGESTIONS)) {if (protocol === 'google') expect(tiers).toEqual([]);diff --git a/ui/src/components/settings/models/tierSuggestions.ts b/ui/src/components/settings/models/tierSuggestions.tsindex 72593454c..dc8085c50 100644--- a/ui/src/components/settings/models/tierSuggestions.ts+++ b/ui/src/components/settings/models/tierSuggestions.ts@@ -1,6 +1,6 @@import type { ReasoningEffort } from '@/lib/effortOptions';-import type { SourceProtocol } from './types';+import type { ModelProtocol } from './types';/*** The effort vocabulary for a source's protocol family.@@ -27,7 +27,7 @@ import type { SourceProtocol } from './types';* becomes data only when the user clicks it, through the same add path typing it* would take.*/-export const TIER_SUGGESTIONS: Readonly<Record<SourceProtocol, readonly ReasoningEffort[]>> = {+export const TIER_SUGGESTIONS: Readonly<Record<ModelProtocol, readonly ReasoningEffort[]>> = {google: [], // No Google family ladder is claimed by Model Hub.anthropic: ['low', 'medium', 'high', 'xhigh', 'max'],openai_responses: ['minimal', 'low', 'medium', 'high', 'xhigh'],diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex bd31d79dc..02ccb6406 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -10,19 +10,21 @@// and the PR records the server implementation and feature-flag activation// edge. The client never synthesizes a fallback payload shape.-export const CONTRACT_VERSION = 16 as const;-export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] as const;+export const CONTRACT_VERSION = 17 as const;+export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] as const;export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;// ── source.schema.json ──────────────────────────────────────────────────export type SourceKind = 'subscription' | 'api_key';-export const SOURCE_PROTOCOLS = [+export const MODEL_PROTOCOLS = ['anthropic','openai_responses','openai_chat','google',] as const;+export type ModelProtocol = (typeof MODEL_PROTOCOLS)[number];+export const SOURCE_PROTOCOLS = [...MODEL_PROTOCOLS, 'search'] as const;export type SourceProtocol = (typeof SOURCE_PROTOCOLS)[number];// Google is API/config-only until its picker frame is approved.export const SELECTABLE_SOURCE_PROTOCOLS = ['anthropic', 'openai_responses', 'openai_chat'] as const;@@ -152,6 +154,8 @@ export type Source = {verification_pending?: string | null;/** Opaque identity of the latest credential or endpoint change; kept after verification. Not for display. */credential_generation?: string | null;+ /** Response-only search recovery state; never persisted. */+ trial_pending?: boolean;usage?: SourceUsage;/** Subscription identity for the row's mono sub-line (e.g. "[email protected]").* Never secret material; may be null. */@@ -644,7 +648,7 @@ export type RecordedAttempt = {channel: SupplyChannel;stripped_reasoning_efforts?: string[];declared_reasoning_efforts?: string[];- origin?: { provider: string; api: SourceProtocol; model: string };+ origin?: { provider: string; api: ModelProtocol; model: string };};export type TurnProvenance = {contract_version: (typeof PERSISTED_TURN_CONTRACT_VERSIONS)[number];@@ -661,7 +665,7 @@ export type TurnProvenance = {configured_model_id: string | null;channel: SupplyChannel | null;local_error_detail?: string;- origin?: { provider: string; api: SourceProtocol; model: string };+ origin?: { provider: string; api: ModelProtocol; model: string };stripped_reasoning_efforts?: string[];declared_reasoning_efforts?: string[];} & ({@@ -1162,7 +1166,7 @@ export type SourceObservation = {outcome: ObservationOutcome;reachable: boolean | null;authenticated: ObservationAuthentication;- protocol: SourceProtocol | null;+ protocol: ModelProtocol | null;discovery: ObservationDiscovery;models: string[];};@@ -1173,13 +1177,13 @@ export type ApiKeySourceObservation = {base_url?: string | null;key: string;/** Omission auto-detects; a value restricts observation to this protocol. */- protocol?: SourceProtocol;+ protocol?: ModelProtocol;};export type SourceProbeResult = {source_id: string;model_id: string;- protocol: SourceProtocol;+ protocol: ModelProtocol;reachable: boolean;latency_ms: number;error: string | null;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 05696a2e3..3a152e558 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1929,6 +1929,7 @@"openaiResponses": "OpenAI Responses","openaiChatCompletions": "OpenAI Chat Completions","google": "Google Gemini",+ "search": "Search service","idleHint": "Identified automatically once Base URL and API key are filled","detecting": "Identifying the interface…","manual": "Manually specify interface type",@@ -2319,6 +2320,7 @@"reauth": "Sign in","replaceKey": "Replace key","retest": "Retry",+ "reenable": "Check again","reauthTitle": "Sign in to “{{name}}” again?","reauthBody": {"immediate": "The old sign-in stops working as soon as you start, and every source using it goes unavailable. Finishing restores only this one — the others need their own sign-in.",@@ -2805,6 +2807,7 @@},"modelHub": {"errors": {+ "credential_replacement_unverified": "The new key could not be verified yet. Your old key is unchanged; please try again later.","source_model_tiers_managed": "This model's tiers are set automatically, so the change was not saved"}},diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 1df23629e..17b403e1f 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1929,6 +1929,7 @@"openaiResponses": "OpenAI Responses","openaiChatCompletions": "OpenAI Chat Completions","google": "Google Gemini",+ "search": "搜索服务","idleHint": "填好 Base URL 和 API Key 后自动识别","detecting": "识别接口中…","manual": "手动指定接口类型",@@ -2319,6 +2320,7 @@"reauth": "重新登录","replaceKey": "更换 Key","retest": "重试",+ "reenable": "重新检查","reauthTitle": "重新登录「{{name}}」?","reauthBody": {"immediate": "开始后旧的登录立即失效,使用它的供应商都会不可用。完成后只恢复这一个,其他供应商需要各自重新登录。",@@ -2805,6 +2807,7 @@},"modelHub": {"errors": {+ "credential_replacement_unverified": "暂时无法验证新密钥,原密钥未改动,请稍后重试","source_model_tiers_managed": "这个模型的档位是自动确定的,这次改动没有保存"}},diff --git a/vibe/authorization.py b/vibe/authorization.pyindex ac2c62d03..899263873 100644--- a/vibe/authorization.py+++ b/vibe/authorization.py@@ -526,7 +526,7 @@ _MEMBER_HTTP_RULES = tuple(("PATCH", r"^/api/models/sources/[^/]+$"),("DELETE", r"^/api/models/sources/[^/]+$"),("PUT", r"^/api/models/sources/[^/]+/credential$"),- ("POST", r"^/api/models/sources/[^/]+/(?:reauth|refresh|probe)$"),+ ("POST", r"^/api/models/sources/[^/]+/(?:reauth|refresh|probe|reenable)$"),("POST", r"^/api/models/sources/[^/]+/evidence/clear$"),("POST", r"^/api/models/sources/[^/]+/models$"),# Model IDs are path parameters and may contain vendor/model slashes.diff --git a/vibe/data/api_key_vendors.json b/vibe/data/api_key_vendors.jsonindex cfbaa1618..b461df96d 100644--- a/vibe/data/api_key_vendors.json+++ b/vibe/data/api_key_vendors.json@@ -29,7 +29,48 @@"label": "DeepSeek","official_base_url": "https://api.deepseek.com","protocol": "openai_chat",- "models_dev_provider": "deepseek"+ "models_dev_provider": "deepseek",+ "search": {+ "service_id": "deepseek/search",+ "endpoint": "https://api.deepseek.com/v1/tools/search",+ "auth": "bearer",+ "request": {+ "method": "POST",+ "query": "query",+ "results": "count",+ "content": "need_content"+ },+ "result": {+ "results": "results",+ "url": "url",+ "title": "title",+ "snippet": "snippet",+ "content": "content",+ "page_age": "date"+ },+ "limits": {+ "results_min": 1,+ "results_max": 50,+ "query_max_chars": 128+ },+ "price": {+ "unit": "search",+ "usd_per_1k": 0.75,+ "extra": [],+ "as_of": "2026-10-19",+ "url": "https://api-docs.deepseek.com/guides/search-tool"+ },+ "free_check": {+ "method": "GET",+ "endpoint": "https://api.deepseek.com/user/balance",+ "pass": {"status": 200, "path": "is_available", "equals": true},+ "balance": {"status": 200, "path": "is_available", "equals": false},+ "invalid_statuses": [401]+ },+ "service_refused_statuses": [400],+ "auto_enroll": true,+ "tool_only": false+ }},{"id": "qwen",@@ -86,5 +127,103 @@"official_base_url": "https://api.fireworks.ai/inference/v1","protocol": "openai_chat","models_dev_provider": "fireworks-ai"+ },+ {+ "id": "tavily",+ "label": "Tavily",+ "official_base_url": "https://api.tavily.com",+ "protocol": "search",+ "search": {+ "service_id": "tavily/search",+ "endpoint": "https://api.tavily.com/search",+ "auth": "bearer",+ "request": {+ "method": "POST",+ "query": "query",+ "results": "max_results",+ "content": "include_raw_content"+ },+ "result": {+ "results": "results",+ "url": "url",+ "title": "title",+ "snippet": "content",+ "content": "raw_content",+ "page_age": "published_date"+ },+ "limits": {+ "results_min": 1,+ "results_max": 20,+ "query_max_chars": null+ },+ "price": {+ "unit": "search",+ "usd_per_1k": 8.0,+ "extra": [],+ "as_of": "2026-10-19",+ "url": "https://www.tavily.com/pricing"+ },+ "free_check": {+ "method": "GET",+ "endpoint": "https://api.tavily.com/usage",+ "pass": {"status": 200},+ "limit": {+ "pairs": [+ {"usage": "key.usage", "limit": "key.limit"},+ {"usage": "account.plan_usage", "limit": "account.plan_limit"},+ {"usage": "account.paygo_usage", "limit": "account.paygo_limit"}+ ]+ },+ "balance": null,+ "invalid_statuses": [401]+ },+ "service_refused_statuses": [400],+ "tool_only": true+ }+ },+ {+ "id": "exa",+ "label": "Exa",+ "official_base_url": "https://api.exa.ai",+ "protocol": "search",+ "search": {+ "service_id": "exa/search",+ "endpoint": "https://api.exa.ai/search",+ "auth": "x-api-key",+ "request": {+ "method": "POST",+ "query": "query",+ "results": "numResults",+ "content": "contents.text",+ "content_max_chars": {"path": "contents.text.maxCharacters", "value": 4000},+ "highlights": "contents.highlights"+ },+ "result": {+ "results": "results",+ "url": "url",+ "title": "title",+ "snippet": "highlights",+ "content": "text",+ "page_age": "publishedDate",+ "reported_cost": {"path": "costDollars.total", "estimate": true}+ },+ "limits": {+ "results_min": 1,+ "results_max": 10,+ "query_max_chars": null+ },+ "price": {+ "unit": "search",+ "usd_per_1k": 7.0,+ "extra": [+ {"unit": "page", "usd_per_1k": 1.0, "when": "content"}+ ],+ "as_of": "2026-10-19",+ "url": "https://exa.ai/blog/exa-3"+ },+ "free_check": null,+ "service_refused_statuses": [400],+ "tool_only": true+ }}]diff --git a/vibe/data/api_key_vendors.schema.json b/vibe/data/api_key_vendors.schema.jsonnew file mode 100644index 000000000..9e609b462--- /dev/null+++ b/vibe/data/api_key_vendors.schema.json@@ -0,0 +1,146 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "$id": "model-hub/api-key-vendors.schema.json",+ "title": "Model Hub API-key vendor catalog",+ "type": "array",+ "items": {+ "type": "object",+ "required": ["id", "label", "official_base_url", "protocol"],+ "additionalProperties": false,+ "properties": {+ "id": {"type": "string", "pattern": "^[a-z0-9]+(?:[._-][a-z0-9]+)*$"},+ "label": {"type": "string", "minLength": 1},+ "official_base_url": {"type": "string", "format": "uri", "pattern": "^https://"},+ "protocol": {"enum": ["anthropic", "openai_responses", "openai_chat", "google", "search"]},+ "models_dev_provider": {"type": ["string", "null"]},+ "search": {+ "type": ["object", "null"],+ "required": ["service_id", "endpoint", "auth", "request", "result", "limits", "price", "free_check", "service_refused_statuses", "tool_only"],+ "allOf": [+ {+ "if": {"type": "object", "required": ["tool_only"], "properties": {"tool_only": {"const": false}}},+ "then": {"required": ["auto_enroll"]}+ },+ {+ "if": {"type": "object", "required": ["tool_only"], "properties": {"tool_only": {"const": true}}},+ "then": {"not": {"required": ["auto_enroll"]}}+ }+ ],+ "additionalProperties": false,+ "properties": {+ "service_id": {"type": "string", "minLength": 1},+ "endpoint": {"type": "string", "format": "uri", "pattern": "^https://"},+ "auth": {"enum": ["bearer", "x-api-key"]},+ "request": {+ "type": "object",+ "properties": {+ "content_max_chars": {+ "type": "object",+ "description": "Vendor text-length request parameter applied only when page content is requested; no larger than the per-source content bound.",+ "required": ["path", "value"],+ "additionalProperties": false,+ "properties": {+ "path": {"type": "string", "minLength": 1},+ "value": {"type": "integer", "minimum": 1, "maximum": 4000}+ }+ }+ }+ },+ "result": {+ "type": "object",+ "properties": {+ "reported_cost": {+ "type": "object",+ "required": ["path", "estimate"],+ "additionalProperties": false,+ "properties": {+ "path": {"type": "string", "minLength": 1},+ "estimate": {"type": "boolean"}+ }+ }+ }+ },+ "limits": {+ "type": "object",+ "required": ["results_max"],+ "properties": {+ "results_max": {+ "type": "integer",+ "minimum": 1,+ "maximum": 100,+ "description": "Version-independent per-request results ceiling; usage page counts remain bounded across catalog versions."+ }+ }+ },+ "price": {+ "type": "object",+ "required": ["unit", "usd_per_1k", "extra", "as_of", "url"],+ "additionalProperties": false,+ "properties": {+ "unit": {"const": "search"},+ "usd_per_1k": {"type": "number", "minimum": 0},+ "extra": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["unit", "usd_per_1k"],+ "additionalProperties": false,+ "properties": {+ "unit": {"const": "page"},+ "usd_per_1k": {"type": "number", "minimum": 0},+ "when": {"const": "content"}+ }+ }+ },+ "as_of": {"type": "string", "format": "date"},+ "url": {"type": "string", "format": "uri", "pattern": "^https://"}+ }+ },+ "free_check": {+ "type": ["object", "null"],+ "additionalProperties": false,+ "properties": {+ "method": {"enum": ["GET", "POST"]},+ "endpoint": {"type": "string", "format": "uri", "pattern": "^https://"},+ "pass": {"type": ["object", "null"]},+ "balance": {"type": ["object", "null"]},+ "limit": {+ "type": ["object", "null"],+ "additionalProperties": false,+ "properties": {+ "pairs": {+ "type": "array",+ "items": {+ "type": "object",+ "required": ["usage", "limit"],+ "additionalProperties": false,+ "properties": {+ "usage": {"type": "string", "minLength": 1},+ "limit": {"type": "string", "minLength": 1}+ }+ }+ }+ }+ },+ "invalid_statuses": {+ "type": "array",+ "items": {"type": "integer", "minimum": 400, "maximum": 499},+ "uniqueItems": true+ }+ }+ },+ "service_refused_statuses": {+ "type": "array",+ "items": {"type": "integer", "minimum": 400, "maximum": 499},+ "uniqueItems": true+ },+ "tool_only": {"type": "boolean"},+ "auto_enroll": {+ "type": "boolean",+ "description": "Whether an official model Source joins search automatically; tool-only Sources do not use this field."+ }+ }+ }+ }+ }+}diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 6ac7b35c3..d23276243 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1158,6 +1158,7 @@"authentication_failed": "Authentication failed. Check whether the API key is valid.","observation_failed": "Connected, but the response did not prove a valid model interface.","adapter_error": "We could not confirm whether the service is reachable. Retry the connection.",+ "credential_replacement_unverified": "The new key could not be verified yet. Your old key is unchanged; please try again later.","native_login_in_progress": "Another native login is already in progress. Finish or cancel it, then retry.","native_subscription_exists": "This vendor already has a native subscription source.","source_timeout": "The connection timed out. Check the network and retry.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex a3e03fd8d..5bd721b6d 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1158,6 +1158,7 @@"authentication_failed": "鉴权失败,请检查 API Key 是否有效。","observation_failed": "已连接,但无法确认服务返回的是有效模型接口。","adapter_error": "无法确认服务是否可连接,请重试。",+ "credential_replacement_unverified": "暂时无法验证新密钥,原密钥未改动,请稍后重试","native_login_in_progress": "另一个 Agent 登录正在进行中,请先完成或取消后再重试。","native_subscription_exists": "该供应商已经有一个由 Agent 管理的订阅。","source_timeout": "连接超时,请检查网络后重试。",diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.pyindex 29757e7ff..ed6cdb9e5 100644--- a/vibe/model_hub_client.py+++ b/vibe/model_hub_client.py@@ -150,6 +150,12 @@ class ModelHubRemoteService:},)+ async def reenable_search_source(self, source_id: str) -> dict:+ return await _rpc(+ "reenable_search_source",+ {"source_id": source_id},+ )+def list_agents(self, *, refresh_cli_presence: bool = False) -> list[dict]:return _rpc_sync("list_agents",diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex 2e0e0da41..126b22f63 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -33,7 +33,9 @@ from core.handlers.model_hub.adapter import (RawOutcomeKind,RetainedMaterialDisposition,RuntimePlatformUnsupportedError,- SOURCE_PROTOCOLS,+ SearchCredentialCheck,+ SearchResponse,+ MODEL_PROTOCOLS,SourceObservation,SourceBinding,make_source_observation,@@ -63,6 +65,7 @@ from vibe.model_hub_runtime.client import (from vibe.model_hub_runtime.api_key_vendors import (anthropic_api_key_header,pinned_api_key_protocol,+ search_service,validate_api_key_auth_scheme,)from vibe.model_hub_runtime.installer import (@@ -145,6 +148,126 @@ _HUB_SUBSCRIPTION_PROTOCOLS = {"kimi": "openai_chat","xai": "openai_chat",}+_SEARCH_BODY_MAX_BYTES = 8 * 1024 * 1024+_SEARCH_TIMEOUT_SECONDS = 30.0+_SEARCH_CHECK_TIMEOUT_SECONDS = 10.0+_SEARCH_CHECK_CONNECT_TIMEOUT_SECONDS = 5.0+_SEARCH_RESPONSE_HEADERS = frozenset({"content-type", "retry-after", "date", "content-length"})+++async def _read_bounded_search_body(content: Any) -> tuple[bytes | None, bool]:+ """Read a response to EOF while stopping as soon as the cap is exceeded."""+ chunks: list[bytes] = []+ total = 0+ async for chunk in content.iter_chunked(64 * 1024):+ data = bytes(chunk)+ total += len(data)+ if total > _SEARCH_BODY_MAX_BYTES:+ return None, True+ chunks.append(data)+ return b"".join(chunks), False+++def _search_check_matches(body: object, rule: Mapping[str, Any]) -> bool:+ if rule.get("status") is not None:+ # Status is checked by the caller; keep this predicate about body facts.+ pass+ path = rule.get("path")+ if path is None:+ return True+ current: object = body+ for part in str(path).split("."):+ if not isinstance(current, Mapping) or part not in current:+ return False+ current = current[part]+ return current == rule.get("equals")+++def _search_limit_outcome(body: object, rule: Mapping[str, Any]) -> Literal["pass", "limit", "unknown"]:+ """Classify complete Tavily usage/limit pairs; the account section is optional."""+ pairs = rule.get("pairs")+ if not isinstance(pairs, list) or not isinstance(body, Mapping):+ return "unknown"+ if any(name in body and not isinstance(body[name], Mapping) for name in ("key", "account")):+ return "unknown"+ missing = object()+ values: dict[str, tuple[float, float | None] | None] = {+ "key": None,+ "plan": None,+ "paygo": None,+ }+ paths = {+ "key": ("key.usage", "key.limit"),+ "plan": ("account.plan_usage", "account.plan_limit"),+ "paygo": ("account.paygo_usage", "account.paygo_limit"),+ }+ for pair in pairs:+ if not isinstance(pair, Mapping):+ return "unknown"+ usage_path = pair.get("usage")+ limit_path = pair.get("limit")+ if not isinstance(usage_path, str) or not isinstance(limit_path, str):+ return "unknown"+ role = next(+ (+ name+ for name, expected in paths.items()+ if expected == (usage_path, limit_path)+ ),+ None,+ )+ if role is None:+ return "unknown"+ usage: object = body+ limit: object = body+ for part in usage_path.split("."):+ if not isinstance(usage, Mapping) or part not in usage:+ usage = missing+ break+ usage = usage[part]+ for part in limit_path.split("."):+ if not isinstance(limit, Mapping) or part not in limit:+ limit = missing+ break+ limit = limit[part]+ if usage is missing and limit is missing:+ continue+ if (+ usage is missing+ or isinstance(usage, bool)+ or not isinstance(usage, (int, float))+ or not math.isfinite(float(usage))+ ):+ return "unknown"+ if role == "key" and limit is None:+ values[role] = (float(usage), None)+ continue+ if (+ limit is missing+ or isinstance(limit, bool)+ or not isinstance(limit, (int, float))+ or not math.isfinite(float(limit))+ ):+ return "unknown"+ values[role] = (float(usage), float(limit))++ if not any(value is not None for value in values.values()):+ return "unknown"+ key = values["key"]+ plan = values["plan"]+ paygo = values["paygo"]+ if key is not None and key[1] is not None and key[0] >= key[1]:+ return "limit"+ if plan is None and paygo is None:+ # A valid key pair with headroom authenticates the key even when+ # account usage is absent; the first search confirms payment.+ return "pass"+ key_has_headroom = key is None or key[1] is None or key[0] < key[1]+ account_has_headroom = (+ (plan is not None and plan[0] < plan[1])+ or (paygo is not None and paygo[0] < paygo[1])+ )+ return "pass" if key_has_headroom and account_has_headroom else "limit"_INSTALL_RECOVERY_WAIT_SECONDS = 30.0_INSTALL_RECOVERY_INITIAL_DELAY_SECONDS = 0.25_INSTALL_RECOVERY_MAX_DELAY_SECONDS = 4.0@@ -1920,6 +2043,227 @@ class CLIProxyEngineAdapter:on_reserved=on_reserved,)+ @staticmethod+ def _search_catalog_parts(catalog: Mapping[str, Any]) -> tuple[str | None, Mapping[str, Any] | None]:+ vendor = catalog.get("vendor")+ service = catalog.get("search")+ if isinstance(service, Mapping):+ return vendor if isinstance(vendor, str) else None, service+ return vendor if isinstance(vendor, str) else None, catalog++ async def _search_http(+ self,+ *,+ catalog: Mapping[str, Any],+ credential_ref: str,+ method: str,+ endpoint: str,+ payload: Mapping[str, Any] | None = None,+ timeout_total: float = _SEARCH_TIMEOUT_SECONDS,+ connect_timeout: float | None = None,+ on_sent: Callable[[], None] | None = None,+ ) -> SearchResponse:+ """Call only the immutable catalog endpoint for one search operation."""+ vendor, service = self._search_catalog_parts(catalog)+ if service is None or not isinstance(service.get("endpoint"), str):+ return SearchResponse(None, {}, None, "invalid_endpoint")+ configured_endpoint = endpoint+ parsed = urllib.parse.urlsplit(configured_endpoint)+ catalog_endpoint = urllib.parse.urlsplit(str(service.get("endpoint") or ""))+ allowed_paths = {catalog_endpoint.path}+ check = service.get("free_check")+ if isinstance(check, Mapping):+ check_endpoint = urllib.parse.urlsplit(str(check.get("endpoint") or ""))+ if check_endpoint.path:+ allowed_paths.add(check_endpoint.path)+ if (+ parsed.scheme != "https"+ or not parsed.hostname+ or parsed.hostname.lower() != (catalog_endpoint.hostname or "").lower()+ or parsed.port != catalog_endpoint.port+ or parsed.path not in allowed_paths+ or parsed.query+ or parsed.fragment+ ):+ return SearchResponse(None, {}, None, "invalid_endpoint")+ try:+ key = await asyncio.to_thread(self.state_store.read_api_key, credential_ref)+ metadata = await asyncio.to_thread(self.state_store.credential_metadata, credential_ref)+ except Exception:+ return SearchResponse(None, {}, None, "connection")+ if vendor is None or metadata.get("vendor") != vendor:+ return SearchResponse(None, {}, None, "invalid_endpoint")+ auth = str(service.get("auth") or "bearer")+ headers = {"Accept": "application/json", "Content-Type": "application/json"}+ if auth == "x-api-key":+ headers["x-api-key"] = key+ else:+ headers["Authorization"] = f"Bearer {key}"+ timeout = aiohttp.ClientTimeout(total=timeout_total, connect=connect_timeout)+ trace = aiohttp.TraceConfig()+ callback_called = False+ response_status: int | None = None+ response_headers: dict[str, str] = {}+ response_received_at: datetime | None = None++ async def request_connection_ready(*_args: Any, **_kwargs: Any) -> None:+ nonlocal callback_called+ if callback_called or on_sent is None:+ return+ callback_called = True+ on_sent()++ trace.on_connection_create_end.append(request_connection_ready)+ trace.on_connection_reuseconn.append(request_connection_ready)+ try:+ async with aiohttp.ClientSession(+ timeout=timeout,+ trust_env=False,+ trace_configs=[trace],+ ) as session:+ async with session.request(+ method,+ configured_endpoint,+ headers=headers,+ json=dict(payload) if payload is not None else None,+ allow_redirects=False,+ ) as response:+ response_status = response.status+ response_received_at = datetime.now(timezone.utc)+ response_headers = {+ name: value+ for name, value in response.headers.items()+ if name.lower() in _SEARCH_RESPONSE_HEADERS+ }+ body, body_too_large = await _read_bounded_search_body(response.content)+ if body_too_large:+ return SearchResponse(+ response_status,+ response_headers,+ None,+ "body_too_large",+ on_sent_fired=callback_called,+ response_received_at=response_received_at,+ )+ assert body is not None+ if 300 <= response_status < 400:+ return SearchResponse(+ response_status,+ response_headers,+ body,+ "redirect",+ on_sent_fired=callback_called,+ response_received_at=response_received_at,+ )+ return SearchResponse(+ response_status,+ response_headers,+ body,+ on_sent_fired=callback_called,+ response_received_at=response_received_at,+ )+ except asyncio.CancelledError:+ return SearchResponse(+ response_status,+ response_headers,+ None,+ "cancelled",+ on_sent_fired=callback_called,+ response_received_at=response_received_at,+ )+ except asyncio.TimeoutError:+ return SearchResponse(+ response_status,+ response_headers,+ None,+ "timeout",+ on_sent_fired=callback_called,+ response_received_at=response_received_at,+ )+ except (aiohttp.ClientError, OSError, ValueError):+ return SearchResponse(+ response_status,+ response_headers,+ None,+ "connection",+ on_sent_fired=callback_called,+ response_received_at=response_received_at,+ )++ async def check_search_credential(+ self,+ credential_ref: str,+ catalog: Mapping[str, Any],+ ) -> SearchCredentialCheck:+ vendor, service = self._search_catalog_parts(catalog)+ if vendor is None or service is None:+ return SearchCredentialCheck("unknown")+ check = service.get("free_check")+ if not isinstance(check, Mapping):+ return SearchCredentialCheck("unknown")+ response = await self._search_http(+ catalog=catalog,+ credential_ref=credential_ref,+ method=str(check.get("method") or "GET"),+ endpoint=str(check.get("endpoint") or ""),+ timeout_total=_SEARCH_CHECK_TIMEOUT_SECONDS,+ connect_timeout=_SEARCH_CHECK_CONNECT_TIMEOUT_SECONDS,+ )+ if response.error == "cancelled":+ raise asyncio.CancelledError+ if response.http_status in set(check.get("invalid_statuses") or ()):+ return SearchCredentialCheck("invalid")+ if response.error or response.http_status is None:+ return SearchCredentialCheck("unknown")+ if response.http_status != 200 or response.body is None:+ return SearchCredentialCheck("unknown")+ try:+ body = json.loads(response.body.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError):+ return SearchCredentialCheck("unknown")+ limit_rule = check.get("limit")+ if isinstance(limit_rule, Mapping):+ limit_outcome = _search_limit_outcome(body, limit_rule)+ if limit_outcome == "limit":+ return SearchCredentialCheck("limit")+ if limit_outcome == "unknown":+ return SearchCredentialCheck("unknown")+ passed = check.get("pass")+ balance = check.get("balance")+ if isinstance(passed, Mapping) and _search_check_matches(body, passed):+ return SearchCredentialCheck("pass")+ if isinstance(balance, Mapping) and _search_check_matches(body, balance):+ return SearchCredentialCheck("balance")+ if balance is None and isinstance(passed, Mapping) and passed.get("status") == 200:+ return SearchCredentialCheck("pass")+ return SearchCredentialCheck("unknown")++ async def search(+ self,+ source_id: str,+ vendor: str,+ service_id: str,+ credential_ref: str,+ request: Mapping[str, Any],+ *,+ on_sent: Callable[[], None] | None = None,+ ) -> SearchResponse:+ service = search_service(vendor, "search" if vendor in {"tavily", "exa"} else "openai_chat")+ if service is None or service.get("service_id") != service_id:+ return SearchResponse(None, {}, None, "invalid_endpoint")+ catalog = {"vendor": vendor, **service}+ return await self._search_http(+ catalog=catalog,+ credential_ref=credential_ref,+ method="POST",+ endpoint=str(service.get("endpoint") or ""),+ payload=request,+ on_sent=on_sent,+ )++ async def revoke_search_credential(self, credential_ref: str) -> None:+ await asyncio.to_thread(self.state_store.revoke_search_credential, credential_ref)+async def provision_oauth_credential(self,source_id: str,@@ -2186,8 +2530,12 @@ class CLIProxyEngineAdapter:async def revoke_api_key_credential(self, credential_ref: str) -> None:await asyncio.to_thread(self.state_store.assert_credential_unbound, credential_ref)- await asyncio.to_thread(self.state_store.credential_auth_scheme, credential_ref)- await asyncio.to_thread(self.supervisor.invalidate_configs)+ is_search = await asyncio.to_thread(+ self.state_store.api_key_credential_is_search,+ credential_ref,+ )+ if not is_search:+ await asyncio.to_thread(self.supervisor.invalidate_configs)await asyncio.to_thread(self.state_store.revoke_api_key_credential, credential_ref)async def revoke_credential(self, credential_ref: str) -> None:@@ -2199,6 +2547,9 @@ class CLIProxyEngineAdapter:self.state_store.credential_metadata_if_present,credential_ref,)+ if metadata is not None and metadata.get("protocol") == "search":+ await self.revoke_search_credential(credential_ref)+ returnauth_name = metadata.get("auth_name") if metadata is not None and metadata.get("kind") == "oauth" else Noneif auth_name:if metadata.get("activation_state") != "staged":@@ -2410,7 +2761,7 @@ class CLIProxyEngineAdapter:response_evidence_by_protocol: dict[str, _ProtocolEvidence] = {}ruled_out_protocols: set[str] = set()for protocol in protocol_order:- if protocol not in SOURCE_PROTOCOLS:+ if protocol not in MODEL_PROTOCOLS:raise EngineStateError("unsupported source protocol")owner_scoped_protocol = _protocol_is_persistable_without_shape_proof(credential_kind=str(credential_kind),diff --git a/vibe/model_hub_runtime/api_key_vendors.py b/vibe/model_hub_runtime/api_key_vendors.pyindex f1caf327d..862a55adc 100644--- a/vibe/model_hub_runtime/api_key_vendors.py+++ b/vibe/model_hub_runtime/api_key_vendors.py@@ -6,12 +6,13 @@ import jsonfrom dataclasses import dataclassfrom functools import lru_cachefrom pathlib import Path+from typing import Any, Mappingfrom urllib.parse import urlsplitfrom config.v2_config import normalize_model_hub_base_url, normalize_model_hub_vendor_id-_SUPPORTED_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat", "google"}+_SUPPORTED_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat", "google", "search"}_LEGACY_OFFICIAL_BASE_URLS = {# ``codex`` remains a supported legacy vendor alias outside the shipped# api-key vendor preset catalog. Runtime official-URL fallback must keep@@ -146,12 +147,88 @@ class APIKeyVendorCatalogEntry:# The models.dev provider whose entries describe what this vendor's# official endpoint accepts; ``None`` when no mapping has been verified.models_dev_provider: str | None = None+ # Bundled wire metadata, never supplied by a caller or a remote catalog.+ search: dict | None = Nonedef _catalog_path() -> Path:return Path(__file__).resolve().parents[1] / "data" / "api_key_vendors.json"+def _validate_search_catalog(item: object, *, protocol: str) -> dict[str, Any] | None:+ if item is None:+ return None+ if not isinstance(item, dict):+ raise ValueError("api-key vendor search catalog is invalid")+ required = {"service_id", "endpoint", "auth", "request", "result", "limits", "price", "free_check", "service_refused_statuses", "tool_only"}+ if protocol != "search":+ required.add("auto_enroll")+ if set(item) != required:+ raise ValueError("api-key vendor search catalog is invalid")+ endpoint = normalize_model_hub_base_url(item.get("endpoint"))+ if endpoint is None or urlsplit(endpoint).scheme != "https":+ raise ValueError("api-key vendor search catalog endpoint is invalid")+ if not isinstance(item.get("service_id"), str) or not item["service_id"].strip():+ raise ValueError("api-key vendor search catalog service id is invalid")+ if item.get("auth") not in {"bearer", "x-api-key"} or not isinstance(item.get("request"), dict) or not isinstance(item.get("result"), dict) or not isinstance(item.get("limits"), dict):+ raise ValueError("api-key vendor search catalog mapping is invalid")+ if "content_max_chars" in item["request"]:+ content_max_chars = item["request"]["content_max_chars"]+ if (+ not isinstance(content_max_chars, dict)+ or set(content_max_chars) != {"path", "value"}+ or not isinstance(content_max_chars.get("path"), str)+ or not content_max_chars["path"]+ or type(content_max_chars.get("value")) is not int+ or not 1 <= content_max_chars["value"] <= 4000+ ):+ raise ValueError("api-key vendor search catalog content maximum is invalid")+ if "reported_cost" in item["result"]:+ reported_cost = item["result"]["reported_cost"]+ if (+ not isinstance(reported_cost, dict)+ or set(reported_cost) != {"path", "estimate"}+ or not isinstance(reported_cost.get("path"), str)+ or not reported_cost["path"]+ or not isinstance(reported_cost.get("estimate"), bool)+ ):+ raise ValueError("api-key vendor search catalog reported cost is invalid")+ results_max = item["limits"].get("results_max")+ # Usage page counters use this fixed ceiling even after a catalog update.+ if isinstance(results_max, bool) or not isinstance(results_max, int) or not 1 <= results_max <= 100:+ raise ValueError("api-key vendor search catalog results maximum is invalid")+ price = item.get("price")+ if not isinstance(price, dict) or set(price) != {"unit", "usd_per_1k", "extra", "as_of", "url"} or price.get("unit") != "search":+ raise ValueError("api-key vendor search catalog price is invalid")+ if not isinstance(price.get("usd_per_1k"), (int, float)) or isinstance(price.get("usd_per_1k"), bool) or price["usd_per_1k"] < 0:+ raise ValueError("api-key vendor search catalog price is invalid")+ if not isinstance(price.get("extra"), list) or not isinstance(price.get("as_of"), str) or not isinstance(price.get("url"), str):+ raise ValueError("api-key vendor search catalog price is invalid")+ if not isinstance(item.get("tool_only"), bool) or item["tool_only"] != (protocol == "search"):+ raise ValueError("api-key vendor search catalog protocol is invalid")+ if protocol != "search" and not isinstance(item.get("auto_enroll"), bool):+ raise ValueError("api-key vendor search catalog auto-enroll flag is invalid")+ if not isinstance(item.get("service_refused_statuses"), list) or any(+ isinstance(status, bool) or not isinstance(status, int) or status < 400 or status >= 500+ for status in item["service_refused_statuses"]+ ) or len(set(item["service_refused_statuses"])) != len(item["service_refused_statuses"]):+ raise ValueError("api-key vendor search catalog refusal statuses are invalid")+ free_check = item.get("free_check")+ if free_check is not None:+ if not isinstance(free_check, dict):+ raise ValueError("api-key vendor search catalog free check is invalid")+ limit_rule = free_check.get("limit")+ if limit_rule is not None:+ pairs = limit_rule.get("pairs") if isinstance(limit_rule, dict) else None+ if not isinstance(pairs, list) or any(+ not isinstance(pair, dict)+ or not isinstance(pair.get("usage"), str)+ or not isinstance(pair.get("limit"), str)+ for pair in pairs+ ):+ raise ValueError("api-key vendor search catalog free check is invalid")+ return dict(item)+@lru_cache(maxsize=1)def api_key_vendor_catalog() -> tuple[APIKeyVendorCatalogEntry, ...]:payload = json.loads(_catalog_path().read_text(encoding="utf-8"))@@ -189,6 +266,7 @@ def api_key_vendor_catalog() -> tuple[APIKeyVendorCatalogEntry, ...]:official_base_url=official_base_url,protocol=protocol,models_dev_provider=models_dev_provider.strip() if models_dev_provider else None,+ search=_validate_search_catalog(item.get("search"), protocol=protocol),))seen_ids.add(vendor_id)@@ -204,6 +282,22 @@ def api_key_vendor_entry(vendor: str) -> APIKeyVendorCatalogEntry | None:return _catalog_by_id().get(vendor.strip().lower())+def search_service(vendor: str, protocol: str, base_url: str | None = None) -> dict | None:+ """The catalog search API this Source can use, never a relay or an OAuth grant.++ Callers also require kind=api_key. This pure predicate deliberately has no+ health or enabled checks: those belong to admission, not catalog identity.+ """+ entry = api_key_vendor_entry(vendor)+ if entry is None or entry.search is None:+ return None+ if entry.search["tool_only"]:+ return entry.search if protocol == "search" and base_url is None else None+ if protocol == "search" or (base_url is not None and not is_official_api_key_endpoint(vendor, base_url)):+ return None+ return entry.search++def pinned_api_key_protocol(vendor: str) -> str | None:entry = api_key_vendor_entry(vendor)return entry.protocol if entry is not None else Nonediff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.pyindex 296519f47..faba17ed8 100644--- a/vibe/model_hub_runtime/config.py+++ b/vibe/model_hub_runtime/config.py@@ -145,6 +145,10 @@ def _append_source(store: EngineStateStore,generation: str = "0",) -> None:+ if source.protocol == "search":+ # Tool-only Sources are owned by Model Hub's search adapter, never by+ # CLIProxyAPI. They must not cause a provider or model registration.+ returncredential = store.credential_metadata(source.credential_ref)if credential["kind"] == "oauth":# OAuth credentials are engine auth files, not YAML credential values.diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex ad92da429..aa008b1b5 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -30,8 +30,8 @@ logger = logging.getLogger(__name__)_CREDENTIAL_REF_RE = re.compile(r"^cred_[A-Za-z0-9_-]{6,128}$")_BEARER_CREDENTIAL_REF_RE = re.compile(r"^cred_auth_bearer_[0-9a-f]{32}$")+_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat", "google", "search"}_SOURCE_ID_RE = re.compile(r"^src_[a-z0-9]{8,}$")-_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat", "google"}# The engine writes its file log to ``logs`` under its working directory, the instance directory, only# when that directory already exists; otherwise it falls back to ``<auth-dir>/logs``, among the# credentials (CLIProxyAPI internal/logging/global_logger.go ResolveLogDirectory).@@ -796,6 +796,21 @@ class EngineStateStore:raise EngineStateError("API key credential is unavailable")return payload.get("auth_scheme")+ def api_key_credential_is_search(self, credential_ref: str) -> bool:+ """Identify tool-only retirement without requiring an intact old secret.++ Missing/corrupt documents retain ordinary API-key config invalidation;+ readable identity conflicts and unsafe paths still refuse retirement.+ """+ with self._lock:+ payload = self._read_replacement_credential_document(credential_ref)+ if payload is None:+ return False+ _validate_credential_auth_scheme(credential_ref, payload, require_secret=False)+ if payload.get("kind") != "api_key":+ raise EngineStateError("API key credential is unavailable")+ return payload.get("protocol") == "search"+def _private_credential_directory_present(self, directory: Path) -> bool:"""Observe owned directories without creating or repairing them."""for path in (self.root, directory):@@ -947,6 +962,14 @@ class EngineStateStore:self._remove_private_file_if_present(temporary_path)self._remove_private_file_if_present(path)+ def revoke_search_credential(self, credential_ref: str) -> None:+ """Retire a search-only namespace even after its document disappeared."""+ with self._lock:+ payload = self._read_replacement_credential_document(credential_ref)+ if payload is not None and payload.get("protocol") != "search":+ raise EngineStateError("credential is not a search API key")+ self.revoke_api_key_credential(credential_ref)+def revoke_api_key_credential(self, credential_ref: str) -> None:"""Retire a known API-key ref, never a watched OAuth auth file.@@ -1659,6 +1682,8 @@ def _validate_source_target(if credential_kind != "api_key":return+ if protocol == "search":+ returnif protocol == "google":try:validate_model_hub_protocol_vendor(vendor, protocol)diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 797cfa43d..7ad758d0a 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -4797,6 +4797,19 @@ async def model_hub_source_credential_put(source_id):return _model_hub_error(exc)[email protected]("/api/models/sources/<source_id>/reenable", methods=["POST"])+async def model_hub_source_reenable_post(source_id):+ from core.handlers.model_hub import ModelHubError++ try:+ if request.json not in (None, {}):+ raise ModelHubError("discovery_failed")+ result = await _model_hub_service().reenable_search_source(source_id)+ return _model_hub_success(**result)+ except ModelHubError as exc:+ return _model_hub_error(exc)++@app.route("/api/models/sources/<source_id>/reauth", methods=["POST"])async def model_hub_source_reauth_post(source_id):from core.handlers.model_hub import ModelHubError