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
fix(model-hub): resolve native menu supply aliases (#1118)
Call White0cd9e9037bcd
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex cedbe5201..dc9b032ab 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -110,6 +110,14 @@ class GatewayTurnTerminalizer:self.turn_id = Nonereturn self.turn_id+ def resolution_model(self, gateway_model_id: str) -> str:+ """Return the caller model retained before the CLI rewrote its request."""++ turn_id = self.bind_request_model(gateway_model_id)+ if turn_id is None:+ return gateway_model_id+ return self._registry.gateway_requested_model(turn_id) or gateway_model_id+def fail(self,reason: Literal["invalid_parameter", "protocol_error"],@@ -435,6 +443,13 @@ class TurnCorrelationRegistry:trace.gateway_model_id = resolved_model_idtrace.gateway_via_mapping = via_mapping+ def gateway_requested_model(self, turn_id: str) -> Optional[str]:+ with self._lock:+ trace = self._traces.get(turn_id)+ if trace is None or trace.ambiguous:+ return None+ return trace.requested_model_id+def gateway_terminalizer(self,*,diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.pyindex ba0b705b3..615ea9acd 100644--- a/core/handlers/model_hub/resolver.py+++ b/core/handlers/model_hub/resolver.py@@ -2,6 +2,7 @@from __future__ import annotations+import refrom dataclasses import dataclass, replacefrom datetime import datetimefrom typing import Literal@@ -15,6 +16,21 @@ BackendName = Literal["claude", "codex", "opencode"]ResolutionChannel = Literal["direct", "native_cli", "hub", "unavailable"]SupplyStatus = Literal["ok", "degraded", "waiting", "interrupted"]+_NATIVE_VENDOR_BY_BACKEND: dict[BackendName, str] = {+ "claude": "anthropic",+ "codex": "openai",+}+_CLAUDE_FAMILY_ALIASES = {+ "opus": "opus",+ "opus[1m]": "opus",+ "sonnet": "sonnet",+ "sonnet[1m]": "sonnet",+ "haiku": "haiku",+}+_CLAUDE_MODEL_ID = re.compile(+ r"^claude-(?P<family>opus|sonnet|haiku|fable)-(?P<version>\d+(?:-\d+)*?)(?:-(?P<date>\d{8}))?$"+)+@dataclass(frozen=True)class ModelHubTurnResolution:@@ -25,11 +41,105 @@ class ModelHubTurnResolution:source: ModelHubSourceConfig | Nonematching_sources: tuple[ModelHubSourceConfig, ...] = ()candidates: tuple[ModelHubSourceConfig, ...] = ()+ source_model_ids: tuple[tuple[str, str], ...] = ()provider: str | None = Nonemapping_applied: bool = Falserecoverable_source_ids: tuple[str, ...] = ()supply_status: SupplyStatus | None = None+ def model_for_source(self, source: ModelHubSourceConfig | str) -> str | None:+ source_id = source if isinstance(source, str) else source.id+ return next(+ (+ model_id+ for candidate_source_id, model_id in self.source_model_ids+ if candidate_source_id == source_id+ ),+ None,+ )+++def _parsed_claude_model_id(+ model_id: str,+) -> tuple[str, tuple[int, ...], int | None] | None:+ match = _CLAUDE_MODEL_ID.fullmatch(model_id)+ if match is None:+ return None+ return (+ match.group("family"),+ tuple(int(part) for part in match.group("version").split("-")),+ int(match.group("date")) if match.group("date") else None,+ )+++def _native_claude_alias(+ requested_model: str,+ source: ModelHubSourceConfig,+) -> str | None:+ family = _CLAUDE_FAMILY_ALIASES.get(requested_model)+ requested_version: tuple[int, ...] | None = None+ if family is None:+ parsed_request = _parsed_claude_model_id(requested_model)+ if parsed_request is None:+ return None+ family, requested_version, requested_date = parsed_request+ if requested_date is not None:+ return None++ matches: list[tuple[tuple[int, ...], int, str]] = []+ for model in source.models:+ if model.provenance != "discovered":+ continue+ parsed = _parsed_claude_model_id(model.id)+ if parsed is None:+ continue+ candidate_family, candidate_version, candidate_date = parsed+ if candidate_family != family:+ continue+ if requested_version is not None and candidate_version != requested_version:+ continue+ matches.append((candidate_version, candidate_date or 0, model.id))+ return max(matches)[2] if matches else None+++def _native_alias_for_source(+ backend: BackendName,+ requested_model: str,+ source: ModelHubSourceConfig,+) -> str | None:+ if source.vendor != _NATIVE_VENDOR_BY_BACKEND.get(backend):+ return None+ if backend == "claude":+ return _native_claude_alias(requested_model, source)+ return None+++def effective_model_for_source(+ *,+ backend: BackendName,+ requested_model: str,+ target_model: str,+ source: ModelHubSourceConfig,+ explicit_mapping: bool,+) -> str | None:+ """Return the upstream id this source can actually supply for one menu id."""++ if not explicit_mapping:+ if source.supply_channel == "native_cli" and any(+ model.id == requested_model for model in source.models+ ):+ return requested_model+ native_alias = _native_alias_for_source(+ backend,+ requested_model,+ source,+ )+ if native_alias is not None:+ return native_alias+ if any(model.id == target_model for model in source.models):+ return target_model+ return None+def allowed_origins(source: ModelHubSourceConfig) -> tuple[str, ...]:if source.kind == "api_key":@@ -249,17 +359,32 @@ def resolve_model_hub_turn()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.effective_source_order(backend))- 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)- )+ source_model_ids: list[tuple[str, str]] = []+ matching_sources: list[ModelHubSourceConfig] = []+ for source in (+ by_id[source_id]+ for source_id in config.effective_source_order(backend)+ ):+ if not source_eligible_for_backend(source, backend) or (+ provider is not None and opencode_provider_id(source.vendor) != provider+ ):+ continue+ effective_model = effective_model_for_source(+ backend=backend,+ requested_model=requested_model,+ target_model=target_model,+ source=source,+ explicit_mapping=mapping is not None,+ )+ if effective_model is None:+ continue+ matching_sources.append(source)+ source_model_ids.append((source.id, effective_model))+ matching_source_tuple = tuple(matching_sources)candidates: list[ModelHubSourceConfig] = []recoverable_source_ids: list[str] = []- for source in matching_sources:+ for source in matching_source_tuple:if supply_channel is not None and source.supply_channel != supply_channel:continueif source.state.status == "cooldown" and source_retry_ready(source, now):@@ -274,19 +399,27 @@ def resolve_model_hub_turn(source = candidates[0] if candidates else Nonecandidate_tuple = tuple(candidates)+ target_source = source or (+ matching_source_tuple[0] if matching_source_tuple else None+ )+ effective_target = dict(source_model_ids).get(+ target_source.id if target_source is not None else "",+ target_model,+ )return ModelHubTurnResolution(backend=backend,channel=source.supply_channel if source is not None else "unavailable",requested_model=requested_model,- target_model=target_model,+ target_model=effective_target,source=source,- matching_sources=matching_sources,+ matching_sources=matching_source_tuple,candidates=candidate_tuple,+ source_model_ids=tuple(source_model_ids),provider=provider,mapping_applied=mapping_applied,recoverable_source_ids=tuple(recoverable_source_ids),supply_status=_supply_status(- matching_sources,+ matching_source_tuple,candidate_tuple,now=now,unavailable_source_ids=unavailable_source_ids,diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 88534cba6..098fcd7af 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -2381,9 +2381,12 @@ class ModelHubService:now=now,unavailable_source_ids=unavailable,)+ effective_model = (+ resolution.model_for_source(source) or resolution.target_model+ )resolved_model = (- resolution.target_model- if resolution.mapping_applied or backend == "opencode"+ effective_model+ if effective_model != resolution.requested_modelelse None)chain.append(@@ -2641,14 +2644,14 @@ class ModelHubService:source,decision,agent=cast(EventAgent, backend),- model_id=resolved_model,+ model_id=chain_payload["model_id"],detail_key=error_key,)elif event_reason is not None:await self._set_source_blocker(source.id,backend=cast(BackendName, backend),- model_id=resolved_model,+ model_id=chain_payload["model_id"],detail_key=error_key,reason=event_reason,)@@ -3129,7 +3132,7 @@ class ModelHubService:self._record_event(agent=cast(EventAgent, resolution.backend),kind="recover",- model_id=resolution.target_model,+ model_id=resolution.requested_model,reason="recovery",to_source=source.id,to_label=source.display_name,@@ -3292,10 +3295,13 @@ class ModelHubService:failed_source: Optional[ModelHubSourceConfig] = Nonefailed_reason: Optional[EventReason] = Nonefor source in candidates:+ target_model = (+ resolution.model_for_source(source) or resolution.target_model+ )if source.supply_channel == "native_cli":self._emit_switch(agent=event_agent,- model_id=target_model,+ model_id=model_id,failed_source=failed_source,failed_reason=failed_reason,source=source,@@ -3328,7 +3334,7 @@ class ModelHubService:if outcome is None:self._emit_switch(agent=event_agent,- model_id=target_model,+ model_id=model_id,failed_source=failed_source,failed_reason=failed_reason,source=source,@@ -3348,7 +3354,7 @@ class ModelHubService:if outcome is None:self._emit_switch(agent=event_agent,- model_id=target_model,+ model_id=model_id,failed_source=failed_source,failed_reason=failed_reason,source=source,@@ -3367,7 +3373,7 @@ class ModelHubService:if decision.action == "return":self._emit_switch(agent=event_agent,- model_id=target_model,+ model_id=model_id,failed_source=failed_source,failed_reason=failed_reason,source=source,@@ -3394,7 +3400,7 @@ class ModelHubService:source,decision,agent=event_agent,- model_id=target_model,+ model_id=model_id,)elif event_reason != "permission_denied":detail_key = {@@ -3407,7 +3413,7 @@ class ModelHubService:await self._set_source_blocker(source.id,backend=cast(BackendName, backend),- model_id=target_model,+ model_id=model_id,detail_key=detail_key,reason=event_reason,)diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex 7f70736d2..669cfe155 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -166,7 +166,7 @@ class ModelHubTurnGateway:if not isinstance(model_id, str) or not model_id or not isinstance(stream, bool):terminalizer.fail("invalid_parameter")return self._error_response(status=400, code="invalid_request_error")- terminalizer.bind_request_model(model_id)+ resolution_model = terminalizer.resolution_model(model_id)def observe_attempt(source_id: str,@@ -197,7 +197,7 @@ class ModelHubTurnGateway:}resolved = await self.service.resolve(backend=backend,- model_id=model_id,+ model_id=resolution_model,request=ModelHubRequest(payload,protocol=_REQUEST_PROTOCOLS[endpoint],diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex 96480210b..c4d19db5b 100644--- a/docs/plans/model-hub-contracts/agent-chain.schema.json+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json@@ -2,7 +2,7 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/agent-chain.schema.json","title": "AgentChain",- "description": "v4 (2026-07-29 targeted amendment): the CAPABILITY chain for one (agent, model) pair — this backend's source order (agent-supply → sources.order) filtered by eligibility and by 'this source can supply this model, mapping applied'. For open menus the requested identifier carries a provider segment, and the vendor predicate is part of that filter: a `zhipuai/…` request is supplied only by zhipuai sources, never by whatever `custom/…` source happens to advertise the same bare model id (spec §4.3 step 2; the shipped resolver already enforces it). Deliberately NOT filtered by runnability: cooling, source-blocked and process-unavailable native_cli members stay at their positions, dimmed, because the user needs to see supply they own. The RUNNABLE candidate list is this chain further filtered to `runnable: true`, where runnable = health-permits AND process-available. Read-only projection, computed per request, never persisted.",+ "description": "v4 (2026-07-30 targeted amendment): the CAPABILITY chain for one (agent, model) pair — this backend's source order (agent-supply → sources.order) filtered by eligibility and by the server's one per-source supply derivation. That derivation applies an explicit mapping first, otherwise resolves a vendor-native fixed-menu alias against discovered inventory only, then tests source capability. For open menus the requested identifier carries a provider segment, and the vendor predicate is part of that filter: a `zhipuai/…` request is supplied only by zhipuai sources, never by whatever `custom/…` source happens to advertise the same bare model id. Deliberately NOT filtered by runnability: cooling, source-blocked and process-unavailable native_cli members stay at their positions, dimmed, because the user needs to see supply they own. The RUNNABLE candidate list is this chain further filtered to `runnable: true`, where runnable = health-permits AND process-available. Read-only projection, computed per request, never persisted.","type": "object","required": ["contract_version", "backend", "model_id", "chain", "supply_state"],"additionalProperties": false,@@ -133,11 +133,11 @@},"via_mapping": {"type": "boolean",- "description": "true when this source supplies the model only because a per-agent mapping rewrote the requested id (spec §4.3 step 1). UI marks the chip 经映射."+ "description": "true only when an explicit per-agent mapping rewrote the requested id (spec §4.3 step 1). A built-in vendor-native alias remains false, so UI can distinguish an owner-authored override from the default native resolution rule."},"resolved_model_id": {"type": ["string", "null"],- "description": "The id actually sent upstream (e.g. glm-5.2 for a requested claude-opus-4-6); null only when it is byte-identical to `model_id`. For open menus that never happens — the request is prefixed and the upstream id is bare — so this is non-null for every opencode chain, pinned by the conditional at the end of this file. Also non-null whenever `via_mapping` is true, since a mapping by definition produced a different id."+ "description": "The id actually sent upstream (e.g. glm-5.2 for an explicit mapping, or claude-opus-4-5-20251101 for a native claude-opus-4-5 alias); null only when it is byte-identical to `model_id`. For open menus that never happens — the request is prefixed and the upstream id is bare — so this is non-null for every opencode chain. Also non-null whenever `via_mapping` is true, since a mapping by definition produced a different id."},"health": {"enum": ["healthy", "cooldown", "needs_action", "error"],@@ -232,8 +232,8 @@}},{- "$comment": "v2 (07-29, review round 5): the converse of the item-level `via_mapping: true ⇒ resolved_model_id: string` rule, which completes it into a biconditional — but ONLY for fixed menus, and the scoping is the substance of the finding rather than a caveat on it. `resolved_model_id` is documented as 'null only when byte-identical to model_id', and for claude/codex the menu identifier IS the upstream id, so a mapping is the only thing that can make them differ (spec §4.3 step 1 is the sole rewrite mechanism at this grain). A fixed-menu item reporting `via_mapping: false` with a non-null resolved id therefore claims a rewrite that nothing performed, and the UI marks that chip 经映射 off `via_mapping` while rendering 实际跑的模型 off this field — so the two disagreeing puts a different model in the chip and in the label. The blanket converse would be WRONG and is deliberately not written: opencode resolves a prefixed request to a bare upstream id (`zhipuai/glm-5.2` → `glm-5.2`) with no mapping involved, so `via_mapping: false` with a non-null resolved id is the normal, required shape there — already pinned by the member above. Stated per backend family, the two members leave no combination undefined: open menus always carry a resolved id, fixed menus carry one exactly when a mapping produced it.",- "if": { "properties": { "backend": { "enum": ["claude", "codex"] } }, "required": ["backend"] },+ "$comment": "v4 (07-30 native-alias amendment): Codex has no built-in upstream-id rewrite today, so `via_mapping:false` still means byte-identical and therefore null for that backend. Claude differs: its fixed menu includes stable aliases that may resolve to a dated discovered id without becoming an explicit user mapping.",+ "if": { "properties": { "backend": { "const": "codex" } }, "required": ["backend"] },"then": {"properties": {"chain": {@@ -248,6 +248,33 @@}}}+ },+ {+ "$comment": "v4 (07-30 native-alias amendment): a non-mapped Claude rewrite is legal only in the vendor-native Claude identifier family. The server additionally proves same-family/version selection against discovered inventory; JSON Schema cannot compare the requested model_id with each row or inspect the source inventory.",+ "if": { "properties": { "backend": { "const": "claude" } }, "required": ["backend"] },+ "then": {+ "properties": {+ "chain": {+ "items": {+ "allOf": [+ {+ "if": { "properties": { "via_mapping": { "const": false } }, "required": ["via_mapping"] },+ "then": {+ "properties": {+ "resolved_model_id": {+ "anyOf": [+ { "type": "null" },+ { "type": "string", "pattern": "^claude-(opus|sonnet|haiku|fable)-[0-9]+(?:-[0-9]+)*(?:-[0-9]{8})?$" }+ ]+ }+ }+ }+ }+ ]+ }+ }+ }+ }}],"examples": [@@ -279,6 +306,24 @@],"supply_state": "ok"},+ {+ "contract_version": 4,+ "backend": "claude",+ "model_id": "claude-opus-4-5",+ "chain": [+ {+ "source_id": "src_glmrelay01",+ "channel": "hub",+ "via_mapping": false,+ "resolved_model_id": "claude-opus-4-5-20251101",+ "health": "healthy",+ "runnable": true,+ "reason": null,+ "retry_at": null+ }+ ],+ "supply_state": "ok"+ },{"contract_version": 4,"backend": "claude",diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.jsonindex acdd880db..3b66d5afb 100644--- a/docs/plans/model-hub-contracts/agent-supply.schema.json+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json@@ -32,7 +32,7 @@"properties": {"model_id": {"type": "string",- "description": "The RESOLVED upstream model id, mapping applied — what actually gets sent (e.g. `glm-5.2`). A property of this attempt, not of the selection, which is why it stays here while the selection moved out. NOT a valid input to the chain query or the probe: for open-menu backends the caller-facing identifier is prefixed (`zhipuai/glm-5.2`), so passing this value through would miss. Use the top-level `selected_model_id` for that. Equal to `selected_model_id` whenever no mapping applied and the menu is fixed — the two differing is the 「我选的模型」 vs 「实际跑的模型」 distinction the UI surfaces, so they are never collapsed."+ "description": "The RESOLVED upstream model id — what actually gets sent (e.g. `glm-5.2` or `claude-opus-4-5-20251101`). A property of this attempt, not of the selection, which is why it stays here while the selection moved out. NOT a valid input to the chain query or the probe: for open-menu backends the caller-facing identifier is prefixed (`zhipuai/glm-5.2`), while a fixed-menu native alias may be source-specific, so passing this value through would miss. Use the top-level `selected_model_id` for that. It equals `selected_model_id` only when neither an explicit mapping nor built-in native alias resolution changes the upstream id. Native alias resolution is automatic supply truth and does not create a mapping entry."},"source_id": { "type": "string" },"channel": { "enum": ["native_cli", "hub"] }diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex ed4124321..b6ce0be0f 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -58,6 +58,14 @@ Ordering is backend-owned through the sources routes.provider; the resolver sends the bare model id upstream.- A mapping rewrites a menu id to an upstream model id. A mapping never chooses asource.+- Without an explicit mapping, a vendor-native fixed menu may resolve a stable menu+ alias per source. Claude version aliases select the latest dated id for that exact+ version; `opus`, `sonnet`, `haiku`, `opus[1m]`, and `sonnet[1m]` select the latest+ discovered id in their family. A dated request remains exact. Alias candidates come+ only from that source's discovered inventory; manual models, foreign-vendor sources,+ and undiscovered passthrough ids do not qualify. A native CLI source preserves an+ exact CLI alias instead of replacing it with a bundled-catalog model. Explicit+ mappings take precedence.- Source event references are checked when emitted. Retained feed entries remainvalid after a later legal source deletion.@@ -133,6 +141,12 @@ which is a list of bare names inside a mutation result.user's explicit configuration request. FALSE means no explicit model selection,including a resolver-picked value or no selected model.+For a fixed native menu, `current.model_id` is the effective upstream id for the+selected source. It may therefore differ from `selected_model_id` without an+explicit mapping when built-in native alias resolution chooses a discovered dated+model. Chain and probe inputs remain the caller-facing `selected_model_id`; each+candidate derives its own effective upstream id.+Disabled Agents are absent. In Direct mode each named Agent may still have aneffective model, but its Hub `supply_status` is null.@@ -433,7 +447,9 @@ Status and submit return the same terminal shape:## Chain and probeIn Hub mode, `AgentChain.chain` is the effective source order filtered by backend-eligibility and model support, with mapping applied. Cooling, source-blocked and+eligibility and the server's per-source effective-model derivation. That derivation+applies an explicit mapping first, otherwise applies the vendor-native alias rule above,+then verifies the resulting id against source inventory. Cooling, source-blocked andprocess-unavailable native CLI members stay in the chain at their original positions.Each item carries `channel`, source-global `health`, process-aware `runnable`, andnullable `reason`. The complete axiom is:diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex fa121b22b..7c22b6cc7 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -261,15 +261,18 @@ cooldown pool keyed on the shared source row, `_cooldown` inlaunches backends per request; switching never happens mid-process.`native_cli` sources are eligible only for their sanctioned client (Claude sub→ Claude Code); enforced in code via `allowed_origins`-style binding.-1. **Mapping** — requested model ID → actual model. Identity by default.+1. **Mapping** — requested model ID → explicit target, when one exists.Only fixed-menu agents (Claude Code / Codex) can override, per-agent(e.g. Claude Code's `claude-opus-4-6` → `glm-5.2`). Mapping is an explicit,- deterministic user choice.+ deterministic user choice and always takes precedence. No mapping means the+ caller-facing menu ID stays intact for the next, per-source derivation; it does+ not promise blind identity passthrough to an upstream.2. **Candidates (v2)** — start from **this agent's ordered subset** (§4.2), inits order, then filter in two stages:- - **capability** (structural, stable): a. the source supplies the (mapped)- model id; b. the source is eligible for this backend and channel (§4.4);- c. for open menus, the source's vendor matches the **provider segment** of the+ - **capability** (structural, stable): a. derive this source's **effective+ upstream model id**, then require the source to supply it; b. the source is+ eligible for this backend and channel (§4.4); c. for open menus, the source's+ vendor matches the **provider segment** of therequested identifier. Predicate c does not fold into a: sources advertise baremodel ids, so `zhipuai/glm-5.2` and `custom/glm-5.2` present the *same* bare id,and without the vendor predicate the agent's source order alone would decide@@ -278,6 +281,21 @@ cooldown pool keyed on the shared source row, `_cooldown` in(`opencode_provider_id(source.vendor) == provider`,`core/handlers/model_hub/resolver.py`); v2 keeps it, and keeps it in the*capability* stage, because a vendor is structural and not momentary.+ The effective-id derivation has one precedence order. An explicit mapping+ requires its target id exactly. Without one, a `native_cli` source first+ preserves an exact CLI alias such as `opus` or `sonnet[1m]`; the installed CLI+ owns that alias's compatibility. For every other fixed-menu source on its+ backend-native vendor, built-in aliases resolve against **that source's+ discovered inventory only**: a Claude version alias chooses the latest dated id+ for that exact version; `opus`, `sonnet`, `haiku`, `opus[1m]`, and+ `sonnet[1m]` choose the latest version/date in the same family; a dated request+ remains exact. If no automatic native alias applies, exact identity is accepted+ when the source advertises the menu id.+ Manual inventory, a foreign vendor, and an undiscovered id never satisfy this+ automatic branch. Therefore two Hub sources may derive different dated ids for+ one menu id. The caller-facing menu id+ remains the stable chain, probe, gateway, and event correlation key; only the+ upstream attempt carries the per-source effective id.What survives is the *capability chain* for this (agent, model) pair — what§4.6 defines and what the UI displays, cooling members included.- **runnability** (momentary, per turn): d. the source is retry-ready —diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex b72b7a9fe..c5ef614e2 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -581,7 +581,7 @@ class ModelHubRuntimeRouter:route_events = [eventfor event in self.service.events.list(limit=100)- if event.get("agent") == current.backend and event.get("model_id") == current.target_model+ if event.get("agent") == current.backend and event.get("model_id") == current.requested_model]pending_source: ModelHubSourceConfig | None = Nonepending_reason: EventReason | None = None@@ -650,7 +650,7 @@ class ModelHubRuntimeRouter:):self.service._emit_switch(agent=cast(EventAgent, current.backend),- model_id=current.target_model,+ model_id=current.requested_model,failed_source=failed_source,failed_reason=failed_reason,source=current_source,@@ -673,7 +673,7 @@ class ModelHubRuntimeRouter:self.service._record_event(agent=cast(EventAgent, current.backend),kind="channel_switch",- model_id=current.target_model,+ model_id=current.requested_model,reason=reason,from_source=previous.source_id,to_source=previous.source_id,@@ -1030,7 +1030,7 @@ class ModelHubRuntimeRouter:source,decision,agent=cast(EventAgent, launch.backend),- model_id=launch.target_model,+ model_id=launch.requested_model,)setattr(context, _CONTEXT_FAILURE_RECORDED_ATTR, True)return Truediff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 21e3498d7..bff20484c 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -195,6 +195,46 @@ def test_every_frozen_schema_example_is_valid_and_json_round_trips():assert _canonical(json.loads(_canonical(example))) == _canonical(example)+def test_agent_supply_contract_accepts_unmapped_native_alias_current():+ payload = {+ "backend": "claude",+ "mode": "hub",+ "menu_kind": "fixed",+ "selected_by_agent": None,+ "selected_model_id": "claude-opus-4-5",+ "selected_model_explicit": True,+ "current": {+ "model_id": "claude-opus-4-5-20251101",+ "source_id": "src_anthropic1",+ "channel": "hub",+ },+ "sources": {+ "policy": "follow",+ "order": ["src_anthropic1"],+ "eligibility": [+ {+ "source_id": "src_anthropic1",+ "eligible": True,+ "reason_key": None,+ "in_current_model_chain": True,+ "process_availability_reason": None,+ }+ ],+ },+ "supply_status": "ok",+ "mappings": [],+ "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_v4_mirror_registry_is_executable_and_complete():registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))schemas = _mirror_schemas(registry)@@ -432,6 +472,20 @@ def test_v4_shape_amendments_reject_the_false_states_they_replace():chain_schema = _schema("agent-chain.schema.json")chain_validator = Draft7Validator(chain_schema)+ native_alias = next(+ example+ for example in chain_schema["examples"]+ if example["model_id"] == "claude-opus-4-5"+ and example["chain"]+ and example["chain"][0]["resolved_model_id"] is not None+ and example["chain"][0]["via_mapping"] is False+ )+ chain_validator.validate(native_alias)+ invalid_native_alias = copy.deepcopy(native_alias)+ invalid_native_alias["chain"][0]["resolved_model_id"] = "glm-5.2"+ with pytest.raises(ValidationError):+ chain_validator.validate(invalid_native_alias)+native_unavailable = copy.deepcopy(chain_schema["examples"][-1])chain_validator.validate(native_unavailable)diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex e5707a659..e8f8d2763 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -482,6 +482,133 @@ def test_mh_chan_001_native_sources_only_dispatch_to_sanctioned_client(tmp_path:assert (launch.channel, launch.source_id) == ("hub", hub_openai.id)+def test_runtime_launch_uses_discovered_native_alias_target(tmp_path: Path) -> None:+ relay = _source(+ "src_alias001",+ kind="api_key",+ vendor="anthropic",+ protocol="anthropic",+ channel="hub",+ model_ids=("claude-opus-4-5-20251101",),+ )+ config = _hub_config(+ sources=[relay],+ order=[relay.id],+ agents=_agents(),+ )+ service = _service(+ tmp_path,+ config,+ LaunchAdapter({relay.id: "route-alias"}),+ now=lambda: datetime(2026, 7, 30, tzinfo=timezone.utc),+ )++ launch = asyncio.run(+ _router(service).resolve("claude", "claude-opus-4-5")+ )++ assert launch.source_id == relay.id+ assert launch.target_model == "claude-opus-4-5-20251101"+ assert launch.runtime_model == "route-alias/claude-opus-4-5-20251101"++[email protected]("requested_model", ["opus", "sonnet[1m]"])+def test_native_cli_preserves_exact_cli_alias(+ tmp_path: Path,+ requested_model: str,+) -> None:+ native = _source(+ "src_native_alias",+ kind="subscription",+ vendor="anthropic",+ protocol="anthropic",+ channel="native_cli",+ model_ids=(+ requested_model,+ "claude-opus-5",+ "claude-sonnet-5",+ ),+ )+ config = _hub_config(+ sources=[native],+ order=[native.id],+ agents=_agents(),+ )+ service = _service(+ tmp_path,+ config,+ LaunchAdapter({}),+ now=lambda: datetime(2026, 7, 30, tzinfo=timezone.utc),+ )++ launch = asyncio.run(_router(service).resolve("claude", requested_model))++ assert launch.channel == "native_cli"+ assert launch.source_id == native.id+ assert launch.target_model == requested_model+ assert launch.runtime_model == requested_model+++def test_runtime_alias_failover_correlates_by_requested_menu_id(tmp_path: Path) -> None:+ requested_model = "claude-opus-4-5"+ primary = _source(+ "src_alias_primary",+ kind="api_key",+ vendor="anthropic",+ protocol="anthropic",+ channel="hub",+ model_ids=("claude-opus-4-5-20251101",),+ )+ backup = _source(+ "src_alias_backup",+ kind="api_key",+ vendor="anthropic",+ protocol="anthropic",+ channel="hub",+ model_ids=("claude-opus-4-5-20250929",),+ )+ config = _hub_config(+ sources=[primary, backup],+ order=[primary.id, backup.id],+ agents=_agents(),+ )+ service = _service(+ tmp_path,+ config,+ LaunchAdapter(+ {+ primary.id: "route-primary",+ backup.id: "route-backup",+ }+ ),+ now=lambda: datetime(2026, 7, 30, tzinfo=timezone.utc),+ )+ router = _router(service)++ primary_launch = asyncio.run(router.resolve("claude", requested_model))+ context = SimpleNamespace()+ bind_launch(context, primary_launch)+ assert asyncio.run(router.record_native_failure(context, "429 rate limit")) is True++ backup_launch = asyncio.run(router.resolve("claude", requested_model))++ assert primary_launch.target_model == "claude-opus-4-5-20251101"+ assert backup_launch.target_model == "claude-opus-4-5-20250929"+ assert backup_launch.source_id == backup.id+ transition_events = [+ event+ for event in service.events.list(limit=20)+ if event["kind"] in {"cooldown", "switch"}+ ]+ assert [event["kind"] for event in transition_events] == [+ "switch",+ "cooldown",+ ]+ assert {event["model_id"] for event in transition_events} == {+ requested_model+ }++def test_mh_chan_001_unconfigured_hub_is_interrupted(tmp_path: Path) -> None:service = _service(tmp_path,diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 459d177fe..48830dcdf 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -138,13 +138,16 @@ def _source(channel: str = "hub",status: str = "standby",retry_at: str | None = None,+ vendor: str = "openai",+ protocol: str = "openai_responses",+ model_id: str = "shared-model",) -> ModelHubSourceConfig:return ModelHubSourceConfig(id=source_id,kind="subscription" if channel == "native_cli" else "api_key",- vendor="openai",+ vendor=vendor,display_name=label,- protocol="openai_responses",+ protocol=protocol,supply_channel=channel,billing="monthly" if channel == "native_cli" else "metered",state=ModelHubSourceStateConfig(@@ -158,7 +161,7 @@ def _source(),models=[ModelHubModelConfig(- id="shared-model",+ id=model_id,provenance="discovered",)],@@ -581,6 +584,98 @@ def test_gateway_provenance_retains_pre_mapping_model_identity(_assert_valid("turn-provenance.schema.json", record)+def test_gateway_preserves_native_alias_for_per_source_failover(+ tmp_path: Path,+) -> None:+ async def exercise() -> None:+ requested_model = "claude-opus-4-5"+ primary_model = "claude-opus-4-5-20251101"+ backup_model = "claude-opus-4-5-20250929"+ primary = _source(+ "src_primary01",+ "Primary",+ vendor="anthropic",+ protocol="anthropic",+ model_id=primary_model,+ )+ backup = _source(+ "src_backup001",+ "Backup",+ vendor="anthropic",+ protocol="anthropic",+ model_id=backup_model,+ )+ service = _service(+ tmp_path,+ sources=[primary, backup],+ outcomes=[+ _outcome(+ RawOutcomeKind.HTTP_ERROR,+ status=429,+ source_id=primary.id,+ ),+ _outcome(+ RawOutcomeKind.SUCCESS,+ source_id=backup.id,+ ),+ ],+ )+ gateway = ModelHubTurnGateway(service)+ base_url, token = await gateway.endpoint(+ "claude",+ process_scope="/repo",+ turn_id="turn_native_alias",+ requested_model_id=requested_model,+ resolved_model_id=primary_model,+ source_id=primary.id,+ )+ try:+ async with aiohttp.ClientSession(trust_env=False) as client:+ response = await client.post(+ f"{base_url}/v1/messages",+ json={+ "model": primary_model,+ "max_tokens": 1,+ "messages": [+ {"role": "user", "content": "ping"}+ ],+ "stream": False,+ },+ headers={"x-api-key": token},+ )+ assert response.status == 200+ await response.read()+ finally:+ await gateway.close()++ assert service.adapter.invocations == [+ (primary.id, primary_model, "claude"),+ (backup.id, backup_model, "claude"),+ ]+ failover_events = [+ event+ for event in service.events.list(limit=20)+ if event["kind"] in {"cooldown", "switch"}+ ]+ assert {event["model_id"] for event in failover_events} == {+ requested_model+ }++ gateway.correlation.settle(+ "turn_native_alias",+ settled_by=SETTLED_BY_TERMINAL_RESULT,+ ts=NOW.isoformat(),+ )+ record = service.provenance.get("turn_native_alias")+ assert record is not None+ assert record["requested_model_id"] == requested_model+ assert record["served"]["source_id"] == backup.id+ assert record["served"]["resolved_model_id"] == backup_model+ _assert_valid("turn-provenance.schema.json", record)++ asyncio.run(exercise())++def test_gateway_model_outside_prepared_turn_fails_closed(tmp_path: Path,) -> None:diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 0b30e0d8d..c42cf6b43 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -635,6 +635,327 @@ def test_mapping_is_scoped_to_the_requesting_backend(tmp_path):assert agents["codex"].mappings == []+ ("requested_model", "discovered_models", "expected_model"),+ [+ (+ "claude-opus-4-5",+ [+ "claude-opus-4-5",+ "claude-opus-4-5-20250929",+ "claude-opus-4-5-20251101",+ ],+ "claude-opus-4-5-20251101",+ ),+ (+ "opus",+ ["opus", "claude-opus-4-8-20260601", "claude-opus-5-20260724"],+ "claude-opus-5-20260724",+ ),+ (+ "opus[1m]",+ ["claude-opus-4-8-20260601", "claude-opus-5-20260724"],+ "claude-opus-5-20260724",+ ),+ (+ "sonnet",+ ["claude-sonnet-4-6-20260301", "claude-sonnet-5-20260720"],+ "claude-sonnet-5-20260720",+ ),+ (+ "sonnet[1m]",+ ["claude-sonnet-4-6-20260301", "claude-sonnet-5-20260720"],+ "claude-sonnet-5-20260720",+ ),+ (+ "haiku",+ ["claude-haiku-4-20250101", "claude-haiku-4-5-20251001"],+ "claude-haiku-4-5-20251001",+ ),+ (+ "claude-opus-4-5-20250929",+ ["claude-opus-4-5-20250929", "claude-opus-4-5-20251101"],+ "claude-opus-4-5-20250929",+ ),+ ],+)+def test_native_claude_aliases_resolve_only_to_discovered_inventory(+ tmp_path,+ requested_model,+ discovered_models,+ expected_model,+):+ service = _service(tmp_path, FakeAdapter([]))+ config = service.store.load()+ config.sources[0].models = [+ ModelHubModelConfig(id=model_id, provenance="discovered")+ for model_id in discovered_models+ ]+ config.sources[1].models = []++ resolution = resolve_model_hub_turn(config, "claude", requested_model)++ assert resolution.source is config.sources[0]+ assert resolution.target_model == expected_model+ assert resolution.mapping_applied is False+++def test_native_aliases_do_not_blind_passthrough_or_use_manual_or_foreign_inventory(+ tmp_path,+):+ service = _service(tmp_path, FakeAdapter([]))+ config = service.store.load()+ relay = config.sources[0]+ relay.base_url = "https://glm-relay.example.test"+ relay.models = [+ ModelHubModelConfig(+ id="claude-opus-4-5-20251101",+ provenance="discovered",+ ),+ ModelHubModelConfig(+ id="claude-fable-5-20260701",+ provenance="manual",+ ),+ ]+ foreign = config.sources[1]+ foreign.vendor = "custom"+ foreign.models = [+ ModelHubModelConfig(+ id="claude-sonnet-5-20260720",+ provenance="discovered",+ )+ ]++ resolved = resolve_model_hub_turn(config, "claude", "claude-opus-4-5")+ fictional = resolve_model_hub_turn(config, "claude", "claude-fable-5")+ foreign_only = resolve_model_hub_turn(config, "claude", "claude-sonnet-5")++ assert resolved.target_model == "claude-opus-4-5-20251101"+ assert [source.id for source in resolved.matching_sources] == [relay.id]+ assert fictional.matching_sources == ()+ assert foreign_only.matching_sources == ()+++def test_explicit_mapping_overrides_native_alias_resolution(tmp_path):+ service = _service(tmp_path, FakeAdapter([]))+ config = service.store.load()+ config.sources[0].models = [+ ModelHubModelConfig(+ id="claude-opus-4-5-20251101",+ provenance="discovered",+ ),+ ModelHubModelConfig(id="glm-5.2", provenance="discovered"),+ ]+ config.sources[1].models = []+ config.agents["claude"].mappings = [+ ModelHubMappingConfig(+ builtin_id="claude-opus-4-5",+ target_model_id="glm-5.2",+ enabled=True,+ )+ ]++ resolution = resolve_model_hub_turn(config, "claude", "claude-opus-4-5")++ assert resolution.target_model == "glm-5.2"+ assert resolution.mapping_applied is True+++def test_wall_drawers_chain_probe_and_resolver_share_native_alias_supply_truth(+ tmp_path,+):+ effective_model = "claude-opus-4-5-20251101"+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])+ service = _service(tmp_path, adapter)+ config = service.store.load()+ config.sources[0].models = [+ ModelHubModelConfig(id=effective_model, provenance="discovered")+ ]+ config.sources[1].models = []+ service.store.requested_models["claude"] = "claude-opus-4-5"++ agent = service.get_agent_sources("claude")+ chain = service.agent_chain("claude", "claude-opus-4-5")+ resolution = resolve_model_hub_turn(+ config,+ "claude",+ "claude-opus-4-5",+ now=service.now(),+ )+ probe = asyncio.run(service.probe_agent("claude", "claude-opus-4-5"))++ # The row wall consumes model_supply/current. Both drawers consume the chain+ # endpoint. Probe and live resolution must carry those exact same bytes.+ wall = next(+ row+ for row in agent["model_supply"]+ if row["model_id"] == "claude-opus-4-5"+ )+ assert wall["chain_length"] == len(chain["chain"]) == 1+ assert (+ agent["current"]["model_id"]+ == chain["chain"][0]["resolved_model_id"]+ == resolution.target_model+ == probe["model_id"]+ == effective_model+ )+ assert chain["chain"][0]["via_mapping"] is False+ assert adapter.invocations == [+ ("src_primary01", effective_model, "claude")+ ]+++def test_probe_flips_from_no_candidate_to_reachable_after_discovered_alias_arrives(+ tmp_path,+):+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])+ service = _service(tmp_path, adapter)+ config = service.store.load()+ config.sources[0].models = []+ config.sources[1].models = []++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(service.probe_agent("claude", "claude-opus-4-5"))+ assert exc_info.value.code == "probe_no_candidate"++ config.sources[0].models = [+ ModelHubModelConfig(+ id="claude-opus-4-5-20251101",+ provenance="discovered",+ )+ ]+ probe = asyncio.run(service.probe_agent("claude", "claude-opus-4-5"))++ assert probe["reachable"] is True+ assert probe["model_id"] == "claude-opus-4-5-20251101"+++ ("outcome", "expected_kind"),+ [+ (+ _outcome(RawOutcomeKind.HTTP_ERROR, status=429),+ "cooldown",+ ),+ (+ _outcome(RawOutcomeKind.HTTP_ERROR, status=403),+ "needs_action",+ ),+ ],+)+def test_probe_alias_failure_events_use_requested_menu_id(+ tmp_path,+ outcome,+ expected_kind,+):+ adapter = FakeAdapter([outcome])+ service = _service(tmp_path, adapter)+ config = service.store.load()+ config.sources[0].models = [+ ModelHubModelConfig(+ id="claude-opus-4-5-20251101",+ provenance="discovered",+ )+ ]+ config.sources[1].models = []++ probe = asyncio.run(service.probe_agent("claude", "claude-opus-4-5"))++ assert probe["reachable"] is False+ assert probe["model_id"] == "claude-opus-4-5-20251101"+ event = next(+ item+ for item in service.events.list(limit=20)+ if item["kind"] == expected_kind+ )+ assert event["model_id"] == "claude-opus-4-5"+++def test_failover_uses_each_sources_effective_native_alias(tmp_path):+ adapter = FakeAdapter(+ [+ _outcome(RawOutcomeKind.HTTP_ERROR, status=429),+ _outcome(RawOutcomeKind.SUCCESS, status=200),+ ]+ )+ service = _service(tmp_path, adapter)+ config = service.store.load()+ config.sources[0].models = [+ ModelHubModelConfig(+ id="claude-opus-4-5-20251101",+ provenance="discovered",+ )+ ]+ config.sources[1].models = [+ ModelHubModelConfig(+ id="claude-opus-4-5-20250929",+ provenance="discovered",+ )+ ]++ result = asyncio.run(+ service.resolve(+ backend="claude",+ model_id="claude-opus-4-5",+ request={},+ )+ )++ assert result.source_id == "src_backup001"+ assert result.model_id == "claude-opus-4-5-20250929"+ assert adapter.invocations == [+ ("src_primary01", "claude-opus-4-5-20251101", "claude"),+ ("src_backup001", "claude-opus-4-5-20250929", "claude"),+ ]+ failover_events = [+ event+ for event in service.events.list(limit=20)+ if event["kind"] in {"cooldown", "switch"}+ ]+ assert {event["model_id"] for event in failover_events} == {+ "claude-opus-4-5"+ }+++def test_runtime_alias_blocker_event_uses_requested_menu_id(tmp_path):+ adapter = FakeAdapter(+ [+ _outcome(RawOutcomeKind.HTTP_ERROR, status=403),+ _outcome(RawOutcomeKind.SUCCESS, status=200),+ ]+ )+ service = _service(tmp_path, adapter)+ config = service.store.load()+ config.sources[0].models = [+ ModelHubModelConfig(+ id="claude-opus-4-5-20251101",+ provenance="discovered",+ )+ ]+ config.sources[1].models = [+ ModelHubModelConfig(+ id="claude-opus-4-5-20250929",+ provenance="discovered",+ )+ ]++ result = asyncio.run(+ service.resolve(+ backend="claude",+ model_id="claude-opus-4-5",+ request={},+ )+ )++ assert result.source_id == "src_backup001"+ blocker = next(+ event+ for event in service.events.list(limit=20)+ if event["kind"] == "needs_action"+ )+ assert blocker["model_id"] == "claude-opus-4-5"++def test_opencode_provider_prefix_selects_matching_source_and_current_payload(tmp_path):adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])service = _service(tmp_path, adapter)