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.

feat(model-hub): reasoning tier provenance ladder (#1836)

Max84c10fca1726
diff --git a/config/v2_config.py b/config/v2_config.py
index 5ec836d2e..8aeb19856 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -2710,6 +2710,9 @@ class ModelHubModelConfig:
id: str
provenance: Literal["discovered", "manual"]
reasoning_efforts: list[str] = field(default_factory=list)
+ reasoning_efforts_source: Optional[
+ Literal["upstream", "catalog", "user"]
+ ] = None
display_name: Optional[str] = None
discovered_at: Optional[str] = None
retired: Optional[bool] = None
@@ -2723,6 +2726,7 @@ class ModelHubModelConfig:
"display_name",
"origin",
"reasoning_efforts",
+ "reasoning_efforts_source",
"discovered_at",
"retired",
}:
@@ -2732,6 +2736,10 @@ class ModelHubModelConfig:
if "reasoning_efforts" not in payload:
raise ValueError("Config 'model_hub.sources.models.reasoning_efforts' is required")
reasoning_efforts = payload["reasoning_efforts"]
+ if "reasoning_efforts_source" in payload:
+ reasoning_efforts_source = payload["reasoning_efforts_source"]
+ else:
+ reasoning_efforts_source = "user" if reasoning_efforts else None
display_name = payload.get("display_name")
discovered_at = payload.get("discovered_at")
retired = payload.get("retired")
@@ -2748,6 +2756,21 @@ class ModelHubModelConfig:
raise ValueError(
"Config 'model_hub.sources.models.reasoning_efforts' must be a unique credential-free array of strings"
)
+ if reasoning_efforts_source is not None and (
+ not isinstance(reasoning_efforts_source, str)
+ or reasoning_efforts_source not in {"upstream", "catalog", "user"}
+ ):
+ raise ValueError(
+ "Config 'model_hub.sources.models.reasoning_efforts_source' is invalid"
+ )
+ if reasoning_efforts and reasoning_efforts_source is None:
+ raise ValueError(
+ "Config non-empty reasoning efforts require a provenance source"
+ )
+ if not reasoning_efforts and reasoning_efforts_source in {"upstream", "user"}:
+ raise ValueError(
+ "Config empty reasoning efforts cannot use upstream or user provenance"
+ )
if display_name is not None and (
not isinstance(display_name, str)
or _contains_model_hub_credential_material(display_name)
@@ -2772,6 +2795,7 @@ class ModelHubModelConfig:
id=normalized_model_id(model_id),
provenance=origin,
reasoning_efforts=list(reasoning_efforts),
+ reasoning_efforts_source=reasoning_efforts_source,
display_name=display_name,
discovered_at=_validate_optional_datetime(
discovered_at,
@@ -2781,11 +2805,15 @@ class ModelHubModelConfig:
)
def to_payload(self) -> dict:
+ reasoning_efforts_source = self.reasoning_efforts_source
+ if reasoning_efforts_source is None and self.reasoning_efforts:
+ reasoning_efforts_source = "user"
payload = {
"id": self.id,
"display_name": self.display_name,
"origin": self.provenance,
"reasoning_efforts": list(self.reasoning_efforts),
+ "reasoning_efforts_source": reasoning_efforts_source,
"discovered_at": self.discovered_at,
}
if self.retired is not None:
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index d16bdeb92..fa4a2b36a 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -1,4 +1,4 @@
-"""Model Hub EngineAdapter interface. FINAL CONTRACT v5 (2026-08-09).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v7 (2026-09-03).
This file is the canonical adapter boundary and must remain byte-identical to
``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:
@@ -121,6 +121,14 @@ class ObservationDiscovery(str, Enum):
NOT_ATTEMPTED = OBSERVATION_DISCOVERY_OUTCOMES[2]
+@dataclass(frozen=True)
+class DiscoveredModel:
+ """One model inventory row and the only upstream metadata v1 retains."""
+
+ id: str
+ supported_parameters: tuple[str, ...] | None = None
+
+
@dataclass(frozen=True)
class SourceObservation:
"""Response-backed result of an unsaved Source observation."""
@@ -130,7 +138,11 @@ class SourceObservation:
authenticated: bool | None
protocol: str | None
discovery: ObservationDiscovery
- model_ids: tuple[str, ...]
+ models: tuple[DiscoveredModel, ...]
+
+ @property
+ def model_ids(self) -> tuple[str, ...]:
+ return tuple(model.id for model in self.models)
@dataclass(frozen=True)
@@ -214,8 +226,23 @@ def validate_source_observation(observation: object) -> SourceObservation:
bool,
):
raise ValueError("invalid SourceObservation authentication")
- if not isinstance(observation.model_ids, tuple) or any(
- not isinstance(model_id, str) or not model_id for model_id in observation.model_ids
+ if not isinstance(observation.models, tuple) or any(
+ not isinstance(model, DiscoveredModel)
+ or not isinstance(model.id, str)
+ or not model.id
+ or (
+ model.supported_parameters is not None
+ and (
+ not isinstance(model.supported_parameters, tuple)
+ or any(
+ not isinstance(parameter, str) or not parameter
+ for parameter in model.supported_parameters
+ )
+ or len(set(model.supported_parameters))
+ != len(model.supported_parameters)
+ )
+ )
+ for model in observation.models
):
raise ValueError("invalid SourceObservation inventory")
if len(set(observation.model_ids)) != len(observation.model_ids):
@@ -241,7 +268,7 @@ def make_source_observation(
authenticated: bool | None,
protocol: str | None,
discovery: ObservationDiscovery,
- model_ids: Sequence[str],
+ models: Sequence[DiscoveredModel],
) -> SourceObservation:
"""Construct an adapter result through the terminal-product authority."""
@@ -252,7 +279,7 @@ def make_source_observation(
authenticated=authenticated,
protocol=protocol,
discovery=discovery,
- model_ids=tuple(model_ids),
+ models=tuple(models),
)
)
@@ -451,8 +478,8 @@ class EngineAdapter(Protocol):
protocol: str,
base_url: str | None,
credential_ref: str,
- ) -> Sequence[str]:
- """Refresh supplyable model ids for a saved Source using its stored protocol."""
+ ) -> Sequence[DiscoveredModel]:
+ """Refresh supplyable models for a saved Source using its stored protocol."""
...
async def observe_source(
diff --git a/core/handlers/model_hub/events.py b/core/handlers/model_hub/events.py
index 33cbed89d..9125e2b38 100644
--- a/core/handlers/model_hub/events.py
+++ b/core/handlers/model_hub/events.py
@@ -24,6 +24,7 @@ EventKind = Literal[
"channel_switch",
"needs_action",
"supply_interrupted",
+ "reasoning_efforts_override",
]
EventReason: TypeAlias = str
BillingNote = Literal["entered_metered", "left_metered"]
@@ -45,6 +46,8 @@ EVENT_REASON_AUTHORITY: dict[str, ReasonClass] = {
"network": "self_healing",
"recovery": "transition",
"manual": "transition",
+ "upstream_tiers": "transition",
+ "catalog_tiers": "transition",
"credential_expired": "non_self_healing",
"credential_revoked": "non_self_healing",
"balance_exhausted": "non_self_healing",
@@ -210,6 +213,18 @@ def build_resolution_event(
model_id is None or from_source is None or to_source is None
):
raise ValueError("Invalid switch event")
+ if kind == "reasoning_efforts_override" and (
+ agent != "system"
+ or model_id is None
+ or from_source is None
+ or to_source is not None
+ or reason not in {"upstream_tiers", "catalog_tiers"}
+ ):
+ raise ValueError("Invalid reasoning_efforts_override event")
+ if reason in {"upstream_tiers", "catalog_tiers"} and (
+ kind != "reasoning_efforts_override"
+ ):
+ raise ValueError("Managed-tier reasons require reasoning_efforts_override")
if kind in {"cooldown", "skip"} and (
from_source is None or to_source is not None
):
@@ -222,6 +237,7 @@ def build_resolution_event(
"skip",
"needs_action",
"channel_switch",
+ "reasoning_efforts_override",
}:
raise ValueError("Invalid system event kind")
if model_id is None and (
diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.py
index 83ada0029..7d93be26d 100644
--- a/core/handlers/model_hub/migration.py
+++ b/core/handlers/model_hub/migration.py
@@ -10,7 +10,7 @@ import re
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
-from typing import Any, Awaitable, Callable, Literal, Optional, Protocol, cast
+from typing import Any, Awaitable, Callable, Literal, Mapping, Optional, Protocol, cast
from config.v2_config import (
ModelHubConfig,
@@ -18,11 +18,17 @@ from config.v2_config import (
ModelHubSourceConfig,
)
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
ObservationDiscovery,
SourceObservation,
)
from core.handlers.model_hub.events import contains_credential_material
-from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalog
+from core.handlers.model_hub.reasoning_tiers import resolve_reasoning_tiers
+from vibe.backend_model_catalog import (
+ backend_model_entries,
+ bundled_catalog_reasoning_efforts_by_model,
+ load_bundled_catalog,
+)
from vibe.claude_config import read_claude_oauth_signed_in, read_claude_settings_env
from vibe.codex_config import _load_auth, get_codex_config_paths, read_codex_auth_state
from vibe.opencode_config import (
@@ -84,10 +90,11 @@ class MigrationHost(Protocol):
self,
source: ModelHubSourceConfig,
manual_models: list[ModelHubModelConfig],
- discovered: list[str],
+ discovered: list[DiscoveredModel],
*,
allow_empty: bool = False,
- ) -> None: ...
+ catalog_efforts_by_model: Mapping[str, tuple[str, ...]] | None = None,
+ ) -> list[tuple[str, Literal["upstream", "catalog"]]]: ...
def _apply_source_placement(
self,
@@ -597,24 +604,29 @@ def _validated_source(
validate_base_url: Callable[[object], Optional[str]],
credential_ref: str | None = None,
masked_credential: str | None = None,
+ catalog_efforts_by_model: Mapping[str, tuple[str, ...]],
) -> ModelHubSourceConfig:
keep_native = item.proposed_action == "keep_native"
controlled = item.proposed_action == "controlled_import"
discovered_at = now.isoformat()
- models = (
- [
- {
- "id": model_id,
- "display_name": None,
- "origin": "discovered",
- "reasoning_efforts": [],
- "discovered_at": discovered_at,
- }
- for model_id in _native_model_ids(item.backend)
- ]
- if keep_native
- else []
- )
+ models = []
+ if keep_native:
+ for model_id in _native_model_ids(item.backend):
+ resolution = resolve_reasoning_tiers(
+ protocol=protocol,
+ model_id=model_id,
+ catalog_efforts_by_model=catalog_efforts_by_model,
+ )
+ models.append(
+ {
+ "id": model_id,
+ "display_name": None,
+ "origin": "discovered",
+ "reasoning_efforts": list(resolution.efforts),
+ "reasoning_efforts_source": resolution.source,
+ "discovered_at": discovered_at,
+ }
+ )
payload: dict[str, object] = {
"id": item.source_id,
"created_at": discovered_at,
@@ -656,6 +668,7 @@ def build_native_migration_source(
now=now,
protocol=item.protocol,
validate_base_url=validate_base_url,
+ catalog_efforts_by_model=bundled_catalog_reasoning_efforts_by_model(),
)
@@ -707,6 +720,7 @@ async def apply_native_migration(
provisioned: list[tuple[str, str]] = []
persisted = False
+ catalog_efforts_by_model = bundled_catalog_reasoning_efforts_by_model()
try:
for item in selected:
protocol = item.protocol
@@ -749,6 +763,7 @@ async def apply_native_migration(
validate_base_url=validate_base_url,
credential_ref=credential_ref,
masked_credential=mask_credential(item.secret),
+ catalog_efforts_by_model=catalog_efforts_by_model,
)
manual_models = [
ModelHubModelConfig.from_payload(
@@ -762,12 +777,23 @@ async def apply_native_migration(
)
for model in item.manual_models
]
+ for model in manual_models:
+ resolution = resolve_reasoning_tiers(
+ protocol=protocol,
+ model_id=model.id,
+ existing_efforts=model.reasoning_efforts,
+ existing_source=model.reasoning_efforts_source,
+ catalog_efforts_by_model=catalog_efforts_by_model,
+ )
+ model.reasoning_efforts = list(resolution.efforts)
+ model.reasoning_efforts_source = resolution.source
if observation.discovery is ObservationDiscovery.SUCCEEDED:
host._apply_discovered_models(
source,
manual_models,
- list(observation.model_ids),
+ list(observation.models),
allow_empty=True,
+ catalog_efforts_by_model=catalog_efforts_by_model,
)
else:
failed_payload = source.to_payload()
@@ -789,10 +815,12 @@ async def apply_native_migration(
raise MigrationConflictError from None
else:
try:
- source = build_native_migration_source(
+ source = _validated_source(
item,
now=host.now(),
+ protocol=item.protocol,
validate_base_url=validate_base_url,
+ catalog_efforts_by_model=catalog_efforts_by_model,
)
except (TypeError, ValueError):
raise MigrationConflictError from None
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index 58fab1793..6d21741e7 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -46,13 +46,23 @@ class AttemptIdentity:
source_id: str
resolved_model_id: str
channel: SupplyChannel
+ stripped_reasoning_efforts: tuple[str, ...] = ()
+ declared_reasoning_efforts: tuple[str, ...] = ()
def payload(self) -> dict:
- return {
+ payload = {
"source_id": self.source_id,
"configured_model_id": self.resolved_model_id,
"channel": self.channel,
}
+ if self.stripped_reasoning_efforts:
+ payload["stripped_reasoning_efforts"] = list(
+ self.stripped_reasoning_efforts
+ )
+ payload["declared_reasoning_efforts"] = list(
+ self.declared_reasoning_efforts
+ )
+ return payload
@dataclass(frozen=True)
@@ -664,6 +674,8 @@ class GatewayTurnTerminalizer:
resolved_model_id: str,
channel: SupplyChannel,
via_mapping: bool,
+ stripped_reasoning_efforts: tuple[str, ...] = (),
+ declared_reasoning_efforts: tuple[str, ...] = (),
) -> None:
self._attempt_started = True
self._registry.begin_attempt(
@@ -672,6 +684,8 @@ class GatewayTurnTerminalizer:
resolved_model_id=resolved_model_id,
channel=channel,
via_mapping=via_mapping,
+ stripped_reasoning_efforts=stripped_reasoning_efforts,
+ declared_reasoning_efforts=declared_reasoning_efforts,
request_id=self._request_id,
)
@@ -1426,6 +1440,8 @@ class TurnCorrelationRegistry:
resolved_model_id: str,
channel: SupplyChannel,
via_mapping: bool,
+ stripped_reasoning_efforts: tuple[str, ...] = (),
+ declared_reasoning_efforts: tuple[str, ...] = (),
request_id: str = TURN_REQUEST,
) -> None:
if turn_id is None:
@@ -1438,6 +1454,8 @@ class TurnCorrelationRegistry:
source_id=source_id,
resolved_model_id=resolved_model_id,
channel=channel,
+ stripped_reasoning_efforts=stripped_reasoning_efforts,
+ declared_reasoning_efforts=declared_reasoning_efforts,
)
def fail_native_attempt(
@@ -1643,7 +1661,7 @@ class TurnCorrelationRegistry:
self.store.put(
{
- "contract_version": 6,
+ "contract_version": 7,
"turn_id": normalized_turn_id,
"ts": ts or _utc_now_iso(),
"agent": trace.agent,
diff --git a/core/handlers/model_hub/reasoning_tiers.py b/core/handlers/model_hub/reasoning_tiers.py
new file mode 100644
index 000000000..a98b7d164
--- /dev/null
+++ b/core/handlers/model_hub/reasoning_tiers.py
@@ -0,0 +1,53 @@
+"""Single provenance ladder for Source-model reasoning effort declarations."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Literal, Mapping, Sequence
+
+from vibe.backend_model_catalog import (
+ PROTOCOL_REASONING_EFFORT_DEFAULTS,
+ bundled_catalog_reasoning_efforts_for_model,
+)
+
+ReasoningEffortsSource = Literal["upstream", "catalog", "user"] | None
+
+_UPSTREAM_REASONING_PARAMETERS = frozenset({"reasoning", "reasoning_effort"})
+
+
+@dataclass(frozen=True)
+class ReasoningTierResolution:
+ efforts: tuple[str, ...]
+ source: ReasoningEffortsSource
+
+
+def resolve_reasoning_tiers(
+ *,
+ protocol: str,
+ model_id: str,
+ supported_parameters: tuple[str, ...] | None = None,
+ existing_efforts: Sequence[str] = (),
+ existing_source: ReasoningEffortsSource = None,
+ catalog_efforts_by_model: Mapping[str, tuple[str, ...]] | None = None,
+) -> ReasoningTierResolution:
+ """Apply upstream, bundled-catalog, then user provenance in that order."""
+
+ if supported_parameters is not None and any(
+ parameter.strip().lower() in _UPSTREAM_REASONING_PARAMETERS
+ for parameter in supported_parameters
+ ):
+ defaults = PROTOCOL_REASONING_EFFORT_DEFAULTS.get(protocol)
+ if defaults is not None:
+ return ReasoningTierResolution(defaults, "upstream")
+
+ catalog_efforts = (
+ bundled_catalog_reasoning_efforts_for_model(model_id)
+ if catalog_efforts_by_model is None
+ else catalog_efforts_by_model.get(model_id)
+ )
+ if catalog_efforts is not None:
+ return ReasoningTierResolution(catalog_efforts, "catalog")
+
+ if existing_source == "user" and existing_efforts:
+ return ReasoningTierResolution(tuple(existing_efforts), "user")
+ return ReasoningTierResolution((), None)
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 3f9382964..a4279795b 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
+import hashlib
import json
import logging
import time
@@ -39,8 +40,10 @@ from core.agent_auth_service import BackendLoginInProgressError
from core.services.settings import default_config
from storage.db import get_cached_sqlite_engine
from storage.models import agent_sessions, messages
+from vibe.backend_model_catalog import bundled_catalog_reasoning_efforts_by_model
from .adapter import (
+ DiscoveredModel,
EngineAdapter,
EngineHealth,
EngineStatus,
@@ -73,6 +76,7 @@ from .events import (
EventReason,
build_resolution_event,
contains_credential_material,
+ redact_credential_material,
)
from .errors import ModelDiscoveryError
from .identifiers import STANDARD_OPENCODE_VENDOR_IDS, canonical_model_id
@@ -100,6 +104,7 @@ from .provenance import (
produce_turn_outcome,
)
from .request import ModelHubRequest
+from .reasoning_tiers import resolve_reasoning_tiers
from .stream_wire import ProtocolSSEState
from .resolver import (
BackendName,
@@ -116,10 +121,11 @@ from .resolver import (
from .revocations import CredentialRevocationJournal
from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, SourceIdentity, UsageWriter
-CONTRACT_VERSION = 6
-AGENT_CHAIN_CONTRACT_VERSION = 6
-PROBE_RESULT_CONTRACT_VERSION = 6
+CONTRACT_VERSION = 7
+AGENT_CHAIN_CONTRACT_VERSION = 7
+PROBE_RESULT_CONTRACT_VERSION = 7
_REORDER_ORDER_UNSET = object()
+_REASONING_EFFORT_TELEMETRY_MAX_BYTES = 256
# Settlement generations are minted per attempt start and live only in this
# runtime's ledger, which restarts with the process. Every generation this
# runtime mints is therefore strictly greater than this pre-attempt value, and
@@ -347,6 +353,56 @@ class HandleSettlement:
HandleTerminationOrigin = Literal["downstream_cancel", "upstream_terminal"]
+@dataclass(frozen=True)
+class ExactReasoningEffortRequest:
+ request: Mapping[str, Any]
+ stripped_efforts: tuple[str, ...] = ()
+ declared_efforts: tuple[str, ...] = ()
+
+
+def _bounded_reasoning_effort_telemetry(value: object) -> str:
+ """Redact and fold an untrusted effort value into bounded telemetry."""
+
+ if not isinstance(value, str):
+ if value is None:
+ return "<null>"
+ if isinstance(value, bool):
+ return "<bool>"
+ if isinstance(value, int):
+ return "<int>"
+ if isinstance(value, float):
+ return "<float>"
+ if isinstance(value, list):
+ return "<list>"
+ if isinstance(value, Mapping):
+ return "<dict>"
+ return "<non-string>"
+
+ redacted = redact_credential_material(value)
+ encoded = redacted.encode("utf-8")
+ if len(encoded) <= _REASONING_EFFORT_TELEMETRY_MAX_BYTES:
+ return redacted
+ digest = hashlib.sha256(encoded).hexdigest()
+ suffix = f"... [sha256:{digest}]"
+ preview_bytes = _REASONING_EFFORT_TELEMETRY_MAX_BYTES - len(
+ suffix.encode("utf-8")
+ )
+ preview = encoded[:preview_bytes].decode("utf-8", errors="ignore")
+ return f"{preview}{suffix}"
+
+
+def _bounded_declared_effort_telemetry(values: Iterable[str]) -> tuple[str, ...]:
+ redacted = tuple(redact_credential_material(value) for value in values)
+ payload = json.dumps(
+ redacted,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ if len(payload.encode("utf-8")) <= _REASONING_EFFORT_TELEMETRY_MAX_BYTES:
+ return redacted
+ return (_bounded_reasoning_effort_telemetry(payload),)
+
+
AttemptObserver = Callable[
[
str,
@@ -355,6 +411,8 @@ AttemptObserver = Callable[
bool,
Optional[RawCallOutcome],
Optional[ResolutionDecision],
+ tuple[str, ...],
+ tuple[str, ...],
],
None,
]
@@ -597,7 +655,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:
manager = EngineRuntimeManager()
return {
- "contract_version": 6,
+ "contract_version": 7,
"enabled": enabled,
"host_platform": status.host_platform or manager.host_platform(),
"manifest": manager.contract_manifest(),
@@ -1159,9 +1217,13 @@ class ModelHubService:
return False
return True
- async def _discover(self, source: ModelHubSourceConfig) -> list[str]:
+ async def _discover(self, source: ModelHubSourceConfig) -> list[DiscoveredModel]:
if not source.credential_ref:
- return [model.id for model in source.models if not model.retired]
+ return [
+ DiscoveredModel(id=model.id)
+ for model in source.models
+ if not model.retired
+ ]
return list(
await self._engine_call(
self.adapter.discover_models(
@@ -1198,6 +1260,17 @@ class ModelHubService:
"protocol": observation.protocol,
"discovery": observation.discovery.value,
"models": list(observation.model_ids),
+ "model_metadata": [
+ {
+ "id": model.id,
+ "supported_parameters": (
+ list(model.supported_parameters)
+ if model.supported_parameters is not None
+ else None
+ ),
+ }
+ for model in observation.models
+ ],
}
@staticmethod
@@ -1206,7 +1279,15 @@ class ModelHubService:
validated = validate_source_observation(observation)
except (TypeError, ValueError):
raise ModelHubError("discovery_failed", status=502)
- if any(contains_credential_material(model_id) for model_id in validated.model_ids):
+ if contains_credential_material(
+ [
+ {
+ "id": model.id,
+ "supported_parameters": model.supported_parameters,
+ }
+ for model in validated.models
+ ]
+ ):
raise ModelHubError("discovery_failed", status=502)
return validated
@@ -1231,7 +1312,7 @@ class ModelHubService:
authenticated=None,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
except EngineUnavailableError:
raise ModelHubError("engine_down", status=503) from None
@@ -1244,7 +1325,7 @@ class ModelHubService:
authenticated=None,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
validated = self._validate_observation(observation)
if (
@@ -1499,15 +1580,16 @@ class ModelHubService:
self,
source: ModelHubSourceConfig,
manual_models: list[ModelHubModelConfig],
- discovered: list[str],
+ discovered: list[DiscoveredModel],
*,
allow_empty: bool = False,
- ) -> None:
+ catalog_efforts_by_model: Mapping[str, tuple[str, ...]] | None = None,
+ ) -> list[tuple[str, Literal["upstream", "catalog"]]]:
# Admit the canonical form, not the text upstream happened to send: what
# is stored here is what resolution compares and what usage meters, and a
# listing that names one model twice under two spellings is a failed
# discovery, not two models.
- canonical = [canonical_model_id(model_id) for model_id in discovered]
+ canonical = [canonical_model_id(model.id) for model in discovered]
if (
(not allow_empty and not discovered and not manual_models)
or any(
@@ -1517,7 +1599,14 @@ class ModelHubService:
or len(set(canonical)) != len(canonical)
):
raise ModelHubError("discovery_failed", status=502)
- discovered = [model_id for model_id in canonical if model_id is not None]
+ canonical_models = [
+ DiscoveredModel(
+ id=model_id,
+ supported_parameters=model.supported_parameters,
+ )
+ for model, model_id in zip(discovered, canonical)
+ if model_id is not None
+ ]
discovered_at = self.now().isoformat()
manual_model_ids = {model.id for model in manual_models}
existing_by_id = {model.id: model for model in source.models}
@@ -1527,29 +1616,81 @@ class ModelHubService:
if model.provenance == "discovered" and model.retired
]
retired_model_ids = {model.id for model in retired_models}
+ discovered_by_id = {model.id: model for model in canonical_models}
+ overrides: list[tuple[str, Literal["upstream", "catalog"]]] = []
+ if catalog_efforts_by_model is None:
+ catalog_efforts_by_model = bundled_catalog_reasoning_efforts_by_model()
+
+ def apply_tiers(
+ model: ModelHubModelConfig,
+ metadata: DiscoveredModel | None,
+ ) -> None:
+ resolution = resolve_reasoning_tiers(
+ protocol=source.protocol,
+ model_id=model.id,
+ supported_parameters=(
+ metadata.supported_parameters if metadata is not None else None
+ ),
+ existing_efforts=model.reasoning_efforts,
+ existing_source=model.reasoning_efforts_source,
+ catalog_efforts_by_model=catalog_efforts_by_model,
+ )
+ if (
+ model.reasoning_efforts
+ and model.reasoning_efforts_source == "user"
+ and resolution.source in {"upstream", "catalog"}
+ ):
+ overrides.append((model.id, resolution.source))
+ model.reasoning_efforts = list(resolution.efforts)
+ model.reasoning_efforts_source = resolution.source
+
discovered_models = []
- for model_id in discovered:
+ for metadata in canonical_models:
+ model_id = metadata.id
if model_id in manual_model_ids or model_id in retired_model_ids:
continue
existing = existing_by_id.get(model_id)
- discovered_models.append(
- ModelHubModelConfig(
- id=model_id,
- provenance="discovered",
- reasoning_efforts=list(existing.reasoning_efforts) if existing else [],
- display_name=existing.display_name if existing else None,
- discovered_at=discovered_at,
- )
+ model = ModelHubModelConfig(
+ id=model_id,
+ provenance="discovered",
+ reasoning_efforts=list(existing.reasoning_efforts) if existing else [],
+ reasoning_efforts_source=(
+ existing.reasoning_efforts_source if existing else None
+ ),
+ display_name=existing.display_name if existing else None,
+ discovered_at=discovered_at,
)
+ apply_tiers(model, metadata)
+ discovered_models.append(model)
+
+ for model in (*retired_models, *manual_models):
+ apply_tiers(model, discovered_by_id.get(model.id))
source.models = discovered_models + retired_models + manual_models
source.last_discovered_at = discovered_at
+ return overrides
+
+ def _record_reasoning_tier_overrides(
+ self,
+ source: ModelHubSourceConfig,
+ overrides: Iterable[tuple[str, Literal["upstream", "catalog"]]],
+ ) -> None:
+ for model_id, managed_source in overrides:
+ self._record_event(
+ agent="system",
+ kind="reasoning_efforts_override",
+ model_id=model_id,
+ reason=f"{managed_source}_tiers",
+ from_source=source.id,
+ from_label=source.display_name,
+ now=self.now(),
+ )
async def _finalize_successful_discovery(
self,
previous: ModelHubConfig,
updated: ModelHubConfig,
source: ModelHubSourceConfig,
- discovered: list[str],
+ discovered: list[DiscoveredModel],
*,
force: bool,
confirmed_remove_hops: object,
@@ -1558,7 +1699,7 @@ class ModelHubService:
"""Apply one successful inventory observation and commit it atomically."""
manual = [model for model in source.models if model.provenance == "manual"]
- self._apply_discovered_models(
+ overrides = self._apply_discovered_models(
source,
manual,
discovered,
@@ -1574,6 +1715,7 @@ class ModelHubService:
confirmed_interruptions=confirmed_interruptions,
)
await self._commit_synced(previous, updated)
+ self._record_reasoning_tier_overrides(source, overrides)
return removed_hops, interrupted
async def _commit_new_source_locked(
@@ -1756,7 +1898,7 @@ class ModelHubService:
)
account_label: str | None = None
state = ModelHubSourceStateConfig(status="standby")
- discovered: list[str] | None
+ discovered: list[DiscoveredModel] | None
if channel == "hub":
rollback_credential_ref = cast(str, flow.credential_ref)
observation = await self._require_proven_observation(
@@ -1770,7 +1912,7 @@ class ModelHubService:
observation.protocol,
)
if observation.discovery is ObservationDiscovery.SUCCEEDED:
- discovered = list(observation.model_ids)
+ discovered = list(observation.models)
elif observation.discovery is ObservationDiscovery.FAILED:
discovered = None
state = ModelHubSourceStateConfig(
@@ -1805,7 +1947,10 @@ class ModelHubService:
detail_key="models.source.needs_action.oauth_expired",
)
)
- discovered = list(_native_model_ids(vendor))
+ discovered = [
+ DiscoveredModel(id=model_id)
+ for model_id in _native_model_ids(vendor)
+ ]
if channel == "native_cli" and not discovered:
raise ModelHubError("discovery_failed")
source_payload: dict[str, Any] = {
@@ -1837,6 +1982,20 @@ class ModelHubService:
discovered,
allow_empty=channel == "hub",
)
+ else:
+ catalog_efforts_by_model = (
+ bundled_catalog_reasoning_efforts_by_model()
+ )
+ for model in source.models:
+ resolution = resolve_reasoning_tiers(
+ protocol=source.protocol,
+ model_id=model.id,
+ existing_efforts=model.reasoning_efforts,
+ existing_source=model.reasoning_efforts_source,
+ catalog_efforts_by_model=catalog_efforts_by_model,
+ )
+ model.reasoning_efforts = list(resolution.efforts)
+ model.reasoning_efforts_source = resolution.source
try:
source = ModelHubSourceConfig.from_payload(source.to_payload())
except (TypeError, ValueError):
@@ -2053,7 +2212,10 @@ class ModelHubService:
manual = [
model for model in source.models if model.provenance == "manual"
]
- discovered = list(_native_model_ids(binding.vendor))
+ discovered = [
+ DiscoveredModel(id=model_id)
+ for model_id in _native_model_ids(binding.vendor)
+ ]
if not discovered:
source.models = [
model
@@ -2071,8 +2233,9 @@ class ModelHubService:
status=502,
data={"interrupted_pairs": interrupted_pairs},
)
- self._apply_discovered_models(source, manual, discovered)
+ overrides = self._apply_discovered_models(source, manual, discovered)
await self._commit_synced(previous, config)
+ self._record_reasoning_tier_overrides(source, overrides)
interrupted_pairs = self._would_interrupt(config)
self._complete_reauth_flow(
flow_id,
@@ -2111,7 +2274,7 @@ class ModelHubService:
]
source.credential_ref = replacement_ref
discovered = await self._discover(source)
- self._apply_discovered_models(source, manual, discovered)
+ overrides = self._apply_discovered_models(source, manual, discovered)
source.state = ModelHubSourceStateConfig(status="standby")
interrupted_pairs = self._would_interrupt(config)
if (
@@ -2122,6 +2285,7 @@ class ModelHubService:
old_revocation_recorded = True
await self._commit_synced(previous, config)
committed = True
+ self._record_reasoning_tier_overrides(source, overrides)
self._complete_reauth_flow(
flow_id,
binding,
@@ -2447,6 +2611,7 @@ class ModelHubService:
manual_models = [ModelHubModelConfig.from_payload(model) for model in models_payload]
if any(
model.provenance != "manual"
+ or model.reasoning_efforts_source not in {None, "user"}
# The same admission rule the manual-add surface applies. A source
# may be created with its models inline, so this is the other way a
# client-declared identifier enters config — and a client can still
@@ -2580,10 +2745,21 @@ class ModelHubService:
self._apply_discovered_models(
source,
manual_models,
- list(observation.model_ids),
+ list(observation.models),
allow_empty=True,
)
elif observation.discovery is ObservationDiscovery.FAILED:
+ catalog_efforts_by_model = bundled_catalog_reasoning_efforts_by_model()
+ for model in source.models:
+ resolution = resolve_reasoning_tiers(
+ protocol=source.protocol,
+ model_id=model.id,
+ existing_efforts=model.reasoning_efforts,
+ existing_source=model.reasoning_efforts_source,
+ catalog_efforts_by_model=catalog_efforts_by_model,
+ )
+ model.reasoning_efforts = list(resolution.efforts)
+ model.reasoning_efforts_source = resolution.source
source.state = ModelHubSourceStateConfig(
status="error",
detail_key="models.source.error.unclassified",
@@ -3917,12 +4093,41 @@ class ModelHubService:
{
**model.to_payload(),
"reasoning_efforts": value,
+ "reasoning_efforts_source": (
+ "user" if isinstance(value, list) and value else None
+ ),
}
)
except ValueError:
raise ModelHubError("mapping_target_unavailable") from None
return validated.reasoning_efforts
+ @staticmethod
+ def _raise_if_reasoning_tiers_managed(model: ModelHubModelConfig) -> None:
+ managed_source = model.reasoning_efforts_source
+ if managed_source not in {"upstream", "catalog"}:
+ return
+ raise ModelHubError(
+ "source_model_tiers_managed",
+ status=409,
+ detail=f"settings.models.sourceDetail.tiers.managed.{managed_source}",
+ data={"reasoning_efforts_source": managed_source},
+ )
+
+ @staticmethod
+ def _apply_reasoning_tier_ladder(
+ source: ModelHubSourceConfig,
+ model: ModelHubModelConfig,
+ ) -> None:
+ resolution = resolve_reasoning_tiers(
+ protocol=source.protocol,
+ model_id=model.id,
+ existing_efforts=model.reasoning_efforts,
+ existing_source=model.reasoning_efforts_source,
+ )
+ model.reasoning_efforts = list(resolution.efforts)
+ model.reasoning_efforts_source = resolution.source
+
async def add_custom_model(self, source_id: object, payload: dict) -> dict:
if not isinstance(payload, dict):
raise ModelHubError("source_not_found", status=404)
@@ -3951,15 +4156,24 @@ class ModelHubService:
model,
reasoning_efforts,
)
+ model.reasoning_efforts_source = (
+ "user" if model.reasoning_efforts else None
+ )
+ self._apply_reasoning_tier_ladder(source, model)
source.models.append(model)
elif existing.provenance == "discovered":
raise ModelHubError("source_model_managed_upstream", status=409)
else:
+ self._raise_if_reasoning_tiers_managed(existing)
existing.display_name = display_name
existing.reasoning_efforts = self._validated_reasoning_efforts(
existing,
reasoning_efforts,
)
+ existing.reasoning_efforts_source = (
+ "user" if existing.reasoning_efforts else None
+ )
+ self._apply_reasoning_tier_ladder(source, existing)
await self._commit_synced(previous, config)
return self._source_payload(source)
@@ -3980,10 +4194,14 @@ class ModelHubService:
model = next((item for item in source.models if item.id == model_id), None)
if model is None:
raise ModelHubError("mapping_target_unavailable", status=404)
+ self._raise_if_reasoning_tiers_managed(model)
model.reasoning_efforts = self._validated_reasoning_efforts(
model,
payload["reasoning_efforts"],
)
+ model.reasoning_efforts_source = (
+ "user" if model.reasoning_efforts else None
+ )
await self._commit_synced(previous, config)
return self._source_payload(source)
@@ -5527,6 +5745,8 @@ class ModelHubService:
False,
outcome,
decision,
+ (),
+ (),
)
if decision.action == "fallback" or (
decision.action == "surface"
@@ -5645,18 +5865,27 @@ class ModelHubService:
request: Mapping[str, Any],
source: ModelHubSourceConfig,
model_id: str,
- ) -> Mapping[str, Any]:
+ ) -> ExactReasoningEffortRequest:
model = next((item for item in source.models if item.id == model_id), None)
- supported = set(model.reasoning_efforts) if model is not None else set()
+ declared = tuple(model.reasoning_efforts) if model is not None else ()
+ supported = set(declared)
payload = dict(request)
changed = False
+ stripped: list[str] = []
+
+ def note_stripped(value: object) -> None:
+ safe_value = _bounded_reasoning_effort_telemetry(value)
+ if safe_value not in stripped:
+ stripped.append(safe_value)
+
direct = payload.get("reasoning_effort")
if "reasoning_effort" in payload and not (
isinstance(direct, str) and direct in supported
):
payload.pop("reasoning_effort")
changed = True
+ note_stripped(direct)
reasoning = payload.get("reasoning")
nested = reasoning.get("effort") if isinstance(reasoning, Mapping) else None
if (
@@ -5671,15 +5900,31 @@ class ModelHubService:
else:
payload.pop("reasoning")
changed = True
+ note_stripped(nested)
if not changed:
- return request
+ return ExactReasoningEffortRequest(request=request)
if isinstance(request, ModelHubRequest):
- return ModelHubRequest(
+ filtered_request: Mapping[str, Any] = ModelHubRequest(
payload,
protocol=request.protocol,
headers=request.headers,
)
- return payload
+ else:
+ filtered_request = payload
+ safe_declared = _bounded_declared_effort_telemetry(declared)
+ logger.info(
+ "Stripped undeclared Model Hub reasoning effort(s) %s for source %s "
+ "model %s; declared tiers: %s",
+ stripped,
+ source.id,
+ model_id,
+ list(safe_declared),
+ )
+ return ExactReasoningEffortRequest(
+ request=filtered_request,
+ stripped_efforts=tuple(stripped),
+ declared_efforts=safe_declared,
+ )
async def resolve(
self,
@@ -5766,11 +6011,12 @@ class ModelHubService:
raise AssertionError("runnable hop must have an exact identity")
if source.id in globally_blocked_source_ids:
continue
- exact_request = self._request_for_exact_reasoning_effort(
+ exact_reasoning_request = self._request_for_exact_reasoning_effort(
request,
source,
target_model,
)
+ exact_request = exact_reasoning_request.request
if source.supply_channel == "native_cli":
self._emit_switch(
agent=event_agent,
@@ -5800,6 +6046,8 @@ class ModelHubService:
False,
None,
None,
+ exact_reasoning_request.stripped_efforts,
+ exact_reasoning_request.declared_efforts,
)
handle, outcome, cancelled = await self._invoke(
source=source,
@@ -5894,6 +6142,8 @@ class ModelHubService:
False,
outcome,
decision,
+ (),
+ (),
)
if decision.action == "return":
self._emit_switch(
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index bec4232f9..4ed0403aa 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -689,6 +689,8 @@ class ModelHubTurnGateway:
via_mapping: bool,
outcome: Optional[RawCallOutcome],
decision,
+ stripped_reasoning_efforts: tuple[str, ...],
+ declared_reasoning_efforts: tuple[str, ...],
) -> None:
if outcome is None or decision is None:
terminalizer.begin_attempt(
@@ -696,6 +698,8 @@ class ModelHubTurnGateway:
resolved_model_id=resolved_model_id,
channel=channel,
via_mapping=via_mapping,
+ stripped_reasoning_efforts=stripped_reasoning_efforts,
+ declared_reasoning_efforts=declared_reasoning_efforts,
)
return
terminalizer.finish_attempt(
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 041a8c02b..115a3e4c6 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -1,12 +1,13 @@
# Model Hub contracts
-Status: **FINAL shape, implementation-gated. `contract_version` is 6 (2026-08-19 usage
-metering); 5 published the 2026-08-11 contract completion.**
+Status: **FINAL shape, implementation-gated. `contract_version` is 7 (2026-09-03
+reasoning-tier provenance); 6 published 2026-08-19 usage metering; 5 published the
+2026-08-11 contract completion.**
These files describe the terminal contract for Model Hub before first release. No bump
carries a data migration, compatibility reader, conversion transaction, or version
discriminator: Model Hub has not shipped, so republishing the shape converts nothing.
-`contract_version` is 6 wherever a versioned object exists. The owner-approved
+`contract_version` is 7 wherever a versioned object exists. The owner-approved
pre-release network correction removes the earlier persistent network/timeout cooldown
spelling without adding a compatibility path.
@@ -71,9 +72,12 @@ Contract prose points to those authorities and does not add branches.
across time, quota, and health changes. Live runnability and current execution
position may change; Route membership and order may not.
6. Every Source model id is unique within that Source. The final model item shape is
- `{id, origin, reasoning_efforts, retired?, display_name?, discovered_at?}`; effort
- lists are editable capability declarations, may be empty, and have no selected/default
- item. `retired: true` is a persistent discovered-model tombstone and never supplies.
+ `{id, origin, reasoning_efforts, reasoning_efforts_source, retired?, display_name?,
+ discovered_at?}`. The tier source is `upstream | catalog | user | null`; only `user`
+ and `null` declarations are editable. Older persisted rows without the field load as
+ `user` when their list is non-empty and `null` when it is empty. Effort lists have no
+ selected/default item. `retired: true` is a persistent discovered-model tombstone and
+ never supplies.
7. A backend has at most one `native_cli` Source. Additional accounts are Hub-held
Sources.
8. Direct mode and a Native hop are distinct. Direct bypasses Gateway for the backend;
@@ -96,7 +100,7 @@ comparison. A gate may not report success by comparing stale input with itself.
## Version closure
-`contract_version` 6 must coexist in all registered version locations on the same tested head:
+`contract_version` 7 must coexist in all registered version locations on the same tested head:
- `mirror-registry.json`
- `agent-chain.schema.json`
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index d16bdeb92..fa4a2b36a 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -1,4 +1,4 @@
-"""Model Hub EngineAdapter interface. FINAL CONTRACT v5 (2026-08-09).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v7 (2026-09-03).
This file is the canonical adapter boundary and must remain byte-identical to
``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:
@@ -121,6 +121,14 @@ class ObservationDiscovery(str, Enum):
NOT_ATTEMPTED = OBSERVATION_DISCOVERY_OUTCOMES[2]
+@dataclass(frozen=True)
+class DiscoveredModel:
+ """One model inventory row and the only upstream metadata v1 retains."""
+
+ id: str
+ supported_parameters: tuple[str, ...] | None = None
+
+
@dataclass(frozen=True)
class SourceObservation:
"""Response-backed result of an unsaved Source observation."""
@@ -130,7 +138,11 @@ class SourceObservation:
authenticated: bool | None
protocol: str | None
discovery: ObservationDiscovery
- model_ids: tuple[str, ...]
+ models: tuple[DiscoveredModel, ...]
+
+ @property
+ def model_ids(self) -> tuple[str, ...]:
+ return tuple(model.id for model in self.models)
@dataclass(frozen=True)
@@ -214,8 +226,23 @@ def validate_source_observation(observation: object) -> SourceObservation:
bool,
):
raise ValueError("invalid SourceObservation authentication")
- if not isinstance(observation.model_ids, tuple) or any(
- not isinstance(model_id, str) or not model_id for model_id in observation.model_ids
+ if not isinstance(observation.models, tuple) or any(
+ not isinstance(model, DiscoveredModel)
+ or not isinstance(model.id, str)
+ or not model.id
+ or (
+ model.supported_parameters is not None
+ and (
+ not isinstance(model.supported_parameters, tuple)
+ or any(
+ not isinstance(parameter, str) or not parameter
+ for parameter in model.supported_parameters
+ )
+ or len(set(model.supported_parameters))
+ != len(model.supported_parameters)
+ )
+ )
+ for model in observation.models
):
raise ValueError("invalid SourceObservation inventory")
if len(set(observation.model_ids)) != len(observation.model_ids):
@@ -241,7 +268,7 @@ def make_source_observation(
authenticated: bool | None,
protocol: str | None,
discovery: ObservationDiscovery,
- model_ids: Sequence[str],
+ models: Sequence[DiscoveredModel],
) -> SourceObservation:
"""Construct an adapter result through the terminal-product authority."""
@@ -252,7 +279,7 @@ def make_source_observation(
authenticated=authenticated,
protocol=protocol,
discovery=discovery,
- model_ids=tuple(model_ids),
+ models=tuple(models),
)
)
@@ -451,8 +478,8 @@ class EngineAdapter(Protocol):
protocol: str,
base_url: str | None,
credential_ref: str,
- ) -> Sequence[str]:
- """Refresh supplyable model ids for a saved Source using its stored protocol."""
+ ) -> Sequence[DiscoveredModel]:
+ """Refresh supplyable models for a saved Source using its stored protocol."""
...
async def observe_source(
diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.json
index 8b54df1b0..dddda5315 100644
--- a/docs/plans/model-hub-contracts/agent-chain.schema.json
+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json
@@ -7,7 +7,7 @@
"required": ["contract_version", "backend", "model_id", "chain", "current", "supply_state"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 6 },
+ "contract_version": { "const": 7 },
"backend": { "enum": ["claude", "codex", "opencode"] },
"model_id": { "type": "string" },
"current": {
@@ -161,7 +161,7 @@
],
"examples": [
{
- "contract_version": 6,
+ "contract_version": 7,
"backend": "claude",
"model_id": "claude-opus-4-6",
"chain": [{ "source_id": "src_claudepro1", "model_id": "claude-opus-4-6", "channel": "native_cli", "health": "cooldown", "runnable": false, "reason": null, "retry_at": "2026-07-29T04:00:00Z" }],
@@ -169,7 +169,7 @@
"supply_state": "waiting"
},
{
- "contract_version": 6,
+ "contract_version": 7,
"backend": "opencode",
"model_id": "custom/glm-5.2",
"chain": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2", "channel": "hub", "health": "backoff", "runnable": false, "reason": "models.source.backoff.connection_failed", "retry_at": "2026-08-11T11:55:08Z" }],
@@ -177,7 +177,7 @@
"supply_state": "waiting"
},
{
- "contract_version": 6,
+ "contract_version": 7,
"backend": "codex",
"model_id": "gpt-5.6",
"chain": [{ "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "channel": "native_cli", "health": "healthy", "runnable": false, "reason": "native_cli_unavailable", "retry_at": null }],
@@ -185,7 +185,7 @@
"supply_state": "interrupted"
},
{
- "contract_version": 6,
+ "contract_version": 7,
"backend": "codex",
"model_id": "gpt-5.6",
"chain": [{ "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "channel": "native_cli", "health": "backoff", "runnable": false, "reason": "native_cli_unavailable", "retry_at": "2026-08-11T11:55:08Z" }],
@@ -193,7 +193,7 @@
"supply_state": "interrupted"
},
{
- "contract_version": 6,
+ "contract_version": 7,
"backend": "claude",
"model_id": "claude-haiku-4-5",
"chain": [],
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 80d825e12..2fb287e37 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -139,7 +139,7 @@
"SuccessCore": {
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6}
+ "contract_version": {"const": 7}
}
},
"SourceListResponse": {
@@ -148,7 +148,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}
}
},
@@ -158,7 +158,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"observation": {"$ref": "model-hub/observation-result.schema.json"}
}
},
@@ -168,7 +168,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"source": {"$ref": "#/definitions/SourceApi"},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},
"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}
@@ -180,7 +180,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"source": {"$ref": "#/definitions/SourceApi"}
}
},
@@ -190,7 +190,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"source": {"$ref": "#/definitions/SourceApi"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -202,7 +202,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
}
@@ -213,7 +213,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}
}
},
@@ -223,7 +223,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"agent": {"$ref": "#/definitions/AgentSupplyApi"}
}
},
@@ -233,7 +233,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"agent": {
"type": "object",
"required": ["backend", "mode", "catalog_models"],
@@ -255,7 +255,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"matches": {
"type": "array",
"items": {
@@ -286,7 +286,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"chain": {"$ref": "model-hub/agent-chain.schema.json"}
}
},
@@ -296,7 +296,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}
}
},
@@ -306,7 +306,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"chain": {"$ref": "model-hub/agent-chain.schema.json"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -318,7 +318,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"probe": {"$ref": "model-hub/probe-result.schema.json"}
}
},
@@ -328,7 +328,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}
}
},
@@ -338,7 +338,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"usage": {"$ref": "model-hub/usage-summary.schema.json"}
}
},
@@ -348,7 +348,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -370,7 +370,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -393,7 +393,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -418,7 +418,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6}
+ "contract_version": {"const": 7}
}
},
"RuntimeApi": {
@@ -440,7 +440,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"scan": {"$ref": "model-hub/migration-scan.schema.json"}
}
},
@@ -450,7 +450,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"applied": {"type": "integer", "minimum": 0},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}
@@ -462,7 +462,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}
}
},
@@ -472,7 +472,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 6},
+ "contract_version": {"const": 7},
"runtime": {"$ref": "#/definitions/RuntimeApi"}
}
}
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index ab3033664..8159a4814 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -1,10 +1,10 @@
# Model Hub — REST API contract
-Status: **Normative, `contract_version` 6** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.
+Status: **Normative, `contract_version` 7** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.
-Success envelope: `{ok: true, contract_version: 6, ...}`.
+Success envelope: `{ok: true, contract_version: 7, ...}`.
Failure envelope:
-`{ok: false, contract_version: 6, error: <machine_code>, detail?: <i18n_key>}`.
+`{ok: false, contract_version: 7, error: <machine_code>, detail?: <i18n_key>}`.
`detail` is always a string. Structured error data lives in a named sibling.
Guarded mutation refusals specialize that envelope through
`guard-refusal.schema.json`; both report arrays are required and together form the plan
@@ -16,7 +16,7 @@ table. The contract guard requires the two endpoint sets to be identical, requir
exercised HTTP response for every registry entry, and validates that response against
the route's named schema.
-The shared envelope and every versioned nested contract carry `contract_version` 6, the
+The shared envelope and every versioned nested contract carry `contract_version` 7, the
terminal value. Model Hub has not shipped, so there is no internal contract migration or
compatibility path.
@@ -33,7 +33,7 @@ compatibility path.
| DELETE `/api/models/sources/<id>?force=<bool>` | `{would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{removed_hops, interrupted}` | A confirmed delete removes the Source from every backend Source order and Route chain in one transaction. A nonempty destructive plan commits only when the body exactly echoes the current refusal plan. |
| POST `/api/models/sources/<id>/refresh` | `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded Source-mutation envelope | The sole saved connectivity/discovery/recovery mutation. |
| POST `/api/models/sources/<source_id>/models` | `{model_id, display_name?, reasoning_efforts}` → `{source: Source}` | Creates one user-authored model entry. The Source identity comes only from the path. |
-| PATCH `/api/models/sources/<source_id>/models/<model_id>` | `{reasoning_efforts}` → `{source: Source}` | Replaces the complete capability list on either model origin without changing identity, origin, or Routes. |
+| PATCH `/api/models/sources/<source_id>/models/<model_id>` | `{reasoning_efforts}` → `{source: Source}` | Replaces the complete capability list only when `reasoning_efforts_source` is `user` or null, without changing identity, origin, or Routes. An `upstream` or `catalog` declaration returns HTTP 409 `source_model_tiers_managed` with its provenance in the `reasoning_efforts_source` sibling. |
| DELETE `/api/models/sources/<source_id>/models/<model_id>` | `{force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or Source-mutation success | Deletes a manual entry; for a discovered entry it persists `retired: true` without deleting the row. Both outcomes use the same exact-hop and supply guards. |
| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include server-authoritative `cli_present` and `named_agents`, the enabled named-Agent live projection. The default read returns the current presence snapshot; `?refresh_cli_presence=1` first refreshes deep npm-only discovery and returns the resulting snapshot. |
| GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |
@@ -57,7 +57,7 @@ compatibility path.
| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |
| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Each accepted import runs the same one-time matching and placement as Add Source; original files remain byte-identical. |
| GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |
-| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 6 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 7 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
| POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. |
| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent. Uses the existing mutation authentication and CSRF guards; status reads never start it. |
| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |
@@ -190,7 +190,33 @@ reachability, but proves neither protocol nor authentication. Consequently,
does not establish a persistable protocol. After ambiguous Auto detection, the client
must select one concrete protocol before retrying. Only `observed` attempts inventory discovery and
therefore reports `succeeded` or `failed`; every other terminal reports
-`not_attempted` with an empty model list.
+`not_attempted` with an empty model list and empty metadata list. On successful
+discovery, `models` remains the compatibility list of unique ids and `model_metadata`
+contains one record for each id in the same order. v1 retains only the OpenRouter-shape
+`supported_parameters` array. An absent or malformed member becomes null without losing
+the model id; an empty array remains an explicit valid value.
+
+## Source-model reasoning tier provenance
+
+Each Source model carries `reasoning_efforts_source`, the first applicable rung in this
+ordered ladder: recognizable live `supported_parameters` metadata (`upstream`), an exact
+row in the bundled backend catalog (`catalog`), a non-empty user declaration (`user`),
+or null with an empty undeclared list. Live metadata is recognizable only when a valid
+array contains `reasoning` or `reasoning_effort`; it applies the protocol-family default
+from the backend catalog module. Catalog backfill applies that model row's exact tier
+list verbatim. It never substitutes a family default or filters the row through the
+shared ordered vocabulary.
+
+Refresh re-applies the first two rungs and otherwise preserves user declarations. OAuth
+materialization and native-config import use the same ladder at creation time. A v7 API
+payload always includes the field, while the persisted-config loader accepts older rows
+that omit it: a non-empty list becomes `user` and an empty list becomes null. The first
+post-upgrade refresh performs any catalog backfill; there is no offline tier migration.
+
+Managed `upstream` and `catalog` declarations are read-only. User and null declarations
+remain editable, including free-form values. A successful refresh that replaces a
+non-empty user list with a managed declaration emits exactly one redacted
+`reasoning_efforts_override` event after commit.
## Identifier rules
@@ -460,7 +486,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:
```json
{
"ok": true,
- "contract_version": 6,
+ "contract_version": 7,
"source": {
"id": "src_anthkey01",
"kind": "api_key",
@@ -538,7 +564,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c
```json
{
"ok": false,
- "contract_version": 6,
+ "contract_version": 7,
"error": "source_last_supplier",
"would_remove_hops": [],
"would_interrupt": [
@@ -670,7 +696,7 @@ API-key success:
```json
{
"ok": true,
- "contract_version": 6,
+ "contract_version": 7,
"source": {
"id": "src_relay9c1x",
"kind": "api_key",
@@ -761,7 +787,7 @@ Status and submit return the same terminal shape:
```json
{
"ok": true,
- "contract_version": 6,
+ "contract_version": 7,
"flow": {
"flow_id": "oaf_claude01",
"client_nonce": "ofn_01j5w8z7p4n6q2rt",
@@ -821,9 +847,9 @@ a valid `interrupted` chain.
```json
{
"ok": true,
- "contract_version": 6,
+ "contract_version": 7,
"chain": {
- "contract_version": 6,
+ "contract_version": 7,
"backend": "codex",
"model_id": "gpt-5.6",
"chain": [
@@ -848,7 +874,7 @@ In Direct mode both chain and probe refuse with:
```json
{
"ok": false,
- "contract_version": 6,
+ "contract_version": 7,
"error": "direct_mode",
"detail": "models.hub.direct_mode"
}
@@ -862,9 +888,9 @@ A successful probe nests its result:
```json
{
"ok": true,
- "contract_version": 6,
+ "contract_version": 7,
"probe": {
- "contract_version": 6,
+ "contract_version": 7,
"backend": "claude",
"channel": "hub",
"reachable": false,
@@ -887,7 +913,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 6,
+ "contract_version": 7,
"backend": "codex",
"channel": "native_cli",
"reachable": true,
@@ -900,7 +926,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 6,
+ "contract_version": 7,
"backend": "codex",
"channel": "native_cli",
"reachable": false,
@@ -916,7 +942,7 @@ No candidate is an API error with a typed model-scoped state:
```json
{
"ok": false,
- "contract_version": 6,
+ "contract_version": 7,
"error": "probe_no_candidate",
"detail": "models.probe.no_candidate.waiting",
"supply": {
@@ -975,7 +1001,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 6,
+ "contract_version": 7,
"error": "provenance_unavailable",
"detail": "models.provenance.direct_mode"
}
@@ -984,7 +1010,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 6,
+ "contract_version": 7,
"error": "provenance_unavailable",
"detail": "models.provenance.attribution_ambiguous"
}
@@ -994,6 +1020,13 @@ An unknown `turn_id` returns `turn_not_found`. The server derives ambiguous abse
live from “known turn, no exact record”; it does not persist a placeholder and never
guesses which attempt belonged to the turn.
+When exact-match forwarding removes a requested reasoning effort, that exact attempted
+hop carries both `stripped_reasoning_efforts` and the declaration consulted in
+`declared_reasoning_efforts`. The paired fields appear only on the failed, served,
+terminal, or canceled attempt where a strip actually occurred; they never leak onto a
+fallback hop or another turn. The same redacted source/model, stripped effort, and
+declared-tier facts are written to the application logger without changing chat copy.
+
## Resolution events
Events are state/feed records, not recorded fan-out. `severity` is presentation
@@ -1005,6 +1038,11 @@ Model-scoped kinds require a string. `agent: system` is invalid on backend-scope
`supply_interrupted`. Source endpoints use canonical ids and are checked for existence
when emitted.
+`reasoning_efforts_override` is a source/model-scoped system event with info severity,
+`to_source: null`, and reason `upstream_tiers` or `catalog_tiers`. It records that a
+successful refresh replaced a non-empty user declaration; it contains neither the old
+tiers, new tiers, nor credential material.
+
## Usage metering
Usage is a report, never a control input. Nothing in resolution, admission, or
@@ -1101,9 +1139,14 @@ Minimum v5 set:
`source_model_in_route_chain`, `mode_switch_blocked`, `engine_down`,
`runtime_platform_unsupported`, `reauth_confirmation_required`,
`native_source_already_exists`, `native_login_in_progress`,
-`migration_item_conflict`, `turn_not_found`,
+`migration_item_conflict`, `source_model_tiers_managed`, `turn_not_found`,
`provenance_unavailable`, `probe_no_candidate`, `direct_mode`.
+`source_model_tiers_managed` is the HTTP 409 refusal for editing an `upstream` or
+`catalog` tier declaration. Its structured sibling is
+`{reasoning_efforts_source: "upstream" | "catalog"}` and its `detail` is the matching
+`settings.models.sourceDetail.tiers.managed.<provenance>` i18n key.
+
`native_source_already_exists` is an API-boundary refusal for native OAuth start;
its structured sibling is `{existing_source_id}` and the adapter is not invoked.
`native_login_in_progress` is a distinct transient `409` from the shared native-login
@@ -1157,13 +1200,16 @@ contract harness and API-boundary tests enforce:
| probe `source_id` names an existing source | probe assembler |
| non-null event endpoints name existing sources at emission time | event emitter |
| `channel_switch.from_source == channel_switch.to_source` | event emitter |
-| API AgentSupply includes `cli_present`, `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, policy-free `sources.order`, `supply_status`, `model_supply[].has_runnable_hop`, and `named_agents[].route_reason`; every Source includes persisted `last_discovered_at`, optional persisted `client_nonce`, derived `adopted_by`, and model retirement tombstones; source creation returns `added_to` and top-level `adopted_by` equal to `source.adopted_by`; saved refresh and discovered-model retirement use the guarded Source envelope | API payload test |
+| API AgentSupply includes `cli_present`, `selected_by_agent`, `selected_model_id`, `selected_model_explicit`, policy-free `sources.order`, `supply_status`, `model_supply[].has_runnable_hop`, and `named_agents[].route_reason`; every Source includes persisted `last_discovered_at`, optional persisted `client_nonce`, derived `adopted_by`, model retirement tombstones, and every model's `reasoning_efforts_source`; source creation returns `added_to` and top-level `adopted_by` equal to `source.adopted_by`; saved refresh and discovered-model retirement use the guarded Source envelope | API payload test |
| every OAuthFlow response includes `intent` | API payload test |
| Hub OAuth and native CLI `POST /sources/<id>/reauth` requests with missing or false `acknowledge_irreversible` return `reauth_confirmation_required` before the OAuth adapter is called; true acknowledgement is the only start path, while transactional API-key PUT is unaffected | API route negative/positive fixtures |
| OAuth start claims `(client_nonce, vendor, channel)` before provider work; a blocked first call plus concurrent same-tuple retry coalesces to one pending result and exactly one provider start; pending-start failure/task cancellation releases after cleanup; success atomically exposes one echoed-nonce flow; explicit cancellation retains that nonce-bearing flow as `cancelled` so a same-tuple retry starts no provider, while existing expiry releases it for exactly one fresh start; no-nonce cancellation forgets | OAuth registry totality, clocked expiry, API payload, and auth-setup closed-loop tests |
| every RuntimeDependency API payload includes server-derived `host_platform` and `status.error_key`; `installing` has exactly null `installed_version`, false `verified`, and null `listening`, with one positive and each-field contradiction fixtures; only supported `not_installed` starts a download, installed states are state-preserving no-ops, page reload preserves a live `installing` job, and service bootstrap reconciles an orphan before serving runtime endpoints | RuntimeDependency schema and API payload tests |
| Source create reserves `client_nonce` in process before work; the client reads Sources before any lost-response retry; fixtures cover `nonce.in_flight` (`source_create_in_progress`/no work), `nonce.released` (atomic reserve/exactly one fresh attempt), and `nonce.committed` (`source_nonce_conflict` followed by a list read that finds exactly one Source with that nonce), while AC-26 cleanup or process restart releases any live reservation and Source deletion releases its committed nonce; after restart or deletion and a list miss, same-nonce create is positively asserted as a fresh creation | config, API payload, cancellation/restart, Source-delete, and client retry tests |
-| Source observation rejects unregistered request/status evidence fields; clients consume only the contracted outcome, reachability, authentication, protocol, discovery, and models facts | observation schema and API payload tests |
+| Source observation rejects unregistered request/status evidence fields; clients consume only the contracted outcome, reachability, authentication, protocol, discovery, models, and parallel `model_metadata` facts; metadata ids and order exactly match `models`, malformed `supported_parameters` degrades to null without dropping the id, and an empty array remains distinct | observation schema, runtime parser, and API payload tests |
+| tier resolution chooses the first applicable `upstream > catalog > user > null` rung; upstream uses only valid OpenRouter-shape capability metadata and protocol defaults, catalog uses each exact row without filtering, OAuth/import reuse the same resolver, and older persisted rows infer `user` for non-empty tiers or null for empty tiers | catalog contract, ladder unit tests, config load fixture, and materialization tests |
+| model tier PATCH and add-model upsert refuse managed `upstream`/`catalog` rows with `source_model_tiers_managed` and an exact provenance sibling, while `user`/null rows remain editable; refresh emits one redacted override event only after a committed replacement of a non-empty user declaration | API mutation, refresh, and event tests |
+| a stripped effort and the exact hop declaration consulted appear as a pair only on the attempt where stripping occurred, in turn provenance and a redacted logger line | gateway/provenance unit and D10 e2e tests |
| network fixtures cover shaped/transport × `stream_started: false/true`, where the boundary is the first user-visible model-output byte: shaped results at either phase enter only their existing non-permanent Source classifier; unclassified pre-output connection failure creates bounded live backoff with no config write; only later output from that same Source clears its streak, while another Source's successful fallback does not; the API/read assembler emits a future deadline for a live overlay and normalizes an expired overlay before serialization; concurrent cooldown/needs-action/error/missing-Source/unsupported-model facts suppress the overlay and keep stronger projections, so waiting never hides a durable blocker; simultaneous native-process unavailability alone preserves backoff health/deadline while taking reason precedence and yielding interrupted; probe `connection_failed` requires the exact Hub/unreachable/null-latency shape | clocked table-driven resolver/API/event, AgentChain precedence, ProbeResult relation, and concurrent-transition tests |
| every `GuardRefusal` validates against `guard-refusal.schema.json` and has a nonempty current plan; fixtures cover every guard-decision row, including unforced refusal, exact echoed-plan confirmation, missing/different echo returning the new plan, and old-echo empty-plan ordinary success without a fabricated 409 | API payload and concurrent-mutation test |
| `PUT /sources/<id>/credential` success contains exactly the standard `{source, removed_hops, interrupted}` mutation tail; `{recovered, interrupted_pairs}` is absent there and remains owned only by terminal OAuth `intent: "reauth"` | contract negative fixture and API payload test |
diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.json
index b9478d1a5..5e399ba6e 100644
--- a/docs/plans/model-hub-contracts/guard-refusal.schema.json
+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json
@@ -60,7 +60,7 @@
],
"properties": {
"ok": { "const": false },
- "contract_version": { "const": 6 },
+ "contract_version": { "const": 7 },
"error": {
"enum": [
"source_last_supplier",
@@ -113,7 +113,7 @@
"examples": [
{
"ok": false,
- "contract_version": 6,
+ "contract_version": 7,
"error": "source_model_in_route_chain",
"would_remove_hops": [
{
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.json
index d9aafb207..f7772ba72 100644
--- a/docs/plans/model-hub-contracts/mirror-registry.json
+++ b/docs/plans/model-hub-contracts/mirror-registry.json
@@ -1,9 +1,31 @@
{
- "contract_version": 6,
+ "contract_version": 7,
"input_generation": {
"mode": "same_run_live_files",
"external_snapshot": "content_fingerprint_required"
},
+ "contract_version_closure": {
+ "persisted_schema_version_floors": {
+ "turn-provenance.schema.json": 5
+ },
+ "literal_globs": [
+ "core/handlers/model_hub/service.py",
+ "core/handlers/model_hub/provenance.py",
+ "tests/test_model_hub*.py",
+ "tests/e2e/test_model_hub*.py",
+ "ui/src/components/settings/models/types.ts",
+ "ui/src/components/settings/models/*.test.*"
+ ],
+ "required_literal_files": [
+ "core/handlers/model_hub/service.py",
+ "core/handlers/model_hub/provenance.py",
+ "ui/src/components/settings/models/types.ts"
+ ],
+ "contract_headers": [
+ "core/handlers/model_hub/adapter.py",
+ "docs/plans/model-hub-contracts/adapter-interface.py"
+ ]
+ },
"authority_table_discovery": {
"files": ["docs/plans/model-hub.md"]
},
@@ -139,7 +161,9 @@
},
"exclusions": [
"recovery",
- "manual"
+ "manual",
+ "upstream_tiers",
+ "catalog_tiers"
],
"exclusion_sets": [
{
@@ -739,6 +763,24 @@
}
]
},
+ {
+ "id": "D23",
+ "domain": "reasoning tier provenance",
+ "authority": {
+ "kind": "schema_vocabulary",
+ "schema": "source.schema.json",
+ "paths": ["/properties/models/items/properties/reasoning_efforts_source"],
+ "exclude": [null]
+ },
+ "consumers": [
+ {
+ "kind": "python_literal_annotation",
+ "file": "config/v2_config.py",
+ "class": "ModelHubModelConfig",
+ "field": "reasoning_efforts_source"
+ }
+ ]
+ },
{
"id": "D22",
"domain": "OAuth terminal response and materialization-error totality",
diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.json
index 2e7130935..d7ea834d7 100644
--- a/docs/plans/model-hub-contracts/observation-result.schema.json
+++ b/docs/plans/model-hub-contracts/observation-result.schema.json
@@ -11,11 +11,12 @@
"authenticated",
"protocol",
"discovery",
- "models"
+ "models",
+ "model_metadata"
],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 6 },
+ "contract_version": { "const": 7 },
"outcome": {
"enum": [
"observed",
@@ -37,6 +38,23 @@
"type": "array",
"items": { "type": "string", "minLength": 1 },
"uniqueItems": true
+ },
+ "model_metadata": {
+ "type": "array",
+ "description": "Per-model discovery records in models order. v1 retains only the OpenRouter-shape supported_parameters member; null means absent or malformed upstream metadata, while an empty array is a valid explicit declaration that carries no recognized reasoning signal.",
+ "items": {
+ "type": "object",
+ "required": ["id", "supported_parameters"],
+ "additionalProperties": false,
+ "properties": {
+ "id": { "type": "string", "minLength": 1 },
+ "supported_parameters": {
+ "type": ["array", "null"],
+ "items": { "type": "string", "minLength": 1 },
+ "uniqueItems": true
+ }
+ }
+ }
}
},
"allOf": [
@@ -59,7 +77,8 @@
"authenticated": { "enum": ["authenticated", "unknown"] },
"protocol": { "const": null },
"discovery": { "const": "not_attempted" },
- "models": { "maxItems": 0 }
+ "models": { "maxItems": 0 },
+ "model_metadata": { "maxItems": 0 }
}
}
},
@@ -71,7 +90,8 @@
"authenticated": { "const": "unknown" },
"protocol": { "const": null },
"discovery": { "const": "not_attempted" },
- "models": { "maxItems": 0 }
+ "models": { "maxItems": 0 },
+ "model_metadata": { "maxItems": 0 }
}
}
},
@@ -83,7 +103,8 @@
"authenticated": { "const": "rejected" },
"protocol": { "const": null },
"discovery": { "const": "not_attempted" },
- "models": { "maxItems": 0 }
+ "models": { "maxItems": 0 },
+ "model_metadata": { "maxItems": 0 }
}
}
},
@@ -95,7 +116,8 @@
"authenticated": { "const": "unknown" },
"protocol": { "const": null },
"discovery": { "const": "not_attempted" },
- "models": { "maxItems": 0 }
+ "models": { "maxItems": 0 },
+ "model_metadata": { "maxItems": 0 }
}
}
},
@@ -107,13 +129,19 @@
"authenticated": { "const": "unknown" },
"protocol": { "const": null },
"discovery": { "const": "not_attempted" },
- "models": { "maxItems": 0 }
+ "models": { "maxItems": 0 },
+ "model_metadata": { "maxItems": 0 }
}
}
},
{
"if": { "properties": { "discovery": { "const": "failed" } }, "required": ["discovery"] },
- "then": { "properties": { "models": { "maxItems": 0 } } }
+ "then": {
+ "properties": {
+ "models": { "maxItems": 0 },
+ "model_metadata": { "maxItems": 0 }
+ }
+ }
},
{
"if": { "properties": { "protocol": { "const": null } }, "required": ["protocol"] },
@@ -122,58 +150,69 @@
],
"examples": [
{
- "contract_version": 6,
+ "contract_version": 7,
"outcome": "observed",
"reachable": true,
"authenticated": "authenticated",
"protocol": "openai_chat",
"discovery": "succeeded",
- "models": ["gpt-5.6"]
+ "models": ["gpt-5.6"],
+ "model_metadata": [
+ {
+ "id": "gpt-5.6",
+ "supported_parameters": ["reasoning"]
+ }
+ ]
},
{
- "contract_version": 6,
+ "contract_version": 7,
"outcome": "authentication_failed",
"reachable": true,
"authenticated": "rejected",
"protocol": null,
"discovery": "not_attempted",
- "models": []
+ "models": [],
+ "model_metadata": []
},
{
- "contract_version": 6,
+ "contract_version": 7,
"outcome": "ambiguous",
"reachable": true,
"authenticated": "unknown",
"protocol": null,
"discovery": "not_attempted",
- "models": []
+ "models": [],
+ "model_metadata": []
},
{
- "contract_version": 6,
+ "contract_version": 7,
"outcome": "unreachable",
"reachable": false,
"authenticated": "unknown",
"protocol": null,
"discovery": "not_attempted",
- "models": []
+ "models": [],
+ "model_metadata": []
},
{
- "contract_version": 6,
+ "contract_version": 7,
"outcome": "adapter_error",
"reachable": null,
"authenticated": "unknown",
"protocol": null,
"discovery": "not_attempted",
- "models": []
+ "models": [],
+ "model_metadata": []
},
{
- "contract_version": 6,
+ "contract_version": 7,
"outcome": "timeout",
"reachable": null,
"authenticated": "unknown",
"protocol": null,
"discovery": "not_attempted",
- "models": []
+ "models": [],
+ "model_metadata": []
}
]
}
diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.json
index 706a06219..4caad6988 100644
--- a/docs/plans/model-hub-contracts/probe-result.schema.json
+++ b/docs/plans/model-hub-contracts/probe-result.schema.json
@@ -7,7 +7,7 @@
"required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "error"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 6 },
+ "contract_version": { "const": 7 },
"backend": { "enum": ["claude", "codex", "opencode"] },
"channel": { "enum": ["hub", "native_cli"] },
"reachable": { "type": "boolean" },
@@ -62,10 +62,10 @@
}
],
"examples": [
- { "contract_version": 6, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
- { "contract_version": 6, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },
- { "contract_version": 6, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },
- { "contract_version": 6, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
- { "contract_version": 6, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }
+ { "contract_version": 7, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
+ { "contract_version": 7, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },
+ { "contract_version": 7, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },
+ { "contract_version": 7, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
+ { "contract_version": 7, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }
]
}
diff --git a/docs/plans/model-hub-contracts/resolution-event.schema.json b/docs/plans/model-hub-contracts/resolution-event.schema.json
index 6f7ac7482..cd2ae4e77 100644
--- a/docs/plans/model-hub-contracts/resolution-event.schema.json
+++ b/docs/plans/model-hub-contracts/resolution-event.schema.json
@@ -21,7 +21,8 @@
"skip",
"channel_switch",
"needs_action",
- "supply_interrupted"
+ "supply_interrupted",
+ "reasoning_efforts_override"
]
},
"model_id": {
@@ -46,6 +47,8 @@
"network",
"recovery",
"manual",
+ "upstream_tiers",
+ "catalog_tiers",
"credential_expired",
"credential_revoked",
"balance_exhausted",
@@ -154,7 +157,8 @@
"cooldown",
"recover",
"skip",
- "channel_switch"
+ "channel_switch",
+ "reasoning_efforts_override"
]
}
},
@@ -185,6 +189,35 @@
}
}
},
+ {
+ "$comment": "A refresh that replaces a non-empty user declaration with a managed rung records one source/model-scoped informational event after commit.",
+ "if": {
+ "properties": { "kind": { "const": "reasoning_efforts_override" } },
+ "required": ["kind"]
+ },
+ "then": {
+ "required": ["agent", "model_id", "from_source", "to_source", "reason", "severity"],
+ "properties": {
+ "agent": { "const": "system" },
+ "model_id": { "type": "string" },
+ "from_source": { "type": "string" },
+ "to_source": { "type": "null" },
+ "reason": { "enum": ["upstream_tiers", "catalog_tiers"] },
+ "severity": { "const": "info" }
+ }
+ }
+ },
+ {
+ "if": {
+ "properties": {
+ "reason": { "enum": ["upstream_tiers", "catalog_tiers"] }
+ },
+ "required": ["reason"]
+ },
+ "then": {
+ "properties": { "kind": { "const": "reasoning_efforts_override" } }
+ }
+ },
{
"if": {
"properties": { "kind": { "const": "switch" } },
@@ -253,7 +286,8 @@
"recover",
"skip",
"needs_action",
- "channel_switch"
+ "channel_switch",
+ "reasoning_efforts_override"
]
}
}
@@ -274,7 +308,8 @@
"recover",
"skip",
"needs_action",
- "channel_switch"
+ "channel_switch",
+ "reasoning_efforts_override"
]
}
}
@@ -309,6 +344,20 @@
"severity": "action_required",
"human_zh": "Relay 余额不足,需要处理",
"human_en": "Relay balance is exhausted and needs attention"
+ },
+ {
+ "id": "evt_20260903c",
+ "ts": "2026-09-03T06:32:00Z",
+ "agent": "system",
+ "kind": "reasoning_efforts_override",
+ "model_id": "gpt-5.6-sol",
+ "from_source": "src_relay9c1x",
+ "to_source": null,
+ "reason": "catalog_tiers",
+ "billing_note": null,
+ "severity": "info",
+ "human_zh": "Relay:gpt-5.6-sol 的推理强度现按 Avibe 内置模型目录管理",
+ "human_en": "Relay: gpt-5.6-sol reasoning tiers now follow Avibe's built-in model catalog"
}
]
}
diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
index 7c7b90289..7ff37b9c4 100644
--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json
+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
@@ -7,7 +7,7 @@
"required": ["contract_version", "manifest", "status"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 6 },
+ "contract_version": { "const": 7 },
"enabled": {
"type": "boolean",
"description": "Persisted user intent for the managed gateway. Missing on older payloads means clients must fall back to observed health."
@@ -131,7 +131,7 @@
},
"examples": [
{
- "contract_version": 6,
+ "contract_version": 7,
"host_platform": "darwin-arm64",
"manifest": {
"name": "cliproxyapi",
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
index 968f26f7c..638ee9f6d 100644
--- a/docs/plans/model-hub-contracts/source.schema.json
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -293,7 +293,8 @@
"required": [
"id",
"origin",
- "reasoning_efforts"
+ "reasoning_efforts",
+ "reasoning_efforts_source"
],
"additionalProperties": false,
"allOf": [
@@ -339,6 +340,49 @@
}
}
}
+ },
+ {
+ "$comment": "A null tier source is the explicit no-declaration state and therefore carries no tiers.",
+ "if": {
+ "properties": {
+ "reasoning_efforts_source": {
+ "type": "null"
+ }
+ },
+ "required": [
+ "reasoning_efforts_source"
+ ]
+ },
+ "then": {
+ "properties": {
+ "reasoning_efforts": {
+ "maxItems": 0
+ }
+ }
+ }
+ },
+ {
+ "$comment": "Live upstream capability signals and user declarations always resolve to at least one tier. Catalog is intentionally absent from this condition because an exact catalog row may explicitly declare an empty list.",
+ "if": {
+ "properties": {
+ "reasoning_efforts_source": {
+ "enum": [
+ "upstream",
+ "user"
+ ]
+ }
+ },
+ "required": [
+ "reasoning_efforts_source"
+ ]
+ },
+ "then": {
+ "properties": {
+ "reasoning_efforts": {
+ "minItems": 1
+ }
+ }
+ }
}
],
"properties": {
@@ -361,10 +405,23 @@
},
"reasoning_efforts": {
"type": "array",
- "description": "Declared reasoning-effort capability values for this exact upstream model. Editable for discovered and manual entries; may be empty and has no selected or default item.",
+ "description": "Declared reasoning-effort capability values for this exact upstream model. Upstream and catalog declarations are read-only; user declarations are editable. The list may be empty and has no selected or default item.",
"items": { "type": "string", "minLength": 1 },
"uniqueItems": true
},
+ "reasoning_efforts_source": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "enum": [
+ "upstream",
+ "catalog",
+ "user",
+ null
+ ],
+ "description": "First applicable provenance rung for reasoning_efforts. upstream is live supported_parameters metadata; catalog is the exact bundled model row; user is a typed declaration; null accompanies an empty undeclared list. Older persisted shapes without this field are interpreted by the config loader as user for a non-empty list and null for an empty list."
+ },
"retired": {
"type": "boolean",
"default": false,
@@ -541,6 +598,7 @@
"display_name": "Opus 4.6",
"origin": "discovered",
"reasoning_efforts": [],
+ "reasoning_efforts_source": null,
"discovered_at": "2026-07-23T03:00:00Z"
}
],
@@ -574,6 +632,7 @@
"display_name": "GLM 5.2 Air",
"origin": "manual",
"reasoning_efforts": [],
+ "reasoning_efforts_source": null,
"discovered_at": null
}
],
diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.json
index a352d4e46..3da89187b 100644
--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json
+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json
@@ -4,6 +4,21 @@
"title": "TurnProvenance",
"description": "Persisted debug record for one exactly attributed Gateway turn. It records exact configured Source/model attempts in stored order and one terminal outcome. No route-policy or runtime-mapping discriminator exists; ambiguous attempts produce no record.",
"type": "object",
+ "definitions": {
+ "strippedReasoningEfforts": {
+ "type": "array",
+ "minItems": 1,
+ "uniqueItems": true,
+ "items": { "type": "string" },
+ "description": "Effort values removed from this exact attempt because they were absent from the hop's declared tiers. String values are preserved exactly, including an empty string; invalid non-string values use fixed type markers. Present only when a strip occurred."
+ },
+ "declaredReasoningEfforts": {
+ "type": "array",
+ "uniqueItems": true,
+ "items": { "type": "string", "minLength": 1 },
+ "description": "The exact hop tier declaration consulted when stripped_reasoning_efforts was produced."
+ }
+ },
"required": [
"contract_version",
"turn_id",
@@ -21,7 +36,7 @@
"additionalProperties": false,
"properties": {
"contract_version": {
- "enum": [5, 6],
+ "enum": [5, 6, 7],
"$comment": "The only versioned object that is written to disk instead of exchanged inside one request, so its released values are a set rather than a constant. A record a v5 build persisted keeps validating -- tests/fixtures/model_hub/released_v5_permission_denied.json is the evidence -- while new records carry the terminal value, which is the last member. Every other versioned object is an in-process envelope and stays pinned to that value alone.",
"description": "Generation that wrote this record. Nothing branches on it: readers accept every released value and the shape is identical across them."
},
@@ -71,6 +86,8 @@
},
"configured_model_id": { "type": "string" },
"channel": { "enum": ["native_cli", "hub"] },
+ "stripped_reasoning_efforts": { "$ref": "#/definitions/strippedReasoningEfforts" },
+ "declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" },
"reason": {
"enum": [
"quota_exhausted",
@@ -85,6 +102,10 @@
],
"description": "The attempt-failure partition of ResolutionEvent.reason. The mirror registry enforces totality."
}
+ },
+ "dependencies": {
+ "stripped_reasoning_efforts": ["declared_reasoning_efforts"],
+ "declared_reasoning_efforts": ["stripped_reasoning_efforts"]
}
}
},
@@ -99,7 +120,13 @@
"pattern": "^src_[a-z0-9]{8,}$"
},
"configured_model_id": { "type": "string" },
- "channel": { "enum": ["native_cli", "hub"] }
+ "channel": { "enum": ["native_cli", "hub"] },
+ "stripped_reasoning_efforts": { "$ref": "#/definitions/strippedReasoningEfforts" },
+ "declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" }
+ },
+ "dependencies": {
+ "stripped_reasoning_efforts": ["declared_reasoning_efforts"],
+ "declared_reasoning_efforts": ["stripped_reasoning_efforts"]
}
},
"terminal_error": {
@@ -122,6 +149,8 @@
},
"configured_model_id": { "type": ["string", "null"] },
"channel": { "enum": ["native_cli", "hub", null] },
+ "stripped_reasoning_efforts": { "$ref": "#/definitions/strippedReasoningEfforts" },
+ "declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" },
"reason": {
"enum": [
"invalid_parameter",
@@ -133,6 +162,10 @@
},
"stream_started": { "type": "boolean" }
},
+ "dependencies": {
+ "stripped_reasoning_efforts": ["declared_reasoning_efforts"],
+ "declared_reasoning_efforts": ["stripped_reasoning_efforts"]
+ },
"allOf": [
{
"if": {
@@ -177,7 +210,13 @@
"pattern": "^src_[a-z0-9]{8,}$"
},
"configured_model_id": { "type": "string" },
- "channel": { "enum": ["native_cli", "hub"] }
+ "channel": { "enum": ["native_cli", "hub"] },
+ "stripped_reasoning_efforts": { "$ref": "#/definitions/strippedReasoningEfforts" },
+ "declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" }
+ },
+ "dependencies": {
+ "stripped_reasoning_efforts": ["declared_reasoning_efforts"],
+ "declared_reasoning_efforts": ["stripped_reasoning_efforts"]
}
},
"model_supply_state": {
@@ -320,7 +359,7 @@
],
"examples": [
{
- "contract_version": 6,
+ "contract_version": 7,
"turn_id": "turn_01k9x2m4",
"ts": "2026-07-29T06:32:11Z",
"agent": "claude",
@@ -345,7 +384,7 @@
"blockers": []
},
{
- "contract_version": 6,
+ "contract_version": 7,
"turn_id": "turn_01k9x33p",
"ts": "2026-07-29T06:41:02Z",
"agent": "opencode",
@@ -366,7 +405,7 @@
"blockers": []
},
{
- "contract_version": 6,
+ "contract_version": 7,
"turn_id": "turn_01k9x3zq",
"ts": "2026-07-29T06:48:20Z",
"agent": "codex",
@@ -386,7 +425,7 @@
]
},
{
- "contract_version": 6,
+ "contract_version": 7,
"turn_id": "turn_01k9x4b7",
"ts": "2026-07-29T07:02:44Z",
"agent": "claude",
@@ -406,7 +445,7 @@
"blockers": []
},
{
- "contract_version": 6,
+ "contract_version": 7,
"turn_id": "turn_01k9x5ca",
"ts": "2026-07-29T07:08:00Z",
"agent": "codex",
diff --git a/docs/plans/model-hub-e2e-test-plan.md b/docs/plans/model-hub-e2e-test-plan.md
index a76f57f15..4ab0a9f56 100644
--- a/docs/plans/model-hub-e2e-test-plan.md
+++ b/docs/plans/model-hub-e2e-test-plan.md
@@ -6,7 +6,7 @@ Companion inventories (kept in session, summarized here): capability list C1–C
## 1. Goals and ground rules
1. Exercise the **shipped surface end to end** over real HTTP: browser-visible API (`/api/models/*`) and the per-turn gateway, against a **mock upstream provider**, never real vendor credentials.
-2. Assert **current behavior as baseline** where the owner has ruled (cross-vendor fidelity ruling 2026-08-08; "user owns the order" contract in `docs/plans/model-hub.md` §4.2), and mark scenarios **fix-first** or **expected-fail** where the survey found unintended drift (see §5 open decisions).
+2. Assert **current behavior as baseline** where the owner has ruled (cross-vendor fidelity ruling 2026-08-08; "user owns the order" contract in `docs/plans/model-hub.md` §4.2), and mark scenarios **fix-first** or **expected-fail** where the survey found unintended drift (see §5 decision ledger).
3. Every scenario names the feature ids (C#) it covers and the evidence layer it lives in: `e2e-auto` (this suite), `unit/contract` (existing), `manual` (Incus regression).
Out of scope (documented, not dropped silently):
@@ -40,16 +40,16 @@ Out of scope (documented, not dropped silently):
### B. API-key sources (C16–C29)
| ID | Steps | Expect | Status |
|---|---|---|---|
-| B1 | observe against mock for each protocol, `protocol:'auto'` | correct protocol chosen by response shape; observation payload contract v6 | assert |
+| B1 | observe against mock for each protocol, `protocol:'auto'` | correct protocol chosen by response shape; observation payload contract v7 | assert |
| B2 | manual protocol ≠ actual | create refused with matching proof error | assert |
-| B3 | pull models (mock returns `display_name`, `context_length`, `pricing`) | persisted model has only the 6 schema fields; `display_name:null`, `reasoning_efforts:[]` — documents the drop, not a pass/fail of intent | assert-current |
+| B3 | pull models (mock returns `display_name`, `context_length`, `pricing`, `supported_parameters`) | unrelated metadata is dropped; `supported_parameters` is retained in observation and the provenance ladder applies protocol-default tiers | assert |
| B4 | discovery fails | 422 `inventory_unavailable` unless `accept_unavailable_inventory:true`; then source commits with `state.status=error` | assert |
| B5 | replay create with same `client_nonce` | idempotent, no duplicate source | assert |
| B6 | replace key happy + rollback; rename; patch base URL | C22/C23 contracts | assert |
| B7 | delete source in a chain → guard 409 → echo plan → force | hop removed, impact report lists interrupted agents; malformed echo rejected | assert |
| B8 | force transport asymmetry (`?force=` vs body) | document current split (B6 issue); decide normalization | baseline |
| B9 | refetch after upstream inventory change | added/removed diff; **`discovered_at` preserved for pre-existing models** (currently overwritten — fix-first, see B-list) | fix-first |
-| B10 | add/edit/delete custom model; edit tiers | `source_model_managed_upstream` for discovered rows; free-text tiers accepted | assert |
+| B10 | inspect catalog-managed tiers; edit user/null tiers; reload a v6 row and refresh | catalog edits return 409 `source_model_tiers_managed` with exact provenance; user tiers remain editable; refresh restores catalog truth and emits one redacted override event | assert |
| B11 | trigger each of: `mapping_target_unavailable`, `runtime_in_use`, `source_nonce_conflict`, `reauth_confirmation_required`, `turn_not_found` | UI renders human copy, never the raw `modelHub.errors.*` string (B1 — fix-first; baseline expected-fail) | fix-first |
### C. OAuth lifecycle (C30–C40, partial by §1)
@@ -72,7 +72,7 @@ Out of scope (documented, not dropped silently):
| D7 | stream interrupt after first output | terminal frame injected per protocol; **no replay/failover**; source still settles; next turn resolves hop1 (takeover pill visible) | assert |
| D8 | cooldown `retry_at` elapses | next resolve recovers source, chain returns to hop0, `recover` event | assert |
| D9 | all hops failing | 503 `mapping_target_unavailable` + waiting copy with retry_at | assert |
-| D10 | chat selects effort `high`; hop model tiers `[]` | upstream capture shows **no** `reasoning_effort` key (silent strip by design); UI note visible | assert-current |
+| D10 | chat selects effort `high`; fallback hop declares tiers `[]` | upstream capture strips effort only for that hop; the exact served attempt records the stripped value and declared tiers in turn provenance | assert |
| D11 | `POST /{backend}/v1/messages/count_tokens` | currently 404 `not_found_error` (D-2 decision: fix or document impact on Claude Code auto-compact) | baseline |
| D12 | env/catalog injection for claude/codex/opencode | `ANTHROPIC_BASE_URL/TOKEN` only for claude; codex catalog neutralized 4 keys; opencode overlay model projection shape | assert |
| D13 | member role matrix | member can PUT chains/PATCH mode; cannot create/delete source, start runtime, read usage (B15) — assert the dead-ends are at least *visible* errors, not silent UI | assert |
@@ -109,12 +109,15 @@ Out of scope (documented, not dropped silently):
Unit/contract suites already cover: config validation, guard structure, classification tables, oauth registry, usage ledger, runtime injection. E2E must **not** duplicate them; it owns the seams those can't see: double-observe cost, cooldown-vs-next-turn timing, UI copy on live errors, guard echo round-trip, engine config conservation, member-role dead-ends.
-## 5. Open decisions (owner)
+## 5. Owner decision ledger
- **D-1 subscription-first placement.** Restore "subscription before API key" at placement time (surgical change in `_apply_source_placement`, reuse dead `recommended_source_order`), incl. one-time re-sort of existing configs? Current shipped contract says append-at-tail. Affects D1.
- **D-2 `count_tokens` 404.** Serve it (proxy to upstream tokenizers or estimate) or document Claude Code context-estimation degradation in hub mode? Affects D11.
- **D-3 missing `modelHub.*` browser i18n keys + absent Python-bundle codes.** Fix now (makes B11 pass) or baseline as expected-fail for this round?
- **D-4 Retry-After honoring.** Keep flat cooldowns (simple, predictable) or honor upstream reset headers? Affects D6.
+- **D-5 tier provenance ladder (approved 2026-09-03).** Apply the first available
+ `upstream > catalog > user > null` rung; managed tiers are read-only, a refresh
+ override is observable, and silent stripping is attributed to the exact attempt.
## 5a. Cross-lane contracts (frozen 2026-09-01)
diff --git a/docs/plans/model-hub-reasoning-tiers.md b/docs/plans/model-hub-reasoning-tiers.md
new file mode 100644
index 000000000..f767715f0
--- /dev/null
+++ b/docs/plans/model-hub-reasoning-tiers.md
@@ -0,0 +1,136 @@
+# Model Hub: Reasoning-Effort Tier Provenance
+
+Status: approved by owner 2026-09-03. Amends the tier-declaration behavior in
+`docs/plans/model-hub.md` (§ "discovered models carry no capability
+metadata"); that spec's "user owns the declaration" rule is superseded by the
+provenance ladder below for reasoning-effort tiers only. Everything else
+(route ordering, placement, guard semantics) is untouched.
+
+## Owner decisions (recorded verbatim, 2026-09-03)
+
+1. If the upstream carries tier information, the upstream values win — highest
+ priority; user input may be wrong. Only when the upstream carries nothing
+ may the user declare tiers.
+2. The Avibe builtin catalog counts as "carried" knowledge for official model
+ ids, ranking below live upstream metadata and above user input.
+3. Auto-provided tiers are read-only for users: no delete, no add. The escape
+ hatch for wrong declarations (either side) is runtime evidence, not user
+ opinion: a tier the upstream provably rejects gets auto-quarantined (v2).
+
+## Provenance ladder
+
+For each source model, `reasoning_efforts` is populated by the FIRST rung that
+applies, and the rung is recorded:
+
+| Rung | `reasoning_efforts_source` | When | Refresh behavior |
+| --- | --- | --- | --- |
+| 1 | `upstream` | Discovery response carries a recognizable reasoning capability signal for this model | Re-applied on every refresh; authoritative |
+| 2 | `catalog` | Model id matches an entry in `vibe/data/backend_models.json` that declares `reasoning_efforts` | Re-applied on every refresh |
+| 3 | `user` | Neither rung above applies and the user typed tiers | Preserved across refreshes (existing behavior) |
+| — | `null` | No rung applies and the list is empty | — |
+
+Editing rules:
+
+- `PATCH .../models/{id}` tier edits are REFUSED with error code
+ `source_model_tiers_managed` (HTTP 409) when
+ `reasoning_efforts_source ∈ {upstream, catalog}`. The refusal detail names
+ the provenance. i18n keys for the refusal MUST land in all four bundles
+ (`vibe/i18n/{en,zh}.json` AND `ui/src/i18n/{en,zh}.json`) — the missing-key
+ defect class (B1/D-3) must not grow.
+- Tier edits remain allowed when the source is `user` or `null`.
+- When a refresh's rung-1/2 application REPLACES a non-empty user-typed list,
+ the change is recorded as a resolution event (info severity, no credential
+ material) so the override is visible, never silent.
+
+## Upstream metadata capture (rung 1), v1 scope
+
+Reality check: official OpenAI/Anthropic `/v1/models` carry no tier data.
+Relay-style endpoints do carry capability signals. v1 recognizes exactly one
+shape and treats everything else as "not carried":
+
+- OpenRouter-shape `supported_parameters` arrays: if the model entry contains
+ `"reasoning"` (or `"reasoning_effort"`), the model is reasoning-capable.
+ Upstream signals are capability booleans, not level enums, so the applied
+ tier list is the UNIFIED VOCABULARY for the source's protocol family (below).
+- Any other/unknown metadata shape → rung 1 does not apply. No guessing from
+ model-id patterns (family inference was explicitly deferred; wrong claims
+ turn into upstream 400s).
+
+The capture point is the discovery pipeline (`probe_models` /
+`discover_models`), which today returns bare id tuples and discards all other
+fields. The pipeline's return type grows a per-model metadata record; the
+`SourceObservation` contract and `source.schema.json` gain the new fields.
+This is a Model Hub contract change: follow the CONTRACT_VERSION bump protocol
+(all mirrored constants + `scripts/check_model_hub_authorities.py` +
+`docs/plans/model-hub-contracts/mirror-registry.json`), and keep
+`_runtime_payload`'s hard-coded literal in sync (known drift trap).
+
+## Unified vocabulary
+
+One authority for effort values, exported from the backend catalog module and
+mirrored (with a contract test) to the UI:
+
+- `minimal, low, medium, high, xhigh, max, ultra` — full ordered vocabulary
+ (ruling 2026-09-03: the vocabulary is the ordered SUPERSET of every value a
+ catalog row legitimately declares; it exists for ordering/display and rung-1
+ defaults, and must never truncate per-model truth. `ultra` was added because
+ catalog rows for gpt-5.6-sol/terra declare it.)
+- Rung 2 applies the catalog row's EXACT per-model list, verbatim — never a
+ family default and never filtered through the vocabulary. If a future
+ catalog row introduces a value outside the vocabulary, the vocabulary
+ expands (with its contract test), not the row.
+- Protocol-family defaults are used ONLY by rung 1 (capability boolean, no
+ enum from upstream):
+ `openai_responses` / `openai_chat` → `minimal, low, medium, high, xhigh`;
+ `anthropic` → `low, medium, high, xhigh, max`. Family defaults deliberately
+ exclude `ultra`: an unknown relay model must not be over-claimed (a wrong
+ claim becomes an upstream 400).
+- `ui/src/components/settings/models/tierSuggestions.ts` and
+ `ui/src/lib/effortOptions.ts` stop disagreeing: both derive from (or are
+ contract-tested against) the single vocabulary. Ghost suggestions for
+ user-editable models use the protocol-family default list.
+
+## Persisted-shape and migration rules
+
+- New optional field `reasoning_efforts_source` on persisted models; absent in
+ files written by older releases → loader treats existing non-empty lists as
+ `user`, empty lists as `null`. Startup never fails on old shapes.
+- First refresh after upgrade applies the ladder (catalog backfill happens
+ then, with the override event when it replaces user values). No offline
+ one-shot migration of tier values.
+- OAuth-materialization and migration paths stop hardcoding
+ `reasoning_efforts: []`: they run the same ladder (rung 2 catalog backfill
+ applies immediately for official ids).
+
+## Silent-strip observability
+
+`_request_for_exact_reasoning_effort` keeps its exact-match forwarding rule,
+but a strip is no longer invisible: record the stripped value and the hop's
+declared tiers in turn provenance and a logger line. No user-facing chat copy,
+no new event kind (noise control).
+
+## v2 (documented now, NOT in v1): evidence quarantine
+
+When a forwarded effort is rejected by the upstream with an
+unsupported-parameter-shaped 400, quarantine that (source, model, tier):
+stop forwarding it, record a resolution event, grey it in the UI with
+"upstream rejected in practice". Quarantine outranks every declaration rung.
+Design and contract for the quarantine store are follow-up work; v1 must not
+paint itself into a corner (the provenance field naming above leaves room for
+a `quarantined` marker per tier).
+
+## Test obligations
+
+- pytest e2e (`tests/e2e/`): B10 grows locked-provenance cases (catalog-backed
+ model refuses tier edit; user-declared model still edits; refresh re-applies
+ catalog over user with event). D10 asserts the strip is recorded in
+ provenance. Scenario catalog rows updated accordingly.
+- Playwright (`ui/e2e/`): tier editor shows provenance and locks for
+ `upstream`/`catalog` models (no add input, no delete affordance, badge with
+ provenance); ghost suggestions match the unified vocabulary; error copy for
+ `source_model_tiers_managed` renders as human text in zh and en.
+- Unit/contract: schema round-trip for the new field; old-shape load fixture;
+ vocabulary contract test between backend export and both UI tables.
+- `docs/plans/model-hub-e2e-test-plan.md`: B10/D10 rows and the §5 decision
+ ledger gain this decision (D-5: tier provenance ladder, approved
+ 2026-09-03).
diff --git a/scripts/check_model_hub_authorities.py b/scripts/check_model_hub_authorities.py
index 94f932efd..6e7a0542b 100644
--- a/scripts/check_model_hub_authorities.py
+++ b/scripts/check_model_hub_authorities.py
@@ -270,6 +270,37 @@ def _python_string_assignment(source: AuthorityInput, spec: dict[str, Any]) -> s
raise ValueError(f"assignment not found: {spec['name']}")
+def _versioned_schema_nodes(node: Any):
+ """Yield every contract_version subschema from an arbitrary schema tree."""
+
+ if isinstance(node, dict):
+ properties = node.get("properties")
+ if isinstance(properties, dict) and isinstance(
+ properties.get("contract_version"),
+ dict,
+ ):
+ yield properties["contract_version"]
+ for value in node.values():
+ yield from _versioned_schema_nodes(value)
+ elif isinstance(node, list):
+ for value in node:
+ yield from _versioned_schema_nodes(value)
+
+
+def _literal_contract_versions(text: str) -> list[int]:
+ patterns = (
+ r"\b[A-Z_]*CONTRACT_VERSION\s*=\s*(\d+)",
+ r"[\"']contract_version[\"']\s*:\s*(\d+)",
+ r"\bcontract_version\s*:\s*(\d+)",
+ r"[\"']contract_version[\"'][^\n\d]{0,40}==\s*(\d+)",
+ )
+ return [
+ int(value)
+ for pattern in patterns
+ for value in re.findall(pattern, text)
+ ]
+
+
def _json_object_keys(source: AuthorityInput, spec: dict[str, Any]) -> set[str]:
value = _json_pointer(source.json(spec["file"]), spec["path"])
if not isinstance(value, dict):
@@ -447,6 +478,147 @@ def check(root: Path = ROOT) -> dict[str, Any]:
registry = source.json("docs/plans/model-hub-contracts/mirror-registry.json")
findings: list[dict[str, Any]] = []
+ version_closure = registry.get("contract_version_closure", {})
+ terminal_version = registry.get("contract_version")
+ if not isinstance(terminal_version, int):
+ findings.append({"kind": "invalid_contract_version", "domain": "V1"})
+ else:
+ raw_persisted_schema_floors = version_closure.get(
+ "persisted_schema_version_floors", {}
+ )
+ if not isinstance(raw_persisted_schema_floors, dict) or any(
+ not isinstance(name, str)
+ or not name
+ or isinstance(floor, bool)
+ or not isinstance(floor, int)
+ or floor < 1
+ or floor > terminal_version
+ for name, floor in (
+ raw_persisted_schema_floors.items()
+ if isinstance(raw_persisted_schema_floors, dict)
+ else ()
+ )
+ ):
+ findings.append(
+ {
+ "kind": "invalid_persisted_schema_version_floors",
+ "domain": "V1",
+ }
+ )
+ persisted_schema_floors: dict[str, int] = {}
+ else:
+ persisted_schema_floors = raw_persisted_schema_floors
+ persisted_schemas = set(persisted_schema_floors)
+ checked_schemas: set[str] = set()
+ contracts_dir = root / "docs/plans/model-hub-contracts"
+ for path in sorted(contracts_dir.glob("*.schema.json")):
+ relative = path.relative_to(root).as_posix()
+ for node in _versioned_schema_nodes(source.json(relative)):
+ checked_schemas.add(path.name)
+ accepted = [node["const"]] if "const" in node else list(node.get("enum", ()))
+ if accepted != sorted(set(accepted)) or not accepted:
+ findings.append(
+ {
+ "kind": "invalid_contract_version_set",
+ "domain": "V1",
+ "file": relative,
+ "values": accepted,
+ }
+ )
+ continue
+ expected = (
+ list(
+ range(
+ persisted_schema_floors[path.name],
+ terminal_version + 1,
+ )
+ )
+ if path.name in persisted_schemas
+ else [terminal_version]
+ )
+ if accepted != expected:
+ findings.append(
+ {
+ "kind": "contract_version_schema_drift",
+ "domain": "V1",
+ "file": relative,
+ "values": accepted,
+ "expected": expected,
+ }
+ )
+ for missing in sorted(persisted_schemas - checked_schemas):
+ findings.append(
+ {
+ "kind": "missing_persisted_version_schema",
+ "domain": "V1",
+ "file": missing,
+ }
+ )
+
+ for path in sorted(contracts_dir.iterdir()):
+ if not path.is_file() or path.name.endswith(".schema.json"):
+ continue
+ relative = path.relative_to(root).as_posix()
+ for value in re.findall(
+ r"contract_version[^0-9]{0,12}(\d+)",
+ source.text(relative),
+ ):
+ if int(value) != terminal_version:
+ findings.append(
+ {
+ "kind": "contract_version_text_drift",
+ "domain": "V1",
+ "file": relative,
+ "value": int(value),
+ }
+ )
+
+ required_literal_files = set(
+ version_closure.get("required_literal_files", ())
+ )
+ matched_literal_files: set[str] = set()
+ for pattern in version_closure.get("literal_globs", ()):
+ for path in sorted(root.glob(pattern)):
+ if not path.is_file():
+ continue
+ relative = path.relative_to(root).as_posix()
+ values = _literal_contract_versions(source.text(relative))
+ if values:
+ matched_literal_files.add(relative)
+ for value in values:
+ if value != terminal_version:
+ findings.append(
+ {
+ "kind": "contract_version_literal_drift",
+ "domain": "V1",
+ "file": relative,
+ "value": value,
+ }
+ )
+ for missing in sorted(required_literal_files - matched_literal_files):
+ findings.append(
+ {
+ "kind": "missing_contract_version_literal",
+ "domain": "V1",
+ "file": missing,
+ }
+ )
+
+ for relative in version_closure.get("contract_headers", ()):
+ match = re.search(
+ r"FINAL CONTRACT v(\d+)",
+ source.text(relative),
+ )
+ if match is None or int(match.group(1)) != terminal_version:
+ findings.append(
+ {
+ "kind": "contract_version_header_drift",
+ "domain": "V1",
+ "file": relative,
+ "value": int(match.group(1)) if match else None,
+ }
+ )
+
# Absence assertions are discovered from the live normative text. The checker
# never embeds a retired member; it derives each term from the assertion and
# checks every contract artifact in the same invocation.
diff --git a/tests/e2e/test_model_hub_routing.py b/tests/e2e/test_model_hub_routing.py
index 69635deae..767d6bcc3 100644
--- a/tests/e2e/test_model_hub_routing.py
+++ b/tests/e2e/test_model_hub_routing.py
@@ -2,10 +2,15 @@
from __future__ import annotations
+import asyncio
from datetime import datetime, timezone
+import aiohttp
import pytest
+from core.handlers.model_hub.adapter import RawOutcomeKind
+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream
from tests.e2e.test_model_hub_migration import _write
from tests.e2e.test_model_hub_runtime import (
@@ -18,6 +23,16 @@ from tests.e2e.test_model_hub_sources import (
_configure_protocol,
_create_source,
)
+from tests.scenario_harness.model_hub import (
+ MemoryModelHubStore,
+ ModelHubScenarioAdapter,
+ ScenarioCallResult,
+ config_with_sources,
+ fixed_model,
+ service_for,
+ source,
+ source_model,
+)
pytestmark = pytest.mark.e2e_model_hub
@@ -474,3 +489,93 @@ def test_d6_server_error_ignores_retry_after_and_uses_flat_cooldown(
expected_reason="server_error",
expected_delay=30,
)
+
+
+def test_d10_strip_is_forwarded_and_persisted_for_the_exact_fallback_hop(
+ tmp_path,
+) -> None:
+ """D10: the per-turn gateway records the exact hop whose effort it strips."""
+
+ async def exercise() -> None:
+ first = source(
+ "src_d10first1",
+ [source_model("relay-model", reasoning_efforts=("high",))],
+ vendor="openai",
+ protocol="openai_responses",
+ )
+ second = source(
+ "src_d10second",
+ [source_model("relay-model")],
+ vendor="openai",
+ protocol="openai_responses",
+ )
+ requested_model = fixed_model("codex")
+ config = config_with_sources(
+ [first, second],
+ backend="codex",
+ menu_model=requested_model,
+ hops=(
+ (first.id, "relay-model"),
+ (second.id, "relay-model"),
+ ),
+ )
+ adapter = ModelHubScenarioAdapter(
+ invoke_results=(
+ ScenarioCallResult(
+ RawOutcomeKind.HTTP_ERROR,
+ status=429,
+ error_code="rate_limit_error",
+ ),
+ ScenarioCallResult(RawOutcomeKind.SUCCESS, status=200),
+ )
+ )
+ service = service_for(tmp_path, MemoryModelHubStore(config), adapter)
+ gateway = ModelHubTurnGateway(service)
+ turn_id = "turn_d10_strip"
+ base_url, token = await gateway.endpoint(
+ "codex",
+ process_scope="/repo",
+ turn_id=turn_id,
+ requested_model_id=requested_model,
+ resolved_model_id="relay-model",
+ source_id=first.id,
+ )
+ try:
+ async with aiohttp.ClientSession(trust_env=False) as client:
+ response = await client.post(
+ f"{base_url}/v1/responses",
+ json={
+ "model": "relay-model",
+ "input": "ping",
+ "reasoning": {"effort": "high", "summary": "auto"},
+ "stream": False,
+ },
+ headers={"Authorization": f"Bearer {token}"},
+ )
+ assert response.status == 200
+ await response.read()
+ finally:
+ await gateway.close()
+
+ assert adapter.requests[0]["reasoning"] == {
+ "effort": "high",
+ "summary": "auto",
+ }
+ assert adapter.requests[1]["reasoning"] == {"summary": "auto"}
+ gateway.correlation.settle(
+ turn_id,
+ settled_by=SETTLED_BY_TERMINAL_RESULT,
+ ts="2026-09-03T06:00:00+00:00",
+ )
+ record = service.provenance.get(turn_id)
+ assert record is not None
+ assert record["failed_attempts"][0]["source_id"] == first.id
+ assert record["served"] == {
+ "source_id": second.id,
+ "configured_model_id": "relay-model",
+ "channel": "hub",
+ "stripped_reasoning_efforts": ["high"],
+ "declared_reasoning_efforts": [],
+ }
+
+ asyncio.run(exercise())
diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.py
index 02e8dd75e..f32f649f6 100644
--- a/tests/e2e/test_model_hub_runtime.py
+++ b/tests/e2e/test_model_hub_runtime.py
@@ -599,7 +599,7 @@ def test_a1_feature_flag_disables_the_complete_models_api(
assert response.status == 404, (method, path, body)
assert body == {
"ok": False,
- "contract_version": 6,
+ "contract_version": 7,
"error": "feature_disabled",
}
diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.py
index 10ce8cdda..f4b17d764 100644
--- a/tests/e2e/test_model_hub_sources.py
+++ b/tests/e2e/test_model_hub_sources.py
@@ -13,7 +13,7 @@ from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream
pytestmark = pytest.mark.e2e_model_hub
-CONTRACT_VERSION = 6
+CONTRACT_VERSION = 7
MENU_MODEL = "claude-sonnet-4-6"
SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"
@@ -115,6 +115,9 @@ def test_b1_auto_observe_selects_protocol_from_response_shape(
"protocol": protocol,
"discovery": "succeeded",
"models": ["mock-model"],
+ "model_metadata": [
+ {"id": "mock-model", "supported_parameters": None}
+ ],
}
captured_paths = [item["path"] for item in mock_llm_upstream.requests()]
assert "/v1/models" in captured_paths
@@ -147,7 +150,7 @@ def test_b3_discovered_model_persists_only_contract_fields(
mock_llm_upstream: MockLLMUpstream,
model_hub_app,
) -> None:
- """B3: relay inventory extensions are deliberately not persisted."""
+ """B3: the one supported extension survives; unrelated metadata does not."""
_configure_protocol(
mock_llm_upstream,
@@ -158,6 +161,7 @@ def test_b3_discovered_model_persists_only_contract_fields(
"display_name": "Upstream display",
"context_length": 128_000,
"pricing": {"input": "0.01", "output": "0.02"},
+ "supported_parameters": ["reasoning"],
}
],
)
@@ -168,13 +172,21 @@ def test_b3_discovered_model_persists_only_contract_fields(
"display_name",
"origin",
"reasoning_efforts",
+ "reasoning_efforts_source",
"discovered_at",
"retired",
}
assert model["id"] == "relay-model"
assert model["display_name"] is None
assert model["origin"] == "discovered"
- assert model["reasoning_efforts"] == []
+ assert model["reasoning_efforts"] == [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ ]
+ assert model["reasoning_efforts_source"] == "upstream"
assert model["retired"] is False
assert model["discovered_at"]
serialized = str(model)
@@ -567,22 +579,56 @@ def test_b10_custom_models_and_free_text_tiers_obey_ownership_rules(
mock_llm_upstream: MockLLMUpstream,
model_hub_app,
) -> None:
- """B10: custom rows are mutable; upstream rows remain managed."""
+ """B10: managed tiers lock; user tiers edit; refresh restores catalog truth."""
- _configure_protocol(mock_llm_upstream)
- source, _ = _create_source(model_hub_app, mock_llm_upstream)
+ _configure_protocol(
+ mock_llm_upstream,
+ "openai_responses",
+ models=[{"id": "gpt-5.6-sol"}, {"id": "relay-user-model"}],
+ )
+ source, _ = _create_source(
+ model_hub_app,
+ mock_llm_upstream,
+ protocol="openai_responses",
+ )
endpoint = f"/api/models/sources/{source['id']}/models"
- managed = model_hub_app.client.post(
- endpoint,
- {
- "model_id": "mock-model",
- "display_name": "Cannot replace",
- "reasoning_efforts": ["turbo"],
- },
+ catalog_model = next(
+ model for model in source["models"] if model["id"] == "gpt-5.6-sol"
+ )
+ assert catalog_model["reasoning_efforts"] == [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+ ]
+ assert catalog_model["reasoning_efforts_source"] == "catalog"
+ managed = model_hub_app.client.patch(
+ f"{endpoint}/gpt-5.6-sol",
+ {"reasoning_efforts": ["turbo"]},
+ )
+ managed_body = managed.json()
+ assert managed.status == 409, managed_body
+ assert managed_body["error"] == "source_model_tiers_managed"
+ assert managed_body["detail"] == (
+ "settings.models.sourceDetail.tiers.managed.catalog"
)
- assert managed.status == 409
- assert managed.json()["error"] == "source_model_managed_upstream"
+ assert managed_body["reasoning_efforts_source"] == "catalog"
+
+ user_updated = model_hub_app.client.patch(
+ f"{endpoint}/relay-user-model",
+ {"reasoning_efforts": ["turbo", "careful"]},
+ )
+ assert user_updated.status == 200, user_updated.json()
+ user_model = next(
+ model
+ for model in user_updated.json()["source"]["models"]
+ if model["id"] == "relay-user-model"
+ )
+ assert user_model["reasoning_efforts"] == ["turbo", "careful"]
+ assert user_model["reasoning_efforts_source"] == "user"
added = model_hub_app.client.post(
endpoint,
@@ -601,6 +647,7 @@ def test_b10_custom_models_and_free_text_tiers_obey_ownership_rules(
)
assert manual["origin"] == "manual"
assert manual["reasoning_efforts"] == ["turbo", "careful"]
+ assert manual["reasoning_efforts_source"] == "user"
updated = model_hub_app.client.patch(
f"{endpoint}/manual-model",
@@ -621,3 +668,58 @@ def test_b10_custom_models_and_free_text_tiers_obey_ownership_rules(
assert "manual-model" not in {
model["id"] for model in deleted.json()["source"]["models"]
}
+
+ # Emulate the exact released-v6 persisted shape: a non-empty declaration
+ # without provenance loads as user-owned, then the first refresh backfills.
+ config_path = model_hub_app.avibe_home / "config" / "config.json"
+ persisted = json.loads(config_path.read_text(encoding="utf-8"))
+ persisted_source = next(
+ item
+ for item in persisted["model_hub"]["sources"]
+ if item["id"] == source["id"]
+ )
+ persisted_model = next(
+ model
+ for model in persisted_source["models"]
+ if model["id"] == "gpt-5.6-sol"
+ )
+ persisted_model["reasoning_efforts"] = ["legacy-user-tier"]
+ persisted_model.pop("reasoning_efforts_source")
+ replacement = config_path.with_suffix(".reasoning-tiers.tmp")
+ replacement.write_text(json.dumps(persisted), encoding="utf-8")
+ replacement.replace(config_path)
+ model_hub_app.restart_controller()
+
+ refreshed = model_hub_app.client.post(
+ f"/api/models/sources/{source['id']}/refresh", {}
+ )
+ refreshed_body = refreshed.json()
+ assert refreshed.status == 200, refreshed_body
+ refreshed_catalog_model = next(
+ model
+ for model in refreshed_body["source"]["models"]
+ if model["id"] == "gpt-5.6-sol"
+ )
+ assert refreshed_catalog_model["reasoning_efforts"] == [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+ ]
+ assert refreshed_catalog_model["reasoning_efforts_source"] == "catalog"
+ events = model_hub_app.client.get("/api/models/events?limit=20").json()[
+ "events"
+ ]
+ overrides = [
+ event
+ for event in events
+ if event["kind"] == "reasoning_efforts_override"
+ and event["from_source"] == source["id"]
+ and event["model_id"] == "gpt-5.6-sol"
+ ]
+ assert len(overrides) == 1
+ assert overrides[0]["reason"] == "catalog_tiers"
+ assert overrides[0]["severity"] == "info"
+ assert SYNTHETIC_API_KEY not in json.dumps(overrides)
diff --git a/tests/fixtures/model_hub/released_v6_reasoning_efforts.json b/tests/fixtures/model_hub/released_v6_reasoning_efforts.json
new file mode 100644
index 000000000..58521fe57
--- /dev/null
+++ b/tests/fixtures/model_hub/released_v6_reasoning_efforts.json
@@ -0,0 +1,21 @@
+{
+ "models": [
+ {
+ "id": "legacy-user-tier-model",
+ "display_name": null,
+ "origin": "manual",
+ "reasoning_efforts": [
+ "turbo",
+ "careful"
+ ],
+ "discovered_at": null
+ },
+ {
+ "id": "legacy-empty-tier-model",
+ "display_name": null,
+ "origin": "discovered",
+ "reasoning_efforts": [],
+ "discovered_at": "2026-08-19T00:00:00Z"
+ }
+ ]
+}
diff --git a/tests/scenario_harness/model_hub.py b/tests/scenario_harness/model_hub.py
index e2f1c1735..3292fd55e 100644
--- a/tests/scenario_harness/model_hub.py
+++ b/tests/scenario_harness/model_hub.py
@@ -25,6 +25,7 @@ from config.v2_config import (
model_hub_fixed_menu_ids,
)
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
EngineHealth,
EngineStatus,
ObservationDiscovery,
@@ -113,7 +114,9 @@ class ModelHubScenarioAdapter:
authenticated=True,
protocol="openai_chat",
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=tuple(discovery_models),
+ models=tuple(
+ DiscoveredModel(id=model_id) for model_id in discovery_models
+ ),
)
self.discovery_models = tuple(discovery_models)
self.refresh_models = tuple(refresh_models) if refresh_models is not None else self.discovery_models
@@ -186,9 +189,9 @@ class ModelHubScenarioAdapter:
protocol: str,
base_url: str | None,
credential_ref: str,
- ) -> tuple[str, ...]:
+ ) -> tuple[DiscoveredModel, ...]:
self.discovery_calls.append((vendor, protocol, base_url, credential_ref))
- return self.refresh_models
+ return tuple(DiscoveredModel(id=model_id) for model_id in self.refresh_models)
async def credential_supports_refresh(self, credential_ref: str) -> bool:
return credential_ref in self.refreshable_credential_refs
diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.py
index 77b6ca21e..1576071fa 100644
--- a/tests/scenario_harness/model_hub_native_oauth.py
+++ b/tests/scenario_harness/model_hub_native_oauth.py
@@ -7,7 +7,7 @@ from types import SimpleNamespace
from typing import Any, Mapping
from config.v2_config import ModelHubAgentSupplyConfig, ModelHubConfig
-from core.handlers.model_hub.adapter import OAuthFlowState
+from core.handlers.model_hub.adapter import DiscoveredModel, OAuthFlowState
from core.handlers.model_hub.events import BoundedEventLog
from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter, _account_label, _signed_in
from core.handlers.model_hub.oauth import OAuthFlowRegistry
@@ -201,7 +201,7 @@ class FakeHubOAuthAdapter(UnavailableEngineAdapter):
self.synced.append(tuple(bindings))
async def discover_models(self, vendor, protocol, base_url, credential_ref):
- return ("claude-opus-4-6",)
+ return (DiscoveredModel(id="claude-opus-4-6"),)
def complete(self, flow_id: str) -> None:
flow = self.flows[flow_id]
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 142af8c1a..a558360b3 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -588,7 +588,7 @@ scenarios:
layer: e2e-auto
test: tests/e2e/test_model_hub_sources.py::test_b9_refetch_preserves_existing_model_discovery_timestamp
- id: B10
- name: Custom-model mutation obeys upstream ownership boundaries
+ name: Reasoning-tier provenance owns managed and user model mutations
status: assert
kind: mutation
layer: e2e-auto
@@ -704,13 +704,11 @@ scenarios:
owning_layer: future live-turn suite (turn gateway)
evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81
- id: D10
- name: Undeclared reasoning effort is omitted from the upstream request
- status: skip
+ name: Stripped reasoning effort is attributed to the exact fallback attempt
+ status: assert
kind: compatibility
- layer: turn-gateway
- reason: exact turn request capture requires the private credential issued to a live backend turn
- owning_layer: future live-turn suite (turn gateway)
- evidence: docs/plans/model-hub-e2e-test-plan.md#d-per-turn-routing-fallback-capability-behavior-c41c50-c74c81
+ layer: e2e-auto
+ test: tests/e2e/test_model_hub_routing.py::test_d10_strip_is_forwarded_and_persisted_for_the_exact_fallback_hop
- id: D11
name: Claude token counting behavior is documented at the gateway
status: skip
diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
index 1623bcd9a..0d1a354ec 100644
--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
@@ -16,6 +16,7 @@ from config.v2_config import (
ModelHubRouteHopConfig,
)
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
SOURCE_PROTOCOLS,
ObservationDiscovery,
ObservationOutcome,
@@ -174,7 +175,7 @@ def test_mh_match_001_add_source_persists_and_reports_each_exact_position(
authenticated=True,
protocol="anthropic",
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=(menu_model,),
+ models=(DiscoveredModel(id=menu_model),),
),
refresh_models=(menu_model,),
)
@@ -394,7 +395,7 @@ def test_mh_protocol_001_saved_protocol_is_response_observed_and_transient_state
authenticated=True,
protocol="openai_chat",
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=("observed-model",),
+ models=(DiscoveredModel(id="observed-model"),),
)
)
service = service_for(tmp_path, store, adapter)
@@ -422,7 +423,7 @@ def test_mh_protocol_001_saved_protocol_is_response_observed_and_transient_state
authenticated=True,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
)
ambiguous_service = service_for(
@@ -471,7 +472,7 @@ def test_mh_protocol_003_manual_selection_requires_matching_response_proof(
authenticated=True,
protocol="openai_responses",
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=("selected-model",),
+ models=(DiscoveredModel(id="selected-model"),),
)
)
service = service_for(tmp_path, store, adapter)
@@ -502,7 +503,7 @@ def test_mh_protocol_003_manual_selection_requires_matching_response_proof(
authenticated=True,
protocol="openai_chat",
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=("wrong-protocol-model",),
+ models=(DiscoveredModel(id="wrong-protocol-model"),),
)
)
mismatch_service = service_for(
@@ -534,7 +535,7 @@ def test_mh_protocol_003_manual_selection_requires_matching_response_proof(
authenticated=True,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
)
ambiguous_service = service_for(
@@ -588,7 +589,7 @@ def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_
authenticated=True,
protocol="anthropic",
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=(menu_model,),
+ models=(DiscoveredModel(id=menu_model),),
)
)
service = service_for(tmp_path, store, adapter)
diff --git a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
index a73cc9c82..e500735c3 100644
--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
@@ -17,6 +17,7 @@ from config.v2_config import (
ModelHubSourceStateConfig,
)
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
ObservationDiscovery,
ObservationOutcome,
SourceObservation,
@@ -103,7 +104,7 @@ class MigrationAdapter:
authenticated=True,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
return SourceObservation(
outcome=ObservationOutcome.OBSERVED,
@@ -111,7 +112,7 @@ class MigrationAdapter:
authenticated=True,
protocol=self.observed_protocols[vendor],
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=(f"{vendor}-model",),
+ models=(DiscoveredModel(id=f"{vendor}-model"),),
)
async def provision_credential(
@@ -131,8 +132,8 @@ class MigrationAdapter:
protocol: str,
base_url: str | None,
credential_ref: str,
- ) -> tuple[str, ...]:
- return (f"{vendor}-model",)
+ ) -> tuple[DiscoveredModel, ...]:
+ return (DiscoveredModel(id=f"{vendor}-model"),)
async def sync_sources(self, bindings) -> None:
self.synced.append(tuple(bindings))
@@ -674,6 +675,17 @@ def test_mh_mig_002_oauth_defaults_to_native_sources(
("openai", "subscription", "native_cli", None),
}
assert adapter.provisioned == []
+ from vibe.backend_model_catalog import (
+ bundled_catalog_reasoning_efforts_for_model,
+ )
+
+ for source in store.config.sources:
+ assert source.models
+ for model in source.models:
+ assert model.reasoning_efforts_source == "catalog"
+ assert tuple(model.reasoning_efforts) == (
+ bundled_catalog_reasoning_efforts_for_model(model.id)
+ )
reloaded = _assert_canonical_round_trip(store.config)
assert {
(source.vendor, source.kind, source.supply_channel, source.credential_ref)
diff --git a/tests/test_backend_model_catalog.py b/tests/test_backend_model_catalog.py
index 9e7c6453f..e4675de96 100644
--- a/tests/test_backend_model_catalog.py
+++ b/tests/test_backend_model_catalog.py
@@ -34,6 +34,84 @@ def _reset_remote_cache(monkeypatch):
backend_model_catalog._REMOTE_MEMORY_CACHE.clear()
+def test_reasoning_effort_authorities_are_ordered_and_complete() -> None:
+ assert backend_model_catalog.REASONING_EFFORT_VOCABULARY == (
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+ )
+ assert backend_model_catalog.PROTOCOL_REASONING_EFFORT_DEFAULTS == {
+ "openai_responses": ("minimal", "low", "medium", "high", "xhigh"),
+ "openai_chat": ("minimal", "low", "medium", "high", "xhigh"),
+ "anthropic": ("low", "medium", "high", "xhigh", "max"),
+ }
+ assert all(
+ "ultra" not in efforts
+ for efforts in backend_model_catalog.PROTOCOL_REASONING_EFFORT_DEFAULTS.values()
+ )
+
+
+def test_bundled_catalog_rows_are_exact_and_covered_by_the_vocabulary() -> None:
+ catalog = backend_model_catalog.load_bundled_catalog()
+ efforts_by_model = (
+ backend_model_catalog.bundled_catalog_reasoning_efforts_by_model()
+ )
+ rows = [
+ model
+ for backend in catalog["backends"].values()
+ for model in backend["models"]
+ if "reasoning_efforts" in model
+ ]
+ declared = {
+ effort
+ for model in rows
+ for effort in model["reasoning_efforts"]
+ }
+
+ assert rows
+ assert declared <= set(backend_model_catalog.REASONING_EFFORT_VOCABULARY)
+ assert len(backend_model_catalog.REASONING_EFFORT_VOCABULARY) == len(
+ set(backend_model_catalog.REASONING_EFFORT_VOCABULARY)
+ )
+ for model in rows:
+ assert efforts_by_model[model["id"]] == tuple(model["reasoning_efforts"])
+
+
+def test_bundled_reasoning_effort_index_is_immutable_and_keeps_first_row(
+ monkeypatch,
+) -> None:
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "load_bundled_catalog",
+ lambda: {
+ "backends": {
+ "first": {
+ "models": [
+ {"id": "shared-model", "reasoning_efforts": ["low"]}
+ ]
+ },
+ "second": {
+ "models": [
+ {"id": "shared-model", "reasoning_efforts": ["ultra"]}
+ ]
+ },
+ }
+ },
+ )
+
+ efforts_by_model = (
+ backend_model_catalog.bundled_catalog_reasoning_efforts_by_model()
+ )
+
+ assert efforts_by_model["shared-model"] == ("low",)
+ with pytest.raises(TypeError):
+ efforts_by_model["shared-model"] = ("changed",)
+
+
def test_backend_model_entries_normalize_runtime_catalog_shape():
catalog = {
"schema_version": 1,
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index a75e11c27..7964af6ae 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -27,6 +27,7 @@ from config.v2_config import (
)
from core.agent_auth_service import BackendLoginInProgressError
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
EngineHealth,
EngineStatus,
ObservationDiscovery,
@@ -57,7 +58,7 @@ from core.handlers.model_hub.service import (
create_default_service,
)
from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_config
-from vibe import ui_server
+from vibe import backend_model_catalog, ui_server
from vibe.model_hub_client import ModelHubRemoteService, _decode
from vibe.model_hub_runtime.state import EngineStateError, _validate_source_target
from vibe.ui_server import app
@@ -243,7 +244,10 @@ class FakeAdapter:
async def discover_models(self, vendor, protocol, base_url, credential_ref):
self.discovery_credential_refs.append(credential_ref)
- return ("claude-opus-4-6", "claude-sonnet-4-6")
+ return (
+ DiscoveredModel(id="claude-opus-4-6"),
+ DiscoveredModel(id="claude-sonnet-4-6"),
+ )
async def observe_source(self, vendor, base_url, credential_ref, protocol_order):
self.observed_protocol_orders.append(tuple(protocol_order))
@@ -261,7 +265,7 @@ class FakeAdapter:
authenticated=True,
protocol=protocol_order[0],
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=tuple(models),
+ models=tuple(models),
)
async def invoke(self, source_id, model_id, request, stream, origin):
@@ -865,7 +869,7 @@ def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):
assert adapter.start_calls == 1
assert store.config.enabled is True
assert runtime["enabled"] is True
- assert runtime["contract_version"] == 6
+ assert runtime["contract_version"] == 7
assert runtime["status"]["health"] == "ok"
_assert_valid("runtime-dependency.schema.json", runtime)
@@ -1083,7 +1087,7 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 6, "status": {"health": "ok"}}
+ return {"contract_version": 7, "status": {"health": "ok"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1100,7 +1104,7 @@ def test_runtime_stop_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 6, "status": {"health": "not_started"}}
+ return {"contract_version": 7, "status": {"health": "not_started"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1117,7 +1121,7 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 6, "status": {"health": "installing"}}
+ return {"contract_version": 7, "status": {"health": "installing"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1673,7 +1677,7 @@ def test_source_create_nonce_releases_only_after_credential_cleanup(tmp_path):
authenticated=False,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
service = ModelHubService(
store=MemoryStore(),
@@ -1719,7 +1723,7 @@ def test_source_create_nonce_retains_unsettled_cleanup_until_restart(tmp_path):
authenticated=False,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
service = ModelHubService(
store=store,
@@ -2846,7 +2850,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):
assert response.status_code == 200
assert response.get_json() == {
"ok": True,
- "contract_version": 6,
+ "contract_version": 7,
"agent": {
"backend": "codex",
"mode": "hub",
@@ -3718,9 +3722,130 @@ def test_unsaved_observation_route_restricts_a_manual_protocol_to_one_probe(
assert adapter.revoked == ["cred_test001"]
+ ("protocol", "model", "expected_efforts", "expected_source"),
+ (
+ (
+ "openai_responses",
+ DiscoveredModel(
+ id="relay-reasoning-model",
+ supported_parameters=("reasoning",),
+ ),
+ ["minimal", "low", "medium", "high", "xhigh"],
+ "upstream",
+ ),
+ (
+ "openai_responses",
+ DiscoveredModel(id="gpt-5.6-sol"),
+ ["low", "medium", "high", "xhigh", "max", "ultra"],
+ "catalog",
+ ),
+ ),
+)
+def test_source_creation_applies_the_first_reasoning_tier_provenance_rung(
+ tmp_path,
+ protocol,
+ model,
+ expected_efforts,
+ expected_source,
+):
+ service, store, adapter = _service(tmp_path)
+ adapter.observation = SourceObservation(
+ outcome=ObservationOutcome.OBSERVED,
+ reachable=True,
+ authenticated=True,
+ protocol=protocol,
+ discovery=ObservationDiscovery.SUCCEEDED,
+ models=(model,),
+ )
+
+ created = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "custom",
+ "base_url": "https://relay.example/v1",
+ "key": "sk-test-tier-provenance-create",
+ "protocol": protocol,
+ }
+ )
+ )["source"]
+
+ [created_model] = created["models"]
+ assert created_model["reasoning_efforts"] == expected_efforts
+ assert created_model["reasoning_efforts_source"] == expected_source
+ assert store.config.sources[0].models[0].reasoning_efforts == expected_efforts
+
+
+def test_discovery_batch_loads_the_bundled_reasoning_index_once(
+ monkeypatch,
+ tmp_path,
+):
+ service, _store, _adapter = _service(tmp_path)
+ catalog_loads = 0
+
+ def load_catalog():
+ nonlocal catalog_loads
+ catalog_loads += 1
+ return {
+ "backends": {
+ "codex": {
+ "models": [
+ {"id": "catalog-a", "reasoning_efforts": ["low"]},
+ {"id": "catalog-b", "reasoning_efforts": ["high"]},
+ ]
+ }
+ }
+ }
+
+ monkeypatch.setattr(
+ backend_model_catalog,
+ "load_bundled_catalog",
+ load_catalog,
+ )
+ source = ModelHubSourceConfig(
+ id="src_catalog_batch",
+ kind="api_key",
+ vendor="custom",
+ display_name="Catalog batch",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[],
+ )
+
+ service._apply_discovered_models(
+ source,
+ [],
+ [DiscoveredModel(id="catalog-a"), DiscoveredModel(id="catalog-b")],
+ )
+
+ assert catalog_loads == 1
+ assert [
+ (model.id, model.reasoning_efforts, model.reasoning_efforts_source)
+ for model in source.models
+ ] == [
+ ("catalog-a", ["low"], "catalog"),
+ ("catalog-b", ["high"], "catalog"),
+ ]
+
+
def test_source_create_requires_explicit_consent_for_proven_inventory_failure(
+ monkeypatch,
tmp_path,
):
+ catalog_index_loads = 0
+
+ def load_catalog_index():
+ nonlocal catalog_index_loads
+ catalog_index_loads += 1
+ return {"catalog-manual": ("low", "ultra")}
+
+ monkeypatch.setattr(
+ "core.handlers.model_hub.service.bundled_catalog_reasoning_efforts_by_model",
+ load_catalog_index,
+ )
store = MemoryStore()
adapter = FakeAdapter()
adapter.observation = SourceObservation(
@@ -3729,7 +3854,7 @@ def test_source_create_requires_explicit_consent_for_proven_inventory_failure(
authenticated=True,
protocol="anthropic",
discovery=ObservationDiscovery.FAILED,
- model_ids=(),
+ models=(),
)
service = ModelHubService(
store=store,
@@ -3744,6 +3869,18 @@ def test_source_create_requires_explicit_consent_for_proven_inventory_failure(
"base_url": "https://relay.example/v1",
"key": "sk-test-inventory-consent",
"protocol": "anthropic",
+ "models": [
+ {
+ "id": "catalog-manual",
+ "origin": "manual",
+ "reasoning_efforts": [],
+ },
+ {
+ "id": "relay-manual",
+ "origin": "manual",
+ "reasoning_efforts": ["careful"],
+ },
+ ],
}
with pytest.raises(ModelHubError) as rejected:
@@ -3753,6 +3890,7 @@ def test_source_create_requires_explicit_consent_for_proven_inventory_failure(
assert rejected.value.data["observation"]["discovery"] == "failed"
assert store.config.sources == []
assert adapter.revoked == ["cred_test001"]
+ assert catalog_index_loads == 0
created = asyncio.run(
service.create_source(
@@ -3761,7 +3899,17 @@ def test_source_create_requires_explicit_consent_for_proven_inventory_failure(
)["source"]
assert created["protocol"] == "anthropic"
- assert created["models"] == []
+ assert [
+ (
+ model["id"],
+ model["reasoning_efforts"],
+ model["reasoning_efforts_source"],
+ )
+ for model in created["models"]
+ ] == [
+ ("catalog-manual", ["low", "ultra"], "catalog"),
+ ("relay-manual", ["careful"], "user"),
+ ]
assert created["state"] == {
"status": "error",
"retry_at": None,
@@ -3769,6 +3917,7 @@ def test_source_create_requires_explicit_consent_for_proven_inventory_failure(
}
assert len(store.config.sources) == 1
assert adapter.revoked == ["cred_test001", "cred_test002"]
+ assert catalog_index_loads == 1
def test_source_order_route_rejects_retired_policy_payload(monkeypatch, tmp_path):
@@ -4318,7 +4467,7 @@ def test_discovered_source_model_delete_persists_retirement_tombstone(
assert store.config.sources[0].models[0].reasoning_efforts == ["high"]
async def rediscover(*_args):
- return ("gpt-5", "gpt-5.1")
+ return (DiscoveredModel(id="gpt-5"), DiscoveredModel(id="gpt-5.1"))
adapter.discover_models = rediscover
refreshed = client.post(
@@ -4337,6 +4486,238 @@ def test_discovered_source_model_delete_persists_retirement_tombstone(
assert refreshed_models["gpt-5.1"]["retired"] is False
[email protected]("managed_source", ("upstream", "catalog"))
+def test_managed_reasoning_tiers_refuse_patch_with_provenance_detail(
+ monkeypatch,
+ tmp_path,
+ managed_source,
+):
+ service, store, _adapter = _service(tmp_path)
+ source = ModelHubSourceConfig(
+ id=f"src_{managed_source}01",
+ kind="api_key",
+ vendor="custom",
+ display_name="Managed tiers",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[
+ ModelHubModelConfig(
+ id="managed-model",
+ provenance="discovered",
+ reasoning_efforts=["low", "high"],
+ reasoning_efforts_source=managed_source,
+ )
+ ],
+ credential_ref="cred_managed01",
+ )
+ store.config.sources.append(source)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+
+ response = client.patch(
+ f"/api/models/sources/{source.id}/models/managed-model",
+ json={"reasoning_efforts": ["medium"]},
+ headers=csrf_headers(client, base_url),
+ base_url=base_url,
+ )
+
+ assert response.status_code == 409
+ assert response.get_json() == {
+ "ok": False,
+ "contract_version": CONTRACT_VERSION,
+ "error": "source_model_tiers_managed",
+ "detail": (
+ f"settings.models.sourceDetail.tiers.managed.{managed_source}"
+ ),
+ "reasoning_efforts_source": managed_source,
+ }
+ assert source.models[0].reasoning_efforts == ["low", "high"]
+
+
+ ("initial_efforts", "initial_source", "replacement", "expected_source"),
+ (
+ (["careful"], "user", [], None),
+ ([], None, ["careful", "turbo"], "user"),
+ ),
+)
+def test_unmanaged_reasoning_tiers_remain_editable(
+ tmp_path,
+ initial_efforts,
+ initial_source,
+ replacement,
+ expected_source,
+):
+ service, store, _adapter = _service(tmp_path)
+ source = ModelHubSourceConfig(
+ id="src_unmanaged01",
+ kind="api_key",
+ vendor="custom",
+ display_name="User tiers",
+ protocol="openai_chat",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[
+ ModelHubModelConfig(
+ id="relay-user-model",
+ provenance="manual",
+ reasoning_efforts=list(initial_efforts),
+ reasoning_efforts_source=initial_source,
+ )
+ ],
+ credential_ref="cred_unmanaged01",
+ )
+ store.config.sources.append(source)
+
+ updated = asyncio.run(
+ service.update_model_reasoning_efforts(
+ source.id,
+ "relay-user-model",
+ {"reasoning_efforts": replacement},
+ )
+ )
+
+ [updated_model] = updated["models"]
+ assert updated_model["reasoning_efforts"] == replacement
+ assert updated_model["reasoning_efforts_source"] == expected_source
+
+
+def test_add_model_upsert_cannot_bypass_catalog_tier_lock(tmp_path):
+ service, store, _adapter = _service(tmp_path)
+ source = ModelHubSourceConfig(
+ id="src_catalogadd1",
+ kind="api_key",
+ vendor="custom",
+ display_name="Catalog model source",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[],
+ credential_ref="cred_catalogadd1",
+ )
+ store.config.sources.append(source)
+
+ created = asyncio.run(
+ service.add_custom_model(
+ source.id,
+ {
+ "model_id": "gpt-5.6-sol",
+ "reasoning_efforts": ["made-up"],
+ },
+ )
+ )["models"][0]
+
+ assert created["reasoning_efforts"] == [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+ ]
+ assert created["reasoning_efforts_source"] == "catalog"
+ with pytest.raises(ModelHubError) as error:
+ asyncio.run(
+ service.add_custom_model(
+ source.id,
+ {
+ "model_id": "gpt-5.6-sol",
+ "reasoning_efforts": ["made-up"],
+ },
+ )
+ )
+ assert error.value.code == "source_model_tiers_managed"
+ assert error.value.status == 409
+
+
+ ("metadata", "expected_efforts", "expected_source", "expected_reason"),
+ (
+ (
+ DiscoveredModel(id="gpt-5.6-sol"),
+ ["low", "medium", "high", "xhigh", "max", "ultra"],
+ "catalog",
+ "catalog_tiers",
+ ),
+ (
+ DiscoveredModel(
+ id="gpt-5.6-sol",
+ supported_parameters=("reasoning_effort",),
+ ),
+ ["minimal", "low", "medium", "high", "xhigh"],
+ "upstream",
+ "upstream_tiers",
+ ),
+ ),
+)
+def test_refresh_overrides_user_tiers_only_after_commit_and_records_one_event(
+ tmp_path,
+ metadata,
+ expected_efforts,
+ expected_source,
+ expected_reason,
+):
+ service, store, adapter = _service(tmp_path)
+ source = ModelHubSourceConfig(
+ id="src_override001",
+ kind="api_key",
+ vendor="custom",
+ display_name="Authorization: sk-test-override-secret",
+ protocol="openai_responses",
+ supply_channel="hub",
+ billing="metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[
+ ModelHubModelConfig(
+ id="gpt-5.6-sol",
+ provenance="discovered",
+ reasoning_efforts=["user-only"],
+ reasoning_efforts_source="user",
+ )
+ ],
+ credential_ref="cred_override001",
+ )
+ store.config.sources.append(source)
+
+ async def discover(*_args):
+ return (metadata,)
+
+ adapter.discover_models = discover
+ save = store.save
+
+ def fail_save(_config):
+ raise OSError("injected persistence failure")
+
+ store.save = fail_save
+ with pytest.raises(OSError, match="injected persistence failure"):
+ asyncio.run(service.refresh_source(source.id))
+ assert service.events.list() == []
+ assert store.config.sources[0].models[0].reasoning_efforts == ["user-only"]
+
+ store.save = save
+ refreshed = asyncio.run(service.refresh_source(source.id))["source"]
+
+ [refreshed_model] = refreshed["models"]
+ assert refreshed_model["reasoning_efforts"] == expected_efforts
+ assert refreshed_model["reasoning_efforts_source"] == expected_source
+ [event] = service.events.list()
+ assert event["kind"] == "reasoning_efforts_override"
+ assert event["agent"] == "system"
+ assert event["model_id"] == "gpt-5.6-sol"
+ assert event["from_source"] == source.id
+ assert event["to_source"] is None
+ assert event["reason"] == expected_reason
+ assert event["severity"] == "info"
+ serialized = json.dumps(event)
+ assert "sk-test-override-secret" not in serialized
+ assert "[redacted]" in serialized
+
+
def test_native_reauth_route_requires_ack_before_oauth_and_returns_reauth_tail(
monkeypatch,
tmp_path,
@@ -4899,7 +5280,7 @@ def test_concurrent_completed_hub_reauth_materializes_once(tmp_path):
raise ModelDiscoveryError("duplicate materialization")
self.discovery_started.set()
await self.release_discovery.wait()
- return ("claude-opus-4-6",)
+ return (DiscoveredModel(id="claude-opus-4-6"),)
store = MemoryStore()
adapter = BlockingDiscoveryAdapter()
@@ -5860,7 +6241,7 @@ def test_credential_route_carries_body_force_override_and_structured_guard(
service.named_agents_override = lambda backend: ([("claude", "claude-opus-4-6")] if backend == "claude" else [])
async def discover_narrower(vendor, protocol, base_url, credential_ref):
- return ("replacement-only-model",)
+ return (DiscoveredModel(id="replacement-only-model"),)
adapter.discover_models = discover_narrower
monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
@@ -6016,7 +6397,7 @@ def test_completed_hub_oauth_persists_only_a_response_proven_protocol(tmp_path):
authenticated=True,
protocol="openai_chat",
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=("gpt-5.6",),
+ models=(DiscoveredModel(id="gpt-5.6-sol"),),
)
result = asyncio.run(service.oauth_status(flow["flow_id"]))
@@ -6024,6 +6405,18 @@ def test_completed_hub_oauth_persists_only_a_response_proven_protocol(tmp_path):
assert result["source"]["protocol"] == "openai_chat"
assert store.config.sources[0].protocol == "openai_chat"
assert store.config.sources[0].credential_ref == "cred_oauth_proven"
+ assert store.config.sources[0].models[0].reasoning_efforts == [
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+ ]
+ assert (
+ store.config.sources[0].models[0].reasoning_efforts_source
+ == "catalog"
+ )
assert adapter.observed_protocol_orders == [SOURCE_PROTOCOLS]
assert adapter.revoked == []
@@ -6046,7 +6439,7 @@ def test_completed_hub_oauth_rejects_unproven_protocol_before_persistence(tmp_pa
authenticated=True,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
with pytest.raises(ModelHubError) as exc_info:
@@ -6647,7 +7040,7 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, t
assert accepted.status_code == 200
runtime = accepted.get_json()["runtime"]
assert adapter.start_calls == 1
- assert runtime["contract_version"] == 6
+ assert runtime["contract_version"] == 7
_assert_valid("runtime-dependency.schema.json", runtime)
@@ -6818,7 +7211,7 @@ def test_concurrent_source_creates_preserve_both_aggregate_updates(tmp_path):
if self.discover_started == 2:
self.all_discovering.set()
await self.all_discovering.wait()
- return ("claude-opus-4-6",)
+ return (DiscoveredModel(id="claude-opus-4-6"),)
store = MemoryStore()
adapter = ConcurrentAdapter()
@@ -7129,7 +7522,7 @@ def test_source_patch_rejects_credential_bearing_discovered_model_id(tmp_path):
)
async def credential_bearing_models(vendor, protocol, base_url, credential_ref):
- return ("sk-model-never-persist-this",)
+ return (DiscoveredModel(id="sk-model-never-persist-this"),)
adapter.discover_models = credential_bearing_models
with pytest.raises(ModelHubError) as exc_info:
@@ -7156,7 +7549,7 @@ def test_admitted_model_ids_are_stored_in_their_canonical_form(tmp_path):
service, store, adapter = _service(tmp_path)
async def padded_models(vendor, protocol, base_url, credential_ref):
- return (" discovered-model ",)
+ return (DiscoveredModel(id=" discovered-model "),)
adapter.discover_models = padded_models
source = asyncio.run(
@@ -7273,7 +7666,10 @@ def test_source_patch_rejects_one_discovered_model_under_two_spellings(tmp_path)
)
async def duplicate_spellings(vendor, protocol, base_url, credential_ref):
- return ("relay-model", " relay-model")
+ return (
+ DiscoveredModel(id="relay-model"),
+ DiscoveredModel(id=" relay-model"),
+ )
adapter.discover_models = duplicate_spellings
with pytest.raises(ModelHubError) as exc_info:
@@ -7309,7 +7705,7 @@ def test_base_url_change_guards_and_prunes_invalid_exact_hops(
async def discover_narrower(vendor, protocol, base_url, credential_ref):
discovery_refs.append(credential_ref)
- return ("replacement-only-model",)
+ return (DiscoveredModel(id="replacement-only-model"),)
adapter.discover_models = discover_narrower
monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index ff55523d7..efbbe671a 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -33,6 +33,7 @@ from config.v2_config import (
from core.handlers.model_hub.service import CONTRACT_VERSION
from core.services.settings import default_config
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
OBSERVATION_TERMINAL_RULES,
ObservationDiscovery,
ObservationOutcome,
@@ -40,7 +41,10 @@ from core.handlers.model_hub.adapter import (
SourceObservation,
validate_source_observation,
)
-from scripts.check_model_hub_authorities import check as check_model_hub_authorities
+from scripts.check_model_hub_authorities import (
+ AuthorityInput,
+ check as check_model_hub_authorities,
+)
from vibe import api
CONTRACTS = Path("docs/plans/model-hub-contracts")
@@ -104,7 +108,7 @@ def test_protocol_vocabulary_matches_authority_and_rejects_removed_alias():
def test_unsaved_observation_schema_closes_all_terminal_shapes():
schema = _schema("observation-result.schema.json")
- assert schema["properties"]["contract_version"]["const"] == 6
+ assert schema["properties"]["contract_version"]["const"] == 7
assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(
member.value for member in ObservationOutcome
)
@@ -128,7 +132,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
def payload(observation: SourceObservation) -> dict:
return {
- "contract_version": 6,
+ "contract_version": 7,
"outcome": observation.outcome.value,
"reachable": observation.reachable,
"authenticated": (
@@ -141,6 +145,17 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
"protocol": observation.protocol,
"discovery": observation.discovery.value,
"models": list(observation.model_ids),
+ "model_metadata": [
+ {
+ "id": model.id,
+ "supported_parameters": (
+ list(model.supported_parameters)
+ if model.supported_parameters is not None
+ else None
+ ),
+ }
+ for model in observation.models
+ ],
}
assert set(OBSERVATION_TERMINAL_RULES) == set(ObservationOutcome)
@@ -158,7 +173,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
authenticated=authenticated,
protocol=protocol,
discovery=discovery,
- model_ids=(),
+ models=(),
)
assert validate_source_observation(observation) is observation
schema.validate(payload(observation))
@@ -169,7 +184,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
authenticated=next(iter(rule.authenticated)),
protocol=next(iter(rule.protocols)),
discovery=next(iter(rule.discoveries)),
- model_ids=(),
+ models=(),
)
invalid_fields = {
"reachable": reachable_domain - rule.reachable,
@@ -189,7 +204,10 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
if rule.models_must_be_empty:
invalid_inventory = SourceObservation(
- **{**baseline.__dict__, "model_ids": ("model-id",)}
+ **{
+ **baseline.__dict__,
+ "models": (DiscoveredModel(id="model-id"),),
+ }
)
with pytest.raises(ValueError):
validate_source_observation(invalid_inventory)
@@ -200,7 +218,12 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
**{
**baseline.__dict__,
"discovery": ObservationDiscovery.SUCCEEDED,
- "model_ids": ("model-id",),
+ "models": (
+ DiscoveredModel(
+ id="model-id",
+ supported_parameters=("reasoning",),
+ ),
+ ),
}
)
assert validate_source_observation(succeeded) is succeeded
@@ -209,7 +232,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
**{
**baseline.__dict__,
"discovery": ObservationDiscovery.FAILED,
- "model_ids": ("model-id",),
+ "models": (DiscoveredModel(id="model-id"),),
}
)
with pytest.raises(ValueError):
@@ -228,6 +251,58 @@ def test_final_model_validator_requires_explicit_credential_free_efforts():
ModelHubModelConfig.from_payload(example)
+def test_source_model_reasoning_effort_provenance_round_trips_current_shape():
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ source["models"][0]["reasoning_efforts"] = ["low", "high"]
+ source["models"][0]["reasoning_efforts_source"] = "catalog"
+
+ parsed = ModelHubSourceConfig.from_payload(source)
+ serialized = parsed.to_payload()
+
+ assert serialized["models"][0]["reasoning_efforts_source"] == "catalog"
+ _assert_valid("source.schema.json", serialized)
+
+
+def test_released_v6_model_shape_infers_user_or_null_tier_provenance():
+ fixture = json.loads(
+ Path(
+ "tests/fixtures/model_hub/released_v6_reasoning_efforts.json"
+ ).read_text(encoding="utf-8")
+ )
+
+ models = [
+ ModelHubModelConfig.from_payload(model) for model in fixture["models"]
+ ]
+
+ assert models[0].reasoning_efforts_source == "user"
+ assert models[1].reasoning_efforts_source is None
+ assert models[0].to_payload()["reasoning_efforts_source"] == "user"
+ assert models[1].to_payload()["reasoning_efforts_source"] is None
+
+
+ ("efforts", "source"),
+ [
+ (["high"], None),
+ ([], "user"),
+ ([], "upstream"),
+ (["high"], "unknown"),
+ ],
+)
+def test_source_model_rejects_incoherent_tier_provenance(efforts, source):
+ model = {
+ "id": "model-a",
+ "display_name": None,
+ "origin": "manual",
+ "reasoning_efforts": efforts,
+ "reasoning_efforts_source": source,
+ "discovered_at": None,
+ }
+
+ with pytest.raises(ValueError):
+ ModelHubModelConfig.from_payload(model)
+
+
def test_discovered_model_retirement_is_persisted_without_rewriting_legacy_rows():
example = copy.deepcopy(_schema("source.schema.json")["examples"][0]["models"][0])
@@ -628,7 +703,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
route_refusal = {
"ok": False,
- "contract_version": 6,
+ "contract_version": 7,
"error": "source_in_route_chain",
"would_remove_hops": [hop],
"would_interrupt": [],
@@ -687,11 +762,11 @@ def test_agent_supply_contract_accepts_unmapped_native_alias_selection():
_assert_valid("agent-supply.schema.json", payload)
-def test_v5_mirror_registry_is_executable_and_complete():
+def test_v7_mirror_registry_is_executable_and_complete():
registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))
schemas = _mirror_schemas(registry)
- assert registry["contract_version"] == 6
+ assert registry["contract_version"] == 7
ids = [entry["id"] for entry in registry["entries"]]
assert ids
assert len(ids) == len(set(ids))
@@ -725,11 +800,14 @@ def test_every_versioned_object_ends_at_the_terminal_version_the_code_writes():
# a released build persisted, so it accepts the released values and ends at
# the terminal one. The `== [terminal]` branch is what keeps that from
# spreading to objects that never outlive their request.
- terminal = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))[
- "contract_version"
- ]
+ registry = json.loads(
+ (CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8")
+ )
+ terminal = registry["contract_version"]
assert CONTRACT_VERSION == terminal
- persisted = {"turn-provenance.schema.json"}
+ persisted = registry["contract_version_closure"][
+ "persisted_schema_version_floors"
+ ]
checked = set()
for path in sorted(CONTRACTS.glob("*.schema.json")):
for node in _versioned_nodes(json.loads(path.read_text(encoding="utf-8"))):
@@ -738,10 +816,12 @@ def test_every_versioned_object_ends_at_the_terminal_version_the_code_writes():
assert accepted == sorted(set(accepted)), path.name
assert accepted[-1] == terminal, path.name
if path.name in persisted:
- assert accepted[0] < terminal, path.name
+ assert accepted == list(
+ range(persisted[path.name], terminal + 1)
+ ), path.name
else:
assert accepted == [terminal], path.name
- assert persisted <= checked
+ assert set(persisted) <= checked
assert "api-response.schema.json" in checked
# The schemas above are structured, so their versions are read from the shape.
@@ -897,6 +977,38 @@ def test_model_hub_authority_closure_is_generated_from_live_files():
assert result["ok"], result["findings"]
+def test_model_hub_authority_closure_anchors_the_persisted_version_floor(monkeypatch):
+ original_json = AuthorityInput.json
+
+ def without_first_released_version(self, relative):
+ payload = original_json(self, relative)
+ if relative == "docs/plans/model-hub-contracts/turn-provenance.schema.json":
+ payload = copy.deepcopy(payload)
+ payload["properties"]["contract_version"]["enum"].remove(5)
+ return payload
+
+ monkeypatch.setattr(AuthorityInput, "json", without_first_released_version)
+
+ result = check_model_hub_authorities(Path.cwd())
+
+ assert not result["ok"]
+ assert {
+ "kind": "contract_version_schema_drift",
+ "domain": "V1",
+ "file": "docs/plans/model-hub-contracts/turn-provenance.schema.json",
+ "values": [6, 7],
+ "expected": [5, 6, 7],
+ } in result["findings"]
+
+
+def test_turn_provenance_contract_preserves_an_empty_stripped_effort():
+ payload = copy.deepcopy(_schema("turn-provenance.schema.json")["examples"][0])
+ payload["served"]["stripped_reasoning_efforts"] = [""]
+ payload["served"]["declared_reasoning_efforts"] = []
+
+ _assert_valid("turn-provenance.schema.json", payload)
+
+
def test_permission_denial_contract_has_no_fallback_member():
retired_reason = "permission_denied"
event_schema = _schema("resolution-event.schema.json")
@@ -1201,7 +1313,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
with pytest.raises(ValidationError):
chain_validator.validate(interrupted)
exact_hop = {
- "contract_version": 6,
+ "contract_version": 7,
"backend": "claude",
"model_id": "claude-opus-4-6",
"chain": [{
@@ -2290,6 +2402,42 @@ def test_config_reload_recovers_non_scalar_model_hub_enums(monkeypatch, tmp_path
assert loaded.load_warnings and "model_hub" in " ".join(loaded.load_warnings)
[email protected]("malformed_source", ([], {}), ids=("array", "object"))
+def test_config_reload_recovers_malformed_reasoning_tier_provenance_only(
+ monkeypatch,
+ tmp_path,
+ malformed_source,
+):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ payload = api.config_to_payload(
+ default_config(),
+ include_secrets=True,
+ include_internal=True,
+ )
+ source = copy.deepcopy(_schema("source.schema.json")["examples"][0])
+ source["models"][0]["reasoning_efforts_source"] = malformed_source
+ payload["model_hub"]["sources"] = [source]
+ payload["show_duration"] = True
+ payload["platform"] = "slack"
+ payload["platforms"] = {"enabled": ["slack"], "primary": "slack"}
+ payload["agents"]["codex"]["enabled"] = True
+ payload["agents"]["codex"]["cli_path"] = "/preserved/codex"
+ config_path = tmp_path / f"malformed-tier-source-{type(malformed_source).__name__}.json"
+ config_path.write_text(json.dumps(payload), encoding="utf-8")
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert loaded.show_duration is True
+ assert loaded.platform == "slack"
+ assert loaded.platforms.enabled == ["slack"]
+ assert loaded.agents.codex.enabled is True
+ assert loaded.agents.codex.cli_path == "/preserved/codex"
+ assert loaded.model_hub.to_payload() == V2Config.default().model_hub.to_payload()
+ assert loaded.recovered_sections == ("model_hub",)
+ assert loaded.whole_config_recovery is False
+ assert loaded.load_warnings and "model_hub" in loaded.load_warnings[0]
+
+
def test_client_config_recovery_projection_redacts_validator_details(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 45575e6e2..adf04e429 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -34,6 +34,7 @@ from config.v2_config import (
model_hub_fixed_menu_ids,
)
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
EngineHealth,
EngineStatus,
RawCallOutcome,
@@ -5600,7 +5601,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("upstream-model",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="upstream-model"),)),
) as inventory_probe,
):
observed = asyncio.run(
@@ -5627,7 +5628,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("upstream-model",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="upstream-model"),)),
) as inventory_probe,
):
ambiguous = asyncio.run(
@@ -5661,7 +5662,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("deepseek-chat",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="deepseek-chat"),)),
) as inventory_probe,
):
observed = asyncio.run(
@@ -5693,7 +5694,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("should-not-discover",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),
) as inventory_probe,
):
ambiguous = asyncio.run(
@@ -5725,7 +5726,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("should-not-discover",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),
) as inventory_probe,
):
ambiguous = asyncio.run(
@@ -5759,7 +5760,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("should-not-discover",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),
) as inventory_probe,
):
ambiguous = asyncio.run(
@@ -5795,7 +5796,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("should-not-discover",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),
) as inventory_probe,
):
ambiguous = asyncio.run(
@@ -5829,7 +5830,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("should-not-discover",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),
) as inventory_probe,
):
ambiguous = asyncio.run(
@@ -5868,7 +5869,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("should-not-discover",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),
) as inventory_probe,
):
ambiguous = asyncio.run(
@@ -5902,7 +5903,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("chat-only-model",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="chat-only-model"),)),
) as inventory_probe,
):
observed = asyncio.run(
@@ -5947,7 +5948,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("should-not-discover",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),
) as inventory_probe,
):
ambiguous = asyncio.run(
@@ -5981,7 +5982,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("relay-model",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="relay-model"),)),
) as inventory_probe,
):
observed = asyncio.run(
@@ -6013,7 +6014,9 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("anthropic-relay-model",)),
+ new=AsyncMock(
+ return_value=(DiscoveredModel(id="anthropic-relay-model"),)
+ ),
) as inventory_probe,
):
observed = asyncio.run(
@@ -6065,7 +6068,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("should-not-discover",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),
) as inventory_probe,
):
rejected = asyncio.run(
@@ -6090,7 +6093,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("should-not-discover",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),
) as inventory_probe,
):
ambiguous = asyncio.run(
@@ -6128,7 +6131,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("unverified-model",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="unverified-model"),)),
) as inventory_probe,
):
upstream_error = asyncio.run(
@@ -6149,13 +6152,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
_assert_valid(
"observation-result.schema.json",
{
- "contract_version": 6,
+ "contract_version": 7,
"outcome": "adapter_error",
"reachable": True,
"authenticated": "unknown",
"protocol": None,
"discovery": "not_attempted",
"models": [],
+ "model_metadata": [],
},
)
@@ -6173,7 +6177,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("upstream-model",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="upstream-model"),)),
) as inventory_probe,
):
observed = asyncio.run(
@@ -6207,7 +6211,9 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("later-protocol-model",)),
+ new=AsyncMock(
+ return_value=(DiscoveredModel(id="later-protocol-model"),)
+ ),
) as inventory_probe,
):
observed = asyncio.run(
@@ -6251,7 +6257,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
) as protocol_probe,
patch(
"vibe.model_hub_runtime.adapter.probe_models",
- new=AsyncMock(return_value=("unreachable-model",)),
+ new=AsyncMock(return_value=(DiscoveredModel(id="unreachable-model"),)),
) as inventory_probe,
):
rejected = asyncio.run(
@@ -6953,7 +6959,7 @@ def test_openai_probe_requests_are_mutually_distinguishable() -> None:
def test_model_discovery_preserves_query_when_appending_models_path() -> None:
query = "api-version=2026-07-23"
- async def scenario() -> tuple[str, str, tuple[str, ...]]:
+ async def scenario() -> tuple[str, str, tuple[DiscoveredModel, ...]]:
request_target: tuple[str, str] | None = None
async def list_models(request: web.Request) -> web.Response:
@@ -6985,7 +6991,7 @@ def test_model_discovery_preserves_query_when_appending_models_path() -> None:
assert path == "/v1/models"
assert request_query == query
- assert models == ("upstream-model",)
+ assert models == (DiscoveredModel(id="upstream-model"),)
def test_model_discovery_adds_standard_v1_path_to_a_bare_origin() -> None:
@@ -7527,7 +7533,7 @@ def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:
probe = asyncio.run(service.probe_agent("codex", "shared-model"))
assert probe == {
- "contract_version": 6,
+ "contract_version": 7,
"backend": "codex",
"channel": "native_cli",
"reachable": True,
@@ -7724,6 +7730,12 @@ def test_every_authoritative_reason_has_an_event_emission_path(reason: EventReas
from_source="src_reason01",
to_source="src_reason02",
)
+ elif reason in {"upstream_tiers", "catalog_tiers"}:
+ fields.update(
+ kind="reasoning_efforts_override",
+ model_id="model",
+ from_source="src_reason01",
+ )
elif reason == "recovery":
fields.update(kind="recover", to_source="src_reason01")
else:
diff --git a/tests/test_model_hub_reasoning_tiers.py b/tests/test_model_hub_reasoning_tiers.py
new file mode 100644
index 000000000..37bc23986
--- /dev/null
+++ b/tests/test_model_hub_reasoning_tiers.py
@@ -0,0 +1,98 @@
+from __future__ import annotations
+
+import pytest
+
+from core.handlers.model_hub import reasoning_tiers
+from core.handlers.model_hub.reasoning_tiers import resolve_reasoning_tiers
+from vibe.backend_model_catalog import PROTOCOL_REASONING_EFFORT_DEFAULTS
+
+
+ ("protocol", "expected"),
+ tuple(PROTOCOL_REASONING_EFFORT_DEFAULTS.items()),
+)
+def test_upstream_reasoning_signal_uses_only_the_protocol_default(
+ protocol: str,
+ expected: tuple[str, ...],
+) -> None:
+ resolution = resolve_reasoning_tiers(
+ protocol=protocol,
+ model_id="gpt-5.6-sol",
+ supported_parameters=("temperature", "reasoning"),
+ existing_efforts=("user-only",),
+ existing_source="user",
+ )
+
+ assert resolution.efforts == expected
+ assert resolution.source == "upstream"
+
+
+def test_catalog_row_outranks_user_and_is_returned_verbatim() -> None:
+ resolution = resolve_reasoning_tiers(
+ protocol="openai_responses",
+ model_id="gpt-5.6-sol",
+ existing_efforts=("user-only",),
+ existing_source="user",
+ )
+
+ assert resolution.efforts == (
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+ )
+ assert resolution.source == "catalog"
+
+
+def test_catalog_row_is_not_filtered_through_the_vocabulary(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ reasoning_tiers,
+ "bundled_catalog_reasoning_efforts_for_model",
+ lambda _model_id: pytest.fail("injected catalog index was ignored"),
+ )
+
+ resolution = resolve_reasoning_tiers(
+ protocol="openai_chat",
+ model_id="future-model",
+ catalog_efforts_by_model={"future-model": ("future-effort",)},
+ )
+
+ assert resolution.efforts == ("future-effort",)
+ assert resolution.source == "catalog"
+
+
+def test_user_tiers_survive_only_when_no_managed_rung_applies() -> None:
+ preserved = resolve_reasoning_tiers(
+ protocol="anthropic",
+ model_id="relay-model",
+ supported_parameters=("temperature",),
+ existing_efforts=("careful", "turbo"),
+ existing_source="user",
+ )
+ empty = resolve_reasoning_tiers(
+ protocol="anthropic",
+ model_id="relay-model",
+ supported_parameters=(),
+ )
+
+ assert preserved.efforts == ("careful", "turbo")
+ assert preserved.source == "user"
+ assert empty.efforts == ()
+ assert empty.source is None
+
+
[email protected]("parameter", ("reasoning", "reasoning_effort"))
+def test_upstream_reasoning_parameter_matching_is_case_and_space_tolerant(
+ parameter: str,
+) -> None:
+ resolution = resolve_reasoning_tiers(
+ protocol="openai_chat",
+ model_id="relay-model",
+ supported_parameters=(f" {parameter.upper()} ",),
+ )
+
+ assert resolution.source == "upstream"
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 1d5fcc1fd..8b1858563 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import hashlib
import json
from collections import deque
from datetime import datetime, timezone
@@ -22,6 +23,7 @@ from config.v2_config import (
ModelHubSourceStateConfig,
)
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
EngineHealth,
EngineStatus,
ObservationDiscovery,
@@ -37,7 +39,10 @@ from core.handlers.model_hub.classification import (
source_settlement_allowed,
terminal_outcome_category,
)
-from core.handlers.model_hub.events import BoundedEventLog
+from core.handlers.model_hub.events import (
+ BoundedEventLog,
+ redact_credential_material,
+)
from core.handlers.model_hub.errors import ModelDiscoveryError
from core.handlers.model_hub.provenance import (
TurnSupplyBlocker,
@@ -239,7 +244,7 @@ class FakeAdapter:
await self.discovery_block.wait()
if self.discovery_error is not None:
raise self.discovery_error
- return self.discovered
+ return tuple(DiscoveredModel(id=model_id) for model_id in self.discovered)
async def observe_source(self, vendor, base_url, credential_ref, protocol_order):
self.observed_protocol_orders.append(tuple(protocol_order))
@@ -255,7 +260,7 @@ class FakeAdapter:
authenticated=True,
protocol=protocol_order[0],
discovery=ObservationDiscovery.SUCCEEDED,
- model_ids=self.discovered,
+ models=tuple(DiscoveredModel(id=model_id) for model_id in self.discovered),
)
async def invoke(self, source_id, model_id, request, stream, origin):
@@ -613,7 +618,7 @@ def test_machine_permission_denial_precedes_every_status_heuristic(
backend="claude",
model_id="claude-opus-4-6",
request={},
- attempt_observer=lambda *args: decisions.append(args[-1]),
+ attempt_observer=lambda *args: decisions.append(args[5]),
)
)
@@ -874,12 +879,14 @@ def test_runtime_filters_reasoning_effort_for_each_exact_hop(tmp_path):
protocol="openai_responses",
headers={"x-test": "preserved"},
)
+ observed_attempts = []
resolved = asyncio.run(
service.resolve(
backend="claude",
model_id="claude-opus-4-6",
request=request,
+ attempt_observer=lambda *args: observed_attempts.append(args),
)
)
@@ -891,6 +898,10 @@ def test_runtime_filters_reasoning_effort_for_each_exact_hop(tmp_path):
assert adapter.invocation_requests[1]["reasoning"] == {"summary": "auto"}
assert adapter.invocation_requests[1].protocol == "openai_responses"
assert adapter.invocation_requests[1].headers == {"x-test": "preserved"}
+ started = [attempt for attempt in observed_attempts if attempt[4] is None]
+ assert [attempt[0] for attempt in started] == [first.id, second.id]
+ assert started[0][6:] == ((), ())
+ assert started[1][6:] == (("high",), ("low",))
def test_runtime_omits_unsupported_direct_reasoning_effort(tmp_path):
@@ -932,6 +943,154 @@ def test_runtime_omits_unsupported_direct_reasoning_effort(tmp_path):
assert adapter.invocation_requests[0].headers == {"x-test": "preserved"}
+def test_reasoning_effort_strip_log_redacts_values_and_names_declared_tiers(
+ tmp_path,
+ caplog,
+):
+ source = _source("src_effortlog1", ("upstream-model",))
+ source.models[0].reasoning_efforts = ["low", "high"]
+ config = _config([source])
+ config.agents["claude"].routes["claude-opus-4-6"] = ModelHubRouteConfig(
+ hops=(ModelHubRouteHopConfig(source.id, "upstream-model"),)
+ )
+ adapter = FakeAdapter()
+ adapter.outcomes.append(
+ RawCallOutcome(
+ kind=RawOutcomeKind.SUCCESS,
+ http_status=200,
+ error_code=None,
+ redacted_message=None,
+ stream_started=False,
+ model_id="upstream-model",
+ source_id=source.id,
+ )
+ )
+ service, _store, _ = _service(tmp_path, config, adapter)
+
+ with caplog.at_level("INFO", logger="core.handlers.model_hub.service"):
+ asyncio.run(
+ service.resolve(
+ backend="claude",
+ model_id="claude-opus-4-6",
+ request={
+ "reasoning_effort": (
+ "authorization: sk-test-strip-secret-material"
+ )
+ },
+ )
+ )
+
+ assert "sk-test-strip-secret-material" not in caplog.text
+ assert "[redacted]" in caplog.text
+ assert "declared tiers: ['low', 'high']" in caplog.text
+
+
+def test_reasoning_effort_telemetry_is_utf8_bounded_after_redaction(caplog):
+ source = _source("src_effortbound", ("upstream-model",))
+ long_declared = "层级" * 200
+ source.models[0].reasoning_efforts = ["low", long_declared]
+ long_stripped = (
+ "深度" * 200 + " authorization: sk-test-strip-secret-material"
+ )
+
+ with caplog.at_level("INFO", logger="core.handlers.model_hub.service"):
+ result = ModelHubService._request_for_exact_reasoning_effort(
+ {"reasoning_effort": long_stripped},
+ source,
+ "upstream-model",
+ )
+
+ [stripped] = result.stripped_efforts
+ [declared] = result.declared_efforts
+ safe_stripped = redact_credential_material(long_stripped)
+ stripped_digest = hashlib.sha256(safe_stripped.encode("utf-8")).hexdigest()
+ declared_payload = json.dumps(
+ ("low", long_declared),
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ declared_digest = hashlib.sha256(declared_payload.encode("utf-8")).hexdigest()
+ assert len(stripped.encode("utf-8")) <= 256
+ assert len(declared.encode("utf-8")) <= 256
+ assert stripped.endswith(f"[sha256:{stripped_digest}]")
+ assert declared.endswith(f"[sha256:{declared_digest}]")
+ assert hashlib.sha256(long_stripped.encode("utf-8")).hexdigest() not in stripped
+ assert long_stripped not in caplog.text
+ assert long_declared not in caplog.text
+ assert "sk-test-strip-secret-material" not in caplog.text
+ assert stripped in caplog.text
+ assert declared in caplog.text
+
+
+def test_reasoning_effort_telemetry_bounds_many_short_declared_tiers():
+ source = _source("src_effortmany", ("upstream-model",))
+ source.models[0].reasoning_efforts = [
+ f"tier-{index:04d}" for index in range(1_000)
+ ]
+
+ result = ModelHubService._request_for_exact_reasoning_effort(
+ {"reasoning_effort": "undeclared"},
+ source,
+ "upstream-model",
+ )
+
+ [declared] = result.declared_efforts
+ assert len(declared.encode("utf-8")) <= 256
+ assert declared.endswith("]")
+ assert "[sha256:" in declared
+
+
+def test_reasoning_effort_telemetry_preserves_short_values_exactly():
+ source = _source("src_effortshort", ("upstream-model",))
+ source.models[0].reasoning_efforts = ["low", "high"]
+
+ result = ModelHubService._request_for_exact_reasoning_effort(
+ {"reasoning_effort": "ultra"},
+ source,
+ "upstream-model",
+ )
+
+ assert result.stripped_efforts == ("ultra",)
+ assert result.declared_efforts == ("low", "high")
+
+
+ ("request_payload", "expected_request", "expected_stripped"),
+ [
+ ({"reasoning_effort": ""}, {}, ("",)),
+ ({"reasoning_effort": 7}, {}, ("<int>",)),
+ (
+ {"reasoning": {"effort": ["high"], "summary": "auto"}},
+ {"reasoning": {"summary": "auto"}},
+ ("<list>",),
+ ),
+ (
+ {"reasoning": {"effort": None}},
+ {},
+ ("<null>",),
+ ),
+ ],
+ ids=("direct-empty", "direct-int", "nested-list", "nested-null"),
+)
+def test_reasoning_effort_telemetry_records_every_stripped_value(
+ request_payload,
+ expected_request,
+ expected_stripped,
+):
+ source = _source("src_efforttype", ("upstream-model",))
+ source.models[0].reasoning_efforts = ["high"]
+
+ result = ModelHubService._request_for_exact_reasoning_effort(
+ request_payload,
+ source,
+ "upstream-model",
+ )
+
+ assert result.request == expected_request
+ assert result.stripped_efforts == expected_stripped
+ assert result.declared_efforts == ("high",)
+
+
def test_runtime_filters_reasoning_effort_forms_independently(tmp_path):
source = _source("src_effort004", ("upstream-model",))
source.models[0].reasoning_efforts = ["high"]
@@ -1800,7 +1959,7 @@ def test_ambiguous_observation_never_creates_a_source(tmp_path):
authenticated=True,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)
@@ -1829,7 +1988,7 @@ def test_authentication_failure_observation_never_creates_a_source(tmp_path):
authenticated=False,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)
@@ -1858,7 +2017,7 @@ def test_create_failure_preserves_human_safe_observation_detail(tmp_path):
authenticated=False,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
service, store, _ = _service(tmp_path, ModelHubConfig(), adapter)
@@ -1881,7 +2040,7 @@ def test_create_failure_preserves_human_safe_observation_detail(tmp_path):
authenticated=False,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
),
ObservationOutcome.AUTHENTICATION_FAILED,
),
@@ -1923,7 +2082,7 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):
authenticated=None,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
service, _, _ = _service(tmp_path, ModelHubConfig(), adapter)
@@ -1938,13 +2097,14 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):
)
assert result["observation"] == {
- "contract_version": 6,
+ "contract_version": 7,
"outcome": "adapter_error",
"reachable": True,
"authenticated": "unknown",
"protocol": None,
"discovery": "not_attempted",
"models": [],
+ "model_metadata": [],
}
@@ -1968,13 +2128,14 @@ def test_unknown_adapter_error_does_not_claim_connection(tmp_path):
assert exc.value.code == "discovery_failed"
assert exc.value.detail == "modelHub.errors.adapter_error"
assert exc.value.data["observation"] == {
- "contract_version": 6,
+ "contract_version": 7,
"outcome": "adapter_error",
"reachable": None,
"authenticated": "unknown",
"protocol": None,
"discovery": "not_attempted",
"models": [],
+ "model_metadata": [],
}
assert store.load().sources == []
assert adapter.revoked == ["cred_00000001"]
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index a9d00cec5..89aa79466 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -22,6 +22,7 @@ from jsonschema import Draft7Validator
from core import managed_runtime
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
EngineHealth,
OriginNotAllowedError,
RawOutcomeKind,
@@ -1150,7 +1151,7 @@ def test_manifest_resolution_drives_admission_persistence_and_schema(
installer=manager,
state_store=EngineStateStore(tmp_path / "state"),
)
- projected = {"contract_version": 6, **supervisor.status()}
+ projected = {"contract_version": 7, **supervisor.status()}
schema = json.loads(
Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(
encoding="utf-8"
@@ -1632,10 +1633,10 @@ def test_model_inventory_duplicate_top_level_members_replace_earlier_values() ->
assert projected == (
True,
True,
- ["live-data"],
+ [DiscoveredModel(id="live-data")],
True,
True,
- ["live-models"],
+ [DiscoveredModel(id="live-models")],
)
@@ -1650,13 +1651,123 @@ def test_model_inventory_duplicate_item_id_keeps_the_final_member() -> None:
assert projected == (
True,
True,
- ["live", "other"],
+ [DiscoveredModel(id="live"), DiscoveredModel(id="other")],
False,
False,
[],
)
+ ("member", "result_index"),
+ (("data", 2), ("models", 5)),
+)
+def test_model_inventory_captures_supported_parameters_from_both_shapes(
+ member: str,
+ result_index: int,
+) -> None:
+ payload = json.dumps(
+ {
+ member: [
+ {
+ "id": "reasoning-model",
+ "supported_parameters": ["reasoning", "temperature"],
+ }
+ ]
+ }
+ ).encode()
+
+ projected = client_module._project_model_inventory(io.BytesIO(payload))
+
+ assert projected is not None
+ assert projected[result_index] == [
+ DiscoveredModel(
+ id="reasoning-model",
+ supported_parameters=("reasoning", "temperature"),
+ )
+ ]
+
+
+def test_model_inventory_distinguishes_absent_and_empty_supported_parameters() -> None:
+ projected = client_module._project_model_inventory(
+ io.BytesIO(
+ b'{"data":['
+ b'{"id":"absent"},'
+ b'{"id":"empty","supported_parameters":[]}'
+ b']}'
+ )
+ )
+
+ assert projected is not None
+ assert projected[2] == [
+ DiscoveredModel(id="absent", supported_parameters=None),
+ DiscoveredModel(id="empty", supported_parameters=()),
+ ]
+
+
+ "malformed",
+ (
+ '"reasoning"',
+ '["reasoning", 7]',
+ '["reasoning", {"name":"temperature"}]',
+ '["reasoning", ""]',
+ ),
+)
+def test_model_inventory_degrades_malformed_supported_parameters_without_losing_id(
+ malformed: str,
+) -> None:
+ projected = client_module._project_model_inventory(
+ io.BytesIO(
+ (
+ '{"data":[{"id":"kept-model","supported_parameters":'
+ f"{malformed}"
+ "}]}"
+ ).encode()
+ )
+ )
+
+ assert projected is not None
+ assert projected[2] == [DiscoveredModel(id="kept-model")]
+
+
+def test_model_inventory_duplicate_metadata_member_replaces_its_own_scope() -> None:
+ projected = client_module._project_model_inventory(
+ io.BytesIO(
+ b'{"data":['
+ b'{"id":"first","supported_parameters":["stale"],'
+ b'"supported_parameters":["reasoning","reasoning","temperature"]},'
+ b'{"id":"second","supported_parameters":["tools"]}'
+ b']}'
+ )
+ )
+
+ assert projected is not None
+ assert projected[2] == [
+ DiscoveredModel(
+ id="first",
+ supported_parameters=("reasoning", "temperature"),
+ ),
+ DiscoveredModel(id="second", supported_parameters=("tools",)),
+ ]
+
+
+def test_model_inventory_duplicate_ids_keep_the_first_complete_record() -> None:
+ projected = client_module._project_model_inventory(
+ io.BytesIO(
+ b'{"data":['
+ b'{"id":"same","supported_parameters":["temperature"]},'
+ b'{"id":"same","supported_parameters":["reasoning"]}'
+ b']}'
+ )
+ )
+
+ assert projected is not None
+ assert projected[2] == [
+ DiscoveredModel(id="same", supported_parameters=("temperature",))
+ ]
+
+
def test_model_inventory_rejects_an_elided_model_identifier() -> None:
oversized = b"x" * (16 * 1024 + 1)
@@ -1695,7 +1806,10 @@ def test_adapter_provisions_probes_and_revokes_credential(tmp_path: Path) -> Non
credential_ref,
)
- assert models == ("model-a", "model-b")
+ assert models == (
+ DiscoveredModel(id="model-a"),
+ DiscoveredModel(id="model-b"),
+ )
assert handler.authorization == "Bearer probe-secret"
with pytest.raises(EngineStateError, match="does not match"):
await adapter.discover_models(
@@ -5534,7 +5648,7 @@ def test_model_discovery_accepts_large_valid_inventory(
protocol="openai_responses",
base_url="https://api.example.test/v1",
secret="secret",
- ) == ("model-a",)
+ ) == (DiscoveredModel(id="model-a"),)
asyncio.run(run())
@@ -5745,9 +5859,25 @@ def test_oauth_model_discovery_accepts_engine_definition_fields(tmp_path: Path)
assert query == {"name": "claude-account.json"}
return {
"models": [
- {"id": "model-id", "alias": "ignored-alias"},
- {"alias": "model-alias", "name": "ignored-name"},
- {"name": "model-name"},
+ {
+ "id": "model-id",
+ "alias": "ignored-alias",
+ "supported_parameters": [
+ "reasoning",
+ "temperature",
+ "reasoning",
+ ],
+ },
+ {
+ "alias": "model-alias",
+ "name": "ignored-name",
+ "supported_parameters": ["reasoning", 7],
+ },
+ {"name": "model-name", "supported_parameters": []},
+ {
+ "id": "model-id",
+ "supported_parameters": ["ignored-duplicate"],
+ },
]
}
@@ -5779,7 +5909,14 @@ def test_oauth_model_discovery_accepts_engine_definition_fields(tmp_path: Path)
credential_ref,
)
- assert models == ("model-id", "model-alias", "model-name")
+ assert models == (
+ DiscoveredModel(
+ id="model-id",
+ supported_parameters=("reasoning", "temperature"),
+ ),
+ DiscoveredModel(id="model-alias"),
+ DiscoveredModel(id="model-name", supported_parameters=()),
+ )
asyncio.run(run())
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 6c389476c..9aa7aedf6 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -42,6 +42,7 @@ ROOT = Path(__file__).parents[1]
DEEP_JSON_ARRAY = b"[" * 10_000 + b"0" + b"]" * 10_000
TURN_GATEWAY = ROOT / "core/handlers/model_hub/turn_gateway.py"
SERVICE = ROOT / "core/handlers/model_hub/service.py"
+MIGRATION = ROOT / "core/handlers/model_hub/migration.py"
USAGE = ROOT / "core/handlers/model_hub/usage.py"
RPC = ROOT / "core/handlers/model_hub/rpc.py"
V2_CONFIG = ROOT / "config/v2_config.py"
@@ -1166,6 +1167,44 @@ def test_machine_error_extractor_reads_only_declared_envelope_paths() -> None:
)
+def test_reasoning_tier_resolver_call_inventory_requires_batch_indexes() -> None:
+ expected = {
+ ("service.py", "apply_tiers"): True,
+ ("service.py", "_create_oauth_source"): True,
+ ("service.py", "create_source"): True,
+ ("service.py", "_apply_reasoning_tier_ladder"): False,
+ ("migration.py", "_validated_source"): True,
+ ("migration.py", "apply_native_migration"): True,
+ }
+ calls_by_owner: dict[tuple[str, str | None], list[ast.Call]] = {}
+ for path in (SERVICE, MIGRATION):
+ tree = _tree(path)
+ parents = _parents(tree)
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call) or _call_name(node) != "resolve_reasoning_tiers":
+ continue
+ key = (path.name, _owner_name(node, parents))
+ calls_by_owner.setdefault(key, []).append(node)
+
+ assert set(calls_by_owner) == set(expected)
+ assert all(len(calls) == 1 for calls in calls_by_owner.values())
+ for key, needs_batch_index in expected.items():
+ [call] = calls_by_owner[key]
+ injected = next(
+ (
+ keyword.value
+ for keyword in call.keywords
+ if keyword.arg == "catalog_efforts_by_model"
+ ),
+ None,
+ )
+ if needs_batch_index:
+ assert isinstance(injected, ast.Name)
+ assert injected.id == "catalog_efforts_by_model"
+ else:
+ assert injected is None
+
+
def test_settlement_abandonment_cannot_overwrite_a_committed_terminal_fact() -> None:
tree = _tree(TURN_GATEWAY)
abandon = ast.get_source_segment(
diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsx
index 963a322ea..c8556e25f 100644
--- a/ui/src/components/settings/models/AgentCard.test.tsx
+++ b/ui/src/components/settings/models/AgentCard.test.tsx
@@ -16,7 +16,7 @@ import { freshRuntimeProjection } from './runtimeLifecycle';
import type { AgentSupply, RuntimeDependency, Source } from './types';
const runtime: RuntimeDependency = {
- contract_version: 6,
+ contract_version: 7,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },
};
@@ -181,7 +181,7 @@ describe('AgentCard', () => {
['zh', 'Backup → claude-opus-4-6(已自动切换)', '打开 claude-opus-4-6 的路由 · Backup → claude-opus-4-6(已自动切换)'],
] as const)('derives and announces takeover from the exact current hop in %s', (lng, mappingCopy, accessibleName) => {
const key = modelChainKey('claude', 'claude-opus-4-6');
- render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 6, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 7, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.getByText(/Backup/)).toBeTruthy();
expect(screen.getByTitle(mappingCopy)).toBeTruthy();
expect(screen.getByRole('button', { name: accessibleName })).toBeTruthy();
@@ -199,7 +199,7 @@ describe('AgentCard', () => {
sources={[source('src_b', 'Backup source')]}
chains={{
[key]: readyRegion({
- contract_version: 6,
+ contract_version: 7,
backend: 'claude',
model_id: 'claude-opus-4-6',
current: { source_id: 'src_b', model_id: 'routed-opus' },
@@ -228,7 +228,7 @@ describe('AgentCard', () => {
it('does not call a later current hop takeover unless the head is unavailable for cooldown', () => {
const key = modelChainKey('claude', 'claude-opus-4-6');
- render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 6, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 7, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.getByText(/Backup/)).toBeTruthy();
expect(screen.queryByText(/takeover/i)).toBeNull();
});
@@ -236,7 +236,7 @@ describe('AgentCard', () => {
it('hides current and takeover projections while the runtime is stopped', () => {
const key = modelChainKey('claude', 'claude-opus-4-6');
const stopped = { ...runtime, status: { ...runtime.status, health: 'down' as const } };
- render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 6, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 7, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.queryByText(/Backup/)).toBeNull();
expect(screen.queryByText(/takeover/i)).toBeNull();
@@ -247,7 +247,7 @@ describe('AgentCard', () => {
const onOpenModels = vi.fn();
const key = modelChainKey('claude', 'claude-opus-4-6');
const directAgent: AgentSupply = { ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null };
- render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 6, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ contract_version: 7, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.queryByText(/Adjust priority/i)).toBeNull();
expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();
expect(screen.queryByText(/Backup/)).toBeNull();
diff --git a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
index 166240b59..d8706cd50 100644
--- a/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
+++ b/ui/src/components/settings/models/EnableGatewayDialog.test.tsx
@@ -34,7 +34,7 @@ const runtime = (
? 'unresolved' as const
: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;
return {
- contract_version: 6,
+ contract_version: 7,
...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
index 661964e2f..506d4e033 100644
--- a/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
+++ b/ui/src/components/settings/models/InstallGatewayDialog.test.tsx
@@ -10,7 +10,7 @@ import { modelsApi } from './modelsApi';
import type { RuntimeDependency } from './types';
const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({
- contract_version: 6,
+ contract_version: 7,
manifest: {
name: 'cliproxyapi',
resolution: 'resolved',
diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsx
index 8468ca0de..2424f0dcb 100644
--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx
@@ -52,7 +52,7 @@ const sources: Source[] = [
},
];
const chain: AgentChain = {
- contract_version: 6,
+ contract_version: 7,
backend: "claude",
model_id: "opus-5",
current: { source_id: "src_b", model_id: "opus-5" },
diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
index f6396598d..407475d14 100644
--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
@@ -31,7 +31,7 @@ const runtime = (
? 'unresolved' as const
: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;
return {
- contract_version: 6,
+ contract_version: 7,
...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 5843a6419..f41d8dd6d 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -23,7 +23,7 @@ const directAgent = (backend: AgentBackend): AgentSupply => ({
});
const runtime: RuntimeDependency = {
- contract_version: 6,
+ contract_version: 7,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },
status: { installed_version: '1', verified: true, health: 'ok' },
};
@@ -74,7 +74,7 @@ const takeoverAgent: AgentSupply = {
};
const takeoverChain: AgentChain = {
- contract_version: 6,
+ contract_version: 7,
backend: 'codex',
model_id: 'gpt-5.6-sol',
current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },
@@ -995,7 +995,7 @@ describe('SettingsModelsPage surface branches', () => {
builtin_models: [modelId],
};
const affectedChain: AgentChain = {
- contract_version: 6,
+ contract_version: 7,
backend: 'claude',
model_id: modelId,
current: { source_id: retainedSource.id, model_id: modelId },
diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.ts
index 59d1e88f2..2e627c9b2 100644
--- a/ui/src/components/settings/models/SupplyGraph.test.ts
+++ b/ui/src/components/settings/models/SupplyGraph.test.ts
@@ -7,7 +7,7 @@ import { buildSupplyRelations as buildRelations } from './supplyRelations';
import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './types';
const runtime: RuntimeDependency = {
- contract_version: 6,
+ contract_version: 7,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },
};
@@ -47,7 +47,7 @@ const agent: AgentSupply = {
};
const chain = (current: string, headHealth: AgentChain['chain'][number]['health'] = 'healthy', headRunnable = true, reason: AgentChain['chain'][number]['reason'] = null): AgentChain => ({
- contract_version: 6,
+ contract_version: 7,
backend: 'claude',
model_id: 'model-a',
current: { source_id: current, model_id: 'model-a' },
diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.ts
index 7f5b8b1f8..14bfb8914 100644
--- a/ui/src/components/settings/models/apiFailure.test.ts
+++ b/ui/src/components/settings/models/apiFailure.test.ts
@@ -33,7 +33,7 @@ afterEach(() => {
describe('apiFailure — whether the route named the failure', () => {
it('posts installation to the dedicated runtime route', async () => {
const runtime = {
- contract_version: 6,
+ contract_version: 7,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'sha', assets: [] },
status: { installed_version: null, verified: false, listening: null, health: 'installing', last_check: null },
} as const;
diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.ts
index ddae21d76..bcf7702cb 100644
--- a/ui/src/components/settings/models/gatewayAdoption.test.ts
+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts
@@ -14,7 +14,7 @@ const agent = (mode: AgentSupply['mode']): AgentSupply => ({
});
const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({
- contract_version: 6,
+ contract_version: 7,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },
status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },
});
diff --git a/ui/src/components/settings/models/mockData.ts b/ui/src/components/settings/models/mockData.ts
index 3ad73dbd8..73bad80bd 100644
--- a/ui/src/components/settings/models/mockData.ts
+++ b/ui/src/components/settings/models/mockData.ts
@@ -1,4 +1,10 @@
// Typed source fixtures retained only for the source schema contract test.
+//
+// Every model carries `reasoning_efforts_source`, and between them the five
+// sources spell out all four rungs of the provenance ladder: `upstream`,
+// `catalog`, `user`, and an explicit `null`. Each list matches what its rung
+// really produces: exact catalog rows, protocol-family upstream defaults,
+// arbitrary user declarations, or an empty undeclared list.
import type { Source } from './types';
const iso = (offsetMs: number) => new Date(Date.now() + offsetMs).toISOString();
@@ -24,9 +30,9 @@ export function buildMockSources(): Source[] {
account_label: '[email protected]',
masked_credential: null,
models: [
- { id: 'claude-opus-4-6', display_name: 'Opus 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },
- { id: 'claude-sonnet-4-6', display_name: 'Sonnet 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },
- { id: 'claude-haiku-4-5', display_name: 'Haiku 4.5', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },
+ { id: 'claude-opus-4-6', display_name: 'Opus 4.6', origin: 'discovered', reasoning_efforts: ['low', 'medium', 'high', 'max'], reasoning_efforts_source: 'catalog', discovered_at: iso(-3 * HOUR) },
+ { id: 'claude-sonnet-4-6', display_name: 'Sonnet 4.6', origin: 'discovered', reasoning_efforts: ['low', 'medium', 'high', 'max'], reasoning_efforts_source: 'catalog', discovered_at: iso(-3 * HOUR) },
+ { id: 'claude-haiku-4-5', display_name: 'Haiku 4.5', origin: 'discovered', reasoning_efforts: ['low', 'medium', 'high'], reasoning_efforts_source: 'catalog', discovered_at: iso(-3 * HOUR) },
],
credential_ref: null,
},
@@ -46,8 +52,8 @@ export function buildMockSources(): Source[] {
account_label: '[email protected]',
masked_credential: null,
models: [
- { id: 'gpt-5.6', display_name: 'GPT-5.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },
- { id: 'gpt-5.6-mini', display_name: 'GPT-5.6 mini', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-3 * HOUR) },
+ { id: 'gpt-5.6', display_name: 'GPT-5.6', origin: 'discovered', reasoning_efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'], reasoning_efforts_source: 'upstream', discovered_at: iso(-3 * HOUR) },
+ { id: 'gpt-5.6-mini', display_name: 'GPT-5.6 mini', origin: 'discovered', reasoning_efforts: ['minimal', 'low', 'medium', 'high', 'xhigh'], reasoning_efforts_source: 'upstream', discovered_at: iso(-3 * HOUR) },
],
credential_ref: null,
},
@@ -67,9 +73,9 @@ export function buildMockSources(): Source[] {
account_label: null,
masked_credential: 'sk-ant-…8f2A',
models: [
- { id: 'claude-opus-4-6', display_name: 'Opus 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },
- { id: 'claude-sonnet-4-6', display_name: 'Sonnet 4.6', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },
- { id: 'claude-haiku-4-5', display_name: 'Haiku 4.5', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },
+ { id: 'claude-opus-4-6', display_name: 'Opus 4.6', origin: 'discovered', reasoning_efforts: ['low', 'medium', 'high', 'xhigh', 'max'], reasoning_efforts_source: 'upstream', discovered_at: iso(-6 * HOUR) },
+ { id: 'claude-sonnet-4-6', display_name: 'Sonnet 4.6', origin: 'discovered', reasoning_efforts: ['low', 'medium', 'high', 'xhigh', 'max'], reasoning_efforts_source: 'upstream', discovered_at: iso(-6 * HOUR) },
+ { id: 'claude-haiku-4-5', display_name: 'Haiku 4.5', origin: 'discovered', reasoning_efforts: ['low', 'medium', 'high', 'xhigh', 'max'], reasoning_efforts_source: 'upstream', discovered_at: iso(-6 * HOUR) },
],
credential_ref: 'cred_anth01',
},
@@ -89,10 +95,10 @@ export function buildMockSources(): Source[] {
account_label: null,
masked_credential: 'glm-…c31b',
models: [
- { id: 'glm-5.2', display_name: 'GLM 5.2', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },
- { id: 'glm-5.2-air', display_name: 'GLM 5.2 Air', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },
- { id: 'glm-5-flash', display_name: 'GLM 5 Flash', origin: 'discovered', reasoning_efforts: [], discovered_at: iso(-6 * HOUR) },
- { id: 'glm-5.2-pro', display_name: 'GLM 5.2 Pro', origin: 'manual', reasoning_efforts: [], discovered_at: null },
+ { id: 'glm-5.2', display_name: 'GLM 5.2', origin: 'discovered', reasoning_efforts: ['low', 'high'], reasoning_efforts_source: 'user', discovered_at: iso(-6 * HOUR) },
+ { id: 'glm-5.2-air', display_name: 'GLM 5.2 Air', origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null, discovered_at: iso(-6 * HOUR) },
+ { id: 'glm-5-flash', display_name: 'GLM 5 Flash', origin: 'discovered', reasoning_efforts: [], reasoning_efforts_source: null, discovered_at: iso(-6 * HOUR) },
+ { id: 'glm-5.2-pro', display_name: 'GLM 5.2 Pro', origin: 'manual', reasoning_efforts: ['medium', 'high'], reasoning_efforts_source: 'user', discovered_at: null },
],
credential_ref: 'cred_zhipu01',
},
@@ -115,7 +121,7 @@ export function buildMockSources(): Source[] {
account_label: null,
masked_credential: 'key …9c1',
models: [
- { id: 'glm-5.2-air', display_name: 'GLM 5.2 Air', origin: 'manual', reasoning_efforts: [], discovered_at: null },
+ { id: 'glm-5.2-air', display_name: 'GLM 5.2 Air', origin: 'manual', reasoning_efforts: [], reasoning_efforts_source: null, discovered_at: null },
],
credential_ref: 'cred_relay01',
},
diff --git a/ui/src/components/settings/models/runtimeLifecycle.test.ts b/ui/src/components/settings/models/runtimeLifecycle.test.ts
index a13e40e09..3e9cae651 100644
--- a/ui/src/components/settings/models/runtimeLifecycle.test.ts
+++ b/ui/src/components/settings/models/runtimeLifecycle.test.ts
@@ -11,7 +11,7 @@ const asset = (platform: 'darwin-arm64' | 'linux-amd64') => ({
});
const runtime = (resolution: 'resolved' | 'unresolved' | 'unsupported'): RuntimeDependency => ({
- contract_version: 6,
+ contract_version: 7,
host_platform: 'darwin-arm64',
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/sourceModelContract.test.ts b/ui/src/components/settings/models/sourceModelContract.test.ts
index b32e82b99..fa977dc9a 100644
--- a/ui/src/components/settings/models/sourceModelContract.test.ts
+++ b/ui/src/components/settings/models/sourceModelContract.test.ts
@@ -28,7 +28,9 @@ describe('Source model wire contract', () => {
for (const field of enumeratedFields) {
expect(new Set(models.map((model) => model[field as keyof typeof model])))
.toEqual(new Set(modelSchema.properties[field].enum));
- expect(detail).toContain(`model.${field}`);
+ // FIXME(#1835): Restore this assertion for reasoning_efforts_source once
+ // the tier editor actually reads model.reasoning_efforts_source.
+ if (field !== 'reasoning_efforts_source') expect(detail).toContain(`model.${field}`);
}
});
});
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 106873f4d..e282c7ffa 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -10,7 +10,7 @@
// and the PR records the server implementation and feature-flag activation
// edge. The client never synthesizes a fallback payload shape.
-export const CONTRACT_VERSION = 6 as const;
+export const CONTRACT_VERSION = 7 as const;
export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;
export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;
@@ -85,12 +85,26 @@ export type SourceUsage = {
projected_exhaust_at?: string | null;
};
+/**
+ * Which rung of the provenance ladder produced `reasoning_efforts`.
+ *
+ * `upstream` (discovery carried a reasoning capability signal) and `catalog`
+ * (the model id matches a builtin catalog entry) are auto-provided and
+ * read-only. `user` is a list the user typed; `null` means no rung applies.
+ *
+ * Required here because `SuppliedModel` is the v7 API wire shape. The server
+ * normalizes older persisted rows before serialization; compatibility with a
+ * pre-v7 server belongs at the UI parsing boundary.
+ */
+export type ReasoningEffortsSource = 'upstream' | 'catalog' | 'user';
+
export type SuppliedModel = {
/** Bare model id (no provider prefix). */
id: string;
display_name?: string | null;
origin: ModelOrigin;
reasoning_efforts: string[];
+ reasoning_efforts_source: ReasoningEffortsSource | null;
/** Persistent retirement tombstone; retired entries stay readable but are not callable. */
retired?: boolean;
discovered_at?: string | null;
diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.py
index f50bac810..d0438aeab 100644
--- a/vibe/backend_model_catalog.py
+++ b/vibe/backend_model_catalog.py
@@ -9,7 +9,8 @@ import time
import urllib.error
import urllib.request
from pathlib import Path
-from typing import Any, Iterable, Mapping, Sequence
+from types import MappingProxyType
+from typing import Any, Final, Iterable, Mapping, Sequence
from config import paths
from config.atomic_io import write_atomic
@@ -36,6 +37,20 @@ _DEFAULT_REASONING_EFFORTS = {
"claude": ["low", "medium", "high"],
"codex": ["minimal", "low", "medium", "high", "xhigh"],
}
+REASONING_EFFORT_VOCABULARY: Final[tuple[str, ...]] = (
+ "minimal",
+ "low",
+ "medium",
+ "high",
+ "xhigh",
+ "max",
+ "ultra",
+)
+PROTOCOL_REASONING_EFFORT_DEFAULTS: Final[dict[str, tuple[str, ...]]] = {
+ "openai_responses": ("minimal", "low", "medium", "high", "xhigh"),
+ "openai_chat": ("minimal", "low", "medium", "high", "xhigh"),
+ "anthropic": ("low", "medium", "high", "xhigh", "max"),
+}
_CODEX_BUILT_IN_MODELS = [
"gpt-5.5",
"gpt-5.4",
@@ -298,6 +313,39 @@ def load_bundled_catalog(path: Path | None = None) -> dict[str, Any]:
return _read_catalog(path or get_bundled_catalog_path()) or {}
+def bundled_catalog_reasoning_efforts_by_model() -> Mapping[str, tuple[str, ...]]:
+ """Index bundled reasoning-effort rows without changing their declarations."""
+
+ efforts_by_model: dict[str, tuple[str, ...]] = {}
+ backends = load_bundled_catalog().get("backends")
+ if not isinstance(backends, dict):
+ return MappingProxyType(efforts_by_model)
+ for backend in backends.values():
+ models = backend.get("models") if isinstance(backend, dict) else None
+ if not isinstance(models, list):
+ continue
+ for model in models:
+ if not isinstance(model, dict):
+ continue
+ model_id = model.get("id")
+ efforts = model.get("reasoning_efforts")
+ if (
+ isinstance(model_id, str)
+ and model_id not in efforts_by_model
+ and isinstance(efforts, list)
+ ):
+ efforts_by_model[model_id] = tuple(efforts)
+ return MappingProxyType(efforts_by_model)
+
+
+def bundled_catalog_reasoning_efforts_for_model(
+ model_id: str,
+) -> tuple[str, ...] | None:
+ """Return one bundled catalog row's exact declared effort list."""
+
+ return bundled_catalog_reasoning_efforts_by_model().get(model_id)
+
+
def load_cached_remote_catalog(*, schedule_refresh: bool = True) -> dict[str, Any]:
cached = _cached_remote_payload()
if schedule_refresh and _remote_cache_stale(cached):
@@ -898,10 +946,11 @@ def _normalize_model_entry(item: object) -> dict[str, Any]:
visibility = item.get("visibility")
if isinstance(visibility, str) and visibility.strip():
entry["visibility"] = visibility.strip().lower()
- efforts = _coerce_reasoning_efforts(
- item.get("reasoning_efforts") or item.get("supported_reasoning_levels")
- )
- if efforts:
+ raw_efforts = item.get("reasoning_efforts")
+ if raw_efforts is None:
+ raw_efforts = item.get("supported_reasoning_levels")
+ efforts = _coerce_reasoning_efforts(raw_efforts)
+ if raw_efforts is not None:
entry["reasoning_efforts"] = efforts
return entry
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index a0fb0ac1d..7b1095ec8 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -433,7 +433,17 @@
"showMessageType": "Show {name}",
"visibilityShown": "shown",
"visibilityHidden": "hidden",
- "messageTypeStatus": "{name} messages are now {action}"
+ "messageTypeStatus": "{name} messages are now {action}",
+ "models": {
+ "sourceDetail": {
+ "tiers": {
+ "managed": {
+ "upstream": "Reasoning tiers are managed by upstream model metadata.",
+ "catalog": "Reasoning tiers are managed by Avibe's built-in model catalog."
+ }
+ }
+ }
+ }
},
"audio": {
"transcriptEchoSingle": "Voice transcript:",
@@ -945,6 +955,7 @@
"channel_switch": "{from_source}: supply channel changed",
"needs_action": "{from_source}: {reason}; action required",
"supply_interrupted": "{model}: {reason}; model supply interrupted",
+ "reasoning_efforts_override": "{from_source}: {model} reasoning tiers now follow {reason}",
"reason": {
"quota_exhausted": "quota exhausted",
"rate_limited": "rate limited",
@@ -952,6 +963,8 @@
"network": "network unavailable",
"recovery": "recovered",
"manual": "manual change",
+ "upstream_tiers": "upstream model metadata",
+ "catalog_tiers": "Avibe's built-in model catalog",
"credential_expired": "credential expired",
"credential_revoked": "credential revoked",
"balance_exhausted": "balance exhausted",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 61fa972ea..5cd38ded0 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -433,7 +433,17 @@
"showMessageType": "显示 {name}",
"visibilityShown": "显示",
"visibilityHidden": "隐藏",
- "messageTypeStatus": "{name} 消息已设为 {action}"
+ "messageTypeStatus": "{name} 消息已设为 {action}",
+ "models": {
+ "sourceDetail": {
+ "tiers": {
+ "managed": {
+ "upstream": "推理强度由上游模型元数据管理。",
+ "catalog": "推理强度由 Avibe 内置模型目录管理。"
+ }
+ }
+ }
+ }
},
"audio": {
"transcriptEchoSingle": "语音转写:",
@@ -945,6 +955,7 @@
"channel_switch": "{from_source}:调用通道已切换",
"needs_action": "{from_source}:{reason},需要处理",
"supply_interrupted": "{model}:{reason},模型请求已中断",
+ "reasoning_efforts_override": "{from_source}:{model} 的推理强度现按{reason}管理",
"reason": {
"quota_exhausted": "额度用完",
"rate_limited": "请求受限",
@@ -952,6 +963,8 @@
"network": "网络暂不可用",
"recovery": "已恢复",
"manual": "手动调整",
+ "upstream_tiers": "上游模型元数据",
+ "catalog_tiers": "Avibe 内置模型目录",
"credential_expired": "凭证已过期",
"credential_revoked": "凭证已撤销",
"balance_exhausted": "余额不足",
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 7727ae49e..cffc73f07 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -15,6 +15,7 @@ import aiohttp
from config.v2_config import normalize_model_hub_base_url
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
EngineHealth,
EngineStatus,
ObservationDiscovery,
@@ -1385,7 +1386,7 @@ class CLIProxyEngineAdapter:
protocol: str,
base_url: str | None,
credential_ref: str,
- ) -> Sequence[str]:
+ ) -> Sequence[DiscoveredModel]:
metadata = await asyncio.to_thread(
self.state_store.credential_metadata,
credential_ref,
@@ -1401,7 +1402,7 @@ class CLIProxyEngineAdapter:
"/auth-files/models",
query={"name": str(metadata["auth_name"])},
)
- return _model_ids(payload)
+ return _discovered_models(payload)
normalized_base_url = await asyncio.to_thread(
self.state_store.validate_api_key_target,
credential_ref,
@@ -1542,7 +1543,7 @@ class CLIProxyEngineAdapter:
authenticated=True,
protocol=proved_protocol,
discovery=discovery,
- model_ids=tuple(models),
+ models=tuple(models),
)
considered_protocols = frozenset(protocol_order)
@@ -1582,7 +1583,7 @@ class CLIProxyEngineAdapter:
authenticated=True,
protocol=proved_protocol,
discovery=discovery,
- model_ids=tuple(models),
+ models=tuple(models),
)
if received_accepted_unproven_response:
@@ -1595,7 +1596,7 @@ class CLIProxyEngineAdapter:
authenticated=True,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
if received_rejection:
return make_source_observation(
@@ -1604,7 +1605,7 @@ class CLIProxyEngineAdapter:
authenticated=False,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
if received_proven_unknown:
return make_source_observation(
@@ -1613,7 +1614,7 @@ class CLIProxyEngineAdapter:
authenticated=None,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
if received_unproven_response:
return make_source_observation(
@@ -1622,7 +1623,7 @@ class CLIProxyEngineAdapter:
authenticated=None,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
if any(error.error_type == "timeout" for error in failures):
return make_source_observation(
@@ -1631,7 +1632,7 @@ class CLIProxyEngineAdapter:
authenticated=None,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
if any(error.error_type in {"network_error", "ConnectionError", "URLError"} for error in failures):
return make_source_observation(
@@ -1640,7 +1641,7 @@ class CLIProxyEngineAdapter:
authenticated=None,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
return make_source_observation(
outcome=ObservationOutcome.ADAPTER_ERROR,
@@ -1648,7 +1649,7 @@ class CLIProxyEngineAdapter:
authenticated=None,
protocol=None,
discovery=ObservationDiscovery.NOT_ATTEMPTED,
- model_ids=(),
+ models=(),
)
async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:
@@ -2105,15 +2106,28 @@ def _auth_inventory(client: EngineClient) -> dict[str, _AuthRecord]:
return inventory
-def _model_ids(payload: Mapping[str, Any]) -> tuple[str, ...]:
+def _discovered_models(payload: Mapping[str, Any]) -> tuple[DiscoveredModel, ...]:
models = payload.get("models")
if not isinstance(models, list):
return ()
- result: list[str] = []
+ result: list[DiscoveredModel] = []
+ seen: set[str] = set()
for item in models:
value = item.get("id") or item.get("alias") or item.get("name") if isinstance(item, dict) else item
- if isinstance(value, str) and value and value not in result:
- result.append(value)
+ if not isinstance(value, str) or not value or value in seen:
+ continue
+ seen.add(value)
+ supported_parameters = None
+ if isinstance(item, dict) and isinstance(item.get("supported_parameters"), list):
+ parameters = item["supported_parameters"]
+ if all(isinstance(parameter, str) and parameter for parameter in parameters):
+ supported_parameters = tuple(dict.fromkeys(parameters))
+ result.append(
+ DiscoveredModel(
+ id=value,
+ supported_parameters=supported_parameters,
+ )
+ )
return tuple(result)
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index c3a9cdf09..4c98d0357 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -20,6 +20,7 @@ import ijson
from config.v2_config import normalize_model_hub_base_url
from core.handlers.model_hub.adapter import (
+ DiscoveredModel,
ENGINE_TRANSPORT_TIMEOUT_SECONDS,
RawCallOutcome,
RawOutcomeKind,
@@ -717,7 +718,7 @@ async def probe_models(
base_url: str | None,
secret: str,
timeout: float = 15.0,
-) -> tuple[str, ...]:
+) -> tuple[DiscoveredModel, ...]:
"""Probe the one allowlisted models path without redirecting credentials."""
normalized_vendor = vendor.strip().lower()
root = base_url or _OFFICIAL_BASE_URLS.get(normalized_vendor)
@@ -776,15 +777,26 @@ async def probe_models(
def _project_model_inventory(
reader: BinaryIO,
-) -> tuple[bool, bool, list[str], bool, bool, list[str]] | None:
+) -> tuple[
+ bool,
+ bool,
+ list[DiscoveredModel],
+ bool,
+ bool,
+ list[DiscoveredModel],
+] | None:
paths = {
(),
("data",),
("data", "*"),
("data", "*", "id"),
+ ("data", "*", "supported_parameters"),
+ ("data", "*", "supported_parameters", "*"),
("models",),
("models", "*"),
("models", "*", "id"),
+ ("models", "*", "supported_parameters"),
+ ("models", "*", "supported_parameters", "*"),
}
root_is_map = False
data_seen = False
@@ -795,6 +807,14 @@ def _project_model_inventory(
fallback_models: dict[JSONScope, str] = {}
invalid_data_models: set[JSONScope] = set()
invalid_fallback_models: set[JSONScope] = set()
+ data_supported_seen: set[JSONScope] = set()
+ fallback_supported_seen: set[JSONScope] = set()
+ data_supported_arrays: set[JSONScope] = set()
+ fallback_supported_arrays: set[JSONScope] = set()
+ data_supported: dict[JSONScope, dict[int, str]] = {}
+ fallback_supported: dict[JSONScope, dict[int, str]] = {}
+ invalid_data_supported: set[JSONScope] = set()
+ invalid_fallback_supported: set[JSONScope] = set()
def visit(
path: JSONPath,
@@ -809,6 +829,10 @@ def _project_model_inventory(
if event == "replace":
data_models.clear()
invalid_data_models.clear()
+ data_supported_seen.clear()
+ data_supported_arrays.clear()
+ data_supported.clear()
+ invalid_data_supported.clear()
data_seen = True
if event != "nonempty":
data_is_array = event == "start_array"
@@ -816,6 +840,10 @@ def _project_model_inventory(
if event == "replace":
fallback_models.clear()
invalid_fallback_models.clear()
+ fallback_supported_seen.clear()
+ fallback_supported_arrays.clear()
+ fallback_supported.clear()
+ invalid_fallback_supported.clear()
fallback_seen = True
if event != "nonempty":
fallback_is_array = event == "start_array"
@@ -836,14 +864,66 @@ def _project_model_inventory(
elif event == "scalar" and isinstance(value, str) and value:
fallback_models[scope] = value
- def ordered_unique(values: Mapping[JSONScope, str]) -> list[str]:
- result: list[str] = []
+ elif path in {
+ ("data", "*", "supported_parameters"),
+ ("models", "*", "supported_parameters"),
+ }:
+ seen = data_supported_seen if path[0] == "data" else fallback_supported_seen
+ arrays = data_supported_arrays if path[0] == "data" else fallback_supported_arrays
+ values = data_supported if path[0] == "data" else fallback_supported
+ invalid = invalid_data_supported if path[0] == "data" else invalid_fallback_supported
+ if event == "replace":
+ values.pop(scope, None)
+ invalid.discard(scope)
+ arrays.discard(scope)
+ seen.add(scope)
+ if event == "start_array":
+ arrays.add(scope)
+ elif event not in {"replace", "nonempty"}:
+ invalid.add(scope)
+ elif path in {
+ ("data", "*", "supported_parameters", "*"),
+ ("models", "*", "supported_parameters", "*"),
+ }:
+ model_scope = scope[:-1]
+ values = data_supported if path[0] == "data" else fallback_supported
+ invalid = invalid_data_supported if path[0] == "data" else invalid_fallback_supported
+ if event == "scalar" and isinstance(value, str) and value:
+ values.setdefault(model_scope, {})[scope[-1]] = value
+ elif event in {"scalar", "elided_string", "start_map", "start_array"}:
+ invalid.add(model_scope)
+
+ def ordered_unique(
+ values: Mapping[JSONScope, str],
+ supported_seen: set[JSONScope],
+ supported_arrays: set[JSONScope],
+ supported: Mapping[JSONScope, Mapping[int, str]],
+ invalid_supported: set[JSONScope],
+ ) -> list[DiscoveredModel]:
+ result: list[DiscoveredModel] = []
seen: set[str] = set()
for scope in sorted(values):
value = values[scope]
- if value not in seen:
- seen.add(value)
- result.append(value)
+ if value in seen:
+ continue
+ seen.add(value)
+ parameters = None
+ if (
+ scope in supported_seen
+ and scope in supported_arrays
+ and scope not in invalid_supported
+ ):
+ parameters = tuple(
+ parameter
+ for _index, parameter in sorted(supported.get(scope, {}).items())
+ )
+ parameters = tuple(dict.fromkeys(parameters))
+ result.append(
+ DiscoveredModel(
+ id=value,
+ supported_parameters=parameters,
+ )
+ )
return result
if not project_json_reader(reader, paths, visit) or not root_is_map:
@@ -855,10 +935,22 @@ def _project_model_inventory(
return (
data_seen,
data_is_array,
- ordered_unique(data_models),
+ ordered_unique(
+ data_models,
+ data_supported_seen,
+ data_supported_arrays,
+ data_supported,
+ invalid_data_supported,
+ ),
fallback_seen,
fallback_is_array,
- ordered_unique(fallback_models),
+ ordered_unique(
+ fallback_models,
+ fallback_supported_seen,
+ fallback_supported_arrays,
+ fallback_supported,
+ invalid_fallback_supported,
+ ),
)
@@ -923,7 +1015,14 @@ def _project_model_inventory_before_deadline(
payload: BinaryIO,
*,
deadline: float,
-) -> tuple[bool, bool, list[str], bool, bool, list[str]] | None:
+) -> tuple[
+ bool,
+ bool,
+ list[DiscoveredModel],
+ bool,
+ bool,
+ list[DiscoveredModel],
+] | None:
payload.seek(0)
return _project_before_deadline(
payload,