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): OpenCode v4 — bare menu ids, native_protocol, per-protocol overlay (#1865)
Call White9fc35b19d2ba
diff --git a/config/v2_config.py b/config/v2_config.pyindex 69a12617b..179aa3d7a 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -268,25 +268,6 @@ def normalize_model_hub_vendor_id(value: object) -> str:return vendor-def canonical_opencode_menu_identity(identifier: object) -> tuple[str, str]:- """Validate and split one persisted OpenCode ``provider/model`` identity."""-- from core.handlers.model_hub.identifiers import parse_opencode_model_id-- if not isinstance(identifier, str) or identifier != identifier.strip():- raise ValueError("Invalid OpenCode model identifier")- provider_id, model_id = parse_opencode_model_id(identifier)- if (- re.fullmatch(r"[a-z0-9]+(?:[._-][a-z0-9]+)*", provider_id) is None- or provider_id != provider_id.strip()- or model_id != model_id.strip()- ):- raise ValueError("Invalid OpenCode model identifier")- if _contains_model_hub_credential_material(identifier):- raise ValueError("OpenCode model identifier contains credential material")- return provider_id, model_id--def model_hub_fixed_menu_ids(backend: str) -> tuple[str, ...]:"""Return the bundled fixed-menu ids used by persisted Hub routes."""@@ -529,16 +510,7 @@ def _legacy_route_hops(backend: str,target_model_id: str,) -> list[dict[str, str]]:- provider: Optional[str] = None- bare_target = backend == "opencode" and "/" not in target_model_id- if backend == "opencode":- if not bare_target:- try:- provider, target_model_id = canonical_opencode_menu_identity(target_model_id)- except ValueError:- return []hops: list[dict[str, str]] = []- bare_matches: list[dict[str, str]] = []for source_id in source_order:source = sources[source_id]legacy_claude_model_id = (@@ -553,43 +525,8 @@ def _legacy_route_hops(if not isinstance(model, dict) or not isinstance(model.get("id"), str):continuemodel_id = model["id"]- if provider is not None:- try:- source_provider, source_model_id = canonical_opencode_menu_identity(- f"{source.get('vendor') or ''}/{model_id}"- )- except ValueError:- try:- source_provider, source_model_id = canonical_opencode_menu_identity(- f"custom/{model_id}"- )- except ValueError:- continue- if (source_provider, source_model_id) != (provider, target_model_id):- continue- hops.append({"source_id": source_id, "model_id": model_id})- continue- if bare_target:- try:- _, source_model_id = canonical_opencode_menu_identity(- f"{source.get('vendor') or ''}/{model_id}"- )- except ValueError:- try:- _, source_model_id = canonical_opencode_menu_identity(- f"custom/{model_id}"- )- except ValueError:- continue- if source_model_id == target_model_id or source_model_id.endswith(- f"/{target_model_id}"- ):- bare_matches.append({"source_id": source_id, "model_id": model_id})- continueif model_id == target_model_id:hops.append({"source_id": source_id, "model_id": model_id})- if bare_target and len(bare_matches) == 1:- return bare_matchesreturn hops@@ -657,7 +594,10 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[)except (TypeError, ValueError):return payload, False, ()- for backend, agent in agents.items():+ for backend in ("claude", "codex"):+ agent = agents.get(backend)+ if agent is None:+ continueif not isinstance(agent, dict):return payload, False, ()if set(agent) - {@@ -672,8 +612,7 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple["removed_model_ids",}:return payload, False, ()- expected_menu_kind = "open" if backend == "opencode" else "fixed"- if agent.get("backend") != backend or agent.get("menu_kind") != expected_menu_kind:+ if agent.get("backend") != backend or agent.get("menu_kind") != "fixed":return payload, False, ()if "mode" in agent:mode = agent["mode"]@@ -686,13 +625,12 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[not _legacy_mapping_is_valid(mapping) for mapping in mappings):return payload, False, ()- if backend in {"claude", "codex"}:- fixed_menu_ids = set(model_hub_fixed_menu_ids(backend))- if any(- mapping["enabled"] and mapping["builtin_id"] not in fixed_menu_ids- for mapping in mappings or []- ):- return payload, False, ()+ fixed_menu_ids = set(model_hub_fixed_menu_ids(backend))+ if any(+ mapping["enabled"] and mapping["builtin_id"] not in fixed_menu_ids+ for mapping in mappings or []+ ):+ return payload, False, ()if "routes" in agent and not isinstance(agent["routes"], dict):return payload, False, ()menu = agent.get("menu")@@ -722,7 +660,11 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[return payload, False, ()has_legacy_shape = bool({"priority_order", "subscription_hub_experimental"} & set(model_hub)- or any(isinstance(agent, dict) and "mappings" in agent for agent in agents.values())+ or any(+ isinstance(agents.get(backend), dict)+ and "mappings" in agents[backend]+ for backend in ("claude", "codex")+ )or any(isinstance(source, dict)and "experimental_consent_at" in source@@ -766,8 +708,8 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[sources_by_id[source_id] = sourcewarnings: list[str] = []- migrated_agents: dict[str, object] = {}- for backend in MODEL_HUB_BACKENDS:+ migrated_agents: dict[str, object] = copy.deepcopy(agents)+ for backend in ("claude", "codex"):raw_agent = agents.get(backend)if not isinstance(raw_agent, dict):continue@@ -775,13 +717,7 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[agent = copy.deepcopy(raw_agent)source_order = _legacy_source_order(migrated_model_hub, sources_by_id, agent, backend)source_settings = {"order": source_order}- route_ids: list[str]- if backend in {"claude", "codex"}:- route_ids = list(model_hub_fixed_menu_ids(backend))- else:- menu = agent.get("menu")- checked = menu.get("checked") if isinstance(menu, dict) else []- route_ids = [item for item in checked if isinstance(item, str)]+ route_ids = list(model_hub_fixed_menu_ids(backend))if isinstance(agent.get("routes"), dict):routes = copy.deepcopy(agent["routes"])@@ -797,12 +733,6 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[builtin_id = item.get("builtin_id")if isinstance(builtin_id, str) and builtin_id not in mapping_by_menu:mapping_by_menu[builtin_id] = item- if backend == "opencode":- route_ids.extend(- builtin_id- for builtin_id, mapping in mapping_by_menu.items()- if builtin_id not in route_ids and mapping.get("enabled") is True- )routes = {}for model_id in route_ids:mapping = mapping_by_menu.get(model_id)@@ -831,7 +761,7 @@ def _migrate_legacy_model_hub_payload(payload: dict) -> tuple[dict, bool, tuple[allowed_agent["backend"] = backendagent_mode = agent.get("mode")allowed_agent["mode"] = agent_mode if isinstance(agent_mode, str) and agent_mode in {"hub", "direct"} else "direct"- allowed_agent["menu_kind"] = "open" if backend == "opencode" else "fixed"+ allowed_agent["menu_kind"] = "fixed"allowed_agent["sources"] = source_settingsallowed_agent["routes"] = routesmigrated_agents[backend] = allowed_agent@@ -3208,6 +3138,7 @@ class ModelHubBackendModelConfig:supports_tools: Optional[bool] = Nonesupports_reasoning: Optional[bool] = Nonereasoning_efforts: list[str] = field(default_factory=list)+ native_protocol: Optional[Literal["openai_responses", "anthropic"]] = None@classmethoddef from_payload(cls, payload: object) -> "ModelHubBackendModelConfig":@@ -3225,6 +3156,7 @@ class ModelHubBackendModelConfig:"supports_tools","supports_reasoning","reasoning_efforts",+ "native_protocol",# These are read-only API projection fields. Accepting and dropping# them lets a client submit the list it observed without turning# server-owned policy into persisted state.@@ -3244,6 +3176,7 @@ class ModelHubBackendModelConfig:supports_tools = payload.get("supports_tools")supports_reasoning = payload.get("supports_reasoning")reasoning_efforts = payload.get("reasoning_efforts", [])+ native_protocol = payload.get("native_protocol")if (not isinstance(model_id, str)@@ -3313,6 +3246,13 @@ class ModelHubBackendModelConfig:raise ValueError("Config 'model_hub.agents.models.reasoning_efforts' is invalid")+ if native_protocol is not None and native_protocol not in {+ "openai_responses",+ "anthropic",+ }:+ raise ValueError(+ "Config 'model_hub.agents.models.native_protocol' is invalid"+ )return cls(id=model_id.strip(),origin=origin,@@ -3325,10 +3265,11 @@ class ModelHubBackendModelConfig:supports_tools=supports_tools,supports_reasoning=supports_reasoning,reasoning_efforts=list(reasoning_efforts),+ native_protocol=native_protocol,)def to_payload(self) -> dict:- return {+ payload = {"id": self.id,"display_name": self.display_name,"origin": self.origin,@@ -3341,6 +3282,9 @@ class ModelHubBackendModelConfig:"supports_reasoning": self.supports_reasoning,"reasoning_efforts": list(self.reasoning_efforts),}+ if self.native_protocol is not None:+ payload["native_protocol"] = self.native_protocol+ return payloaddef normalize_storable_backend_model_text(@@ -3477,7 +3421,7 @@ class ModelHubAgentSupplyConfig:menu_payload = payload.get("menu")sources_payload = payload.get("sources")if backend == "opencode" and menu_payload is None:- menu_payload = {"view": "featured", "checked": []}+ raise ValueError("Config 'model_hub.agents.menu' is required for opencode")if backend != "opencode" and menu_payload is not None:raise ValueError("Config 'model_hub.agents.menu' is only valid for opencode")routes = {@@ -3502,14 +3446,7 @@ class ModelHubAgentSupplyConfig:)if models_payload is None:if backend == "opencode":- legacy_ids = list(menu.checked if menu else ())- legacy_ids.extend(- model_id for model_id in routes if model_id not in legacy_ids- )- models = [- ModelHubBackendModelConfig(id=model_id, origin="manual")- for model_id in legacy_ids- ]+ raise ValueError("Config 'model_hub.agents.models' is required for opencode")else:models = _default_backend_models(backend)known = {model.id for model in models}@@ -3530,12 +3467,26 @@ class ModelHubAgentSupplyConfig:if any(_contains_model_hub_credential_material(model_id) for model_id in routes):raise ValueError("Config 'model_hub.agents.routes' contains an invalid model id")if backend == "opencode":+ from core.handlers.model_hub.identifiers import canonical_model_id+for identifier in (*routes, *(model.id for model in models)):- canonical_opencode_menu_identity(identifier)+ if canonical_model_id(identifier) != identifier:+ raise ValueError("Config 'model_hub.agents.models.id' is invalid")+ if any(model.native_protocol is None for model in models):+ raise ValueError(+ "Config 'model_hub.agents.models.native_protocol' is required for opencode"+ )menu = ModelHubMenuConfig(view=menu.view if menu else "featured",checked=[model.id for model in models],)+ elif any(+ isinstance(item, dict) and "native_protocol" in item+ for item in models_payload or ()+ ):+ raise ValueError(+ "Config 'model_hub.agents.models.native_protocol' is only valid for opencode"+ )return cls(backend=backend,mode=mode,diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex c9b2cbdc6..37d2e14f2 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 v7 (2026-09-03).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v8 (2026-09-05).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:@@ -70,6 +70,9 @@ class SourceBinding:model_ids: tuple[str, ...] # declared supply list (discovered + manual# custom entries); required by the engine's generic/API-key config. Bare# model ids, no provider prefix.+ model_reasoning_efforts: tuple[tuple[str, tuple[str, ...]], ...] = ()+ # Per-model levels declared by the Source. CLIProxyAPI needs these on its+ # model registration or it removes an otherwise valid reasoning effort.class OriginNotAllowedError(Exception):diff --git a/core/handlers/model_hub/catalog_admission.py b/core/handlers/model_hub/catalog_admission.pyindex cfa7b8026..fb475837a 100644--- a/core/handlers/model_hub/catalog_admission.py+++ b/core/handlers/model_hub/catalog_admission.py@@ -5,10 +5,7 @@ from __future__ import annotationsfrom collections.abc import Iterable, Mappingfrom typing import Any, Literal-from config.v2_config import (- ModelHubBackendModelConfig,- canonical_opencode_menu_identity,-)+from config.v2_config import ModelHubBackendModelConfigfrom .identifiers import canonical_model_idfrom .resolver import BackendName@@ -25,11 +22,6 @@ def backend_model_admission_error(canonical = canonical_model_id(model_id)if canonical is None or canonical != model_id:return "backend_model_id_invalid"- if backend == "opencode":- try:- canonical_opencode_menu_identity(canonical)- except ValueError:- return "backend_model_id_invalid"if (backend == "claude"and canonical not in set(claude_builtin_ids)diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.pyindex 3db3a853b..8017d6bbb 100644--- a/core/handlers/model_hub/identifiers.py+++ b/core/handlers/model_hub/identifiers.py@@ -25,6 +25,11 @@ USAGE_LEDGER_KEY_MAX_LENGTH = (USAGE_LEDGER_VERBATIM_MAX_LENGTH + 1 + 2 * hashlib.sha256().digest_size)+OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL = {+ "openai_responses": "avibe-openai",+ "anthropic": "avibe-anthropic",+}+def normalized_model_id(value: str) -> str:"""Spell one identifier the one way this product spells it.@@ -138,39 +143,3 @@ def persisted_ledger_key(value: object) -> str | None:if len(canonical) > USAGE_LEDGER_KEY_MAX_LENGTH:return Nonereturn canonical--# Vendors with native, stable OpenCode provider identifiers. Compatible relays-# and unrecognized vendors share the frozen contract's single custom/ prefix.-STANDARD_OPENCODE_VENDOR_IDS = frozenset(- {- "anthropic",- "deepseek",- "github-copilot",- "google",- "groq",- "kimi",- "minimax",- "mistral",- "moonshot",- "openai",- "openrouter",- "together",- "xai",- "zhipuai",- }-)---def opencode_provider_id(vendor: str) -> str:- return vendor if vendor in STANDARD_OPENCODE_VENDOR_IDS else "custom"---def opencode_model_id(vendor: str, model_id: str) -> str:- return f"{opencode_provider_id(vendor)}/{model_id}"---def parse_opencode_model_id(identifier: str) -> tuple[str, str]:- provider, separator, model_id = identifier.partition("/")- if not separator or not provider or not model_id:- raise ValueError("Invalid OpenCode model identifier")- return provider, model_iddiff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 6d21741e7..9cc58097f 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -1661,7 +1661,7 @@ class TurnCorrelationRegistry:self.store.put({- "contract_version": 7,+ "contract_version": 8,"turn_id": normalized_turn_id,"ts": ts or _utc_now_iso(),"agent": trace.agent,diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.pyindex c908d025c..f6651d239 100644--- a/core/handlers/model_hub/resolver.py+++ b/core/handlers/model_hub/resolver.py@@ -12,10 +12,6 @@ from config.v2_config import (ModelHubConfig,ModelHubRouteHopConfig,ModelHubSourceConfig,- canonical_opencode_menu_identity,-)-from core.handlers.model_hub.identifiers import (- opencode_model_id,)@@ -32,8 +28,6 @@ class ExactHopInspection:menu_model: strsource_id: str | Nonemodel_id: str | None- menu_provider_id: str | None- menu_model_id: strsource: ModelHubSourceConfig | Noneconfiguration_eligible: boolinventory_member: bool@@ -64,8 +58,6 @@ class ModelHubTurnResolution:unsupported_source_ids: tuple[str, ...] = ()route_unconfigured: bool = Falseroute_reason: str | None = None- menu_provider_id: str | None = None- menu_model_id: str | None = Noneprovider: str | None = Nonerecoverable_source_ids: tuple[str, ...] = ()supply_status: SupplyStatus | None = None@@ -100,32 +92,6 @@ def source_eligible_for_backend(source: ModelHubSourceConfig, backend: str) -> breturn ModelHubConfig.source_eligible_for_backend(source, backend)-def opencode_source_model_identity(- source: ModelHubSourceConfig,- model_id: str,-) -> str:- return opencode_model_id(source.vendor, model_id)---def opencode_inventory_menu_ids(config: ModelHubConfig) -> frozenset[str]:- """Return OpenCode identities backed by current eligible inventory."""-- identities = {- opencode_source_model_identity(source, model.id)- for source in config.sources- if source_eligible_for_backend(source, "opencode")- for model in source.models- if not model.retired- }- for menu_model, route in config.agents["opencode"].routes.items():- if any(- inspect_exact_hop(config, "opencode", menu_model, hop).supply_eligible- for hop in route.hops- ):- identities.add(menu_model)- return frozenset(identities)--def source_retry_ready(source: ModelHubSourceConfig, now: datetime | None) -> bool:if source.state.status != "cooldown" or now is None:return False@@ -169,21 +135,6 @@ def source_runnable(return source_retry_ready(source, now)-def normalize_opencode_requested_model(- requested_model: str,- checked_identifiers: tuple[str, ...],-) -> str | None:- """Normalize a bare OpenCode selection to one exact checked menu id."""-- candidate = str(requested_model or "").strip()- if not candidate:- return None- if candidate in checked_identifiers:- return candidate- matches = [identifier for identifier in checked_identifiers if identifier.endswith(f"/{candidate}")]- return matches[0] if len(matches) == 1 else None--_CLAUDE_FAMILY_ALIASES = {"opus": "opus","opus[1m]": "opus",@@ -212,7 +163,6 @@ def matching_v1_model_id(backend: BackendName,requested_model: str,source: ModelHubSourceConfig,- checked_models: tuple[str, ...] = (),include_manual: bool = False,) -> str | None:"""Return one concrete observed model for the frozen add-time matching-v1."""@@ -223,20 +173,6 @@ def matching_v1_model_id(if (include_manual or model.provenance == "discovered") and not model.retired)- if backend == "opencode":- requested_model = normalize_opencode_requested_model(- requested_model,- checked_models,- ) or ""- if not requested_model:- return None- exact = [- model.id- for model in observed_models- if opencode_source_model_identity(source, model.id) == requested_model- ]- return exact[0] if len(exact) == 1 else None-if (backend == "claude"and source.vendor == "anthropic"@@ -284,19 +220,12 @@ def inspect_exact_hop() -> ExactHopInspection:"""Inspect one stored hop without matching, substituting, or reordering it."""- menu_provider_id: str | None = None- menu_model_id = menu_model- if backend == "opencode":- menu_provider_id, menu_model_id = canonical_opencode_menu_identity(menu_model)-if hop is None:return ExactHopInspection(backend=backend,menu_model=menu_model,source_id=None,model_id=None,- menu_provider_id=menu_provider_id,- menu_model_id=menu_model_id,source=None,configuration_eligible=False,inventory_member=False,@@ -314,8 +243,6 @@ def inspect_exact_hop(menu_model=menu_model,source_id=hop.source_id,model_id=hop.model_id,- menu_provider_id=menu_provider_id,- menu_model_id=menu_model_id,source=None,configuration_eligible=False,inventory_member=False,@@ -354,8 +281,6 @@ def inspect_exact_hop(menu_model=menu_model,source_id=source.id,model_id=hop.model_id,- menu_provider_id=menu_provider_id,- menu_model_id=menu_model_id,source=source,configuration_eligible=configuration_eligible,inventory_member=inventory_member,@@ -444,13 +369,6 @@ def resolve_model_hub_turn(route_reason="route_unconfigured",)- menu_provider_id: str | None = None- menu_model_id: str | None = None- if backend == "opencode":- menu_provider_id, menu_model_id = canonical_opencode_menu_identity(- requested_model- )-inspected_hops = tuple(inspect_exact_hop(config,@@ -551,8 +469,6 @@ def resolve_model_hub_turn(unsupported_source_ids=tuple(unsupported_source_ids),route_unconfigured=route_reason == "route_unconfigured",route_reason=route_reason,- menu_provider_id=menu_provider_id,- menu_model_id=menu_model_id,recoverable_source_ids=recoverable,supply_status=_supply_status(inspected_hops,diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 7e019139a..1c0682e42 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -31,7 +31,6 @@ from config.v2_config import (ModelHubSourceStateConfig,ModelHubSourceUsageConfig,V2Config,- canonical_opencode_menu_identity,normalize_storable_backend_model_text,normalize_model_hub_base_url,normalize_model_hub_vendor_id,@@ -88,7 +87,7 @@ from .events import (redact_credential_material,)from .errors import ModelDiscoveryError-from .identifiers import STANDARD_OPENCODE_VENDOR_IDS, canonical_model_id+from .identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL, canonical_model_idfrom .migration import (MigrationConflictError,apply_native_migration,@@ -121,7 +120,6 @@ from .resolver import (allowed_origins,inspect_exact_hop,matching_v1_model_id as _matching_v1_model_id,- opencode_source_model_identity,resolve_model_hub_turn,source_after_cooldown_recovery,source_eligible_for_backend,@@ -130,7 +128,7 @@ from .resolver import (from .revocations import CredentialRevocationJournalfrom .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, SourceIdentity, UsageWriter-CONTRACT_VERSION = 7+CONTRACT_VERSION = 8def _storable_backend_model_metadata(@@ -153,8 +151,8 @@ def _storable_backend_model_metadata(return proposed_display_name, proposed_efforts-AGENT_CHAIN_CONTRACT_VERSION = 7-PROBE_RESULT_CONTRACT_VERSION = 7+AGENT_CHAIN_CONTRACT_VERSION = 8+PROBE_RESULT_CONTRACT_VERSION = 8_REORDER_ORDER_UNSET = object()_REASONING_EFFORT_TELEMETRY_MAX_BYTES = 256# Settlement generations are minted per attempt start and live only in this@@ -171,6 +169,8 @@ def project_opencode_public_model() -> dict[str, Any]:"""Project backend-owned metadata without upstream Route details."""+ if model.native_protocol not in OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL:+ raise ValueError("OpenCode model native_protocol is invalid")identifier = model.idprojected: dict[str, Any] = {"id": identifier,@@ -194,13 +194,21 @@ def project_opencode_public_model(projected["modalities"] = modalitiesif model.supports_tools is not None:projected["tool_call"] = model.supports_tools- if model.supports_reasoning is not None:- projected["reasoning"] = model.supports_reasoning+ if model.supports_reasoning is False:+ projected["reasoning"] = False+ elif (+ model.supports_reasoning is True+ and model.native_protocol == "openai_responses"+ ):+ # Anthropic variants already express support. ``reasoning: true`` makes+ # that SDK add a budget-based option which overrides the selected effort.+ projected["reasoning"] = True+ variant_key = {+ "openai_responses": "reasoningEffort",+ "anthropic": "effort",+ }[model.native_protocol]variants = (- {- effort: {"reasoningEffort": effort}- for effort in model.reasoning_efforts- }+ {effort: {variant_key: effort} for effort in model.reasoning_efforts}if model.supports_reasoning is not Falseelse {})@@ -477,7 +485,11 @@ def _project_opencode_public_models(return {}projected: dict[str, dict[str, Any]] = {}for model in agent.models:- projected[model.id] = project_opencode_public_model(model)+ if model.native_protocol not in OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL:+ raise ValueError("OpenCode model native_protocol is invalid")+ public_model = project_opencode_public_model(model)+ public_model["native_protocol"] = model.native_protocol+ projected[model.id] = public_modelreturn projected@@ -636,6 +648,7 @@ def _binding(source: ModelHubSourceConfig) -> SourceBinding:source_origins = allowed_origins(source)if source.kind == "subscription" and not source_origins:raise ModelHubError("mode_switch_blocked", status=409)+ active_models = [model for model in source.models if not model.retired]return SourceBinding(source_id=source.id,vendor=source.vendor,@@ -643,7 +656,10 @@ def _binding(source: ModelHubSourceConfig) -> SourceBinding:base_url=source.base_url,credential_ref=source.credential_ref,allowed_origins=source_origins,- model_ids=tuple(model.id for model in source.models if not model.retired),+ model_ids=tuple(model.id for model in active_models),+ model_reasoning_efforts=tuple(+ (model.id, tuple(model.reasoning_efforts)) for model in active_models+ ),)@@ -686,7 +702,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:manager = EngineRuntimeManager()return {- "contract_version": 7,+ "contract_version": 8,"enabled": enabled,"host_platform": status.host_platform or manager.host_platform(),"manifest": manager.contract_manifest(),@@ -1796,7 +1812,6 @@ class ModelHubService:backend=cast(BackendName, backend),requested_model=menu_model,source=source,- checked_models=menu_ids,)if matched_model is None or any(hop.source_id == source.id for hop in route.hops):continue@@ -1813,9 +1828,6 @@ class ModelHubService:agent = config.agents[backend]source_by_id = {source.id: source for source in config.sources}hops: list[ModelHubRouteHopConfig] = []- checked_models = self._agent_menu_model_ids(agent)- if menu_model not in checked_models:- checked_models = (*checked_models, menu_model)for source_id in agent.sources.order:source = source_by_id.get(source_id)if source is None or not self._eligible_for_agent(source, backend):@@ -1824,7 +1836,6 @@ class ModelHubService:backend=backend,requested_model=menu_model,source=source,- checked_models=checked_models,include_manual=True,)if matched_model is not None:@@ -3675,7 +3686,6 @@ class ModelHubService:if agent.menu_kind == "fixed"else None)- standard_vendors = sorted(STANDARD_OPENCODE_VENDOR_IDS) if agent.backend == "opencode" else Nonerequested_model = self._requested_model(agent)unavailable_source_ids = self._unavailable_native_sources(config, backend)now = self.now()@@ -3794,7 +3804,6 @@ class ModelHubService:"named_agents": named_agents,"catalog_models": self._catalog_models_payload(agent),"builtin_models": builtin_models,- "standard_vendors": standard_vendors,}def _candidate_suppliers(@@ -3841,6 +3850,13 @@ class ModelHubService:agent_backend = cast(BackendName, backend)config = self.store.load()agent = self._agent(config, backend)+ from vibe.models_dev_catalog import native_protocol_for_model_id++ def protocol_payload(model_id: str) -> dict[str, str]:+ if backend != "opencode":+ return {}+ return {"native_protocol": native_protocol_for_model_id(model_id)}+menu_models = self._catalog_models_payload(agent)menu_ids = {model["id"] for model in menu_models}snapshot = self._current_builtin_models(agent_backend)@@ -3859,6 +3875,7 @@ class ModelHubService:"origin": "builtin","display_name": display_name,"reasoning_efforts": reasoning_efforts,+ **protocol_payload(model_id),},claude_builtin_ids=_builtin_model_ids("claude"),)@@ -3879,6 +3896,7 @@ class ModelHubService:"reasoning_efforts": admitted.reasoning_efforts,"suppliers": suppliers,"origin": "builtin",+ **protocol_payload(admitted.id),})@@ -3891,11 +3909,7 @@ class ModelHubService:for model in source.models:if model.retired:continue- candidate_id = (- opencode_source_model_identity(source, model.id)- if backend == "opencode"- else model.id- )+ candidate_id = model.idif (candidate_id in menu_idsor candidate_id in builtin_ids@@ -3918,6 +3932,7 @@ class ModelHubService:"origin": "provider","display_name": display_name,"reasoning_efforts": reasoning_efforts,+ **protocol_payload(model_id),},claude_builtin_ids=_builtin_model_ids("claude"),)@@ -3930,6 +3945,7 @@ class ModelHubService:"reasoning_efforts": admitted.reasoning_efforts,"suppliers": suppliers,"origin": "provider",+ **protocol_payload(admitted.id),})in_list = []@@ -3963,6 +3979,7 @@ class ModelHubService:if suppliers and provider_candidate is not Noneelse None),+ **protocol_payload(model["id"]),})return {"builtin": builtin, "providers": providers, "in_list": in_list}@@ -4102,11 +4119,15 @@ class ModelHubService:model = ModelHubBackendModelConfig.from_payload(item)except (TypeError, ValueError) as exc:raise ModelHubError("backend_model_catalog_invalid") from exc- if backend == "opencode":- try:- canonical_opencode_menu_identity(model.id)- except ValueError as exc:- raise ModelHubError("backend_model_id_invalid") from exc+ if backend == "opencode" and model.native_protocol is None:+ raise ModelHubError("backend_model_catalog_invalid")+ if backend != "opencode" and model.native_protocol is not None:+ raise ModelHubError("backend_model_catalog_invalid")+ if backend == "opencode" and cls._backend_model_admission_error(+ "opencode",+ model.id,+ ):+ raise ModelHubError("backend_model_id_invalid")rows.append(model)if len({model.id for model in rows}) != len(rows):raise ModelHubError("backend_model_duplicate")diff --git a/docs/plans/backend-model-catalogs.md b/docs/plans/backend-model-catalogs.mdindex d2fd6d3ff..d72424f88 100644--- a/docs/plans/backend-model-catalogs.md+++ b/docs/plans/backend-model-catalogs.md@@ -603,7 +603,8 @@ No new string anywhere else; nothing explains the mechanism.1. For every OpenCode menu row — empty Route chain included — the overlay holds exactly onemodel entry, under the provider named by its `native_protocol`; every generated providerholds at least one entry, the overlay holds no other provider, and `enabled_providers`- equals the set of generated provider ids.+ equals the set of generated provider ids. With an empty menu the overlay is the empty+ overlay (`avibe-openai`, no models) and the serve process keeps running.2. A menu id is byte-identical across Gateway⇄Direct switches, Source add/remove/reorder,failover, route edits, and engine restarts; it changes only when the user renames the row.3. When the serving hop is an API-key Source whose protocol equals the row's@@ -634,4 +635,3 @@ filtering, `modules/agents/opencode/agent.py` addressing), the engine credentialversion 8 · **UI** — bare-id rows, editor `API` field, retired prefixingand buckets, e2e fixtures · **docs mirror**. Gemini ships in its own later revision with aGemini Source protocol.-diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 128bfa3fd..36b9c62d2 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,16 +1,16 @@# Model Hub contracts-Status: **FINAL shape, implementation-gated. `contract_version` is 7 (2026-09-03-backend-catalog composition and reasoning-tier provenance); 6 published 2026-08-19+Status: **FINAL shape, implementation-gated. `contract_version` is 8 (2026-09-05+OpenCode bare ids and per-protocol overlay); 7 defined 2026-09-03 for+backend-catalog composition and reasoning-tier provenance; 6 published 2026-08-19usage metering; 5 published the 2026-08-11 contract completion.**These files describe the terminal contract for Model Hub before first release. No bumpcarries a data migration, compatibility reader, conversion transaction, or versiondiscriminator: Model Hub has not shipped, so republishing the shape converts nothing.-`contract_version` is 7 wherever a versioned object exists. The owner-approved-pre-release corrections add server-owned candidate composition, one-time matching-points, and reasoning-tier provenance while removing the earlier persistent-network/timeout cooldown spelling, without adding compatibility paths.+`contract_version` is 8 wherever a versioned object exists. The owner-approved+pre-release correction adds OpenCode bare ids, server-owned native protocols, and+per-protocol runtime providers while deleting the prefixed-id compatibility paths.`v5` is still written throughout these files and stays: it names the contract-completiongeneration they were authored in, and sentences such as "Minimum v5 set" or@@ -104,7 +104,7 @@ comparison. A gate may not report success by comparing stale input with itself.## Version closure-`contract_version` 7 must coexist in all registered version locations on the same tested head:+`contract_version` 8 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 c9b2cbdc6..37d2e14f2 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 v7 (2026-09-03).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v8 (2026-09-05).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:@@ -70,6 +70,9 @@ class SourceBinding:model_ids: tuple[str, ...] # declared supply list (discovered + manual# custom entries); required by the engine's generic/API-key config. Bare# model ids, no provider prefix.+ model_reasoning_efforts: tuple[tuple[str, tuple[str, ...]], ...] = ()+ # Per-model levels declared by the Source. CLIProxyAPI needs these on its+ # model registration or it removes an otherwise valid reasoning effort.class OriginNotAllowedError(Exception):diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex dddda5315..a32565293 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", "chain", "current", "supply_state"],"additionalProperties": false,"properties": {- "contract_version": { "const": 7 },+ "contract_version": { "const": 8 },"backend": { "enum": ["claude", "codex", "opencode"] },"model_id": { "type": "string" },"current": {@@ -161,7 +161,7 @@],"examples": [{- "contract_version": 7,+ "contract_version": 8,"backend": "claude","model_id": "claude-opus-4-6","chain": [{ "source_id": "src_claudepro1", "model_id": "claude-opus-4-6", "channel": "native_cli", "health": "cooldown", "runnable": false, "reason": null, "retry_at": "2026-07-29T04:00:00Z" }],@@ -169,7 +169,7 @@"supply_state": "waiting"},{- "contract_version": 7,+ "contract_version": 8,"backend": "opencode","model_id": "custom/glm-5.2","chain": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2", "channel": "hub", "health": "backoff", "runnable": false, "reason": "models.source.backoff.connection_failed", "retry_at": "2026-08-11T11:55:08Z" }],@@ -177,7 +177,7 @@"supply_state": "waiting"},{- "contract_version": 7,+ "contract_version": 8,"backend": "codex","model_id": "gpt-5.6","chain": [{ "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "channel": "native_cli", "health": "healthy", "runnable": false, "reason": "native_cli_unavailable", "retry_at": null }],@@ -185,7 +185,7 @@"supply_state": "interrupted"},{- "contract_version": 7,+ "contract_version": 8,"backend": "codex","model_id": "gpt-5.6","chain": [{ "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "channel": "native_cli", "health": "backoff", "runnable": false, "reason": "native_cli_unavailable", "retry_at": "2026-08-11T11:55:08Z" }],@@ -193,7 +193,7 @@"supply_state": "interrupted"},{- "contract_version": 7,+ "contract_version": 8,"backend": "claude","model_id": "claude-haiku-4-5","chain": [],diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.jsonindex 7f7234767..264d330f1 100644--- a/docs/plans/model-hub-contracts/agent-supply.schema.json+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json@@ -144,8 +144,8 @@"view": { "enum": ["featured", "full"] },"checked": {"type": "array",- "description": "prefixed identifiers, e.g. zhipuai/glm-5.2 (see opencode-overlay.md)",- "items": { "type": "string", "pattern": "^[a-z0-9_-]+/.+$" },+ "description": "Bare canonical model identifiers, stored exactly as the backend emits them.",+ "items": { "type": "string", "minLength": 1, "maxLength": 256, "pattern": "^\\S(?:[\\s\\S]*\\S)?$" },"uniqueItems": true}}@@ -160,7 +160,7 @@"properties": {"model_id": {"type": "string",- "description": "The identifier this backend's menu uses: the built-in id for fixed menus, the prefixed identifier (vendor/model) for open menus."+ "description": "The exact canonical identifier this backend's menu uses."},"chain_length": {"type": "integer",@@ -222,8 +222,7 @@]}},- "builtin_models": { "type": ["array", "null"], "items": { "type": "string" }, "description": "Compatibility projection for older clients. New clients consume catalog_models." },- "standard_vendors": { "type": ["array", "null"], "items": { "type": "string" }, "description": "v1.2 (2026-07-24 integration): opencode only — server-populated mirror of STANDARD_OPENCODE_VENDOR_IDS (core/handlers/model_hub/identifiers.py) so the UI never hand-mirrors vendor lists; null otherwise." }+ "builtin_models": { "type": ["array", "null"], "items": { "type": "string" }, "description": "Compatibility projection for older clients. New clients consume catalog_models." }},"allOf": [{@@ -324,12 +323,11 @@}},{- "$comment": "Fixed-menu backends expose their built-in model catalog; open-menu state and provider metadata are null.",+ "$comment": "Fixed-menu backends expose their built-in model catalog; open-menu state is null.","if": { "properties": { "menu_kind": { "const": "fixed" } }, "required": ["menu_kind"] },"then": {"properties": {- "menu": { "type": "null" },- "standard_vendors": { "type": "null" }+ "menu": { "type": "null" }}}},@@ -350,6 +348,34 @@"if": { "properties": { "backend": { "enum": ["claude", "codex"] } }, "required": ["backend"] },"then": { "properties": { "menu_kind": { "const": "fixed" } } }},+ {+ "$comment": "BackendModel has no discriminator, so the containing catalog owns native_protocol presence.",+ "if": { "properties": { "backend": { "const": "opencode" } }, "required": ["backend"] },+ "then": {+ "properties": {+ "catalog_models": {+ "items": {+ "allOf": [+ { "$ref": "backend-model.schema.json" },+ { "required": ["native_protocol"] }+ ]+ }+ }+ }+ },+ "else": {+ "properties": {+ "catalog_models": {+ "items": {+ "allOf": [+ { "$ref": "backend-model.schema.json" },+ { "not": { "required": ["native_protocol"] } }+ ]+ }+ }+ }+ }+ },{"$comment": "A non-null sources object always carries a real eligibility array. The API guard enforces one row per existing Source and requires every id in order to have eligible=true; draft-07 cannot compare the two arrays directly.","if": { "properties": { "sources": { "type": "object" } }, "required": ["sources"] },@@ -371,16 +397,14 @@"mode": "hub","menu_kind": "fixed","menu": null,- "builtin_models": ["claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"],- "standard_vendors": null+ "builtin_models": ["claude-opus-4-6", "claude-sonnet-4-6", "claude-haiku-4-5"]},{"backend": "opencode","mode": "hub","menu_kind": "open",- "menu": { "view": "featured", "checked": ["anthropic/claude-opus-4-6", "openai/gpt-5.6", "zhipuai/glm-5.2", "zhipuai/glm-5.2-air"] },- "builtin_models": null,- "standard_vendors": ["anthropic", "deepseek", "github-copilot", "google", "groq", "kimi", "minimax", "mistral", "moonshot", "openai", "openrouter", "together", "xai", "zhipuai"]+ "menu": { "view": "featured", "checked": ["claude-opus-4-6", "gpt-5.6", "glm-5.2", "glm-5.2-air"] },+ "builtin_models": null}]}diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.jsonindex f552e7de5..8ccb21bae 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 @@"allOf": [{"$ref": "model-hub/agent-supply.schema.json"},{- "required": ["backend", "cli_present", "mode", "menu_kind", "catalog_models", "selected_by_agent", "selected_model_id", "selected_model_explicit", "sources", "routes", "supply_status", "menu", "model_supply", "named_agents", "builtin_models", "standard_vendors"],+ "required": ["backend", "cli_present", "mode", "menu_kind", "catalog_models", "selected_by_agent", "selected_model_id", "selected_model_explicit", "sources", "routes", "supply_status", "menu", "model_supply", "named_agents", "builtin_models"],"properties": {"sources": {"oneOf": [@@ -139,7 +139,7 @@"SuccessCore": {"properties": {"ok": {"const": true},- "contract_version": {"const": 7}+ "contract_version": {"const": 8}}},"SourceListResponse": {@@ -148,7 +148,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}}},@@ -158,7 +158,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"observation": {"$ref": "model-hub/observation-result.schema.json"}}},@@ -168,7 +168,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"source": {"$ref": "#/definitions/SourceApi"},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}@@ -180,7 +180,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"source": {"$ref": "#/definitions/SourceApi"}}},@@ -190,7 +190,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"source": {"$ref": "#/definitions/SourceApi"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -202,7 +202,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}}@@ -213,7 +213,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}}},@@ -223,7 +223,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"agent": {"$ref": "#/definitions/AgentSupplyApi"}}},@@ -236,7 +236,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"agent": {"$ref": "#/definitions/AgentSupplyApi"},"removed_hops": {"type": "array", "minItems": 1, "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}@@ -261,7 +261,7 @@"additionalProperties": false,"properties": {"ok": {"const": false},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"error": {"const": "candidate_suppliers_changed"},"detail": {"type": "string", "minLength": 1},"changed": {@@ -281,11 +281,40 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"agent": {"type": "object","required": ["backend", "mode", "catalog_models"],"additionalProperties": false,+ "allOf": [+ {+ "if": { "properties": { "backend": { "const": "opencode" } }, "required": ["backend"] },+ "then": {+ "properties": {+ "catalog_models": {+ "items": {+ "allOf": [+ { "$ref": "model-hub/backend-model.schema.json" },+ { "required": ["native_protocol"] }+ ]+ }+ }+ }+ },+ "else": {+ "properties": {+ "catalog_models": {+ "items": {+ "allOf": [+ { "$ref": "model-hub/backend-model.schema.json" },+ { "not": { "required": ["native_protocol"] } }+ ]+ }+ }+ }+ }+ }+ ],"properties": {"backend": {"enum": ["claude", "codex", "opencode"]},"mode": {"enum": ["hub", "direct"]},@@ -317,6 +346,7 @@"reasoning_efforts": {"type": "array", "items": {"type": "string", "minLength": 1, "maxLength": 64}, "uniqueItems": true},"suppliers": {"type": "array", "items": {"$ref": "#/definitions/CandidateSupplier"}, "uniqueItems": true},"origin": {"enum": ["builtin", "provider", "models_dev", "manual"]},+ "native_protocol": {"enum": ["openai_responses", "anthropic"]},"group_if_removed": {"anyOf": [{"enum": ["builtin", "providers"]}, {"type": "null"}]}}},@@ -332,7 +362,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"candidates": {"type": "object","required": ["builtin", "providers", "in_list"],@@ -351,13 +381,13 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"matches": {"type": "array","maxItems": 8,"items": {"type": "object",- "required": ["provider_id", "provider_name", "first_party", "model_id", "models_dev_id", "display_name", "context_window", "max_output_tokens", "input_modalities", "output_modalities", "supports_tools", "supports_reasoning", "reasoning_efforts"],+ "required": ["provider_id", "provider_name", "first_party", "model_id", "models_dev_id", "display_name", "context_window", "max_output_tokens", "input_modalities", "output_modalities", "supports_tools", "supports_reasoning", "reasoning_efforts", "native_protocol"],"additionalProperties": false,"properties": {"provider_id": {"type": "string", "minLength": 1},@@ -372,7 +402,8 @@"output_modalities": {"type": "array", "items": {"enum": ["text", "image", "audio", "video"]}, "uniqueItems": true},"supports_tools": {"type": ["boolean", "null"]},"supports_reasoning": {"type": ["boolean", "null"]},- "reasoning_efforts": {"type": "array", "items": {"type": "string", "minLength": 1, "maxLength": 64}, "uniqueItems": true}+ "reasoning_efforts": {"type": "array", "items": {"type": "string", "minLength": 1, "maxLength": 64}, "uniqueItems": true},+ "native_protocol": {"enum": ["openai_responses", "anthropic"]}}}}@@ -384,7 +415,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"chain": {"$ref": "model-hub/agent-chain.schema.json"}}},@@ -394,7 +425,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}}},@@ -404,7 +435,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"chain": {"$ref": "model-hub/agent-chain.schema.json"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -416,7 +447,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"probe": {"$ref": "model-hub/probe-result.schema.json"}}},@@ -426,7 +457,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}}},@@ -436,7 +467,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"usage": {"$ref": "model-hub/usage-summary.schema.json"}}},@@ -446,7 +477,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -468,7 +499,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -491,7 +522,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -516,7 +547,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7}+ "contract_version": {"const": 8}}},"RuntimeApi": {@@ -538,7 +569,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"scan": {"$ref": "model-hub/migration-scan.schema.json"}}},@@ -548,7 +579,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"applied": {"type": "integer", "minimum": 0},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}@@ -560,7 +591,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}}},@@ -570,7 +601,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 7},+ "contract_version": {"const": 8},"runtime": {"$ref": "#/definitions/RuntimeApi"}}}diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex d499c0b11..fd69145c2 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -1,10 +1,10 @@# Model Hub — REST API contract-Status: **Normative, `contract_version` 7** — 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` 8** — 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: 7, ...}`.+Success envelope: `{ok: true, contract_version: 8, ...}`.Failure envelope:-`{ok: false, contract_version: 7, error: <machine_code>, detail?: <i18n_key>}`.+`{ok: false, contract_version: 8, 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@@ -16,7 +16,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` 7, the+The shared envelope and every versioned nested contract carry `contract_version` 8, theterminal value. Model Hub has not shipped, so there is no internal contract migration orcompatibility path.@@ -40,10 +40,10 @@ compatibility path.| PUT `/api/models/agents/<backend>/sources` | `{order: string[]}` → `{agent: AgentSupply}` | Stores and re-echoes the complete canonical order; no policy state exists. This route never touches a Route chain and has no guarded `409` branch. || POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[]}` → `{agent: AgentSupply}` | With `order`, atomically stores the complete Source order and idempotently reorders every stored Route by it; with no body, applies the already stored order. In either form it adds, removes, remaps, matches, and guards nothing. The total order is defined below. || PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. A qualifying Direct → Gateway switch atomically adopts the recognized CLI login as the first native Source; other switches create nothing. |-| GET `/api/models/agents/<backend>/models` | → `{agent: {backend, mode, catalog_models}}` | Picker-safe catalog read. It exposes no Source order, Route, or credential-bearing supplier data; editors use it as the Gateway model menu and fall back to the backend-native catalog in Direct mode, during a rolling upgrade from a pre-catalog server, or while this read is unavailable. |-| GET `/api/models/agents/<backend>/models/candidates` | → `{candidates: {builtin: Candidate[], providers: Candidate[], in_list: Candidate[]}}` | Server-owned picker projection. It returns addable built-ins, deduplicated ordered-provider inventory, and every current menu row with the same exact supplier projection; it is independent of backend mode and contains no credentials. Only `in_list` candidates may carry optional `group_if_removed: "builtin" | "providers" | null`, naming the group where that id would be offered after removal; absence is unknown to rolling-upgrade clients. |-| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[], expected_suppliers?: {<id>: [{source_id, model_id}]}, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409`, stale-candidate `409`, `{agent: AgentSupply}`, or `{agent: AgentSupply, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` | Applies one full-list backend catalog edit with optimistic merge. Each caller addition still absent from the latest list is matched once against complete non-retired inventory in stored eligible Source order. A listed supplier-projection mismatch refuses atomically with the separate exact shape `{ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed}`; a concurrently added row keeps its existing Route. A routeful removal uses the exact echoed-plan guard and then atomically removes its Route; empty-route removal is ordinary success. Supplier inventory remains unchanged. |-| GET `/api/models/catalog/models-dev?query=<text>` | → `{matches: ModelsDevMatch[]}` | Read-only metadata lookup through the server-owned conditional cache. Results keep the shipped provider fields, deduplicate aggregator copies by model id, rank first-party matches first, add `first_party`, cap results at 8, and never persist automatically. |+| GET `/api/models/agents/<backend>/models` | → `{agent: {backend, mode, catalog_models}}` | Picker-safe catalog read. It exposes no Source order, Route, or credential-bearing supplier data. Every OpenCode row carries required `native_protocol`; Claude and Codex rows omit it. |+| GET `/api/models/agents/<backend>/models/candidates` | → `{candidates: {builtin: Candidate[], providers: Candidate[], in_list: Candidate[]}}` | Server-owned picker projection. It returns addable built-ins, deduplicated ordered-provider inventory, and every current menu row with the same exact supplier projection; it is independent of backend mode and contains no credentials. Every OpenCode Candidate carries server-derived `native_protocol`; other backends omit it. Only `in_list` candidates may carry optional `group_if_removed: "builtin" | "providers" | null`, naming the group where that id would be offered after removal. |+| PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[], expected_suppliers?: {<id>: [{source_id, model_id}]}, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409`, stale-candidate `409`, `{agent: AgentSupply}`, or `{agent: AgentSupply, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` | Applies one full-list backend catalog edit with optimistic merge. OpenCode rows require a literal `native_protocol: openai_responses | anthropic`; rows for other backends forbid it. Each caller addition still absent from the latest list is matched once against complete non-retired inventory in stored eligible Source order. A listed supplier-projection mismatch refuses atomically with the separate exact shape `{ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed}`; a concurrently added row keeps its existing Route. A routeful removal uses the exact echoed-plan guard and then atomically removes its Route; empty-route removal is ordinary success. Supplier inventory remains unchanged. |+| GET `/api/models/catalog/models-dev?query=<text>` | → `{matches: ModelsDevMatch[]}` | Read-only metadata lookup through the server-owned conditional cache. Results keep the shipped provider fields, deduplicate aggregator copies by model id, rank first-party matches first, add `first_party`, derive `native_protocol` from the model id's last path segment through the vendor map, cap results at 8, and never persist automatically. || GET `/api/models/agents/<backend>/chains` | → `{chains: AgentChain[]}` | Hub only. Returns the complete Overview model set in menu order, followed by a selected model or configured Route not already present. All members share one config snapshot and observation time. Direct returns the documented `direct_mode` error. || GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. || PUT `/api/models/agents/<backend>/chain?model=<id>` | `{hops: RouteHop[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{chain, removed_hops, interrupted}` | Replaces the exact Source/model pairs in submitted order after validating new or changed pairs; the handler never reads `sources.order`, and the submitted `hops` carry no Source-order semantics. It is the `mutation.route_replace` row of the authoritative mutation matrix. A visible noninterrupting hop removal is ordinary success; only a resulting protected-supply interruption enters the guard. |@@ -57,7 +57,7 @@ compatibility path.| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. || POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Each accepted import runs the same one-time matching and placement as Add Source; original files remain byte-identical. || 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` 7 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` 8 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. 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 Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |@@ -213,7 +213,7 @@ list verbatim. It never substitutes a family default or filters the row throughshared ordered vocabulary.Refresh re-applies the first two rungs and otherwise preserves user declarations. OAuth-materialization and native-config import use the same ladder at creation time. A v7 API+materialization and native-config import use the same ladder at creation time. A v8 APIpayload always includes the field, while the persisted-config loader accepts older rowsthat omit it: a non-empty list becomes `user` and an empty list becomes null. The firstpost-upgrade refresh performs any catalog backfill; there is no offline tier migration.@@ -492,7 +492,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:```json{"ok": true,- "contract_version": 7,+ "contract_version": 8,"source": {"id": "src_anthkey01","kind": "api_key",@@ -570,7 +570,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c```json{"ok": false,- "contract_version": 7,+ "contract_version": 8,"error": "source_last_supplier","would_remove_hops": [],"would_interrupt": [@@ -702,7 +702,7 @@ API-key success:```json{"ok": true,- "contract_version": 7,+ "contract_version": 8,"source": {"id": "src_relay9c1x","kind": "api_key",@@ -793,7 +793,7 @@ Status and submit return the same terminal shape:```json{"ok": true,- "contract_version": 7,+ "contract_version": 8,"flow": {"flow_id": "oaf_claude01","client_nonce": "ofn_01j5w8z7p4n6q2rt",@@ -853,9 +853,9 @@ a valid `interrupted` chain.```json{"ok": true,- "contract_version": 7,+ "contract_version": 8,"chain": {- "contract_version": 7,+ "contract_version": 8,"backend": "codex","model_id": "gpt-5.6","chain": [@@ -880,7 +880,7 @@ In Direct mode both chain and probe refuse with:```json{"ok": false,- "contract_version": 7,+ "contract_version": 8,"error": "direct_mode","detail": "models.hub.direct_mode"}@@ -894,9 +894,9 @@ A successful probe nests its result:```json{"ok": true,- "contract_version": 7,+ "contract_version": 8,"probe": {- "contract_version": 7,+ "contract_version": 8,"backend": "claude","channel": "hub","reachable": false,@@ -919,7 +919,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 7,+ "contract_version": 8,"backend": "codex","channel": "native_cli","reachable": true,@@ -932,7 +932,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 7,+ "contract_version": 8,"backend": "codex","channel": "native_cli","reachable": false,@@ -948,7 +948,7 @@ No candidate is an API error with a typed model-scoped state:```json{"ok": false,- "contract_version": 7,+ "contract_version": 8,"error": "probe_no_candidate","detail": "models.probe.no_candidate.waiting","supply": {@@ -1007,7 +1007,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 7,+ "contract_version": 8,"error": "provenance_unavailable","detail": "models.provenance.direct_mode"}@@ -1016,7 +1016,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 7,+ "contract_version": 8,"error": "provenance_unavailable","detail": "models.provenance.attribution_ambiguous"}diff --git a/docs/plans/model-hub-contracts/backend-model.schema.json b/docs/plans/model-hub-contracts/backend-model.schema.jsonindex 6554587ba..3bb1a67ba 100644--- a/docs/plans/model-hub-contracts/backend-model.schema.json+++ b/docs/plans/model-hub-contracts/backend-model.schema.json@@ -3,6 +3,11 @@"$id": "model-hub/backend-model.schema.json","title": "BackendModel","description": "One model exposed by a backend Agent. This is backend menu metadata, not upstream inventory and not a Route.",+ "definitions": {+ "OpenCodeOverlayProviderId": {+ "enum": ["avibe-openai", "avibe-anthropic"]+ }+ },"type": "object","required": ["id",@@ -24,7 +29,7 @@"id": {"type": "string","minLength": 1,- "description": "The exact identifier shown to and emitted by the backend Agent. OpenCode identifiers use provider/model form. Responses may echo longer identifiers persisted by older releases; mutation admission limits newly added identifiers to 256 characters."+ "description": "The exact canonical identifier shown to and emitted by the backend Agent. OpenCode stores this bare id without an overlay provider prefix. Mutation admission limits newly added identifiers to 256 characters."},"display_name": {"type": ["string", "null"],@@ -74,6 +79,10 @@"uniqueItems": true,"description": "Effort values are sent verbatim unless supports_reasoning is false. False suppresses their runtime projection without deleting the list, so returning the capability to null is lossless. An empty array means the backend omits the effort parameter."},+ "native_protocol": {+ "enum": ["openai_responses", "anthropic"],+ "description": "OpenCode only. The frontend protocol used by its generated provider; containing catalog arrays require it for OpenCode and forbid it for other backends."+ },"locked": {"type": "boolean","description": "Server-derived. A locked system row is visible but cannot be edited, removed, or reordered."diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.jsonindex 33fd90c7e..d8d6c1710 100644--- a/docs/plans/model-hub-contracts/guard-refusal.schema.json+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json@@ -62,7 +62,7 @@],"properties": {"ok": { "const": false },- "contract_version": { "const": 7 },+ "contract_version": { "const": 8 },"error": {"enum": ["source_last_supplier",@@ -117,7 +117,7 @@"examples": [{"ok": false,- "contract_version": 7,+ "contract_version": 8,"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/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex aa2b725c0..a9dc16ec6 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": 7,+ "contract_version": 8,"input_generation": {"mode": "same_run_live_files","external_snapshot": "content_fingerprint_required"@@ -357,6 +357,41 @@"builtin": "builtin","providers": "provider"}+ },+ {+ "id": "M11",+ "vocabulary": "OpenCode native protocol",+ "rule": "equality",+ "sets": [+ {+ "schema": "backend-model.schema.json",+ "paths": ["/properties/native_protocol"]+ },+ {+ "schema": "api-response.schema.json",+ "paths": [+ "/definitions/ModelCandidate/properties/native_protocol",+ "/definitions/ModelsDevResponse/properties/matches/items/properties/native_protocol"+ ]+ }+ ]+ },+ {+ "id": "M12",+ "vocabulary": "OpenCode native protocol provider ids",+ "rule": "mapping",+ "home": {+ "schema": "backend-model.schema.json",+ "path": "/properties/native_protocol"+ },+ "target": {+ "schema": "backend-model.schema.json",+ "path": "/definitions/OpenCodeOverlayProviderId"+ },+ "mapping": {+ "openai_responses": "avibe-openai",+ "anthropic": "avibe-anthropic"+ }}],"decision_tables": [diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.jsonindex d7ea834d7..716e83d92 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": 7 },+ "contract_version": { "const": 8 },"outcome": {"enum": ["observed",@@ -150,7 +150,7 @@],"examples": [{- "contract_version": 7,+ "contract_version": 8,"outcome": "observed","reachable": true,"authenticated": "authenticated",@@ -165,7 +165,7 @@]},{- "contract_version": 7,+ "contract_version": 8,"outcome": "authentication_failed","reachable": true,"authenticated": "rejected",@@ -175,7 +175,7 @@"model_metadata": []},{- "contract_version": 7,+ "contract_version": 8,"outcome": "ambiguous","reachable": true,"authenticated": "unknown",@@ -185,7 +185,7 @@"model_metadata": []},{- "contract_version": 7,+ "contract_version": 8,"outcome": "unreachable","reachable": false,"authenticated": "unknown",@@ -195,7 +195,7 @@"model_metadata": []},{- "contract_version": 7,+ "contract_version": 8,"outcome": "adapter_error","reachable": null,"authenticated": "unknown",@@ -205,7 +205,7 @@"model_metadata": []},{- "contract_version": 7,+ "contract_version": 8,"outcome": "timeout","reachable": null,"authenticated": "unknown",diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.mdindex 600270462..28131e496 100644--- a/docs/plans/model-hub-contracts/opencode-overlay.md+++ b/docs/plans/model-hub-contracts/opencode-overlay.md@@ -26,18 +26,16 @@ contract (one OpenAI-compatible provider, `vendor/model` ids); nothing of that sedit, `native_protocol` edit, gateway credential rotation) Avibe waits for active work tofinish, then restarts the serve process. Restarts are config events: no `resolution-event`of kind `channel_switch`/`switch` is emitted.-- **Nothing projectable.** When the OpenCode menu is empty (the last checked row was- removed), Avibe writes no overlay and drains and stops- the serve process; it relaunches with a fresh overlay when a projectable row exists again.- In Gateway mode a serve process never runs without an overlay, so the user's providers are- never exposed and a stale provider set never lingers in `/config/providers`.+- **Empty menu.** With no checked rows the overlay is the empty overlay —+ `enabled_providers` naming `avibe-openai` and that provider with `models: {}` — written+ through the same change-and-restart path as any other overlay; the serve process is never+ stopped or launched without an overlay in Gateway mode.## Provider entries- One provider entry per downstream protocol used by at least one checked menu row, so no- generated provider is ever empty and `enabled_providers` equals the generated set. When the- OpenCode menu is empty the existing `mapping_target_unavailable` refusal applies, no overlay- is written, and the serve process is stopped (Delivery):+ generated provider is ever empty and `enabled_providers` equals the generated set. With an+ empty menu the empty overlay (Delivery) is written instead:| `native_protocol` | provider id | `name` | `npm` | downstream endpoint || --- | --- | --- | --- | --- |diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonindex 4caad6988..ecab2f5b7 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": 7 },+ "contract_version": { "const": 8 },"backend": { "enum": ["claude", "codex", "opencode"] },"channel": { "enum": ["hub", "native_cli"] },"reachable": { "type": "boolean" },@@ -62,10 +62,10 @@}],"examples": [- { "contract_version": 7, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },- { "contract_version": 7, "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": 7, "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": 7, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },- { "contract_version": 7, "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": 8, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },+ { "contract_version": 8, "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": 8, "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": 8, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },+ { "contract_version": 8, "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 7ff37b9c4..3aa983482 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": 7 },+ "contract_version": { "const": 8 },"enabled": {"type": "boolean","description": "Persisted user intent for the managed gateway. Missing on older payloads means clients must fall back to observed health."@@ -131,7 +131,7 @@},"examples": [{- "contract_version": 7,+ "contract_version": 8,"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 3da89187b..74a054b48 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],+ "enum": [5, 6, 7, 8],"$comment": "The only versioned object that is written to disk instead of exchanged inside one request, so its released values are a set rather than a constant. A record a v5 build persisted keeps validating -- tests/fixtures/model_hub/released_v5_permission_denied.json is the evidence -- while new records carry the terminal value, which is the last member. Every other versioned object is an in-process envelope and stays pinned to that value alone.","description": "Generation that wrote this record. Nothing branches on it: readers accept every released value and the shape is identical across them."},@@ -359,7 +359,7 @@],"examples": [{- "contract_version": 7,+ "contract_version": 8,"turn_id": "turn_01k9x2m4","ts": "2026-07-29T06:32:11Z","agent": "claude",@@ -384,7 +384,7 @@"blockers": []},{- "contract_version": 7,+ "contract_version": 8,"turn_id": "turn_01k9x33p","ts": "2026-07-29T06:41:02Z","agent": "opencode",@@ -405,7 +405,7 @@"blockers": []},{- "contract_version": 7,+ "contract_version": 8,"turn_id": "turn_01k9x3zq","ts": "2026-07-29T06:48:20Z","agent": "codex",@@ -425,7 +425,7 @@]},{- "contract_version": 7,+ "contract_version": 8,"turn_id": "turn_01k9x4b7","ts": "2026-07-29T07:02:44Z","agent": "claude",@@ -445,7 +445,7 @@"blockers": []},{- "contract_version": 7,+ "contract_version": 8,"turn_id": "turn_01k9x5ca","ts": "2026-07-29T07:08:00Z","agent": "codex",diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex d4c895987..04aceed58 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -20,6 +20,7 @@ from core.handlers.model_hub.events import (EventAgent,EventReason,)+from core.handlers.model_hub.identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOLfrom core.handlers.model_hub.provenance import (ENGINE_DOWN_TURN_OUTCOME,TurnOutcomeProjectionInput,@@ -45,7 +46,7 @@ from core.handlers.model_hub.service import (from core.services.settings import load_config_or_defaultfrom core.handlers.model_hub.turn_gateway import ModelHubTurnGatewayfrom vibe.codex_config import format_toml_basic_string-from vibe.opencode_config import model_hub_runtime_provider_id+from vibe.opencode_config import managed_opencode_runtime_config_contentLaunchChannel = Literal["direct", "native_cli", "hub"]@@ -118,7 +119,8 @@ class OpenCodeOverlay:path: Pathcontent_hash: strcontent: bytes- provider_id: str+ provider_ids: tuple[str, ...]+ model_provider_ids: tuple[tuple[str, str], ...]checked_identifiers: tuple[str, ...]available_identifiers: tuple[str, ...]launches: tuple[ModelHubLaunch, ...] = field(repr=False)@@ -371,10 +373,18 @@ def build_codex_hub_launch(return overrides + list(base_args), env-def _provider_package() -> str:- # OpenCode speaks one stable frontend protocol to the local Gateway. The- # persisted exact hop selects the upstream protocol behind that boundary.- return "@ai-sdk/openai-compatible"+_OPENCODE_PROTOCOL_PROVIDERS = {+ "openai_responses": {+ "id": OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL["openai_responses"],+ "name": "Avibe · OpenAI",+ "npm": "@ai-sdk/openai",+ },+ "anthropic": {+ "id": OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL["anthropic"],+ "name": "Avibe · Anthropic",+ "npm": "@ai-sdk/anthropic",+ },+}def _provider_base_url(gateway_base_url: str) -> str:@@ -1042,16 +1052,35 @@ class ModelHubRuntimeRouter:agent = config.agents["opencode"]if agent.mode == "direct":return None- checked = tuple(model.id for model in agent.models)- if not checked:- raise ModelHubError("mapping_target_unavailable", status=409)+ checked = tuple(agent.menu.checked if agent.menu is not None else ())gateway_base_url, gateway_token = await self._gateway_credentials("opencode",process_scope="opencode:shared-server",turn_id=None,)- overlay_provider_id = model_hub_runtime_provider_id(gateway_token)+ base_url = _provider_base_url(gateway_base_url)providers: dict[str, dict[str, Any]] = {}++ def ensure_provider(native_protocol: str) -> tuple[str, dict[str, Any]]:+ provider_spec = _OPENCODE_PROTOCOL_PROVIDERS.get(native_protocol)+ if provider_spec is None:+ raise ModelHubError("mapping_target_unavailable", status=409)+ provider_id = provider_spec["id"]+ provider = providers.setdefault(+ provider_id,+ {+ "name": provider_spec["name"],+ "npm": provider_spec["npm"],+ "options": {"apiKey": gateway_token, "baseURL": base_url},+ "models": {},+ },+ )+ return provider_id, provider++ if not checked:+ ensure_provider("openai_responses")++ model_provider_ids: list[tuple[str, str]] = []projected_identifiers: list[str] = []available_identifiers: list[str] = []launches: list[ModelHubLaunch] = []@@ -1065,50 +1094,15 @@ class ModelHubRuntimeRouter:identifier,supply_channel="hub",)- menu_provider_id = resolution.menu_provider_id- menu_model_id = resolution.menu_model_id- if menu_provider_id is None or menu_model_id is None:- raise ModelHubError("mapping_target_unavailable", status=409)- inspection = (- resolution.candidate_hops[0]- if resolution.candidate_hops- else None- )- if inspection is None:- # Keep every configured route's public identifier stable in the- # overlay. Per-turn resolution still rejects unavailable hops.- inspection = (- resolution.projectable_hops[0]- if resolution.projectable_hops- else None- )- package = _provider_package()- base_url = _provider_base_url(gateway_base_url)- provider = providers.setdefault(- overlay_provider_id,- {- "name": "Avibe Model Hub",- "npm": package,- "options": {"apiKey": gateway_token, "baseURL": base_url},- "models": {},- },+ overlay_provider_id, provider = ensure_provider(+ backend_model.native_protocol or "")runtime_model = identifier- if self.turn_gateway is None:- if (- inspection is None- or inspection.source is None- or inspection.model_id is None- ):- continue- source = inspection.source- exact_model_id = inspection.model_id- prefix = await self._source_prefix(source.id)- runtime_model = f"{prefix}/{exact_model_id}"projected_model = project_opencode_public_model(backend_model)projected_model["id"] = runtime_modelprovider["models"][identifier] = projected_modelprojected_identifiers.append(identifier)+ model_provider_ids.append((identifier, overlay_provider_id))if resolution.candidate_hops:candidate = resolution.candidate_hops[0]if candidate.source is None or candidate.model_id is None:@@ -1127,25 +1121,28 @@ class ModelHubRuntimeRouter:))- if not projected_identifiers:- raise ModelHubError("mapping_target_unavailable", status=409)-content = (json.dumps(- {"$schema": "https://opencode.ai/config.json", "provider": providers},+ {+ "$schema": "https://opencode.ai/config.json",+ "enabled_providers": list(providers),+ "provider": providers,+ },ensure_ascii=True,sort_keys=True,separators=(",", ":"),)+ "\n").encode()- content_hash = hashlib.sha256(content).hexdigest()+ inline_content = managed_opencode_runtime_config_content(content).encode()+ content_hash = hashlib.sha256(inline_content).hexdigest()self._secure_write_overlay(content)return OpenCodeOverlay(path=self.overlay_path,content_hash=content_hash,content=content,- provider_id=overlay_provider_id,+ provider_ids=tuple(providers),+ model_provider_ids=tuple(model_provider_ids),checked_identifiers=tuple(projected_identifiers),available_identifiers=tuple(available_identifiers),launches=tuple(launches),@@ -1186,7 +1183,10 @@ def opencode_model_for_overlay(requested_model = opencode_requested_model_for_overlay(model, overlay)if overlay is None or requested_model is None:return requested_model- return f"{overlay.provider_id}/{requested_model}"+ provider_id = dict(overlay.model_provider_ids).get(requested_model)+ if provider_id is None:+ raise ModelHubError("mapping_target_unavailable", status=409)+ return f"{provider_id}/{requested_model}"def opencode_model_catalog_for_overlay(@@ -1195,9 +1195,18 @@ def opencode_model_catalog_for_overlay("""Project the private overlay into the model metadata needed by its turn."""payload = json.loads(overlay.content)- provider = payload.get("provider", {}).get(overlay.provider_id, {})- models = provider.get("models", {}) if isinstance(provider, dict) else {}return {- "providers": [{"id": overlay.provider_id, "models": models}],+ "providers": [+ {+ "id": provider_id,+ "models": (+ provider.get("models", {})+ if isinstance(provider, dict)+ else {}+ ),+ }+ for provider_id in overlay.provider_ids+ for provider in [payload.get("provider", {}).get(provider_id, {})]+ ],"default": {},}diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex e72f90cd3..688dc4d62 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -1153,6 +1153,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):steer_state: _OpenCodeSteerState | None = Nonepoll_server: _SteeringAwareOpenCodeServer | None = Nonemodel_hub_overlay: OpenCodeOverlay | None = None+ model_hub_turn_mode: str | None = Nonemodel_hub_launch: ModelHubLaunch | None = Nonemodel_hub_overlay_reservation: object | None = Noneserver = None@@ -1181,9 +1182,10 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):model_hub_runtime = getattr(self.controller, "model_hub_runtime", None)turn_mode = getattr(model_hub_runtime, "turn_mode", None)if callable(turn_mode):+ model_hub_turn_mode = turn_mode("opencode")bind_turn_mode(request.context,- turn_mode("opencode"),+ model_hub_turn_mode,)prepare_overlay = getattr(model_hub_runtime, "prepare_opencode_overlay", None)if callable(prepare_overlay):@@ -1378,7 +1380,11 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):# when the user has explicitly chosen a default provider in Settings.# Otherwise leave ``model_dict`` unset so OpenCode keeps using its own# routing for legacy installs.- default_provider = getattr(opencode_cfg, "default_provider", None)+ default_provider = (+ None+ if model_hub_overlay is not None+ else getattr(opencode_cfg, "default_provider", None)+ )model_dict = resolve_opencode_model_dict(model_str, default_provider)display_model_dict = resolve_opencode_model_dict(requested_model_str,diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.pyindex 897ca85af..54dc294c9 100644--- a/modules/agents/opencode/server.py+++ b/modules/agents/opencode/server.py@@ -26,14 +26,17 @@ from typing import Any, Callable, Dict, List, Optionalimport aiohttpfrom config import paths+from core.handlers.model_hub.identifiers import OPENCODE_PROVIDER_BY_NATIVE_PROTOCOLfrom core.process_isolation import isolated_subprocess_kwargs, terminate_process_treefrom core.resource_governance import is_controller_resource_governorfrom modules.agents.opencode.caller_context import ensure_plugin_installed, server_environmentfrom modules.agents.opencode.config_reconciler import OpenCodeConfigReconcilerfrom vibe import runtimefrom vibe.opencode_config import (+ OpenCodeRuntimeConfigInvalidError,get_opencode_custom_provider_adapter,load_first_opencode_user_config,+ managed_opencode_runtime_config_content as _managed_runtime_config_content,parse_jsonc_object,read_opencode_provider_auth_entries,)@@ -55,51 +58,6 @@ _DURABLE_ATTEMPT_ID_RE = re.compile(r"^atm_([0-9a-f]{32})$")_MANAGED_RUNTIME_POLICY_REVISION = "disable-native-skill-v2"-class OpenCodeRuntimeConfigInvalidError(RuntimeError):- """The inherited OpenCode runtime override cannot be safely managed."""---def _managed_runtime_config_content(raw: str | bytes | None) -> str:- """Apply Avibe-owned OpenCode runtime policy without mutating user config."""-- if raw is None:- payload: Any = {}- else:- try:- content = raw.decode("utf-8-sig") if isinstance(raw, bytes) else raw- if not isinstance(content, str):- raise TypeError("runtime config override must be text")- payload = parse_jsonc_object(content)- except (TypeError, UnicodeDecodeError, ValueError) as exc:- raise OpenCodeRuntimeConfigInvalidError(- "OpenCode runtime config override is invalid JSONC"- ) from exc- if not isinstance(payload, dict):- raise OpenCodeRuntimeConfigInvalidError(- "OpenCode runtime config override must be a JSON object"- )-- tools = payload.get("tools")- managed_tools = dict(tools) if isinstance(tools, dict) else {}- managed_tools["skill"] = False- payload["tools"] = managed_tools-- permission = payload.get("permission")- if permission is None:- managed_permission: dict[str, Any] = {}- elif isinstance(permission, str):- managed_permission = {"*": permission}- elif isinstance(permission, dict):- managed_permission = dict(permission)- else:- raise OpenCodeRuntimeConfigInvalidError(- "OpenCode runtime permission override must be a string or object"- )- managed_permission["skill"] = "deny"- payload["permission"] = managed_permission- return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":")) + "\n"--def _percent_encode_path(path: str) -> str:"""Percent-encode *path* so it is safe for an HTTP header value.@@ -124,11 +82,17 @@ def _project_model_hub_models(if isinstance(entry, dict) and isinstance(entry.get("id"), str)}for public_identifier, model_config in runtime_models.items():- if not isinstance(public_identifier, str) or "/" not in public_identifier:+ if not isinstance(public_identifier, str) or not public_identifier:continue- provider_id, model_id = public_identifier.split("/", 1)- if not provider_id or not model_id:+ native_protocol = (+ model_config.get("native_protocol")+ if isinstance(model_config, dict)+ else None+ )+ provider_id = OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL.get(native_protocol)+ if provider_id is None:continue+ model_id = public_identifierprovider = provider_index.get(provider_id)if provider is None:provider = {"id": provider_id, "name": provider_id, "models": {}}@@ -154,6 +118,7 @@ def _project_model_hub_models(public_model = dict(existing_model) if isinstance(existing_model, dict) else {}if isinstance(model_config, dict):public_model.update(model_config)+ public_model.pop("native_protocol", None)public_model["id"] = model_idmetadata = public_model.get("vibe_remote")public_metadata = dict(metadata) if isinstance(metadata, dict) else {}@@ -167,7 +132,7 @@ def _project_model_hub_models(def _public_opencode_catalog(payload: Any,*,- runtime_provider_id: str | None,+ runtime_provider_ids: tuple[str, ...],model_hub_models: dict[str, Any] | None = None,) -> Any:"""Remove private transport state and merge the desired public projection."""@@ -187,15 +152,13 @@ def _public_opencode_catalog(projected[key] = [entryfor entry in value- if runtime_provider_id is None- or _provider_id(entry) != runtime_provider_id+ if _provider_id(entry) not in runtime_provider_ids]elif isinstance(value, dict):projected[key] = {provider_id: entryfor provider_id, entry in value.items()- if runtime_provider_id is None- or provider_id != runtime_provider_id+ if provider_id not in runtime_provider_ids}connected = projected.get("connected")@@ -203,7 +166,7 @@ def _public_opencode_catalog(projected["connected"] = [provider_idfor provider_id in connected- if runtime_provider_id is None or provider_id != runtime_provider_id+ if provider_id not in runtime_provider_ids]for key in ("default", "provider"):@@ -212,8 +175,7 @@ def _public_opencode_catalog(projected[key] = {provider_id: entryfor provider_id, entry in value.items()- if runtime_provider_id is None- or provider_id != runtime_provider_id+ if provider_id not in runtime_provider_ids}providers = projected.get("providers")@@ -225,9 +187,8 @@ def _public_opencode_catalog(model = projected.get("model")if (- runtime_provider_id is not None- and isinstance(model, str)- and model.split("/", 1)[0] == runtime_provider_id+ isinstance(model, str)+ and model.split("/", 1)[0] in runtime_provider_ids):projected.pop("model", None)return projected@@ -306,7 +267,7 @@ class OpenCodeServerManager:self._model_hub_overlay_path: Optional[str] = Noneself._model_hub_overlay_hash: Optional[str] = Noneself._model_hub_overlay_content: Optional[str] = None- self._model_hub_overlay_provider_id: Optional[str] = None+ self._model_hub_overlay_provider_ids: tuple[str, ...] = ()self._model_hub_overlay_transition: tuple[Optional[str], Optional[str], object] | None = None@@ -706,34 +667,52 @@ class OpenCodeServerManager:active = info.get("active_run_sessions") if isinstance(info, dict) else Nonereturn isinstance(active, list) and bool(active)- def _active_model_hub_provider_id(self) -> str | None:- if self._model_hub_overlay_provider_id:- return self._model_hub_overlay_provider_id+ def _active_model_hub_provider_ids(self) -> tuple[str, ...]:+ if self._model_hub_overlay_provider_ids:+ return self._model_hub_overlay_provider_idsinfo = self._read_pid_file()if not self._pid_file_references_current_server(info):- return None- provider_id = (- info.get("model_hub_overlay_provider_id")+ return ()+ provider_ids = (+ info.get("model_hub_overlay_provider_ids")if isinstance(info, dict)- else None+ else ())- return provider_id if isinstance(provider_id, str) and provider_id else None+ if not isinstance(provider_ids, list) or any(+ not isinstance(provider_id, str) or not provider_id+ for provider_id in provider_ids+ ):+ return ()+ return tuple(dict.fromkeys(provider_ids))async def configure_model_hub_overlay(self, overlay: Any | None) -> object:"""Select an overlay and reserve it until the caller registers its run."""desired_path = str(overlay.path) if overlay is not None else Nonedesired_hash = str(overlay.content_hash) if overlay is not None else None- desired_provider_id = getattr(overlay, "provider_id", None)- if overlay is not None and not isinstance(desired_provider_id, str):- raise RuntimeError("Model Hub OpenCode overlay provider is unavailable")+ desired_provider_ids = getattr(overlay, "provider_ids", ())+ if overlay is not None and (+ not isinstance(desired_provider_ids, tuple)+ or not desired_provider_ids+ or any(+ not isinstance(provider_id, str) or not provider_id+ for provider_id in desired_provider_ids+ )+ or len(set(desired_provider_ids)) != len(desired_provider_ids)+ ):+ raise RuntimeError("Model Hub OpenCode overlay providers are unavailable")desired_content = Noneif overlay is not None:content = getattr(overlay, "content", None)if isinstance(content, bytes):- desired_content = content.decode("utf-8")+ desired_content = _managed_runtime_config_content(content)elif isinstance(content, str):- desired_content = content+ desired_content = _managed_runtime_config_content(content)+ if desired_content is None:+ raise RuntimeError("Model Hub OpenCode overlay content is unavailable")+ composed_hash = hashlib.sha256(desired_content.encode()).hexdigest()+ if composed_hash != desired_hash:+ raise RuntimeError("Model Hub OpenCode overlay content hash changed")drain_deadline = time.monotonic() + self._model_hub_overlay_drain_timeout_secondstransition_owner = object()owns_transition = False@@ -770,7 +749,7 @@ class OpenCodeServerManager:self._model_hub_overlay_path = desired_pathself._model_hub_overlay_hash = desired_hashself._model_hub_overlay_content = desired_content- self._model_hub_overlay_provider_id = desired_provider_id+ self._model_hub_overlay_provider_ids = desired_provider_idsself._model_hub_overlay_reservations[transition_owner] = (desired_path,desired_hash,@@ -806,7 +785,7 @@ class OpenCodeServerManager:self._model_hub_overlay_path = desired_pathself._model_hub_overlay_hash = desired_hashself._model_hub_overlay_content = desired_content- self._model_hub_overlay_provider_id = desired_provider_id+ self._model_hub_overlay_provider_ids = desired_provider_idsif await self._is_healthy():logger.info("Restarting OpenCode server after Model Hub overlay change"@@ -938,8 +917,10 @@ class OpenCodeServerManager:if self._model_hub_overlay_path and self._model_hub_overlay_hash:payload["model_hub_overlay_path"] = self._model_hub_overlay_pathpayload["model_hub_overlay_hash"] = self._model_hub_overlay_hash- if self._model_hub_overlay_provider_id:- payload["model_hub_overlay_provider_id"] = self._model_hub_overlay_provider_id+ if self._model_hub_overlay_provider_ids:+ payload["model_hub_overlay_provider_ids"] = list(+ self._model_hub_overlay_provider_ids+ )self._pid_file.write_text(json.dumps(payload))except Exception as e:logger.debug(f"Failed to write OpenCode pid file: {e}")@@ -1779,9 +1760,9 @@ class OpenCodeServerManager:raw_content = Path(self._model_hub_overlay_path).read_bytes()except OSError as exc:raise RuntimeError("Model Hub OpenCode overlay is unavailable") from exc- if hashlib.sha256(raw_content).hexdigest() != self._model_hub_overlay_hash:- raise RuntimeError("Model Hub OpenCode overlay content hash changed")- content = raw_content.decode("utf-8")+ content = _managed_runtime_config_content(raw_content)+ if hashlib.sha256(content.encode()).hexdigest() != self._model_hub_overlay_hash:+ raise RuntimeError("Model Hub OpenCode overlay content hash changed")# Inline config is OpenCode's runtime-override tier, loaded after# project config. Reasserting the exact overlay here prevents a# checked-in opencode.json from replacing Hub provider transport.@@ -2228,7 +2209,7 @@ class OpenCodeServerManager:if resp.status == 200:return _public_opencode_catalog(await resp.json(),- runtime_provider_id=self._active_model_hub_provider_id(),+ runtime_provider_ids=self._active_model_hub_provider_ids(),model_hub_models=model_hub_models,)return {"providers": [], "default": {}}@@ -2278,7 +2259,7 @@ class OpenCodeServerManager:if resp.status == 200:return _public_opencode_catalog(await resp.json(),- runtime_provider_id=self._active_model_hub_provider_id(),+ runtime_provider_ids=self._active_model_hub_provider_ids(),)return {}except Exception as e:@@ -2341,7 +2322,7 @@ class OpenCodeServerManager:if resp.status == 200:return _public_opencode_catalog(await resp.json(),- runtime_provider_id=self._active_model_hub_provider_id(),+ runtime_provider_ids=self._active_model_hub_provider_ids(),)return {}except Exception as e:diff --git a/modules/agents/opencode/utils.py b/modules/agents/opencode/utils.pyindex 7da68a9a9..5eae19ba2 100644--- a/modules/agents/opencode/utils.py+++ b/modules/agents/opencode/utils.py@@ -61,6 +61,28 @@ def _opencode_model_entry_id(model_entry: Any) -> str:return model_id if isinstance(model_id, str) else ""+def opencode_model_is_hub_projected(model_info: object) -> bool:+ if not isinstance(model_info, dict):+ return False+ metadata = model_info.get("vibe_remote")+ return (+ isinstance(metadata, dict)+ and metadata.get("model_hub_projected") is True+ )+++def opencode_model_picker_value(+ provider_id: str,+ model_id: str,+ model_info: object,+) -> str:+ """Keep Model Hub's bare identity out of OpenCode transport addressing."""++ if opencode_model_is_hub_projected(model_info):+ return model_id+ return f"{provider_id}/{model_id}" if provider_id else model_id++def _opencode_model_hub_model_ids(provider: dict) -> set[str]:"""Return models projected from Model Hub for one public provider."""@@ -76,8 +98,7 @@ def _opencode_model_hub_model_ids(provider: dict) -> set[str]:for model_id, model_info in entries:if not isinstance(model_id, str) or not isinstance(model_info, dict):continue- metadata = model_info.get("vibe_remote")- if isinstance(metadata, dict) and metadata.get("model_hub_projected") is True:+ if opencode_model_is_hub_projected(model_info):projected.add(model_id)return projected@@ -283,8 +304,28 @@ def resolve_opencode_reasoning_effort(def _find_model_variants(opencode_models: dict, target_model: Optional[str]) -> Dict[str, Any]:+ if not isinstance(opencode_models, dict):+ return {}+ if isinstance(target_model, str) and target_model:+ matches = []+ for provider in opencode_models.get("providers", []) or []:+ if not isinstance(provider, dict):+ continue+ model_info = find_opencode_model_info(+ opencode_models,+ get_opencode_provider_id(provider),+ target_model,+ )+ if opencode_model_is_hub_projected(model_info):+ matches.append(model_info)+ if len(matches) == 1:+ variants = matches[0].get("variants", {})+ return variants if isinstance(variants, dict) else {}+ if matches:+ return {}+target_provider, target_model_id = _parse_model_key(target_model)- if not target_provider or not target_model_id or not isinstance(opencode_models, dict):+ if not target_provider or not target_model_id:return {}model_info = find_opencode_model_info(opencode_models, target_provider, target_model_id)if isinstance(model_info, dict):@@ -494,9 +535,17 @@ def build_opencode_model_option_items(else:model_name = model_id- full_model = f"{provider_id}/{model_id}" if provider_id else model_id+ full_model = opencode_model_picker_value(+ provider_id,+ model_id,+ model_info,+ )is_default = defaults.get(provider_id) == model_id if provider_id else False- display = f"{provider_name}: {model_name}" if provider_name else model_name+ display = (+ model_name+ if opencode_model_is_hub_projected(model_info)+ else f"{provider_name}: {model_name}" if provider_name else model_name+ )if is_default:display += " (default)"diff --git a/tests/e2e/drivers/mock_llm_upstream.py b/tests/e2e/drivers/mock_llm_upstream.pyindex df0e7d8aa..3b650a237 100644--- a/tests/e2e/drivers/mock_llm_upstream.py+++ b/tests/e2e/drivers/mock_llm_upstream.py@@ -32,6 +32,126 @@ PROTOCOL_PATHS = {"openai_responses": "/v1/responses","openai_chat": "/v1/chat/completions",}+# Frozen from opencode-overlay.md S3/S4. The mock only captures what the real+# engine sends; the E2E cases submit each frontend body to that engine.+OPENCODE_V4_S3_PASSTHROUGH_FIXTURES = {+ "anthropic_api_key": {+ "protocol": "anthropic",+ "stored_model": "claude-sonnet-4-5",+ "frontend_body": {+ "model": "menu-model",+ "max_tokens": 128,+ "system": [+ {+ "type": "text",+ "text": "System fixture",+ "cache_control": {"type": "ephemeral"},+ }+ ],+ "messages": [{"role": "user", "content": "hello"}],+ "stream": False,+ },+ "upstream_body": {+ "model": "claude-sonnet-4-5",+ "max_tokens": 128,+ "system": [+ {+ "type": "text",+ "text": "System fixture",+ "cache_control": {"type": "ephemeral"},+ }+ ],+ "messages": [{"role": "user", "content": "hello"}],+ "stream": False,+ },+ "expected_top_level_diff": {+ "added": {},+ "removed": [],+ "changed": {+ "model": ["menu-model", "claude-sonnet-4-5"],+ },+ },+ },+ "responses_api_key": {+ "protocol": "openai_responses",+ "stored_model": "gpt-5",+ "frontend_body": {+ "model": "menu-model",+ "input": [+ {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "hello"}],+ }+ ],+ "reasoning": {"effort": "high", "summary": "auto"},+ "prompt_cache_key": "cache-fixture",+ "max_output_tokens": 128,+ "include": ["reasoning.encrypted_content"],+ "store": False,+ "stream": True,+ },+ "upstream_body": {+ "model": "gpt-5",+ "input": [+ {+ "type": "message",+ "role": "user",+ "content": [{"type": "input_text", "text": "hello"}],+ }+ ],+ "reasoning": {"effort": "high", "summary": "auto"},+ "prompt_cache_key": "cache-fixture",+ "parallel_tool_calls": True,+ "instructions": "",+ "tools": [{"type": "image_generation", "output_format": "png"}],+ "include": ["reasoning.encrypted_content"],+ "store": False,+ "stream": True,+ },+ "expected_top_level_diff": {+ "added": {+ "instructions": "",+ "parallel_tool_calls": True,+ "tools": [{"type": "image_generation", "output_format": "png"}],+ },+ "removed": ["max_output_tokens"],+ "changed": {+ "model": ["menu-model", "gpt-5"],+ },+ },+ },+}+OPENCODE_V4_S4_VARIANT_FIXTURES = {+ "openai_same_protocol": {+ "protocol": "openai_responses",+ "frontend_protocol": "openai_responses",+ "stored_model": "gpt-5",+ "variant": {"reasoningEffort": "high"},+ "upstream_fragment": {+ "reasoning": {"effort": "high", "summary": "auto"},+ },+ },+ "anthropic_same_protocol": {+ "protocol": "anthropic",+ "frontend_protocol": "anthropic",+ "stored_model": "claude-sonnet-4-5",+ "variant": {"effort": "high"},+ "upstream_fragment": {+ "output_config": {"effort": "high"},+ },+ },+ "responses_to_anthropic": {+ "protocol": "anthropic",+ "frontend_protocol": "openai_responses",+ "stored_model": "claude-sonnet-4-5",+ "variant": {"reasoningEffort": "high"},+ "upstream_fragment": {+ "thinking": {"type": "adaptive", "display": "summarized"},+ "output_config": {"effort": "high"},+ },+ },+}CAPTURED_HEADER_NAMES = ("accept","anthropic-beta",diff --git a/tests/e2e/test_model_hub_mock_upstream.py b/tests/e2e/test_model_hub_mock_upstream.pyindex ee09febf7..bb021dfb9 100644--- a/tests/e2e/test_model_hub_mock_upstream.py+++ b/tests/e2e/test_model_hub_mock_upstream.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonimport re+import shutilimport socketimport subprocessimport sys@@ -15,8 +16,15 @@ from urllib.parse import urlsplitfrom urllib.request import ProxyHandler, Request, build_openerimport pytest+import yaml-from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream+from tests.e2e.drivers.mock_llm_upstream import (+ MockLLMUpstream,+ OPENCODE_V4_S3_PASSTHROUGH_FIXTURES,+ OPENCODE_V4_S4_VARIANT_FIXTURES,+)+from tests.e2e.test_model_hub_runtime import _engine_app, _install_engine+from tests.e2e.test_model_hub_sources import _configure_protocol, _create_sourcepytestmark = pytest.mark.e2e_model_hub@@ -93,6 +101,7 @@ def _json_request(method: str = "GET",body: object | None = None,headers: dict[str, str] | None = None,+ timeout: float = 2,) -> tuple[int, dict[str, str], Any]:status, response_headers, raw = _request(base_url,@@ -100,6 +109,7 @@ def _json_request(method=method,body=body,headers=headers,+ timeout=timeout,)return status, response_headers, json.loads(raw)@@ -113,6 +123,341 @@ def _configure(base_url: str, **config: object) -> dict[str, Any]:return payload["config"]+def _top_level_diff(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:+ return {+ "added": {key: after[key] for key in after.keys() - before.keys()},+ "removed": sorted(before.keys() - after.keys()),+ "changed": {+ key: [before[key], after[key]]+ for key in before.keys() & after.keys()+ if before[key] != after[key]+ },+ }+++def _send_through_real_engine(+ model_hub_app_factory,+ mock_llm_upstream: MockLLMUpstream,+ *,+ upstream_protocol: str,+ frontend_protocol: str,+ stored_model: str,+ frontend_body: dict[str, Any],+) -> tuple[int, dict[str, Any]]:+ with _engine_app(model_hub_app_factory) as app:+ _install_engine(app)+ _configure_protocol(+ mock_llm_upstream,+ upstream_protocol,+ models=[+ {+ "id": stored_model,+ "supported_parameters": ["reasoning"],+ }+ ],+ )+ source, _ = _create_source(+ app,+ mock_llm_upstream,+ protocol=upstream_protocol,+ nonce="scn_0000opencodev4s3",+ extra=(+ {"base_url": f"{mock_llm_upstream.url}/v1"}+ if upstream_protocol == "openai_responses"+ else None+ ),+ )+ source_model = next(+ model for model in source["models"] if model["id"] == stored_model+ )+ assert "high" in source_model["reasoning_efforts"], source_model+ started = app.client.post("/api/models/runtime/start", {})+ started_body = started.json()+ assert started.status == 200, started_body+ listening = started_body["runtime"]["status"]["listening"]++ [config_path] = list(+ (+ app.avibe_home+ / "runtime"+ / "model-hub"+ / "state"+ / "instances"+ ).glob("*/config.yaml")+ )+ config = yaml.safe_load(config_path.read_text(encoding="utf-8"))+ entry_key = (+ "claude-api-key"+ if upstream_protocol == "anthropic"+ else "codex-api-key"+ )+ [credential] = config[entry_key]+ inbound = {+ **frontend_body,+ "model": f"{credential['prefix']}/{stored_model}",+ }+ _configure_protocol(+ mock_llm_upstream,+ upstream_protocol,+ models=[+ {+ "id": stored_model,+ "supported_parameters": ["reasoning"],+ }+ ],+ )+ path = (+ "/v1/messages"+ if frontend_protocol == "anthropic"+ else "/v1/responses"+ )+ auth_header = (+ {"X-Api-Key": config["api-keys"][0]}+ if frontend_protocol == "anthropic"+ else {"Authorization": f"Bearer {config['api-keys'][0]}"}+ )+ status, _, response_body = _request(+ f"http://{listening['host']}:{listening['port']}",+ path,+ method="POST",+ body=inbound,+ headers=auth_header,+ timeout=20,+ )+ captured = [+ request+ for request in mock_llm_upstream.requests()+ if request["path"]+ == (+ "/v1/messages"+ if upstream_protocol == "anthropic"+ else "/v1/responses"+ )+ ]+ assert len(captured) == 1, {+ "engine_status": status,+ "engine_body": response_body[:1000].decode("utf-8", errors="replace"),+ "upstream_requests": mock_llm_upstream.requests(),+ }+ return status, captured[0]["body"]+++def _send_through_opencode_gateway_engine(+ model_hub_app_factory,+ mock_llm_upstream: MockLLMUpstream,+ *,+ upstream_protocol: str,+ native_protocol: str,+ stored_model: str,+ variant: dict[str, Any],+) -> dict[str, Any]:+ binary = shutil.which("opencode")+ if binary is None:+ pytest.skip("OpenCode executable is unavailable")+ menu_model = "menu-model"+ upstream_path = (+ "/v1/messages"+ if upstream_protocol == "anthropic"+ else "/v1/responses"+ )+ with _engine_app(model_hub_app_factory) as app:+ configured = app.client.post(+ "/api/config",+ {"agents": {"opencode": {"enabled": True, "cli_path": binary}}},+ )+ assert configured.status == 200, configured.json()+ _install_engine(app)+ _configure_protocol(+ mock_llm_upstream,+ upstream_protocol,+ models=[+ {+ "id": stored_model,+ "supported_parameters": ["reasoning"],+ }+ ],+ )+ source, _ = _create_source(+ app,+ mock_llm_upstream,+ protocol=upstream_protocol,+ nonce="scn_0000opencodev4s4",+ extra=(+ {"base_url": f"{mock_llm_upstream.url}/v1"}+ if upstream_protocol == "openai_responses"+ else None+ ),+ )+ source_model = next(+ model for model in source["models"] if model["id"] == stored_model+ )+ assert "high" in source_model["reasoning_efforts"], source_model+ sources = app.client.put(+ "/api/models/agents/opencode/sources",+ {"order": [source["id"]]},+ )+ assert sources.status == 200, sources.json()+ current_models = app.client.get("/api/models/agents/opencode/models")+ current_body = current_models.json()+ assert current_models.status == 200, current_body+ baseline = current_body["agent"]["catalog_models"]+ row = {+ "id": menu_model,+ "origin": "manual",+ "supports_reasoning": True,+ "reasoning_efforts": ["high"],+ "native_protocol": native_protocol,+ }+ models = app.client.put(+ "/api/models/agents/opencode/models",+ {"baseline": baseline, "models": [row]},+ )+ assert models.status == 200, models.json()+ mode = app.client.patch(+ "/api/models/agents/opencode/mode",+ {"mode": "hub"},+ )+ assert mode.status == 200, mode.json()+ chain = app.client.put(+ f"/api/models/agents/opencode/chain?model={menu_model}",+ {+ "hops": [+ {"source_id": source["id"], "model_id": stored_model}+ ]+ },+ )+ assert chain.status == 200, chain.json()+ started = app.client.post("/api/models/runtime/start", {})+ assert started.status == 200, started.json()++ agent = app.client.post(+ "/api/agents",+ {+ "name": "opencode-v4-e2e",+ "backend": "opencode",+ "model": menu_model,+ "reasoning_effort": "high",+ "system_prompt": "System fixture",+ },+ )+ assert agent.status == 200, agent.json()+ project = app.client.post(+ "/api/projects",+ {+ "folder_path": str(app.runtime_root),+ "display_name": "OpenCode v4 E2E",+ },+ )+ assert project.status == 201, project.json()+ session = app.client.post(+ "/api/sessions",+ {+ "project_id": project.json()["id"],+ "agent_name": "opencode-v4-e2e",+ "model": menu_model,+ "reasoning_effort": "high",+ },+ )+ assert session.status == 201, session.json()++ _configure_protocol(+ mock_llm_upstream,+ upstream_protocol,+ models=[+ {+ "id": stored_model,+ "supported_parameters": ["reasoning"],+ }+ ],+ )+ sent = app.client.post(+ f"/api/sessions/{session.json()['id']}/messages",+ {"text": "hello"},+ )+ assert sent.status == 202, sent.json()+ deadline = time.monotonic() + 30+ captured: list[dict[str, Any]] = []+ while time.monotonic() < deadline:+ captured = [+ request+ for request in mock_llm_upstream.requests()+ if request["path"] == upstream_path+ and "You are a title generator"+ not in json.dumps(request["body"], sort_keys=True)+ ]+ if captured:+ break+ time.sleep(0.1)+ assert len(captured) == 1, app.diagnostics()+ overlay = json.loads(+ (+ app.avibe_home+ / "runtime"+ / "model-hub"+ / "opencode-overlay.json"+ ).read_text(encoding="utf-8")+ )+ provider_id = {+ "anthropic": "avibe-anthropic",+ "openai_responses": "avibe-openai",+ }[native_protocol]+ assert overlay["provider"][provider_id]["models"][menu_model]["variants"][+ "high"+ ] == variant+ return captured[0]["body"]+++ "fixture",+ OPENCODE_V4_S3_PASSTHROUGH_FIXTURES.values(),+ ids=OPENCODE_V4_S3_PASSTHROUGH_FIXTURES,+)+def test_opencode_v4_s3_engine_diffs_are_frozen_against_mock_capture(+ model_hub_app_factory,+ mock_llm_upstream,+ fixture: dict[str, Any],+) -> None:+ status, captured_body = _send_through_real_engine(+ model_hub_app_factory,+ mock_llm_upstream,+ upstream_protocol=fixture["protocol"],+ frontend_protocol=fixture["protocol"],+ stored_model=fixture["stored_model"],+ frontend_body=fixture["frontend_body"],+ )++ assert status == 200+ assert captured_body == fixture["upstream_body"]+ assert _top_level_diff(+ fixture["frontend_body"],+ captured_body,+ ) == fixture["expected_top_level_diff"]+++ "fixture",+ OPENCODE_V4_S4_VARIANT_FIXTURES.values(),+ ids=OPENCODE_V4_S4_VARIANT_FIXTURES,+)+def test_opencode_v4_s4_variant_shapes_are_frozen_against_mock_capture(+ model_hub_app_factory,+ mock_llm_upstream,+ fixture: dict[str, Any],+) -> None:+ captured_body = _send_through_opencode_gateway_engine(+ model_hub_app_factory,+ mock_llm_upstream,+ upstream_protocol=fixture["protocol"],+ native_protocol=fixture["frontend_protocol"],+ stored_model=fixture["stored_model"],+ variant=fixture["variant"],+ )++ assert captured_body["model"] == fixture["stored_model"]+ for key, value in fixture["upstream_fragment"].items():+ assert captured_body.get(key) == value, captured_body++@pytest.mark.parametrize("protocol", PROTOCOL_CASES)def test_mock_upstream_inventory_and_buffered_protocol_shapes(mock_llm_upstream, protocol: strdiff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.pyindex f32f649f6..723543886 100644--- a/tests/e2e/test_model_hub_runtime.py+++ b/tests/e2e/test_model_hub_runtime.py@@ -599,7 +599,7 @@ def test_a1_feature_flag_disables_the_complete_models_api(assert response.status == 404, (method, path, body)assert body == {"ok": False,- "contract_version": 7,+ "contract_version": 8,"error": "feature_disabled",}diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.pyindex f4b17d764..22fc394dd 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 = 7+CONTRACT_VERSION = 8MENU_MODEL = "claude-sonnet-4-6"SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.pyindex b60d49b80..4f9abc0e5 100644--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py@@ -313,7 +313,7 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ordclaude_model = fixed_model("claude")codex_model = fixed_model("codex")- opencode_model = "custom/route-model"+ opencode_model = "route-model"models = (claude_model, codex_model, "route-model")first = source("src_delete01", models)doomed = source("src_delete02", models)@@ -335,7 +335,12 @@ def test_mh_source_delete_001_removes_every_reference_and_preserves_survivor_ordagent = config.agents[backend]if backend == "opencode":agent.menu.checked = [opencode_model]- agent.models = [ModelHubBackendModelConfig(id=opencode_model)]+ agent.models = [+ ModelHubBackendModelConfig(+ id=opencode_model,+ native_protocol="openai_responses",+ )+ ]agent.routes[menu_model] = ModelHubRouteConfig(hops=tuple(ModelHubRouteHopConfig(item.id, upstream_model) for item in (first, doomed, last)))diff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.pyindex 99d6c8114..918ab742a 100644--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py@@ -60,7 +60,7 @@ class MemoryStore:def _requested_model(backend: str) -> str:if backend == "opencode":- return "anthropic/model-live"+ return "model-live"return model_hub_fixed_menu_ids(backend)[0]@@ -205,7 +205,10 @@ def _config(*sources: ModelHubSourceConfig) -> ModelHubConfig:)if backend == "opencode":agent.models = [- ModelHubBackendModelConfig(id=_requested_model(backend))+ ModelHubBackendModelConfig(+ id=_requested_model(backend),+ native_protocol="anthropic",+ )]assert agent.menu is not Noneagent.menu.checked = [_requested_model(backend)]diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 354f20a61..0428ec5a9 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -907,7 +907,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"] == 7+ assert runtime["contract_version"] == 8assert runtime["status"]["health"] == "ok"_assert_valid("runtime-dependency.schema.json", runtime)@@ -1125,7 +1125,7 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 7, "status": {"health": "ok"}}+ return {"contract_version": 8, "status": {"health": "ok"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1142,7 +1142,7 @@ def test_runtime_stop_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 7, "status": {"health": "not_started"}}+ return {"contract_version": 8, "status": {"health": "not_started"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1159,7 +1159,7 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 7, "status": {"health": "installing"}}+ return {"contract_version": 8, "status": {"health": "installing"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1903,11 +1903,8 @@ def test_source_create_nonce_owns_permanent_credential_through_cancellation(tmp_asyncio.run(scenario())-def test_agents_endpoint_projects_builtin_models_and_standard_vendors(tmp_path):- """Integration (2026-07-24): list_agents() carries the read-only builtin_models /- standard_vendors projections straight from the backend modules, so the UI never- hand-mirrors a fixed menu or the OpenCode vendor list (agent-supply v1.2)."""- from core.handlers.model_hub.identifiers import STANDARD_OPENCODE_VENDOR_IDS+def test_agents_endpoint_projects_builtin_models(tmp_path):+ """list_agents() carries each fixed menu from the backend catalog."""from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalogservice, _store, _adapter = _service(tmp_path)@@ -1920,10 +1917,8 @@ def test_agents_endpoint_projects_builtin_models_and_standard_vendors(tmp_path):expected = [entry["id"] for entry in backend_model_entries(backend, catalog)]assert expected, f"bundled catalog must list built-in {backend} models"assert agents[backend]["builtin_models"] == expected- assert agents[backend]["standard_vendors"] is Noneassert agents["opencode"]["builtin_models"] is None- assert agents["opencode"]["standard_vendors"] == sorted(STANDARD_OPENCODE_VENDOR_IDS)def test_agents_project_one_shared_backend_catalog_contract(tmp_path):@@ -1952,12 +1947,67 @@ def test_agents_project_one_shared_backend_catalog_contract(tmp_path):assert agents["opencode"]["catalog_models"] == []+def test_catalog_model_protocol_condition_is_identical_in_both_contracts():+ model = {+ "id": "fixture-model",+ "display_name": None,+ "origin": "manual",+ "models_dev_id": None,+ "context_window": None,+ "max_output_tokens": None,+ "input_modalities": [],+ "output_modalities": [],+ "supports_tools": None,+ "supports_reasoning": None,+ "reasoning_efforts": [],+ "locked": False,+ "routeable": True,+ }+ supply_validator = Draft7Validator(+ _schema("agent-supply.schema.json"),+ registry=_api_response_registry(),+ )+ catalog_validator = Draft7Validator(+ {"$ref": "model-hub/api-response.schema.json#/definitions/AgentCatalogResponse"},+ registry=_api_response_registry(),+ )++ for backend in ("claude", "codex", "opencode"):+ for carries_protocol in (False, True):+ row = {+ **model,+ **(+ {"native_protocol": "openai_responses"}+ if carries_protocol+ else {}+ ),+ }+ expected_valid = carries_protocol is (backend == "opencode")+ supply = {+ "backend": backend,+ "mode": "hub",+ "menu_kind": "open" if backend == "opencode" else "fixed",+ "catalog_models": [row],+ }+ catalog = {+ "ok": True,+ "contract_version": CONTRACT_VERSION,+ "agent": {+ "backend": backend,+ "mode": "hub",+ "catalog_models": [row],+ },+ }+ assert (not list(supply_validator.iter_errors(supply))) is expected_valid+ assert (not list(catalog_validator.iter_errors(catalog))) is expected_valid++@pytest.mark.parametrize(("backend", "model_id"),(("claude", "claude-deepseek-v4"),("codex", "deepseek-v4"),- ("opencode", "aihub/deepseek-v4"),+ ("opencode", "deepseek-v4"),),)def test_backend_catalog_add_edit_and_runtime_refresh(@@ -1988,6 +2038,8 @@ def test_backend_catalog_add_edit_and_runtime_refresh("locked": False,"routeable": True,}+ if backend == "opencode":+ added["native_protocol"] = "openai_responses"response = asyncio.run(service.set_agent_models(backend, baseline, [*baseline, added]))@@ -2207,7 +2259,7 @@ def test_backend_catalog_candidates_project_builtin_provider_and_current_rows()-def test_opencode_candidates_collapse_custom_vendors_into_one_identity(tmp_path):+def test_opencode_candidates_collapse_suppliers_into_one_bare_identity(tmp_path):service, store, _adapter = _service(tmp_path)sources = [ModelHubSourceConfig(@@ -2230,12 +2282,48 @@ def test_opencode_candidates_collapse_custom_vendors_into_one_identity(tmp_path)candidates = service.agent_model_candidates("opencode")assert candidates["builtin"] == []- assert [item["id"] for item in candidates["providers"]] == ["custom/shared-model"]+ assert [item["id"] for item in candidates["providers"]] == ["shared-model"]+ assert candidates["providers"][0]["native_protocol"] == "openai_responses"assert [supplier["source_id"] for supplier in candidates["providers"][0]["suppliers"]] == [source.id for source in sources]+def test_candidate_protocol_projection_is_total_only_for_opencode(tmp_path):+ from vibe.models_dev_catalog import native_protocol_for_model_id++ service, store, _adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_protocol1",+ kind="api_key",+ vendor="custom",+ display_name="Protocol fixtures",+ protocol="openai_chat",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ ModelHubModelConfig(id="claude-protocol-fixture", provenance="discovered"),+ ModelHubModelConfig(id="gpt-protocol-fixture", provenance="discovered"),+ ],+ credential_ref="cred_protocol1",+ )+ store.config.sources = [source]+ for agent in store.config.agents.values():+ agent.sources.order = [source.id]++ for backend in ("claude", "codex", "opencode"):+ candidates = service.agent_model_candidates(backend)+ rows = [row for group in candidates.values() for row in group]+ assert rows+ for row in rows:+ assert ("native_protocol" in row) is (backend == "opencode")+ if backend == "opencode":+ assert row["native_protocol"] == native_protocol_for_model_id(+ row["id"]+ )++def test_candidates_exclude_ids_the_backend_write_would_reject(monkeypatch, tmp_path):service, store, _adapter = _service(tmp_path)invalid_claude_id = "not-a-claude-family"@@ -3663,13 +3751,23 @@ def test_opencode_public_models_cross_the_controller_rpc_boundary(monkeypatch):def rpc(operation, payload=None):calls.append((operation, payload))- return {"custom/current-model": {"id": "custom/current-model"}}+ return {+ "current-model": {+ "id": "current-model",+ "native_protocol": "openai_responses",+ }+ }monkeypatch.setattr(model_hub_client, "_rpc_sync", rpc)models = ModelHubRemoteService().opencode_public_models()- assert models == {"custom/current-model": {"id": "custom/current-model"}}+ assert models == {+ "current-model": {+ "id": "current-model",+ "native_protocol": "openai_responses",+ }+ }assert calls == [("get_opencode_public_models", None)]@@ -3707,7 +3805,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):assert response.status_code == 200assert response.get_json() == {"ok": True,- "contract_version": 7,+ "contract_version": 8,"agent": {"backend": "codex","mode": "hub",@@ -4264,7 +4362,10 @@ def test_opencode_options_route_passes_controller_projection(monkeypatch):from vibe import apiprojection = {- "custom/current-model": {"id": "custom/current-model"},+ "current-model": {+ "id": "current-model",+ "native_protocol": "openai_responses",+ },}calls = []@@ -7986,7 +8087,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"] == 7+ assert runtime["contract_version"] == 8_assert_valid("runtime-dependency.schema.json", runtime)diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex b0662b162..061f5c278 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -106,7 +106,7 @@ def test_protocol_vocabulary_matches_authority_and_rejects_removed_alias():def test_unsaved_observation_schema_closes_all_terminal_shapes():schema = _schema("observation-result.schema.json")- assert schema["properties"]["contract_version"]["const"] == 7+ assert schema["properties"]["contract_version"]["const"] == 8assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(member.value for member in ObservationOutcome)@@ -130,7 +130,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():def payload(observation: SourceObservation) -> dict:return {- "contract_version": 7,+ "contract_version": 8,"outcome": observation.outcome.value,"reachable": observation.reachable,"authenticated": (@@ -349,17 +349,35 @@ def test_source_validator_enforces_final_cross_field_and_inventory_rules():assert parsed.base_url == "https://relay.example/v1?api-version=2026-07-23"-def test_persisted_model_hub_identifiers_share_the_canonical_validation_boundary():+def test_opencode_persisted_rows_use_bare_canonical_ids_and_require_native_protocol():payload = ModelHubConfig().to_payload()opencode = payload["agents"]["opencode"]opencode["menu"]["checked"] = ["gpt-5"]opencode["routes"]["gpt-5"] = {"hops": []}- with pytest.raises(ValueError):- ModelHubConfig.from_payload(payload)+ opencode["models"] = [+ ModelHubBackendModelConfig(+ id="gpt-5",+ native_protocol="openai_responses",+ ).to_payload()+ ]+ parsed = ModelHubConfig.from_payload(payload)+ assert parsed.agents["opencode"].models[0].id == "gpt-5"++ pre_v4 = copy.deepcopy(payload)+ pre_v4["agents"]["opencode"]["models"][0].pop("native_protocol")+ with pytest.raises(ValueError, match="native_protocol"):+ ModelHubConfig.from_payload(pre_v4)++ missing_menu = copy.deepcopy(payload)+ missing_menu["agents"]["opencode"].pop("menu")+ with pytest.raises(ValueError, match="menu.*required"):+ ModelHubConfig.from_payload(missing_menu)payload = ModelHubConfig().to_payload()opencode = payload["agents"]["opencode"]- opencode["routes"]["custom/authorization: sk-test-credential-material"] = {"hops": []}+ opencode["routes"][" authorization: sk-test-credential-material "] = {+ "hops": []+ }with pytest.raises(ValueError):ModelHubConfig.from_payload(payload)@@ -505,16 +523,27 @@ def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():for raw_example in _schema("agent-supply.schema.json")["examples"]:example = {- key: value for key, value in raw_example.items() if key not in {"builtin_models", "standard_vendors"}+ key: value for key, value in raw_example.items() if key != "builtin_models"}+ if raw_example["backend"] == "opencode":+ example["models"] = [+ ModelHubBackendModelConfig(+ id=model_id,+ native_protocol=(+ "anthropic"+ if model_id.startswith("claude-")+ else "openai_responses"+ ),+ ).to_payload()+ for model_id in raw_example["menu"]["checked"]+ ]agent = ModelHubAgentSupplyConfig.from_payload(example)- # `builtin_models` and `standard_vendors` are read-only endpoint- # projections (v1.2), not persisted config — reconstruct them+ # `builtin_models` is a read-only endpoint projection, not persisted+ # config. Reconstruct it# the way `_agent_payload` merges them onto to_payload().serialized = {**agent.to_payload(),"builtin_models": raw_example.get("builtin_models"),- "standard_vendors": raw_example.get("standard_vendors"),}serialized.pop("models", None)serialized.pop("removed_model_ids", None)@@ -680,7 +709,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():route_refusal = {"ok": False,- "contract_version": 7,+ "contract_version": 8,"error": "source_in_route_chain","detail": "modelHub.errors.source_in_route_chain","would_remove_hops": [hop],@@ -696,7 +725,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():}candidate_refusal = {"ok": False,- "contract_version": 7,+ "contract_version": 8,"error": "candidate_suppliers_changed","detail": "modelHub.errors.candidate_suppliers_changed","changed": {@@ -768,18 +797,17 @@ def test_agent_supply_contract_accepts_unmapped_native_alias_selection():"menu": None,"model_supply": [{"model_id": "claude-opus-4-5", "chain_length": 1}],"builtin_models": ["claude-opus-4-5"],- "standard_vendors": None,"named_agents": [],}_assert_valid("agent-supply.schema.json", payload)-def test_v7_mirror_registry_is_executable_and_complete():+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"] == 7+ assert registry["contract_version"] == 8ids = [entry["id"] for entry in registry["entries"]]assert idsassert len(ids) == len(set(ids))@@ -997,8 +1025,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],- "expected": [5, 6, 7],+ "values": [6, 7, 8],+ "expected": [5, 6, 7, 8],} in result["findings"]@@ -1139,7 +1167,6 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():"model_supply": [],"named_agents": [],"builtin_models": [],- "standard_vendors": None,}supply_validator.validate(base_supply)@@ -1292,7 +1319,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():with pytest.raises(ValidationError):chain_validator.validate(interrupted)exact_hop = {- "contract_version": 7,+ "contract_version": 8,"backend": "claude","model_id": "claude-opus-4-6","chain": [@@ -1519,10 +1546,12 @@ def test_backend_catalog_without_removed_ids_loads_empty_set(tmp_path):def _legacy_model_hub_payload(current: dict) -> dict:- """Build the persisted v3.0.9 Model Hub shape from a current fixture."""+ """Build the released Claude/Codex v3.0.9 shape from a current fixture."""agents = {}for backend, agent in current["agents"].items():+ if backend == "opencode":+ continueagents[backend] = {"backend": agent["backend"],"mode": agent["mode"],@@ -1539,25 +1568,52 @@ def _legacy_model_hub_payload(current: dict) -> dict:}-def test_config_reload_migrates_v3_model_hub_shape_and_persists_backup(monkeypatch, tmp_path):+def test_config_reload_rejects_pre_v4_opencode_shape_on_invalid_config_path(+ monkeypatch,+ tmp_path,+):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)- payload["model_hub"] = _legacy_model_hub_payload(payload["model_hub"])+ opencode = payload["model_hub"]["agents"]["opencode"]+ opencode["menu"] = {"view": "featured", "checked": ["openai/gpt-5"]}+ opencode["models"] = [+ {+ "id": "openai/gpt-5",+ "display_name": "GPT-5",+ "origin": "manual",+ "models_dev_id": None,+ "context_window": None,+ "max_output_tokens": None,+ "input_modalities": [],+ "output_modalities": [],+ "supports_tools": None,+ "supports_reasoning": None,+ "reasoning_efforts": [],+ }+ ]+ opencode["routes"] = {"openai/gpt-5": {"hops": []}}+ opencode["mappings"] = [+ {+ "builtin_id": "openai/gpt-5",+ "target_model_id": "gpt-5",+ "enabled": True,+ }+ ]payload["migration_sentinel"] = {"keep": True}config_path = tmp_path / "config.json"- config_path.write_text(json.dumps(payload), encoding="utf-8")+ original = json.dumps(payload)+ config_path.write_text(original, encoding="utf-8")loaded = V2Config.load(config_path=config_path)- assert loaded.load_warnings == ()- assert set(loaded.model_hub.agents["claude"].routes) == set(ModelHubConfig().agents["claude"].routes)- persisted = json.loads(config_path.read_text(encoding="utf-8"))- assert set(persisted["model_hub"]) == {"enabled", "sources", "agents"}- assert persisted["model_hub"]["enabled"] is False- assert persisted["migration_sentinel"] == {"keep": True}- backups = list(config_path.parent.glob("config.json.bak-model-hub-migration-*"))+ assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()+ assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]+ assert config_path.read_text(encoding="utf-8") == original+ backups = list(config_path.parent.glob("config.json.bak-recovery-*"))assert backupsassert stat.S_IMODE(backups[0].stat().st_mode) == 0o600+ migration_source = inspect.getsource(v2_config._migrate_legacy_model_hub_payload)+ assert "opencode" not in migration_sourcedef test_config_reload_recovers_malformed_legacy_collections(monkeypatch, tmp_path):@@ -1993,40 +2049,6 @@ def test_config_reload_recovers_backend_ineligible_legacy_custom_source_order(assert config_path.read_text(encoding="utf-8") == original-def test_config_reload_preserves_enabled_unchecked_legacy_opencode_mapping(monkeypatch, tmp_path):- monkeypatch.setenv("AVIBE_HOME", str(tmp_path))- source = copy.deepcopy(_schema("source.schema.json")["examples"][1])- source["models"][0]["provenance"] = source["models"][0].pop("origin")- source["models"][0].pop("reasoning_efforts")- current = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)- legacy = _legacy_model_hub_payload(current["model_hub"])- legacy["sources"] = [source]- legacy["agents"]["opencode"]["mode"] = "hub"- legacy["agents"]["opencode"]["sources"] = {- "policy": "custom",- "order": [source["id"]],- }- legacy["agents"]["opencode"]["menu"] = {"view": "featured", "checked": []}- legacy["agents"]["opencode"]["mappings"] = [- {- "builtin_id": "custom/glm-5.2-air",- "target_model_id": "glm-5.2-air",- "enabled": True,- }- ]- current["model_hub"] = legacy- config_path = tmp_path / "config.json"- config_path.write_text(json.dumps(current), encoding="utf-8")-- loaded = V2Config.load(config_path=config_path)-- route = loaded.model_hub.agents["opencode"].routes["custom/glm-5.2-air"]- assert [(hop.source_id, hop.model_id) for hop in route.hops] == [- (source["id"], source["models"][0]["id"]),- ]- assert loaded.load_warnings == ()--def test_config_reload_keeps_legacy_hub_subscription_backend_specific(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))source = copy.deepcopy(_schema("source.schema.json")["examples"][0])@@ -2974,11 +2996,12 @@ def test_persisted_hub_config_requires_explicit_complete_route_rows():dynamic["agents"]["opencode"]["mode"] = "hub"dynamic["agents"]["opencode"]["menu"] = {"view": "featured",- "checked": ["custom/model"],+ "checked": ["model"],}dynamic["agents"]["opencode"]["models"] = [{- "id": "custom/model",+ "id": "model",+ "native_protocol": "openai_responses","display_name": None,"origin": "manual","models_dev_id": None,@@ -2992,14 +3015,14 @@ def test_persisted_hub_config_requires_explicit_complete_route_rows():}]dynamic["agents"]["opencode"]["routes"] = {}- with pytest.raises(ValueError, match="missing menu model 'custom/model'"):+ with pytest.raises(ValueError, match="missing menu model 'model'"):ModelHubConfig.from_payload(dynamic)dormant = json.loads(json.dumps(payload))- dormant["agents"]["opencode"]["routes"]["openai/dormant-model"] = {"hops": []}+ dormant["agents"]["opencode"]["routes"]["dormant-model"] = {"hops": []}restored = ModelHubConfig.from_payload(dormant)assert restored.agents["opencode"].models == []- assert "openai/dormant-model" in restored.agents["opencode"].routes+ assert "dormant-model" in restored.agents["opencode"].routesdef test_backend_model_modalities_match_the_contract_directions():diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex 60290c92b..492a1bd48 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -27,6 +27,7 @@ from modules.agents.model_hub import (opencode_requested_model_for_overlay,persisted_launch_identity,)+from modules.agents.opencode.agent import resolve_opencode_model_dictdef hub_launch(**overrides) -> ModelHubLaunch:@@ -212,30 +213,39 @@ def test_codex_hub_launch_uses_toml_safe_catalog_path(tmp_path):assert tomllib.loads(f"path = {encoded_path}\n")["path"] == str(catalog_path)-def test_opencode_overlay_requires_exact_checked_identifier():+def test_opencode_overlay_addresses_bare_ids_through_their_native_provider():overlay = SimpleNamespace(- provider_id="avibe-model-hub-runtime",- checked_identifiers=("openai/gpt-5", "custom/gpt-5"),- available_identifiers=("openai/gpt-5", "custom/gpt-5"),- )- assert opencode_requested_model_for_overlay("openai/gpt-5", overlay) == (- "openai/gpt-5"+ model_provider_ids=(+ ("gpt-5", "avibe-openai"),+ ("claude-opus-5", "avibe-anthropic"),+ ("moonshotai/kimi-k2", "avibe-openai"),+ ),+ checked_identifiers=("gpt-5", "claude-opus-5", "moonshotai/kimi-k2"),+ available_identifiers=("gpt-5", "claude-opus-5", "moonshotai/kimi-k2"),)- assert opencode_model_for_overlay("openai/gpt-5", overlay) == (- "avibe-model-hub-runtime/openai/gpt-5"+ assert opencode_requested_model_for_overlay("gpt-5", overlay) == "gpt-5"+ assert opencode_model_for_overlay("gpt-5", overlay) == "avibe-openai/gpt-5"+ assert opencode_model_for_overlay("claude-opus-5", overlay) == (+ "avibe-anthropic/claude-opus-5")+ slash_model = opencode_model_for_overlay("moonshotai/kimi-k2", overlay)+ assert slash_model == "avibe-openai/moonshotai/kimi-k2"+ assert resolve_opencode_model_dict(slash_model, default_provider=None) == {+ "providerID": "avibe-openai",+ "modelID": "moonshotai/kimi-k2",+ }with pytest.raises(ModelHubError):- opencode_model_for_overlay("gpt-5", overlay)+ opencode_model_for_overlay("missing", overlay)-def test_opencode_overlay_never_repeats_add_time_bare_identifier_matching():+def test_opencode_overlay_never_repairs_a_prefixed_identifier():overlay = SimpleNamespace(- provider_id="avibe-model-hub-runtime",- checked_identifiers=("openai/gpt-5",),- available_identifiers=("openai/gpt-5",),+ model_provider_ids=(("gpt-5", "avibe-openai"),),+ checked_identifiers=("gpt-5",),+ available_identifiers=("gpt-5",),)with pytest.raises(ModelHubError):- opencode_model_for_overlay("gpt-5", overlay)+ opencode_model_for_overlay("openai/gpt-5", overlay)def test_fallback_launch_identity_is_stable_for_same_route():diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 3334e767b..6a2cff3a3 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -724,7 +724,7 @@ class MemoryStore:self.requested_models = {"claude": "shared-model","codex": "shared-model",- "opencode": "openai/shared-model",+ "opencode": "shared-model",}def load(self) -> ModelHubConfig:@@ -1199,7 +1199,7 @@ def _config(sources: list[ModelHubSourceConfig]) -> ModelHubConfig:agent.sources = ModelHubAgentSourcesConfig(order=[source.id for source in eligible],)- requested_model = "openai/shared-model" if backend == "opencode" else "shared-model"+ requested_model = "shared-model"agent.routes[requested_model] = ModelHubRouteConfig(hops=tuple(ModelHubRouteHopConfig(@@ -1210,9 +1210,12 @@ def _config(sources: list[ModelHubSourceConfig]) -> ModelHubConfig:))agents["opencode"].models = [- ModelHubBackendModelConfig(id="openai/shared-model")+ ModelHubBackendModelConfig(+ id="shared-model",+ native_protocol="openai_responses",+ )]- agents["opencode"].menu.checked = ["openai/shared-model"]+ agents["opencode"].menu.checked = ["shared-model"]return ModelHubConfig(sources=sources, agents=agents)@@ -2363,7 +2366,7 @@ def test_opencode_gateway_round_trips_aliased_tool_names(tmp_path: Path) -> Noneresponse = await client.post(f"{base_url}/v1/chat/completions",json={- "model": "openai/shared-model",+ "model": "shared-model","messages": [{"role": "user", "content": "update the list"}],"tools": [{@@ -5131,7 +5134,7 @@ def test_ambiguous_mixed_and_opencode_attempts_leave_no_record(registry.begin_gateway_request(backend="opencode",token=opencode_token,- requested_model_id="openai/shared-model",+ requested_model_id="shared-model",)is None)@@ -5298,15 +5301,17 @@ def test_opencode_overlay_projects_menu_identity_to_exact_hop_model(tmp_path: Pasource.models[0].reasoning_efforts = ["medium"]config = _config([source])agent = config.agents["opencode"]- agent.routes.pop("openai/shared-model")- agent.routes["openai/menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),))+ agent.routes.pop("shared-model")+ agent.routes["menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),))agent.models = [ModelHubBackendModelConfig(- id="openai/menu-model",+ id="menu-model",+ native_protocol="openai_responses",+ supports_reasoning=True,reasoning_efforts=["low", "high"],)]- agent.menu.checked = ["openai/menu-model"]+ agent.menu.checked = ["menu-model"]service = _service(tmp_path, sources=[source])service.store.config = configgateway = SimpleNamespace(@@ -5322,19 +5327,26 @@ def test_opencode_overlay_projects_menu_identity_to_exact_hop_model(tmp_path: Paassert overlay is not Nonepayload = json.loads(overlay.content)- assert overlay.provider_id.startswith("avibe-model-hub-")- assert overlay.provider_id != "avibe-model-hub"- provider = payload["provider"][overlay.provider_id]- assert provider["models"]["openai/menu-model"]["id"] == "openai/menu-model"- assert provider["models"]["openai/menu-model"]["variants"] == {+ assert overlay.provider_ids == ("avibe-openai",)+ assert payload["enabled_providers"] == ["avibe-openai"]+ provider = payload["provider"]["avibe-openai"]+ assert provider["name"] == "Avibe · OpenAI"+ assert provider["npm"] == "@ai-sdk/openai"+ assert provider["options"] == {+ "apiKey": "gateway-token",+ "baseURL": "http://127.0.0.1:19000/v1",+ }+ assert provider["models"]["menu-model"]["id"] == "menu-model"+ assert provider["models"]["menu-model"]["variants"] == {"high": {"reasoningEffort": "high"},"low": {"reasoningEffort": "low"},}+ assert provider["models"]["menu-model"]["reasoning"] is Trueassert overlay.launches[0].target_model == "upstream-model"assert opencode_model_catalog_for_overlay(overlay) == {"providers": [{- "id": overlay.provider_id,+ "id": "avibe-openai","models": provider["models"],}],@@ -5351,25 +5363,27 @@ def test_opencode_public_models_follow_persisted_config_without_overlay(config = _config([source])agent = config.agents["opencode"]agent.routes = {- "custom/current-model": ModelHubRouteConfig(+ "current-model": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),))}agent.models = [ModelHubBackendModelConfig(- id="custom/current-model",+ id="current-model",+ native_protocol="openai_responses",display_name="Current model",reasoning_efforts=["low", "high"],)]- agent.menu.checked = ["custom/current-model"]+ agent.menu.checked = ["current-model"]service = _service(tmp_path, sources=[source])service.store.config = configassert service.opencode_public_models() == {- "custom/current-model": {- "id": "custom/current-model",+ "current-model": {+ "id": "current-model","name": "Current model",+ "native_protocol": "openai_responses","variants": {"low": {"reasoningEffort": "low"},"high": {"reasoningEffort": "high"},@@ -5389,18 +5403,20 @@ def test_opencode_public_model_hides_preserved_efforts_when_reasoning_is_disableagent = config.agents["opencode"]agent.models = [ModelHubBackendModelConfig(- id="custom/no-reasoning",+ id="no-reasoning",+ native_protocol="openai_responses",supports_reasoning=False,reasoning_efforts=["low", "high"],)]- agent.menu.checked = ["custom/no-reasoning"]+ agent.menu.checked = ["no-reasoning"]service = _service(tmp_path, sources=[source])service.store.config = config- assert service.opencode_public_models()["custom/no-reasoning"] == {- "id": "custom/no-reasoning",- "name": "custom/no-reasoning",+ assert service.opencode_public_models()["no-reasoning"] == {+ "id": "no-reasoning",+ "name": "no-reasoning",+ "native_protocol": "openai_responses","reasoning": False,}@@ -5420,7 +5436,8 @@ def test_opencode_public_model_omits_unspecified_modality_directions(expected: dict[str, list[str]] | None,) -> None:model = ModelHubBackendModelConfig(- id="custom/modalities",+ id="modalities",+ native_protocol="openai_responses",input_modalities=input_modalities,output_modalities=output_modalities,)@@ -5433,7 +5450,7 @@ def test_opencode_public_model_omits_unspecified_modality_directions(assert projected["modalities"] == expected-def test_opencode_overlay_private_provider_id_is_credential_scoped(+def test_opencode_overlay_provider_ids_are_stable_across_gateway_tokens(tmp_path: Path,) -> None:source = _source("src_overlay10", "Overlay")@@ -5455,12 +5472,18 @@ def test_opencode_overlay_private_provider_id_is_credential_scoped(assert first is not Noneassert second is not None- assert first.provider_id != second.provider_id- assert set(json.loads(first.content)["provider"]) == {first.provider_id}- assert set(json.loads(second.content)["provider"]) == {second.provider_id}+ assert first.provider_ids == second.provider_ids == ("avibe-openai",)+ assert set(json.loads(first.content)["provider"]) == {"avibe-openai"}+ assert set(json.loads(second.content)["provider"]) == {"avibe-openai"}+ assert json.loads(first.content)["provider"]["avibe-openai"]["options"]["apiKey"] == (+ "gateway-token-one"+ )+ assert json.loads(second.content)["provider"]["avibe-openai"]["options"]["apiKey"] == (+ "gateway-token-two"+ )-def test_opencode_overlay_supports_mixed_protocols_under_one_provider(tmp_path: Path) -> None:+def test_opencode_overlay_partitions_every_row_by_native_protocol(tmp_path: Path) -> None:first = _source("src_overlay11","First",@@ -5478,13 +5501,27 @@ def test_opencode_overlay_supports_mixed_protocols_under_one_provider(tmp_path:config = _config([first, second])agent = config.agents["opencode"]agent.models = [- ModelHubBackendModelConfig(id="custom/first-model"),- ModelHubBackendModelConfig(id="custom/second-model"),+ ModelHubBackendModelConfig(+ id="first-model",+ native_protocol="anthropic",+ supports_reasoning=True,+ reasoning_efforts=["high"],+ ),+ ModelHubBackendModelConfig(+ id="second-model",+ native_protocol="openai_responses",+ reasoning_efforts=["high"],+ ),+ ModelHubBackendModelConfig(+ id="empty-route-model",+ native_protocol="anthropic",+ ),]- agent.menu.checked = ["custom/first-model", "custom/second-model"]+ agent.menu.checked = ["first-model", "second-model", "empty-route-model"]agent.routes = {- "custom/first-model": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(first.id, "first-model"),)),- "custom/second-model": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(second.id, "second-model"),)),+ "first-model": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(first.id, "first-model"),)),+ "second-model": ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(second.id, "second-model"),)),+ "empty-route-model": ModelHubRouteConfig(),}service = _service(tmp_path, sources=[first, second])service.store.config = config@@ -5500,13 +5537,23 @@ def test_opencode_overlay_supports_mixed_protocols_under_one_provider(tmp_path:assert overlay is not Nonepayload = json.loads(overlay.content)- assert set(payload["provider"]) == {overlay.provider_id}- provider = payload["provider"][overlay.provider_id]- assert provider["npm"] == "@ai-sdk/openai-compatible"- assert provider["options"]["baseURL"] == "http://127.0.0.1:19000/opencode/v1"- assert set(provider["models"]) == {- "custom/first-model",- "custom/second-model",+ assert set(payload["provider"]) == {"avibe-openai", "avibe-anthropic"}+ assert set(payload["enabled_providers"]) == set(payload["provider"])+ assert overlay.provider_ids == ("avibe-anthropic", "avibe-openai")+ anthropic = payload["provider"]["avibe-anthropic"]+ openai = payload["provider"]["avibe-openai"]+ assert anthropic["name"] == "Avibe · Anthropic"+ assert anthropic["npm"] == "@ai-sdk/anthropic"+ assert anthropic["options"]["baseURL"] == "http://127.0.0.1:19000/opencode/v1"+ assert anthropic["models"]["first-model"]["variants"] == {+ "high": {"effort": "high"},+ }+ assert "reasoning" not in anthropic["models"]["first-model"]+ assert set(anthropic["models"]) == {"first-model", "empty-route-model"}+ assert openai["name"] == "Avibe · OpenAI"+ assert openai["npm"] == "@ai-sdk/openai"+ assert openai["models"]["second-model"]["variants"] == {+ "high": {"reasoningEffort": "high"},}assert {launch.target_model for launch in overlay.launches} == {"first-model",@@ -5514,6 +5561,134 @@ def test_opencode_overlay_supports_mixed_protocols_under_one_provider(tmp_path:}+def test_opencode_empty_menu_writes_the_empty_overlay(tmp_path: Path) -> None:+ config = _config([])+ agent = config.agents["opencode"]+ agent.menu.checked = []+ service = _service(tmp_path, sources=[])+ service.store.config = config+ router = ModelHubRuntimeRouter(+ service=service,+ turn_gateway=SimpleNamespace(+ endpoint=AsyncMock(+ return_value=("http://127.0.0.1:19000/opencode", "gateway-token")+ ),+ ),+ overlay_path=tmp_path / "overlay.json",+ )++ overlay = asyncio.run(router.prepare_opencode_overlay())++ assert overlay is not None+ assert overlay.provider_ids == ("avibe-openai",)+ assert overlay.checked_identifiers == ()+ assert overlay.model_provider_ids == ()+ assert overlay.launches == ()+ assert json.loads(overlay.content) == {+ "$schema": "https://opencode.ai/config.json",+ "enabled_providers": ["avibe-openai"],+ "provider": {+ "avibe-openai": {+ "models": {},+ "name": "Avibe · OpenAI",+ "npm": "@ai-sdk/openai",+ "options": {+ "apiKey": "gateway-token",+ "baseURL": "http://127.0.0.1:19000/opencode/v1",+ },+ }+ },+ }+ assert router.overlay_path.read_bytes() == overlay.content+++def test_opencode_overlay_identity_is_stable_under_runtime_perturbations(+ tmp_path: Path,+) -> None:+ first = _source("src_stable001", "First", model_id="upstream-first")+ second = _source("src_stable002", "Second", model_id="upstream-second")+ config = _config([first, second])+ agent = config.agents["opencode"]+ agent.models = [+ ModelHubBackendModelConfig(+ id="stable-model",+ native_protocol="openai_responses",+ reasoning_efforts=["high"],+ )+ ]+ agent.menu.checked = ["stable-model"]+ agent.routes = {+ "stable-model": ModelHubRouteConfig(+ hops=(+ ModelHubRouteHopConfig(first.id, "upstream-first"),+ ModelHubRouteHopConfig(second.id, "upstream-second"),+ )+ )+ }+ service = _service(tmp_path, sources=[first, second])+ service.store.config = config+ endpoint = AsyncMock(+ return_value=("http://127.0.0.1:19000", "gateway-token-one")+ )+ router = ModelHubRuntimeRouter(+ service=service,+ turn_gateway=SimpleNamespace(endpoint=endpoint),+ overlay_path=tmp_path / "overlay.json",+ )++ def projected_content() -> bytes:+ overlay = asyncio.run(router.prepare_opencode_overlay())+ assert overlay is not None+ payload = json.loads(overlay.content)+ for provider in payload["provider"].values():+ provider["options"]["apiKey"] = "<gateway-token>"+ assert overlay.checked_identifiers == ("stable-model",)+ return json.dumps(+ payload,+ ensure_ascii=True,+ sort_keys=True,+ separators=(",", ":"),+ ).encode()++ baseline = projected_content()+ perturbations = (+ lambda: agent.sources.order.reverse(),+ lambda: setattr(+ first,+ "state",+ ModelHubSourceStateConfig(+ status="needs_action",+ detail_key="models.source.needs_action.oauth_expired",+ ),+ ),+ lambda: setattr(+ agent.routes["stable-model"],+ "hops",+ (ModelHubRouteHopConfig(second.id, "upstream-second"),),+ ),+ lambda: config.sources.append(+ _source("src_stable003", "Unrouted", model_id="unrouted")+ ),+ lambda: config.sources.pop(),+ lambda: None,+ )+ for perturb in perturbations:+ perturb()+ assert projected_content() == baseline++ endpoint.return_value = (+ "http://127.0.0.1:19000",+ "gateway-token-two",+ )+ assert projected_content() == baseline++ agent.mode = "direct"+ assert asyncio.run(router.prepare_opencode_overlay()) is None+ assert [model.id for model in agent.models] == ["stable-model"]+ agent.mode = "hub"+ assert projected_content() == baseline++def test_opencode_overlay_selects_supported_fallback_by_exact_hop(tmp_path: Path) -> None:source = _source("src_overlay03",@@ -5522,15 +5697,20 @@ def test_opencode_overlay_selects_supported_fallback_by_exact_hop(tmp_path: Path)config = _config([source])agent = config.agents["opencode"]- agent.routes.pop("openai/shared-model")- agent.routes["openai/menu-model"] = ModelHubRouteConfig(+ agent.routes.pop("shared-model")+ agent.routes["menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "stale-model"),ModelHubRouteHopConfig(source.id, "supported-model"),))- agent.models = [ModelHubBackendModelConfig(id="openai/menu-model")]- agent.menu.checked = ["openai/menu-model"]+ agent.models = [+ ModelHubBackendModelConfig(+ id="menu-model",+ native_protocol="openai_responses",+ )+ ]+ agent.menu.checked = ["menu-model"]service = _service(tmp_path, sources=[source])service.store.config = configrouter = ModelHubRuntimeRouter(@@ -5557,10 +5737,15 @@ def test_opencode_overlay_preserves_checked_route_with_stale_exact_hop()config = _config([source])agent = config.agents["opencode"]- agent.routes.pop("openai/shared-model")- agent.routes["openai/menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "stale-model"),))- agent.models = [ModelHubBackendModelConfig(id="openai/menu-model")]- agent.menu.checked = ["openai/menu-model"]+ agent.routes.pop("shared-model")+ agent.routes["menu-model"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "stale-model"),))+ agent.models = [+ ModelHubBackendModelConfig(+ id="menu-model",+ native_protocol="openai_responses",+ )+ ]+ agent.menu.checked = ["menu-model"]service = _service(tmp_path, sources=[source])service.store.config = configrouter = ModelHubRuntimeRouter(@@ -5574,14 +5759,14 @@ def test_opencode_overlay_preserves_checked_route_with_stale_exact_hop(overlay = asyncio.run(router.prepare_opencode_overlay())assert overlay is not None- provider = json.loads(overlay.content)["provider"][overlay.provider_id]+ provider = json.loads(overlay.content)["provider"]["avibe-openai"]assert provider["models"] == {- "openai/menu-model": {- "id": "openai/menu-model",- "name": "openai/menu-model",+ "menu-model": {+ "id": "menu-model",+ "name": "menu-model",}}- assert overlay.checked_identifiers == ("openai/menu-model",)+ assert overlay.checked_identifiers == ("menu-model",)assert overlay.available_identifiers == ()assert overlay.launches == ()@@ -6240,7 +6425,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(_assert_valid("observation-result.schema.json",{- "contract_version": 7,+ "contract_version": 8,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -8329,7 +8514,7 @@ def test_probe_request_matches_live_backend_protocol_matrix(outcomes=[_outcome(RawOutcomeKind.SUCCESS)],)- requested_model = "openai/shared-model" if backend == "opencode" else "shared-model"+ requested_model = "shared-model"result = asyncio.run(service.probe_agent(backend, requested_model))assert result["reachable"] is True@@ -8365,7 +8550,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": 7,+ "contract_version": 8,"backend": "codex","channel": "native_cli","reachable": True,@@ -8918,7 +9103,7 @@ def test_known_opencode_turn_is_fail_closed_but_not_unknown(registry.begin_gateway_request(backend="opencode",token=token,- requested_model_id="openai/shared-model",+ requested_model_id="shared-model",)is None)diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex fc46d3259..f6880dfba 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -50,10 +50,10 @@ from core.handlers.model_hub.provenance import (project_turn_outcome_copy,)from core.handlers.model_hub.request import ModelHubRequest-from core.handlers.model_hub.resolver import allowed_origins, resolve_model_hub_turnfrom core.handlers.model_hub.resolver import (- canonical_opencode_menu_identity,+ allowed_origins,inspect_exact_hop,+ resolve_model_hub_turn,)from core.handlers.model_hub.revocations import CredentialRevocationJournalfrom core.handlers.model_hub.service import (@@ -349,10 +349,10 @@ def test_matching_v1_is_literal_for_non_native_and_codex():assert _matching_v1_model_id(backend="claude", requested_model="claude-opus-4-6-20260115", source=source) == "claude-opus-4-6-20260115"-def test_matching_v1_opencode_bare_name_requires_unique_checked_suffix():+def test_matching_v1_opencode_uses_the_same_literal_identity_as_codex():source = _source("src_openv001", ("x",), vendor="custom")- assert _matching_v1_model_id(backend="opencode", requested_model="x", source=source, checked_models=("custom/x",)) == "x"- assert _matching_v1_model_id(backend="opencode", requested_model="x", source=source, checked_models=("a/x", "custom/x")) is None+ assert _matching_v1_model_id(backend="opencode", requested_model="x", source=source) == "x"+ assert _matching_v1_model_id(backend="opencode", requested_model="custom/x", source=source) is Nonedef test_matching_v1_never_routes_to_manual_inventory():@@ -370,9 +370,8 @@ def test_matching_v1_never_routes_to_manual_inventory():assert (_matching_v1_model_id(backend="opencode",- requested_model="custom/manual-target",+ requested_model="manual-target",source=source,- checked_models=("custom/manual-target",),)is None)@@ -380,27 +379,29 @@ def test_matching_v1_never_routes_to_manual_inventory():def test_runtime_opencode_resolution_never_repeats_bare_name_matching():source = _source("src_openv001", ("x",), vendor="custom")- config = _config([source], model="custom/x")+ config = _config([source], model="x")agent = config.agents["opencode"]- agent.menu = ModelHubMenuConfig(view="featured", checked=["custom/x"])- agent.routes["custom/x"] = ModelHubRouteConfig(+ agent.menu = ModelHubMenuConfig(view="featured", checked=["x"])+ agent.models = [ModelHubBackendModelConfig(id="x", native_protocol="openai_responses")]+ agent.routes["x"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "x"),))- exact = resolve_model_hub_turn(config, "opencode", "custom/x")- bare = resolve_model_hub_turn(config, "opencode", "x")+ exact = resolve_model_hub_turn(config, "opencode", "x")+ prefixed = resolve_model_hub_turn(config, "opencode", "custom/x")assert exact.source is sourceassert exact.target_model == "x"- assert bare.source is None+ assert prefixed.source is Nonedef test_runtime_opencode_resolution_preserves_absent_selection():source = _source("src_openv002", ("x",), vendor="custom")- config = _config([source], model="custom/x")+ config = _config([source], model="x")agent = config.agents["opencode"]- agent.menu = ModelHubMenuConfig(view="featured", checked=["custom/x"])- agent.routes["custom/x"] = ModelHubRouteConfig(+ agent.menu = ModelHubMenuConfig(view="featured", checked=["x"])+ agent.models = [ModelHubBackendModelConfig(id="x", native_protocol="openai_responses")]+ agent.routes["x"] = ModelHubRouteConfig(hops=(ModelHubRouteHopConfig(source.id, "x"),))@@ -1174,19 +1175,17 @@ def test_launch_failure_reports_unsupported_exact_hop():def test_exact_hop_inspection_is_the_single_identity_and_supply_authority():source = _source("src_exact001", ("upstream-model",), vendor="openai")- config = _config([source], model="openai/menu-model")+ config = _config([source], model="menu-model")hop = ModelHubRouteHopConfig(source.id, "upstream-model")- inspected = inspect_exact_hop(config, "opencode", "openai/menu-model", hop)+ inspected = inspect_exact_hop(config, "opencode", "menu-model", hop)assert inspected.identity == ("opencode",- "openai/menu-model",+ "menu-model",source.id,"upstream-model",)- assert inspected.menu_provider_id == "openai"- assert inspected.menu_model_id == "menu-model"assert inspected.configuration_eligible is Trueassert inspected.inventory_member is Trueassert inspected.supply_eligible is True@@ -1196,55 +1195,55 @@ def test_exact_hop_inspection_is_the_single_identity_and_supply_authority():def test_exact_hop_inspection_rejects_wrong_identity_and_empty_route():source = _source("src_exact002", ("actual-model",), vendor="openai")- config = _config([source], model="openai/menu-model")+ config = _config([source], model="menu-model")wrong = inspect_exact_hop(config,"opencode",- "openai/menu-model",+ "menu-model",ModelHubRouteHopConfig(source.id, "wrong-model"),)- empty = inspect_exact_hop(config, "opencode", "openai/menu-model", None)+ empty = inspect_exact_hop(config, "opencode", "menu-model", None)assert wrong.inventory_member is Falseassert wrong.supply_eligible is Falseassert wrong.runnable is Falseassert wrong.reason == "model_unsupported"- assert empty.identity == ("opencode", "openai/menu-model", None, None)+ assert empty.identity == ("opencode", "menu-model", None, None)assert empty.reason == "route_unconfigured"def test_explicit_opencode_selection_outside_menu_remains_visible(tmp_path):config = ModelHubConfig()config.agents["opencode"].mode = "hub"- config.agents["opencode"].menu.checked = ["openai/visible-model"]+ config.agents["opencode"].menu.checked = ["visible-model"]config.agents["opencode"].models = [- ModelHubBackendModelConfig(id="openai/visible-model")+ ModelHubBackendModelConfig(id="visible-model", native_protocol="openai_responses")]service, store, _ = _service(tmp_path, config)- store.requested_models["opencode"] = "custom/hidden-model"+ store.requested_models["opencode"] = "hidden-model"service.named_agents_override = lambda backend: (- [("researcher", "custom/hidden-model")] if backend == "opencode" else []+ [("researcher", "hidden-model")] if backend == "opencode" else [])payload = service.get_agent_sources("opencode")resolution = resolve_model_hub_turn(config,"opencode",- "custom/hidden-model",+ "hidden-model",)- assert payload["selected_model_id"] == "custom/hidden-model"+ assert payload["selected_model_id"] == "hidden-model"assert payload["supply_status"] == "interrupted"assert payload["named_agents"] == [{"name": "researcher",- "effective_model_id": "custom/hidden-model",+ "effective_model_id": "hidden-model","supply_status": "interrupted","route_reason": "route_unconfigured",}]- assert resolution.requested_model == "custom/hidden-model"+ assert resolution.requested_model == "hidden-model"assert resolution.route_unconfigured is Trueassert resolution.route_reason == "route_unconfigured"@@ -1274,7 +1273,7 @@ def test_direct_mode_rejects_chain_write_before_config_mutation(tmp_path):("backend", "hidden_model"),[("claude", "claude-hidden-model"),- ("opencode", "openai/hidden-model"),+ ("opencode", "hidden-model"),],)def test_chain_write_rejects_models_outside_the_current_menu(@@ -1284,11 +1283,11 @@ def test_chain_write_rejects_models_outside_the_current_menu():source = _source("src_menu0001", ("upstream-model",), vendor="openai")config = _config([source])- config.agents["opencode"].menu.checked = ["openai/visible-model"]+ config.agents["opencode"].menu.checked = ["visible-model"]config.agents["opencode"].models = [- ModelHubBackendModelConfig(id="openai/visible-model")+ ModelHubBackendModelConfig(id="visible-model", native_protocol="openai_responses")]- config.agents["opencode"].routes["openai/visible-model"] = ModelHubRouteConfig()+ config.agents["opencode"].routes["visible-model"] = ModelHubRouteConfig()service, store, _ = _service(tmp_path, config)before = store.load().to_payload()@@ -1342,137 +1341,6 @@ def test_engine_binding_excludes_empty_inventory(tmp_path):assert service._bindings(config) == []-def test_opencode_identity_computation_stays_in_validator_and_resolver():- from ast import (- Attribute,- AsyncFunctionDef,- FunctionDef,- Import,- ImportFrom,- Module,- Name,- NodeVisitor,- parse,- walk,- )- from pathlib import Path-- OPENCODE_IDENTITY_NAMES = {- "STANDARD_OPENCODE_VENDOR_IDS",- "opencode_provider_id",- "opencode_model_id",- "parse_opencode_model_id",- }-- class RawIdentityCalls(NodeVisitor):- def __init__(self):- self.calls = []-- def visit_Call(self, node):- symbol = (- node.func.id- if isinstance(node.func, Name)- else node.func.attr- if isinstance(node.func, Attribute)- else None- )- if symbol in {- "parse_opencode_model_id",- "normalize_opencode_requested_model",- "opencode_model_id",- }:- self.calls.append(symbol)- self.generic_visit(node)-- def visit_Import(self, node):- if any(- alias.name == "core.handlers.model_hub.identifiers"- for alias in node.names- ):- self.calls.append("core.handlers.model_hub.identifiers")- self.generic_visit(node)-- def visit_ImportFrom(self, node):- if node.module == "core.handlers.model_hub.identifiers":- # The OpenCode identity names only. That module also owns model-ID- # spelling, which the config validator is now the single owner of- # — a different property, guarded by its own owner test, and one- # this partition has nothing to say about.- self.calls.extend(- alias.name- for alias in node.names- if alias.name in OPENCODE_IDENTITY_NAMES- )- if node.module == "core.handlers.model_hub.resolver":- self.calls.extend(- alias.name- for alias in node.names- if alias.name == "normalize_opencode_requested_model"- )- self.generic_visit(node)-- root = Path(__file__).parents[1]- config_path = root / "config/v2_config.py"- allowed = {- config_path,- root / "core/handlers/model_hub/identifiers.py",- root / "core/handlers/model_hub/resolver.py",- }- violations = {}- for production_root in ("config", "core", "modules", "vibe"):- for path in (root / production_root).rglob("*.py"):- if path in allowed:- continue- visitor = RawIdentityCalls()- visitor.visit(parse(path.read_text(encoding="utf-8")))- if visitor.calls:- violations[str(path.relative_to(root))] = visitor.calls- assert violations == {}-- config_tree = parse(config_path.read_text(encoding="utf-8"))- validator = next(- node- for node in config_tree.body- if isinstance(node, FunctionDef)- and node.name == "canonical_opencode_menu_identity"- )- validator_calls = RawIdentityCalls()- validator_calls.visit(validator)- assert set(validator_calls.calls) == {"parse_opencode_model_id"}- other_config_calls = RawIdentityCalls()- other_config_calls.visit(- Module(- body=[node for node in config_tree.body if node is not validator],- type_ignores=[],- )- )- assert other_config_calls.calls == []-- shared_startup = parse(- (root / "modules/agents/model_hub.py").read_text(encoding="utf-8")- )- overlay = next(- node- for node in walk(shared_startup)- if isinstance(node, AsyncFunctionDef)- and node.name == "prepare_opencode_overlay"- )- resolution_inputs = {- node.attr- for node in walk(overlay)- if isinstance(node, Attribute)- and isinstance(node.value, Name)- and node.value.id == "resolution"- }- assert {"candidate_hops", "projectable_hops"} <= resolution_inputs- assert "inspected_hops" not in resolution_inputs-- assert canonical_opencode_menu_identity("openai/menu-model") == (- "openai",- "menu-model",- )--def test_agent_chain_projects_exact_hops_and_blockers(tmp_path):source = _source("src_chain001", ("other-model",))config = _config([source], model="stale-model")@@ -1714,9 +1582,14 @@ def test_create_source_normalizes_vendor_before_matching_v1_placement(tmp_path):opencode = config.agents["opencode"]opencode.mode = "hub"assert opencode.menu is not None- opencode.menu.checked = ["openai/gpt-5.6"]- opencode.models = [ModelHubBackendModelConfig(id="openai/gpt-5.6")]- opencode.routes["openai/gpt-5.6"] = ModelHubRouteConfig()+ opencode.menu.checked = ["gpt-5.6"]+ opencode.models = [+ ModelHubBackendModelConfig(+ id="gpt-5.6",+ native_protocol="openai_responses",+ )+ ]+ opencode.routes["gpt-5.6"] = ModelHubRouteConfig()adapter = FakeAdapter(discovered=("gpt-5.6",))service, store, _ = _service(tmp_path, config, adapter)@@ -1736,7 +1609,7 @@ def test_create_source_normalizes_vendor_before_matching_v1_placement(tmp_path):assert store.load().sources[0].vendor == "openai"assert any(position["backend"] == "opencode"- and position["menu_model"] == "openai/gpt-5.6"+ and position["menu_model"] == "gpt-5.6"and position["model_id"] == "gpt-5.6"for position in result["added_to"])@@ -1888,7 +1761,7 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):)assert result["observation"] == {- "contract_version": 7,+ "contract_version": 8,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -1919,7 +1792,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": 7,+ "contract_version": 8,"outcome": "adapter_error","reachable": None,"authenticated": "unknown",diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex b05cf9661..d922682ed 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -1161,7 +1161,7 @@ def test_manifest_resolution_drives_admission_persistence_and_schema(installer=manager,state_store=EngineStateStore(tmp_path / "state"),)- projected = {"contract_version": 7, **supervisor.status()}+ projected = {"contract_version": 8, **supervisor.status()}schema = json.loads(Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(encoding="utf-8"@@ -1417,6 +1417,7 @@ def test_config_generation_is_private_and_never_logs_secrets(vendor="openai",protocol="openai_responses",base_url=None,+ model_reasoning_efforts=(("model-a", ("low", "high")),),),_binding(codex_ref,@@ -1461,6 +1462,18 @@ def test_config_generation_is_private_and_never_logs_secrets(} == {"https://api.example.test/v1", "https://api.deepseek.com"}assert len(payload["codex-api-key"]) == 2assert {entry["base-url"] for entry in payload["codex-api-key"]} == {"https://api.openai.com/v1"}+ responses_entry = next(+ entry+ for entry in payload["codex-api-key"]+ if entry["api-key"] == "responses-secret-value"+ )+ assert responses_entry["models"] == [+ {+ "name": "model-a",+ "alias": "model-a",+ "thinking": {"levels": ["high", "low"]},+ }+ ]assert stat.S_IMODE(config_path.stat().st_mode) == 0o600assert stat.S_IMODE(store.auth_dir.stat().st_mode) == 0o700credential_path = next((store.root / "credentials").iterdir())@@ -1481,6 +1494,78 @@ def test_config_generation_is_private_and_never_logs_secrets(store.prepare_instance("install-1")+def test_mixed_anthropic_credentials_disable_cloak_only_for_api_key_entry(+ tmp_path: Path,+) -> None:+ store = EngineStateStore(tmp_path / "state")+ instance_dir, runtime_secrets = store.prepare_instance("install-1")+ api_key_ref = store.store_api_key(+ "api-key-fixture",+ vendor="anthropic",+ protocol="anthropic",+ )+ oauth_auth_name = "claude-oauth.json"+ oauth_ref = store.bind_oauth_credential(+ "src_oauth0001",+ "anthropic",+ oauth_auth_name,+ )+ oauth_path = store.auth_dir / oauth_auth_name+ oauth_content = b'{"type":"claude","access_token":"oauth-fixture"}\n'+ oauth_path.write_bytes(oauth_content)+ oauth_path.chmod(0o600)+ store.sync_sources(+ [+ _binding(+ api_key_ref,+ source_id="src_apikey001",+ vendor="anthropic",+ protocol="anthropic",+ base_url=None,+ model_ids=("claude-api-model",),+ ),+ _binding(+ oauth_ref,+ source_id="src_oauth0001",+ vendor="anthropic",+ protocol="anthropic",+ base_url=None,+ allowed_origins=("claude",),+ model_ids=("claude-oauth-model",),+ ),+ ]+ )++ config_path = instance_dir / "config.yaml"+ write_engine_config(+ config_path,+ host="127.0.0.1",+ port=18231,+ auth_dir=store.auth_dir,+ runtime_secrets=runtime_secrets,+ sources=store.list_sources(),+ state_store=store,+ )++ payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))+ assert payload["disable-claude-cloak-mode"] is True+ assert payload["claude-api-key"] == [+ {+ "api-key": "api-key-fixture",+ "prefix": store.get_source("src_apikey001").prefix,+ "base-url": "https://api.anthropic.com",+ "cloak": {"mode": "never"},+ "rebuild-mid-system-message": False,+ "models": [+ {"name": "claude-api-model", "alias": "claude-api-model"}+ ],+ }+ ]+ assert oauth_path.read_bytes() == oauth_content+ assert "cloak" not in store.credential_metadata(oauth_ref)+ assert "rebuild-mid-system-message" not in store.credential_metadata(oauth_ref)++def test_state_rejects_unsafe_inputs_and_auth_permissions(tmp_path: Path) -> None:store = EngineStateStore(tmp_path / "state")store.prepare_instance("install-1")@@ -1563,6 +1648,26 @@ def test_state_rejects_unsafe_inputs_and_auth_permissions(tmp_path: Path) -> Nonassert stat.S_IMODE(auth_file.stat().st_mode) == 0o600+def test_source_record_requires_valid_reasoning_state() -> None:+ payload = {+ "source_id": "src_fixture123",+ "vendor": "anthropic",+ "protocol": "anthropic",+ "base_url": None,+ "credential_ref": "cred_fixture123",+ "allowed_origins": [],+ "model_ids": ["model-a"],+ "prefix": "avibe-fixture",+ }++ with pytest.raises(EngineStateError, match="invalid engine source reasoning state"):+ SourceRecord.from_payload(payload)++ payload["model_reasoning_efforts"] = [["other-model", ["high"]]]+ with pytest.raises(EngineStateError, match="invalid engine source reasoning state"):+ SourceRecord.from_payload(payload)++@pytest.mark.parametrize(("vendor", "expected_base_url"),[diff --git a/tests/test_models_dev_catalog.py b/tests/test_models_dev_catalog.pyindex 54c3cb2e3..f1c4dc70d 100644--- a/tests/test_models_dev_catalog.py+++ b/tests/test_models_dev_catalog.py@@ -81,6 +81,7 @@ def test_models_dev_search_normalizes_editable_metadata(monkeypatch, tmp_path):"supports_tools": True,"supports_reasoning": True,"reasoning_efforts": ["low", "high"],+ "native_protocol": "openai_responses",}]cached = json.loads(cache_path.read_text(encoding="utf-8"))@@ -193,6 +194,22 @@ def test_model_vendor_map_is_versioned_unambiguous_and_ordered():assert all(isinstance(provider_id, str) and provider_id for provider_id in aggregators)+def test_native_protocol_derivation_uses_every_vendor_family_on_the_last_segment():+ vendor_map = models_dev_catalog.load_model_vendor_map()++ for family in vendor_map["families"]:+ model_id = f"aggregator/nested/{family['prefix']}fixture"+ expected = (+ "anthropic"+ if family["vendor_id"] == "anthropic"+ else "openai_responses"+ )+ assert models_dev_catalog.native_protocol_for_model_id(+ model_id,+ vendor_map=vendor_map,+ ) == expected++def test_models_dev_deduplicates_by_model_id_and_ranks_first_party_then_match(monkeypatch,):diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 5c6f09957..e747570fb 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -23,7 +23,7 @@ from core.native_dispatch_phase import ()from core.processing_indicator import ProcessingIndicatorServicefrom modules.agents.base import AgentRequest-from modules.agents.model_hub import launch_for_context+from modules.agents.model_hub import OpenCodeOverlay, launch_for_contextfrom modules.agents.service import AgentServicefrom modules.agents.opencode.agent import OpenCodeAgentfrom modules.agents.opencode.server import (@@ -78,6 +78,101 @@ def test_opencode_runtime_config_failure_is_localized() -> None:assert "internal diagnostic" not in display+def test_opencode_hub_turn_with_empty_menu_uses_overlay_and_keeps_server_running(+ monkeypatch,+) -> None:+ calls: list[str] = []+ reservation = object()+ empty_overlay = OpenCodeOverlay(+ path=Path("/tmp/opencode-empty-overlay.json"),+ content_hash="empty-overlay-hash",+ content=(+ b'{"enabled_providers":["avibe-openai"],"provider":'+ b'{"avibe-openai":{"models":{}}}}\n'+ ),+ provider_ids=("avibe-openai",),+ model_provider_ids=(),+ checked_identifiers=(),+ available_identifiers=(),+ launches=(),+ )++ class _Runtime:+ @staticmethod+ def turn_mode(_backend):+ return "hub"++ @staticmethod+ async def prepare_opencode_overlay():+ return empty_overlay++ class _Server:+ async def configure_model_hub_overlay(self, overlay):+ assert overlay is empty_overlay+ calls.append("configure")+ return reservation++ async def release_model_hub_overlay_reservation(self, value):+ assert value is reservation+ calls.append("release")++ async def ensure_running(self):+ calls.append("ensure")++ server = _Server()++ async def _get_server():+ return server++ async def _emit_failure(*_args, **_kwargs):+ calls.append("failure")++ async def _remove_ack(_request):+ calls.append("ack")++ monkeypatch.setattr(+ "modules.agents.opencode.agent.emit_backend_failure",+ _emit_failure,+ )+ controller = type(+ "Controller",+ (),+ {+ "config": type("Config", (), {"language": "en"})(),+ "model_hub_runtime": _Runtime(),+ },+ )()+ agent = OpenCodeAgent.__new__(OpenCodeAgent)+ agent.controller = controller+ agent.config = controller.config+ agent._get_server = _get_server+ agent._remove_ack_reaction = _remove_ack++ def _finish_after_start(_server):+ calls.append("attach")+ raise RuntimeError("test boundary after server start")++ agent._attach_server_activation = _finish_after_start+ request = AgentRequest(+ context=MessageContext(+ user_id="user",+ channel_id="channel",+ platform="slack",+ platform_specific={},+ ),+ message="hello",+ user_message="hello",+ working_path="/tmp/work",+ base_session_id="base",+ composite_session_id="base:/tmp/work",+ session_key="slack::channel",+ )++ asyncio.run(agent._process_message(request))++ assert calls == ["configure", "ensure", "attach", "release", "failure", "ack"]++class _StubClient(BaseIMClient):def __init__(self, name: str, *, supports_editing: bool = True, run_until_stopped: bool = False):super().__init__(_StubConfig())diff --git a/tests/test_opencode_default_provider_routing.py b/tests/test_opencode_default_provider_routing.pyindex 3e61de16f..b1030fc19 100644--- a/tests/test_opencode_default_provider_routing.py+++ b/tests/test_opencode_default_provider_routing.py@@ -15,11 +15,69 @@ import dataclassesfrom config.v2_config import OpenCodeConfigfrom modules.agents.opencode.agent import resolve_opencode_model_dictfrom modules.agents.opencode.utils import (+ build_opencode_model_option_items,+ build_reasoning_effort_options,resolve_opencode_configured_default_model,resolve_opencode_model_id,)+def test_model_hub_picker_keeps_bare_identity_and_hides_transport_provider() -> None:+ catalog = {+ "providers": [+ {+ "id": "avibe-openai",+ "name": "Avibe · OpenAI",+ "models": {+ "gpt-5": {+ "id": "gpt-5",+ "name": "GPT-5",+ "variants": {"high": {"reasoningEffort": "high"}},+ "vibe_remote": {"model_hub_projected": True},+ }+ },+ }+ ],+ "default": {},+ }++ assert build_opencode_model_option_items(catalog, 10) == [+ {"label": "GPT-5", "value": "gpt-5"}+ ]+ assert build_reasoning_effort_options(catalog, "gpt-5") == [+ {"value": "__default__", "label": "(Default)"},+ {"value": "high", "label": "High"}+ ]+++def test_model_hub_picker_keeps_slash_bearing_id_whole_for_variants() -> None:+ catalog = {+ "providers": [+ {+ "id": "avibe-openai",+ "name": "Avibe · OpenAI",+ "models": {+ "moonshotai/kimi-k2": {+ "id": "moonshotai/kimi-k2",+ "name": "Kimi K2",+ "variants": {"xhigh": {"reasoningEffort": "xhigh"}},+ "vibe_remote": {"model_hub_projected": True},+ }+ },+ }+ ],+ "default": {},+ }++ assert build_opencode_model_option_items(catalog, 10) == [+ {"label": "Kimi K2", "value": "moonshotai/kimi-k2"}+ ]+ assert build_reasoning_effort_options(catalog, "moonshotai/kimi-k2") == [+ {"value": "__default__", "label": "(Default)"},+ {"value": "xhigh", "label": "Extra High"},+ ]++def test_opencode_config_default_provider_is_unset_by_default() -> None:cfg = OpenCodeConfig()assert cfg.default_provider is Nonediff --git a/tests/test_opencode_provider_base_url.py b/tests/test_opencode_provider_base_url.pyindex 5f07504a3..5b6c039b2 100644--- a/tests/test_opencode_provider_base_url.py+++ b/tests/test_opencode_provider_base_url.py@@ -429,35 +429,92 @@ def test_upsert_custom_provider_refuses_existing_builtin_block(tmp_path: Path) -)-def test_upsert_custom_provider_keeps_exact_pattern_legacy_id(+def test_upsert_custom_provider_refuses_empty_existing_reserved_block(tmp_path: Path) -> None:+ config_path = get_opencode_config_paths(tmp_path)[0]+ config_path.parent.mkdir(parents=True)+ config_path.write_text(json.dumps({"provider": {"openai": {}}}), encoding="utf-8")++ with pytest.raises(ValueError, match="provider_id already exists"):+ upsert_opencode_custom_provider(+ "openai",+ "OpenAI Override",+ "openai-compatible",+ "https://other.example/v1",+ home=tmp_path,+ )++ assert _read_config(config_path) == {"provider": {"openai": {}}}+++ "provider_id",+ (+ "avibe-openai",+ "avibe-model-hub-0123456789abcdef01234567",+ "avibe-model-hub-relay",+ ),+)+def test_upsert_custom_provider_refuses_new_avibe_prefix(tmp_path: Path,+ provider_id: str,) -> None:- provider_id = "avibe-model-hub-0123456789abcdef01234567"- upsert_opencode_custom_provider(- provider_id,- "Legacy Exact Relay",- "openai-compatible",- "https://relay.example/v1",- home=tmp_path,- )-- config = _read_config(get_opencode_config_paths(tmp_path)[0])- assert config["provider"][provider_id]["name"] == "Legacy Exact Relay"+ with pytest.raises(ValueError, match="provider_id already exists"):+ upsert_opencode_custom_provider(+ provider_id,+ "Reserved Relay",+ "openai-compatible",+ "https://relay.example/v1",+ home=tmp_path,+ )-def test_upsert_custom_provider_keeps_legacy_model_hub_prefix_id(+ "provider_id",+ (+ "avibe-model-hub-0123456789abcdef01234567",+ "avibe-model-hub-relay",+ ),+)+def test_upsert_custom_provider_keeps_existing_avibe_prefix_id_editable(tmp_path: Path,+ provider_id: str,) -> None:+ config_path = get_opencode_config_paths(tmp_path)[0]+ config_path.parent.mkdir(parents=True)+ config_path.write_text(+ json.dumps(+ {+ "provider": {+ provider_id: {+ "name": "Existing Relay",+ "npm": "@ai-sdk/openai-compatible",+ "options": {"baseURL": "https://old.example/v1"},+ "vibe_remote": {+ "custom": True,+ "adapter": "openai-compatible",+ "adapter_label": "OpenAI compatible",+ },+ "models": {},+ }+ }+ }+ ),+ encoding="utf-8",+ )+upsert_opencode_custom_provider(- "avibe-model-hub-relay",- "Legacy Relay",+ provider_id,+ "Updated Relay","openai-compatible","https://relay.example/v1",home=tmp_path,)- config = _read_config(get_opencode_config_paths(tmp_path)[0])- assert config["provider"]["avibe-model-hub-relay"]["name"] == "Legacy Relay"+ config = _read_config(config_path)+ assert config["provider"][provider_id]["name"] == "Updated Relay"+ assert config["provider"][provider_id]["options"]["baseURL"] == (+ "https://relay.example/v1"+ )def test_remove_custom_provider_deletes_only_custom_block(tmp_path: Path) -> None:diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.pyindex 02b15222d..1bd945f3d 100644--- a/tests/test_opencode_server.py+++ b/tests/test_opencode_server.py@@ -1,4 +1,5 @@import asyncio+import hashlibimport importlib.utilimport ioimport json@@ -13,10 +14,6 @@ from unittest.mock import AsyncMock, Mock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))from storage import message_deliveries as delivery_store-from modules.agents.opencode.utils import (- build_opencode_model_option_items,- resolve_opencode_allowed_providers,-)MODULE_PATH = Path(__file__).resolve().parents[1] / "modules" / "agents" / "opencode" / "server.py"@@ -49,6 +46,28 @@ OpenCodeRuntimeConfigInvalidError = SERVER_MODULE.OpenCodeRuntimeConfigInvalidErOpenCodeServerManager = SERVER_MODULE.OpenCodeServerManager+def _model_hub_overlay(path: str, model_id: str | None):+ models = {} if model_id is None else {model_id: {"id": model_id}}+ content = json.dumps(+ {+ "enabled_providers": ["avibe-openai"],+ "provider": {+ "avibe-openai": {+ "models": models,+ }+ }+ },+ sort_keys=True,+ )+ composed = SERVER_MODULE._managed_runtime_config_content(content)+ return types.SimpleNamespace(+ path=Path(path),+ content_hash=hashlib.sha256(composed.encode()).hexdigest(),+ content=content,+ provider_ids=("avibe-openai",),+ )++class _FakeResponse:def __init__(self, *, status: int = 204, text: str = "", json_data=None, headers=None):self.status = status@@ -278,18 +297,19 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):models = await manager.get_available_models("/tmp/work",model_hub_models={- "custom/current-model": {- "id": "custom/current-model",+ "current-model": {+ "id": "current-model","name": "Current model",+ "native_protocol": "openai_responses",},},)model_index = {row["id"]: row["models"] for row in models["providers"]}- self.assertEqual(set(model_index), {"openai", "custom"})+ self.assertEqual(set(model_index), {"openai", "avibe-openai"})self.assertEqual(set(model_index["openai"]), {"native-model"})self.assertEqual(- model_index["custom"]["current-model"],+ model_index["avibe-openai"]["current-model"],{"id": "current-model","name": "Current model",@@ -298,7 +318,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):)async def test_user_catalog_boundary_excludes_model_hub_runtime_provider(self):- private_id = "avibe-model-hub-0123456789abcdef01234567"+ runtime_ids = ("avibe-openai", "avibe-anthropic")legacy_custom_id = "avibe-model-hub-fedcba9876543210fedcba98"class _CatalogSession(_FakeSession):@@ -308,17 +328,18 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):payload = {"providers": [{- "id": private_id,+ "id": "avibe-openai","models": {- "openai/gpt-5": {- "id": "openai/gpt-5",+ "gpt-5": {+ "id": "gpt-5","variants": {"high": {}},},- "custom/first-model": {- "id": "custom/first-model",- },},},+ {+ "id": "avibe-anthropic",+ "models": {"claude-opus-5": {"id": "claude-opus-5"}},+ },{"id": legacy_custom_id, "models": {"relay-model": {}}},{"id": "custom", "models": {"native-model": {}}},{@@ -334,7 +355,8 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):},],"default": {- private_id: "openai/gpt-5",+ "avibe-openai": "gpt-5",+ "avibe-anthropic": "claude-opus-5",legacy_custom_id: "relay-model","openai": "gpt-5",},@@ -342,17 +364,19 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):elif url.endswith("/provider"):payload = {"all": {- private_id: {"id": private_id},+ "avibe-openai": {"id": "avibe-openai"},+ "avibe-anthropic": {"id": "avibe-anthropic"},legacy_custom_id: {"id": legacy_custom_id},"openai": {"id": "openai"},},- "connected": [private_id, legacy_custom_id, "openai"],+ "connected": [*runtime_ids, legacy_custom_id, "openai"],}else:payload = {- "model": f"{private_id}/openai/gpt-5",+ "model": "avibe-openai/gpt-5","provider": {- private_id: {"options": {"apiKey": "private"}},+ "avibe-openai": {"options": {"apiKey": "private"}},+ "avibe-anthropic": {"options": {"apiKey": "private"}},legacy_custom_id: {},"openai": {},},@@ -360,7 +384,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):return _FakeResponse(status=200, json_data=payload)manager = OpenCodeServerManager(binary="opencode", port=4096)- manager._model_hub_overlay_provider_id = private_id+ manager._model_hub_overlay_provider_ids = runtime_idssession = _CatalogSession()manager._get_http_session = AsyncMock(return_value=session) # type: ignore[method-assign]manager.ensure_running = AsyncMock() # type: ignore[method-assign]@@ -368,12 +392,14 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):models = await manager.get_available_models("/tmp/work",model_hub_models={- "openai/gpt-5": {- "id": "openai/gpt-5",+ "gpt-5": {+ "id": "gpt-5",+ "native_protocol": "openai_responses","variants": {"high": {}},},- "custom/first-model": {- "id": "custom/first-model",+ "claude-opus-5": {+ "id": "claude-opus-5",+ "native_protocol": "anthropic",},},)@@ -383,7 +409,7 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):self.assertEqual([row["id"] for row in models["providers"]],- [legacy_custom_id, "custom", "openai"],+ [legacy_custom_id, "custom", "openai", *runtime_ids],)self.assertEqual(models["default"],@@ -408,50 +434,28 @@ class OpenCodeServerTests(unittest.IsolatedAsyncioTestCase):public_models = {row["id"]: row["models"] for row in models["providers"]}- self.assertEqual(set(public_models["openai"]), {"gpt-4", "gpt-5"})- self.assertEqual(public_models["openai"]["gpt-5"]["name"], "GPT-5")+ public_openai = {entry["id"]: entry for entry in public_models["openai"]}+ self.assertEqual(set(public_openai), {"gpt-4", "gpt-5"})+ self.assertEqual(public_openai["gpt-5"]["name"], "GPT-5")self.assertEqual(- public_models["openai"]["gpt-5"]["capabilities"],+ public_openai["gpt-5"]["capabilities"],{"tools": True},)+ self.assertEqual(set(public_models["custom"]), {"native-model"})self.assertEqual(- public_models["openai"]["gpt-5"]["variants"],- {"high": {}},- )- self.assertTrue(- public_models["openai"]["gpt-5"]["vibe_remote"][- "model_hub_projected"- ]- )- self.assertEqual(set(public_models["custom"]), {"native-model", "first-model"})- self.assertEqual(- public_models["custom"]["first-model"],+ public_models["avibe-openai"]["gpt-5"],{- "id": "first-model",+ "id": "gpt-5",+ "variants": {"high": {}},"vibe_remote": {"model_hub_projected": True},},)- allowed_providers = resolve_opencode_allowed_providers(- {"providers": {"openai": {}}},- models,- )self.assertEqual(- allowed_providers,- ["openai"],- )- picker_values = {- item["value"]- for item in build_opencode_model_option_items(- models,- max_total=99,- allowed_providers=allowed_providers,- )- }- self.assertIn("custom/first-model", picker_values)- self.assertNotIn("custom/native-model", picker_values)- self.assertNotIn(f"{legacy_custom_id}/relay-model", picker_values)- self.assertFalse(- any(value.startswith(f"{private_id}/") for value in picker_values)+ public_models["avibe-anthropic"]["claude-opus-5"],+ {+ "id": "claude-opus-5",+ "vibe_remote": {"model_hub_projected": True},+ },)async def test_ensure_running_restarts_healthy_server_when_caller_context_plugin_changes(self):@@ -2903,12 +2907,7 @@ def test_changed_overlay_still_waits_for_active_run_before_restart():manager._pid_file_references_current_server = Mock(return_value=False) # type: ignore[method-assign]manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]- overlay = types.SimpleNamespace(- path=Path("/tmp/new-overlay.json"),- content_hash="new-hash",- content='{"provider": {}}',- provider_id="avibe-model-hub-new",- )+ overlay = _model_hub_overlay("/tmp/new-overlay.json", "new-model")async def exercise():configuring = asyncio.create_task(manager.configure_model_hub_overlay(overlay))@@ -2925,6 +2924,27 @@ def test_changed_overlay_still_waits_for_active_run_before_restart():manager._restart_for_auth_refresh_locked.assert_awaited_once()+def test_empty_model_hub_overlay_uses_the_normal_change_path():+ manager = OpenCodeServerManager(binary="opencode", port=4096)+ manager._model_hub_overlay_path = "/tmp/old-overlay.json"+ manager._model_hub_overlay_hash = "old-hash"+ manager._read_pid_file = lambda: {} # type: ignore[method-assign]+ manager._pid_file_references_current_server = Mock(return_value=False) # type: ignore[method-assign]+ manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]+ manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]+ overlay = _model_hub_overlay("/tmp/empty-overlay.json", None)++ reservation = asyncio.run(manager.configure_model_hub_overlay(overlay))+ asyncio.run(manager.release_model_hub_overlay_reservation(reservation))++ assert json.loads(overlay.content)["provider"]["avibe-openai"]["models"] == {}+ assert manager._model_hub_overlay_path == str(overlay.path)+ assert manager._model_hub_overlay_hash == overlay.content_hash+ manager._restart_for_auth_refresh_locked.assert_awaited_once_with(+ native_turns_drained=True,+ )++def test_changed_overlay_passes_completed_persisted_drain_to_retirement():manager = OpenCodeServerManager(binary="opencode", port=4096)manager._model_hub_overlay_path = "/tmp/old-overlay.json"@@ -2938,12 +2958,7 @@ def test_changed_overlay_passes_completed_persisted_drain_to_retirement():manager._pid_file_references_current_server = Mock(return_value=True) # type: ignore[method-assign]manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]- overlay = types.SimpleNamespace(- path=Path("/tmp/new-overlay.json"),- content_hash="new-hash",- content='{"provider": {}}',- provider_id="avibe-model-hub-new",- )+ overlay = _model_hub_overlay("/tmp/new-overlay.json", "new-model")reservation = asyncio.run(manager.configure_model_hub_overlay(overlay))asyncio.run(manager.release_model_hub_overlay_reservation(reservation))@@ -2956,27 +2971,16 @@ def test_changed_overlay_passes_completed_persisted_drain_to_retirement():def test_mh_runtime_003_pending_overlay_transition_blocks_new_turns_on_the_old_overlay():"""MH-RUNTIME-003: a queued change drains without old-overlay starvation."""+ old_overlay = _model_hub_overlay("/tmp/old-overlay.json", "old-model")+ new_overlay = _model_hub_overlay("/tmp/new-overlay.json", "new-model")manager = OpenCodeServerManager(binary="opencode", port=4096)manager._model_hub_overlay_path = "/tmp/old-overlay.json"- manager._model_hub_overlay_hash = "old-hash"+ manager._model_hub_overlay_hash = old_overlay.content_hashmanager._active_run_sessions.add("sess-active")manager._read_pid_file = lambda: {} # type: ignore[method-assign]manager._pid_file_references_current_server = Mock(return_value=False) # type: ignore[method-assign]manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]- old_overlay = types.SimpleNamespace(- path=Path("/tmp/old-overlay.json"),- content_hash="old-hash",- content='{"provider": {}}',- provider_id="avibe-model-hub-old",- )- new_overlay = types.SimpleNamespace(- path=Path("/tmp/new-overlay.json"),- content_hash="new-hash",- content='{"provider": {}}',- provider_id="avibe-model-hub-new",- )-async def exercise():configuring = asyncio.create_task(manager.configure_model_hub_overlay(new_overlay)@@ -3004,26 +3008,15 @@ def test_mh_runtime_003_pending_overlay_transition_blocks_new_turns_on_the_old_odef test_mh_runtime_004_overlay_reservation_promotes_atomically_to_active_run():"""MH-RUNTIME-004: selection stays leased through active-run registration."""+ old_overlay = _model_hub_overlay("/tmp/old-overlay.json", "old-model")+ new_overlay = _model_hub_overlay("/tmp/new-overlay.json", "new-model")manager = OpenCodeServerManager(binary="opencode", port=4096)manager._model_hub_overlay_path = "/tmp/old-overlay.json"- manager._model_hub_overlay_hash = "old-hash"+ manager._model_hub_overlay_hash = old_overlay.content_hashmanager._read_pid_file = lambda: {} # type: ignore[method-assign]manager._pid_file_references_current_server = Mock(return_value=False) # type: ignore[method-assign]manager._is_healthy = AsyncMock(return_value=True) # type: ignore[method-assign]manager._restart_for_auth_refresh_locked = AsyncMock() # type: ignore[method-assign]- old_overlay = types.SimpleNamespace(- path=Path("/tmp/old-overlay.json"),- content_hash="old-hash",- content='{"provider": {}}',- provider_id="avibe-model-hub-old",- )- new_overlay = types.SimpleNamespace(- path=Path("/tmp/new-overlay.json"),- content_hash="new-hash",- content='{"provider": {}}',- provider_id="avibe-model-hub-new",- )-async def exercise():reservation = await manager.configure_model_hub_overlay(new_overlay)reverting = asyncio.create_task(diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.pyindex 5a80c2830..d0bf48fcc 100644--- a/tests/test_settings_handler.py+++ b/tests/test_settings_handler.py@@ -541,7 +541,10 @@ def test_gather_routing_modal_data_only_fetches_current_backend() -> None:def test_gather_routing_modal_data_uses_current_model_hub_projection() -> None:handler, server = _make_routing_handler()projection = {- "custom/current-model": {"id": "custom/current-model"},+ "current-model": {+ "id": "current-model",+ "native_protocol": "openai_responses",+ },}handler.controller.model_hub_service = SimpleNamespace(opencode_public_models=lambda: projection,diff --git a/tests/test_ui_api.py b/tests/test_ui_api.pyindex 8d7210904..5a1098f55 100644--- a/tests/test_ui_api.py+++ b/tests/test_ui_api.py@@ -2565,12 +2565,22 @@ def test_agent_model_options_opencode_overlay_and_provider_filter(monkeypatch):"name": "DeepSeek","models": {"deepseek-chat": {"vibe_remote": {"user_model": True}}},},+ {+ "id": "avibe-openai",+ "name": "Avibe · OpenAI",+ "models": {+ "gpt-5": {+ "vibe_remote": {"model_hub_projected": True},+ }+ },+ },],"default": {"anthropic": "claude-x"},},"reasoning_options": {"anthropic/claude-x": [{"value": "__default__"}, {"value": "low"}, {"value": "high"}],"deepseek/deepseek-chat": [{"value": "low"}],+ "gpt-5": [{"value": "high"}],},},}@@ -2584,12 +2594,19 @@ def test_agent_model_options_opencode_overlay_and_provider_filter(monkeypatch):providers = {p["id"]: p for p in result["providers"]}assert providers["deepseek"]["custom"] is Trueassert providers["anthropic"]["custom"] is False+ assert "avibe-openai" not in providersby_value = {m["value"]: m for m in result["models"]}# custom-provider models + reasoning + source annotation flow through unchangedassert by_value["anthropic/claude-x"]["reasoning_efforts"] == ["low", "high"]assert by_value["anthropic/claude-x"]["default"] is Trueassert by_value["anthropic/claude-x"]["source"] == "catalog"assert by_value["deepseek/deepseek-chat"]["source"] == "user"+ assert by_value["gpt-5"] == {+ "value": "gpt-5",+ "default": False,+ "source": "catalog",+ "reasoning_efforts": ["high"],+ }filtered = api.agent_model_options("opencode", provider="deepseek")assert [p["id"] for p in filtered["providers"]] == ["deepseek"]diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsxindex c8556e25f..47cfef294 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -16,7 +16,7 @@ import { freshRuntimeProjection } from './runtimeLifecycle';import type { AgentSupply, RuntimeDependency, Source } from './types';const runtime: RuntimeDependency = {- contract_version: 7,+ contract_version: 8,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 },};@@ -60,12 +60,11 @@ const openCodeAgent: AgentSupply = {model_supply: [],named_agents: [{name: 'opencode',- effective_model_id: 'openai/gpt-5.6-terra',+ effective_model_id: 'gpt-5.6-terra',supply_status: 'interrupted',route_reason: 'route_unconfigured',}],builtin_models: null,- standard_vendors: ['openai'],menu: { view: 'featured', checked: [] },};@@ -74,7 +73,7 @@ afterEach(cleanup);describe('AgentCard', () => {it('renders an empty OpenCode selection as configurable rather than as missing backend supply', async () => {const onOpenModels = vi.fn();- const retainedModelId = 'openai/gpt-5.6-luna';+ const retainedModelId = 'gpt-5.6-luna';const agentWithRetainedRoute = {...openCodeAgent,routes: { [retainedModelId]: { hops: [{ source_id: 'src_a', model_id: 'gpt-5.6-luna' }] } },@@ -104,12 +103,13 @@ describe('AgentCard', () => {id, display_name: null, origin: 'manual', models_dev_id: null, context_window: null, max_output_tokens: null,input_modalities: ['text'], output_modalities: ['text'], supports_tools: true, supports_reasoning: false,reasoning_efforts: [], locked: false, routeable: true,+ ...(backend === 'opencode' ? { native_protocol: 'openai_responses' as const } : {}),})),});const agents = [catalogued('claude', ['claude-two', 'claude-one']),catalogued('codex', ['codex-only']),- catalogued('opencode', ['openai/one']),+ catalogued('opencode', ['one']),];render(<I18nextProvider i18n={i18n}><AgentCard agents={agents} sources={[]} chains={{}} 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>);@@ -125,12 +125,12 @@ describe('AgentCard', () => {'Open claude-two route chain','Open claude-one route chain','Open codex-only route chain',- 'Open openai/one route chain',+ 'Open one route chain',]);});it('labels a selected OpenCode model with an empty route as unconfigured', () => {- const modelId = 'openai/gpt-5.6-luna';+ const modelId = 'gpt-5.6-luna';render(<I18nextProvider i18n={localeInstance('zh')}><AgentCard agents={[{...openCodeAgent,menu: { view: 'featured', checked: [modelId] },@@ -181,7 +181,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({ contract_version: 7, 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({ contract_version: 8, 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();@@ -199,7 +199,7 @@ describe('AgentCard', () => {sources={[source('src_b', 'Backup source')]}chains={{[key]: readyRegion({- contract_version: 7,+ contract_version: 8,backend: 'claude',model_id: 'claude-opus-4-6',current: { source_id: 'src_b', model_id: 'routed-opus' },@@ -228,7 +228,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({ contract_version: 7, 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({ contract_version: 8, 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();});@@ -236,7 +236,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({ contract_version: 7, 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({ contract_version: 8, 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();@@ -247,7 +247,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({ contract_version: 7, 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({ contract_version: 8, 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/BackendModelCatalogDialog.test.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsxindex f36346777..2185bd410 100644--- a/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.test.tsx@@ -235,21 +235,15 @@ describe('BackendModelCatalogDialog', () => {it('asks which row a typed ID names as the ID it would be saved as', async () => {const user = userEvent.setup();- // The id the user types is not yet the id the row is saved under: on OpenCode- // an unrecognized provider resolves to `custom/`, and the editor applies that- // rule when it commits. So the lookup behind this door has to be asked about- // the resolved id. Asked about the raw one it misses the row the user already- // has and opens a blank one, which then commits over that same saved id and- // drops everything they had described about it.- const FOO = model('custom/foo', {+ const FOO = model('foo', {+ native_protocol: 'openai_responses',display_name: 'Foo Air',context_window: 180000,origin: 'manual',});- const catalog = [model('zai/glm-4.7'), FOO];+ const catalog = [model('glm-4.7', { native_protocol: 'openai_responses' }), FOO];vi.spyOn(modelsApi, 'getAgentSources').mockResolvedValue(agent(catalog, {backend: 'opencode',- standard_vendors: ['zai'],}));// Nothing offered under this query, which is the only state that offers the// typed id as a custom model at all.@@ -265,7 +259,7 @@ describe('BackendModelCatalogDialog', () => {// Their own row, opened as itself: the id fixed, and the description they// wrote still in it. The button is the tell — this is an edit, not an add.- expect((await screen.findByLabelText('Model') as HTMLInputElement).value).toBe('custom/foo');+ expect((await screen.findByLabelText('Model') as HTMLInputElement).value).toBe('foo');expect((screen.getByLabelText('Display name') as HTMLInputElement).value).toBe('Foo Air');expect((screen.getByLabelText('Context window') as HTMLInputElement).value).toBe('180,000');await user.type(screen.getByLabelText('Maximum output'), '8000');@@ -277,7 +271,7 @@ describe('BackendModelCatalogDialog', () => {// window gone — the write is what the user would have to undo by hand.await waitFor(() => expect(write).toHaveBeenCalledWith('opencode', {baseline: catalog,- models: [model('zai/glm-4.7'), { ...FOO, max_output_tokens: 8000 }],+ models: [model('glm-4.7', { native_protocol: 'openai_responses' }), { ...FOO, max_output_tokens: 8000 }],}));});diff --git a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx b/ui/src/components/settings/models/BackendModelCatalogDialog.tsxindex f2d433849..a10cc406c 100644--- a/ui/src/components/settings/models/BackendModelCatalogDialog.tsx+++ b/ui/src/components/settings/models/BackendModelCatalogDialog.tsx@@ -365,13 +365,6 @@ export const BackendModelCatalogDialog: React.FC<{const movableIds = draft.filter((model) => !model.locked).map((model) => model.id);const takenIds = new Set(draft.map((model) => model.id));const effortSuggestions = [...new Set(draft.flatMap((model) => model.reasoning_efforts))];- /** Threaded from the server's own projection rather than mirrored here: the- * editor's id rule has to agree with the backend that will accept the id. */- const standardVendors = React.useMemo(- () => new Set(baseline?.agent.standard_vendors ?? []),- [baseline?.agent.standard_vendors],- );-/** Reordering permutes which movable row sits in which movable slot; a locked* row keeps its absolute index, so the order sent never moves one. */const reorderMovable = (nextIds: string[]) => {@@ -1136,14 +1129,14 @@ export const BackendModelCatalogDialog: React.FC<{// editor itself commits under (`backendModelId`, which `draftWithId`// applies there). The lookup is a total function of the id, so the id// it is asked about has to be the one the row would be saved as: asked- // about a typed `foo` it does not find the user's saved `custom/foo`,+ // about a typed `foo` it finds the user's saved `foo`,// and the editor — resolving the id only on commit — would then write// a blank row onto it, dropping the limits, modalities, capabilities// and name they had described. The resolver is idempotent, so the// editor re-applying it to this seed changes nothing.onCustom={(typed) => {addCandidates([]);- const seedId = backendModelId(typed, backend, standardVendors);+ const seedId = backendModelId(typed);const existing = heldRowFor(seedId, draftRef.current, baselineRef.current?.models ?? []);setEditing(existing ? { model: existing } : { model: null, seedId });}}@@ -1158,7 +1151,6 @@ export const BackendModelCatalogDialog: React.FC<{seedId={editing.seedId}takenIds={takenIds}effortSuggestions={effortSuggestions}- standardVendors={standardVendors}onCancel={() => setEditing(null)}onCommit={commitEdit}/>diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.test.tsxindex a7f62266f..adb2863a8 100644--- a/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx+++ b/ui/src/components/settings/models/BackendModelEditorDialog.test.tsx@@ -23,6 +23,7 @@ const match = (overrides: Partial<ModelsDevMatch> = {}): ModelsDevMatch => ({supports_tools: true,supports_reasoning: true,reasoning_efforts: ['low', 'high'],+ native_protocol: 'anthropic',...overrides,});@@ -37,7 +38,6 @@ const renderEditor = (overrides: Partial<React.ComponentProps<typeof BackendModemodel={null}takenIds={new Set()}effortSuggestions={[]}- standardVendors={new Set()}onCancel={onCancel}onCommit={onCommit}{...overrides}@@ -267,32 +267,20 @@ describe('BackendModelEditorDialog', () => {expect(screen.queryByRole('listbox')).toBeNull();});- it('takes the query as the ID and, on OpenCode, as one OpenCode accepts', async () => {+ it('takes an OpenCode query as the bare model ID', async () => {const user = userEvent.setup();- // The one id rule this dialog owns: OpenCode addresses `provider/model`, so- // the escape supplies the provider a query does not name and offers the id- // the backend will accept rather than the one it would reject after saving.- const { onCommit } = renderEditor({ backend: 'opencode', standardVendors: new Set(['zai']) });+ const { onCommit } = renderEditor({ backend: 'opencode' });await user.type(modelField(), 'glm-4.7');- expect(await screen.findByRole('option', { name: 'Use "custom/glm-4.7" as the model ID' })).toBeTruthy();+ await user.click(await screen.findByRole('option', { name: 'Use "glm-4.7" as the model ID' }));- await user.clear(modelField());- await user.type(modelField(), 'zai/glm-4.7');- // A query that already names a provider is taken as typed.- expect(await screen.findByRole('option', { name: 'Use "zai/glm-4.7" as the model ID' })).toBeTruthy();-- await user.clear(modelField());- await user.type(modelField(), 'acme/glm-4.7');- // Including a provider the standard vendor list does not know. The server- // admits any provider segment its grammar accepts, so offering- // `custom/acme/glm-4.7` would save a different public model id than the one- // that was typed — and save it silently, because the server accepts that too.- await user.click(await screen.findByRole('option', { name: 'Use "acme/glm-4.7" as the model ID' }));-- expect(modelField().value).toBe('acme/glm-4.7');+ expect(modelField().value).toBe('glm-4.7');await user.click(screen.getByRole('button', { name: 'Add model' }));- expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({ id: 'acme/glm-4.7', origin: 'manual' }));+ expect(onCommit).toHaveBeenCalledWith(expect.objectContaining({+ id: 'glm-4.7',+ origin: 'manual',+ native_protocol: 'openai_responses',+ }));});it('takes the query verbatim on a backend whose IDs have no provider segment', async () => {diff --git a/ui/src/components/settings/models/BackendModelEditorDialog.tsx b/ui/src/components/settings/models/BackendModelEditorDialog.tsxindex 9de327444..7503343fa 100644--- a/ui/src/components/settings/models/BackendModelEditorDialog.tsx+++ b/ui/src/components/settings/models/BackendModelEditorDialog.tsx@@ -19,10 +19,9 @@ import { Input } from '@/components/ui/input';import { SegmentedRadio } from '@/components/ui/segmented';import { isComposingKey } from '@/lib/imeComposition';import { cn } from '@/lib/utils';-import { applyModelsDevMatch, backendModelId, blankBackendModel, draftWithId, opencodeMenuIdentity, retireModelsDevMatch } from './backendCatalog';+import { applyModelsDevMatch, backendModelId, blankBackendModel, draftWithId, retireModelsDevMatch } from './backendCatalog';import { Field } from './dialogFields';import { formatTokensCompact } from './format';-import type { StandardVendors } from './menus/identifiers';import { apiFailure, modelsApi } from './modelsApi';import { modelsDevFillFailureKey } from './serverCopy';import {@@ -127,14 +126,9 @@ export const BackendModelEditorDialog: React.FC<{/** Effort values this backend's other rows already use. Suggestions, never a* vocabulary — every effort is sent verbatim and any string is equally valid. */effortSuggestions: readonly string[];- /** OpenCode's standard vendor ids, as the server projects them — the input to- * the shared id rule both typeahead rows resolve through (`backendModelId`).- * Empty for every other backend, and for a server too old to project them:- * `custom/` is then the answer for every query, which OpenCode still accepts. */- standardVendors: StandardVendors;onCancel: () => void;onCommit: (model: BackendModel) => void;-}> = ({ open, backend, model, seedId, takenIds, effortSuggestions, standardVendors, onCancel, onCommit }) => {+}> = ({ open, backend, model, seedId, takenIds, effortSuggestions, onCancel, onCommit }) => {const { t } = useTranslation();const creating = model === null;const [draft, setDraft] = React.useState<BackendModel>(() => model ?? blankBackendModel());@@ -191,10 +185,10 @@ export const BackendModelEditorDialog: React.FC<{// by the one route nobody watches. The query stays what was typed: it is a// models.dev search, and searching for the resolved id would search for the// vendor prefix the resolver just added.- const next = model ?? draftWithId(blankBackendModel(), seedId?.trim() ?? '', backend, standardVendors);+ const next = model ?? draftWithId(blankBackendModel(), seedId?.trim() ?? '', backend);seed(next);setLookup(model === null ? seedId?.trim() ?? '' : '');- }, [backend, model, open, seed, seedId, standardVendors]);+ }, [backend, model, open, seed, seedId]);/*** The typeahead: what has been typed so far, answered by models.dev.@@ -248,14 +242,14 @@ export const BackendModelEditorDialog: React.FC<{* Add mode resolves the id through the one chokepoint here, so the rules below* and the row `commit` sends judge and write the same value — the one the* backend receives. Checking the raw box instead would measure a length and a- * collision against an id that does not exist yet: `custom/` is part of what- * gets stored, and a row already holding `custom/foo` collides with a freshly- * typed `foo`.+ * collision against an id that does not exist yet: canonicalization trims+ * surrounding whitespace, and a row already holding `foo` collides with a+ * freshly typed ` foo `.** An edit mints nothing. The id came from the server and is held read-only, so* resolving it again would rename a saved row whose id predates the rule.*/- const resolved = creating ? draftWithId(draft, trimmedId, backend, standardVendors) : draft;+ const resolved = creating ? draftWithId(draft, trimmedId, backend) : draft;// Every id rule is a rule about what the user may type, and only add mode lets// them type it — an edit shows the id read-only. Judging a value the dialog// itself locks is what made a persisted row whose id predates the length@@ -267,16 +261,9 @@ export const BackendModelEditorDialog: React.FC<{? 'required': resolved.id.length > BACKEND_MODEL_ID_MAX_LENGTH? 'tooLong'- // Asked of the resolved id for the same reason the length and the- // collision are: `custom/` is part of what gets stored, so the shape- // rule has to judge the value the backend will actually parse. It is- // the last rule that can be answered without the list, and the- // collision check below is the one that needs it.- : !opencodeMenuIdentity(resolved.id, backend)- ? 'invalid'- : takenIds.has(resolved.id)- ? 'duplicate'- : null;+ : takenIds.has(resolved.id)+ ? 'duplicate'+ : null;const valid = idError === null && context.ok && output.ok;const patch = (next: Partial<BackendModel>) => setDraft((current) => ({ ...current, ...next }));@@ -302,7 +289,7 @@ export const BackendModelEditorDialog: React.FC<{// its provider publishes it as. `origin` is `models_dev` unconditionally// because the typeahead is add mode's field: a saved row's own creation path// is never re-decided here.- const next = applyModelsDevMatch(draft, match, 'models_dev', backend, standardVendors);+ const next = applyModelsDevMatch(draft, match, 'models_dev', backend);const name = match.display_name ?? '';const context = groupTokens(match.context_window);const output = groupTokens(match.max_output_tokens);@@ -319,7 +306,7 @@ export const BackendModelEditorDialog: React.FC<{* earlier fill still owned was retired by `changeId` the moment they typed* again, and what survived that is what they typed themselves. */const takeLookupAsId = () => {- setDraft((current) => draftWithId(current, lookup.trim(), backend, standardVendors));+ setDraft((current) => draftWithId(current, lookup.trim(), backend));setLookup('');};@@ -535,7 +522,7 @@ export const BackendModelEditorDialog: React.FC<{other one would be describing a different model. */}<span className="model-hub-model-match-literal min-w-0 truncate">{t('settings.models.gateway.modelEditor.useAsId', {- query: backendModelId(lookup.trim(), backend, standardVendors),+ query: backendModelId(lookup.trim()),})}</span></button>diff --git a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx b/ui/src/components/settings/models/EnableGatewayDialog.test.tsxindex d8706cd50..2856b5897 100644--- a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx+++ b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx@@ -34,7 +34,7 @@ const runtime = (? 'unresolved' as const: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;return {- contract_version: 7,+ contract_version: 8,...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),manifest: resolution === 'unresolved'? { name: 'cliproxyapi', resolution, assets: [] }diff --git a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx b/ui/src/components/settings/models/InstallGatewayDialog.test.tsxindex 506d4e033..4bfac5c92 100644--- a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx+++ b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx@@ -10,7 +10,7 @@ import { modelsApi } from './modelsApi';import type { RuntimeDependency } from './types';const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({- contract_version: 7,+ contract_version: 8,manifest: {name: 'cliproxyapi',resolution: 'resolved',diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsxindex 2424f0dcb..8dc74b9f2 100644--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx@@ -52,7 +52,7 @@ const sources: Source[] = [},];const chain: AgentChain = {- contract_version: 7,+ contract_version: 8,backend: "claude",model_id: "opus-5",current: { source_id: "src_b", model_id: "opus-5" },diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsxindex 407475d14..6716d6a46 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: 7,+ contract_version: 8,...(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 dea2ac545..0ed9ab3bd 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -25,7 +25,7 @@ const directAgent = (backend: AgentBackend): AgentSupply => ({});const runtime: RuntimeDependency = {- contract_version: 7,+ contract_version: 8,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },status: { installed_version: '1', verified: true, health: 'ok' },};@@ -76,7 +76,7 @@ const takeoverAgent: AgentSupply = {};const takeoverChain: AgentChain = {- contract_version: 7,+ contract_version: 8,backend: 'codex',model_id: 'gpt-5.6-sol',current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },@@ -1007,7 +1007,7 @@ describe('SettingsModelsPage surface branches', () => {builtin_models: [modelId],};const affectedChain: AgentChain = {- contract_version: 7,+ contract_version: 8,backend: 'claude',model_id: modelId,current: { source_id: retainedSource.id, model_id: modelId },diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.tsindex 2e627c9b2..627bbde2e 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: 7,+ contract_version: 8,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 => ({- contract_version: 7,+ contract_version: 8,backend: 'claude',model_id: 'model-a',current: { source_id: current, model_id: 'model-a' },diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.tsindex 14bfb8914..a98e362a3 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: 7,+ contract_version: 8,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/asyncLifetime.test.ts b/ui/src/components/settings/models/asyncLifetime.test.tsindex edae5e8f0..3cb279f09 100644--- a/ui/src/components/settings/models/asyncLifetime.test.ts+++ b/ui/src/components/settings/models/asyncLifetime.test.ts@@ -567,8 +567,8 @@ describe('savedSourcesKey / savedMenuKey', () => {});it('reads the menu the drawer seeds from', () => {- expect(savedMenuKey({ view: 'featured', checked: ['zhipuai/glm-5.2'] })).not.toBe(- savedMenuKey({ view: 'full', checked: ['zhipuai/glm-5.2'] }),+ expect(savedMenuKey({ view: 'featured', checked: ['glm-5.2'] })).not.toBe(+ savedMenuKey({ view: 'full', checked: ['glm-5.2'] }),);expect(savedMenuKey(null)).toBe(savedMenuKey({ view: 'featured', checked: [] }));});diff --git a/ui/src/components/settings/models/backendCatalog.test.ts b/ui/src/components/settings/models/backendCatalog.test.tsindex 0a45259d1..5a204b2fb 100644--- a/ui/src/components/settings/models/backendCatalog.test.ts+++ b/ui/src/components/settings/models/backendCatalog.test.ts@@ -18,7 +18,6 @@ import {echoableRefusal,heldRowFor,offeredCandidates,- opencodeMenuIdentity,orderWithRestored,MODELS_DEV_FIELDS,pickerGroups,@@ -27,7 +26,6 @@ import {sameBackendModel,samePlanContents,} from './backendCatalog';-import { inferProvider, type StandardVendors } from './menus/identifiers';import type {AgentSupply,BackendModel,@@ -67,6 +65,7 @@ const match: ModelsDevMatch = {supports_tools: true,supports_reasoning: true,reasoning_efforts: ['low', 'high'],+ native_protocol: 'anthropic',};describe('catalogModelIds', () => {@@ -102,14 +101,10 @@ describe('catalogModelIds', () => {});describe('applyModelsDevMatch', () => {- /** These cases are about the fields a match fills, so they use a backend- * whose ids carry no provider segment; the id rule has its own describe. */- const NO_VENDORS: ReadonlySet<string> = new Set();-it('names the row after the model that was picked and fills the rest from it', () => {const draft = model('half-typed-anthro', { locked: true, routeable: false });- const filled = applyModelsDevMatch(draft, match, 'models_dev', 'codex', NO_VENDORS);+ const filled = applyModelsDevMatch(draft, match, 'models_dev', 'codex');// Choosing a suggestion is choosing a model, not decorating one, so the row// carries that model's own id — the one a backend accepts, not the@@ -139,12 +134,12 @@ describe('applyModelsDevMatch', () => {});it('takes the origin from the caller so a re-fill never rewrites how the row was created', () => {- expect(applyModelsDevMatch(model('m', { origin: 'manual' }), match, 'manual', 'codex', NO_VENDORS).origin).toBe('manual');- expect(applyModelsDevMatch(blankBackendModel(), match, 'models_dev', 'codex', NO_VENDORS).origin).toBe('models_dev');+ expect(applyModelsDevMatch(model('m', { origin: 'manual' }), match, 'manual', 'codex').origin).toBe('manual');+ expect(applyModelsDevMatch(blankBackendModel(), match, 'models_dev', 'codex').origin).toBe('models_dev');});it('copies the match lists instead of aliasing them', () => {- const filled = applyModelsDevMatch(model('m'), match, 'models_dev', 'codex', NO_VENDORS);+ const filled = applyModelsDevMatch(model('m'), match, 'models_dev', 'codex');filled.reasoning_efforts.push('mutated');expect(match.reasoning_efforts).toEqual(['low', 'high']);@@ -162,7 +157,6 @@ describe('applyModelsDevMatch', () => {* and a field added to `applyModelsDevMatch` alone fails the first case.*/describe('retireModelsDevMatch', () => {- const NO_VENDORS: ReadonlySet<string> = new Set();/** A match differing from the blank row in every field it fills, so 「the fill* set this」 is never indistinguishable from 「it was already blank」. */const sentinel: ModelsDevMatch = {@@ -177,7 +171,7 @@ describe('retireModelsDevMatch', () => {supports_reasoning: true,reasoning_efforts: ['sentinel'],};- const fill = () => applyModelsDevMatch(blankBackendModel(), sentinel, 'models_dev', 'codex', NO_VENDORS);+ const fill = () => applyModelsDevMatch(blankBackendModel(), sentinel, 'models_dev', 'opencode');const same = (left: unknown, right: unknown): boolean =>Array.isArray(left) && Array.isArray(right)@@ -234,187 +228,36 @@ describe('retireModelsDevMatch', () => {}});-/**- * The id rule, asserted where ids are written instead of at each writer.- *- * This started as a table of producers, and the table is what kept failing. The- * rule was written for the 「use what I typed」 escape; choosing a models.dev- * suggestion then shipped with a bare id OpenCode rejects; the picker's seed did- * it again. A list of producers cannot state this property, because the producer- * that is missing from the list is exactly the one nobody checked — and the list- * reads complete either way.- *- * So the property belongs to `draftWithId`, the one write that gives a draft row- * its id, and it is stated over arbitrary input rather than over known callers:- * whatever this function is handed, what it writes is admissible. A producer- * added later inherits it by calling the only function that can write the field,- * and the boundary test below is what keeps 「the only」 true.- */-describe('the id chokepoint', () => {- const VENDORS: StandardVendors = new Set(['anthropic', 'zhipuai']);- /** Not a list of cases that must pass — a spread of shapes the field can hold:- * no vendor, a standard one, an unknown one, the escape hatch, extra- * separators, and separators in the positions that parse to nothing. */- const HANDED = [- 'glm-5.2',- 'zhipuai/glm-5.2',- 'anthropic/claude',- 'nosuchvendor/glm-5.2',- 'custom/glm-5.2',- 'a/b/c',- '/leading',- 'trailing/',- ];- /** Who offered the model, when anyone did: the picker and the escape name no- * vendor, a models.dev match names its provider, standard or not. */- const OFFERED_BY = ['', 'zhipuai', 'nosuchvendor'];-- /** Admissible as the backend decides it, not as this test decides it. This- * used to ask the vendor list — whether OpenCode's own normalization agreed- * the segment was that segment — and that was the defect, stated as the- * property: `canonical_opencode_menu_identity` admits any segment matching- * its grammar and never consults `standard_vendors`, so the test called- * `nosuchvendor/glm-5.2` inadmissible and locked in a rewrite the server had- * no objection to. The one mirror of that rule is the authority here too. */- const admissible = (id: string): boolean => opencodeMenuIdentity(id, 'opencode');- /** Each bucket asserted below, and asserted to be inhabited: a filter that- * matches nothing states its property vacuously forever. */- const bucket = (of: (id: string) => boolean): string[] => {- const ids = HANDED.filter(of);- expect(ids.length).toBeGreaterThan(0);- return ids;- };-- it('round-trips an identity that already names a provider, standard or not', () => {- for (const handed of bucket(admissible)) {- for (const vendor of OFFERED_BY) {- // Byte-identical, `nosuchvendor/…` included. An id the user gave is the- // public model they asked for, and the server splits on the first- // separator, so `custom/nosuchvendor/glm-5.2` would be accepted as a- // different model with nothing downstream to notice the substitution.- expect(draftWithId(blankBackendModel(), handed, 'opencode', VENDORS, vendor).id).toBe(handed);- }+describe('the bare id chokepoint', () => {+ it('applies the same canonical spelling to OpenCode and Codex', () => {+ for (const id of ['glm-5.2', 'namespace/model', 'a/b/c']) {+ expect(backendModelId(` ${id} `)).toBe(id);+ expect(draftWithId(blankBackendModel(), id, 'opencode').id).toBe(id);+ expect(draftWithId(blankBackendModel(), id, 'codex').id).toBe(id);}});- it('gives an id that names no provider exactly one, from whoever offered it', () => {- for (const handed of bucket((id) => !id.includes('/'))) {- for (const vendor of OFFERED_BY) {- const written = draftWithId(blankBackendModel(), handed, 'opencode', VENDORS, vendor).id;- // The vendor list's one job: which segment a SOURCE's vendor maps to,- // byte-matching `opencode_model_id(source.vendor, model.id)`.- expect(written).toBe(`${inferProvider(vendor, VENDORS)}/${handed}`);- expect(admissible(written), `${handed} from ${vendor || 'nobody'} was written as ${written}`).toBe(true);- }- }- });-- it('leaves a malformed identity malformed instead of completing it into another one', () => {- for (const handed of bucket((id) => id.includes('/') && !admissible(id))) {- for (const vendor of OFFERED_BY) {- const written = draftWithId(blankBackendModel(), handed, 'opencode', VENDORS, vendor).id;- // The prefix is for an id that names no provider, and these name a- // broken one. `custom//leading` and `custom/trailing/` are both- // admissible to the server and neither is what was typed, so a typo- // would be saved as a row instead of refused at the field — which is- // where admissibility is asked, of this write's own output.- expect(written).toBe(handed);- expect(admissible(written)).toBe(false);- }- }- });-- it('is settled by one pass, so resolving an already-resolved id changes nothing', () => {- for (const handed of HANDED) {- for (const vendor of OFFERED_BY) {- const once = draftWithId(blankBackendModel(), handed, 'opencode', VENDORS, vendor);- // Why a producer may route a value through here twice — an editor that- // resolves at commit what the escape already resolved — without the- // prefix accumulating.- expect(draftWithId(once, once.id, 'opencode', VENDORS, vendor).id).toBe(once.id);- }- }- });+ it('defaults only a typed OpenCode row to Responses', () => {+ const row = model('kept', { display_name: 'Kept', context_window: 200_000, origin: 'manual' });- it('has nothing to prefix the blank floor with', () => {- // The one id that is not admissible and must still pass: a draft opens with- // no id at all, and 「required」 is the editor's answer to that, not a vendor.- expect(draftWithId(blankBackendModel(), '', 'opencode', VENDORS).id).toBe('');- });-- it('leaves a backend without provider segments alone', () => {- for (const handed of HANDED) {- expect(draftWithId(blankBackendModel(), handed, 'codex', VENDORS).id).toBe(handed);- }- });-- it('writes the id and nothing else', () => {- const row = model('kept', { display_name: 'Kept', context_window: 200_000, origin: 'models_dev' });- expect(draftWithId(row, 'glm-5.2', 'opencode', VENDORS)).toEqual({ ...row, id: 'custom/glm-5.2' });+ expect(draftWithId(row, 'glm-5.2', 'opencode')).toEqual({+ ...row,+ id: 'glm-5.2',+ native_protocol: 'openai_responses',+ });+ expect(draftWithId(row, 'glm-5.2', 'codex')).toEqual({ ...row, id: 'glm-5.2' });});- it('takes the offering provider when it is standard and falls back to custom when it is not', () => {- const from = (providerId: string, vendors: StandardVendors) => applyModelsDevMatch(+ it('takes both the bare id and native protocol from a models.dev match', () => {+ const filled = applyModelsDevMatch(blankBackendModel(),- { ...match, model_id: 'glm-5.2', provider_id: providerId },+ { ...match, model_id: 'glm-5.2', native_protocol: 'anthropic' },'models_dev','opencode',- vendors,- ).id;-- expect(from('zhipuai', VENDORS)).toBe('zhipuai/glm-5.2');- // Not `zhipuai/…`: an unrecognized vendor is one provider called `custom`- // there, so naming it would produce an id the menu rejects.- expect(from('zhipuai', new Set())).toBe('custom/glm-5.2');- });-- it('gives an id that names no vendor a custom provider', () => {- expect(backendModelId('glm-5.2', 'opencode', VENDORS)).toBe('custom/glm-5.2');- });-});--describe('the OpenCode identity rule', () => {- // One clause of `canonical_opencode_menu_identity` (config/v2_config.py) each,- // named by what the server checks, so a rule that moves there is findable- // here. The server is still the authority; this only decides early enough for- // the id field to say what is wrong before the `PUT` rejects the whole list.- it.each([- // `not separator`: nothing splits the halves.- ['glm-5.2', false],- // `not model_id`: the hole this closes. Any provider prefix is taken as- // given by the chokepoint, which hands `openai/` straight back — and- // `custom/` is the same hole behind the fallback prefix it adds itself.- ['openai/', false],- ['custom/', false],- // `not provider`: a leading separator names no provider.- ['/glm-5.2', false],- // The provider segment's own shape: lowercase alphanumeric runs, joined by- // single `.`, `_` or `-`.- ['OpenAI/glm-5.2', false],- ['-openai/glm-5.2', false],- ['open_ai/glm-5.2', true],- ['relay.example/glm-5.2', true],- // `identifier != identifier.strip()`, then `model_id != model_id.strip()`.- [' openai/glm-5.2', false],- ['openai/glm-5.2 ', false],- ['openai/ glm-5.2', false],- // Split on the FIRST separator, so a reseller keeps its own: this is- // provider `openrouter` serving the model `anthropic/claude-x`.- ['openrouter/anthropic/claude-x', true],- ['custom/glm-5.2-air', true],- ])('mirrors the server rule for %s', (id, admissible) => {- expect(opencodeMenuIdentity(id, 'opencode')).toBe(admissible);- });+ );- it('judges nothing for a backend whose ids have no segments to satisfy', () => {- // claude and codex ids are flat, and their admission rules stay the- // server's alone: a copy here would be a second authority over admission- // that drifts silently (Known-by-design 22).- for (const backend of ['claude', 'codex'] as const) {- for (const id of ['openai/', 'claude-sonnet-4-5', 'anything at all']) {- expect(opencodeMenuIdentity(id, backend)).toBe(true);- }- }+ expect(filled.id).toBe('glm-5.2');+ expect(filled.native_protocol).toBe('anthropic');});});diff --git a/ui/src/components/settings/models/backendCatalog.ts b/ui/src/components/settings/models/backendCatalog.tsindex 86e19b168..36f621fe8 100644--- a/ui/src/components/settings/models/backendCatalog.ts+++ b/ui/src/components/settings/models/backendCatalog.ts@@ -11,7 +11,6 @@// model the Agent may select; which supplier serves it stays with the Route, and// mixing the two here is what the contract's 「no Source id, no upstream model// id, no priority, no fallback」 rule exists to prevent.-import { buildIdentifier, type StandardVendors } from './menus/identifiers';import type { ModelsApi } from './modelsApi';import type {AgentBackend,@@ -153,6 +152,7 @@ export const candidateBackendModel = (candidate: ModelCandidate): BackendModel =display_name: candidate.display_name,origin: candidate.origin,reasoning_efforts: [...candidate.reasoning_efforts],+ ...(candidate.native_protocol ? { native_protocol: candidate.native_protocol } : {}),});/**@@ -311,89 +311,8 @@ export const pickerGroups = (return groups;};-/** The provider segment `canonical_opencode_menu_identity` accepts, verbatim. */-const OPENCODE_PROVIDER_SEGMENT = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;--/**- * Whether an id is a whole OpenCode menu identity, or only looks like one.- *- * `canonical_opencode_menu_identity` is the authority and stays the authority:- * this decides nothing the server does not, it just decides it early enough for- * the id field to say what is wrong while the user is still typing. Without it- * the dialog calls `openai/` valid, saves, and the `PUT` rejects the whole list- * for a row the user was told was fine.- *- * Both halves or neither. A provider prefix proves only that the left half is- * admissible — `openai/` has no right half at all, and `custom/` is the same- * hole behind the fallback prefix this file adds itself. This is the only rule- * that judges admissibility, which is why `backendModelId` can hand a malformed- * identity straight back instead of inventing a well-formed one. Splitting on- * the FIRST separator is what the backend does, so a reseller id keeps its own- * slashes (`openrouter/anthropic/claude-…` is provider `openrouter`, model- * `anthropic/claude-…`).- *- * The credential-material rule is deliberately not mirrored. It is a heuristic- * over secret shapes that the server can revise whenever it learns a new one,- * and a copy here would be a second opinion about what a secret looks like,- * drifting silently in whichever direction it was last edited. A row it catches- * is refused by the `PUT` with its own message.- */-export const opencodeMenuIdentity = (id: string, backend: AgentBackend): boolean => {- if (backend !== 'opencode') return true;- if (id !== id.trim()) return false;- const separator = id.indexOf('/');- if (separator <= 0) return false;- const model = id.slice(separator + 1);- return OPENCODE_PROVIDER_SEGMENT.test(id.slice(0, separator))- && model !== ''- && model === model.trim();-};--/**- * An id the backend will accept, whoever proposed it.- *- * Every id this UI *produces* comes through here — the models.dev suggestion the- * user chose and the 「use what I typed」 escape alike. That is the whole point of- * one function: an id the backend rejects is discovered at save time, long after- * the row was built, so the two places that mint one cannot each carry their own- * rule. An id the user types character by character is not produced here; it is- * theirs, and the id field validates it rather than rewriting it underneath them.- *- * OpenCode identifiers are `provider/model`, and what this function contributes- * is the provider segment an id does not have. So the question it asks is- * whether one is there at all, never whether the backend recognizes it:- * `canonical_opencode_menu_identity` admits any segment matching its grammar,- * `standard_vendors` membership included and not required, so `acme/model` is a- * public identity the server accepts, and rewriting it to `custom/acme/model`- * saves a different model than the user asked for — one the server accepts too,- * because it splits on the first separator, so nothing downstream would notice.- *- * The vendor list answers a different question, and only that one: which- * provider segment a SOURCE's vendor maps to, which has to byte-match- * `opencode_model_id(source.vendor, model.id)` or the menu rejects the checked- * value. That is what `vendor` is normalized through here — the proposing- * provider when there is one, and nothing when there is not, which- * `buildIdentifier` answers with `custom` for the same reason the backend does.- * Every other backend takes the id verbatim, because its ids have no segment to- * satisfy.- *- * An id that carries a provider segment is therefore taken as typed even when- * the whole identity is malformed. `openai/` is not a bare model id, and- * prefixing it would mint `custom/openai/` — a typo the server then accepts as- * the model `openai/`. Admissibility is `opencodeMenuIdentity`'s question, asked- * of this function's output at the field, and the only honest answer to a broken- * identity is to refuse it rather than to complete it into a different one.- */-export const backendModelId = (- id: string,- backend: AgentBackend,- standardVendors: StandardVendors,- vendor = '',-): string => {- if (backend !== 'opencode' || id === '') return id;- if (id.includes('/')) return id;- return buildIdentifier(vendor, id, standardVendors);-};+/** Canonicalize one user-proposed model identity without adding transport state. */+export const backendModelId = (id: string): string => id.trim();/*** The one write that gives a draft row its id.@@ -415,9 +334,13 @@ export const draftWithId = (draft: BackendModel,id: string,backend: AgentBackend,- standardVendors: StandardVendors,- vendor = '',-): BackendModel => ({ ...draft, id: backendModelId(id, backend, standardVendors, vendor) });+): BackendModel => ({+ ...draft,+ id: backendModelId(id),+ ...(backend === 'opencode'+ ? { native_protocol: draft.native_protocol ?? 'openai_responses' }+ : {}),+});/*** A models.dev match, poured into a draft — the id included.@@ -439,7 +362,6 @@ export const applyModelsDevMatch = (match: ModelsDevMatch,origin: BackendModelOrigin,backend: AgentBackend,- standardVendors: StandardVendors,): BackendModel => draftWithId({...draft,@@ -453,11 +375,10 @@ export const applyModelsDevMatch = (supports_tools: match.supports_tools,supports_reasoning: match.supports_reasoning,reasoning_efforts: [...match.reasoning_efforts],+ ...(backend === 'opencode' ? { native_protocol: match.native_protocol } : {}),},match.model_id,backend,- standardVendors,- match.provider_id,);const sameList = (left: readonly unknown[], right: readonly unknown[]): boolean =>@@ -481,6 +402,7 @@ export const MODELS_DEV_FIELDS = ['supports_tools','supports_reasoning','reasoning_efforts',+ 'native_protocol',] as const satisfies readonly (keyof BackendModel)[];/**@@ -505,7 +427,9 @@ export const retireModelsDevMatch = (const blank = blankBackendModel();const next: BackendModel = { ...draft, id };for (const field of MODELS_DEV_FIELDS) {- if (sameValue(draft[field], filled[field])) Object.assign(next, { [field]: blank[field] });+ if (!sameValue(draft[field], filled[field])) continue;+ if (blank[field] === undefined) delete (next as Partial<BackendModel>)[field];+ else Object.assign(next, { [field]: blank[field] });}return next;};@@ -524,7 +448,8 @@ export const sameBackendModel = (left: BackendModel, right: BackendModel): boole&& sameList(left.output_modalities, right.output_modalities)&& left.supports_tools === right.supports_tools&& left.supports_reasoning === right.supports_reasoning- && sameList(left.reasoning_efforts, right.reasoning_efforts);+ && sameList(left.reasoning_efforts, right.reasoning_efforts)+ && left.native_protocol === right.native_protocol;export const sameCatalog = (left: readonly BackendModel[], right: readonly BackendModel[]): boolean =>left.length === right.length && left.every((model, index) => sameBackendModel(model, right[index]));diff --git a/ui/src/components/settings/models/backendModelContract.test.ts b/ui/src/components/settings/models/backendModelContract.test.tsindex 13bcabb22..0d7afc160 100644--- a/ui/src/components/settings/models/backendModelContract.test.ts+++ b/ui/src/components/settings/models/backendModelContract.test.ts@@ -72,7 +72,7 @@ const MODEL: BackendModel = {const HOP_REF: RouteHopRef = {backend: 'opencode',- menu_model: 'custom/glm-5.2',+ menu_model: 'glm-5.2',source_id: 'src_relay0001',model_id: 'glm-5.2-air',position: 2,@@ -87,6 +87,7 @@ const CANDIDATE: Required<ModelCandidate> = {suppliers: [{ source_id: 'src_relay0001', source_name: 'relay.example', model_id: 'glm-5.2-air' }],origin: 'provider',group_if_removed: 'providers',+ native_protocol: 'openai_responses',};const MATCH: ModelsDevMatch = {@@ -102,6 +103,7 @@ const MATCH: ModelsDevMatch = {supports_tools: true,supports_reasoning: null,reasoning_efforts: ['low'],+ native_protocol: 'openai_responses',first_party: true,};@@ -112,7 +114,7 @@ const PUT: BackendModelsPut = {models: [MODEL, { ...MODEL, id: 'glm-5.2', models_dev_id: null, origin: 'manual' }],force: true,would_remove_hops: [HOP_REF],- would_interrupt: [{ backend: 'opencode', model_id: 'custom/glm-5.2', agents: ['pm'] }],+ would_interrupt: [{ backend: 'opencode', model_id: 'glm-5.2', agents: ['pm'] }],expected_suppliers: { 'glm-5.2': [{ source_id: 'src_relay0001', model_id: 'glm-5.2-air' }] },};@@ -170,7 +172,9 @@ describe('backend model catalog contract', () => {// And what the mirror calls optional is what the schema leaves out of// `required`, rather than a second opinion about the same field.expect(new Set(candidate.required))- .toEqual(new Set(Object.keys(CANDIDATE).filter((field) => field !== 'group_if_removed')));+ .toEqual(new Set(Object.keys(CANDIDATE).filter(+ (field) => !['group_if_removed', 'native_protocol'].includes(field),+ )));// The re-entry vocabulary, and the reason it is a separate field: the schema// forbids it on the two addable groups, because a candidate not in the list@@ -273,7 +277,7 @@ describe('backend model catalog contract', () => {contract_version: CONTRACT_VERSION,error: 'backend_model_in_route',would_remove_hops: [HOP_REF],- would_interrupt: [{ backend: 'opencode', model_id: 'custom/glm-5.2', agents: ['pm'] }],+ would_interrupt: [{ backend: 'opencode', model_id: 'glm-5.2', agents: ['pm'] }],});expect(guarded.code).toBe('backend_model_in_route');diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.tsindex bcf7702cb..a5873260d 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: 7,+ contract_version: 8,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/menus/identifiers.ts b/ui/src/components/settings/models/menus/identifiers.tsdeleted file mode 100644index 01be8da25..000000000--- a/ui/src/components/settings/models/menus/identifiers.ts+++ /dev/null@@ -1,37 +0,0 @@-// OpenCode identifier scheme (spec §4.4, locked 07-23; opencode-overlay.md).-// Identifiers are `provider/model-id`. The provider segment is the standard-// vendor id; unrecognizable vendors fall back to a single `custom/` provider.-// Identifiers are STABLE across Hub/Direct switches and across source-// add/remove/failover — they never encode a concrete source.--// The standard OpenCode vendor ids come from the backend via the opencode-// agent's `standard_vendors` projection (agent-supply v1.2), server-populated-// from STANDARD_OPENCODE_VENDOR_IDS (core/handlers/model_hub/identifiers.py).-// The UI threads that set through — it no longer hand-mirrors the list, so a-// divergence that would make `set_opencode_menu` reject identifiers can't arise.-export type StandardVendors = ReadonlySet<string>;--/**- * Provider segment for a source's model, per the FROZEN opencode-overlay.md- * contract: it is the SOURCE's vendor when that is a standard vendor id, else- * the single `custom` provider. It is deliberately NOT inferred from the model- * name — that must byte-match the backend's `opencode_model_id(source.vendor,- * model.id)`, or `set_opencode_menu` rejects the checked value. So- * `relay.example` (vendor `custom`) supplying- * `glm-5.2-air` yields `custom/glm-5.2-air` (not `zhipuai/…`).- */-export function inferProvider(sourceVendor: string, standardVendors: StandardVendors): string {- return standardVendors.has(sourceVendor) ? sourceVendor : 'custom';-}--/** Full prefixed identifier for a (source vendor, model id). */-export function buildIdentifier(sourceVendor: string, modelId: string, standardVendors: StandardVendors): string {- return `${inferProvider(sourceVendor, standardVendors)}/${modelId}`;-}--// `isSourceEligible` lived here and is gone: it mirrored the backend-// `_eligible_for_agent` predicate, whose server-owned inventory inputs the UI-// cannot reconstruct, so it was guaranteed to drift and offer rows the live API-// rejects. Contract v5-// publishes the answer as `AgentSupply.sources.eligibility`; read it through-// `../eligibility`.diff --git a/ui/src/components/settings/models/modelRows.ts b/ui/src/components/settings/models/modelRows.tsindex 7122fe223..8442e5e66 100644--- a/ui/src/components/settings/models/modelRows.ts+++ b/ui/src/components/settings/models/modelRows.ts@@ -1,6 +1,5 @@import { catalogModelIds } from './backendCatalog';import { eligibleSources } from './eligibility';-import { buildIdentifier } from './menus/identifiers';import type { RegionRead } from './regionRead';import type { AgentBackend, AgentChain, AgentSupply, Source } from './types';@@ -46,12 +45,9 @@ export function orderedRouteSources(agent: AgentSupply, sources: Source[]): Sour/** Whether the model already exists on an eligible supplier omitted from this Agent's order. */export function modelHasOffOrderSupplier(agent: AgentSupply, sources: Source[], modelId: string): boolean {const enabled = new Set(agent.sources?.order ?? []);- const standardVendors = new Set(agent.standard_vendors ?? []);return eligibleSources(sources, agent).some((source) => !enabled.has(source.id) && source.models.some((model) => (- agent.menu_kind === 'open'- ? buildIdentifier(source.vendor, model.id, standardVendors) === modelId- : model.id === modelId+ model.id === modelId)),);}diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex bdfcd0389..4ca587971 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -26,6 +26,7 @@ import type {ModelCandidate,ModelCandidateSupplier,ModelsDevMatch,+ NativeProtocol,OAuthFlow,ProbeResult,ResolutionEvent,@@ -295,6 +296,7 @@ export const CANDIDATE_ORIGINS: readonly CandidateOrigin[] = ['builtin', 'provid/** The groups the server names as a removed row's way back (C4). A value it* does not state is not a group, and `null` is a value it states. */const REENTRY_GROUPS: readonly ('builtin' | 'providers')[] = ['builtin', 'providers'];+const NATIVE_PROTOCOLS: readonly NativeProtocol[] = ['openai_responses', 'anthropic'];/** What the server says would offer this id again if it left the menu, read* only when the server says it. Absent stays absent rather than becoming@@ -332,6 +334,9 @@ const modelCandidates = (raw: unknown, fallbackOrigin: CandidateOrigin): ModelCaorigin: CANDIDATE_ORIGINS.includes(row.origin as CandidateOrigin)? row.origin as CandidateOrigin: fallbackOrigin,+ ...(NATIVE_PROTOCOLS.includes(row.native_protocol as NativeProtocol)+ ? { native_protocol: row.native_protocol as NativeProtocol }+ : {}),...reentryGroup(row),}];})diff --git a/ui/src/components/settings/models/runtimeLifecycle.test.ts b/ui/src/components/settings/models/runtimeLifecycle.test.tsindex 3e9cae651..3c1b8c00d 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: 7,+ contract_version: 8,host_platform: 'darwin-arm64',manifest: resolution === 'unresolved'? { name: 'cliproxyapi', resolution, assets: [] }diff --git a/ui/src/components/settings/models/supply.test.ts b/ui/src/components/settings/models/supply.test.tsindex a15072b32..9038d5884 100644--- a/ui/src/components/settings/models/supply.test.ts+++ b/ui/src/components/settings/models/supply.test.ts@@ -63,7 +63,6 @@ const hubAgent = (over: Partial<AgentSupply> = {}): AgentSupply => ({named_agents: [],menu: null,builtin_models: [],- standard_vendors: null,...over,});@@ -102,7 +101,7 @@ describe('agentGroupStatus', () => {expect(agentGroupStatus([{name: 'opencode',- effective_model_id: 'openai/gpt-5.6-terra',+ effective_model_id: 'gpt-5.6-terra',supply_status: 'interrupted',route_reason: 'route_unconfigured',},@@ -110,7 +109,7 @@ describe('agentGroupStatus', () => {expect(agentGroupStatus([{name: 'opencode',- effective_model_id: 'openai/gpt-5.6-terra',+ effective_model_id: 'gpt-5.6-terra',supply_status: 'interrupted',route_reason: null,},diff --git a/ui/src/components/settings/models/tierMutation.test.ts b/ui/src/components/settings/models/tierMutation.test.tsindex 6ce14d3b9..a94e20279 100644--- a/ui/src/components/settings/models/tierMutation.test.ts+++ b/ui/src/components/settings/models/tierMutation.test.ts@@ -21,7 +21,7 @@ const source = (tiers: string[], provenance?: ReasoningEffortsSource | null): Soreasoning_efforts: tiers,// `undefined` here means the key is absent, which is the payload a server// that predates the field sends and the parser is expected to tolerate. The- // v7 type has no shape for that, so the omission is asserted at the one key+ // v8 type has no shape for that, so the omission is asserted at the one key// it concerns rather than by loosening the whole fixture....(provenance === undefined? ({} as Pick<SuppliedModel, 'reasoning_efforts_source'>)diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 26c3e1b14..0f5bdfbfa 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -10,7 +10,7 @@// and the PR records the server implementation and feature-flag activation// edge. The client never synthesizes a fallback payload shape.-export const CONTRACT_VERSION = 7 as const;+export const CONTRACT_VERSION = 8 as const;export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;@@ -92,9 +92,9 @@ export type SourceUsage = {* (the model id matches a builtin catalog entry) are auto-provided and* read-only. `user` is a list the user typed; `null` means no rung applies.*- * Required here because `SuppliedModel` is the v7 API wire shape. The server+ * Required here because `SuppliedModel` is the v8 API wire shape. The server* normalizes older persisted rows before serialization; compatibility with a- * pre-v7 server belongs at the UI parsing boundary.+ * pre-v8 server belongs at the UI parsing boundary.*/export type ReasoningEffortsSource = 'upstream' | 'catalog' | 'user';@@ -155,7 +155,7 @@ export type MenuKind = 'fixed' | 'open';export type AgentMenu = {view: 'featured' | 'full';- /** prefixed identifiers, e.g. zhipuai/glm-5.2. */+ /** Bare canonical model identifiers, stored exactly as emitted. */checked: string[];};@@ -172,12 +172,14 @@ export const BACKEND_MODEL_OUTPUT_MODALITIES = ['text', 'image', 'audio', 'videoexport type BackendModelOutputModality = (typeof BACKEND_MODEL_OUTPUT_MODALITIES)[number];export const BACKEND_MODEL_ID_MAX_LENGTH = 256 as const;export const BACKEND_MODEL_EFFORT_MAX_LENGTH = 64 as const;+export const NATIVE_PROTOCOLS = ['openai_responses', 'anthropic'] as const;+export type NativeProtocol = (typeof NATIVE_PROTOCOLS)[number];/** One model a backend Agent exposes: backend menu metadata, never upstream* inventory and never a Route. The catalog deliberately holds no Source id,* upstream model id, priority or fallback — those stay with the Route. */export type BackendModel = {- /** The exact identifier the backend Agent emits. OpenCode uses provider/model. */+ /** The exact identifier the backend Agent emits. OpenCode stores a bare id. */id: string;display_name: string | null;origin: BackendModelOrigin;@@ -196,6 +198,8 @@ export type BackendModel = {/** Sent verbatim upstream. `[]` means the backend omits the effort parameter,* which is a decision — not an absence the UI may fill in. */reasoning_efforts: string[];+ /** Required for OpenCode rows and absent for Claude/Codex rows. */+ native_protocol?: NativeProtocol;/** Server-derived: visible, but not editable, removable or reorderable. */locked: boolean;/** Server-derived: false only for a backend-owned selector such as Claude@@ -246,6 +250,8 @@ export type ModelCandidateSupplier = {* the catalog draft on selection (C2). */export type ModelCandidate = {id: string;+ /** Server-derived for OpenCode candidates; absent for other backends. */+ native_protocol?: NativeProtocol;display_name: string | null;reasoning_efforts: string[];/** In the backend's Source order. Empty is meaningful: nothing supplies this@@ -299,6 +305,7 @@ export type ModelsDevMatch = {supports_tools: boolean | null;supports_reasoning: boolean | null;reasoning_efforts: string[];+ native_protocol: NativeProtocol;/** Whether this provider is the model's own vendor rather than an aggregator* reselling it (v2 C7). Optional because it postdates the shipped shape: a* server that does not state it leaves the ranking to the order it served. */@@ -421,10 +428,6 @@ export type AgentSupply = {* built-in model ids (from vibe/backend_model_catalog.py). null for open-menu* backends. The route editor renders these; the UI never hardcodes menus. */builtin_models?: string[] | null;- /** v1.2 read-only projection: opencode only — server mirror of- * STANDARD_OPENCODE_VENDOR_IDS, so the UI never hand-mirrors vendor prefixes.- * null otherwise. */- standard_vendors?: string[] | null;};// ── migration-scan.schema.json ──────────────────────────────────────────diff --git a/vibe/api.py b/vibe/api.pyindex 85a37d30e..002677b41 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -5961,13 +5961,6 @@ async def opencode_options_async(cache_projection_matches = (cache_entry.get("model_hub_projection") == projection_key)- if (- cache_data- and cache_age < _OPENCODE_OPTIONS_TTL_SECONDS- and cache_projection_matches- ):- return {"ok": True, "data": cache_data, "cached": True}-server = Nonetry:from config.v2_compat import to_app_config@@ -5976,8 +5969,23 @@ async def opencode_options_async(OpenCodeServerManager,build_reasoning_effort_options,)+ from modules.agents.opencode.utils import opencode_model_picker_valuev2_config = V2Config.load()+ model_hub_agents = getattr(getattr(v2_config, "model_hub", None), "agents", {})+ model_hub_agent = (+ model_hub_agents.get("opencode")+ if isinstance(model_hub_agents, dict)+ else None+ )+ model_hub_mode = getattr(model_hub_agent, "mode", "direct")+ if (+ model_hub_mode != "hub"+ and cache_data+ and cache_age < _OPENCODE_OPTIONS_TTL_SECONDS+ and cache_projection_matches+ ):+ return {"ok": True, "data": cache_data, "cached": True}config = to_app_config(v2_config)if not config.opencode:return {"ok": False, "error": "opencode disabled"}@@ -5993,16 +6001,22 @@ async def opencode_options_async(provider_id = provider.get("id") or provider.get("provider_id") or provider.get("name")if not provider_id:continue- model_ids = []+ model_items = []provider_models = provider.get("models", {})if isinstance(provider_models, dict):- model_ids = list(provider_models.keys())+ model_items = list(provider_models.items())elif isinstance(provider_models, list):- model_ids = [- model.get("id") for model in provider_models if isinstance(model, dict) and model.get("id")+ model_items = [+ (model.get("id"), model)+ for model in provider_models+ if isinstance(model, dict) and model.get("id")]- for model_id in model_ids:- model_key = f"{provider_id}/{model_id}"+ for model_id, model_info in model_items:+ model_key = opencode_model_picker_value(+ provider_id,+ model_id,+ model_info,+ )options[model_key] = builder(models, model_key)return options@@ -6023,45 +6037,46 @@ async def opencode_options_async())models = await asyncio.wait_for(model_request, timeout=timeout_seconds)- provider_catalog_available = True- try:- providers_raw = await asyncio.wait_for(server.get_providers(), timeout=timeout_seconds)- except Exception as exc:- logger.debug("OpenCode provider auth filter skipped: provider list failed: %s", exc)- providers_raw = {}- provider_catalog_available = False- try:- from vibe.opencode_config import read_opencode_provider_auth_entries+ if model_hub_mode != "hub":+ provider_catalog_available = True+ try:+ providers_raw = await asyncio.wait_for(server.get_providers(), timeout=timeout_seconds)+ except Exception as exc:+ logger.debug("OpenCode provider auth filter skipped: provider list failed: %s", exc)+ providers_raw = {}+ provider_catalog_available = False+ try:+ from vibe.opencode_config import read_opencode_provider_auth_entries- auth_entries = await asyncio.to_thread(- read_opencode_provider_auth_entries, logger_instance=logger- )- except Exception as exc:- logger.debug("OpenCode provider auth filter skipped: auth read failed: %s", exc)- auth_entries = {}- allowed_provider_ids: set[str] | None = None- if provider_catalog_available:- config_api_key_provider_ids = await _read_opencode_config_api_key_provider_ids()- custom_config_provider_ids = await _read_opencode_custom_provider_ids()- allowed_provider_ids = _configured_opencode_provider_ids(- providers_raw=providers_raw,- auth_entries=auth_entries,- config_api_key_provider_ids=config_api_key_provider_ids,- custom_config_provider_ids=custom_config_provider_ids,- )- models = _filter_opencode_models_to_configured_providers(+ auth_entries = await asyncio.to_thread(+ read_opencode_provider_auth_entries, logger_instance=logger+ )+ except Exception as exc:+ logger.debug("OpenCode provider auth filter skipped: auth read failed: %s", exc)+ auth_entries = {}+ allowed_provider_ids: set[str] | None = None+ if provider_catalog_available:+ config_api_key_provider_ids = await _read_opencode_config_api_key_provider_ids()+ custom_config_provider_ids = await _read_opencode_custom_provider_ids()+ allowed_provider_ids = _configured_opencode_provider_ids(+ providers_raw=providers_raw,+ auth_entries=auth_entries,+ config_api_key_provider_ids=config_api_key_provider_ids,+ custom_config_provider_ids=custom_config_provider_ids,+ )+ models = _filter_opencode_models_to_configured_providers(+ models,+ providers_raw=providers_raw,+ auth_entries=auth_entries,+ config_api_key_provider_ids=config_api_key_provider_ids,+ custom_config_provider_ids=custom_config_provider_ids,+ )+ user_model_index = await _read_opencode_user_model_index()+ models = _merge_opencode_user_models(models,- providers_raw=providers_raw,- auth_entries=auth_entries,- config_api_key_provider_ids=config_api_key_provider_ids,- custom_config_provider_ids=custom_config_provider_ids,+ user_model_index,+ allowed_provider_ids=allowed_provider_ids,)- user_model_index = await _read_opencode_user_model_index()- models = _merge_opencode_user_models(- models,- user_model_index,- allowed_provider_ids=allowed_provider_ids,- )defaults = await asyncio.wait_for(server.get_default_config(expanded_cwd), timeout=timeout_seconds)reasoning_options = _build_reasoning_options(models, build_reasoning_effort_options)data = {@@ -6860,7 +6875,13 @@ def _opencode_model_options(_oc_is_user_model = Nonecustom_ids = set()+ from modules.agents.opencode.utils import (+ opencode_model_is_hub_projected,+ opencode_model_picker_value,+ )+provider_filter = (provider or "").strip().lower() or None+ matched_provider_filter = Falseproviders_out: list[dict] = []models_out: list[dict] = []for prov in providers_raw:@@ -6871,7 +6892,7 @@ def _opencode_model_options(continueif provider_filter and pid.lower() != provider_filter:continue- providers_out.append({"id": pid, "name": prov.get("name") or pid, "custom": pid in custom_ids})+ matched_provider_filter = Trueprov_models = prov.get("models")if isinstance(prov_models, dict):model_items = list(prov_models.items())@@ -6879,28 +6900,34 @@ def _opencode_model_options(model_items = [(m.get("id"), m) for m in prov_models if isinstance(m, dict) and m.get("id")]else:model_items = []+ if not model_items or not all(+ opencode_model_is_hub_projected(model_info)+ for _model_id, model_info in model_items+ ):+ providers_out.append({"id": pid, "name": prov.get("name") or pid, "custom": pid in custom_ids})for model_id, model_info in model_items:if not isinstance(model_id, str) or not model_id:continue- value = f"{pid}/{model_id}"+ projected = opencode_model_is_hub_projected(model_info)+ value = opencode_model_picker_value(pid, model_id, model_info)source = "catalog"if _oc_is_user_model is not None and isinstance(model_info, dict) and _oc_is_user_model(model_id, model_info):source = "user"- models_out.append(- {- "value": value,- "provider": pid,- "default": default_block.get(pid) == model_id,- "source": source,- "reasoning_efforts": _effort_values(reasoning_map.get(value)),- }- )+ row = {+ "value": value,+ "default": default_block.get(pid) == model_id,+ "source": source,+ "reasoning_efforts": _effort_values(reasoning_map.get(value)),+ }+ if not projected:+ row["provider"] = pid+ models_out.append(row)opencode_cfg = getattr(getattr(config, "agents", None), "opencode", None) if config is not None else Nonedefault_provider = getattr(opencode_cfg, "default_provider", None) if opencode_cfg is not None else Nonenotes: list[str] = []- if provider_filter and not providers_out:+ if provider_filter and not matched_provider_filter:notes.append(f"no configured OpenCode provider matches '{provider}'")return {"ok": True,diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.pyindex a80e6d48b..3ee272912 100644--- a/vibe/model_hub_runtime/config.py+++ b/vibe/model_hub_runtime/config.py@@ -49,6 +49,7 @@ def write_engine_config("max-retry-credentials": 1,"max-retry-interval": 0,"disable-cooling": True,+ "disable-claude-cloak-mode": True,"save-cooldown-status": False,"transient-error-cooldown-seconds": -1,"quota-exceeded": {@@ -70,14 +71,28 @@ def _append_source(payload: dict[str, Any], source: SourceRecord, store: EngineS# OAuth credentials are engine auth files, not YAML credential values.returnapi_key = store.read_api_key(source.credential_ref)- models = [{"name": model, "alias": model} for model in source.model_ids]+ reasoning_by_model = dict(source.model_reasoning_efforts)+ models = []+ for model in source.model_ids:+ entry: dict[str, Any] = {"name": model, "alias": model}+ reasoning_efforts = reasoning_by_model.get(model, ())+ if reasoning_efforts:+ # CLIProxyAPI's measured model-registration shape is strongest-first.+ entry["thinking"] = {"levels": list(reversed(reasoning_efforts))}+ models.append(entry)if source.protocol == "anthropic":base_url = source.base_urlif not base_url:base_url = official_api_key_base_url(source.vendor)if not base_url:raise EngineStateError("Anthropic-compatible source requires a base URL")- entry: dict[str, Any] = {"api-key": api_key, "prefix": source.prefix, "base-url": base_url}+ entry: dict[str, Any] = {+ "api-key": api_key,+ "prefix": source.prefix,+ "base-url": base_url,+ "cloak": {"mode": "never"},+ "rebuild-mid-system-message": False,+ }if models:entry["models"] = modelspayload.setdefault("claude-api-key", []).append(entry)diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex 1969e888f..8870ecb3f 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -40,9 +40,37 @@ class SourceRecord:allowed_origins: tuple[str, ...]model_ids: tuple[str, ...]prefix: str+ model_reasoning_efforts: tuple[tuple[str, tuple[str, ...]], ...] = ()@classmethoddef from_payload(cls, payload: dict[str, Any]) -> SourceRecord:+ try:+ raw_reasoning_efforts = payload["model_reasoning_efforts"]+ except KeyError as exc:+ raise EngineStateError("invalid engine source reasoning state") from exc+ if not isinstance(raw_reasoning_efforts, list):+ raise EngineStateError("invalid engine source reasoning state")+ raw_model_ids = payload.get("model_ids", [])+ if not isinstance(raw_model_ids, list):+ raise EngineStateError("invalid engine source state")+ model_ids = tuple(str(model) for model in raw_model_ids)+ parsed_reasoning_efforts: list[tuple[str, tuple[str, ...]]] = []+ seen_reasoning_models: set[str] = set()+ for item in raw_reasoning_efforts:+ if (+ not isinstance(item, list)+ or len(item) != 2+ or not isinstance(item[0], str)+ or not item[0]+ or item[0] not in model_ids+ or not isinstance(item[1], list)+ or any(not isinstance(effort, str) or not effort for effort in item[1])+ or len(set(item[1])) != len(item[1])+ or item[0] in seen_reasoning_models+ ):+ raise EngineStateError("invalid engine source reasoning state")+ seen_reasoning_models.add(item[0])+ parsed_reasoning_efforts.append((item[0], tuple(item[1])))return cls(source_id=str(payload["source_id"]),vendor=str(payload["vendor"]),@@ -50,8 +78,9 @@ class SourceRecord:base_url=str(payload["base_url"]) if payload.get("base_url") else None,credential_ref=str(payload["credential_ref"]),allowed_origins=tuple(str(item) for item in payload.get("allowed_origins", [])),- model_ids=tuple(str(model) for model in payload.get("model_ids", [])),+ model_ids=model_ids,prefix=str(payload["prefix"]),+ model_reasoning_efforts=tuple(parsed_reasoning_efforts),)@@ -209,6 +238,19 @@ class EngineStateStore:raise EngineStateError("source requires at least one model id")if any(not model for model in model_ids):raise EngineStateError("model id cannot be empty")+ reasoning_by_model: dict[str, tuple[str, ...]] = {}+ for model_id, efforts in binding.model_reasoning_efforts:+ normalized_model_id = str(model_id).strip()+ if not normalized_model_id or normalized_model_id not in model_ids:+ raise EngineStateError("reasoning model id is not registered")+ if normalized_model_id in reasoning_by_model:+ raise EngineStateError("duplicate reasoning model id")+ normalized_efforts = tuple(+ dict.fromkeys(str(effort).strip() for effort in efforts)+ )+ if any(not effort for effort in normalized_efforts):+ raise EngineStateError("reasoning effort cannot be empty")+ reasoning_by_model[normalized_model_id] = normalized_effortsrecords.append(SourceRecord(source_id=source_id,@@ -225,6 +267,7 @@ class EngineStateStore:if previouselse f"avibe-{secrets.token_hex(12)}"),+ model_reasoning_efforts=tuple(reasoning_by_model.items()),))self._write_sources(records)@@ -246,7 +289,18 @@ class EngineStateStore:raise EngineStateError("source requires at least one model id")if any(not model for model in models):raise EngineStateError("model id cannot be empty")- updated_record = SourceRecord(**{**asdict(current), "model_ids": models})+ retained_reasoning = tuple(+ (model_id, efforts)+ for model_id, efforts in current.model_reasoning_efforts+ if model_id in models+ )+ updated_record = SourceRecord(+ **{+ **asdict(current),+ "model_ids": models,+ "model_reasoning_efforts": retained_reasoning,+ }+ )self._write_sources([updated_record if source.source_id == source_id else source for source in sources])return updated_record@@ -426,6 +480,10 @@ class EngineStateStore:**asdict(source),"allowed_origins": list(source.allowed_origins),"model_ids": list(source.model_ids),+ "model_reasoning_efforts": [+ [model_id, list(efforts)]+ for model_id, efforts in source.model_reasoning_efforts+ ],}for source in sources]diff --git a/vibe/models_dev_catalog.py b/vibe/models_dev_catalog.pyindex be049adeb..b71889340 100644--- a/vibe/models_dev_catalog.py+++ b/vibe/models_dev_catalog.py@@ -62,6 +62,22 @@ def _first_party_vendor(return max(matches, key=lambda item: len(item["prefix"]))["vendor_id"]+def native_protocol_for_model_id(+ model_id: str,+ *,+ vendor_map: dict[str, Any] | None = None,+) -> str:+ """Derive the OpenCode-facing protocol from the model family authority."""++ family_id = model_id.rsplit("/", 1)[-1]+ resolved_map = vendor_map if vendor_map is not None else load_model_vendor_map()+ return (+ "anthropic"+ if _first_party_vendor(family_id, resolved_map) == "anthropic"+ else "openai_responses"+ )++def _vendor_rank(vendor_id: str,*,@@ -347,6 +363,10 @@ def search_models_dev(query: str) -> list[dict[str, Any]]:else None),"reasoning_efforts": reasoning_efforts,+ "native_protocol": native_protocol_for_model_id(+ model_id,+ vendor_map=vendor_map,+ ),}admitted = admissible_backend_model(None,@@ -362,6 +382,7 @@ def search_models_dev(query: str) -> list[dict[str, Any]]:"supports_tools": row["supports_tools"],"supports_reasoning": row["supports_reasoning"],"reasoning_efforts": row["reasoning_efforts"],+ "native_protocol": row["native_protocol"],},)if admitted is None:@@ -378,6 +399,7 @@ def search_models_dev(query: str) -> list[dict[str, Any]]:"supports_tools": admitted.supports_tools,"supports_reasoning": admitted.supports_reasoning,"reasoning_efforts": admitted.reasoning_efforts,+ "native_protocol": admitted.native_protocol,})candidates.setdefault(admitted.id, []).append((score, provider_id, row))diff --git a/vibe/opencode_config.py b/vibe/opencode_config.pyindex df78192e6..4c15d0005 100644--- a/vibe/opencode_config.py+++ b/vibe/opencode_config.py@@ -2,7 +2,6 @@from __future__ import annotations-import hashlibimport jsonimport loggingimport re@@ -22,7 +21,6 @@ _CUSTOM_PROVIDER_LABELS = {"openai-compatible": "OpenAI compatible","anthropic-compatible": "Anthropic compatible",}-MODEL_HUB_RUNTIME_PROVIDER_PREFIX = "avibe-model-hub-"_RESERVED_PROVIDER_IDS = {"alibaba-cn","anthropic",@@ -54,6 +52,51 @@ class OpenCodeConfigProbeResult:errors: list[tuple[Path, str]] = field(default_factory=list)+class OpenCodeRuntimeConfigInvalidError(RuntimeError):+ """The inherited OpenCode runtime override cannot be safely managed."""+++def managed_opencode_runtime_config_content(raw: str | bytes | None) -> str:+ """Apply Avibe-owned OpenCode runtime policy without mutating user config."""++ if raw is None:+ payload: Any = {}+ else:+ try:+ content = raw.decode("utf-8-sig") if isinstance(raw, bytes) else raw+ if not isinstance(content, str):+ raise TypeError("runtime config override must be text")+ payload = parse_jsonc_object(content)+ except (TypeError, UnicodeDecodeError, ValueError) as exc:+ raise OpenCodeRuntimeConfigInvalidError(+ "OpenCode runtime config override is invalid JSONC"+ ) from exc+ if not isinstance(payload, dict):+ raise OpenCodeRuntimeConfigInvalidError(+ "OpenCode runtime config override must be a JSON object"+ )++ tools = payload.get("tools")+ managed_tools = dict(tools) if isinstance(tools, dict) else {}+ managed_tools["skill"] = False+ payload["tools"] = managed_tools++ permission = payload.get("permission")+ if permission is None:+ managed_permission: dict[str, Any] = {}+ elif isinstance(permission, str):+ managed_permission = {"*": permission}+ elif isinstance(permission, dict):+ managed_permission = dict(permission)+ else:+ raise OpenCodeRuntimeConfigInvalidError(+ "OpenCode runtime permission override must be a string or object"+ )+ managed_permission["skill"] = "deny"+ payload["permission"] = managed_permission+ return json.dumps(payload, ensure_ascii=True, sort_keys=True, separators=(",", ":")) + "\n"++def get_opencode_config_paths(home: Path | None = None) -> list[Path]:resolved_home = home or Path.home()return [@@ -494,7 +537,7 @@ def _normalize_model_id(model_id: str, *, provider_id: str | None = None) -> strreturn candidate-def _normalize_custom_provider_id(provider_id: str, *, reject_reserved: bool = False) -> str:+def _normalize_custom_provider_id(provider_id: str) -> str:if not isinstance(provider_id, str) or not provider_id.strip():raise ValueError("provider_id is required")candidate = provider_id.strip().lower()@@ -502,8 +545,6 @@ def _normalize_custom_provider_id(provider_id: str, *, reject_reserved: bool = Fraise ValueError("provider_id is too long")if not re.fullmatch(r"[a-z0-9][a-z0-9_.-]*", candidate):raise ValueError("provider_id must use lowercase letters, numbers, dot, hyphen, or underscore")- if reject_reserved and is_reserved_opencode_provider_id(candidate):- raise ValueError("provider_id already exists")return candidate@@ -513,13 +554,6 @@ def is_reserved_opencode_provider_id(provider_id: str) -> bool:return provider_id.strip().lower() in _RESERVED_PROVIDER_IDS-def model_hub_runtime_provider_id(gateway_token: str) -> str:- """Derive the private OpenCode provider namespace for one gateway process."""-- digest = hashlib.sha256(gateway_token.encode()).hexdigest()[:24]- return f"{MODEL_HUB_RUNTIME_PROVIDER_PREFIX}{digest}"--def get_opencode_custom_provider_adapter(provider_id: str,provider_config: Dict[str, Any],@@ -729,15 +763,24 @@ def upsert_opencode_custom_provider(logger_instance: Optional[logging.Logger] = None,) -> Path:active_logger = logger_instance or logger- provider_id = _normalize_custom_provider_id(provider_id, reject_reserved=True)+ provider_id = _normalize_custom_provider_id(provider_id)name = _normalize_custom_provider_name(name)adapter = _normalize_custom_provider_adapter(adapter)base_url = _normalize_base_url(base_url)config, target_path = _load_or_create_user_config(home=home, logger_instance=active_logger)+ provider_map = config.get("provider")+ provider_exists = isinstance(provider_map, dict) and provider_id in provider_map+ if not provider_exists and (+ is_reserved_opencode_provider_id(provider_id)+ or provider_id.startswith("avibe-")+ ):+ raise ValueError("provider_id already exists")provider_config = _get_provider_config(config, provider_id)- existing_meta = provider_config.get(_CUSTOM_PROVIDER_META_KEY)- if provider_config and not (isinstance(existing_meta, dict) and existing_meta.get("custom") is True):+ if provider_exists and get_opencode_custom_provider_adapter(+ provider_id,+ provider_config,+ ) is None:raise ValueError("provider_id already exists")options = provider_config.setdefault("options", {})