Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(models): unify Model Hub turn resolution (#1029)

Call White71636ca3d857
diff --git a/core/controller.py b/core/controller.py
index e0d7c407c..86632dd98 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -293,7 +293,15 @@ class Controller:
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
from modules.agents.model_hub import ModelHubRuntimeRouter
- self.model_hub_service = create_default_service()
+ def default_vibe_agent_model(backend: str) -> Optional[str]:
+ agent = self.vibe_agent_store.get_default_agent()
+ if agent is None or agent.backend != backend:
+ return None
+ return agent.model
+
+ self.model_hub_service = create_default_service(
+ requested_model_override=default_vibe_agent_model,
+ )
self.model_hub_turn_gateway = ModelHubTurnGateway(self.model_hub_service)
self.model_hub_runtime = ModelHubRuntimeRouter(
service=self.model_hub_service,
diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.py
new file mode 100644
index 000000000..95c0545c4
--- /dev/null
+++ b/core/handlers/model_hub/resolver.py
@@ -0,0 +1,257 @@
+"""Pure Model Hub turn resolution shared by runtime and API projections."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, replace
+from datetime import datetime
+from typing import Literal
+
+from config.v2_config import ModelHubConfig, ModelHubSourceConfig
+
+from .identifiers import opencode_provider_id, parse_opencode_model_id
+
+
+BackendName = Literal["claude", "codex", "opencode"]
+ResolutionChannel = Literal["direct", "native_cli", "hub", "unavailable"]
+
+
+@dataclass(frozen=True)
+class ModelHubTurnResolution:
+ backend: BackendName
+ channel: ResolutionChannel
+ requested_model: str
+ target_model: str
+ source: ModelHubSourceConfig | None
+ matching_sources: tuple[ModelHubSourceConfig, ...] = ()
+ candidates: tuple[ModelHubSourceConfig, ...] = ()
+ provider: str | None = None
+ mapping_applied: bool = False
+ recoverable_source_ids: tuple[str, ...] = ()
+
+
+def allowed_origins(source: ModelHubSourceConfig) -> tuple[str, ...]:
+ if source.kind == "api_key":
+ return ()
+ if source.vendor == "anthropic":
+ return ("claude",)
+ if source.vendor == "openai":
+ return ("codex",)
+ return ()
+
+
+def source_eligible_for_backend(source: ModelHubSourceConfig, backend: str) -> bool:
+ if source.kind == "api_key":
+ return source.supply_channel == "hub"
+ return backend in allowed_origins(source)
+
+
+def source_retry_ready(source: ModelHubSourceConfig, now: datetime | None) -> bool:
+ if source.state.status != "cooldown" or now is None:
+ return False
+ try:
+ retry_at = datetime.fromisoformat((source.state.retry_at or "").replace("Z", "+00:00"))
+ except ValueError:
+ return False
+ return retry_at <= now
+
+
+def source_after_cooldown_recovery(
+ source: ModelHubSourceConfig,
+ now: datetime | None,
+) -> ModelHubSourceConfig:
+ """Project the source state used by the next turn after retry recovery."""
+
+ if not source_retry_ready(source, now):
+ return source
+ return replace(
+ source,
+ state=replace(
+ source.state,
+ status=("active" if source.supply_channel == "native_cli" else "standby"),
+ retry_at=None,
+ detail_key=None,
+ ),
+ )
+
+
+def normalize_opencode_requested_model(
+ requested_model: str,
+ checked_identifiers: tuple[str, ...],
+) -> str | None:
+ """Match a full or uniquely bare OpenCode model to its checked identifier."""
+
+ 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
+
+
+def resolve_model_hub_turn(
+ config: ModelHubConfig,
+ backend: BackendName,
+ requested_model: str,
+ *,
+ now: datetime | None = None,
+ unavailable_source_ids: frozenset[str] = frozenset(),
+ supply_channel: Literal["hub"] | None = None,
+) -> ModelHubTurnResolution:
+ """Resolve one turn without starting runtimes, reading credentials, or mutating state.
+
+ ``now`` makes cooldown recovery deterministic. ``unavailable_source_ids`` is
+ caller-supplied runtime viability discovered before this pure decision.
+ """
+
+ requested_model = str(requested_model or "").strip()
+ agent = config.agents[backend]
+ if agent.mode == "direct":
+ return ModelHubTurnResolution(
+ backend=backend,
+ channel="direct",
+ requested_model=requested_model,
+ target_model=requested_model,
+ source=None,
+ )
+
+ if backend == "opencode":
+ checked = tuple(agent.menu.checked if agent.menu else ())
+ if not checked:
+ return ModelHubTurnResolution(
+ backend=backend,
+ channel="direct",
+ requested_model=requested_model,
+ target_model=requested_model,
+ source=None,
+ )
+ if not requested_model:
+ for identifier in checked:
+ candidate = resolve_model_hub_turn(
+ config,
+ backend,
+ identifier,
+ now=now,
+ unavailable_source_ids=unavailable_source_ids,
+ supply_channel=supply_channel,
+ )
+ if candidate.source is not None:
+ return candidate
+ return ModelHubTurnResolution(
+ backend=backend,
+ channel="unavailable",
+ requested_model=requested_model,
+ target_model=requested_model,
+ source=None,
+ )
+ normalized = normalize_opencode_requested_model(requested_model, checked)
+ if normalized is None:
+ return ModelHubTurnResolution(
+ backend=backend,
+ channel="unavailable",
+ requested_model=requested_model,
+ target_model=requested_model,
+ source=None,
+ )
+ requested_model = normalized
+
+ mapping = (
+ next(
+ (
+ item
+ for item in agent.mappings
+ if item.enabled and item.builtin_id == requested_model
+ ),
+ None,
+ )
+ if agent.menu_kind == "fixed"
+ else None
+ )
+ target_model = mapping.target_model_id if mapping is not None else requested_model
+ mapping_applied = target_model != requested_model
+ provider: str | None = None
+
+ if backend == "opencode":
+ try:
+ provider, target_model = parse_opencode_model_id(target_model)
+ except ValueError:
+ return ModelHubTurnResolution(
+ backend=backend,
+ channel="unavailable",
+ requested_model=requested_model,
+ target_model=target_model,
+ source=None,
+ mapping_applied=mapping_applied,
+ )
+ if f"{provider}/{target_model}" not in agent.menu.checked:
+ return ModelHubTurnResolution(
+ backend=backend,
+ channel="unavailable",
+ requested_model=requested_model,
+ target_model=target_model,
+ source=None,
+ provider=provider,
+ mapping_applied=mapping_applied,
+ )
+ if not target_model:
+ return ModelHubTurnResolution(
+ backend=backend,
+ channel=(
+ "direct"
+ if backend != "opencode" and mapping is None
+ else "unavailable"
+ ),
+ requested_model=requested_model,
+ target_model=target_model,
+ source=None,
+ provider=provider,
+ mapping_applied=mapping_applied,
+ )
+
+ by_id = {source.id: source for source in config.sources}
+ matching_sources = tuple(
+ source
+ for source in (by_id[source_id] for source_id in config.priority_order)
+ if source_eligible_for_backend(source, backend)
+ and (provider is None or opencode_provider_id(source.vendor) == provider)
+ and any(model.id == target_model for model in source.models)
+ )
+ if backend != "opencode" and mapping is None and not matching_sources:
+ return ModelHubTurnResolution(
+ backend=backend,
+ channel="direct",
+ requested_model=requested_model,
+ target_model=requested_model,
+ source=None,
+ )
+
+ candidates: list[ModelHubSourceConfig] = []
+ recoverable_source_ids: list[str] = []
+ for source in matching_sources:
+ if supply_channel is not None and source.supply_channel != supply_channel:
+ continue
+ if source.state.status == "cooldown":
+ if not source_retry_ready(source, now):
+ continue
+ recoverable_source_ids.append(source.id)
+ if source.id in unavailable_source_ids or source.state.status == "error":
+ continue
+ candidates.append(source)
+
+ source = candidates[0] if candidates else None
+ return ModelHubTurnResolution(
+ backend=backend,
+ channel=source.supply_channel if source is not None else "unavailable",
+ requested_model=requested_model,
+ target_model=target_model,
+ source=source,
+ matching_sources=matching_sources,
+ candidates=tuple(candidates),
+ provider=provider,
+ mapping_applied=mapping_applied,
+ recoverable_source_ids=tuple(recoverable_source_ids),
+ )
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 44e06d142..e8cafed81 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -66,6 +66,14 @@ from .oauth import (
OAuthFlowRegistry,
UnavailableNativeOAuthAdapter,
)
+from .resolver import (
+ BackendName,
+ ModelHubTurnResolution,
+ allowed_origins,
+ resolve_model_hub_turn,
+ source_after_cooldown_recovery,
+ source_eligible_for_backend,
+)
from .revocations import CredentialRevocationJournal
CONTRACT_VERSION = 1
@@ -124,6 +132,19 @@ class V2ModelHubConfigStore:
config.model_hub = model_hub
config.save()
+ def requested_model(self, backend: str) -> str:
+ try:
+ config = V2Config.load()
+ except FileNotFoundError:
+ config = default_config()
+ backend_config = getattr(config.agents, backend, None)
+ model = str(getattr(backend_config, "default_model", None) or "").strip()
+ if backend == "opencode" and model and "/" not in model:
+ provider = str(getattr(backend_config, "default_provider", None) or "").strip()
+ if provider:
+ return f"{provider}/{model}"
+ return model
+
class UnavailableEngineAdapter:
"""Explicit fail-closed adapter for isolated callers and tests."""
@@ -280,21 +301,11 @@ def _default_protocol(vendor: str) -> str:
return "openai_compatible"
-def _allowed_origins(source: ModelHubSourceConfig) -> tuple[str, ...]:
- if source.kind == "api_key":
- return ()
- if source.vendor == "anthropic":
- return ("claude",)
- if source.vendor == "openai":
- return ("codex",)
- return ()
-
-
def _binding(source: ModelHubSourceConfig) -> SourceBinding:
if not source.credential_ref:
raise ModelHubError("engine_down", status=503)
- allowed_origins = _allowed_origins(source)
- if source.kind == "subscription" and not allowed_origins:
+ source_origins = allowed_origins(source)
+ if source.kind == "subscription" and not source_origins:
raise ModelHubError("mode_switch_blocked", status=409)
return SourceBinding(
source_id=source.id,
@@ -302,7 +313,7 @@ def _binding(source: ModelHubSourceConfig) -> SourceBinding:
protocol=source.protocol,
base_url=source.base_url,
credential_ref=source.credential_ref,
- allowed_origins=allowed_origins,
+ allowed_origins=source_origins,
model_ids=tuple(model.id for model in source.models),
)
@@ -356,6 +367,7 @@ class ModelHubService:
oauth_flows: Optional[OAuthFlowRegistry] = None,
revocations: Optional[CredentialRevocationJournal] = None,
migration_claude_oauth_probe: Optional[Callable[[], bool]] = None,
+ requested_model_override: Optional[Callable[[BackendName], Optional[str]]] = None,
now: Callable[[], datetime] = _utc_now,
):
self.store = store
@@ -367,7 +379,11 @@ class ModelHubService:
paths.get_state_dir() / "model_hub_pending_revocations.json"
)
self.migration_claude_oauth_probe = migration_claude_oauth_probe
+ self.requested_model_override = requested_model_override
self.now = now
+ self.native_source_ready: Callable[[BackendName, ModelHubSourceConfig], bool] = (
+ lambda _backend, _source: True
+ )
self._mutation_lock = asyncio.Lock()
self._engine_synced = False
@@ -385,6 +401,33 @@ class ModelHubService:
raise ModelHubError("mode_switch_blocked")
return agent
+ def _requested_model(self, agent: ModelHubAgentSupplyConfig) -> str:
+ if self.requested_model_override is not None:
+ requested_model = str(
+ self.requested_model_override(cast(BackendName, agent.backend)) or ""
+ ).strip()
+ if requested_model:
+ return requested_model
+ getter = getattr(self.store, "requested_model", None)
+ requested_model = str(getter(agent.backend) if callable(getter) else "").strip()
+ return requested_model
+
+ def _unavailable_native_sources(
+ self,
+ config: ModelHubConfig,
+ backend: BackendName,
+ ) -> frozenset[str]:
+ return frozenset(
+ source.id
+ for source in config.sources
+ if source.supply_channel == "native_cli"
+ and source_eligible_for_backend(source, backend)
+ and not self.native_source_ready(
+ backend,
+ source_after_cooldown_recovery(source, self.now()),
+ )
+ )
+
async def _engine_call(self, awaitable):
try:
return await awaitable
@@ -1047,9 +1090,7 @@ class ModelHubService:
@staticmethod
def _eligible_for_agent(source: ModelHubSourceConfig, backend: str) -> bool:
- if source.kind == "api_key":
- return source.supply_channel == "hub"
- return backend in _allowed_origins(source)
+ return source_eligible_for_backend(source, backend)
def _available_model_ids(self, config: ModelHubConfig, backend: str) -> set[str]:
return {
@@ -1085,40 +1126,24 @@ class ModelHubService:
if identifier in available
]
- def _source_available(self, source: ModelHubSourceConfig) -> bool:
- if source.state.status == "error":
- return False
- if source.state.status != "cooldown":
- return True
- try:
- return _parse_datetime(source.state.retry_at or "") <= self.now()
- except ValueError:
- return False
-
def _agent_payload(self, config: ModelHubConfig, agent: ModelHubAgentSupplyConfig) -> dict:
- current = None
- opencode_menu_empty = agent.backend == "opencode" and (agent.menu is None or not agent.menu.checked)
- if agent.mode == "hub" and not opencode_menu_empty:
- provider = None
- target = next((mapping.target_model_id for mapping in agent.mappings if mapping.enabled), None)
- if target is None and agent.menu and agent.menu.checked:
- try:
- provider, target = parse_opencode_model_id(agent.menu.checked[0])
- except ValueError:
- provider = None
- by_id = {source.id: source for source in config.sources}
- for source_id in config.priority_order:
- source = by_id[source_id]
- if not self._eligible_for_agent(source, agent.backend):
- continue
- if not self._source_available(source):
- continue
- if provider is not None and opencode_provider_id(source.vendor) != provider:
- continue
- model = next((model for model in source.models if target is None or model.id == target), None)
- if model is not None:
- current = {"model_id": model.id, "source_id": source.id, "channel": source.supply_channel}
- break
+ backend = cast(BackendName, agent.backend)
+ resolution = resolve_model_hub_turn(
+ config,
+ backend,
+ self._requested_model(agent),
+ now=self.now(),
+ unavailable_source_ids=self._unavailable_native_sources(config, backend),
+ )
+ current = (
+ {
+ "model_id": resolution.target_model,
+ "source_id": resolution.source.id,
+ "channel": resolution.source.supply_channel,
+ }
+ if resolution.source is not None
+ else None
+ )
# Read-only projections (agent-supply.schema.json v1.2, integration 2026-07-24):
# fixed-menu backends expose their built-in catalog; opencode exposes the
# standard vendor prefixes. Both are populated straight from the backend
@@ -1339,54 +1364,38 @@ class ModelHubService:
raise ModelHubError("migration_item_conflict", status=409)
return {"applied": applied, "sources": self.list_sources()}
- async def _resolution_candidates(
+ async def _recover_resolution_sources(
self,
- backend: str,
- model_id: str,
- *,
- provider: Optional[str] = None,
- supply_channel: Literal["hub"] | None = None,
- ) -> list[ModelHubSourceConfig]:
+ resolution: ModelHubTurnResolution,
+ ) -> None:
+ if not resolution.recoverable_source_ids:
+ return
async with self._mutation_lock:
config = self.store.load()
- by_id = {source.id: source for source in config.sources}
- candidates: list[ModelHubSourceConfig] = []
config_changed = False
- for source_id in config.priority_order:
- source = by_id[source_id]
- matches_request = (
- self._eligible_for_agent(source, backend)
- and (supply_channel is None or source.supply_channel == supply_channel)
- and (provider is None or opencode_provider_id(source.vendor) == provider)
- and any(model.id == model_id for model in source.models)
+ for source_id in resolution.recoverable_source_ids:
+ source = next(
+ (item for item in config.sources if item.id == source_id),
+ None,
)
- if not matches_request:
+ if source is None or source.state.status != "cooldown":
continue
- if source.state.status == "cooldown":
- try:
- retry_at = _parse_datetime(source.state.retry_at or "")
- except ValueError:
- retry_at = self.now() + timedelta(days=1)
- if retry_at > self.now():
- continue
- source.state = ModelHubSourceStateConfig(
- status=("active" if source.supply_channel == "native_cli" else "standby")
- )
- config_changed = True
- self._record_event(
- agent=cast(EventAgent, backend),
- kind="recover",
- model_id=model_id,
- reason="recovery",
- to_source=source.id,
- to_label=source.display_name,
- now=self.now(),
- )
- if source.state.status != "error":
- candidates.append(source)
+ recovered_source = source_after_cooldown_recovery(source, self.now())
+ if recovered_source is source:
+ continue
+ source.state = recovered_source.state
+ config_changed = True
+ self._record_event(
+ agent=cast(EventAgent, resolution.backend),
+ kind="recover",
+ model_id=resolution.target_model,
+ reason="recovery",
+ to_source=source.id,
+ to_label=source.display_name,
+ now=self.now(),
+ )
if config_changed:
self.store.save(config)
- return candidates
async def _cooldown(
self,
@@ -1473,29 +1482,38 @@ class ModelHubService:
if backend not in {"claude", "codex", "opencode"}:
raise ModelHubError("mapping_target_unavailable")
config = self.store.load()
- agent = self._agent(config, backend)
- if agent.mode != "hub":
- raise ModelHubError("mode_switch_blocked", status=409)
- target_model = next(
- (
- mapping.target_model_id
- for mapping in agent.mappings
- if mapping.enabled and mapping.builtin_id == model_id
- ),
+ resolution = resolve_model_hub_turn(
+ config,
+ cast(BackendName, backend),
model_id,
+ now=self.now(),
+ unavailable_source_ids=self._unavailable_native_sources(
+ config,
+ cast(BackendName, backend),
+ ),
+ supply_channel=supply_channel,
)
- mapping_applied = target_model != model_id
- provider = None
- if backend == "opencode":
- try:
- provider, target_model = parse_opencode_model_id(target_model)
- except ValueError:
- raise ModelHubError("mapping_target_unavailable", status=409)
- selected_identifier = f"{provider}/{target_model}"
- if agent.menu is None or selected_identifier not in agent.menu.checked:
- raise ModelHubError("mapping_target_unavailable", status=409)
+ if config.agents[backend].mode != "hub":
+ raise ModelHubError("mode_switch_blocked", status=409)
+ if resolution.channel == "direct":
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ if resolution.recoverable_source_ids:
+ await self._recover_resolution_sources(resolution)
+ config = self.store.load()
+ resolution = resolve_model_hub_turn(
+ config,
+ cast(BackendName, backend),
+ model_id,
+ now=self.now(),
+ unavailable_source_ids=self._unavailable_native_sources(
+ config,
+ cast(BackendName, backend),
+ ),
+ supply_channel=supply_channel,
+ )
+ target_model = resolution.target_model
event_agent = cast(EventAgent, backend)
- if mapping_applied:
+ if resolution.mapping_applied:
self._record_event(
agent=event_agent,
kind="mapping_applied",
@@ -1504,12 +1522,7 @@ class ModelHubService:
from_label=model_id,
now=self.now(),
)
- candidates = await self._resolution_candidates(
- backend,
- target_model,
- provider=provider,
- supply_channel=supply_channel,
- )
+ candidates = list(resolution.candidates)
if not candidates:
raise ModelHubError("mapping_target_unavailable", status=409)
@@ -1606,6 +1619,7 @@ def create_default_service(
*,
adapter: Optional[EngineAdapter] = None,
native_oauth_adapter: Optional[NativeOAuthAdapter] = None,
+ requested_model_override: Optional[Callable[[BackendName], Optional[str]]] = None,
) -> ModelHubService:
if adapter is None:
from vibe.model_hub_runtime import get_model_hub_engine_adapter
@@ -1647,4 +1661,5 @@ def create_default_service(
oauth_flows=OAuthFlowRegistry(paths.get_state_dir() / "model_hub_oauth_flows.json"),
revocations=CredentialRevocationJournal(paths.get_state_dir() / "model_hub_pending_revocations.json"),
migration_claude_oauth_probe=claude_oauth_probe,
+ requested_model_override=requested_model_override,
)
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index 222a8493b..bd1792193 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -16,12 +16,19 @@ from config import paths
from config.v2_config import ModelHubConfig, ModelHubSourceConfig
from core.handlers.model_hub.classification import ResolutionDecision
from core.handlers.model_hub.events import EventAgent, EventReason
-from core.handlers.model_hub.identifiers import opencode_provider_id, parse_opencode_model_id
+from core.handlers.model_hub.identifiers import parse_opencode_model_id
+from core.handlers.model_hub.resolver import (
+ BackendName,
+ ModelHubTurnResolution,
+ normalize_opencode_requested_model,
+ resolve_model_hub_turn,
+ source_after_cooldown_recovery,
+ source_eligible_for_backend,
+)
from core.handlers.model_hub.service import ModelHubError, ModelHubService, create_default_service
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
-BackendName = Literal["claude", "codex", "opencode"]
LaunchChannel = Literal["direct", "native_cli", "hub"]
_CONTEXT_LAUNCH_ATTR = "_vibe_model_hub_launch"
@@ -265,7 +272,11 @@ class ModelHubRuntimeRouter:
self.overlay_path = overlay_path or paths.get_runtime_dir() / "model-hub" / "opencode-overlay.json"
self._uses_default_native_cli_ready = native_cli_ready is None
self.native_cli_ready = native_cli_ready or self._default_native_cli_ready
+ self.service.native_source_ready = self._native_source_ready
self._last_launch: dict[tuple[BackendName, str], ModelHubLaunch] = {}
+ self._last_launch_mode: dict[
+ tuple[BackendName, str], Literal["hub", "direct"]
+ ] = {}
@staticmethod
def _default_native_cli_ready(
@@ -321,36 +332,54 @@ class ModelHubRuntimeRouter:
verified_oauth=backend == "codex" and source.state.status == "active",
)
- @staticmethod
- def _route_key(launch: ModelHubLaunch) -> tuple[BackendName, str]:
- return launch.backend, launch.target_model
-
- @staticmethod
- def _is_bootstrap_unconfigured(
+ def _unavailable_native_source_ids(
+ self,
config: ModelHubConfig,
backend: BackendName,
- requested_model: str = "",
- ) -> bool:
- agent = config.agents[backend]
- if backend == "opencode":
- return agent.menu is None or not agent.menu.checked
+ ) -> frozenset[str]:
+ return frozenset(
+ source.id
+ for source in config.sources
+ if source.supply_channel == "native_cli"
+ and source_eligible_for_backend(source, backend)
+ and not self._native_source_ready(
+ backend,
+ source_after_cooldown_recovery(source, self.service.now()),
+ )
+ )
- explicit_mapping = any(
- mapping.enabled and mapping.builtin_id == requested_model
- for mapping in agent.mappings
+ async def _resolve_turn(
+ self,
+ config: ModelHubConfig,
+ backend: BackendName,
+ requested_model: str,
+ *,
+ supply_channel: Literal["hub"] | None = None,
+ ) -> tuple[ModelHubConfig, ModelHubTurnResolution]:
+ resolution = resolve_model_hub_turn(
+ config,
+ backend,
+ requested_model,
+ now=self.service.now(),
+ unavailable_source_ids=self._unavailable_native_source_ids(config, backend),
+ supply_channel=supply_channel,
)
- if explicit_mapping:
- return False
- target_model = ModelHubRuntimeRouter._target_model(config, backend, requested_model)
- for source in config.sources:
- if not any(model.id == target_model for model in source.models):
- continue
- if source.supply_channel == "hub":
- return False
- sanctioned_backend = {"anthropic": "claude", "openai": "codex"}.get(source.vendor)
- if source.kind == "subscription" and sanctioned_backend == backend:
- return False
- return True
+ if not resolution.recoverable_source_ids:
+ return config, resolution
+ await self.service._recover_resolution_sources(resolution)
+ config = self.service.store.load()
+ return config, resolve_model_hub_turn(
+ config,
+ backend,
+ requested_model,
+ now=self.service.now(),
+ unavailable_source_ids=self._unavailable_native_source_ids(config, backend),
+ supply_channel=supply_channel,
+ )
+
+ @staticmethod
+ def _route_key(launch: ModelHubLaunch) -> tuple[BackendName, str]:
+ return launch.backend, launch.requested_model
@staticmethod
def _direct_launch(backend: BackendName, requested_model: str) -> ModelHubLaunch:
@@ -362,18 +391,6 @@ class ModelHubRuntimeRouter:
runtime_model=requested_model,
)
- @staticmethod
- def _target_model(config: ModelHubConfig, backend: BackendName, requested_model: str) -> str:
- agent = config.agents[backend]
- return next(
- (
- mapping.target_model_id
- for mapping in agent.mappings
- if mapping.enabled and mapping.builtin_id == requested_model
- ),
- requested_model,
- )
-
async def _source_prefix(self, source_id: str) -> str:
adapter = self.service.adapter
getter = getattr(adapter, "source_prefix", None)
@@ -452,6 +469,12 @@ class ModelHubRuntimeRouter:
if event.get("kind") == "cooldown":
source = self._source_for_id(config, event.get("from_source"))
elif event.get("kind") in {"switch", "channel_switch"}:
+ if event.get("kind") == "channel_switch" and event.get("to_source") is None:
+ previous = self._direct_launch(
+ current.backend,
+ current.requested_model,
+ )
+ break
source = self._source_for_id(config, event.get("to_source"))
else:
continue
@@ -467,9 +490,18 @@ class ModelHubRuntimeRouter:
break
return previous, pending_source, pending_reason
- def _emit_transition(self, current: ModelHubLaunch, config: ModelHubConfig) -> None:
+ def _emit_transition(
+ self,
+ current: ModelHubLaunch,
+ config: ModelHubConfig,
+ *,
+ configured_mode: Literal["hub", "direct"],
+ ) -> None:
previous, failed_source, failed_reason = self._transition_context(current, config)
- self._last_launch[self._route_key(current)] = current
+ route_key = self._route_key(current)
+ previous_mode = self._last_launch_mode.get(route_key)
+ self._last_launch[route_key] = current
+ self._last_launch_mode[route_key] = configured_mode
current_source = self._source_for_id(config, current.source_id)
if (
failed_source is not None
@@ -484,7 +516,48 @@ class ModelHubRuntimeRouter:
failed_reason=failed_reason,
source=current_source,
)
- if previous is None or previous.channel == current.channel:
+ if previous is None:
+ if configured_mode == "hub" and current.channel == "direct":
+ self.service._record_event(
+ agent=cast(EventAgent, current.backend),
+ kind="channel_switch",
+ model_id=current.target_model,
+ reason="manual",
+ to_source=None,
+ now=self.service.now(),
+ )
+ return
+ if previous.channel == current.channel:
+ if (
+ current.channel == "direct"
+ and configured_mode == "hub"
+ and previous_mode == "direct"
+ ):
+ self.service._record_event(
+ agent=cast(EventAgent, current.backend),
+ kind="channel_switch",
+ model_id=current.target_model,
+ reason="manual",
+ to_source=None,
+ now=self.service.now(),
+ )
+ return
+ if "direct" in {previous.channel, current.channel}:
+ if configured_mode != "hub":
+ return
+ previous_source = self._source_for_id(config, previous.source_id)
+ reason = failed_reason or "manual"
+ self.service._record_event(
+ agent=cast(EventAgent, current.backend),
+ kind="channel_switch",
+ model_id=current.target_model,
+ reason=reason,
+ from_source=previous.source_id,
+ to_source=current.source_id,
+ from_label=previous_source.display_name if previous_source else None,
+ to_label=current_source.display_name if current_source else None,
+ now=self.service.now(),
+ )
return
if {previous.channel, current.channel} != {"native_cli", "hub"}:
return
@@ -502,21 +575,25 @@ class ModelHubRuntimeRouter:
async def resolve(self, backend: BackendName, requested_model: str) -> ModelHubLaunch:
requested_model = str(requested_model or "").strip()
config = self.service.store.load()
- agent = config.agents[backend]
- if agent.mode == "direct":
+ config, resolution = await self._resolve_turn(
+ config,
+ backend,
+ requested_model,
+ )
+ configured_mode = config.agents[backend].mode
+ if resolution.channel == "direct":
launch = self._direct_launch(backend, requested_model)
- self._emit_transition(launch, config)
+ self._emit_transition(
+ launch,
+ config,
+ configured_mode=configured_mode,
+ )
return launch
- # Fresh installs seed Hub mode before setup/migration has configured
- # every backend/model route. Preserve native launch only for an
- # unconfigured route; explicitly configured Hub routes remain fail-closed.
- if self._is_bootstrap_unconfigured(config, backend, requested_model):
- return self._direct_launch(backend, requested_model)
- if not requested_model:
+ if resolution.source is None:
raise ModelHubError("mapping_target_unavailable", status=409)
- target_model = self._target_model(config, backend, requested_model)
- if target_model != requested_model:
+ target_model = resolution.target_model
+ if resolution.mapping_applied:
self.service._record_event(
agent=cast(EventAgent, backend),
kind="mapping_applied",
@@ -525,28 +602,7 @@ class ModelHubRuntimeRouter:
from_label=requested_model,
now=self.service.now(),
)
- provider: str | None = None
- if backend == "opencode":
- try:
- provider, target_model = parse_opencode_model_id(target_model)
- except ValueError:
- raise ModelHubError("mapping_target_unavailable", status=409) from None
- if agent.menu is None or f"{provider}/{target_model}" not in agent.menu.checked:
- raise ModelHubError("mapping_target_unavailable", status=409)
- candidates = await self.service._resolution_candidates(backend, target_model, provider=provider)
- if not candidates:
- raise ModelHubError("mapping_target_unavailable", status=409)
- source = next(
- (
- candidate
- for candidate in candidates
- if candidate.supply_channel != "native_cli"
- or self._native_source_ready(backend, candidate)
- ),
- None,
- )
- if source is None:
- raise ModelHubError("mapping_target_unavailable", status=409)
+ source = resolution.source
if source.supply_channel == "native_cli":
if self.service.revocations.list():
try:
@@ -578,7 +634,11 @@ class ModelHubRuntimeRouter:
gateway_base_url=gateway_base_url,
gateway_token=gateway_token,
)
- self._emit_transition(launch, config)
+ self._emit_transition(
+ launch,
+ config,
+ configured_mode=configured_mode,
+ )
return launch
async def resolve_opencode_overlay_launch(
@@ -595,7 +655,11 @@ class ModelHubRuntimeRouter:
if launch is None:
raise ModelHubError("mapping_target_unavailable", status=409)
config = self.service.store.load()
- self._emit_transition(launch, config)
+ self._emit_transition(
+ launch,
+ config,
+ configured_mode=config.agents["opencode"].mode,
+ )
return launch
async def record_native_failure(self, context: Any, diagnostic: str) -> bool:
@@ -640,32 +704,27 @@ class ModelHubRuntimeRouter:
agent = config.agents["opencode"]
if agent.mode == "direct":
return None
- if self._is_bootstrap_unconfigured(config, "opencode"):
- return None
checked = tuple(agent.menu.checked if agent.menu else ())
if not checked:
- raise ModelHubError("mapping_target_unavailable", status=409)
+ return None
gateway_base_url, gateway_token = await self._gateway_credentials("opencode")
providers: dict[str, dict[str, Any]] = {}
projected_identifiers: list[str] = []
available_identifiers: list[str] = []
launches: list[ModelHubLaunch] = []
- sources_by_id = {source.id: source for source in config.sources}
for identifier in dict.fromkeys(checked):
try:
provider_id, model_id = parse_opencode_model_id(identifier)
except ValueError:
raise ModelHubError("mapping_target_unavailable", status=409) from None
- candidates = await self.service._resolution_candidates(
+ config, resolution = await self._resolve_turn(
+ config,
"opencode",
- model_id,
- provider=provider_id,
- )
- available_source = next(
- (candidate for candidate in candidates if candidate.supply_channel == "hub"),
- None,
+ identifier,
+ supply_channel="hub",
)
+ available_source = resolution.source
source = available_source
if source is None:
# Keep a cooling/error route's public identifier stable in the
@@ -674,11 +733,8 @@ class ModelHubRuntimeRouter:
source = next(
(
candidate
- for source_id in config.priority_order
- if (candidate := sources_by_id.get(source_id)) is not None
- and candidate.supply_channel == "hub"
- and opencode_provider_id(candidate.vendor) == provider_id
- and any(model.id == model_id for model in candidate.models)
+ for candidate in resolution.matching_sources
+ if candidate.supply_channel == "hub"
),
None,
)
@@ -778,9 +834,10 @@ def opencode_model_for_overlay(model: str | None, overlay: OpenCodeOverlay | Non
if not overlay.available_identifiers:
raise ModelHubError("mapping_target_unavailable", status=409)
return overlay.available_identifiers[0]
- if candidate in overlay.checked_identifiers:
- return candidate
- matches = [identifier for identifier in overlay.checked_identifiers if identifier.endswith(f"/{candidate}")]
- if len(matches) == 1:
- return matches[0]
+ normalized = normalize_opencode_requested_model(
+ candidate,
+ overlay.checked_identifiers,
+ )
+ if normalized is not None:
+ return normalized
raise ModelHubError("mapping_target_unavailable", status=409)
diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.py
index bf37a0226..d200334eb 100644
--- a/tests/scenario_harness/model_hub_native_oauth.py
+++ b/tests/scenario_harness/model_hub_native_oauth.py
@@ -24,6 +24,7 @@ class MemoryStore:
}
)
self.config.subscription_hub_experimental = experimental
+ self.requested_models = {"claude": "claude-opus-4-6"}
def load(self) -> ModelHubConfig:
return self.config
@@ -31,6 +32,9 @@ class MemoryStore:
def save(self, config: ModelHubConfig) -> None:
self.config = config
+ def requested_model(self, backend: str) -> str:
+ return self.requested_models.get(backend, "")
+
class FakeAgentAuthService:
"""AgentAuthService boundary fake; the native adapter remains real."""
diff --git a/tests/test_controller_model_hub_gate.py b/tests/test_controller_model_hub_gate.py
index c4decbb91..9336d0568 100644
--- a/tests/test_controller_model_hub_gate.py
+++ b/tests/test_controller_model_hub_gate.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import json
+from types import SimpleNamespace
import pytest
@@ -52,10 +53,22 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
self.turn_gateway = turn_gateway
monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")
- monkeypatch.setattr(model_hub, "create_default_service", lambda: service)
+ captured = {}
+
+ def create_service(**kwargs):
+ captured.update(kwargs)
+ return service
+
+ monkeypatch.setattr(model_hub, "create_default_service", create_service)
monkeypatch.setattr(turn_gateway, "ModelHubTurnGateway", Gateway)
monkeypatch.setattr(agent_model_hub, "ModelHubRuntimeRouter", Router)
controller = Controller.__new__(Controller)
+ controller.vibe_agent_store = SimpleNamespace(
+ get_default_agent=lambda: SimpleNamespace(
+ backend="codex",
+ model="agent-model",
+ )
+ )
controller._init_model_hub()
@@ -63,6 +76,8 @@ def test_controller_builds_one_model_hub_aggregate_after_explicit_opt_in(monkeyp
assert controller.model_hub_turn_gateway.service is service
assert controller.model_hub_runtime.service is service
assert controller.model_hub_runtime.turn_gateway is controller.model_hub_turn_gateway
+ assert captured["requested_model_override"]("codex") == "agent-model"
+ assert captured["requested_model_override"]("claude") is None
assert calls == [
("gateway", service),
("router", service, controller.model_hub_turn_gateway),
diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.py
index 120caeb53..f215c26e6 100644
--- a/tests/test_model_hub_injection.py
+++ b/tests/test_model_hub_injection.py
@@ -23,6 +23,7 @@ from config.v2_config import (
)
from core.handlers.model_hub.adapter import EngineHealth, EngineStatus
from core.handlers.model_hub.events import BoundedEventLog
+from core.handlers.model_hub.resolver import resolve_model_hub_turn
from core.handlers.model_hub.revocations import CredentialRevocationJournal
from core.handlers.model_hub.service import ModelHubError, ModelHubService
from core.handlers.session_handler import SessionHandler
@@ -45,8 +46,14 @@ from modules.agents.opencode.server import OpenCodeServerManager
class MemoryStore:
- def __init__(self, config: ModelHubConfig):
+ def __init__(
+ self,
+ config: ModelHubConfig,
+ *,
+ requested_models: dict[str, str] | None = None,
+ ):
self.config = config
+ self.requested_models = requested_models or {}
def load(self) -> ModelHubConfig:
return self.config
@@ -54,6 +61,9 @@ class MemoryStore:
def save(self, config: ModelHubConfig) -> None:
self.config = config
+ def requested_model(self, backend: str) -> str:
+ return self.requested_models.get(backend, "")
+
class LaunchAdapter:
def __init__(self, prefixes: dict[str, str], *, token: str = "local-gateway-token"):
@@ -361,10 +371,122 @@ def test_mh_chan_001_unconfigured_fresh_hub_preserves_native_launch(tmp_path: Pa
launch = asyncio.run(_router(service).resolve("codex", "gpt-5"))
+ assert launch.channel == "direct"
+ event = service.events.list(limit=10)[0]
+ assert (event["kind"], event["to_source"]) == ("channel_switch", None)
+
+ asyncio.run(_router(service).resolve("codex", "gpt-5"))
+
+ assert len(service.events.list(limit=10)) == 1
+
+
+def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> None:
+ """MH-EVT-002: mode history does not suppress or duplicate degradation."""
+
+ agents = _agents(mode="direct")
+ adapter = LaunchAdapter({})
+ config = ModelHubConfig(sources=[], priority_order=[], agents=agents)
+ service = _service(
+ tmp_path,
+ config,
+ adapter,
+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
+ )
+ router = _router(service)
+
+ assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "direct"
+ assert service.events.list(limit=10) == []
+
+ agents["codex"].mode = "hub"
+ assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "direct"
+ assert [event["kind"] for event in service.events.list(limit=10)] == [
+ "channel_switch"
+ ]
+
+ asyncio.run(router.resolve("codex", "gpt-5"))
+
+ assert len(service.events.list(limit=10)) == 1
+
+ hub = _source(
+ "src_hub_after_direct",
+ kind="api_key",
+ vendor="openai",
+ protocol="openai_responses",
+ channel="hub",
+ model_ids=("gpt-5",),
+ )
+ config.sources.append(hub)
+ config.priority_order.append(hub.id)
+ adapter.prefixes[hub.id] = "route-hub"
+ assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "hub"
+ assert service.events.list(limit=10)[0]["reason"] == "manual"
+
+
+def test_recovered_turn_uses_post_wait_mode_for_events(tmp_path: Path) -> None:
+ """MH-EVT-002: recovered resolution and telemetry use one config snapshot."""
+
+ initial = ModelHubConfig(
+ sources=[],
+ priority_order=[],
+ agents=_agents(mode="hub"),
+ )
+ recovered = ModelHubConfig(
+ sources=[],
+ priority_order=[],
+ agents=_agents(mode="direct"),
+ )
+ service = _service(
+ tmp_path,
+ initial,
+ LaunchAdapter({}),
+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
+ )
+ router = _router(service)
+ resolution = resolve_model_hub_turn(recovered, "codex", "gpt-5")
+ router._resolve_turn = AsyncMock(return_value=(recovered, resolution))
+
+ launch = asyncio.run(router.resolve("codex", "gpt-5"))
+
assert launch.channel == "direct"
assert service.events.list(limit=10) == []
+def test_direct_to_healthy_hub_switch_is_manual(tmp_path: Path) -> None:
+ """MH-EVT-002: a mapped Direct-to-Hub mode switch stays manual."""
+
+ hub = _source(
+ "src_hub_manual",
+ kind="api_key",
+ vendor="openai",
+ protocol="openai_responses",
+ channel="hub",
+ model_ids=("custom-gpt-5",),
+ )
+ agents = _agents(mode="direct")
+ agents["codex"].mappings = [
+ ModelHubMappingConfig("gpt-5", "custom-gpt-5", True)
+ ]
+ service = _service(
+ tmp_path,
+ ModelHubConfig(sources=[hub], priority_order=[hub.id], agents=agents),
+ LaunchAdapter({hub.id: "route-hub"}),
+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
+ )
+ router = _router(service)
+
+ assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "direct"
+ agents["codex"].mode = "hub"
+ launch = asyncio.run(router.resolve("codex", "gpt-5"))
+
+ assert (launch.channel, launch.source_id) == ("hub", hub.id)
+ event = service.events.list(limit=10)[0]
+ assert (event["kind"], event["reason"], event["to_source"]) == (
+ "channel_switch",
+ "manual",
+ hub.id,
+ )
+
+
def test_mh_chan_001_other_backend_source_does_not_activate_hub(tmp_path: Path) -> None:
codex_native = _source(
"src_native_other",
@@ -390,6 +512,264 @@ def test_mh_chan_001_other_backend_source_does_not_activate_hub(tmp_path: Path)
assert launch.channel == "direct"
+def test_agent_projection_matches_next_turn_for_unmapped_fixed_backend(tmp_path: Path) -> None:
+ """MH-CHAN-001: an unmapped fixed backend projects its direct launch."""
+
+ hub = _source(
+ "src_hub_display",
+ kind="api_key",
+ vendor="openai",
+ protocol="openai_responses",
+ channel="hub",
+ model_ids=("codex-auto-review",),
+ )
+ adapter = LaunchAdapter({hub.id: "route-hub"})
+ service = _service(
+ tmp_path,
+ ModelHubConfig(
+ sources=[hub],
+ priority_order=[hub.id],
+ agents=_agents(),
+ ),
+ adapter,
+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
+ )
+ service.store.requested_models["claude"] = "claude-opus-4-6"
+
+ projected = next(
+ agent for agent in service.list_agents() if agent["backend"] == "claude"
+ )
+ router = _router(service)
+ launch = asyncio.run(router.resolve("claude", "claude-opus-4-6"))
+
+ assert launch.channel == "direct"
+ assert projected["current"] is None
+ assert adapter.starts == 0
+ event = service.events.list(limit=10)[0]
+ assert (event["kind"], event["to_source"]) == ("channel_switch", None)
+
+ asyncio.run(router.resolve("claude", "claude-opus-4-6"))
+
+ assert len(service.events.list(limit=10)) == 1
+
+
+def test_agent_projection_uses_global_default_vibe_agent_model(tmp_path: Path) -> None:
+ """MH-CHAN-001: the global default Vibe Agent supplies the projected model."""
+
+ hub = _source(
+ "src_hub_agent_model",
+ kind="api_key",
+ vendor="openai",
+ protocol="openai_responses",
+ channel="hub",
+ model_ids=("agent-model",),
+ )
+ service = _service(
+ tmp_path,
+ ModelHubConfig(
+ sources=[hub],
+ priority_order=[hub.id],
+ agents=_agents(),
+ ),
+ LaunchAdapter({hub.id: "route-hub"}),
+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
+ )
+ service.store.requested_models["codex"] = "backend-default"
+ service.requested_model_override = (
+ lambda backend: "agent-model" if backend == "codex" else None
+ )
+ router = _router(service)
+
+ projected = next(
+ agent for agent in service.list_agents() if agent["backend"] == "codex"
+ )["current"]
+ launch = asyncio.run(router.resolve("codex", "agent-model"))
+
+ assert projected == {
+ "model_id": launch.target_model,
+ "source_id": launch.source_id,
+ "channel": launch.channel,
+ }
+
+
+def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Path) -> None:
+ """MH-CHAN-001/MH-MAP-001/MH-OC-001: projection equals runtime resolution."""
+
+ fixed_hub = _source(
+ "src_hub_mapped",
+ kind="api_key",
+ vendor="openai",
+ protocol="openai_responses",
+ channel="hub",
+ model_ids=("mapped-model",),
+ )
+ fixed_agents = _agents()
+ fixed_agents["claude"].mappings = [
+ ModelHubMappingConfig("claude-native", "mapped-model", True)
+ ]
+
+ direct_hub = _source(
+ "src_hub_direct",
+ kind="api_key",
+ vendor="openai",
+ protocol="openai_responses",
+ channel="hub",
+ model_ids=("gpt-5",),
+ )
+ direct_agents = _agents()
+ direct_agents["codex"].mode = "direct"
+
+ opencode_hub = _source(
+ "src_hub_open",
+ kind="api_key",
+ vendor="anthropic",
+ protocol="anthropic",
+ channel="hub",
+ model_ids=("claude-opus",),
+ )
+ opencode_agents = _agents()
+ opencode_agents["opencode"].menu = ModelHubMenuConfig(
+ view="featured",
+ checked=["anthropic/claude-opus", "custom/mapped-open"],
+ )
+ opencode_agents["opencode"].mappings = [
+ ModelHubMappingConfig("anthropic/claude-opus", "custom/mapped-open", True)
+ ]
+ opencode_mapped = _source(
+ "src_hub_open_mapped",
+ kind="api_key",
+ vendor="custom",
+ protocol="openai_compatible",
+ channel="hub",
+ model_ids=("mapped-open",),
+ )
+ unavailable_open = _source(
+ "src_hub_open_error",
+ kind="api_key",
+ vendor="anthropic",
+ protocol="anthropic",
+ channel="hub",
+ model_ids=("blocked-model",),
+ state="error",
+ )
+ available_open = _source(
+ "src_hub_open_ready",
+ kind="api_key",
+ vendor="custom",
+ protocol="openai_compatible",
+ channel="hub",
+ model_ids=("ready-model",),
+ )
+ default_open_agents = _agents()
+ default_open_agents["opencode"].menu = ModelHubMenuConfig(
+ view="featured",
+ checked=["anthropic/blocked-model", "custom/ready-model"],
+ )
+
+ native = _source(
+ "src_native_table",
+ kind="subscription",
+ vendor="openai",
+ protocol="openai_responses",
+ channel="native_cli",
+ model_ids=("gpt-5",),
+ )
+
+ cases = [
+ (
+ "claude",
+ "claude-native",
+ ModelHubConfig(
+ sources=[fixed_hub],
+ priority_order=[fixed_hub.id],
+ agents=fixed_agents,
+ ),
+ {"model_id": "mapped-model", "source_id": fixed_hub.id, "channel": "hub"},
+ ),
+ (
+ "codex",
+ "gpt-5",
+ ModelHubConfig(
+ sources=[direct_hub],
+ priority_order=[direct_hub.id],
+ agents=direct_agents,
+ ),
+ None,
+ ),
+ (
+ "opencode",
+ "claude-opus",
+ ModelHubConfig(
+ sources=[opencode_hub, opencode_mapped],
+ priority_order=[opencode_mapped.id, opencode_hub.id],
+ agents=opencode_agents,
+ ),
+ {
+ "model_id": "claude-opus",
+ "source_id": opencode_hub.id,
+ "channel": "hub",
+ },
+ ),
+ (
+ "opencode",
+ "",
+ ModelHubConfig(
+ sources=[unavailable_open, available_open],
+ priority_order=[unavailable_open.id, available_open.id],
+ agents=default_open_agents,
+ ),
+ {
+ "model_id": "ready-model",
+ "source_id": available_open.id,
+ "channel": "hub",
+ },
+ ),
+ (
+ "codex",
+ "gpt-5",
+ ModelHubConfig(
+ sources=[native],
+ priority_order=[native.id],
+ agents=_agents(),
+ ),
+ {"model_id": "gpt-5", "source_id": native.id, "channel": "native_cli"},
+ ),
+ ]
+
+ for backend, requested_model, config, expected in cases:
+ adapter = LaunchAdapter(
+ {
+ source.id: f"route-{source.id}"
+ for source in config.sources
+ if source.supply_channel == "hub"
+ }
+ )
+ service = _service(
+ tmp_path,
+ config,
+ adapter,
+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
+ )
+ service.store.requested_models[backend] = requested_model
+ router = _router(service)
+
+ projected = next(
+ agent for agent in service.list_agents() if agent["backend"] == backend
+ )["current"]
+ launch = asyncio.run(router.resolve(backend, requested_model))
+ actual = (
+ None
+ if launch.channel == "direct"
+ else {
+ "model_id": launch.target_model,
+ "source_id": launch.source_id,
+ "channel": launch.channel,
+ }
+ )
+
+ assert projected == actual == expected
+
+
def test_mh_chan_001_configured_hub_stays_fail_closed_for_unavailable_model(tmp_path: Path) -> None:
hub = _source(
"src_hub0099",
@@ -458,6 +838,57 @@ def test_mh_chan_001_invalid_native_runtime_skips_to_hub(tmp_path: Path) -> None
assert native.state.status == "standby"
+def test_projection_rechecks_expired_native_readiness_before_recovery(
+ tmp_path: Path,
+) -> None:
+ """MH-CHAN-001: projection uses post-recovery native readiness."""
+
+ clock = datetime(2026, 7, 23, tzinfo=timezone.utc)
+ native = _source(
+ "src_native_expired",
+ kind="subscription",
+ vendor="openai",
+ protocol="openai_responses",
+ channel="native_cli",
+ model_ids=("gpt-5",),
+ state="cooldown",
+ retry_at=(clock - timedelta(seconds=1)).isoformat(),
+ )
+ hub = _source(
+ "src_hub_after_expired",
+ kind="api_key",
+ vendor="openai",
+ protocol="openai_responses",
+ channel="hub",
+ model_ids=("gpt-5",),
+ )
+ service = _service(
+ tmp_path,
+ ModelHubConfig(
+ sources=[native, hub],
+ priority_order=[native.id, hub.id],
+ agents=_agents(),
+ ),
+ LaunchAdapter({hub.id: "route-hub"}),
+ now=lambda: clock,
+ )
+ service.store.requested_models["codex"] = "gpt-5"
+ router = _router(service, native_cli_ready=lambda _backend: False)
+
+ projected = next(
+ agent for agent in service.list_agents() if agent["backend"] == "codex"
+ )["current"]
+ launch = asyncio.run(router.resolve("codex", "gpt-5"))
+
+ assert projected == {
+ "model_id": "gpt-5",
+ "source_id": hub.id,
+ "channel": "hub",
+ }
+ assert (launch.channel, launch.source_id) == ("hub", hub.id)
+ assert native.state.status == "active"
+
+
def test_mh_chan_001_codex_native_runtime_requires_chatgpt_oauth(
tmp_path: Path, monkeypatch
) -> None:
@@ -547,8 +978,18 @@ def test_mh_chan_001_verified_codex_keyring_source_remains_routable(
assert native.state.status == "cooldown"
clock["now"] += timedelta(seconds=301)
+ service.store.requested_models["codex"] = "gpt-5"
+ projected = next(
+ agent for agent in service.list_agents() if agent["backend"] == "codex"
+ )["current"]
+ assert native.state.status == "cooldown"
recovered = asyncio.run(router.resolve("codex", "gpt-5"))
+ assert projected == {
+ "model_id": "gpt-5",
+ "source_id": native.id,
+ "channel": "native_cli",
+ }
assert (recovered.channel, recovered.source_id) == ("native_cli", native.id)
assert native.state.status == "active"
@@ -742,6 +1183,47 @@ def test_mh_ovl_001_identifiers_stay_stable_across_all_perturbations(tmp_path: P
assert stat.S_IMODE(router.overlay_path.stat().st_mode) == 0o600
+def test_mh_oc_001_open_menu_ignores_stale_fixed_mapping(tmp_path: Path) -> None:
+ """MH-OC-001: OpenCode menu identifiers, not fixed mappings, define routes."""
+
+ config = _opencode_config()
+ config.agents["opencode"].mappings = [
+ ModelHubMappingConfig(
+ "anthropic/claude-opus",
+ "custom/local-model",
+ True,
+ )
+ ]
+ service = _service(
+ tmp_path,
+ config,
+ LaunchAdapter(
+ {
+ "src_hub0004": "route-anthropic",
+ "src_hub0005": "route-custom",
+ }
+ ),
+ now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
+ )
+ router = _router(service, overlay_path=tmp_path / "overlay.json")
+
+ overlay = asyncio.run(router.prepare_opencode_overlay())
+ assert overlay is not None
+ assert json.loads(overlay_identifier_bytes(overlay.content)) == [
+ "anthropic/claude-opus",
+ "custom/local-model",
+ ]
+ launch = asyncio.run(
+ router.resolve_opencode_overlay_launch(
+ overlay,
+ "anthropic/claude-opus",
+ )
+ )
+ assert launch.source_id == "src_hub0004"
+ assert launch.target_model == "claude-opus"
+ assert launch.runtime_model == "route-anthropic/claude-opus"
+
+
def test_mh_ovl_001_unavailable_menu_entry_does_not_block_healthy_model(tmp_path: Path) -> None:
config = _opencode_config()
anthropic = config.sources[0]
@@ -771,6 +1253,7 @@ def test_mh_ovl_001_unavailable_menu_entry_does_not_block_healthy_model(tmp_path
]
assert cooling_overlay.available_identifiers == ("custom/local-model",)
assert opencode_model_for_overlay(None, cooling_overlay) == "custom/local-model"
+ assert opencode_model_for_overlay("local-model", cooling_overlay) == "custom/local-model"
assert opencode_model_for_overlay("custom/local-model", cooling_overlay) == "custom/local-model"
with pytest.raises(ModelHubError):
asyncio.run(router.resolve("opencode", "anthropic/claude-opus"))
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 80e9ec806..f1ab960ce 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -32,6 +32,7 @@ class MemoryStore:
def __init__(self, config: ModelHubConfig):
self.config = config
self.fail_save = False
+ self.requested_models = {"claude": "claude-opus-4-6"}
def load(self) -> ModelHubConfig:
return self.config
@@ -41,6 +42,9 @@ class MemoryStore:
raise OSError("save failed")
self.config = config
+ def requested_model(self, backend: str) -> str:
+ return self.requested_models.get(backend, "")
+
class FakeAdapter:
def __init__(self, outcomes):