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): web search service settings and Tools read (S1b) (#2887)
Call White7e2f19f58c5e
diff --git a/config/v2_config.py b/config/v2_config.pyindex f796577a3..0d8e67e6d 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -3131,6 +3131,94 @@ class ModelHubImageModelChoice:return {"source_id": self.source_id, "model_id": self.model_id}+def model_hub_search_service(source: ModelHubSourceConfig) -> Optional[dict[str, Any]]:+ """Catalog capability, independent of health and opt-in; never a relay or subscription."""++ from vibe.model_hub_runtime.api_key_vendors import search_service++ if source.kind != "api_key" or source.supply_channel != "hub" or not source.credential_ref:+ return None+ return search_service(source.vendor, source.protocol, source.base_url)+++@dataclass(frozen=True)+class ModelHubSearchServiceSettings:+ """Partial saved overrides, not resolved defaults (web-search-services.md §3.2)."""++ results: Optional[int] = None+ content: Optional[bool] = None+ enabled: Optional[bool] = None++ @classmethod+ def from_payload(cls, payload: object) -> "ModelHubSearchServiceSettings":+ if not isinstance(payload, dict):+ raise ValueError("Config 'model_hub.hosted_tools.web_search.services' entries must be objects")+ unknown = set(payload) - {"results", "content", "enabled"}+ if unknown:+ logger.warning("Config 'model_hub.hosted_tools.web_search.services' ignores unknown fields %s", sorted(unknown))+ if "results" in payload and (type(payload["results"]) is not int or payload["results"] < 1):+ raise ValueError("Config search service results must be a positive integer")+ for key in ("content", "enabled"):+ if key in payload and not isinstance(payload[key], bool):+ raise ValueError(f"Config search service {key} must be a boolean")+ return cls(**{key: payload[key] for key in ("results", "content", "enabled") if key in payload})++ def clamped(self, service: Mapping[str, Any]) -> "ModelHubSearchServiceSettings":+ """Read an obsolete override safely; disk is unchanged until an authorized write."""++ return replace(+ self,+ results=min(self.results, service["limits"]["results_max"]) if self.results is not None else None,+ content=False if self.content and not service["result"].get("content") else self.content,+ )++ def effective(self, service: Mapping[str, Any]) -> dict[str, Any]:+ saved = self.clamped(service)+ return {+ "results": saved.results if saved.results is not None else min(5, service["limits"]["results_max"]),+ "content": saved.content if saved.content is not None else False,+ "enabled": saved.enabled if saved.enabled is not None else bool(service["tool_only"] or service.get("auto_enroll")),+ }++ def to_payload(self) -> dict[str, Any]:+ return {key: value for key in ("results", "content", "enabled") if (value := getattr(self, key)) is not None}+++def _search_service_settings_from_payload(+ payload: object, sources: Optional[list[ModelHubSourceConfig]]+) -> dict[str, ModelHubSearchServiceSettings]:+ if not isinstance(payload, dict) or any(not is_model_hub_source_id(key) for key in payload):+ raise ValueError("Config 'model_hub.hosted_tools.web_search.services' must map Source ids to settings")+ live = {source.id: source for source in sources} if sources is not None else None+ settings = {}+ for source_id, raw in payload.items():+ # Removed Sources have no settings. Keep an extant but retargeted/retired Source's choices:+ # forgetting an opt-out would silently re-enrol it if its search capability returns later.+ if live is not None and source_id not in live:+ continue+ service = model_hub_search_service(live[source_id]) if live is not None else None+ saved = ModelHubSearchServiceSettings.from_payload(raw)+ # Only the in-memory parse is normalized. V2Config.load never writes it back; an authorized+ # writer later serializes these clamped overrides without freezing any absent default.+ settings[source_id] = saved.clamped(service) if service is not None else saved+ return settings+++def _executor_order_kinds_from_payload(+ payload: object, order: Optional[tuple[str, ...]], sources: Optional[list[ModelHubSourceConfig]]+) -> Optional[dict[str, str]]:+ # This derived snapshot affects placement, not consent. Damage follows the released missing-map rule;+ # discarding the whole tool entry would erase service opt-outs on the next unrelated config write.+ if isinstance(payload, dict):+ live = {source.id for source in sources} if sources is not None else None+ named = {key: value for key, value in payload.items()+ if key in (order or ()) and (live is None or key in live)}+ if all(isinstance(value, str) and value in {"service", "model"} for value in named.values()):+ return named+ logger.warning("Config 'model_hub.hosted_tools.web_search.executor_order_kinds': ignoring damaged role map")+ return None++@dataclass(frozen=True)class ModelHubHostedToolConfig:"""One hosted tool's user settings (``vibey-hosted-tools.md`` §3.3).@@ -3145,15 +3233,21 @@ class ModelHubHostedToolConfig:executor_order: Optional[tuple[str, ...]] = Noneservice_order: Optional[tuple[str, ...]] = Nonedefault_image: Optional[ModelHubImageModelChoice] = None+ prefer_native: bool = True+ services: Mapping[str, ModelHubSearchServiceSettings] = field(default_factory=dict)+ executor_order_kinds: Optional[Mapping[str, str]] = None@classmethod- def from_payload(cls, payload: object, *, tool: str) -> "ModelHubHostedToolConfig":+ def from_payload(+ cls, payload: object, *, tool: str, sources: Optional[list[ModelHubSourceConfig]] = None+ ) -> "ModelHubHostedToolConfig":"""Read one entry; fields it does not know are ignored with a warning, the ones it knows are kept."""if not isinstance(payload, dict):raise ValueError(f"Config 'model_hub.hosted_tools.{tool}' must be an object")known = {"enabled"} | (- ({"executor_order", "service_order"} if tool == "web_search" else {"executor_order"})+ ({"executor_order", "service_order", "prefer_native", "services", "executor_order_kinds"}+ if tool == "web_search" else {"executor_order"})if tool in MODEL_HUB_SEARCH_TOOLSelse {"default_model"})@@ -3163,15 +3257,28 @@ class ModelHubHostedToolConfig:enabled = payload.get("enabled", True)if not isinstance(enabled, bool):raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.enabled' must be a boolean")+ prefer_native = payload.get("prefer_native", True) if tool == "web_search" else True+ if not isinstance(prefer_native, bool):+ raise ValueError("Config 'model_hub.hosted_tools.web_search.prefer_native' must be a boolean")# 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 payloadhas_service_order = "service_order" in known and "service_order" in payloadhas_default = "default_model" in known and "default_model" in payload+ order = model_hub_executor_order(payload["executor_order"], tool=tool) if has_order else Nonereturn cls(enabled=enabled,- executor_order=model_hub_executor_order(payload["executor_order"], tool=tool) if has_order else None,+ executor_order=order,service_order=model_hub_service_order(payload["service_order"], tool=tool) if has_service_order else None,+ prefer_native=prefer_native,+ services=(+ _search_service_settings_from_payload(payload["services"], sources)+ if tool == "web_search" and "services" in payload else {}+ ),+ executor_order_kinds=(+ _executor_order_kinds_from_payload(payload["executor_order_kinds"], order, sources)+ if tool == "web_search" and "executor_order_kinds" in payload else None+ ),default_image=(ModelHubImageModelChoice.from_payload(payload["default_model"], tool=tool) if has_default else None),@@ -3185,10 +3292,21 @@ class ModelHubHostedToolConfig:out["service_order"] = list(self.service_order)if self.default_image is not None:out["default_model"] = self.default_image.to_payload()+ if not self.prefer_native:+ out["prefer_native"] = False+ if self.services:+ out["services"] = {source_id: saved.to_payload() for source_id, saved in self.services.items()}+ if self.executor_order_kinds is not None:+ out["executor_order_kinds"] = {+ source_id: kind for source_id, kind in self.executor_order_kinds.items()+ if source_id in (self.executor_order or ())+ }return out-def _hosted_tools_from_payload(section: Mapping[str, Any]) -> dict[str, ModelHubHostedToolConfig]:+def _hosted_tools_from_payload(+ section: Mapping[str, Any], sources: list[ModelHubSourceConfig]+) -> dict[str, ModelHubHostedToolConfig]:"""Read ``model_hub.hosted_tools`` as an optional feature that degrades on its own.Absent means every tool takes its defaults (on). An unknown tool key, or an unknown field inside an entry, is@@ -3210,7 +3328,7 @@ def _hosted_tools_from_payload(section: Mapping[str, Any]) -> dict[str, ModelHublogger.warning("Config 'model_hub.hosted_tools' ignores an unknown tool %r", tool)continuetry:- tools[tool] = ModelHubHostedToolConfig.from_payload(raw, tool=tool)+ tools[tool] = ModelHubHostedToolConfig.from_payload(raw, tool=tool, sources=sources)except ValueError as exc:logger.warning("%s; hosted tool %r is off", exc, tool)tools[tool] = ModelHubHostedToolConfig(enabled=False)@@ -3362,7 +3480,7 @@ class ModelHubConfig:sources=sources,agents=agents,runtime_default_applied=runtime_default_applied,- hosted_tools=_hosted_tools_from_payload(payload),+ hosted_tools=_hosted_tools_from_payload(payload, sources),)_drop_vibey_client_presets(config.agents["vibey"])agents = config.agentsdiff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex 94de03c66..d1002c869 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -1,4 +1,4 @@-"""Model Hub EngineAdapter interface. FINAL CONTRACT v17 (2026-10-19).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v18 (2026-10-20).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:diff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.pyindex 8cdf873c4..57c09e8d6 100644--- a/core/handlers/model_hub/hosted_tools.py+++ b/core/handlers/model_hub/hosted_tools.py@@ -31,17 +31,20 @@ from config.v2_config import (ModelHubConfig,ModelHubHostedToolConfig,ModelHubImageModelChoice,+ ModelHubSearchServiceSettings,ModelHubSourceConfig,hosted_tool_setting,is_model_hub_model_id,is_model_hub_source_id,model_hub_executor_order,+ model_hub_search_service,)from vibe.backend_model_catalog import (IMAGE_PROTOCOLS,HostedToolSpec,ImageModelSpec,bundled_provider_vendors,+ hosted_tool_spec,provider_image_models,provider_overlay_entry,source_executor_models,@@ -65,6 +68,9 @@ SpecLookup = Callable[[str, str, str, str], Optional[HostedToolSpec]]UNKNOWN_ENGINE_RELEASE = "unknown-engine"NATIVE_REPLAY_PROTOCOLS: frozenset[str] = frozenset({"anthropic", "openai_responses"})+# S2 enables this together with the chain, after S3/S4 and disclosure ship. Never a user-facing toggle.+SEARCH_SERVICES_ACTIVE: Final = False+Assumption = Literal["assumed", "unsupported"]@@ -473,9 +479,81 @@ def hop_hosted_tools(return entries+def search_service_settings(+ setting: ModelHubHostedToolConfig, source: ModelHubSourceConfig+) -> dict[str, Any] | None:+ """Effective per-Source settings, including catalog defaults and obsolete-value clamping."""++ service = model_hub_search_service(source)+ if service is None:+ return None+ return setting.services.get(source.id, ModelHubSearchServiceSettings()).effective(service)+++def search_executor_kind(source: ModelHubSourceConfig, setting: ModelHubHostedToolConfig) -> str:+ """The role an order save records, not a chain/placement decision (S2 owns those)."""++ settings = search_service_settings(setting, source)+ if settings is None:+ return "model"+ if settings["enabled"] or not listed_executor_model(source, "web_search", spec_for=hosted_tool_spec):+ return "service"+ # Opting a model Source out of its search API preserves its existing model executor, if any.+ return "model"++# --- The Tools read (§3.3) ---------------------------------------------------------------------------------------+def _service_candidate_payload(+ source: ModelHubSourceConfig, setting: ModelHubHostedToolConfig, *, trial_pending: bool+) -> dict[str, Any]:+ service = model_hub_search_service(source)+ assert service is not None+ return {+ "kind": "service",+ "source_id": source.id,+ "model_id": service["service_id"],+ # A model Source may have monthly model billing; its separate search API is still priced per search.+ "billing": "metered",+ "relay": False,+ "price": {**service["price"], "extra": [dict(part) for part in service["price"]["extra"]]},+ "settings": search_service_settings(setting, source),+ "state": source.state.to_payload(),+ "trial_pending": trial_pending,+ # S2's service-scoped cooldown owner supplies this at activation; S1b has no service attempts.+ "cooldown_until": None,+ }+++def _service_vendors(config: ModelHubConfig) -> list[dict[str, Any]]:+ from vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalog++ return [+ {+ "id": vendor.id,+ "name": vendor.label,+ "price": {**service["price"], "extra": [dict(part) for part in service["price"]["extra"]]},+ # No free-tier promise has been verified in the bundled catalog. Null is unknown, never zero.+ "free_tier": None,+ "facts": {+ "tool_only": service["tool_only"],+ "auto_enroll": bool(service.get("auto_enroll")),+ "free_check": service["free_check"] is not None,+ },+ "results_max": service["limits"]["results_max"],+ "content_supported": bool(service["result"].get("content")),+ "content_changes_price": any(part.get("when") == "content" for part in service["price"]["extra"]),+ "source_ids": [+ source.id for source in config.sources+ if source.vendor == vendor.id and model_hub_search_service(source) is not None+ ],+ }+ for vendor in api_key_vendor_catalog()+ if (service := vendor.search) is not None+ ]++def _price_payload(price: Any) -> dict[str, Any] | None:"""An overlay list price; None when no list price is known, never zero."""@@ -554,6 +632,7 @@ def hosted_tools_status(evidence: HostedEvidence,spec_for: SpecLookup,image_price: Callable[[ModelHubSourceConfig, ImageModelSpec], Optional[dict[str, Any]]],+ search_trial_pending: Callable[[str], bool] = lambda _source_id: False,) -> dict[str, Any]:"""What Models → Tools reads (``hosted-tools-status.schema.json``): settings, saved and effective, and status."""@@ -568,6 +647,7 @@ def hosted_tools_status(entry["effective_order"] = [candidate.source.id for candidate in chain]entry["executor_candidates"] = [{+ "kind": "model","source_id": candidate.source.id,"model_id": candidate.model_id,"billing": candidate.source.billing,@@ -576,6 +656,27 @@ def hosted_tools_status(}for candidate in chain]+ if tool == "web_search":+ entry["prefer_native"] = setting.prefer_native+ entry["services"] = {+ source_id: saved.clamped(service).to_payload()+ for source_id, saved in setting.services.items()+ if source_id in sources and (service := model_hub_search_service(sources[source_id])) is not None+ }+ entry["service_order"] = [source_id for source_id in (setting.service_order or ()) if source_id in sources]+ # This is the only activation gate for BOTH read additions. S2 supplies the unified chain+ # and its placement rule here when enabling it; this lane only defines the projection.+ if SEARCH_SERVICES_ACTIVE:+ service_rows = [+ _service_candidate_payload(source, setting, trial_pending=search_trial_pending(source.id))+ for source in config.sources+ if model_hub_search_service(source) is not None and search_executor_kind(source, setting) == "service"+ ]+ service_ids = {row["source_id"] for row in service_rows}+ entry["executor_candidates"] = service_rows + [+ row for row in entry["executor_candidates"] if row["source_id"] not in service_ids+ ]+ entry["service_vendors"] = _service_vendors(config)else:choices = image_choices(config, evidence=evidence)saved = choices.saved_default@@ -626,6 +727,8 @@ def apply_hosted_tool_put(config: ModelHubConfig, tool: str, payload: object) ->if tool not in MODEL_HUB_HOSTED_TOOLS:raise HostedToolSettingRefused("hosted_tool_not_found", 404)allowed = {"enabled"} | ({"executor_order"} if tool in MODEL_HUB_SEARCH_TOOLS else {"default_model"})+ if tool == "web_search":+ allowed |= {"prefer_native", "services"}if not isinstance(payload, dict) or not payload or set(payload) - allowed:raise HostedToolSettingRefused("invalid_parameter", 400)changes: dict[str, Any] = {}@@ -635,6 +738,12 @@ def apply_hosted_tool_put(config: ModelHubConfig, tool: str, payload: object) ->if not isinstance(payload["enabled"], bool):raise ValueError("enabled must be a boolean")changes["enabled"] = payload["enabled"]+ if "prefer_native" in payload:+ if not isinstance(payload["prefer_native"], bool):+ raise ValueError("prefer_native must be a boolean")+ changes["prefer_native"] = payload["prefer_native"]+ if "services" in payload:+ changes["services"] = _patch_search_services(config, payload["services"])if "executor_order" in payload:order = payload["executor_order"]changes["executor_order"] = None if order is None else model_hub_executor_order(order, tool=tool)@@ -643,7 +752,48 @@ def apply_hosted_tool_put(config: ModelHubConfig, tool: str, payload: object) ->changes["default_image"] = None if default is None else ModelHubImageModelChoice.from_payload(default, tool=tool)except ValueError:raise HostedToolSettingRefused("invalid_parameter", 400) from None- return replace(hosted_tool_setting(config, tool), **changes)+ setting = replace(hosted_tool_setting(config, tool), **changes)+ if tool == "web_search" and "executor_order" in payload:+ live = {source.id: source for source in config.sources}+ setting = replace(setting, executor_order_kinds=(+ {source_id: search_executor_kind(live[source_id], setting)+ for source_id in setting.executor_order if source_id in live}+ if setting.executor_order is not None else None+ ))+ return setting+++def _patch_search_services(config: ModelHubConfig, payload: object) -> dict[str, ModelHubSearchServiceSettings]:+ if not isinstance(payload, dict):+ raise ValueError("services must be a Source-keyed patch")+ saved = dict(hosted_tool_setting(config, "web_search").services)+ live = {source.id: source for source in config.sources}+ for source_id, patch in payload.items():+ if not is_model_hub_source_id(source_id):+ raise ValueError("services keys must be Source ids")+ if patch is None:+ saved.pop(source_id, None)+ continue+ source = live.get(source_id)+ service = model_hub_search_service(source) if source is not None else None+ if service is None or not isinstance(patch, dict) or set(patch) - {"results", "content", "enabled"}:+ raise ValueError("services must name a search-capable Source and known fields")+ merged = saved.get(source_id, ModelHubSearchServiceSettings()).clamped(service).to_payload()+ for key, value in patch.items():+ if value is None:+ merged.pop(key, None)+ else:+ merged[key] = value+ parsed = ModelHubSearchServiceSettings.from_payload(merged)+ if parsed.results is not None and parsed.results > service["limits"]["results_max"]:+ raise ValueError("results exceeds the catalog maximum")+ if parsed.content and not service["result"].get("content"):+ raise ValueError("the service does not return page text")+ if parsed.to_payload():+ saved[source_id] = parsed+ else:+ saved.pop(source_id, None)+ return saveddef clear_request(tool: str, payload: object) -> Callable[[EvidenceRecord], bool]:diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 56cff8d75..7b002fce5 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": 17,+ "contract_version": 18,"turn_id": normalized_turn_id,"ts": ts or _utc_now_iso(),"agent": trace.agent,diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 8fba27f65..e6f9347aa 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -42,6 +42,7 @@ from config.v2_config import (normalize_storable_backend_model_text,normalize_model_hub_base_url,normalize_model_hub_vendor_id,+ model_hub_search_service,normalized_model_hub_override,validate_model_hub_protocol_vendor,validate_model_hub_source_client_nonce,@@ -259,7 +260,7 @@ from .usage import (local_usage_day,)-CONTRACT_VERSION = 17+CONTRACT_VERSION = 18def seeded_source_name(vendor: str) -> str:@@ -382,8 +383,8 @@ def _described_as_unfit_for_agent_turns(match: Mapping[str, Any]) -> bool:)-AGENT_CHAIN_CONTRACT_VERSION = 17-PROBE_RESULT_CONTRACT_VERSION = 17+AGENT_CHAIN_CONTRACT_VERSION = 18+PROBE_RESULT_CONTRACT_VERSION = 18_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15_SOURCE_PROBE_TIMEOUT_SECONDS = 60# Background inventory refresh. The first tick doubles as the startup delay, so@@ -1110,9 +1111,7 @@ def _mask_credential(value: str) -> str: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)+ return model_hub_search_service(source)def _search_service_for_source(source: ModelHubSourceConfig) -> dict[str, Any] | None:@@ -1376,7 +1375,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:manager = EngineRuntimeManager()return {- "contract_version": 17,+ "contract_version": 18,"enabled": enabled,"host_platform": status.host_platform or manager.host_platform(),"manifest": manager.contract_manifest(),@@ -6818,6 +6817,7 @@ class ModelHubService:evidence=self.hosted_evidence(),spec_for=hosted_tool_spec,image_price=self._image_price,+ search_trial_pending=self.search_reenable_trial_pending,)}diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex a7fce1816..1d2fb4178 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,6 +1,24 @@# Model Hub contracts-Status: **contract_version 17**, 2026-10-19: search-service foundations+Status: **contract_version 18**, 2026-10-20: web-search settings and dormant Tools+read (S1b, `../web-search-services.md` §3.2/§3.5). The RC tag `gh-v3.2.2rc12`+contains S1a and v17, so these additions open a new event rather than changing v17.+- V2 adds `prefer_native`, partial Source-keyed `services` overrides with catalog+ clamping, and server-owned `executor_order_kinds` saved with each web-search order.+- The PUT merges Source/field patches and supports null override resets.+- The Tools read adds `prefer_native`, saved `services`, read-only `service_order`,+ model/service candidate discriminants, service settings/health/trial/cooldown+ fields, service vendor facts, and page-text list-price extras.+- Service candidates and `service_vendors` remain absent behind the single internal+ activation gate until S2. There is no new UI, service execution, placement rule,+ turn freeze or native-preference routing change in S1b.+- The versioned mirrors advance together; persisted TurnProvenance retains v5–v17+ and adds v18. The rc12 hosted-tools loader ignores new optional config fields+ and retains the whole-tool switch and both orders, not per-Source service+ opt-outs. An rc12 config write drops those overrides; re-upgrading then uses+ service defaults, so DeepSeek's opt-out must be reapplied before execution.++It builds on v17 (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 persistenceship before search execution. S1b, S2 and S3 extend this same version event only@@ -273,7 +291,7 @@ comparison. A gate may not report success by comparing stale input with itself.## Version closure-`contract_version` 17 must coexist in all registered version locations on the same tested head:+`contract_version` 18 must coexist in all registered version locations on the same tested head:- `mirror-registry.json`- `agent-chain.schema.json`diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex 94de03c66..d1002c869 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -1,4 +1,4 @@-"""Model Hub EngineAdapter interface. FINAL CONTRACT v17 (2026-10-19).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v18 (2026-10-20).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:diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex d702d0b4c..66e515f6c 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": 17 },+ "contract_version": { "const": 18 },"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },"model_id": { "type": "string" },"manual_override": {@@ -255,7 +255,7 @@],"examples": [{- "contract_version": 17,+ "contract_version": 18,"backend": "codex","model_id": "unlisted-model","manual_override": null,@@ -265,7 +265,7 @@"supply_state": "ok"},{- "contract_version": 17,+ "contract_version": 18,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -275,7 +275,7 @@"supply_state": "ok"},{- "contract_version": 17,+ "contract_version": 18,"backend": "claude","model_id": "claude-opus-4-6","manual_override": null,@@ -285,7 +285,7 @@"supply_state": "waiting"},{- "contract_version": 17,+ "contract_version": 18,"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": 17,+ "contract_version": 18,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -305,7 +305,7 @@"supply_state": "interrupted"},{- "contract_version": 17,+ "contract_version": 18,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -315,7 +315,7 @@"supply_state": "interrupted"},{- "contract_version": 17,+ "contract_version": 18,"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 b95a91dbc..1cd68951e 100644--- a/docs/plans/model-hub-contracts/api-response.schema.json+++ b/docs/plans/model-hub-contracts/api-response.schema.json@@ -61,7 +61,7 @@"required": ["ok", "contract_version", "probe"],"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"probe": {"$ref": "model-hub/source-probe-result.schema.json"}}},@@ -160,7 +160,7 @@"SuccessCore": {"properties": {"ok": {"const": true},- "contract_version": {"const": 17}+ "contract_version": {"const": 18}}},"SourceListResponse": {@@ -169,7 +169,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}}},@@ -179,7 +179,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"observation": {"$ref": "model-hub/observation-result.schema.json"}}},@@ -189,7 +189,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"source": {"$ref": "#/definitions/SourceApi"},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}@@ -201,7 +201,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"source": {"$ref": "#/definitions/SourceApi"}}},@@ -211,7 +211,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"source": {"$ref": "#/definitions/SourceApi"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -223,7 +223,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"source": {"allOf": [{"$ref": "#/definitions/SourceApi"},@@ -241,7 +241,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}}@@ -252,7 +252,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}}},@@ -262,7 +262,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"agent": {"$ref": "#/definitions/AgentSupplyApi"}}},@@ -279,7 +279,7 @@],"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"agent": {"$ref": "#/definitions/AgentSupplyApi"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}@@ -304,7 +304,7 @@"additionalProperties": false,"properties": {"ok": {"const": false},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"error": {"const": "candidate_suppliers_changed"},"detail": {"type": "string", "minLength": 1},"changed": {@@ -324,7 +324,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"agent": {"type": "object","required": ["backend", "mode", "catalog_models"],@@ -425,7 +425,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"candidates": {"type": "object","required": ["builtin", "providers", "in_list"],@@ -444,7 +444,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"matches": {"type": "array","maxItems": 8,@@ -478,7 +478,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"chain": {"$ref": "model-hub/agent-chain.schema.json"}}},@@ -488,7 +488,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}}},@@ -498,7 +498,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"chain": {"$ref": "model-hub/agent-chain.schema.json"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -510,7 +510,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"probe": {"$ref": "model-hub/probe-result.schema.json"}}},@@ -520,7 +520,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}}},@@ -530,7 +530,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"usage": {"$ref": "model-hub/usage-summary.schema.json"}}},@@ -540,7 +540,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"quota": {"$ref": "model-hub/quota-summary.schema.json"}}},@@ -550,7 +550,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"hosted_tools": {"$ref": "model-hub/hosted-tools-status.schema.json"}}},@@ -560,7 +560,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -582,7 +582,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -605,7 +605,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -630,7 +630,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17}+ "contract_version": {"const": 18}}},"RuntimeApi": {@@ -652,7 +652,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"scan": {"$ref": "model-hub/migration-scan.schema.json"}}},@@ -662,7 +662,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"applied": {"type": "integer", "minimum": 0},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}@@ -674,7 +674,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}}},@@ -685,7 +685,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"provenance": {"anyOf": [{"$ref": "model-hub/turn-provenance.schema.json"},@@ -700,7 +700,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 17},+ "contract_version": {"const": 18},"runtime": {"$ref": "#/definitions/RuntimeApi"}}}diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex b9f4324bf..39e76f169 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` 17** — 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` 18** — 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: 17, ...}`.+Success envelope: `{ok: true, contract_version: 18, ...}`.Failure envelope:-`{ok: false, contract_version: 17, error: <machine_code>, detail?: <i18n_key>}`.+`{ok: false, contract_version: 18, 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` 17, the+The shared envelope and every versioned nested contract carry `contract_version` 18, theterminal value. Supported persisted config shapes and historical TurnProvenanceremain readable; ephemeral envelopes use only the terminal version.@@ -73,7 +73,7 @@ runtime open. Once models are configured it participates in the runtime Stop gua| GET `/api/models/quota` | → `{quota: QuotaSummary}` | Rate-limit windows of every hub-held subscription Source, from the vendor's own usage report, plus each Source's API-price `value` (see Subscription quota). Served from the server cache; a Source older than five minutes is re-read before answering, bounded by a short deadline, and a Source still being read is listed in `pending`. Never starts the engine. || POST `/api/models/quota/refresh` | → `{quota: QuotaSummary}` | Forced re-read. Rate-limited per Source to one vendor call every 30 seconds and suppressed while a Source cools down after a vendor 429; a suppressed Source returns its cached snapshot. || GET `/api/models/hosted-tools` | → `{hosted_tools: HostedToolsStatus}` | Models → Tools (`hosted-tools-status.schema.json`): every catalog tool with its switch (absent setting = on), its passive status from real use (`latest_ok`, current `refused[]`, per-pair `verified[]`), for a search tool the saved and effective executor order with every eligible executor candidate and its unit rates, and for `image_generate` the saved and effective default and the available image models. Memory only; nothing is probed. |-| PUT `/api/models/hosted-tools/<tool>` | `{enabled?: boolean, executor_order?: null \| [source_id], default_model?: null \| {source_id, model_id}}` → `{hosted_tools: HostedToolsStatus}` | Changes one tool's settings field by field: an absent field is unchanged, `null` resets `executor_order` to automatic or `default_model` to the default. `executor_order` is for search tools and `default_model` for `image_generate`; values are saved as given, never resolved. It applies from the next turn and interrupts nothing. An unknown tool returns `404 hosted_tool_not_found`; an empty or malformed body `400 invalid_parameter`, including a null `enabled`, an id that is not a Source id (`src_…`), or a model id with surrounding whitespace. |+| PUT `/api/models/hosted-tools/<tool>` | `{enabled?: boolean, executor_order?: null \| [source_id], default_model?: null \| {source_id, model_id}, prefer_native?: boolean, services?: {source_id: null \| {results?: integer \| null, content?: boolean \| null, enabled?: boolean \| null}}}` → `{hosted_tools: HostedToolsStatus}` | Changes one tool's settings field by field: an absent field is unchanged, `null` resets `executor_order` to automatic or `default_model` to the default. `executor_order` is for search tools and `default_model` for `image_generate`; values are saved as given, never resolved. It applies from the next turn and interrupts nothing. An unknown tool returns `404 hosted_tool_not_found`; an empty or malformed body `400 invalid_parameter`, including a null `enabled`, an id that is not a Source id (`src_…`), or a model id with surrounding whitespace. || POST `/api/models/hosted-tools/<tool>/clear` | `{source_id?, model_id?}` → `{hosted_tools: HostedToolsStatus}` | Clears the tool's refusals (`call` and `replay`): on one Source and model, on one Source (every model), or with `{}` on every Source. `model_id` requires `source_id`; neither is nullable, so a malformed body is refused rather than widened into a broader clear. A Source or model with nothing to clear is a no-op that answers the read. The file is written first: a failed write returns `500 state_write_failed` and changes nothing. A cleared Source is assumed again from its next request. An unknown tool returns `404 hosted_tool_not_found`; any other body `400 invalid_parameter`. || POST `/api/models/sources/<source_id>/evidence/clear` | `{model_id, feature: {kind: "effort", name}}` → `{source: Source}` | Clears one effort refusal of a Source's model, so the next request at that effort may reach it. A missing record is a no-op. An unknown Source returns `404 source_not_found`; a hosted-tool feature or any other body `400 invalid_parameter` (hosted refusals clear through the Tools clear); a failed write `500 state_write_failed` with nothing changed. || POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. |@@ -83,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` 17 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` 18 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. |@@ -93,6 +93,69 @@ PUT and compatibility chains/reorder share backend-default semantics and effectipreserving all manual arrays. Exact manual order is saved through the chain resource;DELETE restores automatic and POST preview evaluates the draft without a write.+### Web-search settings and dormant service read (S1b)++`web_search` additionally reads `prefer_native` (true when absent), `services`+(saved partial overrides for currently search-capable Sources, not resolved defaults), and `service_order`+(the server-owned tool-only Source creation order with removed ids skipped, `[]` when absent). Every search+executor now has a discriminant `kind: "model" | "service"`; `x_search` remains model-only.+Extant retargeted or retired Sources are omitted from `services` while they cannot+search, but their overrides (especially opt-out) stay in config for when capability+returns. Removed Sources' overrides are ignored.++Until S2 activates execution, **the read contains no service candidates and omits+`service_vendors` entirely**. One internal `SEARCH_SERVICES_ACTIVE` switch gates+both. Settings load and save now, but `prefer_native` does not change hop facts+and service settings do not change the model executor chain in S1b. No user-facing+activation toggle exists.++The service variant is frozen for S4/S2 in `hosted-tools-status.schema.json`:+`model_id` is the catalog service id; `billing: "metered"`, `relay: false`, and+`price` is the catalog list price, including optional `extra[].when: "content"`+and unit `page`. `settings` holds effective `{results, content, enabled}`;+`state` is the Source's health, `trial_pending` covers both armed and in-flight+one-shot trials, and `cooldown_until` is nullable (S2 owns service cooldowns).+`service_vendors` contains `{id, name, price, free_tier, facts, results_max,+content_supported, content_changes_price, source_ids}`. Facts are the catalog's+`{tool_only, auto_enroll, free_check}` booleans. A free tier not verified in the+catalog reads as null, never a promise of zero cost. `source_ids` includes+opted-out search-capable Sources, but not relays or subscriptions.++PUT accepts `prefer_native` and `services` only for `web_search`. `prefer_native`+is a boolean, not nullable. `services` is a Source-keyed patch: an absent Source+is untouched, a present object merges only its supplied fields, and a null+Source or null field removes its saved override. An empty patch is a no-op.+Defaults are `results: min(5, vendor maximum)`, `content: false`, and `enabled:+true`, except false for a model vendor without `auto_enroll`. Writes reject+non-integer/out-of-range results and page text where the catalog does not offer+it; unknown/non-search-capable Sources reject non-null patches. Null may clear+a stale Source override. A rejected patch changes nothing. Concurrent edits to+different Sources or fields serialize against the current saved settings.++Loading ignores removed Sources and clamps obsolete catalog bounds in memory+without changing the file: results to the current maximum, content to false+when page text is no longer offered. The next authorized config write persists+normalization; absent overrides remain absent.++Every `web_search.executor_order` save also writes `executor_order_kinds` from+the resulting per-Source settings: each extant named Source's `service` or+`model` role. Removed ids remain in the saved order but have no map entry. Reset+to automatic removes both fields. A missing map/entry reads as `model`; map ids+not named by the order or no longer naming an extant Source are ignored on load,+including before role validation, and the next authorized write drops them. An+extant retargeted/retired Source keeps its saved role. A damaged map is treated as absent with a+warning, retaining the tool switch, service opt-outs and other saved choices.+Neither `executor_order_kinds` nor `service_order` is client-writable. S2 owns the+read-time placement rule; S1b preserves the saved order and kinds across restart+without changing execution.++Downgrade boundary: rc12 ignores `prefer_native`, `services` and+`executor_order_kinds`. Its next config write drops those fields, including+per-Source search opt-outs, while preserving the whole-tool switch and both+orders. Re-upgrading then uses service defaults; reapply DeepSeek's opt-out+before enabling service execution. This is not a promise to retain new choices+through an older release's write.+### Usage report windows`GET /api/models/usage?days=<n>` keeps the released daily-only response shape.@@ -649,7 +712,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:```json{"ok": true,- "contract_version": 17,+ "contract_version": 18,"source": {"id": "src_anthkey01","kind": "api_key",@@ -759,7 +822,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c```json{"ok": false,- "contract_version": 17,+ "contract_version": 18,"error": "source_last_supplier","would_remove_hops": [],"would_interrupt": [@@ -898,7 +961,7 @@ API-key success:```json{"ok": true,- "contract_version": 17,+ "contract_version": 18,"source": {"id": "src_relay9c1x","kind": "api_key",@@ -993,7 +1056,7 @@ Status and submit return the same terminal shape:```json{"ok": true,- "contract_version": 17,+ "contract_version": 18,"flow": {"flow_id": "oaf_claude01","client_nonce": "ofn_01j5w8z7p4n6q2rt",@@ -1066,9 +1129,9 @@ a valid `interrupted` chain.```json{"ok": true,- "contract_version": 17,+ "contract_version": 18,"chain": {- "contract_version": 17,+ "contract_version": 18,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -1095,7 +1158,7 @@ In Direct mode both chain and probe refuse with:```json{"ok": false,- "contract_version": 17,+ "contract_version": 18,"error": "direct_mode","detail": "models.hub.direct_mode"}@@ -1109,9 +1172,9 @@ A successful probe nests its result:```json{"ok": true,- "contract_version": 17,+ "contract_version": 18,"probe": {- "contract_version": 17,+ "contract_version": 18,"backend": "claude","channel": "hub","reachable": false,@@ -1134,7 +1197,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 17,+ "contract_version": 18,"backend": "codex","channel": "native_cli","reachable": true,@@ -1147,7 +1210,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 17,+ "contract_version": 18,"backend": "codex","channel": "native_cli","reachable": false,@@ -1163,7 +1226,7 @@ No candidate is an API error with a typed model-scoped state:```json{"ok": false,- "contract_version": 17,+ "contract_version": 18,"error": "probe_no_candidate","detail": "models.probe.no_candidate.waiting","supply": {@@ -1354,7 +1417,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: 17, provenance: TurnProvenance | null}`;+Success uses exactly `{ok: true, contract_version: 18, provenance: TurnProvenance | null}`;there is no `success` field or envelope exception.Local `engine_down` records may also contain `local_error_detail`, an OS-generated@@ -1448,7 +1511,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 17,+ "contract_version": 18,"error": "provenance_unavailable","detail": "models.provenance.direct_mode"}@@ -1457,7 +1520,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 17,+ "contract_version": 18,"error": "provenance_unavailable","detail": "models.provenance.attribution_ambiguous"}diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.jsonindex 47d636676..67a910ff6 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": 17 },+ "contract_version": { "const": 18 },"error": {"enum": ["source_last_supplier",@@ -116,7 +116,7 @@"examples": [{"ok": false,- "contract_version": 17,+ "contract_version": 18,"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/hosted-tools-status.schema.json b/docs/plans/model-hub-contracts/hosted-tools-status.schema.jsonindex 236c1db8c..8e6aa27c4 100644--- a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json+++ b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json@@ -89,8 +89,9 @@"required": ["unit", "usd_per_1k"],"additionalProperties": false,"properties": {- "unit": { "enum": ["call", "search", "post", "profile"] },- "usd_per_1k": { "type": "number", "minimum": 0 }+ "unit": { "enum": ["call", "search", "post", "profile", "page"] },+ "usd_per_1k": { "type": "number", "minimum": 0 },+ "when": { "const": "content", "description": "Charged only when page text is requested; highlights are included in the search price." }}}},@@ -98,12 +99,113 @@"url": { "type": "string", "pattern": "^https://" }}},+ "ModelListPrice": {+ "allOf": [+ { "$ref": "#/definitions/ListPrice" },+ { "properties": { "extra": { "items": { "properties": {+ "unit": { "enum": ["call", "search", "post", "profile"] }, "when": false+ } } } } }+ ]+ },+ "ServiceListPrice": {+ "allOf": [{ "$ref": "#/definitions/ListPrice" }, { "properties": { "unit": { "const": "search" } } }]+ },+ "SavedServiceSettings": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "results": { "type": "integer", "minimum": 1, "maximum": 100 },+ "content": { "type": "boolean" },+ "enabled": { "type": "boolean" }+ }+ },+ "ServiceSettings": {+ "allOf": [+ { "$ref": "#/definitions/SavedServiceSettings" },+ { "required": ["results", "content", "enabled"] }+ ]+ },+ "ModelExecutor": {+ "type": "object",+ "required": ["kind", "source_id", "model_id", "billing", "relay", "price"],+ "additionalProperties": false,+ "properties": {+ "kind": { "const": "model" },+ "source_id": { "$ref": "#/definitions/SourceId" },+ "model_id": { "type": "string", "minLength": 1 },+ "billing": { "enum": ["monthly", "metered"] },+ "relay": { "type": "boolean", "description": "A non-official endpoint is priced at its vendor's API price." },+ "price": { "oneOf": [{ "type": "null" }, { "$ref": "#/definitions/ModelListPrice" }] }+ }+ },+ "ServiceExecutor": {+ "type": "object",+ "description": "Dormant until S2. A search API's catalog service id occupies model_id; Source health and one-shot trial state are display facts, not a probe.",+ "required": ["kind", "source_id", "model_id", "billing", "relay", "price", "settings", "state", "trial_pending", "cooldown_until"],+ "additionalProperties": false,+ "properties": {+ "kind": { "const": "service" },+ "source_id": { "$ref": "#/definitions/SourceId" },+ "model_id": { "type": "string", "minLength": 1 },+ "billing": { "const": "metered" },+ "relay": { "const": false },+ "price": { "$ref": "#/definitions/ServiceListPrice" },+ "settings": { "$ref": "#/definitions/ServiceSettings" },+ "state": { "$ref": "source.schema.json#/properties/state" },+ "trial_pending": { "type": "boolean" },+ "cooldown_until": { "oneOf": [{ "type": "null" }, { "$ref": "#/definitions/Moment" }] }+ }+ },+ "ServiceVendor": {+ "type": "object",+ "additionalProperties": false,+ "required": ["id", "name", "price", "free_tier", "facts", "results_max", "content_supported", "content_changes_price", "source_ids"],+ "properties": {+ "id": { "type": "string", "minLength": 1 },+ "name": { "type": "string", "minLength": 1 },+ "price": { "$ref": "#/definitions/ServiceListPrice" },+ "free_tier": { "type": ["string", "null"], "description": "Catalog-verified free-tier description, null when unknown (not a claim of no free tier). Currently null for every vendor." },+ "facts": {+ "type": "object",+ "additionalProperties": false,+ "required": ["tool_only", "auto_enroll", "free_check"],+ "properties": {+ "tool_only": { "type": "boolean" },+ "auto_enroll": { "type": "boolean" },+ "free_check": { "type": "boolean" }+ }+ },+ "results_max": { "type": "integer", "minimum": 1, "maximum": 100 },+ "content_supported": { "type": "boolean" },+ "content_changes_price": { "type": "boolean" },+ "source_ids": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/definitions/SourceId" }, "description": "All current search-capable Sources for this vendor, including opted-out Sources. Empty means not added." }+ }+ },"SearchTool": {"type": "object","required": ["name", "enabled", "status", "executor_order", "effective_order", "executor_candidates"],"additionalProperties": false,+ "allOf": [{+ "if": { "properties": { "name": { "const": "web_search" } } },+ "then": { "required": ["prefer_native", "services", "service_order"] },+ "else": {+ "properties": {+ "prefer_native": false, "services": false, "service_order": false, "service_vendors": false,+ "executor_candidates": { "items": { "$ref": "#/definitions/ModelExecutor" } }+ }+ }+ }],"properties": {"name": { "enum": ["web_search", "x_search"] },+ "prefer_native": { "type": "boolean", "description": "Saved preference, true when absent. S2 activates its effect on hop facts." },+ "services": {+ "type": "object",+ "description": "Saved partial overrides for currently search-capable Sources, not resolved defaults. Extant retargeted/retired Sources are omitted while incapable, but their overrides remain in config for when capability returns. Removed Sources are ignored and obsolete catalog bounds read clamped.",+ "propertyNames": { "$ref": "#/definitions/SourceId" },+ "additionalProperties": { "$ref": "#/definitions/SavedServiceSettings" }+ },+ "service_order": { "type": "array", "uniqueItems": true, "items": { "$ref": "#/definitions/SourceId" }, "description": "Server-owned tool-only Source creation order, skipping ids that no longer name a Source. Read-only; absent config reads as an empty list." },+ "service_vendors": { "type": "array", "items": { "$ref": "#/definitions/ServiceVendor" }, "description": "Absent until S2 activates both service reads and execution. Not a client toggle." },"enabled": { "type": "boolean" },"status": { "$ref": "#/definitions/Status" },"executor_order": {@@ -114,18 +216,7 @@"executor_candidates": {"type": "array","description": "Every eligible executor Source for the tool, in effective order, with its vendor's executor model; a Claude subscription never is one.",- "items": {- "type": "object",- "required": ["source_id", "model_id", "billing", "relay", "price"],- "additionalProperties": false,- "properties": {- "source_id": { "$ref": "#/definitions/SourceId" },- "model_id": { "type": "string", "minLength": 1 },- "billing": { "enum": ["monthly", "metered"] },- "relay": { "type": "boolean", "description": "An API-key Source on an endpoint other than its vendor's own: its price is labelled \"at API price\"." },- "price": { "oneOf": [{ "type": "null" }, { "$ref": "#/definitions/ListPrice" }] }- }- }+ "items": { "oneOf": [{ "$ref": "#/definitions/ModelExecutor" }, { "$ref": "#/definitions/ServiceExecutor" }] }}}},diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex fd132ae0a..72e5d0ddf 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": 17,+ "contract_version": 18,"input_generation": {"mode": "same_run_live_files","external_snapshot": "content_fingerprint_required"diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.jsonindex 07b7fc7e6..3759c95c9 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": 17 },+ "contract_version": { "const": 18 },"outcome": {"enum": ["observed",@@ -150,7 +150,7 @@],"examples": [{- "contract_version": 17,+ "contract_version": 18,"outcome": "observed","reachable": true,"authenticated": "authenticated",@@ -165,7 +165,7 @@]},{- "contract_version": 17,+ "contract_version": 18,"outcome": "authentication_failed","reachable": true,"authenticated": "rejected",@@ -175,7 +175,7 @@"model_metadata": []},{- "contract_version": 17,+ "contract_version": 18,"outcome": "ambiguous","reachable": true,"authenticated": "unknown",@@ -185,7 +185,7 @@"model_metadata": []},{- "contract_version": 17,+ "contract_version": 18,"outcome": "unreachable","reachable": false,"authenticated": "unknown",@@ -195,7 +195,7 @@"model_metadata": []},{- "contract_version": 17,+ "contract_version": 18,"outcome": "adapter_error","reachable": null,"authenticated": "unknown",@@ -205,7 +205,7 @@"model_metadata": []},{- "contract_version": 17,+ "contract_version": 18,"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 f6fac6280..abb8bb2ce 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": 17 },+ "contract_version": { "const": 18 },"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },"channel": { "enum": ["hub", "native_cli"] },"reachable": { "type": "boolean" },@@ -68,10 +68,10 @@}],"examples": [- { "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" }+ { "contract_version": 18, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },+ { "contract_version": 18, "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": 18, "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": 18, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },+ { "contract_version": 18, "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/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.jsonindex 0bf044a27..99f668294 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": 17 },+ "contract_version": { "const": 18 },"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": 17,+ "contract_version": 18,"host_platform": "darwin-arm64","manifest": {"name": "cliproxyapi",diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonindex b5695ded8..8e762b152 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, 17],+ "enum": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],"$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": 17,+ "contract_version": 18,"turn_id": "turn_01k9x2m4","ts": "2026-07-29T06:32:11Z","agent": "claude",@@ -512,7 +512,7 @@"blockers": []},{- "contract_version": 17,+ "contract_version": 18,"turn_id": "turn_01k9x33p","ts": "2026-07-29T06:41:02Z","agent": "opencode",@@ -533,7 +533,7 @@"blockers": []},{- "contract_version": 17,+ "contract_version": 18,"turn_id": "turn_01k9x3zq","ts": "2026-07-29T06:48:20Z","agent": "codex",@@ -553,7 +553,7 @@]},{- "contract_version": 17,+ "contract_version": 18,"turn_id": "turn_01k9x4b7","ts": "2026-07-29T07:02:44Z","agent": "claude",@@ -573,7 +573,7 @@"blockers": []},{- "contract_version": 17,+ "contract_version": 18,"turn_id": "turn_modelmissing01","ts": "2026-09-05T17:31:10Z","agent": "claude",@@ -595,7 +595,7 @@"blockers": []},{- "contract_version": 17,+ "contract_version": 18,"turn_id": "turn_01k9x5ca","ts": "2026-07-29T07:08:00Z","agent": "codex",diff --git a/docs/plans/web-search-services-s1b.md b/docs/plans/web-search-services-s1b.mdnew file mode 100644index 000000000..949ed6928--- /dev/null+++ b/docs/plans/web-search-services-s1b.md@@ -0,0 +1,75 @@+# S1b: settings and dormant Tools read++Source of truth: `web-search-services.md` §3.2, §3.5, §8–9; S1a is merged as+`68a59d11e9dea070f5fe4d231e90d0acbc2aca64`.++## Change contract++- Extend only V2 web-search settings and the Models → Tools read/PUT contracts.+ Preserve model routing, native tool declarations, turn freezing and execution.+- Optional `prefer_native`, Source-keyed partial `services`, and server-written+ `executor_order_kinds` survive a restart. Absence keeps defaults, including+ opt-in for a model vendor without `auto_enroll`. Removed Sources are ignored.+- Loading clamps obsolete catalog bounds in memory without rewriting disk. The+ next authorized write persists the normalized values. Defaults remain absent+ rather than being frozen as explicit user choices.+- PUT merges only supplied Sources/fields under the existing mutation lock;+ null removes an override. Reject invalid current-catalog values atomically.+ Every web-search order save snapshots the resulting settings' Source roles;+ missing Sources have no map entry, missing roles read as model. A damaged+ derived role map warns and loads as absent without discarding consent settings;+ S2 owns interpreting roles at read time, with no dormant test-only helper here.+ Loaded roles for removed Sources are ignored before validation and dropped at+ the next authorized write, including normal Source deletion. Extant retargeted+ Sources retain their saved role. The Tools read skips removed `service_order`+ ids without mutating the saved order; `executor_order` remains as saved.+- Define service candidate/vendor shapes and add model candidates' `kind`.+ One explicit internal activation switch suppresses both service candidates+ and service vendors until S2. No new UI, user toggle, chain or placement rule.+- S1a's v17 was unshipped at branch creation (latest `gh-v3.2.2rc11` carried+ v16). During implementation, `gh-v3.2.2rc12` was tagged with S1a and v17.+ S1b therefore opens v18, advancing all terminal mirrors and retaining v17+ among the readable persisted versions. Recheck the release evidence at close-out.++## Validation++Scenarios: **MH-HOSTED-002** (compatibility) and **MH-HOSTED-004** (Tools read/patch).+Existing hosted-tools tests cover the old settings only. Extend their owner+coverage for defaults/partial values and mixed-order restart persistence,+catalog downgrades without load-time writes, field/source patch isolation and+concurrent edits, atomic validation, order-role snapshots and stale ids. Validate+both the dormant public read and the defined future service variants against+the closed schema. Exercise the pinned rc12 loader against new fields and its+lossy downgrade write. The damaged-map regression fails before the fix and checks+real V2 load, unrelated write, re-enable and restart without losing an opt-out.+Removed-id regressions fail before the fix and cover the Tools projection and+live role-map loading followed by normal Source deletion, preserving survivor+order, retargeted roles and opt-outs.+Run focused tests through `~/.local/bin/hd1-test`, changed-file Ruff, UI test+typechecking (`npm run typecheck:tests`) and UI build.+No paid search, live runtime restart or regression update is part of this lane.++## Delivery++Fresh independent branch from master. Deliver to exact-head Codex/CI gates,+zero unresolved threads and CLEAN; report to the orchestrator, do not merge.+A SHA-bearing Codex no-findings receipt is a pass without a reaction; inspect+receipts directly instead of relying only on a coalesced Watch success event.++## Intentional non-changes++The dormant projection helpers define payloads, not S2's unified candidate chain,+placement or cooldown owner. S2 connects those while enabling the one gate. The+existing model-only Tools price renderer narrows out the new dormant variant;+there is no service renderer or new copy. Free-tier metadata remains null because+the bundled catalog makes no verified free-tier promise. Vendor facts are+structured booleans, so S4 can localize its own copy without backend prose.+Retargeted/retired but extant Sources retain their overrides (especially opt-out)+for when capability returns; the Tools read hides them while incapable, and only+removed Sources are forgotten.++Downgrade through rc12 preserves the whole-tool switch and both orders, but its+next config write drops new fields, including `services.<id>.enabled: false`.+Re-upgrading uses service defaults again: DeepSeek's opt-out must be reapplied+before service execution is enabled. The rc12 fixture records this limitation,+not a cross-version consent guarantee; S2/S6 must carry it into their guidance.diff --git a/docs/plans/web-search-services.md b/docs/plans/web-search-services.mdindex ba637866b..e689d3937 100644--- a/docs/plans/web-search-services.md+++ b/docs/plans/web-search-services.md@@ -134,7 +134,10 @@ The user has an Anthropic API key and a DeepSeek API key, adds Tavily, and changEach save also writes `executor_order_kinds`, a map from each named Source id to the role it had when the orderwas saved (`service` or `model`); a released order has no map, so its entries were all saved as `model`. Themap is what lets a read tell a deliberate placement from a stale one (§4.1).-- Releases before this feature ignore both fields with a warning: the existing loader rule for unknown fields.+- A damaged server-written `executor_order_kinds` map warns and loads as absent, without discarding the+ tool switch, service opt-outs or other saved choices. S2 interprets absent roles as `model` as above.+- Releases before these settings ignore unknown fields with a warning. An older release's config write drops+ those fields, including per-Source opt-outs; see §12. rc12 retains `service_order` but not the three S1b fields.- A settings change applies from the next turn. The turn's first resolution freezes `prefer_native`, the effectivecandidate list (Sources with `services.<id>.enabled: false` kept, last, as `disabled` entries) and each candidate's `results` and `content` in the turntrace's `hosted_tools`, beside the tool set and the executor order (hosted tools §6). Later hop resolutions and every call of the turn read the frozen values.@@ -177,6 +180,9 @@ The user has an Anthropic API key and a DeepSeek API key, adds Tavily, and chang`GET /api/models/hosted-tools` (hosted tools §3.3), for `web_search`:- `prefer_native` (saved, `true` when absent);+- `services`: saved partial overrides for currently search-capable Sources, not effective defaults. Extant+ retargeted or retired Sources are omitted while incapable, but retain their overrides in config for when+ capability returns; removed Sources' overrides are ignored;- `executor_candidates[]` entries gain `kind: "service" | "model"`. A service entry carries `model_id` = thecatalog's service id (for example `tavily/search`), `price` in the existing unit form with unit `search` (its`extra[]` gains the unit `page` and an optional `when: "content"`, so Exa shows "$7 / 千次,正文另加 $1 / 千页": one@@ -761,6 +767,11 @@ Hermetic, against stub vendor servers; no live upstream and no real keys.Removing Sources does not repair a transcript. This matches the existing boundary for downgrades after anauthorized write (`model-hub-upgrade-config-compatibility.md`); release notes say it.++ Settings alone also have a lossy boundary: rc12 loads S1b's unknown settings with warnings, and its next config+ write drops `prefer_native`, `services` and `executor_order_kinds`. The whole-tool switch and both orders+ survive, but a per-Source DeepSeek opt-out does not. Re-upgrading restores service defaults, so that opt-out+ must be reapplied before service execution is enabled. S2/S6's activation and opt-out guidance must state this.2. **No custom endpoints in phase 1.** Search services use the catalog endpoint only, so relays and self-hostedSearXNG wait for a custom-endpoint rule.3. **Settings are per service, not per call.** The model cannot ask for more results or for page content.diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.pyindex 212a62712..32c902b3e 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": 17,+ "contract_version": 18,"error": "feature_disabled",}diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.pyindex 3027b2ed4..c0ff7a2cc 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 = 17+CONTRACT_VERSION = 18MENU_MODEL = "claude-sonnet-4-6"SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"diff --git a/tests/fixtures/model_hub/released_rc12_hosted_tools.py b/tests/fixtures/model_hub/released_rc12_hosted_tools.pynew file mode 100644index 000000000..e92739c3b--- /dev/null+++ b/tests/fixtures/model_hub/released_rc12_hosted_tools.py@@ -0,0 +1,106 @@+"""Unchanged hosted-tool loader from gh-v3.2.2rc12:config/v2_config.py.++Only its imports are supplied here; the unchanged Source-id/model-choice/order+helpers remain shared. This snapshot tests downgrade of optional settings:+rc12 retains tool switches and both orders, but not the new service opt-outs.+"""++import logging+from dataclasses import dataclass+from typing import Any, Mapping, Optional++from config.v2_config import (+ MODEL_HUB_HOSTED_TOOLS,+ MODEL_HUB_SEARCH_TOOLS,+ ModelHubImageModelChoice,+ model_hub_executor_order,+ model_hub_service_order,+)++logger = logging.getLogger(__name__)+++@dataclass(frozen=True)+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; ``service_order`` (``web_search``) is the server-owned automatic order of+ tool-only search Sources; ``default_image`` (``image_generate``, persisted as ``default_model``) is the+ chosen default image model, None for the catalog default. Both are saved values, never resolved ones.+ """++ enabled: bool = True+ executor_order: Optional[tuple[str, ...]] = None+ service_order: Optional[tuple[str, ...]] = None+ default_image: Optional[ModelHubImageModelChoice] = None++ @classmethod+ def from_payload(cls, payload: object, *, tool: str) -> "ModelHubHostedToolConfig":+ """Read one entry; fields it does not know are ignored with a warning, the ones it knows are kept."""++ if not isinstance(payload, dict):+ raise ValueError(f"Config 'model_hub.hosted_tools.{tool}' must be an object")+ 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) - known+ if unknown:+ logger.warning("Config 'model_hub.hosted_tools.%s' ignores unknown fields %s", tool, sorted(unknown))+ enabled = payload.get("enabled", True)+ if not isinstance(enabled, bool):+ raise ValueError(f"Config 'model_hub.hosted_tools.{tool}.enabled' must be a boolean")+ # 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 payload+ has_default = "default_model" in known and "default_model" in payload+ return 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+ ),+ )++ def to_payload(self) -> dict:+ 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+++def _hosted_tools_from_payload(section: Mapping[str, Any]) -> dict[str, ModelHubHostedToolConfig]:+ """Read ``model_hub.hosted_tools`` as an optional feature that degrades on its own.++ Absent means every tool takes its defaults (on). An unknown tool key, or an unknown field inside an entry, is+ ignored with a warning, and the fields the loader knows are kept, so a user's opt-out survives. A broken section+ or entry turns its tools off, with a warning: hosted tools reach third parties and cost money, so damage never+ turns one on. Sources and Agents still load.+ """++ if "hosted_tools" not in section:+ return {}+ payload = section["hosted_tools"]+ # Present but not an object, ``null`` included, is damage, never absence.+ if not isinstance(payload, dict):+ logger.warning("Config 'model_hub.hosted_tools' is not an object; hosted tools are off")+ return {tool: ModelHubHostedToolConfig(enabled=False) for tool in MODEL_HUB_HOSTED_TOOLS}+ tools: dict[str, ModelHubHostedToolConfig] = {}+ for tool, raw in payload.items():+ if tool not in MODEL_HUB_HOSTED_TOOLS:+ logger.warning("Config 'model_hub.hosted_tools' ignores an unknown tool %r", tool)+ continue+ try:+ tools[tool] = ModelHubHostedToolConfig.from_payload(raw, tool=tool)+ except ValueError as exc:+ logger.warning("%s; hosted tool %r is off", exc, tool)+ tools[tool] = ModelHubHostedToolConfig(enabled=False)+ return toolsdiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex fb4a3ccce..f6d6b2df6 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -196,6 +196,10 @@ scenarios:- tests/test_model_hub_hosted_tools_config.py::test_disk_load_with_a_broken_hosted_tools_section_keeps_model_hub- tests/test_model_hub_hosted_tools_config.py::test_released_configs_load_with_every_tool_on_and_stay_without_the_section- tests/test_model_hub_hosted_tools_config.py::test_hosted_tool_settings_round_trip_in_canonical_order+ - tests/test_model_hub_search_settings.py::test_released_order_keeps_missing_kinds_absent_and_ignores_unnamed_entries+ - tests/test_model_hub_search_settings.py::test_damaged_role_map_keeps_opt_out_across_load_write_and_reenable+ - tests/test_model_hub_search_settings.py::test_role_metadata_drops_removed_sources_on_load_and_real_deletion+ - tests/test_model_hub_search_settings.py::test_rc12_loader_preserves_tool_switch_and_orders_but_drops_service_overrides- id: MH-HOSTED-003name: A refusal is routing state with no time limit that applies only under its Source identity and wire stamp; a success is display history that never replaces it; a clear is persisted before it takes effectstatus: covered@@ -230,6 +234,9 @@ scenarios:- tests/test_model_hub_hosted_tools_resolution.py::test_a_relay_is_any_endpoint_but_the_vendors_own_by_the_engines_endpoint_identity- tests/test_model_hub_hosted_tools_resolution.py::test_the_tools_read_states_saved_and_effective_values_and_what_real_use_showed- tests/test_model_hub_hosted_tools_resolution.py::test_a_put_changes_only_the_fields_it_names+ - tests/test_model_hub_search_settings.py::test_put_merges_absent_sources_fields_and_null_resets+ - tests/test_model_hub_search_settings.py::test_http_tools_put_and_read_preserve_patch_and_dormant_contract+ - tests/test_model_hub_search_settings.py::test_service_order_read_skips_removed_sources_without_rewriting_saved_order- tests/test_model_hub_hosted_tools_resolution.py::test_a_put_refuses_what_the_contract_forbids- tests/test_model_hub_hosted_tools_resolution.py::test_the_latest_success_is_the_newest_in_time_not_in_text- tests/test_model_hub_hosted_tools_resolution.py::test_the_latest_success_is_the_newest_one_whose_source_is_still_the_samediff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 8536ff7a9..d58056e0f 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -1062,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"] == 17+ assert runtime["contract_version"] == 18assert runtime["status"]["health"] == "ok"_assert_valid("runtime-dependency.schema.json", runtime)@@ -1369,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": 17, "status": {"health": "ok"}}+ return {"contract_version": 18, "status": {"health": "ok"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1386,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": 17, "status": {"health": "not_started"}}+ return {"contract_version": 18, "status": {"health": "not_started"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1403,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": 17, "status": {"health": "installing"}}+ return {"contract_version": 18, "status": {"health": "installing"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1421,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": 17,+ "contract_version": 18,"changed": True,"status": {"health": "not_started", "verified": True},}@@ -4873,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": 17,+ "contract_version": 18,"agent": {"backend": "codex","mode": "hub",@@ -10140,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"] == 17+ assert runtime["contract_version"] == 18_assert_valid("runtime-dependency.schema.json", runtime)diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex cab2a4648..190164fea 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -97,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"] == 17+ assert schema["properties"]["contract_version"]["const"] == 18assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(member.value for member in ObservationOutcome)@@ -121,7 +121,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():def payload(observation: SourceObservation) -> dict:return {- "contract_version": 17,+ "contract_version": 18,"outcome": observation.outcome.value,"reachable": observation.reachable,"authenticated": (@@ -737,7 +737,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():route_refusal = {"ok": False,- "contract_version": 17,+ "contract_version": 18,"error": "source_in_route_chain","detail": "modelHub.errors.source_in_route_chain","would_remove_hops": [hop],@@ -753,7 +753,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():}candidate_refusal = {"ok": False,- "contract_version": 17,+ "contract_version": 18,"error": "candidate_suppliers_changed","detail": "modelHub.errors.candidate_suppliers_changed","changed": {@@ -837,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"] == 17+ assert registry["contract_version"] == 18ids = [entry["id"] for entry in registry["entries"]]assert idsassert len(ids) == len(set(ids))@@ -974,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, 17],- "expected": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],+ "values": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],+ "expected": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],} in result["findings"]@@ -1286,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": 17,+ "contract_version": 18,"backend": "claude","model_id": "claude-opus-4-6","manual_override": None,diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex f19c0a542..0d058b0cc 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -5580,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": 17,+ "contract_version": 18,"turn_id": "turn_released_rejection","ts": NOW.isoformat(),"agent": "vibey",@@ -7056,7 +7056,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(_assert_valid("observation-result.schema.json",{- "contract_version": 17,+ "contract_version": 18,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -9590,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": 17,+ "contract_version": 18,"backend": "codex","channel": "native_cli","reachable": True,diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.pyindex d2a421d4b..e15421fc0 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": 17,+ "contract_version": 18,"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": 17, "provenance": record}+ assert response.get_json() == {"ok": True, "contract_version": 18, "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 fecd986b5..a13285dfb 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": 17,+ "contract_version": 18,"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": 17,+ "contract_version": 18,"outcome": "adapter_error","reachable": None,"authenticated": "unknown",diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex c4d8b6f6a..7e3981a39 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -1367,7 +1367,7 @@ def test_manifest_resolution_drives_admission_persistence_and_schema(installer=manager,state_store=EngineStateStore(tmp_path / "state"),)- projected = {"contract_version": 17, **supervisor.status()}+ projected = {"contract_version": 18, **supervisor.status()}schema = json.loads(Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(encoding="utf-8"diff --git a/tests/test_model_hub_search_settings.py b/tests/test_model_hub_search_settings.pynew file mode 100644index 000000000..731a9904a--- /dev/null+++ b/tests/test_model_hub_search_settings.py@@ -0,0 +1,420 @@+"""S1b owner coverage: persistent settings/patches and the dormant Tools read.++The pre-service hosted-tools tests cannot exercise catalog-dependent defaults,+clamping, role snapshots or Source-keyed patches. These tests use the real V2+store/mutation owner; no provider, credential or live runtime is contacted.+Scenarios: MH-HOSTED-002 (compatibility), MH-HOSTED-004 (Tools read/patch).+"""++from __future__ import annotations++import asyncio+import copy+import json+import runpy+from dataclasses import replace+from pathlib import Path++import pytest+from jsonschema import Draft7Validator, ValidationError++from config import paths+from config.v2_config import ModelHubConfig, ModelHubSourceStateConfig, V2Config, hosted_tool_setting+from core.handlers.model_hub import hosted_tools+from core.handlers.model_hub.service import ModelHubError, V2ModelHubConfigStore+from core.services.settings import default_config+from tests.test_model_hub_api import _api_response_registry, _service+from tests.test_model_hub_hosted_tools_config import SOURCE+from vibe import api+from vibe.model_hub_runtime import api_key_vendors++TAVILY = "src_tavily01"+EXA = "src_exa00001"+DEEPSEEK = "src_deepseek1"+MODEL = SOURCE["id"]+GONE = "src_gone0001"+CONTRACT = "model-hub/hosted-tools-status.schema.json"+++def _source(source_id, vendor, protocol="search"):+ return {**SOURCE, "id": source_id, "vendor": vendor, "display_name": vendor,+ "protocol": protocol, "models": [], "credential_ref": f"cred_{source_id}"}+++def _config(web=None):+ return ModelHubConfig.from_payload({+ "sources": [SOURCE, _source(TAVILY, "tavily"), _source(EXA, "exa"),+ _source(DEEPSEEK, "deepseek", "openai_chat")],+ "hosted_tools": {"web_search": web or {}},+ })+++def _disk_service(tmp_path, config):+ path = paths.get_config_path()+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)+ payload["model_hub"] = config.to_payload()+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(payload), encoding="utf-8")+ service, _, adapter = _service(tmp_path)+ service.store = V2ModelHubConfigStore()+ return service, path, adapter+++def _web(service):+ status = service.hosted_tools_status()["hosted_tools"]+ Draft7Validator({"$ref": CONTRACT}, registry=_api_response_registry()).validate(status)+ return next(tool for tool in status["tools"] if tool["name"] == "web_search")+++def _catalog_change(monkeypatch, vendor_id, **changes):+ original = api_key_vendors.api_key_vendor_entry+ vendor = original(vendor_id)+ service = copy.deepcopy(vendor.search)+ service.update(changes)+ monkeypatch.setattr(api_key_vendors, "api_key_vendor_entry", lambda key: replace(vendor, search=service)+ if key == vendor_id else original(key))+++def test_defaults_follow_catalog_without_freezing_overrides(monkeypatch):+ """Default counts and opt-in evolve with catalog facts, not saved effective settings."""+ config = _config()+ setting = hosted_tool_setting(config, "web_search")+ assert setting.prefer_native is True+ assert setting.services == {} and setting.executor_order_kinds is None+ for source in config.sources[1:]:+ assert hosted_tools.search_service_settings(setting, source) == {"results": 5, "content": False, "enabled": True}+ _catalog_change(monkeypatch, "deepseek", auto_enroll=False, limits={"results_max": 3})+ assert hosted_tools.search_service_settings(setting, config.sources[-1]) == {+ "results": 3, "content": False, "enabled": False,+ }+ assert setting.to_payload() == {"enabled": True}+ # A subscription or relay cannot inherit an official API's search permission.+ assert hosted_tools.search_service_settings(setting, replace(config.sources[-1], kind="subscription")) is None+ assert hosted_tools.search_service_settings(setting, replace(config.sources[-1], base_url="https://relay.invalid/v1")) is None+++async def test_mixed_order_and_role_snapshot_survive_real_v2_restart(tmp_path):+ """An explicit model-before-service placement and role map are saved, not recomputed on load."""+ service, path, _ = _disk_service(tmp_path, _config({"service_order": [TAVILY, EXA]}))+ order = [MODEL, TAVILY, GONE, DEEPSEEK, EXA]+ await service.set_hosted_tool("web_search", {+ "prefer_native": False, "executor_order": order,+ "services": {TAVILY: {"results": 7, "content": True}, DEEPSEEK: {"enabled": False}},+ })+ saved = json.loads(path.read_text())["model_hub"]["hosted_tools"]["web_search"]+ assert saved["executor_order"] == order+ assert saved["executor_order_kinds"] == {MODEL: "model", TAVILY: "service", DEEPSEEK: "service", EXA: "service"}+ # Disabled DeepSeek has no existing model executor; it remains a disabled service row (S2).+ assert GONE not in saved["executor_order_kinds"]+ restarted = V2ModelHubConfigStore().load()+ assert restarted.hosted_tools["web_search"].to_payload() == saved+ assert restarted.hosted_tools["web_search"].service_order == (TAVILY, EXA)+ assert not restarted.hosted_tools["web_search"].prefer_native+ assert _web(service)["executor_order"] == order+ # Dormancy keeps actual model execution unchanged, despite the saved future role map/order.+ assert _web(service)["effective_order"] == [MODEL]+ await service.set_hosted_tool("web_search", {"executor_order": None})+ reset = V2ModelHubConfigStore().load().hosted_tools["web_search"].to_payload()+ assert "executor_order" not in reset and "executor_order_kinds" not in reset+ assert reset["service_order"] == [TAVILY, EXA]+++def test_released_order_keeps_missing_kinds_absent_and_ignores_unnamed_entries():+ """MH-HOSTED-002: persistence does not invent roles; S2 owns interpreting absent roles as model."""+ setting = _config({"executor_order": [DEEPSEEK, MODEL]}).hosted_tools["web_search"]+ assert setting.executor_order == (DEEPSEEK, MODEL)+ assert setting.executor_order_kinds is None and "executor_order_kinds" not in setting.to_payload()+ setting = replace(setting, executor_order_kinds={DEEPSEEK: "service", EXA: "service"})+ assert setting.to_payload()["executor_order_kinds"] == {DEEPSEEK: "service"}+ loaded = _config({"executor_order": [MODEL], "executor_order_kinds": {EXA: []}}).hosted_tools["web_search"]+ assert loaded.enabled and loaded.executor_order == (MODEL,) and loaded.executor_order_kinds == {}+++async def test_order_save_uses_the_resulting_service_opt_in_and_preserves_model_role(tmp_path, monkeypatch):+ """A future model vendor's search opt-out keeps its existing executor; a combined save snapshots the new role."""+ catalog_service = copy.deepcopy(api_key_vendors.api_key_vendor_entry("deepseek").search)+ catalog_service["auto_enroll"] = False+ original = api_key_vendors.api_key_vendor_entry+ vendor = original("xai")+ monkeypatch.setattr(api_key_vendors, "api_key_vendor_entry", lambda key: replace(vendor, search=catalog_service)+ if key == "xai" else original(key))+ service, _, _ = _disk_service(tmp_path, _config())+ await service.set_hosted_tool("web_search", {"executor_order": [MODEL]})+ assert service.store.load().hosted_tools["web_search"].executor_order_kinds == {MODEL: "model"}+ await service.set_hosted_tool("web_search", {"executor_order": [MODEL], "services": {MODEL: {"enabled": True}}})+ assert V2ModelHubConfigStore().load().hosted_tools["web_search"].executor_order_kinds == {MODEL: "service"}+ await service.set_hosted_tool("web_search", {"executor_order": [MODEL], "services": {MODEL: {"enabled": None}}})+ assert V2ModelHubConfigStore().load().hosted_tools["web_search"].executor_order_kinds == {MODEL: "model"}+++def test_retargeted_source_keeps_its_opt_out_until_search_capability_returns(tmp_path):+ """MH-HOSTED-004: the read hides ineligible overrides, but a real V2 save must keep consent."""+ config = _config({"services": {DEEPSEEK: {"enabled": False}}})+ config.sources[-1].base_url = "https://relay.invalid/v1"+ service, _, _ = _disk_service(tmp_path, config)+ loaded = service.store.load()+ assert hosted_tools.search_service_settings(loaded.hosted_tools["web_search"], loaded.sources[-1]) is None+ assert loaded.hosted_tools["web_search"].services[DEEPSEEK].enabled is False+ assert _web(service)["services"] == {}+ loaded.sources[-1].base_url = None+ service.store.save(loaded)+ restored = V2ModelHubConfigStore().load()+ assert hosted_tools.search_service_settings(restored.hosted_tools["web_search"], restored.sources[-1])["enabled"] is False+ assert _web(service)["services"] == {DEEPSEEK: {"enabled": False}}+++async def test_catalog_downgrade_clamps_on_load_without_rewriting_until_next_save(tmp_path, monkeypatch):+ """A catalog maximum/content removal cannot disable the tool or silently edit disk on read."""+ service, path, _ = _disk_service(tmp_path, _config({"services": {TAVILY: {"results": 20, "content": True}}}))+ original = path.read_bytes()+ result_mapping = dict(api_key_vendors.api_key_vendor_entry("tavily").search["result"])+ result_mapping.pop("content")+ _catalog_change(monkeypatch, "tavily", limits={"results_max": 2}, result=result_mapping)+ loaded = V2Config.load().model_hub.hosted_tools["web_search"]+ assert loaded.enabled+ assert loaded.services[TAVILY].to_payload() == {"results": 2, "content": False}+ assert _web(service)["services"][TAVILY] == {"results": 2, "content": False}+ assert path.read_bytes() == original+ await service.set_hosted_tool("web_search", {"prefer_native": False})+ written = json.loads(path.read_text())["model_hub"]["hosted_tools"]["web_search"]+ assert written["services"][TAVILY] == {"results": 2, "content": False}+ assert V2ModelHubConfigStore().load().hosted_tools["web_search"].to_payload() == written+++async def test_put_merges_absent_sources_fields_and_null_resets(tmp_path):+ """MH-HOSTED-004: partial clients cannot echo defaults over other clients' saved choices."""+ service, path, _ = _disk_service(tmp_path, _config({"services": {+ TAVILY: {"results": 8, "content": True, "enabled": False}, EXA: {"content": True},+ }}))+ await service.set_hosted_tool("web_search", {"services": {TAVILY: {"results": 9}}})+ assert _web(service)["services"] == {+ TAVILY: {"results": 9, "content": True, "enabled": False}, EXA: {"content": True},+ }+ await service.set_hosted_tool("web_search", {"services": {TAVILY: {"content": None}, EXA: None}})+ assert _web(service)["services"] == {TAVILY: {"results": 9, "enabled": False}}+ await service.set_hosted_tool("web_search", {"services": {TAVILY: {"results": None, "enabled": None}}})+ assert _web(service)["services"] == {}+ before = path.read_bytes()+ await service.set_hosted_tool("web_search", {"services": {}})+ assert path.read_bytes() == before+ assert V2ModelHubConfigStore().load().hosted_tools["web_search"].services == {}+++async def test_concurrent_different_fields_and_sources_are_not_lost(tmp_path):+ """The controller mutation owner loads the latest config after acquiring its lock."""+ service, _, _ = _disk_service(tmp_path, _config())+ async with service._mutation_lock:+ writes = [asyncio.create_task(service.set_hosted_tool("web_search", patch)) for patch in (+ {"services": {TAVILY: {"results": 11}}}, {"services": {TAVILY: {"content": True}}},+ {"services": {EXA: {"enabled": False}}}, {"prefer_native": False},+ )]+ await asyncio.sleep(0)+ assert all(not task.done() for task in writes)+ await asyncio.gather(*writes)+ restarted = V2ModelHubConfigStore().load().hosted_tools["web_search"]+ assert restarted.to_payload() == {"enabled": True, "prefer_native": False, "services": {+ TAVILY: {"results": 11, "content": True}, EXA: {"enabled": False},+ }}++[email protected]("tool,patch", [+ ("web_search", {"prefer_native": None}), ("web_search", {"prefer_native": 1}),+ ("web_search", {"services": None}), ("web_search", {"service_order": []}),+ ("web_search", {"executor_order_kinds": {TAVILY: "model"}}),+ ("web_search", {"services": {TAVILY: {"results": 21}}}),+ ("web_search", {"services": {TAVILY: {"results": True}}}),+ ("web_search", {"services": {TAVILY: {"results": 0}}}),+ ("web_search", {"services": {TAVILY: {"content": 1}}}),+ ("web_search", {"services": {TAVILY: {"unknown": True}}}),+ ("web_search", {"services": {GONE: {"results": 5}}}),+ ("web_search", {"services": {MODEL: {"enabled": True}}}),+ ("x_search", {"prefer_native": False}), ("image_generate", {"services": {}}),+])+async def test_invalid_patches_are_atomic(tmp_path, tool, patch):+ service, path, _ = _disk_service(tmp_path, _config())+ before = path.read_bytes()+ with pytest.raises(ModelHubError) as error:+ await service.set_hosted_tool(tool, {"enabled": False, **patch})+ assert (error.value.status, error.value.code) == (400, "invalid_parameter")+ assert path.read_bytes() == before+++async def test_content_write_requires_catalog_page_text(tmp_path, monkeypatch):+ service, path, _ = _disk_service(tmp_path, _config())+ result = dict(api_key_vendors.api_key_vendor_entry("tavily").search["result"])+ result.pop("content")+ _catalog_change(monkeypatch, "tavily", result=result)+ before = path.read_bytes()+ with pytest.raises(ModelHubError):+ await service.set_hosted_tool("web_search", {"services": {TAVILY: {"content": True}}})+ assert path.read_bytes() == before+ await service.set_hosted_tool("web_search", {"services": {TAVILY: {"content": False}}})+ assert _web(service)["services"][TAVILY] == {"content": False}+++def test_service_order_read_skips_removed_sources_without_rewriting_saved_order(tmp_path):+ """MH-HOSTED-004: a retained stale id is never presented as an automatic search Source."""+ order = [EXA, GONE, TAVILY]+ service, path, _ = _disk_service(tmp_path, _config({"service_order": order}))+ before = path.read_bytes()+ assert _web(service)["service_order"] == [EXA, TAVILY]+ assert V2ModelHubConfigStore().load().hosted_tools["web_search"].service_order == tuple(order)+ assert path.read_bytes() == before++[email protected]("stale_role", ["service", []])+async def test_role_metadata_drops_removed_sources_on_load_and_real_deletion(tmp_path, stale_role):+ """MH-HOSTED-002: removed roles are ignored before validation; normal deletion saves the same invariant."""+ order = [GONE, TAVILY, DEEPSEEK, MODEL]+ live_roles = {TAVILY: "service", DEEPSEEK: "service", MODEL: "model"}+ config = _config({"executor_order": order, "executor_order_kinds": live_roles,+ "service_order": [TAVILY, EXA], "services": {DEEPSEEK: {"enabled": False}}})+ config.sources[-1].base_url = "https://relay.invalid/v1" # Retargeting is not deletion: keep its saved role.+ service, path, _ = _disk_service(tmp_path, config)+ raw = json.loads(path.read_text())+ raw["model_hub"]["hosted_tools"]["web_search"]["executor_order_kinds"][GONE] = stale_role+ path.write_text(json.dumps(raw), encoding="utf-8")+ before = path.read_bytes()+ loaded = V2ModelHubConfigStore().load().hosted_tools["web_search"]+ assert loaded.enabled and loaded.executor_order_kinds == live_roles+ assert loaded.executor_order == tuple(order)+ assert path.read_bytes() == before+ await service.delete_source(TAVILY)+ written = json.loads(path.read_text())["model_hub"]["hosted_tools"]["web_search"]+ assert written["executor_order"] == order+ assert written["executor_order_kinds"] == {DEEPSEEK: "service", MODEL: "model"}+ assert written["services"] == {DEEPSEEK: {"enabled": False}}+ assert written["service_order"] == [EXA]+ assert V2ModelHubConfigStore().load().hosted_tools["web_search"].to_payload() == written+++def test_removed_source_settings_are_ignored_before_validation():+ config = _config({"services": {GONE: "obsolete", TAVILY: {"results": 6}}})+ assert config.hosted_tools["web_search"].enabled+ assert config.hosted_tools["web_search"].to_payload()["services"] == {TAVILY: {"results": 6}}++[email protected]("field,value", [("prefer_native", None), ("services", None),+ ("services", {TAVILY: {"content": None}})])+def test_damaged_optional_settings_disable_only_web_search(field, value):+ config = _config({"executor_order": [TAVILY], field: value})+ assert not config.hosted_tools["web_search"].enabled+ assert len(config.sources) == 4+ assert hosted_tool_setting(config, "x_search").enabled++[email protected]("damaged", [None, [], {DEEPSEEK: []}, {DEEPSEEK: "future"}])[email protected]("enabled", [True, False])+async def test_damaged_role_map_keeps_opt_out_across_load_write_and_reenable(tmp_path, caplog, damaged, enabled):+ """MH-HOSTED-002: damaged derived metadata must not erase consent on the next real V2 write."""+ expected = {"enabled": enabled, "prefer_native": False, "executor_order": [DEEPSEEK, MODEL],+ "service_order": [TAVILY], "services": {DEEPSEEK: {"enabled": False}}}+ service, path, _ = _disk_service(tmp_path, _config(expected))+ payload = json.loads(path.read_text())+ payload["model_hub"]["hosted_tools"]["web_search"]["executor_order_kinds"] = damaged+ path.write_text(json.dumps(payload), encoding="utf-8")+ before = path.read_bytes()+ loaded = V2ModelHubConfigStore().load().hosted_tools["web_search"]+ assert loaded.to_payload() == expected+ assert "executor_order_kinds" in caplog.text and "ignoring damaged" in caplog.text+ assert path.read_bytes() == before+ await service.set_hosted_tool("x_search", {"enabled": False})+ assert V2ModelHubConfigStore().load().hosted_tools["web_search"].to_payload() == expected+ await service.set_hosted_tool("web_search", {"enabled": True})+ restarted = V2ModelHubConfigStore().load()+ setting = restarted.hosted_tools["web_search"]+ assert setting.to_payload() == {**expected, "enabled": True}+ assert hosted_tools.search_service_settings(setting, restarted.sources[-1])["enabled"] is False+++async def test_dormant_read_and_future_service_variant_validate_without_paid_calls(tmp_path, monkeypatch):+ """One switch gates both read additions; defined service payloads do not require execution/UI activation."""+ service, _, _ = _disk_service(tmp_path, _config({"services": {DEEPSEEK: {"enabled": False}}}))+ dormant = _web(service)+ assert dormant["prefer_native"] is True+ assert "service_vendors" not in dormant+ assert {row["kind"] for row in dormant["executor_candidates"]} == {"model"}+ # Check the prepared projection only. S2's ordering/chain/cooldown semantics are intentionally not exercised.+ config = service.store.load()+ config.sources[-1].billing = "monthly" # Model billing does not make the separate search API included.+ config.sources[2].state = ModelHubSourceStateConfig(+ status="needs_action", detail_key="models.source.needs_action.balance_exhausted")+ service.store.save(config)+ service._search_reenable_trials.add(EXA)+ monkeypatch.setattr(hosted_tools, "SEARCH_SERVICES_ACTIVE", True)+ visible = _web(service)+ exa = next(row for row in visible["executor_candidates"] if row["source_id"] == EXA)+ assert exa == {+ "kind": "service", "source_id": EXA, "model_id": "exa/search", "billing": "metered", "relay": False,+ "price": {"unit": "search", "usd_per_1k": 7, "extra": [{"unit": "page", "usd_per_1k": 1, "when": "content"}],+ "as_of": "2026-10-19", "url": "https://exa.ai/blog/exa-3"},+ "settings": {"results": 5, "content": False, "enabled": True},+ "state": {"status": "needs_action", "retry_at": None, "detail_key": "models.source.needs_action.balance_exhausted"},+ "trial_pending": True, "cooldown_until": None,+ }+ deepseek_candidate = next(row for row in visible["executor_candidates"] if row["source_id"] == DEEPSEEK)+ assert deepseek_candidate["billing"] == "metered" and not deepseek_candidate["settings"]["enabled"]+ assert service.store.load().sources[-1].billing == "monthly"+ deepseek = next(vendor for vendor in visible["service_vendors"] if vendor["id"] == "deepseek")+ assert deepseek["source_ids"] == [DEEPSEEK] and deepseek["facts"]["auto_enroll"] is True+ assert deepseek["free_tier"] is None+ assert next(vendor for vendor in visible["service_vendors"] if vendor["id"] == "exa")["content_changes_price"]+ validator = Draft7Validator({"$ref": CONTRACT + "#/definitions/ServiceExecutor"}, registry=_api_response_registry())+ for changed in ({"kind": "model"}, {"billing": "monthly"}, {"settings": {"results": 5}}, {"trial_pending": None}):+ with pytest.raises(ValidationError):+ validator.validate({**exa, **changed})+++def test_http_tools_put_and_read_preserve_patch_and_dormant_contract(tmp_path, monkeypatch):+ """MH-HOSTED-004: the public route accepts new fields and returns a valid dormant envelope."""+ from tests.test_model_hub_api import _as_ui_client+ from tests.ui_server_test_helpers import csrf_headers, save_config+ from vibe import ui_server++ save_config(tmp_path)+ service, store, _ = _service(tmp_path)+ store.config = _config()+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: _as_ui_client(service))+ client = ui_server.app.test_client()+ origin = "http://127.0.0.1:15131"+ response = client.put(+ "/api/models/hosted-tools/web_search", base_url=origin, headers=csrf_headers(client, origin),+ json={"prefer_native": False, "services": {TAVILY: {"results": 7, "content": True}}},+ )+ assert response.status_code == 200+ written = response.get_json()+ response = client.get("/api/models/hosted-tools", base_url=origin)+ assert response.status_code == 200 and response.get_json() == written+ Draft7Validator({"$ref": "model-hub/api-response.schema.json#/definitions/HostedToolsResponse"},+ registry=_api_response_registry()).validate(written)+ web = written["hosted_tools"]["tools"][0]+ assert web["prefer_native"] is False and web["services"] == {TAVILY: {"results": 7, "content": True}}+ assert "service_vendors" not in web and all(row["kind"] == "model" for row in web["executor_candidates"])+++def test_rc12_loader_preserves_tool_switch_and_orders_but_drops_service_overrides(caplog):+ """MH-HOSTED-002: rc12 keeps its known choices, but a downgrade write cannot retain new service opt-outs."""+ released = runpy.run_path(str(Path(__file__).parent / "fixtures/model_hub/released_rc12_hosted_tools.py"))+ section = _config({"enabled": False, "prefer_native": False, "executor_order": [MODEL, DEEPSEEK],+ "executor_order_kinds": {MODEL: "model", DEEPSEEK: "service"},+ "services": {DEEPSEEK: {"enabled": False}}, "service_order": [TAVILY]}).to_payload()+ loaded = released["_hosted_tools_from_payload"](section)+ written = loaded["web_search"].to_payload()+ assert written == {"enabled": False, "executor_order": [MODEL, DEEPSEEK], "service_order": [TAVILY]}+ assert all(field in caplog.text for field in ("prefer_native", "services", "executor_order_kinds"))+ assert "service_order" not in caplog.text+ section["hosted_tools"]["web_search"] = written+ upgraded = ModelHubConfig.from_payload(section)+ setting = upgraded.hosted_tools["web_search"]+ assert not setting.enabled and setting.services == {}+ assert hosted_tools.search_service_settings(setting, upgraded.sources[-1])["enabled"] is Truediff --git a/tests/test_model_hub_vibey_contract_matrix.py b/tests/test_model_hub_vibey_contract_matrix.pyindex b89fb9f85..47d447838 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": 17, "backend": "claude", "channel": "native_cli", "reachable": True,+ "contract_version": 18, "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": 17, "backend": "vibey", "model_id": "fixture-model",+ "contract_version": 18, "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": 17, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z",+ "contract_version": 18, "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/ui/e2e/chat-interactions/interactions.spec.ts b/ui/e2e/chat-interactions/interactions.spec.tsindex 5cd5f201b..c9923c587 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: 17, turn_id: TURN, agent: 'codex', requested_model_id: 'fixture-model',+ contract_version: 18, 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 e07f99d0f..4e8059448 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: 17, backend, model_id, route_origin: origins[index],+ contract_version: 18, 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: 17,+ contract_version: 18,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 06158443f..50ae65c3e 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: 17, backend, model_id: modelId,+ contract_version: 18, 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 42bdf5cac..1ef1c0b9a 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: 17, error: 'source_in_route_chain', ...plan });+ expect(await refused.json()).toMatchObject({ ok: false, contract_version: 18, 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 b6fc7222a..3a55b208f 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: 17, enabled: true, host_platform: 'linux',+ contract_version: 18, 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 4fef97275..e5189d7f4 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: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'});+ const chain=(b:string,hs=saved[b])=>({contract_version:18,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: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/runtime/status')return answer({ok:true,runtime:{contract_version:18,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 580a1a77b..ad69c2e8c 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: 17,+ contract_version: 18,enabled: true,host_platform: 'darwin',manifest: {diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.tsindex a66628e32..8a79120cd 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: 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('**/api/models/runtime/status', (route) => route.fulfill({ json: { ok: true, runtime: { contract_version: 18, 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 e4f88f484..38b480414 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: 17,+ contract_version: 18,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 6f4b3b101..7d4d88b7e 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: 17, backend: 'claude', model_id: 'opus-5',+ contract_version: 18, 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: 17, backend: 'claude', model_id: 'opus-5',+ contract_version: 18, 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 d7a2e0dcf..d4fe358c8 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: 17, backend: 'vibey', model_id: modelId,+ contract_version: 18, 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 25f02ea5a..524939494 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: 17,+ contract_version: 18,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 82a6083e2..b0af8ce2c 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: 17,+ contract_version: 18,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/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex 97f4bd09b..14a76303e 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: 17,+ contract_version: 18,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: 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>);+ 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: 18, 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: 17,+ contract_version: 18,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: 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>);+ 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: 18, 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: 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>);+ 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: 18, 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: 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>);+ 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: 18, 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/BackendSupplyModeCard.test.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsxindex b51cca36a..4f6169f0d 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: 17,+ contract_version: 18,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/RouteChainDialog.directEdit.test.tsx b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsxindex a1598f4df..aaf3e0bbd 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: 17, backend, model_id: 'gpt-test', route_origin: routeOrigin,+ contract_version: 18, 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 548af086d..60f011922 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: 17,+ contract_version: 18,backend: "claude",model_id: "opus-5",current: { source_id: "src_b", model_id: "opus-5" },diff --git a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx b/ui/src/components/settings/models/RouteRecordedTurn.test.tsxindex 83a280612..a81d1811a 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: 17, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',+ contract_version: 18, 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 79fb6002d..8c687b82e 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: 17,+ contract_version: 18,...(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 25e8b3591..d53c75b83 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: 17,+ contract_version: 18,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: 17,+ contract_version: 18,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: 17,+ contract_version: 18,backend: 'claude',model_id: routedModelId,current: { source_id: retainedSource.id, model_id: routedModelId },@@ -252,7 +252,7 @@ const routedImpact = {const unused = { latest_ok: null, verified: [], refused: [] };const hostedToolsStatus: HostedToolsStatus = {tools: [- { name: 'web_search', enabled: true, status: unused, executor_order: null, effective_order: [], executor_candidates: [] },+ { name: 'web_search', prefer_native: true, services: {}, service_order: [], enabled: true, status: unused, executor_order: null, effective_order: [], executor_candidates: [] },{ name: 'x_search', enabled: true, status: unused, executor_order: null, effective_order: [], executor_candidates: [] },{ name: 'image_generate', enabled: true, status: unused, default_model: null, effective_default: null, models: [], image_offered_by: [] },],diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsxindex 8348a3ab2..9e5b492a9 100644--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx@@ -1461,7 +1461,7 @@ describe('SourceDetailPanel hosted-tool capability chips', () => {const status = (): HostedToolsStatus => ({tools: [// model-b runs web search but refused a replay of its results; model-a refused nothing.- { name: 'web_search', enabled: true, status: run([ok('model-a'), ok('model-b')], [refused('model-b', 'replay')]), executor_order: null, effective_order: [], executor_candidates: [] },+ { name: 'web_search', prefer_native: true, services: {}, service_order: [], enabled: true, status: run([ok('model-a'), ok('model-b')], [refused('model-b', 'replay')]), executor_order: null, effective_order: [], executor_candidates: [] },// A later refusal on a pair that once ran the tool: the refusal is what routes.{ name: 'x_search', enabled: true, status: run([ok('model-a', '2026-10-10T08:00:00Z')], [refused('model-a')]), executor_order: null, effective_order: [], executor_candidates: [] },{ name: 'image_generate', enabled: true, status: run([], []), default_model: null, effective_default: null, models: [], image_offered_by: [] },diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.tsindex d1802b877..34c26fc20 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: 17,+ contract_version: 18,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: 17,+ contract_version: 18,backend: 'claude',model_id: 'model-a',current: { source_id: current, model_id: 'model-a' },diff --git a/ui/src/components/settings/models/ToolsTab.test.tsx b/ui/src/components/settings/models/ToolsTab.test.tsxindex 0ddd4da57..8dc8ffe42 100644--- a/ui/src/components/settings/models/ToolsTab.test.tsx+++ b/ui/src/components/settings/models/ToolsTab.test.tsx@@ -16,6 +16,7 @@ import { readyRegion } from './regionRead';import { ToolsTab } from './ToolsTab';import type {HostedExecutorCandidate,+ HostedModelExecutorCandidate,HostedImageModel,HostedImageToolStatus,HostedRefusal,@@ -63,7 +64,8 @@ const refusal = (sourceId: string, modelId: string, at: string, aspect: HostedResource_id: sourceId, model_id: modelId, aspect, at, reason: '400 unsupported_tool_type',});-const candidate = (sourceId: string, modelId: string, over: Partial<HostedExecutorCandidate> = {}): HostedExecutorCandidate => ({+const candidate = (sourceId: string, modelId: string, over: Partial<HostedModelExecutorCandidate> = {}): HostedModelExecutorCandidate => ({+ kind: 'model',source_id: sourceId,model_id: modelId,billing: SOURCES.find((entry) => entry.id === sourceId)?.billing ?? 'metered',@@ -72,15 +74,17 @@ const candidate = (sourceId: string, modelId: string, over: Partial<HostedExecut...over,});-const search = (name: 'web_search' | 'x_search', over: Partial<HostedSearchToolStatus> = {}): HostedSearchToolStatus => ({- name,- enabled: true,- status: run(),- executor_order: null,- effective_order: (over.executor_candidates ?? []).map((entry) => entry.source_id),- executor_candidates: [],- ...over,-});+const search = (name: 'web_search' | 'x_search', over: Partial<HostedSearchToolStatus> = {}): HostedSearchToolStatus => {+ const common = {+ enabled: true, status: run(), executor_order: null,+ effective_order: (over.executor_candidates ?? []).map((entry) => entry.source_id),+ executor_candidates: [], ...over,+ };+ const candidates: HostedExecutorCandidate[] = common.executor_candidates;+ return name === 'web_search'+ ? { prefer_native: true, services: {}, service_order: [], ...common, name }+ : { ...common, name, executor_candidates: candidates.filter((entry): entry is HostedModelExecutorCandidate => entry.kind === 'model') };+};const image = (over: Partial<HostedImageToolStatus> = {}): HostedImageToolStatus => ({name: 'image_generate',diff --git a/ui/src/components/settings/models/ToolsTab.tsx b/ui/src/components/settings/models/ToolsTab.tsxindex 3d603d5f6..50a86a0be 100644--- a/ui/src/components/settings/models/ToolsTab.tsx+++ b/ui/src/components/settings/models/ToolsTab.tsx@@ -132,6 +132,8 @@ const StatusLines: React.FC<{ tool: HostedToolStatus; summary: RefusalSummary; l/** What one executor call costs: included on a subscription, else the overlay's list price; unknown is never zero. */const ExecutorPrice: React.FC<{ candidate: HostedExecutorCandidate }> = ({ candidate }) => {const { t } = useTranslation();+ // Service variants are a dormant contract until S4 supplies their renderer and S2 activates the read.+ if (candidate.kind === 'service') return null;if (candidate.billing === 'monthly') {return <span className="flex flex-col"><span className="font-semibold text-foreground">{t('settings.models.tools.cost.included')}</span><span className="model-hub-tool-cost-note">{t('settings.models.tools.cost.includedNote')}</span></span>;}diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.tsindex 40ca4bab6..06831842b 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: 17,+ contract_version: 18,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/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.tsindex 0cbf301c1..47e56ac79 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: 17,+ contract_version: 18,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/hostedTools.test.ts b/ui/src/components/settings/models/hostedTools.test.tsindex c8fab4fdd..5a7a7452d 100644--- a/ui/src/components/settings/models/hostedTools.test.ts+++ b/ui/src/components/settings/models/hostedTools.test.ts@@ -70,7 +70,7 @@ describe('hosted-tool status projection', () => {const replayed = run({ verified: [ok(RELAY, 'gpt-6-astra', '2026-10-15T08:00:00Z')], refused: [refused(RELAY, 'gpt-6-astra', '2026-10-14T09:00:00Z', 'replay')] });const refusedToo = { ...replayed, refused: [...replayed.refused, refused(RELAY, 'gpt-6-astra', '2026-10-14T10:00:00Z')] };const kinds = (runStatus: HostedToolRunStatus) => modelCapabilities(- { tools: [{ name: 'web_search', enabled: true, status: runStatus, executor_order: null, effective_order: [], executor_candidates: [] }] },+ { tools: [{ name: 'web_search', prefer_native: true, services: {}, service_order: [], enabled: true, status: runStatus, executor_order: null, effective_order: [], executor_candidates: [] }] },RELAY, 'gpt-6-astra',).map(({ evidence }) => (evidence.kind === 'ok' ? 'ok' : evidence.refusal.aspect));expect(kinds(replayed)).toEqual(['ok', 'replay']);@@ -80,7 +80,7 @@ describe('hosted-tool status projection', () => {it('MH-HOSTED-UI-006: gives a Source model one capability per tool with a record, in catalog order', () => {const status: HostedToolsStatus = {tools: [- { name: 'web_search', enabled: true, status: run({ verified: [ok(RELAY, 'gpt-6-astra', '2026-10-15T08:00:00Z')] }), executor_order: null, effective_order: [], executor_candidates: [] },+ { name: 'web_search', prefer_native: true, services: {}, service_order: [], enabled: true, status: run({ verified: [ok(RELAY, 'gpt-6-astra', '2026-10-15T08:00:00Z')] }), executor_order: null, effective_order: [], executor_candidates: [] },{ name: 'x_search', enabled: true, status: run({ refused: [refused(RELAY, 'gpt-6-astra', '2026-10-14T09:00:00Z')] }), executor_order: null, effective_order: [], executor_candidates: [] },// No record draws nothing: unused is the normal state, not a problem.{ name: 'image_generate', enabled: true, status: run({}), default_model: null, effective_default: null, models: [], image_offered_by: [] },diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts b/ui/src/components/settings/models/routeProjectionReconciliation.test.tsindex 7fcfbaae0..d98620456 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: 17,+ contract_version: 18,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 5281c7bd1..0bbc553c3 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: 17,+ contract_version: 18,host_platform: 'darwin-arm64',manifest: resolution === 'unresolved'? { name: 'cliproxyapi', resolution, assets: [] }diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 02ccb6406..a78492eeb 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -10,8 +10,8 @@// and the PR records the server implementation and feature-flag activation// edge. The client never synthesizes a fallback payload shape.-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 CONTRACT_VERSION = 18 as const;+export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] as const;export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;@@ -1073,7 +1073,8 @@ export type HostedToolListPrice = {};/** A Source that can execute a search for models that cannot run it natively, with the vendor's executor model. */-export type HostedExecutorCandidate = {+export type HostedModelExecutorCandidate = {+ kind: 'model';source_id: string;model_id: string;billing: 'monthly' | 'metered';@@ -1083,6 +1084,45 @@ export type HostedExecutorCandidate = {price: HostedToolListPrice | null;};+/** Service prices extend model tool prices with page-text surcharges, without changing model-only renderers. */+export type HostedServiceListPrice = Omit<HostedToolListPrice, 'unit' | 'extra'> & {+ unit: 'search';+ extra: { unit: HostedToolPriceUnit | 'page'; usd_per_1k: number; when?: 'content' }[];+};++/** Effective settings. Saved settings and PUT patches keep omitted fields absent instead. */+export type HostedSearchServiceSettings = { results: number; content: boolean; enabled: boolean };++/** Defined now, but the server lists no service candidate until S2 activates the chain. */+export type HostedServiceExecutorCandidate = {+ kind: 'service';+ source_id: string;+ /** Catalog service id, e.g. exa/search, never a model name. */+ model_id: string;+ billing: 'metered';+ relay: false;+ price: HostedServiceListPrice;+ settings: HostedSearchServiceSettings;+ state: SourceState;+ trial_pending: boolean;+ cooldown_until: string | null;+};+export type HostedExecutorCandidate = HostedModelExecutorCandidate | HostedServiceExecutorCandidate;++export type HostedSearchServiceVendor = {+ id: string;+ name: string;+ price: HostedServiceListPrice;+ /** Catalog-verified description; null means unknown, not no free tier. */+ free_tier: string | null;+ facts: { tool_only: boolean; auto_enroll: boolean; free_check: boolean };+ results_max: number;+ content_supported: boolean;+ content_changes_price: boolean;+ /** Includes opted-out Sources, so a disabled DeepSeek still reads as already added. */+ source_ids: string[];+};+export type HostedModelRef = { source_id: string; model_id: string };/** One image's price: the vendor's list price, or an estimate from token pricing. */@@ -1093,16 +1133,32 @@ export type HostedImageModel = HostedModelRef & { description: string; billing:type HostedToolBase = { enabled: boolean; status: HostedToolRunStatus };-export type HostedSearchToolStatus = HostedToolBase & {- name: HostedSearchToolName;+type HostedSearchToolBase = HostedToolBase & {/** The saved order; null when automatic. */executor_order: string[] | null;/** The order the gateway would try now. */effective_order: string[];- /** Every eligible executor, in effective order. */+};++export type HostedWebSearchToolStatus = HostedSearchToolBase & {+ name: 'web_search';+ prefer_native: boolean;+ /** Saved partial overrides, never effective defaults. PUT merges only supplied fields. */+ services: Record<string, Partial<HostedSearchServiceSettings>>;+ /** Server-owned creation order; clients never write this back. */+ service_order: string[];executor_candidates: HostedExecutorCandidate[];+ /** Absent until S2 activates service reads and the search chain together. */+ service_vendors?: HostedSearchServiceVendor[];+};++export type HostedXSearchToolStatus = HostedSearchToolBase & {+ name: 'x_search';+ executor_candidates: HostedModelExecutorCandidate[];};+export type HostedSearchToolStatus = HostedWebSearchToolStatus | HostedXSearchToolStatus;+export type HostedImageToolStatus = HostedToolBase & {name: 'image_generate';/** The saved default; null when default. A saved model no longer available stays, flagged. */@@ -1121,6 +1177,10 @@ export type HostedToolsStatus = { tools: HostedToolStatus[] };/** PUT /api/models/hosted-tools/<tool>, per field: an absent field is unchanged, `null` resets it. */export type HostedToolPut = {enabled?: boolean;+ /** web_search only; a boolean, never null. */+ prefer_native?: boolean;+ /** web_search only; null removes a Source override or one of its saved fields. */+ services?: Record<string, { [K in keyof HostedSearchServiceSettings]?: HostedSearchServiceSettings[K] | null } | null>;executor_order?: string[] | null;default_model?: HostedModelRef | null;};diff --git a/ui/src/components/settings/models/useHostedTools.test.tsx b/ui/src/components/settings/models/useHostedTools.test.tsxindex 0b21ed7f6..be8d63afd 100644--- a/ui/src/components/settings/models/useHostedTools.test.tsx+++ b/ui/src/components/settings/models/useHostedTools.test.tsx@@ -17,6 +17,7 @@ import { useHostedTools } from './useHostedTools';const status = (enabled: boolean): HostedToolsStatus => ({tools: [{name: 'web_search',+ prefer_native: true, services: {}, service_order: [],enabled,status: { latest_ok: null, verified: [], refused: [] },executor_order: null,