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): add per-agent source order resolution (#1084)

Call White951ad39c1172
diff --git a/config/v2_config.py b/config/v2_config.py
index 8aae2f8c2..660f49424 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -93,6 +93,8 @@ MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12
MAX_CHAT_MESSAGE_FONT_SIZE_PX = 20
DEFAULT_AGENT_PROGRESS_STYLE = "off"
MODEL_HUB_ENABLED_ENV = "VIBE_MODEL_HUB_ENABLED"
+MODEL_HUB_BACKENDS = ("claude", "codex", "opencode")
+MODEL_HUB_LEGACY_CREATED_AT = "1970-01-01T00:00:00Z"
def is_model_hub_enabled(environ: Optional[Mapping[str, str]] = None) -> bool:
@@ -395,7 +397,7 @@ class ModelHubModelConfig:
@dataclass
class ModelHubSourceStateConfig:
- status: Literal["active", "standby", "cooldown", "error"] = "standby"
+ status: Literal["active", "standby", "cooldown", "needs_action", "error"] = "standby"
retry_at: Optional[str] = None
detail_key: Optional[str] = None
@@ -406,10 +408,32 @@ class ModelHubSourceStateConfig:
status = payload.get("status")
retry_at = payload.get("retry_at")
detail_key = payload.get("detail_key")
- if status not in {"active", "standby", "cooldown", "error"}:
+ if status not in {"active", "standby", "cooldown", "needs_action", "error"}:
raise ValueError("Config 'model_hub.sources.state.status' is invalid")
if detail_key is not None and not isinstance(detail_key, str):
raise ValueError("Config 'model_hub.sources.state.detail_key' must be a string or null")
+ cooldown_keys = {
+ None,
+ "models.source.cooldown.network",
+ "models.source.cooldown.timeout",
+ "models.source.cooldown.rate_limited",
+ "models.source.cooldown.quota_exhausted",
+ "models.source.cooldown.server_error",
+ }
+ needs_action_keys = {
+ "models.source.needs_action.oauth_expired",
+ "models.source.needs_action.balance_exhausted",
+ "models.source.needs_action.credential_revoked",
+ "models.source.needs_action.account_banned",
+ }
+ if status in {"active", "standby"} and (retry_at is not None or detail_key is not None):
+ raise ValueError(f"Config healthy source state '{status}' cannot carry blocker detail")
+ if status == "cooldown" and (retry_at is None or detail_key not in cooldown_keys):
+ raise ValueError("Config cooldown source state requires retry_at and a known detail key")
+ if status == "needs_action" and (retry_at is not None or detail_key not in needs_action_keys):
+ raise ValueError("Config needs_action source state requires a known detail key")
+ if status == "error" and (retry_at is not None or detail_key != "models.source.error.unclassified"):
+ raise ValueError("Config error source state requires the generic error detail key")
return cls(
status=status,
retry_at=_validate_optional_datetime(retry_at, "model_hub.sources.state.retry_at"),
@@ -425,6 +449,7 @@ class ModelHubSourceUsageConfig:
cycle_used_pct: Optional[float] = None
month_spend_cents: Optional[int] = None
currency: Optional[str] = None
+ projected_exhaust_at: Optional[str] = None
@classmethod
def from_payload(cls, payload: dict) -> "ModelHubSourceUsageConfig":
@@ -439,6 +464,7 @@ class ModelHubSourceUsageConfig:
raise ValueError("Config 'model_hub.sources.usage.cycle_used_pct' must be between 0 and 100")
month_spend_cents = payload.get("month_spend_cents")
currency = payload.get("currency")
+ projected_exhaust_at = payload.get("projected_exhaust_at")
if month_spend_cents is not None and (
isinstance(month_spend_cents, bool) or not isinstance(month_spend_cents, int) or month_spend_cents < 0
):
@@ -449,6 +475,10 @@ class ModelHubSourceUsageConfig:
cycle_used_pct=cycle_used_pct,
month_spend_cents=month_spend_cents,
currency=currency,
+ projected_exhaust_at=_validate_optional_datetime(
+ projected_exhaust_at,
+ "model_hub.sources.usage.projected_exhaust_at",
+ ),
)
def to_payload(self) -> dict:
@@ -456,6 +486,7 @@ class ModelHubSourceUsageConfig:
"cycle_used_pct": self.cycle_used_pct,
"month_spend_cents": self.month_spend_cents,
"currency": self.currency,
+ "projected_exhaust_at": self.projected_exhaust_at,
}
@@ -470,6 +501,7 @@ class ModelHubSourceConfig:
billing: Literal["monthly", "metered"]
state: ModelHubSourceStateConfig
models: list[ModelHubModelConfig]
+ created_at: str = MODEL_HUB_LEGACY_CREATED_AT
base_url: Optional[str] = None
experimental_consent_at: Optional[str] = None
usage: Optional[ModelHubSourceUsageConfig] = None
@@ -511,6 +543,7 @@ class ModelHubSourceConfig:
credential_ref = payload.get("credential_ref")
account_label = payload.get("account_label")
masked_credential = payload.get("masked_credential")
+ created_at = payload.get("created_at")
if base_url is not None and not isinstance(base_url, str):
raise ValueError("Config 'model_hub.sources.base_url' is invalid")
if credential_ref is not None and not isinstance(credential_ref, str):
@@ -529,6 +562,13 @@ class ModelHubSourceConfig:
billing=billing,
state=ModelHubSourceStateConfig.from_payload(payload.get("state")),
models=[ModelHubModelConfig.from_payload(model) for model in models_payload],
+ created_at=(
+ _validate_optional_datetime(
+ created_at,
+ "model_hub.sources.created_at",
+ )
+ or MODEL_HUB_LEGACY_CREATED_AT
+ ),
base_url=base_url,
experimental_consent_at=_validate_optional_datetime(
consent_at,
@@ -543,6 +583,7 @@ class ModelHubSourceConfig:
def to_payload(self) -> dict:
payload = {
"id": self.id,
+ "created_at": self.created_at,
"kind": self.kind,
"vendor": self.vendor,
"display_name": self.display_name,
@@ -615,11 +656,37 @@ class ModelHubMenuConfig:
return {"view": self.view, "checked": list(self.checked)}
+@dataclass
+class ModelHubAgentSourcesConfig:
+ policy: Literal["follow", "custom"] = "follow"
+ order: list[str] = field(default_factory=list)
+
+ @classmethod
+ def from_payload(cls, payload: dict) -> "ModelHubAgentSourcesConfig":
+ if not isinstance(payload, dict):
+ raise ValueError("Config 'model_hub.agents.sources' must be an object")
+ if set(payload) != {"policy", "order"}:
+ raise ValueError("Config 'model_hub.agents.sources' must contain policy and order")
+ policy = payload.get("policy")
+ order = payload.get("order")
+ if policy not in {"follow", "custom"}:
+ raise ValueError("Config 'model_hub.agents.sources.policy' is invalid")
+ if not isinstance(order, list) or not all(isinstance(item, str) for item in order):
+ raise ValueError("Config 'model_hub.agents.sources.order' must be an array of strings")
+ if len(set(order)) != len(order):
+ raise ValueError("Config 'model_hub.agents.sources.order' must be unique")
+ return cls(policy=policy, order=list(order))
+
+ def to_payload(self) -> dict:
+ return {"policy": self.policy, "order": list(self.order)}
+
+
@dataclass
class ModelHubAgentSupplyConfig:
backend: Literal["claude", "codex", "opencode"]
mode: Literal["hub", "direct"]
menu_kind: Literal["fixed", "open"]
+ sources: ModelHubAgentSourcesConfig = field(default_factory=ModelHubAgentSourcesConfig)
mappings: list[ModelHubMappingConfig] = field(default_factory=list)
menu: Optional[ModelHubMenuConfig] = None
@@ -651,6 +718,7 @@ class ModelHubAgentSupplyConfig:
if not isinstance(mappings_payload, list):
raise ValueError("Config 'model_hub.agents.mappings' must be an array")
menu_payload = payload.get("menu")
+ sources_payload = payload.get("sources")
if backend == "opencode" and menu_payload is None:
menu_payload = {"view": "featured", "checked": []}
if backend != "opencode" and menu_payload is not None:
@@ -659,6 +727,11 @@ class ModelHubAgentSupplyConfig:
backend=backend,
mode=mode,
menu_kind=menu_kind,
+ sources=(
+ ModelHubAgentSourcesConfig.from_payload(sources_payload)
+ if sources_payload is not None
+ else ModelHubAgentSourcesConfig()
+ ),
mappings=[ModelHubMappingConfig.from_payload(mapping) for mapping in mappings_payload],
menu=ModelHubMenuConfig.from_payload(menu_payload) if menu_payload is not None else None,
)
@@ -668,6 +741,7 @@ class ModelHubAgentSupplyConfig:
"backend": self.backend,
"mode": self.mode,
"menu_kind": self.menu_kind,
+ "sources": self.sources.to_payload(),
"mappings": [mapping.to_payload() for mapping in self.mappings],
"menu": self.menu.to_payload() if self.menu else None,
}
@@ -676,27 +750,63 @@ class ModelHubAgentSupplyConfig:
@dataclass
class ModelHubConfig:
sources: list[ModelHubSourceConfig] = field(default_factory=list)
- priority_order: list[str] = field(default_factory=list)
agents: dict[str, ModelHubAgentSupplyConfig] = field(
default_factory=lambda: {
- backend: ModelHubAgentSupplyConfig.default(backend, mode="direct")
- for backend in ("claude", "codex", "opencode")
+ backend: ModelHubAgentSupplyConfig.default(backend, mode="direct") for backend in MODEL_HUB_BACKENDS
}
)
subscription_hub_experimental: bool = False
+ @staticmethod
+ def source_eligible_for_backend(
+ source: ModelHubSourceConfig,
+ backend: str,
+ ) -> bool:
+ if backend not in MODEL_HUB_BACKENDS:
+ return False
+ if source.kind == "api_key":
+ return source.supply_channel == "hub"
+ expected_backend = {"anthropic": "claude", "openai": "codex"}.get(source.vendor)
+ return expected_backend == backend
+
+ def recommended_source_order(self, backend: str) -> list[str]:
+ def sort_key(source: ModelHubSourceConfig) -> tuple[object, ...]:
+ if source.kind == "subscription":
+ return (
+ 0,
+ 0 if source.supply_channel == "native_cli" else 1,
+ source.id,
+ )
+ created_at = datetime.fromisoformat(source.created_at.replace("Z", "+00:00"))
+ return (1, created_at.timestamp(), source.id)
+
+ return [
+ source.id
+ for source in sorted(self.sources, key=sort_key)
+ if self.source_eligible_for_backend(source, backend)
+ ]
+
+ def effective_source_order(self, backend: str) -> list[str]:
+ sources = self.agents[backend].sources
+ if sources.policy == "follow":
+ return self.recommended_source_order(backend)
+ return list(sources.order)
+
+ def refresh_follow_orders(self) -> None:
+ for backend in MODEL_HUB_BACKENDS:
+ sources = self.agents[backend].sources
+ if sources.policy == "follow":
+ sources.order = self.recommended_source_order(backend)
+
@classmethod
def from_payload(cls, payload: dict) -> "ModelHubConfig":
if not isinstance(payload, dict):
raise ValueError("Config 'model_hub' must be an object")
sources_payload = payload.get("sources") or []
- priority_order = payload.get("priority_order") or []
agents_payload = payload.get("agents") or {}
experimental = payload.get("subscription_hub_experimental", False)
if not isinstance(sources_payload, list):
raise ValueError("Config 'model_hub.sources' must be an array")
- if not isinstance(priority_order, list) or not all(isinstance(item, str) for item in priority_order):
- raise ValueError("Config 'model_hub.priority_order' must be an array of strings")
if not isinstance(agents_payload, dict):
raise ValueError("Config 'model_hub.agents' must be an object")
if not isinstance(experimental, bool):
@@ -705,15 +815,12 @@ class ModelHubConfig:
source_ids = [source.id for source in sources]
if len(set(source_ids)) != len(source_ids):
raise ValueError("Config 'model_hub.sources' contains duplicate ids")
- if len(set(priority_order)) != len(priority_order) or set(priority_order) != set(source_ids):
- raise ValueError("Config 'model_hub.priority_order' must be a permutation of source ids")
agents = {
backend: ModelHubAgentSupplyConfig.from_payload(
- agents_payload.get(backend)
- or ModelHubAgentSupplyConfig.default(backend, mode="direct").to_payload(),
+ agents_payload.get(backend) or ModelHubAgentSupplyConfig.default(backend, mode="direct").to_payload(),
expected_backend=backend,
)
- for backend in ("claude", "codex", "opencode")
+ for backend in MODEL_HUB_BACKENDS
}
for source in sources:
if source.kind == "subscription" and source.supply_channel == "hub":
@@ -721,18 +828,39 @@ class ModelHubConfig:
raise ValueError("Config hub-held subscription source requires recorded experimental consent")
elif source.experimental_consent_at is not None:
raise ValueError("Config experimental consent is only valid for hub-held subscription sources")
- return cls(
+ config = cls(
sources=sources,
- priority_order=list(priority_order),
agents=agents,
subscription_hub_experimental=experimental,
)
+ for backend in MODEL_HUB_BACKENDS:
+ configured_sources = agents[backend].sources
+ invalid_id = next(
+ (
+ source_id
+ for source_id in configured_sources.order
+ if source_id not in source_ids
+ or not config.source_eligible_for_backend(
+ next(source for source in sources if source.id == source_id),
+ backend,
+ )
+ ),
+ None,
+ )
+ if invalid_id is not None:
+ raise ValueError(
+ f"Config 'model_hub.agents.{backend}.sources.order' contains "
+ f"ineligible or missing source '{invalid_id}'"
+ )
+ if configured_sources.policy == "follow":
+ recommended = config.recommended_source_order(backend)
+ configured_sources.order = recommended
+ return config
def to_payload(self) -> dict:
return {
"sources": [source.to_payload() for source in self.sources],
- "priority_order": list(self.priority_order),
- "agents": {backend: self.agents[backend].to_payload() for backend in ("claude", "codex", "opencode")},
+ "agents": {backend: self.agents[backend].to_payload() for backend in MODEL_HUB_BACKENDS},
"subscription_hub_experimental": self.subscription_hub_experimental,
}
diff --git a/core/controller.py b/core/controller.py
index 86632dd98..1321417af 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -299,8 +299,23 @@ class Controller:
return None
return agent.model
+ def default_vibe_agent_name(backend: str) -> Optional[str]:
+ agent = self.vibe_agent_store.get_default_agent()
+ if agent is None or agent.backend != backend or not str(agent.model or "").strip():
+ return None
+ return agent.name
+
+ def named_vibe_agents(backend: str) -> list[tuple[str, Optional[str]]]:
+ return [
+ (agent.name, agent.model)
+ for agent in self.vibe_agent_store.list_agents(include_disabled=False)
+ if agent.backend == backend
+ ]
+
self.model_hub_service = create_default_service(
requested_model_override=default_vibe_agent_model,
+ selected_agent_override=default_vibe_agent_name,
+ named_agents_override=named_vibe_agents,
)
self.model_hub_turn_gateway = ModelHubTurnGateway(self.model_hub_service)
self.model_hub_runtime = ModelHubRuntimeRouter(
diff --git a/core/handlers/model_hub/migration.py b/core/handlers/model_hub/migration.py
index 129ba5e2b..0af474e1a 100644
--- a/core/handlers/model_hub/migration.py
+++ b/core/handlers/model_hub/migration.py
@@ -595,6 +595,7 @@ def _new_source(
)
return ModelHubSourceConfig(
id=item.source_id,
+ created_at=discovered_at,
kind="subscription" if keep_native or controlled else "api_key",
vendor=item.vendor,
display_name=item.display_name,
@@ -656,8 +657,6 @@ async def apply_native_migration(
raise MigrationConflictError
provisioned: list[tuple[str, str]] = []
- native_source_ids: list[str] = []
- hub_source_ids: list[str] = []
persisted = False
try:
for item in selected:
@@ -700,16 +699,6 @@ async def apply_native_migration(
]
host._apply_discovered_models(source, manual_models, discovered)
updated.sources.append(source)
- if item.proposed_action == "keep_native":
- native_source_ids.append(source.id)
- else:
- hub_source_ids.append(source.id)
-
- updated.priority_order = [
- *updated.priority_order,
- *native_source_ids,
- *hub_source_ids,
- ]
await host._commit_synced(previous, updated)
persisted = True
diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.py
index 95c0545c4..ba0b705b3 100644
--- a/core/handlers/model_hub/resolver.py
+++ b/core/handlers/model_hub/resolver.py
@@ -13,6 +13,7 @@ from .identifiers import opencode_provider_id, parse_opencode_model_id
BackendName = Literal["claude", "codex", "opencode"]
ResolutionChannel = Literal["direct", "native_cli", "hub", "unavailable"]
+SupplyStatus = Literal["ok", "degraded", "waiting", "interrupted"]
@dataclass(frozen=True)
@@ -27,6 +28,7 @@ class ModelHubTurnResolution:
provider: str | None = None
mapping_applied: bool = False
recoverable_source_ids: tuple[str, ...] = ()
+ supply_status: SupplyStatus | None = None
def allowed_origins(source: ModelHubSourceConfig) -> tuple[str, ...]:
@@ -40,9 +42,7 @@ def allowed_origins(source: ModelHubSourceConfig) -> tuple[str, ...]:
def source_eligible_for_backend(source: ModelHubSourceConfig, backend: str) -> bool:
- if source.kind == "api_key":
- return source.supply_channel == "hub"
- return backend in allowed_origins(source)
+ return ModelHubConfig.source_eligible_for_backend(source, backend)
def source_retry_ready(source: ModelHubSourceConfig, now: datetime | None) -> bool:
@@ -74,6 +74,48 @@ def source_after_cooldown_recovery(
)
+def source_runnable(
+ source: ModelHubSourceConfig,
+ *,
+ now: datetime | None,
+ unavailable_source_ids: frozenset[str] = frozenset(),
+) -> bool:
+ if source.id in unavailable_source_ids:
+ return False
+ if source.state.status in {"active", "standby"}:
+ return True
+ return source_retry_ready(source, now)
+
+
+def _supply_status(
+ matching_sources: tuple[ModelHubSourceConfig, ...],
+ candidates: tuple[ModelHubSourceConfig, ...],
+ *,
+ now: datetime | None,
+ unavailable_source_ids: frozenset[str],
+) -> SupplyStatus:
+ if not matching_sources:
+ return "interrupted"
+ if candidates:
+ all_runnable = all(
+ source_runnable(
+ source,
+ now=now,
+ unavailable_source_ids=unavailable_source_ids,
+ )
+ for source in matching_sources
+ )
+ return "ok" if candidates[0].id == matching_sources[0].id and all_runnable else "degraded"
+ if all(
+ source.id not in unavailable_source_ids
+ and source.state.status == "cooldown"
+ and not source_retry_ready(source, now)
+ for source in matching_sources
+ ):
+ return "waiting"
+ return "interrupted"
+
+
def normalize_opencode_requested_model(
requested_model: str,
checked_identifiers: tuple[str, ...],
@@ -85,11 +127,7 @@ def normalize_opencode_requested_model(
return None
if candidate in checked_identifiers:
return candidate
- matches = [
- identifier
- for identifier in checked_identifiers
- if identifier.endswith(f"/{candidate}")
- ]
+ matches = [identifier for identifier in checked_identifiers if identifier.endswith(f"/{candidate}")]
return matches[0] if len(matches) == 1 else None
@@ -124,10 +162,11 @@ def resolve_model_hub_turn(
if not checked:
return ModelHubTurnResolution(
backend=backend,
- channel="direct",
+ channel="unavailable",
requested_model=requested_model,
target_model=requested_model,
source=None,
+ supply_status="interrupted",
)
if not requested_model:
for identifier in checked:
@@ -147,6 +186,7 @@ def resolve_model_hub_turn(
requested_model=requested_model,
target_model=requested_model,
source=None,
+ supply_status="interrupted",
)
normalized = normalize_opencode_requested_model(requested_model, checked)
if normalized is None:
@@ -156,16 +196,13 @@ def resolve_model_hub_turn(
requested_model=requested_model,
target_model=requested_model,
source=None,
+ supply_status="interrupted",
)
requested_model = normalized
mapping = (
next(
- (
- item
- for item in agent.mappings
- if item.enabled and item.builtin_id == requested_model
- ),
+ (item for item in agent.mappings if item.enabled and item.builtin_id == requested_model),
None,
)
if agent.menu_kind == "fixed"
@@ -186,6 +223,7 @@ def resolve_model_hub_turn(
target_model=target_model,
source=None,
mapping_applied=mapping_applied,
+ supply_status="interrupted",
)
if f"{provider}/{target_model}" not in agent.menu.checked:
return ModelHubTurnResolution(
@@ -196,53 +234,46 @@ def resolve_model_hub_turn(
source=None,
provider=provider,
mapping_applied=mapping_applied,
+ supply_status="interrupted",
)
if not target_model:
return ModelHubTurnResolution(
backend=backend,
- channel=(
- "direct"
- if backend != "opencode" and mapping is None
- else "unavailable"
- ),
+ channel="unavailable",
requested_model=requested_model,
target_model=target_model,
source=None,
provider=provider,
mapping_applied=mapping_applied,
+ supply_status="interrupted",
)
by_id = {source.id: source for source in config.sources}
matching_sources = tuple(
source
- for source in (by_id[source_id] for source_id in config.priority_order)
+ for source in (by_id[source_id] for source_id in config.effective_source_order(backend))
if source_eligible_for_backend(source, backend)
and (provider is None or opencode_provider_id(source.vendor) == provider)
and any(model.id == target_model for model in source.models)
)
- if backend != "opencode" and mapping is None and not matching_sources:
- return ModelHubTurnResolution(
- backend=backend,
- channel="direct",
- requested_model=requested_model,
- target_model=requested_model,
- source=None,
- )
candidates: list[ModelHubSourceConfig] = []
recoverable_source_ids: list[str] = []
for source in matching_sources:
if supply_channel is not None and source.supply_channel != supply_channel:
continue
- if source.state.status == "cooldown":
- if not source_retry_ready(source, now):
- continue
+ if source.state.status == "cooldown" and source_retry_ready(source, now):
recoverable_source_ids.append(source.id)
- if source.id in unavailable_source_ids or source.state.status == "error":
+ if not source_runnable(
+ source,
+ now=now,
+ unavailable_source_ids=unavailable_source_ids,
+ ):
continue
candidates.append(source)
source = candidates[0] if candidates else None
+ candidate_tuple = tuple(candidates)
return ModelHubTurnResolution(
backend=backend,
channel=source.supply_channel if source is not None else "unavailable",
@@ -250,8 +281,14 @@ def resolve_model_hub_turn(
target_model=target_model,
source=source,
matching_sources=matching_sources,
- candidates=tuple(candidates),
+ candidates=candidate_tuple,
provider=provider,
mapping_applied=mapping_applied,
recoverable_source_ids=tuple(recoverable_source_ids),
+ supply_status=_supply_status(
+ matching_sources,
+ candidate_tuple,
+ now=now,
+ unavailable_source_ids=unavailable_source_ids,
+ ),
)
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index 8d7895254..6333f7672 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -24,12 +24,15 @@ async def dispatch_model_hub_rpc(
if operation == "test_source":
source, discovered = await service.test_source(payload.get("source_id"))
return {"source": source, "discovered": discovered}
- if operation == "priority":
- return service.priority()
- if operation == "set_priority":
- return await service.set_priority(payload.get("order"))
if operation == "list_agents":
return service.list_agents()
+ if operation == "get_agent_sources":
+ return service.get_agent_sources(payload.get("backend"))
+ if operation == "set_agent_sources":
+ return await service.set_agent_sources(
+ payload.get("backend"),
+ payload.get("sources"),
+ )
if operation == "set_agent_mode":
return await service.set_agent_mode(payload.get("backend"), payload.get("mode"))
if operation == "set_mappings":
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index e8cafed81..325557347 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -13,6 +13,7 @@ from urllib.parse import parse_qsl, urlsplit
from config import paths
from config.v2_config import (
CONFIG_LOCK,
+ MODEL_HUB_BACKENDS,
ModelHubAgentSupplyConfig,
ModelHubConfig,
ModelHubMappingConfig,
@@ -57,7 +58,6 @@ from .migration import (
scan_native_configs,
)
from .oauth import (
- NATIVE_OAUTH_SIGNED_OUT_DETAIL_KEY,
NativeOAuthAdapter,
NativeOAuthUnavailableError,
OAuthAdapter,
@@ -76,7 +76,7 @@ from .resolver import (
)
from .revocations import CredentialRevocationJournal
-CONTRACT_VERSION = 1
+CONTRACT_VERSION = 3
logger = logging.getLogger(__name__)
_NATIVE_VENDOR_BACKENDS = {"anthropic": "claude", "openai": "codex"}
@@ -97,9 +97,16 @@ _CREDENTIAL_QUERY_KEYS = {
"token",
}
+
class ModelHubError(Exception):
- def __init__(self, code: str, *, status: int = 400):
- detail_key = f"modelHub.errors.{code}"
+ def __init__(
+ self,
+ code: str,
+ *,
+ status: int = 400,
+ detail: Optional[str] = None,
+ ):
+ detail_key = detail or f"modelHub.errors.{code}"
super().__init__(detail_key)
self.code = code
self.status = status
@@ -321,6 +328,7 @@ def _binding(source: ModelHubSourceConfig) -> SourceBinding:
def _oauth_payload(flow: OAuthFlowState, *, channel: str) -> dict:
return {
"flow_id": flow.flow_id,
+ "intent": "create",
"source_id": flow.source_id,
"vendor": flow.vendor,
"channel": channel,
@@ -368,6 +376,10 @@ class ModelHubService:
revocations: Optional[CredentialRevocationJournal] = None,
migration_claude_oauth_probe: Optional[Callable[[], bool]] = None,
requested_model_override: Optional[Callable[[BackendName], Optional[str]]] = None,
+ selected_agent_override: Optional[Callable[[BackendName], Optional[str]]] = None,
+ named_agents_override: Optional[
+ Callable[[BackendName], list[tuple[str, Optional[str]]]]
+ ] = None,
now: Callable[[], datetime] = _utc_now,
):
self.store = store
@@ -380,6 +392,8 @@ class ModelHubService:
)
self.migration_claude_oauth_probe = migration_claude_oauth_probe
self.requested_model_override = requested_model_override
+ self.selected_agent_override = selected_agent_override
+ self.named_agents_override = named_agents_override
self.now = now
self.native_source_ready: Callable[[BackendName, ModelHubSourceConfig], bool] = (
lambda _backend, _source: True
@@ -408,9 +422,11 @@ class ModelHubService:
).strip()
if requested_model:
return requested_model
+ return self._backend_default_model(agent.backend)
+
+ def _backend_default_model(self, backend: str) -> str:
getter = getattr(self.store, "requested_model", None)
- requested_model = str(getter(agent.backend) if callable(getter) else "").strip()
- return requested_model
+ return str(getter(backend) if callable(getter) else "").strip()
def _unavailable_native_sources(
self,
@@ -608,11 +624,29 @@ class ModelHubService:
if any(item.id == source.id for item in config.sources):
raise ModelHubError("migration_item_conflict", status=409)
config.sources.append(source)
- config.priority_order.append(source.id)
+ config.refresh_follow_orders()
if consented:
config.subscription_hub_experimental = True
await self._commit_synced(previous, config)
+ def _adopted_by(self, source_id: str) -> list[dict]:
+ config = self.store.load()
+ return [
+ {
+ "backend": backend,
+ "policy": "follow",
+ "position": config.effective_source_order(backend).index(source_id) + 1,
+ }
+ for backend in MODEL_HUB_BACKENDS
+ if config.agents[backend].sources.policy == "follow" and source_id in config.effective_source_order(backend)
+ ]
+
+ def _source_creation_result(self, source: dict) -> dict:
+ return {
+ "source": source,
+ "adopted_by": self._adopted_by(source["id"]),
+ }
+
async def _create_oauth_source(
self,
source: ModelHubSourceConfig,
@@ -675,11 +709,11 @@ class ModelHubService:
raise ModelHubError("engine_down", status=503) from None
source.account_label = source_status.account_label
source.state = (
- ModelHubSourceStateConfig(status="active")
+ ModelHubSourceStateConfig(status="standby")
if source_status.signed_in
else ModelHubSourceStateConfig(
- status="error",
- detail_key=NATIVE_OAUTH_SIGNED_OUT_DETAIL_KEY,
+ status="needs_action",
+ detail_key="models.source.needs_action.oauth_expired",
)
)
@@ -789,6 +823,7 @@ class ModelHubService:
source = ModelHubSourceConfig(
id=binding.source_id,
+ created_at=self.now().isoformat(),
kind="subscription",
vendor=binding.vendor,
display_name=binding.vendor,
@@ -822,8 +857,7 @@ class ModelHubService:
def list_sources(self) -> list[dict]:
config = self.store.load()
- by_id = {source.id: source for source in config.sources}
- return [by_id[source_id].to_payload() for source_id in config.priority_order]
+ return [source.to_payload() for source in config.sources]
async def create_source(self, payload: dict) -> dict:
if not isinstance(payload, dict):
@@ -836,6 +870,7 @@ class ModelHubService:
"experimental_consent_at",
"state",
"usage",
+ "created_at",
} & set(payload)
if forbidden:
raise ModelHubError("discovery_failed")
@@ -899,6 +934,7 @@ class ModelHubService:
state=ModelHubSourceStateConfig(status="standby"),
usage=ModelHubSourceUsageConfig(),
models=manual_models,
+ created_at=self.now().isoformat(),
)
source = ModelHubSourceConfig.from_payload(source.to_payload())
except (TypeError, ValueError):
@@ -920,13 +956,15 @@ class ModelHubService:
raise ModelHubError("discovery_failed")
if oauth_ref:
- return await self._create_oauth_source(
- source,
- manual_models,
- oauth_ref=oauth_ref,
- channel=cast(Literal["native_cli", "hub"], channel),
- vendor=vendor,
- consented=consented,
+ return self._source_creation_result(
+ await self._create_oauth_source(
+ source,
+ manual_models,
+ oauth_ref=oauth_ref,
+ channel=cast(Literal["native_cli", "hub"], channel),
+ vendor=vendor,
+ consented=consented,
+ )
)
if kind == "subscription":
raise ModelHubError("flow_not_found", status=404)
@@ -943,7 +981,7 @@ class ModelHubService:
async with self._mutation_lock:
await self._commit_new_source_locked(source, consented=consented)
persisted = True
- return source.to_payload()
+ return self._source_creation_result(source.to_payload())
except Exception:
if not persisted:
await self._rollback_credential(source.id, rollback_credential_ref)
@@ -1030,7 +1068,9 @@ class ModelHubService:
if not force and self._only_selected_supplier(config, source):
raise ModelHubError("mode_switch_blocked", status=409)
config.sources = [item for item in config.sources if item.id != source_id]
- config.priority_order = [item for item in config.priority_order if item != source_id]
+ for agent in config.agents.values():
+ agent.sources.order = [item for item in agent.sources.order if item != source_id]
+ config.refresh_follow_orders()
self._prune_unavailable_agent_references(config)
if source.credential_ref:
self.revocations.add(source.id, source.credential_ref)
@@ -1070,28 +1110,77 @@ class ModelHubService:
await self._commit_synced(previous, config)
return source.to_payload(), len(model_ids)
- async def set_priority(self, order: object) -> dict:
- async with self._mutation_lock:
- config = self.store.load()
- source_ids = [source.id for source in config.sources]
- if (
- not isinstance(order, list)
- or not all(isinstance(item, str) for item in order)
- or len(set(order)) != len(order)
- or set(order) != set(source_ids)
- ):
- raise ModelHubError("invalid_priority_order")
- config.priority_order = list(order)
- self.store.save(config)
- return {"contract_version": CONTRACT_VERSION, "order": list(order)}
-
- def priority(self) -> dict:
- return {"contract_version": CONTRACT_VERSION, "order": list(self.store.load().priority_order)}
-
@staticmethod
def _eligible_for_agent(source: ModelHubSourceConfig, backend: str) -> bool:
return source_eligible_for_backend(source, backend)
+ @classmethod
+ def _source_eligibility(cls, source: ModelHubSourceConfig, backend: str) -> dict:
+ if cls._eligible_for_agent(source, backend):
+ reason_key = None
+ elif source.kind == "subscription" and backend == "opencode":
+ reason_key = "models.eligibility.opencode_api_key_only"
+ elif source.kind == "subscription":
+ reason_key = "models.eligibility.subscription_wrong_client"
+ else:
+ reason_key = "models.eligibility.consent_required"
+ return {
+ "source_id": source.id,
+ "eligible": reason_key is None,
+ "reason_key": reason_key,
+ }
+
+ @staticmethod
+ def _invalid_source_order(detail: object = None) -> ModelHubError:
+ return ModelHubError(
+ "invalid_source_order",
+ detail=str(detail) if isinstance(detail, str) and detail else None,
+ )
+
+ async def set_agent_sources(self, backend: str, payload: object) -> dict:
+ if backend not in MODEL_HUB_BACKENDS or not isinstance(payload, dict):
+ raise self._invalid_source_order()
+ policy = payload.get("policy")
+ if policy == "follow":
+ if set(payload) != {"policy"}:
+ raise self._invalid_source_order()
+ elif policy == "custom":
+ if set(payload) != {"policy", "order"}:
+ raise self._invalid_source_order()
+ else:
+ raise self._invalid_source_order()
+
+ async with self._mutation_lock:
+ previous = self.store.load()
+ config = self._clone_config(previous)
+ agent = self._agent(config, backend)
+ if policy == "follow":
+ agent.sources.policy = "follow"
+ agent.sources.order = config.recommended_source_order(backend)
+ else:
+ order = payload.get("order")
+ if not isinstance(order, list):
+ raise self._invalid_source_order()
+ seen: set[str] = set()
+ by_id = {source.id: source for source in config.sources}
+ for source_id in order:
+ if (
+ not isinstance(source_id, str)
+ or source_id in seen
+ or source_id not in by_id
+ or not self._eligible_for_agent(by_id[source_id], backend)
+ ):
+ raise self._invalid_source_order(source_id)
+ seen.add(source_id)
+ agent.sources.policy = "custom"
+ agent.sources.order = list(order)
+ self.store.save(config)
+ return self._agent_payload(config, agent)
+
+ def get_agent_sources(self, backend: str) -> dict:
+ config = self.store.load()
+ return self._agent_payload(config, self._agent(config, backend))
+
def _available_model_ids(self, config: ModelHubConfig, backend: str) -> set[str]:
return {
model.id
@@ -1128,12 +1217,16 @@ class ModelHubService:
def _agent_payload(self, config: ModelHubConfig, agent: ModelHubAgentSupplyConfig) -> dict:
backend = cast(BackendName, agent.backend)
+ builtin_models = list(_builtin_model_ids(agent.backend)) if agent.menu_kind == "fixed" else None
+ standard_vendors = sorted(STANDARD_OPENCODE_VENDOR_IDS) if agent.backend == "opencode" else None
+ requested_model = self._requested_model(agent)
+ unavailable_source_ids = self._unavailable_native_sources(config, backend)
resolution = resolve_model_hub_turn(
config,
backend,
- self._requested_model(agent),
+ requested_model,
now=self.now(),
- unavailable_source_ids=self._unavailable_native_sources(config, backend),
+ unavailable_source_ids=unavailable_source_ids,
)
current = (
{
@@ -1144,16 +1237,78 @@ class ModelHubService:
if resolution.source is not None
else None
)
- # Read-only projections (agent-supply.schema.json v1.2, integration 2026-07-24):
- # fixed-menu backends expose their built-in catalog; opencode exposes the
- # standard vendor prefixes. Both are populated straight from the backend
- # modules so the UI never hand-mirrors a menu or vendor list. Not persisted
- # config — injected here exactly like `current`.
- builtin_models = list(_builtin_model_ids(agent.backend)) if agent.menu_kind == "fixed" else None
- standard_vendors = sorted(STANDARD_OPENCODE_VENDOR_IDS) if agent.backend == "opencode" else None
+ menu_model_ids = (
+ builtin_models if builtin_models is not None else list(agent.menu.checked if agent.menu else ())
+ )
+ model_supply = [
+ {
+ "model_id": model_id,
+ "chain_length": len(
+ resolve_model_hub_turn(
+ config,
+ backend,
+ model_id,
+ now=self.now(),
+ unavailable_source_ids=unavailable_source_ids,
+ ).matching_sources
+ ),
+ }
+ for model_id in menu_model_ids
+ ]
+ sources = (
+ {
+ "policy": agent.sources.policy,
+ "order": config.effective_source_order(agent.backend),
+ "eligibility": [
+ self._source_eligibility(source, agent.backend)
+ for source in sorted(config.sources, key=lambda item: item.id)
+ ],
+ }
+ if agent.mode == "hub"
+ else None
+ )
+ selected_by_agent = (
+ self.selected_agent_override(backend)
+ if agent.mode == "hub" and self.selected_agent_override is not None
+ else None
+ )
+ named_agents = []
+ if self.named_agents_override is not None:
+ for name, pinned_model in self.named_agents_override(backend):
+ requested = str(pinned_model or "").strip() or self._backend_default_model(
+ backend
+ )
+ named_resolution = resolve_model_hub_turn(
+ config,
+ backend,
+ requested,
+ now=self.now(),
+ unavailable_source_ids=unavailable_source_ids,
+ )
+ named_agents.append(
+ {
+ "name": name,
+ "effective_model_id": named_resolution.requested_model or None,
+ "supply_status": (
+ named_resolution.supply_status
+ if agent.mode == "hub" and named_resolution.requested_model
+ else None
+ ),
+ }
+ )
return {
**agent.to_payload(),
+ "selected_by_agent": selected_by_agent,
+ "selected_model_id": (resolution.requested_model or None) if agent.mode == "hub" else None,
"current": current,
+ "sources": sources,
+ "supply_status": (
+ resolution.supply_status
+ if agent.mode == "hub" and resolution.requested_model
+ else None
+ ),
+ "model_supply": model_supply if agent.mode == "hub" else None,
+ "named_agents": named_agents,
"builtin_models": builtin_models,
"standard_vendors": standard_vendors,
}
@@ -1294,17 +1449,38 @@ class ModelHubService:
config = self.store.load()
config.subscription_hub_experimental = True
self.store.save(config)
- return _oauth_payload(flow, channel=channel)
+ return {"flow": _oauth_payload(flow, channel=channel)}
+
+ def _oauth_result(
+ self,
+ flow_id: str,
+ flow: OAuthFlowState,
+ *,
+ channel: OAuthChannel,
+ ) -> dict:
+ result = {"flow": _oauth_payload(flow, channel=channel)}
+ if flow.state != "success":
+ return result
+ binding = self._oauth_binding(flow_id)
+ source = self._completed_oauth_source(binding)
+ if source is None:
+ raise ModelHubError("flow_not_found", status=404)
+ result.update(self._source_creation_result(source.to_payload()))
+ return result
async def oauth_status(self, flow_id: str) -> dict:
binding = self._oauth_binding(flow_id)
completed = self._completed_oauth_flow(flow_id, binding)
if completed is not None:
- return _oauth_payload(completed, channel=binding.channel)
+ return self._oauth_result(
+ flow_id,
+ completed,
+ channel=binding.channel,
+ )
flow = await self._oauth_status(flow_id, binding.channel)
self._raise_if_flow_expired(flow_id, flow)
flow = await self._materialize_completed_oauth(flow_id, binding, flow)
- return _oauth_payload(flow, channel=binding.channel)
+ return self._oauth_result(flow_id, flow, channel=binding.channel)
async def oauth_submit(self, payload: dict) -> dict:
flow_id = payload.get("flow_id") if isinstance(payload, dict) else None
@@ -1314,7 +1490,11 @@ class ModelHubService:
binding = self._oauth_binding(flow_id)
completed = self._completed_oauth_flow(flow_id, binding)
if completed is not None:
- return _oauth_payload(completed, channel=binding.channel)
+ return self._oauth_result(
+ flow_id,
+ completed,
+ channel=binding.channel,
+ )
current = await self._oauth_status(flow_id, binding.channel)
self._raise_if_flow_expired(flow_id, current)
flow = await self._oauth_call(
@@ -1322,7 +1502,7 @@ class ModelHubService:
flow_id=flow_id,
)
flow = await self._materialize_completed_oauth(flow_id, binding, flow)
- return _oauth_payload(flow, channel=binding.channel)
+ return self._oauth_result(flow_id, flow, channel=binding.channel)
async def oauth_cancel(self, flow_id: object) -> None:
if not isinstance(flow_id, str):
@@ -1620,6 +1800,10 @@ def create_default_service(
adapter: Optional[EngineAdapter] = None,
native_oauth_adapter: Optional[NativeOAuthAdapter] = None,
requested_model_override: Optional[Callable[[BackendName], Optional[str]]] = None,
+ selected_agent_override: Optional[Callable[[BackendName], Optional[str]]] = None,
+ named_agents_override: Optional[
+ Callable[[BackendName], list[tuple[str, Optional[str]]]]
+ ] = None,
) -> ModelHubService:
if adapter is None:
from vibe.model_hub_runtime import get_model_hub_engine_adapter
@@ -1662,4 +1846,6 @@ def create_default_service(
revocations=CredentialRevocationJournal(paths.get_state_dir() / "model_hub_pending_revocations.json"),
migration_claude_oauth_probe=claude_oauth_probe,
requested_model_override=requested_model_override,
+ selected_agent_override=selected_agent_override,
+ named_agents_override=named_agents_override,
)
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 05023b21f..3fceb63f7 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -1,9 +1,9 @@
# Model Hub — Interface Contracts
-Status: **FROZEN v2** · 2026-07-29 · change only via orchestrator
-Supersedes FROZEN v1 (2026-07-23 10:45) outright — no back-compat, no migration shims.
+Status: **FROZEN v3** · 2026-07-29 · change only via orchestrator
+Supersedes FROZEN v2 outright — no back-compat, no migration shims.
Derived from: spec v2 (`../model-hub.md`), implementation plan
-(`../model-hub-implementation.md`, v1 — a v2 lane plan is cut separately),
+(`../model-hub-implementation.md`),
spike S1 engine survey (`docs/plans/model-hub-engine-survey.md`),
spike S2 ToS review (`docs/plans/model-hub-tos-review.md`).
@@ -27,6 +27,32 @@ Cooldown and health stay **source-global**, deliberately: quota exhaustion and
network reachability are properties of the account, not of the agent that happened
to touch it (`core/handlers/model_hub/service.py::_cooldown`).
+## v3 handoff notes (single freeze, orchestrator 2026-07-29)
+
+v3 is the batch's only post-v2 contract state. L1 authors this freeze once; every
+later lane treats `model-hub-contracts/**` as read-only and implements against it.
+An implementation-proven mismatch is escalated for a targeted v4 rather than edited
+in a later lane. No v3 term is deferred to v4.
+
+Client-visible changes:
+
+- `GET /api/models/agents` adds `named_agents`, with each enabled named Agent's
+ effective model and live `supply_status`.
+- Hub with no explicit Agent model and no backend default reports a null selection,
+ null `current`, and null rollup. This is deliberate: no pinned selection means each
+ turn resolves the model carried by that request. Choosing `builtin_models[0]` would
+ invent state the user never selected, the same false-state class as a fabricated
+ source or recovery.
+- Direct chain/probe calls and Direct or ambiguously unattributed provenance reads
+ return documented errors instead of fabricated Hub data.
+- Turn provenance adds `outcome: canceled` and `canceled_attempt`; resolution events
+ allow `model_id: null` only for source-scoped system events.
+- Canonical `src_` patterns, closed eligibility reasons, repair confirmations,
+ credential force, blocked-source re-test, enabled-mapping guard scope, and durable
+ revocation reconciliation are frozen in `api.md` and the schemas.
+- Resolution events remain single records. v3 adds neither affected-backend fan-out
+ nor an attribution-grain marker.
+
## Resolved decision, carried forward from v1 (owner, 2026-07-23 10:33)
**Hybrid supply by default + consent-gated experimental hub-held subscriptions.**
@@ -50,13 +76,13 @@ order after any mutation; clients never compute partial reorders.
## Freeze protocol
- The orchestrator commits these files with message
- `docs(model-hub): freeze interface contracts v2` and announces the commit SHA
+ `docs(model-hub): freeze interface contracts v3` and announces the commit SHA
in every lane brief. From then on: lanes cite, never edit; changes go through
the orchestrator and bump `contract_version`.
- Contract tests (implementation plan §5) validate both directions against
these schemas.
-## Required-vs-optional discipline (v2)
+## Required-vs-optional discipline (v3)
Contracts land before implementation, so v2 fields describe a destination the
shipped v1 serializers have not reached yet. The rule that keeps that honest:
@@ -70,7 +96,7 @@ shipped v1 serializers have not reached yet. The rule that keeps that honest:
cannot compute a value has to say so explicitly.
- **Fields grafted onto a live v1 serializer are optional here and REQUIRED at the
API boundary once that serializer lands them.** That covers
- `agent-supply.sources` / `supply_status` / `model_supply` /
+ `agent-supply.sources` / `supply_status` / `model_supply` / `named_agents` /
`selected_model_id`, `source.created_at`, `source.usage.projected_exhaust_at`
and `resolution-event.severity`. Each such property says so in its own
`description`; the implementation PR flips it to `required` in the same change
@@ -95,8 +121,8 @@ shipped v1 serializers have not reached yet. The rule that keeps that honest:
pattern it kept finding was the same one twice: a constraint stated in a
`description` while the shape still permitted its negation. Now conditionals —
`kind: needs_action` pinning `severity: action_required` and its four causes
- (a revoked key that validates as `info` is an alert the user silently never
- gets); `reachable: true` pinning non-null `source_id` / `model_id` /
+ (a revoked key that validates as `info` is presented as self-healing);
+ `reachable: true` pinning non-null `source_id` / `model_id` /
`via_mapping` / `latency_ms` and a null `error` (「答了,但不知道是谁答的,另附失败原因」
was a valid probe); `outcome: failed_terminal` and the `terminal_error` slot
beside `served`; every `outcome` branch now pinning the slots it *forbids*, not
@@ -106,7 +132,7 @@ shipped v1 serializers have not reached yet. The rule that keeps that honest:
- **A predicate has exactly one home** (added 07-29, round 3). Round 2 restated the
`waiting`/`interrupted` split in three files and got it wrong in two — 「每个成员都
需要用户处理」 instead of 「至少一个」 — which made a mixed chain match no value and
- suppressed the action-required push. Likewise the 跟随推荐 recommendation rule,
+ suppressed the action-required state. Likewise the 跟随推荐 recommendation rule,
paraphrased in `agent-supply.policy` in a way that excluded the hub-held
subscription the spec admits. Both now point at spec §4.5 / §4.2 and paraphrase
nothing. A determinism rule that two files describe differently is not one.
@@ -143,8 +169,8 @@ shipped v1 serializers have not reached yet. The rule that keeps that honest:
creation paths. And `resolution-event.reason: unclassified_error` closes a taxonomy
hole: `state.status: error` is a blocker (`agent-chain` has always counted it with
`needs_action`), so an interruption caused by the last runnable source erroring had
- a push obligation and no representable event — the emitter had to misclassify or
- stay silent. It became a fifth CAUSE rather than a ninth kind, which keeps the
+ no representable state event — the emitter had to misclassify or stay silent.
+ It became a fifth CAUSE rather than a ninth kind, which keeps the
reason↔`detail_key` correspondence a bijection and leaves the standing 「four causes
do not imply `kind: needs_action`」 ruling untouched. The sequencing finding is the
one worth remembering as a rule: **a documented sequence must be executable through
@@ -173,10 +199,9 @@ shipped v1 serializers have not reached yet. The rule that keeps that honest:
answered 「谁明确写了这个模型」 and therefore returned an empty list on a real
interruption, which is false reassurance where the product owes the user a named
cause and a named victim. The remaining finding was a GRAIN mismatch that default
- naming had hidden: 「Agent」 on an event is a backend, 「Agent」 in routing is a named
- Vibe Agent, and the two coincide only because the default Agents are named after
- their backends — so §4.5's recipient rule now expands in two hops, backend → enabled
- Agents on it → scopes selecting those Agents.
+ naming had hidden: 「Agent」 on an event is a backend, while `named_agents` is a
+ live projection of named Vibe Agents. The two coincide only for a default Agent
+ whose name happens to equal its backend.
- **Round 7's other class was vocabulary blast radius, and it is now mechanical.**
Round 6 added one cause to two files and left the three other files that mirror that
vocabulary asserting an identity they no longer had — a required field with no legal
@@ -209,25 +234,26 @@ a MECHANICAL RULE, and the harness evaluates the rule rather than trusting the p
including the inverse direction: **a field whose description names another contract file
must appear in this table.** Adding a value to a home field is therefore never a local
edit; this table is the list of files that edit reaches.
+The executable source of this table is `mirror-registry.json`; the contract harness
+loads it and mutation-tests every comparable row.
| # | Vocabulary | Home | Mirrors | Rule |
| --- | --- | --- | --- | --- |
| M1 | the ten `detail_key` values (5 cooldown + 4 needs_action + 1 error) | `source.schema.json` → `state`, across all three status branches — the `error` key is pinned as a `const`, which counts | `probe-result.schema.json` → `error` (minus null), and the `examples` list on the home field itself | `equality` |
| M2 | source status → chain health | `source.schema.json` → `state.status` | `agent-chain.schema.json` → `chain[].health` | `projection` |
| M3 | attempt-failure causes | `resolution-event.schema.json` → `reason` | `turn-provenance.schema.json` → `failed_attempts[].reason` | `partition` |
-| M4 | non-self-healing cause ↔ blocking `detail_key` | `resolution-event.schema.json` → `reason` description | `source.schema.json` → the `needs_action` and `error` `detail_key` branches | `none` |
-| M5 | the supply-state taxonomy | `agent-supply.schema.json` → `supply_status` | `agent-chain.schema.json` → `supply_state`; `turn-provenance.schema.json` → `model_supply_state` | `projection` |
-| M6 | backend identifiers | `agent-supply.schema.json` → `backend` | `agent-chain.schema.json` and `probe-result.schema.json` → `backend`; `turn-provenance.schema.json` → `agent` | `equality` |
-| M7 | supply channel | `source.schema.json` → `supply_channel` | `agent-supply.schema.json` → `current.channel`; `turn-provenance.schema.json` → `failed_attempts[].channel`, `served.channel`, `terminal_error.channel` | `equality` |
+| M4 | non-self-healing cause ↔ blocking `detail_key` | `resolution-event.schema.json` → `reason` | `source.schema.json` → the `needs_action` and `error` `detail_key` branches | `bijection` |
+| M5 | the supply-state taxonomy | `agent-supply.schema.json` → `supply_status` | `named_agents[].supply_status`; `agent-chain.schema.json` → `supply_state`; `turn-provenance.schema.json` → `model_supply_state` | `projection` |
+| M6 | backend identifiers | `agent-supply.schema.json` → `backend` | `agent-chain.schema.json` and `probe-result.schema.json` → `backend`; `turn-provenance.schema.json` and `resolution-event.schema.json` → `agent` (`system` is the declared event-only extra) | `equality` |
+| M7 | supply channel | `source.schema.json` → `supply_channel` | `agent-supply.schema.json` → `current.channel`; all four turn-provenance attempt slots | `equality` |
| N1 | source recommendation rule | `agent-supply.schema.json` → `sources.policy` | — | `none` |
What the rules mean, and why three of them are not equality:
- **`equality`** — the sets are identical, in both directions. M6 carries one declared
- superset: `resolution-event.agent` is the home set plus `system`, the emitter for
- events no backend produced, which expands to no Agent and therefore to no recipient.
- A documented superset is checked as `home ∪ {declared extras}`, so a *fourth* backend
- appearing there alone still fails.
+ superset: `resolution-event.agent` is the home set plus `system`, used for a
+ source-scoped non-turn operation. A documented superset is checked as
+ `home ∪ {declared extras}`, so a fourth backend appearing there alone still fails.
- **`projection`** — the mirror is a stated function of the home, because the two live
at different grains. M2: `health` carries the health half only, so `active`/`standby`
collapse into `healthy`. M5: one taxonomy at two grains — the backend rollup adds
@@ -241,27 +267,25 @@ What the rules mean, and why three of them are not equality:
on the branch that pins `kind: supply_interrupted` — and `recovery`/`manual`/`mapping`
are declared, because a resolution that is not a failure has no attempt to report. A
new `reason` fails the check until it is classified, which is the point.
-- **`none`** — registered as non-comparable, with the reason. M4 is a BIJECTION, not a
- set identity: a permuted pairing has identical sets, so it is checked against the
- mapping documented in the home field's own description instead. N1 is a pointer to a
- rule (spec §4.2 plus the absent-`created_at` half-rule), not a shared value set —
- there is nothing to compare. A row with neither rule nor reason is itself a failure.
+- **`bijection`** — M4 checks both sets and each explicit cause→detail-key pair;
+ a permuted pairing therefore fails even when the two sets still match.
+- **`none`** — registered as non-comparable, with the reason. N1 is a pointer to a
+ rule, not a shared value set. A row with neither rule nor reason is itself a failure.
## Files
| File | Consumers |
| --- | --- |
| `source.schema.json` | L2 API, L4 UI. **v2:** +`state.status: needs_action` (+ mandatory `detail_key` there, enforced by an `if/then`), +immutable `created_at` (the sort key 跟随推荐 needs) with its **null placement now normative (07-29)** — absent sorts before every stamp, constant-epoch backfill, because a tie-break orders equals and cannot order null against a timestamp — +optional `usage.projected_exhaust_at`. No ordering field, ever. |
-| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI. **v2 owns the spend order:** +`sources` {policy, order, eligibility}, +`supply_status` (incl. `waiting`), +`model_supply`, +top-level `selected_model_id`. **07-29 round 3:** the selection was hoisted out of `current` (where round 2 had it as `menu_model_id`) because `current` is null in `waiting`/`interrupted` — the two states where the drawer most needs to name the model. A persisted user choice must not inherit the nullability of a momentary fact. `policy` also stopped paraphrasing the 跟随推荐 rule and now points at spec §4.2. **+`selected_by_agent`** names the GRAIN of that selection — which Vibe Agent's `model` produced it, null when it came from `agents.<backend>.default_model` — because N Agents can share one backend with different models, so `selected_model_id` on its own answers for nobody in particular. It names a grain and does NOT reverse the frozen per-Agent ordering ruling. It is required on every hub-mode response at the API boundary (`api.md`) rather than by `required` here, for the byte-faithful reason below. |
+| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI. Owns `sources`, the selected-route rollup, and v3 `named_agents`. Hub with no pinned selection keeps `selected_model_id`, `current`, and `supply_status` null; the server never invents `builtin_models[0]`. |
| `agent-chain.schema.json` | **New in v2.** L2 API, L4 UI (model box drill-in, 模型菜单 drawer). Carries the CAPABILITY chain — cooling members included with `runnable: false` — and per-item `health` only; per-agent role is positional, never a copied `active`/`standby`. **+`supply_state` (07-29):** the three-class taxonomy at the (agent, model) grain, and the ONE field every model-scoped consumer reads (chain drill-in, the probe's `supply` sibling, turn record) so none of them consults the agent rollup for a model it does not describe. Its predicate is not restated here or there — spec §4.5 owns it, after round 3 found two files paraphrasing it into a different rule. |
| `probe-result.schema.json` | **New in v2.** L2 API, L4 UI (「试跑一次」). Outcome field is `reachable`; the object nests under `probe` so it never collides with the envelope's `ok`. **07-29 round 3:** `reachable` now drives conditionals in both directions, so a reachable probe cannot carry null ids or an error; and `probe_no_candidate` moved its structured half out of `detail` into a typed `supply` sibling — the shipped clients declare `detail?: string`, so the object would have rendered as `[object Object]`. It reads the requested model's `supply_state`, never `supply_status`. |
-| `turn-provenance.schema.json` | **New in v2.** L2 API, L3 (writes it per turn), IM surfaces (per-turn detail). Gives spec §4.5's turn-provenance promise an actual read contract. **Shape ruling 07-29:** top-level `outcome` + `failed_attempts` + one slot for the terminating attempt; the empty attempt list is legal because a turn that never touched a source is exactly the one users inspect, and the terminating attempt lives in one place so contradictory records cannot be written at all. **Round 3 added the fourth outcome:** `failed_terminal` + a `terminal_error` slot, for §4.3's non-fallback errors (param/protocol/tool-compat, and anything after the first streamed token). Without it such a turn fit no outcome, and filing it as `exhausted` would have forced a fallback reason onto it — blaming the user's account for a malformed request. |
-| `priority.schema.json` | **Removed in contract v2 — v1 tombstone, do not implement.** Nothing in v2 reads it. Kept only because dormant v1 code still emits the shape and `tests/test_model_hub_api.py` still validates against it; the lane that removes `PUT /api/models/priority` and `ModelHubConfig.priority_order` deletes this file and replaces that one assertion with an inline shape check. |
-| `resolution-event.schema.json` | L2 (adapter-owned), L4 UI, L1 adapter. **v2:** +`severity` (notification tier), +`kind: needs_action`, +`kind: supply_interrupted` — the only AGENT-scoped kind, for a chain that empties without any source changing state (last enabled source removed). Its shape is enforced by conditionals, not prose: `severity` is `action_required`, source endpoints are null, and its three reasons are unusable with any other kind. Worked payload in `api.md` (a schema example would need `severity`, which the shipped emitter has no field for). **Round 5 (07-29):** `severity` decides WHETHER to interrupt, never WHOM — there is deliberately no recipient, channel, platform, or audience field, and recipients resolve at push time from the event's `agent` against the live routing table (spec §4.5 → 「Who receives an action-required push」). Carrying them here would freeze a routing snapshot into an append-only feed; the feed is a record of what happened to supply, not an outbox. |
+| `turn-provenance.schema.json` | L2 API, L3 writer. v3 adds the FSM-truth `canceled` outcome and a reason-free `canceled_attempt` slot. Records exist only when attribution is exact; Direct and ambiguous absence are route errors in `api.md`. |
+| `resolution-event.schema.json` | L2 emitter, L4 UI. v3 permits nullable `model_id` only for source-scoped system events, rejects `system` on backend-scoped interruption, and keeps one record with impact derived live. |
| `oauth-flow.schema.json` | L2, L4 UI, L1 engine adapter |
| `migration-scan.schema.json` | L6, L5 UI. Unchanged by the v2 ruling — native-config import is an onboarding feature, not a priority mechanism. |
| `runtime-dependency.schema.json` | L1, L2 status API, L7 guards. **URL policy (orchestrator, 07-23 12:05):** the example URLs are placeholders; L1 ships with upstream release URLs + SHA256 integrity verification. Availability guard = L7/orchestrator deliverable BEFORE GA: mirror the pinned assets into Avibe-owned release storage (same manifest-verified backup/recovery pattern as Show Runtime, per repo release rules), then point the manifest at the mirror with upstream recorded as provenance. SHA256s never change (same bytes). L1 must NOT build the mirror or touch the Show Runtime guard. **Platform expansion (07-23 13:13):** linux-arm64 / darwin-x64 assets get pinned (+ schema platform-enum rev) together with the mirror work at L7; until then unsupported hosts fail closed, Direct = escape hatch (L1's `model_hub_engine_platform_unsupported` coverage is the intended behavior). **Cross-vendor note (07-29):** if the v2.1 cross-vendor spike (spec §10.4) concludes that a conversion pair needs a CPA plugin or a different engine build, that lands here as a pin + SHA256 revision with mirrored assets published before the manifest moves — never as user-facing configuration. |
-| `api.md` | all. **v2:** `PUT /api/models/priority` removed; +`PUT /api/models/agents/<backend>/sources`, +chain query, +probe, +`adopted_by`. **07-29 round 3:** +`PUT /api/models/sources/<id>/credential` and +`POST /api/models/sources/<id>/reauth` — spec §4.5 promised the `needs_action` card a one-tap 「换 Key / 重新登录」 and there was no route to send that tap to, only create-a-new-source, which loses the source's `created_at` and its slot in every order. Recovery must not be a reorder. Also: the `detail`-is-a-string rule made normative, and the DELETE guard re-scoped to (backend, model) — a backend with four enabled sources still starves a model supplied by only the one being deleted. |
+| `api.md` | All route and envelope contracts. v3 defines Direct errors, named-Agent reads, repair acknowledgement/force, blocked-source re-test, the enabled-mapping guard, and durable pending revocations. |
| `opencode-overlay.md` | L3, L7 (identifier-stability tests). Identifiers stay stable across per-agent reordering — a source is never encoded into the provider segment. |
| `adapter-interface.py` | L1 (implements), L2 (consumes; owns in-repo copy). Dual-copy rule: both lanes copy VERBATIM to `core/handlers/model_hub/adapter.py` in their branches — byte-identical, merge is a no-op. Added 07-23 10:55 after L1 raised the ordering race; **v1.1 07-23 11:05**: +OAuth surface with deterministic source binding (`start_oauth(source_id)` → success carries `credential_ref`), +`allowed_origins`/`invoke(origin)`/`OriginNotAllowedError` (both from L1 review findings). Unchanged by v2: candidate walking and error classification stay Python-side, so moving ordering from global to per-agent needs no adapter or engine change (spec §8). |
diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.json
index 2fef2a0ba..ac58ee049 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", "supply_state"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 2 },
+ "contract_version": { "const": 3 },
"backend": { "enum": ["claude", "codex", "opencode"] },
"model_id": {
"type": "string",
@@ -101,7 +101,7 @@
},
"supply_state": {
"enum": ["ok", "waiting", "interrupted"],
- "description": "v2 (07-29, review round 2): the MODEL-SCOPED supply state — the same three-class taxonomy as agent-supply `supply_status`, evaluated for THIS (agent, model) pair instead of the backend as a whole. The predicate is spec §4.5's, verbatim, and is stated once there: `ok` = at least one `runnable: true` item. Otherwise the chain is blocked, and the split is on whether the user owes an action — `interrupted` = the chain is empty, or AT LEAST ONE blocker needs the user (`needs_action` / `error`) — 「需处理」; `waiting` = chain non-empty and EVERY blocker is a cooldown, so it recovers unattended at the earliest `retry_at` — 「稍等即可」. Corrected 07-29 (review round 3): round 2 wrote `interrupted` as 'every member needs the user', which left the mixed chain — one cooling source plus one revoked key — matching neither class, so the (agent, model) grain silently disagreed with `supply_status` (which had 'at least one' all along) and suppressed the action-required push for exactly the case that needs it most. `interrupted` is the OR-branch and `waiting` the AND-branch; in that order the two are total over every blocked chain, and a chain that needs the user is never reported as one that heals itself. Exists because the agent-level rollup answers only for the backend's CURRENT model: a user can inspect, probe, or request a model that is starved while the selected one is perfectly healthy, and consulting the rollup there reports `ok` for a chain that cannot run. Every consumer of a model-scoped answer reads this one field — the chain drill-in, `probe_no_candidate`'s typed `supply` sibling (api.md), and TurnProvenance `model_supply_state` — so 「稍等即可」 vs 「需处理」 has exactly one definition per grain."
+ "description": "v2 (07-29, review round 2): the MODEL-SCOPED supply state — the same three-class taxonomy as agent-supply `supply_status`, evaluated for THIS (agent, model) pair instead of the backend as a whole. The predicate is spec §4.5's, verbatim, and is stated once there: `ok` = at least one `runnable: true` item. Otherwise the chain is blocked, and the split is on whether the user owes an action — `interrupted` = the chain is empty, or AT LEAST ONE blocker needs the user (`needs_action` / `error`) — 「需处理」; `waiting` = chain non-empty and EVERY blocker is a cooldown, so it recovers unattended at the earliest `retry_at` — 「稍等即可」. Corrected 07-29 (review round 3): round 2 wrote `interrupted` as 'every member needs the user', which left the mixed chain — one cooling source plus one revoked key — matching neither class, so the (agent, model) grain silently disagreed with `supply_status` (which had 'at least one' all along) and suppressed the action-required state for exactly the case that needs it most. `interrupted` is the OR-branch and `waiting` the AND-branch; in that order the two are total over every blocked chain, and a chain that needs the user is never reported as one that heals itself. Exists because the agent-level rollup answers only for the backend's CURRENT model: a user can inspect, probe, or request a model that is starved while the selected one is perfectly healthy, and consulting the rollup there reports `ok` for a chain that cannot run. Every consumer of a model-scoped answer reads this one field — the chain drill-in, `probe_no_candidate`'s typed `supply` sibling (api.md), and TurnProvenance `model_supply_state` — so 「稍等即可」 vs 「需处理」 has exactly one definition per grain."
}
},
"allOf": [
@@ -127,7 +127,7 @@
}
},
{
- "$comment": "v2 (07-29, review round 4): and the waiting/interrupted split, which is where §4.5's asymmetry becomes checkable. `waiting` is the AND-branch — non-empty chain, EVERY blocker a cooldown — so a chain holding one revoked key cannot be reported as one that heals itself, which is exactly the suppressed action_required push the round-3 correction was about. `interrupted` is the OR-branch: empty chain, or at least one member the user has to fix. In that order the two are total over every blocked chain.",
+ "$comment": "v2 (07-29, review round 4): and the waiting/interrupted split, which is where §4.5's asymmetry becomes checkable. `waiting` is the AND-branch — non-empty chain, EVERY blocker a cooldown — so a chain holding one revoked key cannot be reported as one that heals itself, which is exactly the suppressed action_required state the round-3 correction was about. `interrupted` is the OR-branch: empty chain, or at least one member the user has to fix. In that order the two are total over every blocked chain.",
"if": { "properties": { "supply_state": { "const": "waiting" } }, "required": ["supply_state"] },
"then": {
"properties": {
@@ -181,7 +181,7 @@
],
"examples": [
{
- "contract_version": 2,
+ "contract_version": 3,
"backend": "claude",
"model_id": "claude-opus-4-6",
"chain": [
@@ -205,14 +205,14 @@
"supply_state": "ok"
},
{
- "contract_version": 2,
+ "contract_version": 3,
"backend": "claude",
"model_id": "claude-haiku-4-5",
"chain": [],
"supply_state": "interrupted"
},
{
- "contract_version": 2,
+ "contract_version": 3,
"backend": "codex",
"model_id": "gpt-5.3-codex",
"chain": [
diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.json
index 8ac0205d4..5da00a74c 100644
--- a/docs/plans/model-hub-contracts/agent-supply.schema.json
+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json
@@ -2,7 +2,7 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/agent-supply.schema.json",
"title": "AgentSupply",
- "description": "Per-backend supply strategy & status (spec §4.2, frames V6 01–04 / M01–M02). v2: this record OWNS the spend order. Ordering is a consumption property — each backend keeps its own ordered subset of the sources it is eligible for. There is no global priority list.",
+ "description": "Per-backend supply strategy and live status (spec §4.2, frames V6 01–04 / M01–M02). v3 keeps the spend order at the backend grain and adds the enabled named-Agent projection used to attribute model supply honestly.",
"type": "object",
"required": ["backend", "mode", "menu_kind"],
"additionalProperties": false,
@@ -39,7 +39,7 @@
},
"sources": {
"type": ["object", "null"],
- "description": "v2 (2026-07-29): this backend's source order — the ordered SUBSET of sources it spends, plus the policy that governs the order (spec §4.2). Replaces v1's global priority.schema.json. Optional in this schema only because the shipped v1 serializer predates it; it becomes REQUIRED at the API boundary in the serializer PR that lands per-agent ordering (README → Required-vs-optional). null while mode=direct.",
+ "description": "This backend's source order — the ordered SUBSET of sources it spends, plus the policy that governs the order (spec §4.2). Replaces the removed global priority contract. Optional in this schema only because the frozen legacy examples predate it; it is REQUIRED at the API boundary. null while mode=direct.",
"required": ["policy", "order"],
"additionalProperties": false,
"properties": {
@@ -70,7 +70,13 @@
"then": {
"required": ["reason_key"],
"properties": {
- "reason_key": { "type": "string", "minLength": 1 }
+ "reason_key": {
+ "enum": [
+ "models.eligibility.subscription_wrong_client",
+ "models.eligibility.opencode_api_key_only",
+ "models.eligibility.consent_required"
+ ]
+ }
}
}
},
@@ -90,8 +96,13 @@
"source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
"eligible": { "type": "boolean" },
"reason_key": {
- "type": ["string", "null"],
- "description": "i18n key explaining an ineligible source (e.g. models.eligibility.subscription_wrong_client, models.eligibility.opencode_api_key_only, models.eligibility.consent_required). REQUIRED and non-null when `eligible` is false, null when it is true — both pinned by the conditionals above (07-29, review round 4), because 不适用 with no cause is a row the drawer cannot act on."
+ "enum": [
+ "models.eligibility.subscription_wrong_client",
+ "models.eligibility.opencode_api_key_only",
+ "models.eligibility.consent_required",
+ null
+ ],
+ "description": "Closed i18n-key vocabulary explaining an ineligible source. REQUIRED and non-null when `eligible` is false, null when it is true. A new eligibility cause therefore requires an explicit contract and locale change."
}
}
}
@@ -101,7 +112,7 @@
"supply_status": {
"type": ["string", "null"],
"enum": ["ok", "degraded", "waiting", "interrupted", null],
- "description": "v2: derived per-agent health rollup (spec §4.5), computed per request and never persisted, for the model of the route named by `selected_by_agent` — not for every model this backend can be asked for (§4.5 'two grains, one taxonomy'; grain of the selection itself corrected in round 4). Split on the SAME question as source status — does it heal itself: ok = serving from the intended head of the chain; degraded = serving via a fallback and/or some chain members are down (still running); waiting = nothing runnable right now but every blocker is a cooldown, so it recovers unattended at the earliest `retry_at` (UI: 「暂时全部在冷却」, feed only, NEVER an IM push); interrupted = nothing runnable and at least one blocker needs the user (needs_action / error), or the capability chain is structurally EMPTY (UI: 「当前无可用来源」, `severity: action_required`, proactive push). waiting exists precisely so an all-cooling agent does not trip the push path — pushing there would contradict the rule that self-healing states never interrupt the user. interrupted is otherwise the state v1 could not express: a populated source list while this particular agent has nothing to call. null when mode=direct."
+ "description": "Derived health rollup (spec §4.5), computed per request and never persisted, for the model of the route named by `selected_by_agent`. ok = serving from the intended head; degraded = serving through fallback and/or with blocked members; waiting = no runnable member and every blocker is a cooldown; interrupted = no runnable member and at least one blocker needs action, or the capability chain is empty. null when mode=direct or when Hub has no pinned selection."
},
"mappings": {
"type": "array",
@@ -152,6 +163,38 @@
}
}
},
+ "named_agents": {
+ "type": "array",
+ "description": "v3 read-only projection of every enabled named Vibe Agent on this backend. It is derived live from each Agent's pinned model, falling back to the backend default when the Agent inherits. The distinct name avoids collision with SupplyGap.agents, whose items are bare names inside a mutation-refusal payload.",
+ "items": {
+ "type": "object",
+ "required": ["name", "effective_model_id", "supply_status"],
+ "additionalProperties": false,
+ "properties": {
+ "name": { "type": "string", "minLength": 1 },
+ "effective_model_id": {
+ "type": ["string", "null"],
+ "description": "The Agent's pinned model, or the inherited backend default, in the caller-facing menu identifier namespace. null means no selection exists."
+ },
+ "supply_status": {
+ "enum": ["ok", "degraded", "waiting", "interrupted", null],
+ "description": "This named Agent's own live rollup for effective_model_id. null in Direct mode or when effective_model_id is null."
+ }
+ },
+ "allOf": [
+ {
+ "if": {
+ "properties": { "effective_model_id": { "type": "null" } },
+ "required": ["effective_model_id"]
+ },
+ "then": {
+ "required": ["supply_status"],
+ "properties": { "supply_status": { "type": "null" } }
+ }
+ }
+ ]
+ }
+ },
"builtin_models": { "type": ["array", "null"], "items": { "type": "string" }, "description": "v1.2 (2026-07-24 integration): fixed-menu backends only — real built-in model ids, server-populated from vibe/backend_model_catalog.py; null for open-menu backends. UI must not hardcode menus." },
"standard_vendors": { "type": ["array", "null"], "items": { "type": "string" }, "description": "v1.2 (2026-07-24 integration): opencode only — server-populated mirror of STANDARD_OPENCODE_VENDOR_IDS (core/handlers/model_hub/identifiers.py) so the UI never hand-mirrors vendor lists; null otherwise." }
},
@@ -166,7 +209,74 @@
"current": { "type": "null" },
"sources": { "type": "null" },
"supply_status": { "type": "null" },
- "model_supply": { "type": "null" }
+ "model_supply": { "type": "null" },
+ "named_agents": {
+ "items": {
+ "required": ["supply_status"],
+ "properties": { "supply_status": { "type": "null" } }
+ }
+ }
+ }
+ }
+ },
+ {
+ "$comment": "v3 Hub-mode half. `sources`, `model_supply`, and `named_agents` are non-null when present. Presence is deliberately enforced at the API boundary rather than here so the two frozen legacy examples, which predate these projections, remain valid. The selection fields are deliberately NOT constrained non-null: Hub with no explicit Vibe-Agent model and no backend default has no pinned selection. In that state each turn resolves the model carried by the request itself, so inventing a menu selection would be false state.",
+ "if": { "properties": { "mode": { "const": "hub" } }, "required": ["mode"] },
+ "then": {
+ "properties": {
+ "sources": { "type": "object" },
+ "model_supply": { "type": "array" },
+ "named_agents": {
+ "type": "array",
+ "items": {
+ "allOf": [
+ {
+ "if": {
+ "properties": { "effective_model_id": { "type": "string" } },
+ "required": ["effective_model_id"]
+ },
+ "then": {
+ "required": ["supply_status"],
+ "properties": {
+ "supply_status": {
+ "enum": ["ok", "degraded", "waiting", "interrupted"]
+ }
+ }
+ }
+ }
+ ]
+ }
+ }
+ }
+ }
+ },
+ {
+ "$comment": "v3 D-1: a missing Hub selection is honest absence, never a projected builtin_models[0]. The route remains usable because a turn carries its own requested model.",
+ "if": {
+ "properties": { "selected_model_id": { "type": "null" } },
+ "required": ["selected_model_id"]
+ },
+ "then": {
+ "required": ["selected_by_agent", "current", "supply_status"],
+ "properties": {
+ "selected_by_agent": { "type": "null" },
+ "current": { "type": "null" },
+ "supply_status": { "type": "null" }
+ }
+ }
+ },
+ {
+ "if": {
+ "properties": { "selected_model_id": { "type": "string" } },
+ "required": ["selected_model_id"]
+ },
+ "then": {
+ "required": ["supply_status"],
+ "properties": {
+ "mode": { "const": "hub" },
+ "supply_status": {
+ "enum": ["ok", "degraded", "waiting", "interrupted"]
+ }
}
}
},
@@ -176,7 +286,7 @@
"then": { "properties": { "current": { "type": "null" } } }
},
{
- "$comment": "v2 (07-29, review round 4): and the converse the field already claimed ('Non-null ⇒ supply_status is ok or degraded'), plus the mode half. A record that names a serving source while reporting a blocked rollup is contradictory in the other direction, and either half alone leaves that payload writable. PRESENCE DELIBERATELY NOT REQUIRED here (07-29, review round 5), the one declared exception to the rule that a non-null `then` constraint must also require its field: this file's frozen examples carry `current` with no `supply_status` at all — they round-trip byte-faithfully through the SHIPPED v1 serializer, which has no such field — so `required: [\"supply_status\"]` would fail the contract gate rather than strengthen it. The obligation moves to the API boundary, where the v2 serializer emits it (README → required-vs-optional). Absence is also the fail-safe direction: no rollup means no claim about health and no push, whereas the dangerous absences (`severity` on a needs_action event, `current` under an ok rollup) are all required above. The exception is enforced as a declared entry in the round-5 presence checker, so 'missing on purpose' cannot decay into 'missing by accident' (api.md → Serializer completeness).",
+ "$comment": "v2 (07-29, review round 4): and the converse the field already claimed ('Non-null ⇒ supply_status is ok or degraded'), plus the mode half. A record that names a serving source while reporting a blocked rollup is contradictory in the other direction, and either half alone leaves that payload writable. PRESENCE DELIBERATELY NOT REQUIRED here (07-29, review round 5), the one declared exception to the rule that a non-null `then` constraint must also require its field: this file's frozen examples carry `current` with no `supply_status` at all — they round-trip byte-faithfully through the SHIPPED v1 serializer, which has no such field — so `required: [\"supply_status\"]` would fail the contract gate rather than strengthen it. The obligation moves to the API boundary, where the v2 serializer emits it (README → required-vs-optional). Absence is also the fail-safe direction: no rollup means no claim about health and no action-required claim, whereas the dangerous absences (`severity` on a needs_action event, `current` under an ok rollup) are all required above. The exception is enforced as a declared entry in the round-5 presence checker, so 'missing on purpose' cannot decay into 'missing by accident' (api.md → Serializer completeness).",
"if": { "properties": { "current": { "type": "object" } }, "required": ["current"] },
"then": {
"properties": {
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 57c9e8329..33bce00d4 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -1,756 +1,442 @@
# Model Hub — REST API contract
-All endpoints live under `/api/models/`. Envelope: success `{ok: true, ...}`;
-failure `{ok: false, error: <machine_code>, detail?: <i18n key or safe text>}`.
-Every response includes `contract_version: 2`. Auth follows existing UI-server
-session auth; localhost curl is rejected the same way as other `/api/*` routes.
-
-**`detail` is a string, and structured failure data goes in a named sibling
-key** (normative, 07-29 review round 3). The shipped client types it as one —
-`ApiErr.detail?: string` and `ApiCallError.detail?: string`
-(`ui/src/components/settings/models/types.ts`, `modelsApi.ts`) — and every
-existing producer fills it with an i18n key or a safe fragment. An error that
-needs a payload therefore adds its own typed field next to `error`, exactly as
-success responses nest `probe` / `agent` / `provenance`, instead of widening
-`detail` to `string | object`. A union there would break both live consumers on
-the first structured error and force every future reader to type-check a field
-whose only job is to be rendered.
-
-> **v2 target, not current runtime.** Contracts land before implementation
-> (the v1 precedent). The shipped-but-dormant v1 serializers still emit
-> `contract_version: 1` and still expose `PUT /api/models/priority`; the
-> serializer PR that lands per-agent ordering bumps the envelope and removes
-> that route in one change. Read this file as the destination.
-
-| Method & path | Req / Resp schema | Notes |
+Status: **FROZEN v3**. All endpoints live under `/api/models/`.
+
+Success envelope: `{ok: true, contract_version: 3, ...}`.
+Failure envelope:
+`{ok: false, contract_version: 3, error: <machine_code>, detail?: <i18n_key>}`.
+`detail` is always a string. Structured error data lives in a named sibling.
+Authentication and CSRF rules are the existing UI-server rules.
+
+## Route table
+
+| Method and path | Request → response | Normative notes |
| --- | --- | --- |
-| GET `/api/models/sources` | → `{sources: Source[]}` | **v2:** an unordered asset inventory. Sources carry no position, rank, or priority field; the array order is display convenience only (never a spend order). Each source does carry immutable `created_at`, which is what 跟随推荐 sorts by — a stored fact about the source, not a position in this array. |
-| POST `/api/models/sources` | `SourceCreate` (kind, vendor, base_url?, key? / oauth flow ref) → `{source: Source, adopted_by: AdoptedBy[]}` | api_key create validates + discovers models (test-and-add, frame V4 06r). The pasted key is TRANSIENT: L2 provisions it into the engine-owned store (`provision_credential`) and persists only the returned `credential_ref`; on persist failure it revokes. Secrets never enter config, logs, or any response. **v2:** the server stamps immutable `created_at` here — it is server-assigned and never accepted from the client, since a client-supplied value could reorder 跟随推荐. **v2 `adopted_by`** closes the "so what now?" loop in the same response — see below. |
-| PATCH `/api/models/sources/<id>` | partial Source (display_name, base_url) → `Source` | metadata only — never credential material. Replacement has its own route below, because "rename it" and "hand me a new key" are different operations with different failure modes. |
-| **PUT** `/api/models/sources/<id>/credential` | `{key}` → `{source: Source, recovered: boolean, interrupted_pairs: SupplyGap[]}` | **v2 (07-29, review round 3).** Replaces the credential of an existing `api_key` source in place. **The sequence, the response shape and the refusal case are defined once, under 「Credential replacement and re-auth」 below** — rewritten there 07-29, review round 6, because three rounds of corrections had left this cell carrying two incompatible orderings of the same steps, the leading one unimplementable against the frozen adapter. **This route exists because spec §4.5 promises the interrupted-source card a one-tap 「换一个 Key」 and there was nowhere to send that tap:** create-a-new-source is not the same operation — it strands the old row, drops the source's position in every backend's `sources.order`, and loses its `created_at`, so 跟随推荐 silently reshuffles as a side effect of fixing a key. Replacement keeps the identity and the order. Same transient-secret rule as create: the plaintext never enters config, logs, or any response. |
-| **POST** `/api/models/sources/<id>/reauth` | → `{flow: OAuthFlow}` | **v2 (07-29, review round 3).** The subscription counterpart: re-runs OAuth **bound to an existing source** rather than creating one, for `credential_expired` / `credential_revoked`. Thin by design — it is `POST /api/models/oauth/start` with `source_id` instead of `{vendor, channel}`, and the adapter surface it needs already exists (`start_oauth(source_id)` with deterministic source binding, adapter-interface v1.1). The flow then polls `/api/models/oauth/status/<flow_id>` like any other; its completion response is defined under 「OAuth completion responses」 below and its repair tail under 「Credential replacement and re-auth」, which is where the channel-specific rule for where the refreshed credential lands also lives. |
-| DELETE `/api/models/sources/<id>` | → `{ok}`, or `{ok: false, error: "source_last_supplier", would_interrupt: SupplyGap[]}` | refuses while the source is the last supplier of a SELECTED model unless `force=true` — "selected" is wider than 「已勾选/已映射」, see the round-5 note at the end of this cell. **v2 re-scopes what "last" counts over:** per affected backend, over that backend's **enabled order** (`sources.order`) — never over eligible inventory. With per-agent ordered subsets a source can be eligible for a backend while absent from its order, so the v1 inventory scan would count an unreachable source as the replacement, allow the delete without `force`, and leave that agent `interrupted` on the next turn (`kind: supply_interrupted`, `reason: no_enabled_source`). **The guard is per (backend, model), not per backend** (corrected 07-29, review round 3): refuse if the delete would leave ANY protected model of ANY affected backend with no runnable supplier, and the confirm copy names those (backend, model) pairs. **Which models are protected, what 「no runnable supplier」 means, and what the refusal carries are ONE definition, stated once under 「The supply guard」 below** (07-29, review round 7) — this cell and the credential routes reference it rather than restating it. Round 6 wrote the test here as `model_supply[].chain_length` becoming 0, which is structural emptiness and a strictly weaker question than the one the guard asks: a chain still holding one revoked key is not empty and cannot serve, so the delete passed unguarded and the agent went `interrupted` on its next turn — the exact surprise this guard exists to prevent, reintroduced by counting rows instead of asking whether any row could run. Round 2 wrote it as "zero enabled suppliers" for the backend, which is a strictly weaker test than the sentence it was meant to implement: a backend with four enabled sources loses nothing by that test, yet deleting the only one that supplies `claude-haiku-4-5` silently starves that model and the user finds out on the next turn. Backend-level emptiness is simply the special case where every protected model hits zero at once. **"checked/mapped" is the wrong protected set — it is every SELECTED model** (corrected 07-29, review round 5): that phrase came from the V4 fixed-menu drawer, where a model earns protection by being checked in the menu or by owning a mapping row. Both tests miss the model a backend is actually running. `agents.<backend>.default_model` is a selection in its own right; so is `agents.<name>.model` for each enabled Vibe Agent; and a fixed-menu model that resolves by IDENTITY (`selected_model_id == resolved_model_id`, no mapping row — `agent-chain.schema.json` → `via_mapping: false`) is mapped in effect while being invisible to any mapping scan. Composed, those gaps let a source be the only supplier of the model the user's `pm` Agent runs on, hold no mapping row, sit unchecked in a menu the user never opened, and be deleted without `force` — the interruption arriving on `pm`'s next turn as `kind: supply_interrupted`, `reason: no_enabled_source`, which is the class of surprise this guard exists to prevent. The protected set is therefore a UNION of four selection facts, enumerated with its identifier namespace under 「The supply guard」 below — where 「mapping targets」 is corrected to the mapping's MENU side (07-29, review round 7): a mapping row rewrites `claude-opus-4-6 → glm-5.2`, so protecting the *target* protects a resolved id the user never selected, loses the built-in model the selection actually names, and coalesces every menu model mapped onto one upstream id into a single gap the client cannot attribute. The fourth term is the frozen per-Agent grain doing its job (see `selected_by_agent` above): with per-Agent ordered subsets there is no single "the backend's model" to test, so the guard has to close over the Agents — and the confirm copy names the Agents, not only the pairs, because 「删除后 pm 将没有可用来源」 is a sentence the user can act on while 「claude / claude-opus-4 将没有可用来源」 is not, when four Agents share that backend. Disabled Agents are deliberately excluded — they cannot take a turn, so their model is not a live capability — but a disabled Agent's model that is ALSO the backend default stays protected through the default term, which is the overlap the union is built to absorb. `force=true` still overrides the whole set; widening the guard changes what the user is warned about, never what they are forbidden. **The refusal is machine-readable** (07-29, review round 6): round 5 promised confirm copy naming the pairs and the Agents but declared no shape for either, so the client had nothing to render it from and no code to switch on. The refusal is `ok: false`, `error: "source_last_supplier"`, with the affected pairs in `would_interrupt` — the `SupplyGap` shape defined under 「The supply guard」 below, whose `agents` member is what 「删除后 pm 将没有可用来源」 is composed from. Also drops the id from every backend's `sources.order`. |
-| POST `/api/models/sources/<id>/test` | → `{ok, discovered: n}` | re-discovery |
-| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | includes `current`, **v2** `sources` (policy + order + eligibility), `supply_status`, and `model_supply` per backend. Response agents[] carry server-populated read-only `builtin_models` / `standard_vendors` (integration 2026-07-24). |
-| **PUT** `/api/models/agents/<backend>/sources` | `{policy, order}` → `AgentSupply` | **v2, replaces `PUT /api/models/priority`.** Authoritative: the server re-echoes the full canonical order. See semantics below. |
-| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `AgentSupply` | hub⇄direct switch; never silent (plan §4) |
-| PUT `/api/models/agents/<backend>/mappings` | `{mappings}` → `AgentSupply` | fixed-menu backends only |
-| PUT `/api/models/agents/opencode/menu` | `{menu}` → `AgentSupply` | open menu config |
-| **GET** `/api/models/agents/<backend>/chain?model=<id>` | → `AgentChain` | **v2.** The capability chain for that (agent, model) — cooling members included, flagged `runnable: false`. An empty `chain` is `ok: true` with `chain: []`, not an error. Carries `supply_state` (`ok`/`waiting`/`interrupted`) at the MODEL grain: the single answer every model-scoped consumer reads, including the probe's `supply` sibling and `TurnProvenance.model_supply_state`, so none of them consults the backend rollup for a question it cannot answer. The `waiting`/`interrupted` split is spec §4.5's predicate, stated there once — `interrupted` when at least one blocker needs the user, `waiting` only when every blocker is a cooldown. `model` is a **menu identifier** (see identifier rules below). **Hub-mode route** (07-29, review round 9): this row is defined for `mode: hub` and the client must not offer it for a Direct backend. `agent-supply.schema.json` nulls `sources`, `selected_model_id` and `model_supply` in Direct, so there is no order to walk and no default model to fill in — the honest answer is not `chain: []`, because the empty-chain rule above means 「Hub has nothing that can serve this」 and a Direct backend's native CLI may be running that model perfectly well. Presenting Hub starvation for a backend that is not on Hub is a worse failure than refusing the question. What Direct *should* answer — a documented error or a mode-specific payload — is **AC-7** in `docs/plans/model-hub-implementation.md` §8 and is not decided here. |
-| **POST** `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | **v2.** One minimal dry-run request through the current chain (「试跑一次」). `model` is a **menu identifier** and defaults to `selected_model_id`. The result is NESTED under `probe`, never spread into the envelope — see below. **Hub-mode route** (07-29, review round 9), for the same reason as the chain row and one of its own: in Direct there is no `selected_model_id` to default to, and a `ProbeResult` requires a non-nullable `source_id`, which a Direct turn has no Hub source to name — the implementation would have to fabricate one to return a valid object. Scoped to `mode: hub`; the Direct representation is **AC-7**. |
-| POST `/api/models/custom-models` | `{source_id, model_id, display_name?}` → `Source` | appends manual-provenance model entry (frame V4 08) |
-| DELETE `/api/models/custom-models` | `{source_id, model_id}` → `Source` | |
-| GET `/api/models/events?limit=n&before=<id>` | → `{events: ResolutionEvent[]}` | adapter-owned feed (最近切换). **v2:** each event carries `severity`; the IM push layer keys off `severity == "action_required"` and never re-derives urgency from `kind`. **That field decides WHETHER to interrupt, not WHOM** (07-29, review round 5): no event carries a recipient, channel, or platform, and recipients are resolved at push time from the event's `agent` against the live routing table — spec §4.5 → 「Who receives an action-required push」 is normative, and this feed stays a record of what happened to supply rather than an outbox. Adds `kind: supply_interrupted`, the only agent-scoped kind — see the worked payload below. |
-| POST `/api/models/oauth/start` | `{vendor, channel}` → `{flow: OAuthFlow}` | runtime-declared presentation. Creates a NEW source on success; re-authenticating an existing one is `POST /api/models/sources/<id>/reauth`. **v2 stamps `flow.intent`** so the completion response shape is a total function of the flow — see 「OAuth completion responses」 below. |
-| GET `/api/models/oauth/status/<flow_id>` | → `{flow: OAuthFlow}`, plus the completion fields on the terminal success poll | 2s polling, server holds flow. **The terminal poll carries the flow's OUTCOME, not only its state** (07-29, review round 6) — the created source and its `adopted_by` for a create flow, the repair result for a reauth flow. See below. |
-| POST `/api/models/oauth/submit` | `{flow_id, value}` → same shape as `status` | value = pasted code or callback URL per `presentation.expects`. A submit that terminates the flow carries the same completion fields, so a form-A paste needs no extra poll to learn what it produced. |
-| POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | |
-| POST `/api/models/migration/scan` | → `MigrationScan` | read-only. Unaffected by the v2 ordering ruling — native-config import is an onboarding feature, not a priority mechanism. |
-| POST `/api/models/migration/apply` | `{item_ids: []}` → `{applied: n, sources: Source[]}` | copy-only; originals untouched (tested) |
-| **GET** `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` | **v2.** What served one turn, incl. every attempt in order (spec §4.5 turn provenance). `outcome` has FOUR values, not three (07-29 round 3): `served` / `exhausted` / `failed_terminal` / `no_candidate`, where `failed_terminal` covers the non-fallback errors of spec §4.3 — param, protocol, tool-compat, and anything after the first streamed token — recorded in a `terminal_error` slot beside `served`. Read-only. `turn_not_found` when the turn is unknown or predates the feature. |
-| GET `/api/models/runtime/status` | → `RuntimeDependency` | engine manifest + health |
-
-Removed in v2: `PUT /api/models/priority` (the global spend order). Its schema
-file survives only as a tombstone — see `priority.schema.json`.
-
-## Identifier rules (v2)
-
-Two namespaces exist and mixing them silently misses:
-
-- **menu identifier** — what the user picked and what every menu renders: the
- built-in id for fixed-menu backends (`claude-opus-4-6`), the prefixed
- `vendor/model` form for open menus (`zhipuai/glm-5.2`, per
- `opencode-overlay.md`).
-- **resolved model id** — what goes upstream after mapping, always bare
- (`glm-5.2`).
-
-Rule: **every request parameter is a menu identifier; every "what actually ran"
-field is a resolved id.** So `chain?model=`, `probe {model}`,
-`AgentChain.model_id`, `AgentSupply.selected_model_id` and
-`TurnProvenance.requested_model_id` take menu identifiers, while
-`AgentChain.resolved_model_id`, `ProbeResult.model_id`,
-`AgentSupply.current.model_id` and every `resolved_model_id` in
-`TurnProvenance` — `failed_attempts[]`, `served`, `terminal_error` — report
-resolved ids. (Round 2 replaced that record's single `attempts[]` array with
-those three slots; the reference here was not updated with it.)
-
-Consequence worth stating because it is the easy bug: `current.model_id` is a
-resolved id, so it is **not** a valid default for the chain query or the probe. For
-OpenCode it is bare (`glm-5.2`) while the chain expects `zhipuai/glm-5.2`, and the
-lookup would fail or, worse, match a different vendor's identically-named model.
-Defaults therefore read `AgentSupply.selected_model_id`, which is also the only
-one of the two that still exists when nothing is runnable — `current` is null in
-precisely the `waiting` / `interrupted` states where the drawer most needs to name
-the selected model (round 3 hoisted it out of `current` for that reason).
-
-### `selected_model_id` answers for ONE route, not for the backend
-
-`AgentSupply` is keyed by backend, so `selected_model_id` reads as "the model this
-backend will use". It is not (grain corrected 07-29, review round 4). A Vibe Agent
-row in SQLite carries **both** `backend` and `model`, so `pm` and
-`evm-contract-audit` can share the `claude` backend on different models, and
-routing follows the selected Vibe Agent (`AGENTS.md` → Agent routing model). One
-backend therefore has as many "selected models" as it has Agents.
-
-What the shipped projection actually resolves is one specific route:
-`core/controller.py::default_vibe_agent_model` takes the **global default** Vibe
-Agent and returns its `model` only if that Agent's backend matches, else null —
-whereupon `core/handlers/model_hub/service.py::requested_model` falls back to
-`agents.<backend>.default_model`. So the field has always answered for a single
-route while being named as if it answered for the backend. That is why v2 adds
-`selected_by_agent`: the Agent whose `model` produced the value, or null when it
-came from the backend default. The pair is honest about its own grain, and a UI
-rendering 「当前模型」 can say whose.
-
-Per-Agent questions have per-Agent routes already: `GET …/chain?model=<id>` and
-`POST …/probe {model}` both take an explicit model, so anything that needs another
-Agent's answer asks for it rather than reading this rollup.
-
-**REQUIRED on every hub-mode response** (07-29, review round 5). A payload may not
-publish `selected_model_id`, `current` or `supply_status` while leaving out the
-route they describe: all three inherit this grain, so without the field a client
-can render the global-default Agent's model as a backend-wide fact — the exact
-ambiguity `selected_by_agent` was added to remove, reintroduced by omission. Both
-worked payloads below now carry it. `null` is a legitimate value and means one
-specific thing — the model came from `agents.<backend>.default_model` because the
-resolved Agent pins none — so it is written explicitly rather than left absent; a
-missing key would be indistinguishable from a serializer that forgot.
-
-The obligation is stated here rather than as `required` in
-`agent-supply.schema.json` for the standing reason (README → required-vs-optional):
-that file's two frozen examples are `mode: hub` and predate every v2 field,
-because they round-trip byte-faithfully through the SHIPPED serializer, so a
-`required` under a hub branch would fail the contract gate instead of tightening
-it. This is the same boundary that makes `sources`, `supply_status` and `severity`
-optional in their schemas and mandatory at the API — the schema describes what
-today's serializer can emit, this file describes what the v2 API owes its
-callers. Enforcement therefore lands with the serializer PR, as a response-shape
-assertion next to the ones listed under Serializer completeness.
-
-**Open decision for the owner, deliberately not settled in this PR:** whether the
-Models page should surface per-Agent model selection as a first-class control
-(one row per Vibe Agent, not per backend). That is a product-surface question with
-its own frames, and the frozen ordering ruling — order is a per-Agent subset, no
-global list — is untouched either way; naming the grain here does not pre-empt it.
-
-## `PUT /api/models/agents/<backend>/sources` semantics
-
-**The request body is its own shape, not an `AgentSupply.sources` instance.** In
-the response object both `policy` and `order` are required, because the server
-always knows the canonical order; in the request `order` is required only under
-`policy: "custom"`, because under `follow` there is nothing for the client to say.
-Spelling that out here rather than reusing one schema for both directions is
-deliberate — a client that had to send an ignored `order` to select 跟随推荐 would
-be inventing data, and the next reader could not tell whether it mattered.
-
-Request is the whole intended state, never a delta:
+| GET `/api/models/sources` | → `{sources: Source[]}` | Unordered asset inventory. Array order is never a spend order. |
+| POST `/api/models/sources` | `SourceCreate` → `{source: Source, adopted_by: AdoptedBy[]}` | The server assigns `id` and immutable `created_at`; plaintext keys are transient. |
+| PATCH `/api/models/sources/<id>` | `{display_name?, base_url?}` → `{source: Source}` | Metadata only. |
+| PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean}` → `{source, recovered, interrupted_pairs}` | API-key replacement. The optional `force` is a JSON body field, never a query parameter. |
+| POST `/api/models/sources/<id>/reauth` | `{acknowledge_irreversible?: true}` → `{flow: OAuthFlow}` | A `native_cli` source requires the acknowledgement before OAuth starts. See repair rules. |
+| DELETE `/api/models/sources/<id>?force=<bool>` | → `{ok}` or `source_last_supplier` + `would_interrupt` | Guard evaluates the post-delete enabled orders. |
+| POST `/api/models/sources/<id>/test` | → `{discovered: integer}` | Explicit source re-discovery, including blocked-source recovery. |
+| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | Backend records include `named_agents`, the enabled named-Agent live projection. |
+| GET `/api/models/agents/<backend>/sources` | → `{agent: AgentSupply}` | Returns the authoritative effective order and eligibility. |
+| PUT `/api/models/agents/<backend>/sources` | source-order request → `{agent: AgentSupply}` | Full canonical order is re-echoed. |
+| PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. |
+| PUT `/api/models/agents/<backend>/mappings` | `{mappings}` → `{agent: AgentSupply}` | Fixed-menu backends only. |
+| PUT `/api/models/agents/opencode/menu` | `{menu}` → `{agent: AgentSupply}` | Open-menu configuration. |
+| GET `/api/models/agents/<backend>/chain?model=<id>` | → `{chain: AgentChain}` | Hub only. Direct returns the documented `direct_mode` error. |
+| POST `/api/models/agents/<backend>/probe` | `{model?}` → `{probe: ProbeResult}` | Hub only. Direct returns the same `direct_mode` error. |
+| POST `/api/models/custom-models` | `{source_id, model_id, display_name?}` → `{source: Source}` | Adds manual provenance. |
+| DELETE `/api/models/custom-models` | `{source_id, model_id}` → `{source: Source}` | Removes only the named manual model. |
+| GET `/api/models/events?limit=<n>&before=<id>` | → `{events: ResolutionEvent[]}` | Bounded source-resolution feed. |
+| POST `/api/models/oauth/start` | `{vendor, channel}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. |
+| GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. |
+| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. |
+| POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | Cancels and forgets the flow. |
+| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |
+| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources}` | Imported sources auto-join eligible follow orders; custom orders stay frozen. |
+| GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |
+| GET `/api/models/runtime` | → `RuntimeDependency` status | Managed engine status. |
+
+The removed global route `PUT /api/models/priority` has no v3 replacement.
+Ordering is backend-owned through the sources routes.
+
+## Identifier rules
+
+- `Source.id` and every non-null source reference match
+ `^src_[a-z0-9]{8,}$`.
+- The API boundary also verifies referential existence where a new reference is
+ emitted or accepted. JSON Schema can validate format, not cross-document existence.
+- Claude and Codex requests use fixed-menu built-in ids.
+- OpenCode requests use a prefixed `vendor/model` menu id. The prefix chooses the
+ provider; the resolver sends the bare model id upstream.
+- A mapping rewrites a menu id to an upstream model id. A mapping never chooses a
+ source.
+- Source event references are checked when emitted. Retained feed entries remain
+ valid after a later legal source deletion.
+
+## AgentSupply read projection
+
+Each backend entry on `GET /api/models/agents` carries the v3 API-boundary keys:
```json
-{ "policy": "custom", "order": ["src_anthkey01", "src_claudepro1", "src_relay9c1x"] }
+{
+ "backend": "claude",
+ "mode": "hub",
+ "selected_by_agent": "pm",
+ "selected_model_id": "claude-opus-4-6",
+ "current": {
+ "model_id": "claude-opus-4-6",
+ "source_id": "src_claudepro1",
+ "channel": "native_cli"
+ },
+ "sources": {
+ "policy": "follow",
+ "order": ["src_claudepro1", "src_anthkey01"],
+ "eligibility": [
+ {
+ "source_id": "src_claudepro1",
+ "eligible": true,
+ "reason_key": null
+ }
+ ]
+ },
+ "supply_status": "ok",
+ "model_supply": [
+ {"model_id": "claude-opus-4-6", "chain_length": 2}
+ ],
+ "named_agents": [
+ {
+ "name": "pm",
+ "effective_model_id": "claude-opus-4-6",
+ "supply_status": "ok"
+ },
+ {
+ "name": "reviewer",
+ "effective_model_id": "claude-haiku-4-5",
+ "supply_status": "interrupted"
+ }
+ ]
+}
```
+`named_agents` lists every enabled named Vibe Agent whose backend matches this
+record. `effective_model_id` is the Agent's pinned model, otherwise the backend
+default. `supply_status` is derived independently for that effective model. The
+list name and object shape are intentionally distinct from `SupplyGap.agents`,
+which is a list of bare names inside a mutation result.
+
+Disabled Agents are absent. In Direct mode each named Agent may still have an
+effective model, but its Hub `supply_status` is null.
+
+### Honest null selection
+
+Hub mode does not invent a default. When neither the routed Vibe Agent nor the
+backend configuration pins a model:
+
```json
-{ "policy": "follow" }
+{
+ "mode": "hub",
+ "selected_by_agent": null,
+ "selected_model_id": null,
+ "current": null,
+ "supply_status": null
+}
```
-Validation (`invalid_source_order` on any failure, with `detail` naming the first
-offending id):
-
-1. every id exists and is not deleted;
-2. every id is **eligible** for `<backend>` (§4.4 matrix — server-authoritative);
-3. ids are unique;
-4. it is a **subset**, not a permutation: omitting an eligible source is the
- normal way to say 未启用, and is not an error.
-
-Policy handling:
-
-- `{"policy": "follow"}` — `order` MUST be omitted; the server recomputes from the
- recommendation rule **defined once in spec §4.2** and echoes the result. This is
- the wire form of 「恢复推荐顺序」. The rule is deliberately NOT restated here
- (corrected 07-29, review round 4): round 3 carried an abbreviated parenthetical
- — "own-vendor subscription → api_key by `created_at` ascending → id tie-break" —
- which silently dropped §4.2's channel clause, that a sanctioned `native_cli`
- subscription precedes a hub-held one for the same own vendor. With both
- present the abbreviation fell through to the id tie-break and could put the
- experimental hub credential first, i.e. the paraphrase did not merely omit the
- clause, it contradicted it. That is what a second home for a predicate costs,
- so the fix is one home rather than a better copy: §4.2 states the rule, and
- every other file cites it.
- An `order` sent alongside `follow` is rejected with `invalid_source_order` rather
- than silently dropped: accepting and ignoring it would let a client believe it
- had set an order it did not set.
-- `{"policy": "custom", "order": [...]}` — `order` is required (an empty array is
- legal and means 全部未启用); stored verbatim and never reordered by the server
- afterwards (spec §2 promise 4).
-- Sending `policy: "custom"` with an `order` equal to the current recommendation is
- still a fork to custom — the user asked to own it.
-
-Response is the full `AgentSupply` for that backend, so one round trip refreshes
-the drawer, the row's order chips, and `supply_status`.
+This means “no pinned selection.” Each turn still resolves against the model carried
+by that request, including the CLI's own default. `sources`, `model_supply`, and
+`named_agents` remain present and non-null in Hub mode.
+
+## Per-backend source order
+
+Request shapes are total:
+
+```json
+{"policy": "follow"}
+```
+
+```json
+{"policy": "custom", "order": ["src_anthkey01", "src_relay9c1x"]}
+```
+
+- `follow` accepts no `order`; the server recomputes the live recommended order.
+- `custom` requires the complete desired ordered subset. The empty subset is legal.
+- Any manual order mutation changes policy to `custom`.
+- Restoring `follow` is the explicit restore-to-recommendation operation.
+- Every id is unique, exists, and is eligible for the backend. Otherwise the route
+ returns `invalid_source_order`.
+- New eligible sources auto-join `follow` at their recommended position.
+- A `custom` order never changes because a source was created or imported.
+
+Eligibility is server-authoritative. An ineligible row carries exactly one closed
+`reason_key` from `agent-supply.schema.json`; an eligible row carries null.
+
+## Source creation outcome
+
+`AdoptedBy` is:
+
+```json
+{"backend": "claude", "policy": "follow", "position": 2}
+```
+
+`position` is one-based in the effective order after commit. The array contains only
+eligible `follow` backends that actually adopted the source and is frozen with the
+source response. `custom` backends are absent and retain their prior order.
+
+The terminal result of both ordinary API-key creation and OAuth creation is:
```json
{
"ok": true,
- "contract_version": 2,
- "agent": {
- "backend": "claude",
- "mode": "hub",
- "menu_kind": "fixed",
- "selected_by_agent": "pm",
- "selected_model_id": "claude-opus-4-6",
- "current": {
- "model_id": "claude-opus-4-6",
- "source_id": "src_anthkey01",
- "channel": "hub"
- },
- "sources": {
- "policy": "custom",
- "order": ["src_anthkey01", "src_claudepro1", "src_relay9c1x"],
- "eligibility": [
- { "source_id": "src_anthkey01", "eligible": true, "reason_key": null },
- { "source_id": "src_claudepro1", "eligible": true, "reason_key": null },
- { "source_id": "src_relay9c1x", "eligible": true, "reason_key": null },
- { "source_id": "src_chatgptplus", "eligible": false,
- "reason_key": "models.eligibility.subscription_wrong_client" }
- ]
- },
- "supply_status": "degraded",
- "model_supply": [
- { "model_id": "claude-opus-4-6", "chain_length": 2 },
- { "model_id": "claude-haiku-4-5", "chain_length": 0 }
- ]
- }
+ "contract_version": 3,
+ "source": {"id": "src_anthkey01", "kind": "api_key"},
+ "adopted_by": [
+ {"backend": "claude", "policy": "follow", "position": 2}
+ ]
}
```
-## Interrupted agent payload (`current: null`)
+The public HTTP wrapper, RPC layer, and client pass this shape through directly; no
+extra `source` or `flow` nesting is added.
+
+## Supply guard
-The case worth writing out, because it is the one that motivated hoisting the
-selection out of `current` (round 3): the backend has nothing runnable, so
-`current` is null, yet the drawer still has to name the model it is complaining
-about, offer its chain drill-in, and default 「试跑一次」 to it.
+`SupplyGap` is:
```json
{
- "ok": true,
- "contract_version": 2,
- "agent": {
- "backend": "codex",
- "mode": "hub",
- "menu_kind": "fixed",
- "selected_by_agent": null,
- "selected_model_id": "gpt-5.3-codex",
- "current": null,
- "supply_status": "interrupted",
- "sources": {
- "policy": "follow",
- "order": ["src_chatgptplus"],
- "eligibility": [
- { "source_id": "src_chatgptplus", "eligible": true, "reason_key": null }
- ]
- },
- "model_supply": [ { "model_id": "gpt-5.3-codex", "chain_length": 1 } ]
- }
+ "backend": "claude",
+ "model_id": "claude-opus-4-6",
+ "agents": ["pm"]
}
```
-Read it together: one enabled source, which *can* supply the model
-(`chain_length: 1`), but it is `needs_action`, so nothing is runnable and
-`supply_status` is `interrupted` rather than `waiting`. `current` is null because
-naming a source here would render 使用中 for one that will not be called;
-`selected_model_id` survives because the user's choice did not change. The two
-payloads show both values of `selected_by_agent`: `"pm"` above, where a named Vibe
-Agent pins that model, and `null` here, where no Agent on this backend pins one
-and the value came from `agents.<backend>.default_model`. Null is a fact about
-provenance, not a missing field — the drawer says 「后端默认」 instead of naming an
-Agent, and 「当前模型」 is never attributed to an Agent that did not choose it.
+`agents` is the set of enabled named Vibe Agents whose effective model is the
+menu-side `model_id`, including Agents that inherit the backend default. It is
+present and may be empty.
-This payload lives here rather than in `agent-supply.schema.json`'s `examples`
-for the standing reason (README → required-vs-optional): those examples
-round-trip byte-faithfully through the shipped v1 serializer, so a v2 field in
-them would assert that dormant v1 code already speaks v2.
+The protected model set for a backend is the union of:
-## `adopted_by` on source create
+1. effective models of enabled named Vibe Agents;
+2. the backend default;
+3. checked open-menu models;
+4. the menu-side `builtin_id` of mappings whose `enabled` is true.
+
+The guard evaluates each protected `(backend, model)` against the post-mutation
+state. It counts only runnable suppliers in that backend's enabled effective order,
+never eligible inventory outside the order. A pair with no runnable supplier appears
+once in `would_interrupt` or `interrupted_pairs`.
+
+DELETE and elective replacement of a healthy API key refuse with:
```json
-{ "ok": true, "contract_version": 2,
- "source": { "id": "src_zhipukey01", "kind": "api_key", "...": "..." },
- "adopted_by": [ { "backend": "codex", "policy": "follow", "position": 2 } ] }
+{
+ "ok": false,
+ "contract_version": 3,
+ "error": "source_last_supplier",
+ "would_interrupt": [
+ {
+ "backend": "claude",
+ "model_id": "claude-opus-4-6",
+ "agents": ["pm"]
+ }
+ ]
+}
```
-One entry per backend that picked the new source up **automatically** — i.e. those
-on `policy: "follow"`, where `position` is its 1-based slot in the recomputed
-order. Backends on `custom` are absent from the list, which is exactly the set the
-success state offers one-tap enable for (「Claude Code 未启用此来源」). Eligible-for-nobody
-sources yield `adopted_by: []`.
-
-`position` is computed with the full recommendation rule, tie-break included, so
-the server must have written the source's immutable `created_at` before answering —
-`adopted_by` is the first consumer of that field.
-
-## The supply guard: `SupplyGap` and `would_interrupt`
-
-Two destructive operations can starve a model someone is running on: deleting a
-source, and rotating a healthy source onto a credential that sees fewer models.
-**They share one predicate, one shape and one refusal code, defined here once**
-(07-29, review round 7). Round 6 gave the shape a home under credential replacement
-and left the predicate paraphrased in the DELETE cell, where it drifted into a
-structural test — and a guard two routes describe differently is not one guard
-(README → 「A predicate has exactly one home」).
-
-**The shape.** `SupplyGap` is `{backend, model_id, agents: string[]}`, all three
-required, and it is what both keys carry: `would_interrupt` on a refusal (what WOULD
-be starved), `interrupted_pairs` on a completed repair (what WAS). One shape, two
-keys, because the two facts differ only in mood.
-
-**Namespace: menu identifiers throughout** (see the identifier rules above).
-`model_id` is a menu identifier — `claude-opus-4-6`, `zhipuai/glm-5.2` — never the
-resolved id it maps to, so the protected set, the gap report and the confirm copy all
-live in the namespace the user selected in and every menu renders. Mapping is applied
-*inside* the supply computation and nowhere else: to decide whether `claude-opus-4-6`
-is still supplied you resolve it through its mapping row and test the chain of
-`glm-5.2`, then report the gap as `claude-opus-4-6`.
-
-**What is protected: a backend's EFFECTIVE selections** — the union of four facts,
-each named as a menu identifier:
-
-1. every entry in an **open** menu's `menu.checked` (07-29, review round 9). Round 5
- wrote this term as 「every checked fixed-menu model」, which names state that does not
- exist: `agent-supply.schema.json` permits `menu` — and therefore `checked` — only for
- `menu_kind: open`, and gives a fixed menu `builtin_models`, which is the
- server-populated CATALOG, not a selection. Both readings of the old wording were
- wrong. Skipping the term drops real protection from the one menu kind that *does*
- persist a checked set, so deleting a source could starve a model the user ticked in
- the OpenCode menu. Treating a fixed menu's catalog as checked refuses deletes over
- dozens of models nobody selected and some the backend cannot even run, which trains
- the user to pass `force=true` reflexively and hollows out the whole guard. A fixed
- menu therefore contributes nothing here and is protected by terms 2-4 — which is
- exactly right, because a fixed-menu model the user actually selected either owns a
- mapping row, is the backend default, or is some enabled Agent's effective model.
- `menu.checked` entries are already prefixed menu identifiers (`zhipuai/glm-5.2`), so
- they enter the union in the namespace above with no translation;
-2. every model that owns a mapping row, named by its MENU side (`builtin_id`), never
- by the target it rewrites to;
-3. `agents.<backend>.default_model`;
-4. for every ENABLED Vibe Agent on that backend, its **effective model**: its own
- `model` when it has one, otherwise `agents.<backend>.default_model` — inheritance
- is a selection, not the absence of one.
-
-Disabled Agents are excluded: they cannot take a turn, so their model is not a live
-capability. A disabled Agent's model that is *also* the backend default stays
-protected through term 3, which is the overlap the union exists to absorb.
-
-**The gap predicate: no runnable supplier, not an empty chain.** A protected pair is
-a gap when, AFTER the change, its capability chain holds no `runnable: true`
-member — `runnable` exactly as `agent-chain.schema.json` defines it (healthy, or
-cooling with `retry_at` already past; never `needs_action`, never `error`).
-Equivalently: the pair's `supply_state` would stop being `ok`. `chain_length > 0` is
-NOT the test, and that was the round-6 defect: a chain of one revoked key is
-non-empty and cannot serve, so the structural test passed the delete and the agent
-went `interrupted` on its next turn.
-
-**One boundary, stated so nobody re-derives it.** This predicate is deliberately not
-the `interrupted` predicate. A pair whose remaining members are all merely cooling is
-`waiting`, not `interrupted` (spec §4.5) — and it IS reported here, because the guard
-asks 「删完之后现在还有能跑的来源吗」, which is false in both cases, while
-`waiting`/`interrupted` answers the different question 「要不要你处理」. The guard
-over-warns by exactly that one case, on purpose: it is a confirmation prompt,
-`force=true` overrides it either way, and a client that wants to distinguish 暂时
-from 需处理 reads that pair's `supply_state` from the chain query. Nothing here
-forbids an operation; it decides what the user is told before they confirm.
-
-**`agents` names the Agents that would actually break, INCLUDING the ones that
-inherit the backend default** (07-29, review round 7). Membership is by effective
-model, term 4 above: an enabled Vibe Agent belongs in `agents` when the starved pair
-is the model it would actually run on, whether it names that model itself or inherits
-it from `agents.<backend>.default_model`. **This reverses round 6's parenthetical**,
-which emptied the list for a gap protected only through the backend default;
-recorded as an orchestrator ruling, open to owner veto at final review. The reason
-for the reversal: the field answers 「谁会坏」, and round 6's rule answered 「谁明确
-写了这个模型」 — a different question whose answer is `[]` on a real interruption.
-That is not a neutral omission but false reassurance, since the client then renders
-「无 Agent 受影响」 for a refusal that exists *because* an Agent is about to stop
-working, and 中断必须点名成因与受影响方 is the whole reason the member was added.
-`agents` may still be legitimately empty — an open menu's checked-but-unassigned model,
-or a mapping row no Agent runs on — and after this ruling that is the only way it
-empties.
-
-## Credential replacement and re-auth
-
-Two routes share one repair: `PUT …/sources/<id>/credential` (paste a new key) and
-the completion of `POST …/sources/<id>/reauth` (re-run OAuth on an existing source).
-**This section states the PROPERTIES that repair must satisfy, not the steps it
-takes** (rewritten 07-29, review round 7). Rounds 3–6 each corrected the step list,
-and each correction bred the next round's findings: an ordered list of five steps
-admits an unbounded supply of 「what about between 3 and 4」 questions, and round 7
-asked four of them at once — where the guard runs, when the engine learns about the
-swap, whether the steps are executable on the default channel at all, and what
-counts as recovered. The invariants below are finite and total; the sequence that
-satisfies them belongs to the implementing lane, and one is sketched
-non-normatively at the end.
-
-**The commit point.** Every invariant is stated against one named instant. The
-**commit point** is the single write that makes the replacement live: `credential_ref`
-swapped, `masked_credential` refreshed, the discovered list merged into
-`Source.models`, `state.retry_at` and `state.detail_key` cleared, affected chain state
-recomputed, **and the engine's own source table synchronised to the new ref**
-(`sync_sources`, the last step of the frozen adapter's canonical flow). Those happen
-together or not at all. The engine sync is INSIDE the commit phase, not after it,
-because a swap the engine has not seen is not a repair — round 7's finding was
-precisely that: persist-then-revoke with the sync left implicit lets the engine keep
-serving turns from a handle we just revoked, so a successful repair breaks the next
-turn.
-
-1. **Atomicity.** There is exactly one commit point. Before it the prior state is
- fully recoverable and still serving; after it the replacement is fully in effect.
- No intermediate state is observable to a turn — there is no instant at which the
- source's `credential_ref` and the engine's binding disagree, and no half-applied
- repair to reconcile later.
-2. **No revoked-credential window.** The engine must never hold a reference to a
- revoked credential. The old ref is revoked only AFTER the commit point — that is,
- only once the engine's source table reflects the swap — never before it and never
- inside it. A revoke that then fails must not undo a completed repair: it leaves an
- orphaned handle in the engine store, which is a cleanup problem, not a supply
- problem.
-3. **Failure preserves the prior state.** Any failure before the commit point leaves
- the original credential active and serving, and revokes whatever temporary
- replacement ref the attempt minted; the route answers `discovery_failed`.
- **Temporary refs never outlive the operation** — success revokes the old one,
- failure revokes the new one, and no path leaves two live handles for one source.
- 「Prior state」 means the state this contract owns: the `Source` row and the
- engine-owned credential store (see invariant 5 for the channel where that
- boundary bites).
-4. **Guard before commit.** `would_interrupt` is evaluated against the POST-swap
- world — the model set the new credential actually discovered — and evaluated
- BEFORE the commit point. A refusal therefore happens with the prior state intact,
- with nothing to roll back beyond invariant 3's temporary ref, and it is
- unrepresentable for this route to commit a swap and *then* find it was not allowed
- to: the guard is a precondition, not a postcondition. Which pairs count, and what
- counts as starved: 「The supply guard」 above, the same definition DELETE uses.
-
-5. **Per-channel executability.** Every supply channel must have a path that
- satisfies the invariants above through the surfaces it actually has (round 4 made
- this channel-specific; round 7 asked whether the default channel could execute the
- steps at all). What a credential *is* differs by channel:
- - **`api_key` sources and consented hub-held subscriptions** hold an engine-owned
- handle. Repair mints a replacement ref, discovers through it, swaps at the
- commit point. This is the only channel where invariants 2 and 3 have refs to
- talk about.
- - **`native_cli` subscriptions hold no engine ref at all** — the Source contract
- pins `credential_ref: null`, because the credential lives in the CLI's own
- sanctioned store. **Replacement there IS re-auth of that store**, performed at
- the CLI's own surface; the engine-ref steps do not apply and must not be
- simulated, since there is nothing to provision, nothing to swap and nothing of
- ours to revoke. Writing the hub behaviour as universal would put a non-null ref
- on a source whose channel forbids it, failing validation on the path most users
- take. What the commit point writes there is the state half only — the discovered
- list, the cleared `state` fields, the recomputed chain, the engine sync — and
- invariants 1, 4 and 6 hold unchanged, evaluated on the same `Source` row.
-
- Two boundaries keep that honest rather than hand-waved. **Discovery reads through
- the CLI's store**, not through a ref we hold, so 「discover before committing」 is
- still satisfiable: the CLI is authoritative for the credential, we are
- authoritative for the row. And **invariant 3's rollback is bounded by what this
- contract owns**: a completed CLI re-auth has already replaced the user's login
- inside a store we do not manage, and no adapter surface can put the previous login
- back. So a post-re-auth discovery failure leaves the `Source` row untouched and
- answers `discovery_failed` — the row keeps its prior state, which is what invariant
- 3 promises — while the CLI store keeps whatever the user just authorised. That
- asymmetry is declared, not accidental: pretending we could restore the old login
- would be inventing an adapter surface, and re-authenticating a CLI is something the
- user did at the vendor's own prompt, not a transaction we brokered.
-
- **Read that as a statement about the row, not about the user's supply** (07-29,
- review round 8). On this channel the preserved row is intact and no longer TRUE: its
- `models` and `state` describe the login that has just been replaced, so the next
- native turn runs on the new account against a row describing the old one, and a
- refusal that 「preserves the prior supply」 preserves a supply that no longer exists.
- Invariant 3 is therefore satisfiable here only in its weak sense — we corrupt
- nothing — and the strong sense it carries on the ref-holding channel, that a failed
- repair leaves the user no worse off, is not available once the login is gone. Two
- ways close it: require confirmation BEFORE the irreversible login, or commit the
- swap and report the resulting gaps instead of refusing. Both have a UI consequence,
- so the choice is the owner's, recorded as **AC-2** in `model-hub-implementation.md`
- and NOT decided here. What is decided: this channel must not present a
- post-re-auth refusal as though the prior supply were intact. **What
- 「recovered」 observes there** is exactly what it observes everywhere — whether this
- operation cleared the source's blocker state (invariant 6). Nothing in that
- definition reads a credential handle, which is why it needs no channel-specific
- case.
-6. **Recovery symmetry.** `recovered` is true when the operation cleared a BLOCKER
- state, and 「blocker」 is the same set the chain classifier uses: `state.status` of
- `needs_action` **or** `error` — the two values `agent-chain.schema.json` counts in
- the branch that makes a chain `interrupted`, and the two whose `retry_at` is null
- because nothing clears them unattended. One definition, referenced, never
- re-enumerated. Round 6 wrote 「cleared a `needs_action`」, a strict SUBSET of that
- set, so repairing a source sitting in `error` — a state round 6 itself promoted to
- a blocker in the same commit — would have reported `recovered: false`, filing a
- real repair as an elective rotation: it suppresses the `recover` event the user is
- owed and sends the operation down the stricter refusal branch below for a source
- that was already unusable. A cooldown is deliberately NOT a blocker here, because
- it heals itself: replacing a key while a source is merely cooling is an elective
- rotation.
-
-**"Healthy" here is `active` or `standby`, recomputed — never a literal** (round 4).
-Round 3 wrote `state.status: "healthy"`, which is not in the enum, so a literal
-implementation would have made every SUCCESSFUL replacement fail Source validation.
-Nor is the fix a third literal: `active` vs `standby` is a display rollup over "is
-this source serving any agent right now", so the commit point clears the two detail
-fields and lets the rollup resolve. A route that hard-coded either would be asserting
-a fact about every backend's order from inside a single-source operation.
-
-**`Source.models` merge rule:** entries with `provenance: discovered` are REPLACED by
-the new discovery, entries with `provenance: manual` are PRESERVED. The model list of
-an `api_key` source is a property of the CREDENTIAL, not of the base URL — a
-replacement key on a different plan, project or tier can legitimately see fewer
-models — while a hand-added id is the user's assertion, and swapping a key does not
-withdraw it. A subscription can likewise come back on a different plan than it went
-in on, so re-auth runs the same refresh.
-
-**The response names what the repair cost**, which is what round 6 found missing: the
-prose promised every newly starved (backend, model) pair while the declared shape was
-only `{source, recovered}`. `recovered` answers invariant 6; `interrupted_pairs`
-reports the protected pairs the repair left with no runnable supplier — the same
-predicate and the same `SupplyGap` shape as 「The supply guard」 above — and is `[]`,
-present and empty, when the repair cost nothing:
+DELETE uses the query `force=true`. API-key replacement uses the JSON body
+`force: true`. A blocked-source repair proceeds and reports the remaining gaps in
+`interrupted_pairs`; refusing it would prevent recovery from the state the route
+exists to repair.
+
+## Credential replacement and reauth
+
+The commit point is the single durable write that makes the replacement source state
+live. Implementations may sequence adapter calls differently only if all invariants
+remain true:
+
+1. **Atomic source state.** Before the commit point, readers see the old source.
+ After it, readers see the replacement credential reference, mask, discovered
+ models, and derived state together.
+2. **Rollback before commit.** Any failure before commit preserves the old source and
+ revokes replacement engine material created by that attempt.
+3. **Guard before commit.** Elective API-key replacement evaluates the supply guard
+ against the discovered replacement model set before the write.
+4. **Per-channel truth.** Hub credentials are engine-owned and transactional.
+ Native credentials are CLI-owned and replacement is irreversible once login starts.
+5. **Server-enforced native acknowledgement.** For a `native_cli` source,
+ `POST …/reauth` requires `{"acknowledge_irreversible": true}`. Missing or false
+ returns `reauth_confirmation_required` before any OAuth adapter call. This is
+ unconditional and does not claim that a pre-login supply prediction exists.
+ Hub-channel repair does not require this acknowledgement.
+6. **Recovery symmetry.** Both routes return the same repair tail:
+ `{source, recovered, interrupted_pairs}`. `recovered` is true exactly when the
+ prior source state was `needs_action` or `error`.
+7. **Durable failed-revocation reconciliation.** If old engine material cannot be
+ revoked after commit, the service persists a pending-revocation record before
+ returning success. A reconstructed service reads the same journal and retries it.
+ The source remains usable; no state is allowed where the old handle is live and no
+ durable record names it. Successful reconciliation removes the record.
+
+API-key success:
```json
-{ "ok": true, "contract_version": 2,
- "source": { "id": "src_relay9c1x", "kind": "api_key", "...": "..." },
+{
+ "ok": true,
+ "contract_version": 3,
+ "source": {"id": "src_relay9c1x", "kind": "api_key"},
"recovered": true,
- "interrupted_pairs": [
- { "backend": "claude", "model_id": "claude-haiku-4-5", "agents": ["pm"] }
- ] }
+ "interrupted_pairs": []
+}
```
-**Illustrative sequence for the ref-holding channel (NON-NORMATIVE).** Offered
-because the frozen adapter surface forces most of it, and because rounds 3–5 argued
-about an ordering that cannot be written: `discover_models` takes a `credential_ref`
-and `provision_credential` is the only thing that mints one
-(`adapter-interface.py`), so 「validate the key, *then* provision it」 has no handle to
-validate with — provisioning IS how a key is validated, and the docstring's canonical
-flow is already **provision → discover → persist → sync**, which shipped
-`create_source` implements. Round 5 was right that discovery must precede the swap and
-expressed it as discovery preceding the *provision*; both halves are satisfied by
-provisioning a replacement ref that is not yet the source's. A conforming walk:
-provision the pasted or newly authorised credential into the engine store, yielding a
-replacement ref while the source still points at its old one and still serves from it
-→ discover through the replacement ref → evaluate the guard against what was
-discovered → commit → revoke the old ref. Any failure or refusal before the commit
-revokes the replacement ref and answers with the prior state intact. **This is an
-example, not the contract**: an implementation that satisfies the six invariants by
-another route is conforming, and a step list that reads better while violating one is
-not.
-
-**A predicted gap gates by intent, not by severity.** Repairing a blocked source
-(`recovered == true`, invariant 6) PROCEEDS and reports through `interrupted_pairs` —
-refusing would trap the user in the exact state 「换一个 Key」 exists to escape, and a
-narrower working key is strictly better than a revoked one. An elective rotation of an
-already-serving source (`recovered == false`) is refused unless `force=true`, with the
-same `source_last_supplier` + `would_interrupt` shape DELETE uses, because there the
-user has a working supply and no reason to be surprised out of part of it. Both
-branches read the same guard (invariant 4); only the response to it differs.
-
-**`kind: recover` is CONDITIONAL on the prior state, not on success** (round 5). The
-route already answers "did this clear a blocker" in `recovered`, and the same
-success can happen to a perfectly healthy source — a scheduled key rotation. Emitting
-`recover` unconditionally publishes a restoration for a source that was never
-interrupted: the timeline gains a 「已恢复」 entry with nothing to recover from, and
-severity promotion can push it to the user as news. So emit `kind: recover` **iff
-`recovered == true`**, with `to_source: <this source>` — `recover` is the one kind whose
-subject sits on the WINNING side. When `recovered == false` the routes emit **no
-resolution event at all**, and that is deliberately NOT a 9th `kind`: the enum names
-*resolutions of supply state*, and a rotation that starts healthy and ends healthy
-resolves nothing, while a new value would force every consumer's switch to grow a
-branch that renders nothing.
-
-## OAuth completion responses
-
-`POST /api/models/oauth/start` and `POST …/sources/<id>/reauth` both return a flow,
-and the UI polls `GET /api/models/oauth/status/<flow_id>` (2s, 15-min timeout). **The
-terminal `state: "success"` response carries the flow's OUTCOME alongside the flow**
-(07-29, review round 6). Round 5 left that shape undefined, which made the two
-creation paths inconsistent: `POST /sources` closes the 「so what now?」 loop with
-`adopted_by`, while a subscription added through OAuth — the *default* way a
-subscription is added — returned only a flow state. The closing loop is a v2 product
-commitment for BOTH creation paths, so the shape is declared rather than left to the
-implementing lane.
-
-The response is a total function of `flow.intent`, which v2 adds to `OAuthFlow`:
+## Blocked-source test
+
+`POST /api/models/sources/<id>/test` is an explicit source-scoped operation. It may
+test a source whose global state is `needs_action` or `error`, even though normal
+turn resolution and the chain probe exclude that source as non-runnable.
+
+On usable discovery it updates the discovered model set, clears the blocker, and
+sets the source to `standby`. A classified failure updates the source-global state
+and returns the normal safe error. This route is the only recovery test added; v3
+does not add a second “recover” endpoint.
+
+## OAuth completion
+
+`OAuthFlow.intent` makes the terminal shape a function of the flow:
+
+- non-terminal, failed, or canceled → `{flow}`;
+- terminal `intent: "create"` → `{flow, source, adopted_by}`;
+- terminal `intent: "reauth"` → `{flow, source, recovered, interrupted_pairs}`.
+
+Status and submit return the same terminal shape:
```json
-{ "ok": true, "contract_version": 2,
- "flow": { "flow_id": "oaf_claude01", "intent": "create", "state": "success",
- "source_id": "src_claudepro1", "...": "..." },
- "source": { "id": "src_claudepro1", "kind": "subscription", "...": "..." },
- "adopted_by": [ { "backend": "claude", "policy": "follow", "position": 1 } ] }
+{
+ "ok": true,
+ "contract_version": 3,
+ "flow": {
+ "flow_id": "oaf_claude01",
+ "intent": "create",
+ "state": "success",
+ "source_id": "src_claudepro1"
+ },
+ "source": {"id": "src_claudepro1", "kind": "subscription"},
+ "adopted_by": [
+ {"backend": "claude", "policy": "follow", "position": 1}
+ ]
+}
```
-- `intent: "create"` → `{flow, source, adopted_by}`, with `source` and `adopted_by`
- carrying exactly the `POST /sources` semantics, because it is the same event: a new
- source exists and the backends on 跟随推荐 picked it up. Auto-creation on flow
- success is already the shipped behaviour; what round 6 adds is that the created
- source stops being discarded from the response.
-- `intent: "reauth"` → `{flow, source, recovered, interrupted_pairs}` — the repair tail
- above, field for field, because it is the same repair reached through a different
- door. `adopted_by` is deliberately **absent** here rather than `[]`: the source
- already existed and no order changed, whereas `[]` on the create path asserts the
- real fact 「eligible for nobody」.
-
-`intent` is what makes the shape derivable from the payload instead of from client
-memory of which button was pressed. `source_id` cannot serve: hub-channel *create*
-flows also set it, for the pending source they bind to, so it does not discriminate
-creation from repair. A non-terminal poll, and a flow that ends `failed` or
-`cancelled`, carry `flow` alone — there is no source and no repair to report. The
-field is OPTIONAL in `oauth-flow.schema.json` for the standing reason (README →
-required-vs-optional): the shipped flow payloads are validated against that file by
-`tests/test_model_hub_api.py`, and they predate the field, so a `required` there
-would fail the contract gate instead of tightening it. The server always emits it
-from v2 on, which is a response-shape assertion in the serializer PR.
-
-## Probe response nesting
+`adopted_by` is absent for reauth because the existing source order did not change.
+
+## Chain and probe
+
+In Hub mode, `AgentChain.chain` is the effective source order filtered by backend
+eligibility and model support, with mapping applied. Cooling and other blocked members
+stay in the chain; `runnable` is the retry-readiness filter used by the resolver.
+An empty Hub chain is a valid `interrupted` chain.
+
+In Direct mode both chain and probe refuse with:
```json
-{ "ok": true, "contract_version": 2,
- "probe": { "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2",
- "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted",
- "via_mapping": true, "contract_version": 2, "backend": "claude" } }
+{
+ "ok": false,
+ "contract_version": 3,
+ "error": "direct_mode",
+ "detail": "models.hub.direct_mode"
+}
```
-The latency is **measured, not null** (corrected 07-29, review round 4). A
-`balance_exhausted` is learned FROM a completed upstream response — the server
-answered and told us the credit is gone — and `latency_ms: null` is reserved for
-attempts that never completed at all, which the UI renders as 未完成. A frozen
-example carrying that pair teaches every implementation and example-driven test
-to show a completed billing answer as an unfinished request, so
-`probe-result.schema.json` now makes the pair unrepresentable: any
-`models.source.needs_action.*` error requires an integer latency. null belongs to
-the transport family (`models.source.cooldown.network` / `.timeout`), which has
-its own example on that schema.
-
-`ProbeResult` is **nested**, and its outcome field is `reachable`, not `ok`. Both
-halves of that matter. `reachable` means **the upstream completed the request
-usably** — 能不能用, the question 「试跑一次」 asks — and NOT "the upstream answered"
-(wording corrected 07-29, review round 6: that phrasing survived from round 4 and
-contradicted both the corrected schema definition and the example directly above,
-where a `balance_exhausted` is learned FROM a completed 402 and is `reachable:
-false`). The schema makes the alignment mechanical: `reachable: true` requires a
-null `error`, so `true` is exactly "a usable completion for this (source, model)".
-Transport failures and completed-but-refused responses are both `false`, and
-`reachable: false` beside a measured `latency_ms` is the normal shape of the second.
-Whether the attempt completed at all is still answerable from the same object —
-`latency_ms != null` — so the two questions stay separable without a second flag.
-The envelope's `ok`, meanwhile, means the API call succeeded: a probe that cleanly
-establishes the source is broken is a *successful* call reporting `reachable: false`
-— spreading the object into the envelope would collide two different questions on
-one key, and every client would eventually read the wrong one.
-
-`ok: false` on this route is reserved for the call itself failing:
-`probe_no_candidate`, `engine_down`, an unknown backend.
+They never return `chain: []` or fabricate a `source_id` to represent native CLI
+supply.
+
+A successful probe nests its result:
```json
-{ "ok": false, "contract_version": 2, "error": "probe_no_candidate",
+{
+ "ok": true,
+ "contract_version": 3,
+ "probe": {
+ "contract_version": 3,
+ "backend": "claude",
+ "reachable": false,
+ "source_id": "src_relay9c1x",
+ "model_id": "glm-5.2",
+ "latency_ms": 287,
+ "via_mapping": true,
+ "error": "models.source.needs_action.balance_exhausted"
+ }
+}
+```
+
+No candidate is an API error with a typed model-scoped state:
+
+```json
+{
+ "ok": false,
+ "contract_version": 3,
+ "error": "probe_no_candidate",
"detail": "models.probe.no_candidate.waiting",
- "supply": { "supply_state": "waiting", "retry_at": "2026-07-29T09:15:00Z" } }
+ "supply": {
+ "supply_state": "waiting",
+ "retry_at": "2026-07-29T09:15:00Z"
+ }
+}
```
-The structured half lives in its own `supply` key, **not in `detail`** (corrected
-07-29, review round 3): round 2 put the object there, which contradicts the
-envelope rule above and the two shipped client types that already declare
-`detail?: string`. A client would have rendered `[object Object]` next to the one
-error whose whole purpose is to explain itself. `detail` keeps doing its one job —
-an i18n key, here varying with the state so the string alone is already showable.
+## Turn provenance absence
-`supply.supply_state` is the requested model's `AgentChain.supply_state`, so the copy
-can be 「该模型的来源都在冷却,约 09:15 恢复」 for `waiting` and 「该模型暂无可用来源,需处理」
-for `interrupted`. `supply.retry_at` is the earliest across that chain and is null for
-`interrupted`, because nothing in it recovers on a timer. `supply` is present on
-`probe_no_candidate` and on no other error code — a per-error typed sibling is
-cheap precisely because it does not have to generalise.
+`TurnProvenance` is returned only for an exactly attributed Hub turn. Direct and
+ambiguous absence are explicit and distinguishable from an unknown turn:
-## Agent-interrupted event payload
+```json
+{
+ "ok": false,
+ "contract_version": 3,
+ "error": "provenance_unavailable",
+ "detail": "models.provenance.direct_mode"
+}
+```
```json
-{ "id": "evt_20260729c", "ts": "2026-07-29T06:55:10Z", "agent": "codex",
- "kind": "supply_interrupted", "model_id": "gpt-5.3-codex",
- "from_source": null, "to_source": null, "reason": "no_enabled_source",
- "severity": "action_required",
- "human_zh": "Codex:启用的来源已全部移除,现在无法运行 —— 去「模型」页加一个来源",
- "human_en": "Codex: every enabled source was removed, so it cannot run — add one on the Models page" }
+{
+ "ok": false,
+ "contract_version": 3,
+ "error": "provenance_unavailable",
+ "detail": "models.provenance.attribution_ambiguous"
+}
```
-The one event kind scoped to an **agent** rather than a source (spec §4.5). It fires
-on the transition into `supply_status: interrupted` when no source changed state —
-typically the last member of that backend's order being deleted or unchecked — which
-is the case a source-keyed feed structurally cannot express. `from_source` and
-`to_source` are null: nothing switched, the chain emptied. `severity` is
-`action_required` by contract (schema conditional), never a judgement call at emit
-time, so this is always ELIGIBLE for a proactive push and never feed-only. Emitted once
-per transition, never per starved turn. Note what the payload does not carry: no
-recipient, no channel, no platform. `agent: "codex"` is the addressing input — the push
-layer resolves it to the scopes whose routing currently selects a Codex Vibe Agent (spec
-§4.5 → 「Who receives an action-required push」). This kind is the clearest case for
-resolving at delivery rather than at emit: it typically fires from a Web UI settings
-mutation, which has no originating conversation to reply into.
-
-It lives in `api.md` rather than as a `resolution-event.schema.json` example for the
-same reason `severity` does — the round-trip test drives every example in that file
-through the shipped v1 `ResolutionEvent`, which has no `severity` field yet (README →
-required-vs-optional discipline).
-
-## Error codes (minimum set)
+An unknown `turn_id` returns `turn_not_found`. The server derives ambiguous absence
+live from “known turn, no exact record”; it does not persist a placeholder and never
+guesses which attempt belonged to the turn.
+
+## Resolution events
+
+Events are state/feed records, not recorded fan-out. `severity` is presentation
+metadata (`info` or `action_required`). Consumers derive current impact from live
+source orders and named-Agent effective models.
+
+`model_id: null` means a source-scoped system event is about the source as a whole.
+Model-scoped kinds require a string. `agent: system` is invalid on backend-scoped
+`supply_interrupted`. Source endpoints use canonical ids and are checked for existence
+when emitted.
+
+## Error codes
+
+Minimum v3 set:
`source_not_found`, `flow_not_found`, `flow_expired`, `discovery_failed`,
-`invalid_source_order` (the four rules above, plus `order` sent with
-`policy: "follow"`), `source_last_supplier` (**added 07-29, review round 6** — the
-guard that refuses a destructive change while it is the last supplier of a selected
-model had prose, a `force=true` override and no code, so a client could not tell it
-apart from a generic failure. Carries `would_interrupt: SupplyGap[]`. Raised by
-DELETE without `force`, and by an elective credential rotation that would starve a
-pair), `mapping_target_unavailable`, `mode_switch_blocked`,
-`engine_down`, `consent_required` (hub-held subscription paths while the
-experimental flag is unset), `migration_item_conflict`, `turn_not_found`,
-`probe_no_candidate` (probe requested while this backend has no **runnable**
-candidate for the model. The typed `supply` sibling names which case, since 「稍等即可」
-and 「需处理」 are different answers for the user — and it is read from the REQUESTED
-model's own chain (`AgentChain.supply_state`), never from the backend's
-`supply_status` rollup. The
-rollup answers for the backend's *current* model, so probing a starved non-current
-menu item while the selected model is healthy would report `ok` and leave `supply`
-unable to say anything true. Probing a cooling source is not offered: it would spend
-a request against an account we already know is exhausted).
-
-Removed in v2: `invalid_priority_order`.
-
-Serializer completeness: every field in these schemas must round-trip through
-`config_to_payload` (or the runtime status assembler) and is covered by the CI
-completeness guards (issue #939 pattern) in the same PR that introduces it.
-Derived, never-persisted fields (`supply_status`, `model_supply`,
-`sources.eligibility`, `AgentChain`, `ProbeResult`, `TurnProvenance`) are exempt
-from config round-tripping but must still be covered by an API-payload test.
-`created_at` is the opposite case — persisted, immutable, and therefore inside the
-completeness guard the moment the serializer emits it.
-
-**Mechanical guards the schemas cannot carry** (07-29, review round 5). Round 5 pushed
-every invariant it could into the schemas themselves — closed enums instead of prefix
-patterns, biconditionals instead of one-way implications, `required` alongside every
-non-null `then`. What is listed here is the residue: invariants JSON Schema draft-07
-cannot state at all. Each one ships as a check in the contract test that already walks
-these files, in the same PR that introduces the field it guards. They are recorded
-here so a reader can tell "draft-07 cannot express this" from "nobody thought of it":
-
-| Guard | Why not in the schema |
+`invalid_source_order`, `source_last_supplier`, `mapping_target_unavailable`,
+`mode_switch_blocked`, `engine_down`, `consent_required`,
+`reauth_confirmation_required`, `migration_item_conflict`, `turn_not_found`,
+`provenance_unavailable`, `probe_no_candidate`, `direct_mode`.
+
+Removed: `invalid_priority_order`.
+
+## Mechanical guards
+
+JSON Schema draft-07 cannot express cross-document or live-state relations. The
+contract harness and API-boundary tests enforce:
+
+| Guard | Boundary |
| --- | --- |
-| `probe-result.error` enum ≡ ALL THREE of `source.state.detail_key`'s enforced status vocabularies — cooldown ∪ needs_action ∪ the single `error` key (widened 07-29, review round 7) | cross-file identity; a bare `Draft7Validator` resolves no `$ref` across files, and two hand-kept lists drift. Round 6 widened two files and left this one asserting an identity it no longer had, so a source could enter `error` while no probe had a legal value to report it. Round 7's correction is mechanical, not editorial: the comparison now runs across files for EVERY vocabulary any of these schemas claims to mirror, from the table in `README.md` → 「Vocabulary mirrors and their blast radius」 |
-| `source.state.detail_key.examples` ≡ the union of the enforced per-status enums | `examples` is documentation, so the human-readable list can silently outlive the enforced one — this already happened once in round 4, and again in round 6. The round-6 recurrence needed a second fix in the CHECKER, not the schema: the `error` key is pinned as a `const`, and a checker that collects only `enum` lists cannot see a closed vocabulary of size one, so its own union came up one key short and the comparison passed vacuously. `const` now counts as an enum of cardinality one |
-| every vocabulary shared across these files is a registered row with a mechanical rule — equality, a documented projection (`chain[].health`, `supply_state`, `model_supply_state`), or a total partition (`turn-provenance.failed_attempts[].reason` against `resolution-event.reason`) | all of them are cross-file, and the non-equality ones are worse than cross-file: they are relations between vocabularies at different grains, which no schema keyword expresses in either direction. The rules and their reasons live in `README.md` → 「Vocabulary mirrors and their blast radius」; the partition is what makes a new `reason` a decision rather than a default, since it fails until the new value is either mirrored or excluded on the record |
-| the INVERSE: a field whose description names another contract file must appear in that table (07-29, review round 7) | this is the half that closes the class rather than the instance. Round 6's three drifted mirrors were each asserted in prose and compared by nothing; only the pair someone had thought to check was checked. Detection is by schema STEM, not by the `.schema.json` suffix and not by the word "mirror" — the claim round 7 missed (`turn-provenance` → `failed_attempts[].reason`, naming "the resolution-event `reason` vocabulary") used neither |
-| every non-null `then` constraint is accompanied by `required` for the field it constrains | draft-07 `properties` validates only fields that are PRESENT, so a conditional over an optional field is toothless when it is absent. The checker carries exactly two declared exceptions (`agent-supply` → `supply_status`, `resolution-event` → `severity`), each one a fail-SAFE absence forced by a frozen example, and fails if a declared exception stops being needed |
-| `AgentChain.chain` has unique `source_id` values | `uniqueItems` compares whole items, so the same source twice with different health flags passes — and inflates `chain_length` into counting one credential as two fallbacks |
-| `AgentChain.chain` preserves the relative order of `sources.order` | ordering of a *different* document is not expressible |
-| every id in `sources.order` appears in `sources.eligibility` with `eligible: true` | one field constraining another; draft-07 has no `$data` |
-| `channel_switch` events have `from_source == to_source` | same reason — equality between two sibling values |
-| `selected_by_agent` is present on every hub-mode `AgentSupply` response | a `required` here would fail the byte-faithful round-trip on that file's two frozen examples (see the response-shape assertion above) |
-| `model_supply` holds exactly one row per menu model: `model_id` values are UNIQUE and the set COVERS that backend's whole menu (07-29, review round 6) | both halves are inexpressible. `uniqueItems` compares whole items, so two rows for one model differing only in `chain_length` validate — and then a `0` row sits beside a `2` row for the same id, with every consumer reading whichever it hits first, which is worse than a missing row: the 「无来源可供」 flag becomes a coin flip. Coverage is a relation to a different document (the backend's menu), which draft-07 cannot reach. Recorded as a server-validated invariant in spec §4.4 |
-| the `reason`↔`detail_key` correspondence between `resolution-event` and `source.state` is a BIJECTION over the five non-self-healing causes (07-29, review round 6) | cross-file identity again, and here it is load-bearing rather than tidy: a source state with no event reason is a blocker that cannot be announced, and an event reason with no source state is a push whose 「去处理」 lands on a row that renders nothing. The five pairs are listed at `resolution-event.schema.json` → `reason` |
-| `intent` is present on every v2 `OAuthFlow` response | same boundary as `selected_by_agent`: the shipped flow payloads are validated against that schema by `tests/test_model_hub_api.py` and predate the field, so `required` would fail the gate rather than tighten it |
+| every example validates and JSON round-trips | contract harness |
+| mirror registry equality/projection/partition/bijection, including mutation probes | `mirror-registry.json` harness |
+| every non-null `then` constraint has matching `required`, except a declared fail-safe legacy-example exception | contract harness |
+| every `sources.order` id exists, is unique, and is eligible | config loader + source-order route |
+| eligibility contains one row per source and every ordered source is eligible | AgentSupply assembler |
+| `AgentChain.chain` source ids are unique and preserve effective order | chain assembler |
+| `model_supply` has one row per menu model with unique ids | AgentSupply assembler |
+| 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 `selected_by_agent`, `selected_model_id`, `sources`, `supply_status`, `model_supply`, and `named_agents` | API payload test |
+| every OAuthFlow response includes `intent` | API payload test |
+
+Serializer completeness follows the issue #939 pattern. Persisted fields must
+round-trip through config serialization. Derived fields are exempt from persistence
+but require an API-payload test.
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.json
new file mode 100644
index 000000000..029703726
--- /dev/null
+++ b/docs/plans/model-hub-contracts/mirror-registry.json
@@ -0,0 +1,186 @@
+{
+ "contract_version": 3,
+ "entries": [
+ {
+ "id": "M1",
+ "vocabulary": "source state detail keys",
+ "rule": "equality",
+ "sets": [
+ {
+ "schema": "source.schema.json",
+ "paths": [
+ "/properties/state/allOf/1/then/properties/detail_key",
+ "/properties/state/allOf/2/then/properties/detail_key",
+ "/properties/state/allOf/3/then/properties/detail_key"
+ ],
+ "exclude": [null]
+ },
+ {
+ "schema": "probe-result.schema.json",
+ "paths": ["/properties/error"],
+ "exclude": [null]
+ }
+ ]
+ },
+ {
+ "id": "M2",
+ "vocabulary": "source status to chain health",
+ "rule": "mapping",
+ "home": {
+ "schema": "source.schema.json",
+ "path": "/properties/state/properties/status"
+ },
+ "target": {
+ "schema": "agent-chain.schema.json",
+ "path": "/properties/chain/items/properties/health"
+ },
+ "mapping": {
+ "active": "healthy",
+ "standby": "healthy",
+ "cooldown": "cooldown",
+ "needs_action": "needs_action",
+ "error": "error"
+ }
+ },
+ {
+ "id": "M3",
+ "vocabulary": "attempt failure causes",
+ "rule": "partition",
+ "home": {
+ "schema": "resolution-event.schema.json",
+ "path": "/properties/reason"
+ },
+ "member": {
+ "schema": "turn-provenance.schema.json",
+ "path": "/properties/failed_attempts/items/properties/reason"
+ },
+ "exclusions": [
+ "recovery",
+ "manual",
+ "mapping"
+ ],
+ "exclusion_sets": [
+ {
+ "schema": "resolution-event.schema.json",
+ "path": "/allOf/0/then/properties/reason"
+ }
+ ]
+ },
+ {
+ "id": "M4",
+ "vocabulary": "non-self-healing cause to detail key",
+ "rule": "bijection",
+ "home": {
+ "schema": "resolution-event.schema.json",
+ "path": "/properties/reason"
+ },
+ "target_sets": [
+ {
+ "schema": "source.schema.json",
+ "paths": [
+ "/properties/state/allOf/2/then/properties/detail_key",
+ "/properties/state/allOf/3/then/properties/detail_key"
+ ]
+ }
+ ],
+ "pairs": {
+ "credential_expired": "models.source.needs_action.oauth_expired",
+ "credential_revoked": "models.source.needs_action.credential_revoked",
+ "balance_exhausted": "models.source.needs_action.balance_exhausted",
+ "account_banned": "models.source.needs_action.account_banned",
+ "unclassified_error": "models.source.error.unclassified"
+ }
+ },
+ {
+ "id": "M5",
+ "vocabulary": "supply state taxonomy",
+ "rule": "projection",
+ "home": {
+ "schema": "agent-supply.schema.json",
+ "path": "/properties/supply_status",
+ "exclude": [null]
+ },
+ "targets": [
+ {
+ "schema": "agent-supply.schema.json",
+ "path": "/properties/named_agents/items/properties/supply_status",
+ "exclude": [null],
+ "drop_from_home": []
+ },
+ {
+ "schema": "agent-chain.schema.json",
+ "path": "/properties/supply_state",
+ "drop_from_home": ["degraded"]
+ },
+ {
+ "schema": "turn-provenance.schema.json",
+ "path": "/properties/model_supply_state",
+ "exclude": [null],
+ "drop_from_home": ["ok", "degraded"]
+ }
+ ]
+ },
+ {
+ "id": "M6",
+ "vocabulary": "backend identifiers",
+ "rule": "equality",
+ "sets": [
+ {
+ "schema": "agent-supply.schema.json",
+ "paths": ["/properties/backend"]
+ },
+ {
+ "schema": "agent-chain.schema.json",
+ "paths": ["/properties/backend"]
+ },
+ {
+ "schema": "probe-result.schema.json",
+ "paths": ["/properties/backend"]
+ },
+ {
+ "schema": "turn-provenance.schema.json",
+ "paths": ["/properties/agent"]
+ },
+ {
+ "schema": "resolution-event.schema.json",
+ "paths": ["/properties/agent"],
+ "extras": ["system"]
+ }
+ ]
+ },
+ {
+ "id": "M7",
+ "vocabulary": "supply channel",
+ "rule": "equality",
+ "sets": [
+ {
+ "schema": "source.schema.json",
+ "paths": ["/properties/supply_channel"]
+ },
+ {
+ "schema": "agent-supply.schema.json",
+ "paths": ["/properties/current/properties/channel"]
+ },
+ {
+ "schema": "turn-provenance.schema.json",
+ "paths": [
+ "/properties/failed_attempts/items/properties/channel",
+ "/properties/served/properties/channel",
+ "/properties/terminal_error/properties/channel",
+ "/properties/canceled_attempt/properties/channel"
+ ]
+ }
+ ]
+ },
+ {
+ "id": "N1",
+ "vocabulary": "source recommendation rule",
+ "rule": "none",
+ "home": {
+ "schema": "agent-supply.schema.json",
+ "path": "/properties/sources/properties/policy"
+ },
+ "reason": "The deterministic ordering predicate has one normative home in model-hub.md section 4.2 and is not a shared vocabulary."
+ }
+ ]
+}
diff --git a/docs/plans/model-hub-contracts/priority.schema.json b/docs/plans/model-hub-contracts/priority.schema.json
deleted file mode 100644
index d355269cd..000000000
--- a/docs/plans/model-hub-contracts/priority.schema.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "$schema": "http://json-schema.org/draft-07/schema#",
- "$id": "model-hub/priority.schema.json",
- "title": "Priority (REMOVED in contract v2 — v1 tombstone, DO NOT IMPLEMENT)",
- "description": "REMOVED IN CONTRACT v2 (owner ruling 2026-07-28/29). The single global spend order was a product-model error: ordering is a CONSUMPTION property, so it now lives per agent backend in agent-supply.schema.json → `sources` {policy, order}. Nothing in v2 reads or writes this shape, and `PUT /api/models/priority` is gone from api.md. This file survives only as a v1 tombstone: the shipped-but-dormant v1 code still emits this payload and tests/test_model_hub_api.py still validates against it, so deleting the file today turns CI red for a shape v2 does not use. The lane that removes the endpoint and ModelHubConfig.priority_order deletes this file in the same PR and replaces that one assertion with an inline shape check. Text below is frozen v1 and must not be extended.",
- "type": "object",
- "required": ["contract_version", "order"],
- "additionalProperties": false,
- "properties": {
- "contract_version": { "const": 1 },
- "order": {
- "type": "array",
- "description": "v1 only: source ids, position 0 = spend first; MUST contain every non-deleted source exactly once. v2's replacement is a per-backend SUBSET, not a permutation.",
- "items": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
- "uniqueItems": true
- }
- },
- "examples": [
- { "contract_version": 1, "order": ["src_claudepro1", "src_chatgptplus", "src_anthkey01", "src_zhipukey01", "src_relay9c1x"] }
- ]
-}
diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.json
index 07e488cf9..45061d35b 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", "reachable", "source_id", "model_id", "latency_ms", "via_mapping", "error"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 2 },
+ "contract_version": { "const": 3 },
"backend": { "enum": ["claude", "codex", "opencode"] },
"reachable": {
"type": "boolean",
@@ -15,7 +15,7 @@
},
"source_id": {
"type": "string",
- "minLength": 1,
+ "pattern": "^src_[a-z0-9]{8,}$",
"description": "The source that served (or failed) the probe — the first runnable candidate in this backend's chain for the probed model. NON-NULLABLE (07-29, review round 4): returning this object already means a candidate was resolved and attempted, because the no-candidate case is the separate `probe_no_candidate` error envelope. The v1 draft made it nullable 'for defensive serialization', which only bought the right to answer 「跑不通」 without saying what was tried — the one thing a probe exists to report."
},
"model_id": {
@@ -113,7 +113,7 @@
],
"examples": [
{
- "contract_version": 2,
+ "contract_version": 3,
"backend": "codex",
"reachable": true,
"source_id": "src_chatgptplus",
@@ -123,7 +123,7 @@
"via_mapping": false
},
{
- "contract_version": 2,
+ "contract_version": 3,
"backend": "claude",
"reachable": false,
"source_id": "src_relay9c1x",
@@ -133,7 +133,7 @@
"via_mapping": true
},
{
- "contract_version": 2,
+ "contract_version": 3,
"backend": "claude",
"reachable": false,
"source_id": "src_relay9c1x",
diff --git a/docs/plans/model-hub-contracts/resolution-event.schema.json b/docs/plans/model-hub-contracts/resolution-event.schema.json
index 1c4b5471d..734ac2856 100644
--- a/docs/plans/model-hub-contracts/resolution-event.schema.json
+++ b/docs/plans/model-hub-contracts/resolution-event.schema.json
@@ -2,7 +2,7 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/resolution-event.schema.json",
"title": "ResolutionEvent",
- "description": "最近切换 feed entry. ADAPTER-OWNED: our adapter classifies per-source outcomes and emits these; the engine's own usage feed stays disabled because it leaks inbound keys (S1 gap ②). Redaction invariant: no credential material, no raw upstream error bodies.",
+ "description": "v3 source-resolution feed entry. Adapter-owned and redacted: ids, classified causes, and bounded human summaries only; never credential material or raw upstream error bodies. The record stays single-grained. Consumers derive current per-backend and per-Agent impact live instead of storing fan-out.",
"type": "object",
"required": ["id", "ts", "agent", "kind", "model_id", "reason", "human_zh", "human_en"],
"additionalProperties": false,
@@ -11,22 +11,33 @@
"ts": { "type": "string", "format": "date-time" },
"agent": {
"enum": ["claude", "codex", "opencode", "system"],
- "description": "A BACKEND identifier, not a Vibe Agent name (07-29, review round 7): the enum is the three agent backends, while Avibe routing selects NAMED Vibe Agents (`pm`, and any the user creates) whose backend is one of these. The two grains coincide only for the default Agent of each backend, which is why one-hop readings of 'the event names an Agent' looked correct. Consumers that need Agents or scopes MUST expand: backend → Vibe Agents currently enabled on that backend → scopes whose routing selects them (spec §4.5 → 'Who receives an action-required push' is the normative rule). `system` is not a backend at all: it is the emitter for events no backend produced (a settings mutation, a manual recovery), and it expands to no Agent and therefore to no recipient — those events are feed-and-page records, which is the zero-scope outcome spec §4.5 declares correct."
+ "description": "The discovering backend, or system for a source-scoped non-turn operation. system is never valid for backend-scoped supply_interrupted. Mirrors the backend vocabulary with the one declared extra system."
},
"kind": {
- "enum": ["switch", "cooldown", "recover", "skip", "mapping_applied", "channel_switch", "needs_action", "supply_interrupted"],
- "description": "v2 adds two. `needs_action`: a SOURCE stopped being usable in a way that will not heal itself (OAuth expired, balance exhausted, key revoked, or — round 6 — an unclassified failure, which promises no recovery either) — without it the feed would have to file such a source under `cooldown`, which promises an automatic recovery that is never coming. Its scope is 「a source went dead and stays dead until someone acts」; WHICH way it died is `reason`, which is why round 6 closed the `error`-status hole by adding a cause rather than a kind. `supply_interrupted` (07-29, review round 2): an AGENT's chain became structurally unrunnable — every other kind here is scoped to a source, and an agent can go `interrupted` with no source changing state at all (its last enabled source is removed from the order, or its selected model stops being supplied by anything in that order). The spec requires an `action_required` push for that transition (§4.5); without this kind the emitter would have to borrow a credential/quota reason and misstate the cause, or stay silent about the one state that always needs the user. Scoped to the agent: `from_source`/`to_source` are null, because nothing switched — the chain emptied. Emit on the TRANSITION only, never per starved turn. Like `needs_action`, this is a v2 target the shipped emitter predates."
+ "enum": [
+ "switch",
+ "cooldown",
+ "recover",
+ "skip",
+ "mapping_applied",
+ "channel_switch",
+ "needs_action",
+ "supply_interrupted"
+ ]
+ },
+ "model_id": {
+ "type": ["string", "null"],
+ "description": "The caller-facing model when the event is about one model. null means a system event is about the source as a whole, not an invented representative model."
},
- "model_id": { "type": "string" },
"from_source": {
"type": ["string", "null"],
- "description": "v2 (07-29, review round 5): DEFINED here for the first time — the pair carried no description at all, which is the root of the round-5 finding and of the round-4 one before it. With the meaning unstated, every kind's endpoint shape was an open question and each review round found another kind nobody had pinned (round 4: `switch` had two blanks; round 5: `needs_action` had no source at all). The events split into two families and the pair serves both: TRAFFIC events say where the traffic went (`switch`, `channel_switch`, `recover`), STATE events name the one source they are about. `from_source` is the LOSING side: the source traffic moved away from, or — for a state event that moves no traffic — the source that became unusable (`cooldown`, `needs_action`, `skip`). Non-null for all four of those plus `channel_switch`; null only for the agent-scoped `supply_interrupted`, where nothing switched and no single source is the subject. A `needs_action` event without it is what the round-5 review caught: the push it mandates would have no machine-readable source to hand to the credential/reauth routes, and the localized sentence is not a safe thing to parse.",
- "examples": ["src_claudepro1"]
+ "pattern": "^src_[a-z0-9]{8,}$",
+ "description": "The losing source or the source a degradation is about. Non-null identifiers use the canonical Source id format."
},
"to_source": {
"type": ["string", "null"],
- "description": "v2 (07-29, review round 5): the WINNING side — the source traffic moved to, or, for `recover`, the source that became usable again. Non-null for `switch`, `channel_switch` and `recover`; null for the pure degradations (`cooldown`, `needs_action`, `skip`), where nothing gained traffic, and for `supply_interrupted`. `recover` is why the subject of a state event cannot simply always be `from_source`: it is the one restoration in the enum, so its subject enters service rather than leaving it, and filing it under 'from' would invert the sentence the feed renders. `channel_switch` carries the SAME id at both ends by design — the channel changed, the source did not (see the `allOf` note).",
- "examples": ["src_anthkey01"]
+ "pattern": "^src_[a-z0-9]{8,}$",
+ "description": "The winning or recovered source. Non-null identifiers use the canonical Source id format."
},
"reason": {
"enum": [
@@ -46,84 +57,147 @@
"no_eligible_source",
"model_unsupported"
],
- "description": "Canonical error classification lives in the adapter (S1 gap ①): param/protocol/tool-compat errors surface to the caller and never produce switch events. The last three are the `supply_interrupted` causes (07-29), and they are three rather than one because each names a different one-tap fix: `no_enabled_source` = this backend's order is empty or just lost its last member (add one to the order, or switch back to 跟随推荐), `no_eligible_source` = nothing in the whole inventory is eligible for this backend (add a source), `model_unsupported` = the order is populated but nothing in it supplies the selected model (pick another model, or map this one). Agent-scoped by construction — they are never valid for a source-scoped kind. PRECEDENCE IS NORMATIVE, not emitter preference (07-29, review round 3): these three overlap, so evaluate them in this order and emit the FIRST that matches — (1) `no_eligible_source`, (2) `no_enabled_source`, (3) `model_unsupported`. Ineligibility subsumes emptiness: if nothing in the inventory is eligible for this backend then its enabled order is necessarily empty too, and both predicates match. Picking `no_enabled_source` there would offer 「加到顺序里」 for a set of candidates that does not exist, sending the user to a drawer with nothing to enable, when the real fix is to add a source. `model_unsupported` comes last because it presupposes a populated, eligible order. `reason` is required, so v2 also adds the four needs_action causes — without them a `kind: needs_action` event would have to borrow a self-healing reason like `quota_exhausted` and the feed would misstate what happened. FIVE, as of 07-29 review round 6: `unclassified_error` is the counterpart of source `state.status: \"error\"`, and it closes a hole the review named. `error` is a BLOCKER that needs the user — `agent-chain.schema.json` pins `runnable: false` for it and counts it in the OR-branch that makes a chain `interrupted`, exactly like `needs_action` — so an interruption caused by the last runnable source going `error` obliges an action_required push (spec §4.5), and there was no reason in this enum that could carry it. The emitter's only options were to misclassify (borrow `credential_revoked` and assert a cause nobody established) or stay silent (drop the one alert the user is owed, on the state we understand least). Neither is acceptable, so the vocabulary grew by one rather than the obligation shrinking. It is deliberately NOT a widening of `supply_interrupted`, which nulls both endpoints: this interruption HAS a source — the one that failed — and stripping the push of its machine-readable source is the exact defect round 5 fixed for `needs_action`. Nor is it a 9th `kind`: the state is 「a source stopped being usable and will not heal itself」, which is what `needs_action` already means; only the cause differs, and cause is what `reason` is for. THE FIVE MAP 1:1 ONTO source `state.detail_key`, and with this one the correspondence is a BIJECTION over every non-self-healing key: credential_expired→models.source.needs_action.oauth_expired, credential_revoked→.credential_revoked, balance_exhausted→.balance_exhausted, account_banned→.account_banned, unclassified_error→models.source.error.unclassified. Totality in both directions is the property that matters — a source state with no reason cannot be announced, and a reason with no state sends 「去处理」 to a row that renders nothing — and it is checked mechanically (api.md → Mechanical guards). Note the deliberate pair: `quota_exhausted` is a subscription cycle running out (self-healing, resets) while `balance_exhausted` is prepaid credit hitting zero (needs a top-up). THIS FIELD IS A VOCABULARY HOME with a computed downstream (07-29, review round 7): `turn-provenance.schema.json` → `failed_attempts[].reason` holds exactly this set minus the three resolution-shaped values (`recovery`, `manual`, `mapping`) minus the three that classify an agent's whole supply rather than one candidate's attempt (`no_enabled_source`, `no_eligible_source`, `model_unsupported`) — a set equality, checked across files (README.md → vocabulary mirror table). So adding a value here is never a local edit: it lands in the attempt-failure set by default, and keeping it out requires putting it in one of the two documented exclusions. Round 6 added `unclassified_error` here alone, which left that mirror one value short and an unmappable fallback with no legal reason to report."
+ "description": "Adapter classification. The five non-self-healing source causes map bijectively to Source.state.detail_key: credential_expired→models.source.needs_action.oauth_expired; credential_revoked→models.source.needs_action.credential_revoked; balance_exhausted→models.source.needs_action.balance_exhausted; account_banned→models.source.needs_action.account_banned; unclassified_error→models.source.error.unclassified. The machine-readable mirror registry enforces the relation."
+ },
+ "billing_note": {
+ "enum": [null, "entered_metered", "left_metered"]
},
- "billing_note": { "enum": [null, "entered_metered", "left_metered"], "description": "drives the gold dot in frame V6 01" },
"severity": {
"type": ["string", "null"],
"enum": ["info", "action_required", null],
- "description": "v2 (2026-07-29): the notification tier, decided once at emit time (spec §4.5). info = self-healing (switch/cooldown/recover) — appears in the 最近切换 feed ONLY, never an IM push. action_required = the user owes an action (needs_action sources, an interrupted agent chain) — proactive IM push in colleague voice. The push layer MUST key off this field rather than re-deriving urgency from `kind`, so 'when do we interrupt the user' has exactly one definition. Because it is the sole input to that decision, the two kinds the spec puts in the action-required tier — `needs_action` and `supply_interrupted` — pin it to `action_required` by CONDITIONAL (see `allOf`), not by emitter discipline: those are the events whose whole purpose is to reach the user, so 'emitted correctly but never delivered' must not be a representable state. Every OTHER kind is `info` by conditional too (07-29, review round 4) — the §4.5 table has exactly two action-required rows, so the tier is a total function of `kind` and no emitter judgement enters: 'emitted a self-healing state as an interruption' is likewise unrepresentable. SEVERITY ANSWERS WHETHER TO INTERRUPT, NEVER WHOM (07-29, review round 5): it is a tier, not an address, which is why this event carries no recipient, channel, platform, or audience field. Recipients are resolved AT DELIVERY from the event's `agent` (source-scoped kinds resolve to the agents whose `sources.order` contains that source) against the live routing table — spec §4.5 → 'Who receives an action-required push' is the normative rule. Putting them here instead would freeze a routing snapshot into an append-only feed: a scope re-pointed at a different agent afterwards would still be addressed by the old event, and a scope added later would never be. So `action_required` makes an event ELIGIBLE for delivery rather than constituting delivery, and an eligible event resolving to zero scopes is correctly delivered nowhere. Optional in this schema only because the shipped v1 emitter predates it; it becomes REQUIRED at the API boundary in the serializer PR (README → Required-vs-optional)."
+ "description": "Feed and Models-page presentation metadata. info marks self-healing state; action_required marks state that needs user action. It is not an address or a delivery instruction."
},
"human_zh": { "type": "string", "maxLength": 200 },
"human_en": { "type": "string", "maxLength": 200 }
},
"allOf": [
{
- "$comment": "v2 (07-29): agent-scoped kind ⇒ agent-scoped shape. Stated as a conditional rather than prose so a contradictory event cannot validate: nothing switched, so no source endpoints; the state always needs the user, so the tier is not a judgement call at emit time.",
- "if": { "properties": { "kind": { "const": "supply_interrupted" } }, "required": ["kind"] },
+ "$comment": "Backend-scoped supply interruption: no source endpoint, a real backend, a real model, and one of the three structural causes.",
+ "if": {
+ "properties": { "kind": { "const": "supply_interrupted" } },
+ "required": ["kind"]
+ },
"then": {
- "required": ["severity"],
+ "required": ["agent", "model_id", "severity"],
"properties": {
+ "agent": { "enum": ["claude", "codex", "opencode"] },
+ "model_id": { "type": "string" },
"severity": { "const": "action_required" },
"from_source": { "type": "null" },
"to_source": { "type": "null" },
- "reason": { "enum": ["no_enabled_source", "no_eligible_source", "model_unsupported"] }
+ "reason": {
+ "enum": [
+ "no_enabled_source",
+ "no_eligible_source",
+ "model_unsupported"
+ ]
+ }
}
}
},
{
- "$comment": "v2 (07-29): and the converse, so the three agent-scoped reasons cannot be attached to a source-scoped kind.",
"if": {
- "properties": { "reason": { "enum": ["no_enabled_source", "no_eligible_source", "model_unsupported"] } },
+ "properties": {
+ "reason": {
+ "enum": [
+ "no_enabled_source",
+ "no_eligible_source",
+ "model_unsupported"
+ ]
+ }
+ },
"required": ["reason"]
},
- "then": { "properties": { "kind": { "const": "supply_interrupted" } } }
+ "then": {
+ "required": ["kind"],
+ "properties": { "kind": { "const": "supply_interrupted" } }
+ }
},
{
- "$comment": "v2 (07-29, review round 3): `needs_action` gets the same treatment as `supply_interrupted`, for the same reason. `severity` is the SOLE input to the push layer (api.md → events), and the spec puts needs_action in the action-required tier unconditionally (§4.5 notification table). Leaving `info`/null writable here would let a semantically invalid event validate and silently cost the user the one alert they are owed — a revoked key that never notifies. Its causes are pinned too: a needs_action event carrying `quota_exhausted` would describe a state that heals itself, which is exactly the confusion this kind exists to end. FIVE causes as of round 6, not four — `unclassified_error` joins them so the source status `error`, which `agent-chain` already treats as a user-owed blocker, has a representable action-required event instead of forcing the emitter to misclassify or stay silent (see `reason`). Source-scoped, so `from_source`/`to_source` are deliberately NOT constrained here — the round-5 member below requires `from_source` for this kind, which is what gives the push something to open.",
- "if": { "properties": { "kind": { "const": "needs_action" } }, "required": ["kind"] },
+ "$comment": "A needs_action record is source-scoped and carries one of the five non-self-healing source causes.",
+ "if": {
+ "properties": { "kind": { "const": "needs_action" } },
+ "required": ["kind"]
+ },
"then": {
- "required": ["severity"],
+ "required": ["from_source", "severity"],
"properties": {
+ "from_source": { "type": "string" },
+ "to_source": { "type": "null" },
"severity": { "const": "action_required" },
- "reason": { "enum": ["credential_expired", "credential_revoked", "balance_exhausted", "account_banned", "unclassified_error"] }
+ "reason": {
+ "enum": [
+ "credential_expired",
+ "credential_revoked",
+ "balance_exhausted",
+ "account_banned",
+ "unclassified_error"
+ ]
+ }
}
}
},
{
- "$comment": "v2 (07-29, review round 4): the tier is now decided for EVERY kind, not just the two that push. Round 3 pinned `needs_action` and `supply_interrupted` to `action_required` and left the rest 'the emitter's choice', which meant a `switch` or a `cooldown` could still carry `action_required` and interrupt the user about a state that heals itself in minutes — the exact failure the `waiting` class was invented to prevent (spec §4.5: self-healing states are feed-only, NEVER an IM push). The spec's notification table has exactly two rows and names exactly two action-required causes, so every other kind is `info` by that table, not by judgement. With both halves pinned, `severity` is fully determined by `kind` — which is the point: the push layer reads one field, and no emitter can disagree with the table. PRESENCE DELIBERATELY NOT REQUIRED on this branch (07-29, review round 5), unlike the two action-required branches above which do require it: this file's frozen example is a `switch` carrying no `severity` at all — it round-trips byte-faithfully through the shipped v1 emitter, which predates the field — so requiring it here would fail the contract gate. The asymmetry is not a compromise, it is the right way round. An absent `severity` on an info kind means no push, which is what the info tier asks for anyway; an absent `severity` on `needs_action` would mean a revoked key that never alerts anyone, so that is exactly where presence IS required. Enforced as a declared exception in the round-5 presence checker so it cannot decay into an accident (api.md → Serializer completeness).",
+ "$comment": "Presence of severity remains optional only for byte-faithful legacy examples. The API boundary requires it.",
"if": {
"properties": {
- "kind": { "enum": ["switch", "cooldown", "recover", "skip", "mapping_applied", "channel_switch"] }
+ "kind": {
+ "enum": [
+ "switch",
+ "cooldown",
+ "recover",
+ "skip",
+ "mapping_applied",
+ "channel_switch"
+ ]
+ }
},
"required": ["kind"]
},
- "then": { "properties": { "severity": { "const": "info" } } }
+ "then": {
+ "properties": { "severity": { "const": "info" } }
+ }
},
{
- "$comment": "v2 (07-29, review round 4; widened to five in round 6): the NON-SELF-HEALING causes cannot be filed under a SELF-HEALING kind. `cooldown` promises an automatic recovery and `recover` reports one, so 'cooling because the key was revoked' and 'recovered by account ban' are both contradictions — and the first is precisely the misfiling `needs_action` was added to end (a dead source dressed as a timer, with an `info` tier and no alert). `unclassified_error` is in the same class and joins for the same reason: an unclassified failure carries no promise about when it lapses (`source.schema.json` pins `retry_at` null for `error`), so filing it as a cooldown would invent a recovery time the adapter explicitly does not have. NOTE the deliberately narrow scope, unchanged: these reasons ARE valid on `switch`, because falling back AWAY from a revoked — or unclassifiably broken — source is a real self-healing switch whose cause is that failure, and turn-provenance keeps the same causes in its FALLBACK vocabulary for that reason. A blanket 'these reasons imply kind == needs_action' converse would make that switch unrepresentable and force the emitter to relabel the cause of a switch it correctly performed; the two events are emitted together (one `switch`, info + one `needs_action`, action_required), each true about its own subject.",
"if": {
"properties": {
- "reason": { "enum": ["credential_expired", "credential_revoked", "balance_exhausted", "account_banned", "unclassified_error"] }
+ "reason": {
+ "enum": [
+ "credential_expired",
+ "credential_revoked",
+ "balance_exhausted",
+ "account_banned",
+ "unclassified_error"
+ ]
+ }
},
"required": ["reason"]
},
- "then": { "properties": { "kind": { "not": { "enum": ["cooldown", "recover"] } } } }
+ "then": {
+ "properties": {
+ "kind": { "not": { "enum": ["cooldown", "recover"] } }
+ }
+ }
},
{
- "$comment": "v2 (07-29, review round 4; presence added in round 5): a `switch` has two ends by definition — it is the one kind whose whole content is 'from here to there', and the feed line 「A 额度用完 → 已切到 B」 cannot be written without both. Left free, a switch with null endpoints would render as a sentence with two blanks. ROUND 5: `required` was missing, and neither endpoint is in the top-level `required` list, so this whole conditional was decorative — a switch that simply omitted both keys validated, which is the same defect the review named on source.schema.json's `credential_ref` and is fixed the same way. `then: {properties: …}` never enforces presence in draft-07.",
- "if": { "properties": { "kind": { "const": "switch" } }, "required": ["kind"] },
+ "if": {
+ "properties": { "kind": { "const": "switch" } },
+ "required": ["kind"]
+ },
"then": {
- "required": ["from_source", "to_source"],
+ "required": ["model_id", "from_source", "to_source"],
"properties": {
+ "model_id": { "type": "string" },
"from_source": { "type": "string" },
"to_source": { "type": "string" }
}
}
},
{
- "$comment": "v2 (07-29, review round 5): every SOURCE-SCOPED kind must name its source, which round 4 left open for four of the eight kinds after pinning it for `switch`. `needs_action` is the one that costs the user something real and is what the review named: it is the action_required tier, so its whole purpose is to reach the user with 「去处理」 — and with both endpoints null the push has nothing to open, nothing to hand the credential/reauth routes, and only a localized sentence, which is not a safe thing to parse. `cooldown` and `skip` are the same shape and are fixed in the same member rather than waiting to be reported: all three are degradations, so the subject is the LOSING side and `to_source` stays null because nothing gained traffic. Fixing the reported kind alone would have left two instances of the identical hole one line away.",
- "if": { "properties": { "kind": { "enum": ["needs_action", "cooldown", "skip"] } }, "required": ["kind"] },
+ "if": {
+ "properties": { "kind": { "enum": ["cooldown", "skip"] } },
+ "required": ["kind"]
+ },
"then": {
"required": ["from_source"],
"properties": {
@@ -133,18 +207,22 @@
}
},
{
- "$comment": "v2 (07-29, review round 5): `recover` is the one RESTORATION in the enum, so its subject enters service instead of leaving it and belongs on the winning side — this is exactly why 'the subject of a state event is always from_source' would have been the wrong rule to write. `from_source` is deliberately NOT constrained: a recovery reached by switching back from a fallback has one (「已切回 A」), while a recovery that only restores availability — the credential-replacement route in api.md, where nothing was serving because the source was needs_action — has nothing on the losing side, and both are true events.",
- "if": { "properties": { "kind": { "const": "recover" } }, "required": ["kind"] },
+ "$comment": "recover can be a source-wide repair or a model-specific fallback return, so from_source and model_id are deliberately not constrained.",
+ "if": {
+ "properties": { "kind": { "const": "recover" } },
+ "required": ["kind"]
+ },
"then": {
"required": ["to_source"],
- "properties": {
- "to_source": { "type": "string" }
- }
+ "properties": { "to_source": { "type": "string" } }
}
},
{
- "$comment": "v2 (07-29, review round 5): `channel_switch` keeps the source and changes how it is consumed (native_cli ↔ hub), so both ends exist and carry the SAME id — the shape was already documented in the round-4 note and was the last source-scoped kind with no constraint at all. The equality itself is not expressible in draft-07 (no `$data`, so one field cannot reference another) and is a mechanical guard instead (api.md → Serializer completeness); what IS enforced here is that neither end is empty, so 「已改为中枢通道」 can always name its source. With this member the endpoint shape is a total function of `kind`: two ends for the traffic events, the losing end for the degradations, the winning end for the restoration, neither end for the agent-scoped `supply_interrupted`. ONE kind is deliberately left unconstrained: `mapping_applied` is decided at spec §4.3 step 1, BEFORE any candidate is selected, so it has no endpoint of its own and its feed line names models rather than sources (「claude-opus-4-6 → glm-5.2(经映射)」). An emitter that attaches the serving source is stating a true fact about a different subject, so neither shape is a contradiction and pinning one would be inventing a rule the spec does not have.",
- "if": { "properties": { "kind": { "const": "channel_switch" } }, "required": ["kind"] },
+ "$comment": "The schema cannot express from_source == to_source; the API-boundary guard enforces equality for channel_switch.",
+ "if": {
+ "properties": { "kind": { "const": "channel_switch" } },
+ "required": ["kind"]
+ },
"then": {
"required": ["from_source", "to_source"],
"properties": {
@@ -152,6 +230,62 @@
"to_source": { "type": "string" }
}
}
+ },
+ {
+ "if": {
+ "properties": { "kind": { "const": "mapping_applied" } },
+ "required": ["kind"]
+ },
+ "then": {
+ "required": ["agent", "model_id"],
+ "properties": {
+ "agent": { "enum": ["claude", "codex", "opencode"] },
+ "model_id": { "type": "string" }
+ }
+ }
+ },
+ {
+ "$comment": "v3 AC-11: null model_id is allowed only for a source-scoped system event. The converse is deliberately open because a system test of one explicit model may honestly name that model.",
+ "if": {
+ "properties": { "model_id": { "type": "null" } },
+ "required": ["model_id"]
+ },
+ "then": {
+ "required": ["agent", "kind"],
+ "properties": {
+ "agent": { "const": "system" },
+ "kind": {
+ "enum": [
+ "cooldown",
+ "recover",
+ "skip",
+ "needs_action",
+ "channel_switch"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "$comment": "system is reserved for source-scoped non-turn operations and cannot claim a backend-scoped or mapping event.",
+ "if": {
+ "properties": { "agent": { "const": "system" } },
+ "required": ["agent"]
+ },
+ "then": {
+ "required": ["kind"],
+ "properties": {
+ "kind": {
+ "enum": [
+ "cooldown",
+ "recover",
+ "skip",
+ "needs_action",
+ "channel_switch"
+ ]
+ }
+ }
+ }
}
],
"examples": [
@@ -167,6 +301,20 @@
"billing_note": "entered_metered",
"human_zh": "Claude Code:Claude Pro 本周期额度用完 → 已切到 Anthropic API Key(按量)",
"human_en": "Claude Code: Claude Pro cycle quota exhausted → switched to Anthropic API Key (metered)"
+ },
+ {
+ "id": "evt_20260729b",
+ "ts": "2026-07-29T09:10:00Z",
+ "agent": "system",
+ "kind": "needs_action",
+ "model_id": null,
+ "from_source": "src_relay9c1x",
+ "to_source": null,
+ "reason": "balance_exhausted",
+ "billing_note": null,
+ "severity": "action_required",
+ "human_zh": "Relay 余额不足,需要处理",
+ "human_en": "Relay balance is exhausted and needs attention"
}
]
}
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
index 0b1d6622e..e5af42403 100644
--- a/docs/plans/model-hub-contracts/source.schema.json
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -178,7 +178,7 @@
}
},
{
- "$comment": "v2 (07-29, review round 5): `error` is the UNCLASSIFIED failure, and round 4 read that as a reason to leave `detail_key` unconstrained — 'the point of the value is that we do not know the cause', recorded as a deliberate non-constraint. That reasoning was wrong, and the round-5 review is right that it was: not knowing the CAUSE is not permission to widen the CHANNEL. An unconstrained `detail_key` on the one status an adapter reaches when it cannot classify a failure is precisely where a raw upstream body lands — an auth response, a token-bearing diagnostic — and this field is persisted to config and rendered in the UI, so the redaction invariant (README invariant 1) would be waived at exactly the path most likely to carry secret material. Being unclassified makes redaction MORE load-bearing, not less. The vocabulary is therefore a single generic key, which is the honest cardinality: there is nothing to distinguish, so a richer set would be inventing causes the adapter by definition could not name, and any new one is a contract change with a designed remedy. It is REQUIRED rather than nullable for the same reason the needs_action keys are — the row must have something to render — and a null would be a second way to say the one thing this status says. The raw diagnostic keeps its home in scrubbed logs, never here. `retry_at` stays pinned null: an unclassified failure carries no promise about when it lapses, and offering one would be a guess rendered as a fact. ROUND 6 pins the other end of this status too: because `retry_at` is null and nothing will clear it unattended, `error` is a blocker that NEEDS THE USER — `agent-chain.schema.json` already counts it in the OR-branch that makes a chain `interrupted`, alongside `needs_action` — so an interruption caused by the last runnable source landing here is owed an action_required push. `resolution-event.schema.json` therefore carries `reason: unclassified_error`, which maps onto this exact key and makes the reason↔detail_key correspondence a bijection over all five non-self-healing keys. Without it the emitter had to choose between misclassifying the cause and staying silent on the state we understand least.",
+ "$comment": "v2 (07-29, review round 5): `error` is the UNCLASSIFIED failure, and round 4 read that as a reason to leave `detail_key` unconstrained — 'the point of the value is that we do not know the cause', recorded as a deliberate non-constraint. That reasoning was wrong, and the round-5 review is right that it was: not knowing the CAUSE is not permission to widen the CHANNEL. An unconstrained `detail_key` on the one status an adapter reaches when it cannot classify a failure is precisely where a raw upstream body lands — an auth response, a token-bearing diagnostic — and this field is persisted to config and rendered in the UI, so the redaction invariant (README invariant 1) would be waived at exactly the path most likely to carry secret material. Being unclassified makes redaction MORE load-bearing, not less. The vocabulary is therefore a single generic key, which is the honest cardinality: there is nothing to distinguish, so a richer set would be inventing causes the adapter by definition could not name, and any new one is a contract change with a designed remedy. It is REQUIRED rather than nullable for the same reason the needs_action keys are — the row must have something to render — and a null would be a second way to say the one thing this status says. The raw diagnostic keeps its home in scrubbed logs, never here. `retry_at` stays pinned null: an unclassified failure carries no promise about when it lapses, and offering one would be a guess rendered as a fact. ROUND 6 pins the other end of this status too: because `retry_at` is null and nothing will clear it unattended, `error` is a blocker that NEEDS THE USER — `agent-chain.schema.json` already counts it in the OR-branch that makes a chain `interrupted`, alongside `needs_action` — so an interruption caused by the last runnable source landing here requires an action_required state event. `resolution-event.schema.json` therefore carries `reason: unclassified_error`, which maps onto this exact key and makes the reason↔detail_key correspondence a bijection over all five non-self-healing keys. Without it the emitter had to choose between misclassifying the cause and staying silent on the state we understand least.",
"if": {
"properties": {
"status": {
diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.json
index 43642cee5..8d04da874 100644
--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json
+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json
@@ -2,46 +2,70 @@
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "model-hub/turn-provenance.schema.json",
"title": "TurnProvenance",
- "description": "v2 (2026-07-29): what served one turn — read via GET /api/models/turns/<turn_id>/provenance, rendered as the per-turn detail the conversation surface reveals on demand (spec §4.5). Frozen in v2 because the spec promises per-turn inspectability and a promise with no interface cannot be implemented consistently: this file is where that promise says what it means. Distinct from resolution-event.schema.json, which is the account-wide 最近切换 feed keyed on state CHANGES; this is keyed on a TURN and always exists, switch or not. Storage is the implementing lane's decision, with one constraint: written when the turn resolves and readable after the process exits — 'which source paid for this turn' is a billing question the user asks days later. Same redaction invariant as every other payload here: ids and i18n keys, never credential material or raw upstream error bodies. SHAPE RULING (07-29, review round 2): the winning attempt lives in `served` and NOWHERE ELSE, so 'at most one attempt served' and 'the served attempt is last' are not invariants a validator or a test has to defend — they are unrepresentable. Round 1 had one `attempts` array carrying an `outcome` per item, which let a payload claim two winners, a winner in the middle, or a top-level projection naming a source the array never mentions. The full attempt sequence is still recoverable, in order, as `failed_attempts` ++ [the terminating attempt], where the terminating attempt is `served`, `terminal_error`, or neither (nothing was ever tried). Round 3 generalised the ruling rather than bending it: a turn ends exactly one way, so the attempt that ENDED it lives in exactly one slot, and at most one of `served`/`terminal_error` is ever non-null.",
+ "description": "v3 debug record for one exactly attributed Hub turn. A record is written only when the turn FSM can attribute every included attempt to this turn; ambiguous attempts produce no provenance record. turn_id therefore remains required and no attribution-grain marker exists. The attempt sequence is failed_attempts followed by exactly one terminating slot when a source attempt terminated the turn: served, terminal_error, or canceled_attempt.",
"type": "object",
- "required": ["contract_version", "turn_id", "ts", "agent", "requested_model_id", "outcome", "failed_attempts", "served", "terminal_error", "model_supply_state"],
+ "required": [
+ "contract_version",
+ "turn_id",
+ "ts",
+ "agent",
+ "requested_model_id",
+ "outcome",
+ "failed_attempts",
+ "served",
+ "terminal_error",
+ "canceled_attempt",
+ "model_supply_state"
+ ],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 2 },
+ "contract_version": { "const": 3 },
"turn_id": {
"type": "string",
- "description": "The turn this describes, in whatever id space the session store already uses. Opaque here — this contract does not invent a new identifier."
+ "description": "Opaque id in the existing turn/session id space."
},
"ts": {
"type": "string",
"format": "date-time",
- "description": "When the turn resolved (served or gave up), not when it started."
+ "description": "When the FSM settled the turn."
},
"agent": {
"enum": ["claude", "codex", "opencode"],
- "description": "A BACKEND identifier, not a Vibe Agent name (07-29, review round 7): the enum is the three agent backends, while Avibe routing selects NAMED Vibe Agents (`pm`, and any the user creates) whose backend is one of these. The two grains coincide only for the default Agent of each backend, which is why one-hop readings of 'the event names an Agent' looked correct. Consumers that need Agents or scopes MUST expand: backend → Vibe Agents currently enabled on that backend → scopes whose routing selects them (spec §4.5 → 'Who receives an action-required push' is the normative rule). Mirrors `agent-supply.schema.json` → `backend` exactly; the name is historical and kept for round-trip fidelity with the shipped payload."
+ "description": "Backend identifier. Mirrors AgentSupply.backend exactly."
},
"requested_model_id": {
"type": "string",
- "description": "What the caller asked for, as the caller-facing MENU identifier (prefixed for open menus) — before mapping. Recorded because 「我选的模型」 and 「实际跑的模型」 differing is precisely what the user is inspecting."
+ "description": "Caller-facing menu identifier before mapping."
},
"outcome": {
- "enum": ["served", "exhausted", "failed_terminal", "no_candidate"],
- "description": "How the turn ended, as one field instead of something the reader infers by comparing two others. served = one attempt COMPLETED the turn successfully. Not 'produced output' (corrected 07-29, review round 4): a source that emits one token and then dies has produced output, and §4.3 rules that same turn `failed_terminal` with `stream_interrupted` — so the loose reading made both outcomes true of the one scenario whose whole point is that it is NOT a success, and the field exists precisely to stop the reader inferring the answer. Partial output followed by a failure is `failed_terminal` with `stream_started: true`; that pair is how the record says 'the user saw a half-written answer', and it is the only honest way to say it. exhausted = fallback was walked to the end and every attempt failed for a fallback cause (`failed_attempts` non-empty, everything else null). failed_terminal (07-29, review round 3) = an attempt hit a NON-fallback error and the turn stopped there, recorded in `terminal_error`. no_candidate = the pipeline never tried anything (`failed_attempts` EMPTY) because this (agent, model) chain had nothing runnable — an empty chain, or every member blocked. `failed_terminal` closes a hole round 2 left open: spec §4.3 says param/protocol/tool-compat errors surface to the caller instead of producing a fallback, and that once streaming has started there is no transparent retry — so such a turn is neither `served` nor `no_candidate`, and calling it `exhausted` would be a lie twice over (the chain was NOT exhausted, and the emitter would have to borrow a fallback reason like `server_error` to fill a required field, misfiling a broken request as a supply problem and pointing the user at their account instead of the actual bug). A record with no honest value for its own outcome field is worse than no record. `no_candidate` is the reason `failed_attempts` has no minItems: a turn that gave up before touching a source is exactly the turn the user most needs to inspect, so fabricating a phantom attempt to satisfy a schema would corrupt the record it exists to preserve."
+ "enum": [
+ "served",
+ "exhausted",
+ "failed_terminal",
+ "no_candidate",
+ "canceled"
+ ],
+ "description": "FSM terminal classification. canceled is emitted only from explicit Stop/cancel truth, never inferred from a dropped transport."
},
"failed_attempts": {
"type": "array",
- "description": "Every candidate that was tried and did NOT serve, in the order it was tried. May be empty (see `outcome: no_candidate`). Candidates SKIPPED before being tried (cooling, ineligible, needs_action) are not attempts and are absent — the chain query answers 'what else exists'. Every item here failed, by construction: there is no per-item outcome to disagree with the top level.",
+ "description": "Candidates tried and left behind through fallback, in order. Skipped candidates are not attempts.",
"items": {
"type": "object",
- "required": ["source_id", "resolved_model_id", "channel", "via_mapping", "reason"],
+ "required": [
+ "source_id",
+ "resolved_model_id",
+ "channel",
+ "via_mapping",
+ "reason"
+ ],
"additionalProperties": false,
"properties": {
- "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
- "resolved_model_id": {
+ "source_id": {
"type": "string",
- "description": "The id actually sent upstream for this attempt, mapping applied."
+ "pattern": "^src_[a-z0-9]{8,}$"
},
+ "resolved_model_id": { "type": "string" },
"channel": { "enum": ["native_cli", "hub"] },
"via_mapping": { "type": "boolean" },
"reason": {
@@ -56,18 +80,21 @@
"account_banned",
"unclassified_error"
],
- "description": "Why this attempt failed, from the resolution-event `reason` vocabulary narrowed to the FALLBACK causes — every value here is a cause that made the resolver move to the next candidate. NOT nullable and NOT free text: a failed attempt with no reason was the round-1 shape's other unrepresentable-should-have-been, and the classification already exists adapter-side (S1 gap ①). Param/protocol/tool-compat errors are absent from this enum by construction, because they do not produce a fallback (spec §4.3 error taxonomy) — they end the turn, and their home is `terminal_error`. The narrowing is MECHANICAL, not editorial (07-29, review round 7): this set is exactly `resolution-event.reason` minus the three resolution-shaped values that are not attempt failures (`recovery`, `manual`, `mapping`) minus the three that classify the agent's own supply rather than one candidate's attempt (`no_enabled_source`, `no_eligible_source`, `model_unsupported`), so it is a computed set equality and a new `reason` cannot be added without deciding which side it falls on. `unclassified_error` was missing until round 7: round 6 added it to `resolution-event` as a fallback-producing cause and stopped there, so an adapter that fell back from an unmappable failure had no legal value for a REQUIRED field and the only way to emit a valid record was to misreport the cause as `server_error`. `timeout` is legitimately absent — it is not in `resolution-event.reason` either; a timed-out attempt reports `network`."
+ "description": "The attempt-failure partition of ResolutionEvent.reason. The mirror registry enforces totality."
}
}
}
},
"served": {
"type": ["object", "null"],
- "description": "The attempt that COMPLETED the turn — the record of the winner, not a projection of it. 'Completed', not 'produced output' (07-29, review round 4): an attempt that started streaming and then failed belongs in `terminal_error` with `stream_started: true`, never here, so the two slots stay disjoint on the mid-stream case as well as the clean ones. NULL for all three failure outcomes. Carries the same fields as a failed attempt minus `reason`, so the render walks `failed_attempts` then appends this one.",
+ "description": "The attempt that completed the turn; non-null only for outcome served.",
"required": ["source_id", "resolved_model_id", "channel", "via_mapping"],
"additionalProperties": false,
"properties": {
- "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
+ "source_id": {
+ "type": "string",
+ "pattern": "^src_[a-z0-9]{8,}$"
+ },
"resolved_model_id": { "type": "string" },
"channel": { "enum": ["native_cli", "hub"] },
"via_mapping": { "type": "boolean" }
@@ -75,85 +102,177 @@
},
"terminal_error": {
"type": ["object", "null"],
- "description": "v2 (07-29, review round 3): the attempt that ENDED the turn with a non-fallback error — the counterpart to `served`, in the same slot-per-terminating-attempt shape and for the same reason. NULL unless `outcome` is `failed_terminal`. Carries the same identity fields as an attempt, so the render still walks `failed_attempts` and appends this one; the difference is the `reason` vocabulary, which is disjoint from the fallback vocabulary by construction. This is deliberately NOT an entry in `failed_attempts`: everything in that array is a step the resolver took and then moved past, and folding a turn-ending error in would make the array mean two things and re-open the 'which item was decisive' ambiguity the round-2 shape ruling closed.",
- "required": ["source_id", "resolved_model_id", "channel", "via_mapping", "reason", "stream_started"],
+ "description": "The attempt that stopped the turn with a non-fallback failure.",
+ "required": [
+ "source_id",
+ "resolved_model_id",
+ "channel",
+ "via_mapping",
+ "reason",
+ "stream_started"
+ ],
"additionalProperties": false,
"properties": {
- "source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
+ "source_id": {
+ "type": "string",
+ "pattern": "^src_[a-z0-9]{8,}$"
+ },
"resolved_model_id": { "type": "string" },
"channel": { "enum": ["native_cli", "hub"] },
"via_mapping": { "type": "boolean" },
"reason": {
- "enum": ["invalid_parameter", "protocol_error", "tool_incompatible", "stream_interrupted"],
- "description": "The non-fallback causes of spec §4.3's error taxonomy, kept in their own vocabulary so no reader has to know which values of the other enum are 'the ones that don't fall back'. `invalid_parameter` / `protocol_error` / `tool_incompatible` are the three the taxonomy names as surfacing to the caller. `stream_interrupted` is the fourth because §4.3 also rules that once streaming has started there is no transparent retry: the same underlying 5xx that would have been `server_error` and a fallback before the first token becomes terminal after it, so the phase — not the status code — decides, and the record must be able to say so."
+ "enum": [
+ "invalid_parameter",
+ "protocol_error",
+ "tool_incompatible",
+ "stream_interrupted"
+ ]
},
- "stream_started": {
- "type": "boolean",
- "description": "Whether any output had reached the caller when the error hit. Load-bearing rather than derivable: it is the fact §4.3's no-transparent-retry rule turns on, and the fact §4.5's copy obligation turns on (a half-written answer needs different words than a request that never started). Independent of `reason` for the first three — a tool call can arrive malformed mid-stream — and therefore pinned true only for `stream_interrupted`, where false would be a contradiction."
- }
+ "stream_started": { "type": "boolean" }
},
"allOf": [
{
- "if": { "properties": { "reason": { "const": "stream_interrupted" } }, "required": ["reason"] },
- "then": { "properties": { "stream_started": { "const": true } } }
+ "if": {
+ "properties": { "reason": { "const": "stream_interrupted" } },
+ "required": ["reason"]
+ },
+ "then": {
+ "required": ["stream_started"],
+ "properties": { "stream_started": { "const": true } }
+ }
}
]
},
+ "canceled_attempt": {
+ "type": ["object", "null"],
+ "description": "The in-flight attempt interrupted by explicit Stop/cancel. It carries identity but no failure reason because the source did not fail. null is honest when cancellation settled before any source attempt started.",
+ "required": ["source_id", "resolved_model_id", "channel", "via_mapping"],
+ "additionalProperties": false,
+ "properties": {
+ "source_id": {
+ "type": "string",
+ "pattern": "^src_[a-z0-9]{8,}$"
+ },
+ "resolved_model_id": { "type": "string" },
+ "channel": { "enum": ["native_cli", "hub"] },
+ "via_mapping": { "type": "boolean" }
+ }
+ },
"model_supply_state": {
"type": ["string", "null"],
"enum": ["waiting", "interrupted", null],
- "description": "v2 (07-29, review round 2): why nothing was tried, as the MODEL-SCOPED supply state of this (agent, requested_model) chain — the same value `supply_state` in agent-chain.schema.json would carry for this pair, under spec §4.5's single definition of the predicate: `interrupted` when the chain is empty or AT LEAST ONE blocker needs the user, `waiting` when every blocker is a cooldown and the turn would have succeeded later unattended. Corrected 07-29 (review round 3): round 2 wrote `interrupted` as 'every member needs the user', which is not the spec's predicate and left the mixed chain (one cooling, one revoked) fitting neither value — see agent-chain.schema.json → supply_state for the full note. Non-null IFF `outcome` is `no_candidate`; null otherwise, on the same pattern as `retry_at` in agent-chain.schema.json. Deliberately NOT the agent-level `supply_status` rollup from agent-supply.schema.json: that rollup answers for the backend's CURRENT model, and a turn can request a different one (see api.md → probe, same distinction). Same three-class taxonomy, evaluated at the (agent, model) grain — 「稍等即可」 and 「需处理」 are different answers and the turn record must not blur them."
+ "description": "Model-scoped cause for no_candidate. null for every other outcome."
}
},
"allOf": [
{
- "$comment": "One conditional per `outcome`, and each one pins EVERY optional slot — including the ones it forbids. Naming only the slots an outcome uses would leave the others writable, which is how a payload ends up with both a winner and a terminal error.",
- "if": { "properties": { "outcome": { "const": "served" } }, "required": ["outcome"] },
+ "if": {
+ "properties": { "outcome": { "const": "served" } },
+ "required": ["outcome"]
+ },
"then": {
+ "required": [
+ "served",
+ "terminal_error",
+ "canceled_attempt",
+ "model_supply_state"
+ ],
"properties": {
"served": { "type": "object" },
"terminal_error": { "type": "null" },
+ "canceled_attempt": { "type": "null" },
"model_supply_state": { "type": "null" }
}
}
},
{
- "if": { "properties": { "outcome": { "const": "exhausted" } }, "required": ["outcome"] },
+ "if": {
+ "properties": { "outcome": { "const": "exhausted" } },
+ "required": ["outcome"]
+ },
"then": {
+ "required": [
+ "served",
+ "terminal_error",
+ "canceled_attempt",
+ "model_supply_state"
+ ],
"properties": {
"served": { "type": "null" },
"terminal_error": { "type": "null" },
+ "canceled_attempt": { "type": "null" },
"failed_attempts": { "minItems": 1 },
"model_supply_state": { "type": "null" }
}
}
},
{
- "$comment": "v2 (07-29, review round 3): no `minItems` on `failed_attempts` here, deliberately. The FIRST candidate can hit a param error, in which case nothing fell back and the array is legitimately empty; a later one can hit it after real fallbacks, in which case it is not. Both are honest records of the same outcome, and requiring one shape would force the emitter to falsify the other.",
- "if": { "properties": { "outcome": { "const": "failed_terminal" } }, "required": ["outcome"] },
+ "$comment": "failed_attempts deliberately has no minItems: the first candidate can be terminal.",
+ "if": {
+ "properties": { "outcome": { "const": "failed_terminal" } },
+ "required": ["outcome"]
+ },
"then": {
+ "required": [
+ "served",
+ "terminal_error",
+ "canceled_attempt",
+ "model_supply_state"
+ ],
"properties": {
"served": { "type": "null" },
"terminal_error": { "type": "object" },
+ "canceled_attempt": { "type": "null" },
"model_supply_state": { "type": "null" }
}
}
},
{
- "if": { "properties": { "outcome": { "const": "no_candidate" } }, "required": ["outcome"] },
+ "if": {
+ "properties": { "outcome": { "const": "no_candidate" } },
+ "required": ["outcome"]
+ },
"then": {
+ "required": [
+ "served",
+ "terminal_error",
+ "canceled_attempt",
+ "model_supply_state"
+ ],
"properties": {
"served": { "type": "null" },
"terminal_error": { "type": "null" },
+ "canceled_attempt": { "type": "null" },
"failed_attempts": { "maxItems": 0 },
"model_supply_state": { "type": "string" }
}
}
+ },
+ {
+ "$comment": "canceled_attempt is deliberately nullable: Stop can settle before an upstream attempt starts. When an attempt was in flight, the producer fills this slot without a reason.",
+ "if": {
+ "properties": { "outcome": { "const": "canceled" } },
+ "required": ["outcome"]
+ },
+ "then": {
+ "required": [
+ "served",
+ "terminal_error",
+ "canceled_attempt",
+ "model_supply_state"
+ ],
+ "properties": {
+ "served": { "type": "null" },
+ "terminal_error": { "type": "null" },
+ "canceled_attempt": { "type": ["object", "null"] },
+ "model_supply_state": { "type": "null" }
+ }
+ }
}
],
"examples": [
{
- "contract_version": 2,
+ "contract_version": 3,
"turn_id": "turn_01k9x2m4",
"ts": "2026-07-29T06:32:11Z",
"agent": "claude",
@@ -175,10 +294,11 @@
"via_mapping": false
},
"terminal_error": null,
+ "canceled_attempt": null,
"model_supply_state": null
},
{
- "contract_version": 2,
+ "contract_version": 3,
"turn_id": "turn_01k9x33p",
"ts": "2026-07-29T06:41:02Z",
"agent": "opencode",
@@ -195,10 +315,11 @@
],
"served": null,
"terminal_error": null,
+ "canceled_attempt": null,
"model_supply_state": null
},
{
- "contract_version": 2,
+ "contract_version": 3,
"turn_id": "turn_01k9x3zq",
"ts": "2026-07-29T06:48:20Z",
"agent": "codex",
@@ -207,24 +328,17 @@
"failed_attempts": [],
"served": null,
"terminal_error": null,
+ "canceled_attempt": null,
"model_supply_state": "waiting"
},
{
- "contract_version": 2,
+ "contract_version": 3,
"turn_id": "turn_01k9x4b7",
"ts": "2026-07-29T07:02:44Z",
"agent": "claude",
"requested_model_id": "claude-opus-4-6",
"outcome": "failed_terminal",
- "failed_attempts": [
- {
- "source_id": "src_claudepro1",
- "resolved_model_id": "claude-opus-4-6",
- "channel": "native_cli",
- "via_mapping": false,
- "reason": "quota_exhausted"
- }
- ],
+ "failed_attempts": [],
"served": null,
"terminal_error": {
"source_id": "src_anthkey01",
@@ -234,6 +348,25 @@
"reason": "stream_interrupted",
"stream_started": true
},
+ "canceled_attempt": null,
+ "model_supply_state": null
+ },
+ {
+ "contract_version": 3,
+ "turn_id": "turn_01k9x5ca",
+ "ts": "2026-07-29T07:08:00Z",
+ "agent": "codex",
+ "requested_model_id": "gpt-5.3-codex",
+ "outcome": "canceled",
+ "failed_attempts": [],
+ "served": null,
+ "terminal_error": null,
+ "canceled_attempt": {
+ "source_id": "src_codexplus1",
+ "resolved_model_id": "gpt-5.3-codex",
+ "channel": "native_cli",
+ "via_mapping": false
+ },
"model_supply_state": null
}
]
diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.md
index 2a106cbff..7433d464d 100644
--- a/docs/plans/model-hub-implementation.md
+++ b/docs/plans/model-hub-implementation.md
@@ -8,7 +8,8 @@ Lane workflow standard: `~/vibe-remote-project/.agents/skills/pr-delivery-loop/S
> **Superseded for ordering (2026-07-29).** This document plans the **v1** build,
> which shipped dormant. Spec v2 moved the spend order from one global list to a
> per-backend ordered subset (`model-hub.md` §0, §4.2; contracts at
-> `contract_version: 2`). Anything below that assumes a global priority list is
+> `contract_version: 3`, with v2 retained as the historical ordering decision).
+> Anything below that assumes a global priority list is
> historical. This document is not being rewritten in place, only annotated where
> it would otherwise contradict the frozen contracts. **§3 and §8 are the
> exceptions: both are v2-current and binding** — §3 now carries the v2 lane plan
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index fda645d09..fa121b22b 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -5,7 +5,7 @@ Owner decisions incorporated through: 2026-07-29 (+08:00)
Design source: `../avibe-docs/design.pen`, frames `产品改造 V6 01 – V6 04` (desktop)
and `产品改造 V6 M01 – V6 M02` (mobile). The V4 frames document the shipped v1 and
are kept as history; V5A/V5B/V5C are rejected explorations.
-Contracts: `model-hub-contracts/` at `contract_version: 2`.
+Contracts: `model-hub-contracts/` at `contract_version: 3` (single batch freeze).
Discussion record: Show Page of session `sesb7r2qwb4z4` (v1 rounds 1–10) plus the
V6 redesign round (2026-07-28/29).
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 6054f4f4f..246a58045 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -45,11 +45,17 @@ scenarios:
layer: unit
test: tests/test_model_hub_resolution.py::test_quota_failure_cools_source_switches_and_emits_redacted_events
- id: MH-PRI-001
- name: Priority reorder takes effect on the next turn
- status: partial
+ name: Per-agent source-order mutations and follow restoration take effect immediately
+ status: covered
kind: ordering
- layer: unit_contract
- test: tests/test_model_hub_api.py::test_model_hub_rest_api_contract
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_mh_pri_001_order_mutations_change_the_next_turn
+ - id: MH-SEL-001
+ name: Unpinned Hub activation stays honest and resolves the turn model
+ status: covered
+ kind: selection
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py::test_unpinned_hub_projection_is_null_while_explicit_turn_resolves
- id: MH-MAP-001
name: Mapping applies to Claude Code only
status: partial
@@ -165,6 +171,7 @@ scenarios:
next_priority:
- MH-RES-001
- MH-PRI-001
+ - MH-SEL-001
- MH-MAP-001
- MH-OC-001
- MH-CHAN-001
diff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
index 42da2d15e..de97d11e8 100644
--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
@@ -12,6 +12,7 @@ import aiohttp
import pytest
from config.v2_config import (
+ ModelHubAgentSourcesConfig,
ModelHubAgentSupplyConfig,
ModelHubConfig,
ModelHubModelConfig,
@@ -125,14 +126,19 @@ def _source(
def _config(*sources: ModelHubSourceConfig) -> ModelHubConfig:
- return ModelHubConfig(
+ config = ModelHubConfig(
sources=list(sources),
- priority_order=[source.id for source in sources],
agents={
backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")
for backend in ("claude", "codex", "opencode")
},
)
+ for agent in config.agents.values():
+ agent.sources = ModelHubAgentSourcesConfig(
+ policy="custom",
+ order=[source.id for source in sources],
+ )
+ return config
def _service(
@@ -167,6 +173,83 @@ async def _post_turn(
return response.status, await response.read()
+def test_mh_pri_001_order_mutations_change_the_next_turn(tmp_path: Path) -> None:
+ """MH-PRI-001: custom edits and follow restoration affect the next turn."""
+
+ async def exercise() -> None:
+ alpha = _source("src_alpha001")
+ zulu = _source("src_zulu0001")
+ store = MemoryStore(_config(alpha, zulu))
+ adapter = AdapterBoundaryFake([])
+ service = _service(
+ tmp_path,
+ store,
+ adapter,
+ now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc),
+ )
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ initial = await router.resolve("claude", "model-live")
+ assert initial.source_id == alpha.id
+
+ custom = await service.set_agent_sources(
+ "claude",
+ {"policy": "custom", "order": [zulu.id, alpha.id]},
+ )
+ assert custom["sources"]["policy"] == "custom"
+ reordered = await router.resolve("claude", "model-live")
+ assert reordered.source_id == zulu.id
+
+ restored = await service.set_agent_sources(
+ "claude",
+ {"policy": "follow"},
+ )
+ assert restored["sources"]["policy"] == "follow"
+ assert restored["sources"]["order"] == [alpha.id, zulu.id]
+ recommended = await router.resolve("claude", "model-live")
+ assert recommended.source_id == alpha.id
+ finally:
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
+def test_unpinned_hub_projection_is_null_while_explicit_turn_resolves(
+ tmp_path: Path,
+) -> None:
+ """MH-SEL-001: no pinned selection is null while the request model runs."""
+
+ async def exercise() -> None:
+ source = _source("src_explicit1")
+ store = MemoryStore(_config(source))
+ adapter = AdapterBoundaryFake([])
+ service = _service(
+ tmp_path,
+ store,
+ adapter,
+ now=lambda: datetime(2026, 7, 25, tzinfo=timezone.utc),
+ )
+ projected = next(
+ agent for agent in service.list_agents() if agent["backend"] == "claude"
+ )
+ assert projected["selected_by_agent"] is None
+ assert projected["selected_model_id"] is None
+ assert projected["current"] is None
+ assert projected["supply_status"] is None
+
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ launch = await router.resolve("claude", "model-live")
+ assert launch.source_id == source.id
+ assert launch.target_model == "model-live"
+ finally:
+ await gateway.close()
+
+ asyncio.run(exercise())
+
+
@pytest.mark.parametrize(
("backend", "requested_model", "endpoint"),
[
@@ -347,9 +430,7 @@ def test_mh_res_live_003_started_stream_never_retries(tmp_path: Path) -> None:
def test_turn_gateway_tokens_are_bound_to_backend_origin(tmp_path: Path) -> None:
async def exercise() -> None:
- adapter = AdapterBoundaryFake(
- [AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}')]
- )
+ adapter = AdapterBoundaryFake([AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}')])
store = MemoryStore(_config(_source("src_primary")))
service = _service(
tmp_path,
@@ -377,9 +458,7 @@ def test_turn_gateway_tokens_are_bound_to_backend_origin(tmp_path: Path) -> None
def test_turn_gateway_preserves_only_protocol_capability_headers(tmp_path: Path) -> None:
async def exercise() -> None:
- adapter = AdapterBoundaryFake(
- [AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}')]
- )
+ adapter = AdapterBoundaryFake([AdapterResult(RawOutcomeKind.SUCCESS, status=200, body=b'{"ok":true}')])
store = MemoryStore(_config(_source("src_primary")))
service = _service(
tmp_path,
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 748da58e0..76630b501 100644
--- a/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_migration_scenarios.py
@@ -467,6 +467,7 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(
before = _tree_digest(native_home)
service, store, adapter = _service(tmp_path)
+ store.config.agents["codex"].sources.policy = "custom"
monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
client = app.test_client()
base_url = "http://127.0.0.1:15131"
@@ -497,7 +498,26 @@ def test_mh_mig_001_api_apply_keeps_native_tree_byte_identical(
assert adapter.revoked == []
assert before == _tree_digest(native_home)
by_id = {source.id: source for source in store.config.sources}
- assert all(by_id[source_id].billing == "metered" for source_id in store.config.priority_order)
+ imported_ids = set(by_id)
+ assert store.config.agents["claude"].sources.order == []
+ assert store.config.agents["codex"].sources.order == []
+ assert store.config.agents["opencode"].sources.order == []
+ assert set(store.config.effective_source_order("claude")) == imported_ids
+ assert store.config.effective_source_order("codex") == []
+ assert set(store.config.effective_source_order("opencode")) == imported_ids
+ codex_payload = next(
+ agent for agent in service.list_agents() if agent["backend"] == "codex"
+ )
+ assert codex_payload["sources"]["order"] == []
+ assert {
+ item["source_id"]
+ for item in codex_payload["sources"]["eligibility"]
+ if item["eligible"]
+ } == imported_ids
+ assert all(
+ by_id[source_id].billing == "metered"
+ for source_id in store.config.effective_source_order("opencode")
+ )
codex_source = next(
source for source in store.config.sources if source.vendor == "openai" and source.kind == "api_key"
)
@@ -952,7 +972,7 @@ def test_failed_batch_revokes_every_provisioned_credential(
assert error.value.code == "engine_down"
assert adapter.revoked == ["cred_migration_2", "cred_migration_1"]
assert store.config.sources == []
- assert store.config.priority_order == []
+ assert all(agent.sources.order == [] for agent in store.config.agents.values())
def test_failed_persist_sync_restores_config_and_revokes_credentials(
@@ -971,7 +991,7 @@ def test_failed_persist_sync_restores_config_and_revokes_credentials(
assert error.value.code == "engine_down"
assert adapter.revoked == ["cred_migration_2", "cred_migration_1"]
assert store.config.sources == []
- assert store.config.priority_order == []
+ assert all(agent.sources.order == [] for agent in store.config.agents.values())
def test_failed_revoke_survives_retry_with_same_source_id(
diff --git a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
index 87bc7afbd..e2a3f5657 100644
--- a/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_native_oauth_scenarios.py
@@ -74,7 +74,7 @@ def test_mh_oauth_native_001_claude_paste_code_happy_path(monkeypatch, tmp_path)
assert completed["state"] == "success"
assert len(sources) == 1
assert sources[0]["id"] == started["source_id"]
- assert sources[0]["state"] == {"status": "active", "retry_at": None, "detail_key": None}
+ assert sources[0]["state"] == {"status": "standby", "retry_at": None, "detail_key": None}
assert sources[0]["account_label"] is None
assert sources[0]["credential_ref"] is None
assert harness.store.config.sources[0].id == started["source_id"]
@@ -107,6 +107,8 @@ def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_p
"organizations": [{"title": "Example Org", "is_default": True}],
},
}
+ harness.store.config.agents["codex"].sources.policy = "custom"
+ harness.store.config.agents["codex"].sources.order = []
client, headers = _client(monkeypatch, harness.service)
started = client.post(
@@ -129,17 +131,40 @@ def test_mh_oauth_native_002_codex_device_code_self_completes(monkeypatch, tmp_p
assert awaiting["presentation"]["expects"] == "none"
harness.agent_auth.complete(started["flow_id"])
- completed = client.get(
+ completion = client.get(
f"/api/models/oauth/status/{started['flow_id']}",
base_url=BASE_URL,
- ).get_json()["flow"]
+ ).get_json()
+ assert set(completion) == {
+ "ok",
+ "contract_version",
+ "flow",
+ "source",
+ "adopted_by",
+ }
+ completed = completion["flow"]
source = client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"][0]
+ codex = next(
+ agent
+ for agent in client.get("/api/models/agents", base_url=BASE_URL).get_json()["agents"]
+ if agent["backend"] == "codex"
+ )
assert completed["state"] == "success"
assert harness.agent_auth.submissions == []
- assert source["state"]["status"] == "active"
+ assert source["state"]["status"] == "standby"
assert source["account_label"] == "[email protected] \u00b7 plus \u00b7 Example Org"
assert source["credential_ref"] is None
+ assert completion["adopted_by"] == []
+ assert codex["sources"]["policy"] == "custom"
+ assert codex["sources"]["order"] == []
+ assert codex["sources"]["eligibility"] == [
+ {
+ "source_id": source["id"],
+ "eligible": True,
+ "reason_key": None,
+ }
+ ]
def test_mh_oauth_native_003_cancel_and_timeout_terminate_cleanly(monkeypatch, tmp_path):
@@ -175,16 +200,13 @@ def test_mh_oauth_native_003_cancel_and_timeout_terminate_cleanly(monkeypatch, t
f"/api/models/oauth/status/{signed_out['flow_id']}",
base_url=BASE_URL,
)
- assert signed_out_response.get_json()["flow"]["state"] == "failed"
- assert (
- signed_out_response.get_json()["flow"]["error_key"]
- == "settings.models.source.oauthSignedOut"
- )
+ assert signed_out_response.get_json()["flow"]["state"] == "success"
+ assert signed_out_response.get_json()["flow"]["error_key"] is None
source = client.get("/api/models/sources", base_url=BASE_URL).get_json()["sources"][0]
assert source["state"] == {
- "status": "error",
+ "status": "needs_action",
"retry_at": None,
- "detail_key": "settings.models.source.oauthSignedOut",
+ "detail_key": "models.source.needs_action.oauth_expired",
}
claude = next(
agent
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 930482eec..407ac7e18 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -24,7 +24,12 @@ from core.handlers.model_hub.errors import ModelDiscoveryError
from core.handlers.model_hub.events import BoundedEventLog, ResolutionEvent
from core.handlers.model_hub.oauth import NativeOAuthSourceStatus, OAuthFlowRegistry
from core.handlers.model_hub.revocations import CredentialRevocationJournal
-from core.handlers.model_hub.service import ModelHubError, ModelHubService, create_default_service
+from core.handlers.model_hub.service import (
+ CONTRACT_VERSION,
+ ModelHubError,
+ ModelHubService,
+ create_default_service,
+)
from vibe.model_hub_client import ModelHubRemoteService, _decode
from tests.ui_server_test_helpers import csrf_headers
from vibe import ui_server
@@ -199,9 +204,13 @@ def _service(tmp_path):
return service, store, adapter
+async def _create_source(service: ModelHubService, payload: dict) -> dict:
+ return (await service.create_source(payload))["source"]
+
+
def _assert_envelope(payload: dict, *, ok: bool = True):
assert payload["ok"] is ok
- assert payload["contract_version"] == 1
+ assert payload["contract_version"] == CONTRACT_VERSION
def test_default_service_uses_real_engine_adapter(monkeypatch, tmp_path):
@@ -332,12 +341,13 @@ def test_discovery_probe_failure_is_not_reported_as_engine_down(tmp_path):
with pytest.raises(ModelHubError) as error:
asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "openai",
"key": "sk-test-invalid-but-syntactically-valid",
- }
+ },
)
)
@@ -369,6 +379,50 @@ def test_agents_endpoint_projects_builtin_models_and_standard_vendors(tmp_path):
assert agents["opencode"]["standard_vendors"] == sorted(STANDARD_OPENCODE_VENDOR_IDS)
+def test_agents_endpoint_projects_each_enabled_named_agent_live(tmp_path):
+ service, store, _adapter = _service(tmp_path)
+ store.requested_model = lambda backend: {
+ "claude": "claude-sonnet-4-6",
+ "codex": "gpt-5.3-codex",
+ }.get(backend)
+ service.named_agents_override = lambda backend: {
+ "claude": [("pm", None), ("reviewer", "claude-opus-4-6")],
+ "codex": [("codex", None)],
+ "opencode": [],
+ }[backend]
+
+ agents = {agent["backend"]: agent for agent in service.list_agents()}
+
+ assert agents["claude"]["named_agents"] == [
+ {
+ "name": "pm",
+ "effective_model_id": "claude-sonnet-4-6",
+ "supply_status": "interrupted",
+ },
+ {
+ "name": "reviewer",
+ "effective_model_id": "claude-opus-4-6",
+ "supply_status": "interrupted",
+ },
+ ]
+ assert agents["codex"]["named_agents"] == [
+ {
+ "name": "codex",
+ "effective_model_id": "gpt-5.3-codex",
+ "supply_status": "interrupted",
+ }
+ ]
+ assert agents["opencode"]["named_agents"] == []
+
+ store.config.agents["claude"].mode = "direct"
+ direct = service.get_agent_sources("claude")
+ assert direct["named_agents"][0] == {
+ "name": "pm",
+ "effective_model_id": "claude-sonnet-4-6",
+ "supply_status": None,
+ }
+
+
def test_ui_model_hub_default_is_controller_rpc_client(monkeypatch):
monkeypatch.setattr(ui_server, "_MODEL_HUB_SERVICE", None)
@@ -406,9 +460,9 @@ def test_ui_model_hub_rpc_preserves_controller_error_contract():
("PATCH", "/api/models/sources/src_test0001"),
("DELETE", "/api/models/sources/src_test0001"),
("POST", "/api/models/sources/src_test0001/test"),
- ("GET", "/api/models/priority"),
- ("PUT", "/api/models/priority"),
("GET", "/api/models/agents"),
+ ("GET", "/api/models/agents/claude/sources"),
+ ("PUT", "/api/models/agents/claude/sources"),
("PATCH", "/api/models/agents/claude/mode"),
("PUT", "/api/models/agents/claude/mappings"),
("PUT", "/api/models/agents/opencode/menu"),
@@ -462,7 +516,7 @@ def test_disabled_model_hub_rest_surface_returns_feature_disabled_without_runtim
assert response.status_code == 404
assert response.get_json() == {
"ok": False,
- "contract_version": 1,
+ "contract_version": CONTRACT_VERSION,
"error": "feature_disabled",
}
assert remote_service_calls == []
@@ -552,6 +606,12 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
assert response.status_code == 201
body = response.get_json()
_assert_envelope(body)
+ assert set(body) == {"ok", "contract_version", "source", "adopted_by"}
+ assert {item["backend"] for item in body["adopted_by"]} == {
+ "claude",
+ "codex",
+ "opencode",
+ }
source = body["source"]
_assert_valid("source.schema.json", source)
source_id = source["id"]
@@ -560,24 +620,41 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
assert adapter.secret_lengths[0] == len(fake_key)
response = client.put(
- "/api/models/priority",
- json={"order": []},
+ "/api/models/agents/claude/sources",
+ json={"policy": "custom", "order": ["src_missing01"]},
headers=headers,
base_url=base_url,
)
error = response.get_json()
_assert_envelope(error, ok=False)
- assert error["error"] == "invalid_priority_order"
+ assert error["error"] == "invalid_source_order"
response = client.put(
- "/api/models/priority",
- json={"order": [source_id]},
+ "/api/models/agents/claude/sources",
+ json={"policy": "custom", "order": []},
headers=headers,
base_url=base_url,
)
- priority = response.get_json()
- _assert_envelope(priority)
- _assert_valid("priority.schema.json", {"contract_version": 1, "order": priority["order"]})
+ custom = response.get_json()
+ _assert_envelope(custom)
+ assert custom["agent"]["sources"]["policy"] == "custom"
+ assert custom["agent"]["sources"]["order"] == []
+
+ codex_sources = client.get(
+ "/api/models/agents/codex/sources",
+ base_url=base_url,
+ ).get_json()["agent"]["sources"]
+ assert codex_sources["policy"] == "follow"
+ assert codex_sources["order"] == [source_id]
+
+ restored = client.put(
+ "/api/models/agents/claude/sources",
+ json={"policy": "follow"},
+ headers=headers,
+ base_url=base_url,
+ ).get_json()
+ assert restored["agent"]["sources"]["policy"] == "follow"
+ assert restored["agent"]["sources"]["order"] == [source_id]
response = client.patch(
f"/api/models/sources/{source_id}",
@@ -607,11 +684,7 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
response = client.put(
"/api/models/agents/claude/mappings",
- json={
- "mappings": [
- {"builtin_id": "claude-native", "target_model_id": "custom-model", "enabled": True}
- ]
- },
+ json={"mappings": [{"builtin_id": "claude-native", "target_model_id": "custom-model", "enabled": True}]},
headers=headers,
base_url=base_url,
)
@@ -636,6 +709,15 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
agents = client.get("/api/models/agents", base_url=base_url).get_json()["agents"]
assert len(agents) == 3
for agent in agents:
+ assert {
+ "selected_by_agent",
+ "selected_model_id",
+ "current",
+ "sources",
+ "supply_status",
+ "model_supply",
+ "named_agents",
+ } <= set(agent)
_assert_valid("agent-supply.schema.json", agent)
event_example = _schema("resolution-event.schema.json")["examples"][0]
@@ -665,7 +747,7 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
)
- assert asyncio.run(restarted.oauth_status(flow["flow_id"]))["channel"] == "native_cli"
+ assert asyncio.run(restarted.oauth_status(flow["flow_id"]))["flow"]["channel"] == "native_cli"
flow = client.post(
"/api/models/oauth/submit",
@@ -677,7 +759,6 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
assert adapter.secret_lengths[-1] == len("secret-auth-code")
assert "secret-auth-code" not in (tmp_path / "events.json").read_text(encoding="utf-8")
-
response = client.post(
"/api/models/oauth/cancel",
json={"flow_id": flow["flow_id"]},
@@ -733,7 +814,14 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
base_url=base_url,
)
assert response.status_code == 201
- consented_source = response.get_json()["source"]
+ oauth_creation = response.get_json()
+ assert set(oauth_creation) == {
+ "ok",
+ "contract_version",
+ "source",
+ "adopted_by",
+ }
+ consented_source = oauth_creation["source"]
_assert_valid("source.schema.json", consented_source)
assert consented_source["experimental_consent_at"] == "2026-07-23T03:00:00+00:00"
completed_binding = service.oauth_flows.binding(hub_flow["flow_id"])
@@ -799,7 +887,7 @@ def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
("path", "method", "error"),
[
("/api/models/sources/src_test0001", "patch", "discovery_failed"),
- ("/api/models/priority", "put", "invalid_priority_order"),
+ ("/api/models/agents/claude/sources", "put", "invalid_source_order"),
("/api/models/agents/claude/mode", "patch", "mode_switch_blocked"),
("/api/models/agents/claude/mappings", "put", "mapping_target_unavailable"),
("/api/models/agents/opencode/menu", "put", "mapping_target_unavailable"),
@@ -833,11 +921,9 @@ def test_model_hub_routes_reject_non_object_json_with_error_envelope(
def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):
service, store, adapter = _service(tmp_path)
- flow = asyncio.run(
- service.oauth_start(
- {"vendor": "anthropic", "channel": "hub", "experimental_consent": True}
- )
- )
+ flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "hub", "experimental_consent": True}))[
+ "flow"
+ ]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -849,7 +935,8 @@ def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):
with pytest.raises(ModelHubError) as exc_info:
asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "subscription",
"vendor": "anthropic",
@@ -857,7 +944,7 @@ def test_failed_hub_oauth_source_creation_revokes_credential(tmp_path):
"supply_channel": "hub",
"oauth_flow_ref": flow["flow_id"],
"experimental_consent": True,
- }
+ },
)
)
@@ -893,9 +980,9 @@ def test_concurrent_completed_hub_oauth_flow_has_single_credential_owner(tmp_pat
oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
)
- flow = await service.oauth_start(
- {"vendor": "anthropic", "channel": "hub", "experimental_consent": True}
- )
+ flow = (await service.oauth_start({"vendor": "anthropic", "channel": "hub", "experimental_consent": True}))[
+ "flow"
+ ]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -913,9 +1000,9 @@ def test_concurrent_completed_hub_oauth_flow_has_single_credential_owner(tmp_pat
}
adapter.block_next_sync = True
- first = asyncio.create_task(service.create_source(payload))
+ first = asyncio.create_task(_create_source(service, payload))
await adapter.sync_started.wait()
- second = asyncio.create_task(service.create_source(payload))
+ second = asyncio.create_task(_create_source(service, payload))
await asyncio.sleep(0)
adapter.release_sync.set()
return await asyncio.gather(first, second, return_exceptions=True), store, adapter
@@ -934,7 +1021,7 @@ def test_concurrent_completed_hub_oauth_flow_has_single_credential_owner(tmp_pat
def test_failed_oauth_cancel_keeps_flow_retryable(tmp_path):
async def run_cancel_retry():
service, _, adapter = _service(tmp_path)
- flow = await service.oauth_start({"vendor": "anthropic", "channel": "native_cli"})
+ flow = (await service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))["flow"]
adapter.fail_cancel = True
with pytest.raises(ModelHubError) as exc_info:
await service.oauth_cancel(flow["flow_id"])
@@ -953,7 +1040,7 @@ def test_failed_oauth_cancel_keeps_flow_retryable(tmp_path):
def test_oauth_completion_requires_the_persisted_pending_source_identity(tmp_path):
service, store, adapter = _service(tmp_path)
- flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))
+ flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))["flow"]
binding = service.oauth_flows.binding(flow["flow_id"])
assert binding is not None
@@ -1014,7 +1101,7 @@ def test_native_oauth_cannot_record_experimental_hub_consent(tmp_path):
def test_expired_oauth_flow_is_rejected_before_submit(tmp_path):
service, _, adapter = _service(tmp_path)
- flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))
+ flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))["flow"]
adapter.flows[flow["flow_id"]] = OAuthFlowState(
**{
**adapter.flows[flow["flow_id"]].__dict__,
@@ -1057,19 +1144,18 @@ def test_native_source_configuration_does_not_require_l1_engine(tmp_path):
now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
)
- flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))
- native.flows[flow["flow_id"]] = OAuthFlowState(
- **{**native.flows[flow["flow_id"]].__dict__, "state": "success"}
- )
+ flow = asyncio.run(service.oauth_start({"vendor": "anthropic", "channel": "native_cli"}))["flow"]
+ native.flows[flow["flow_id"]] = OAuthFlowState(**{**native.flows[flow["flow_id"]].__dict__, "state": "success"})
source = asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "subscription",
"vendor": "anthropic",
"display_name": "Claude native",
"supply_channel": "native_cli",
"oauth_flow_ref": flow["flow_id"],
- }
+ },
)
)
@@ -1077,10 +1163,8 @@ def test_native_source_configuration_does_not_require_l1_engine(tmp_path):
assert source["supply_channel"] == "native_cli"
assert any(model["id"] == "claude-opus-4-6" for model in source["models"])
assert {model["provenance"] for model in source["models"]} == {"discovered"}
- assert store.config.priority_order == [source["id"]]
- resolved = asyncio.run(
- service.resolve(backend="claude", model_id="claude-opus-4-6", request={})
- )
+ assert store.config.effective_source_order("claude") == [source["id"]]
+ resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
assert resolved.source_id == source["id"]
assert resolved.supply_channel == "native_cli"
assert native.synced == []
@@ -1128,21 +1212,23 @@ def test_concurrent_source_creates_preserve_both_aggregate_updates(tmp_path):
revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
)
created = await asyncio.gather(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "anthropic",
"display_name": "Concurrent A",
"key": "sk-test-concurrent-a",
- }
+ },
),
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "anthropic",
"display_name": "Concurrent B",
"key": "sk-test-concurrent-b",
- }
+ },
),
)
return created, store.config
@@ -1151,7 +1237,59 @@ def test_concurrent_source_creates_preserve_both_aggregate_updates(tmp_path):
assert {source["display_name"] for source in created} == {"Concurrent A", "Concurrent B"}
assert {source.display_name for source in config.sources} == {"Concurrent A", "Concurrent B"}
- assert set(config.priority_order) == {source.id for source in config.sources}
+ assert all(
+ set(config.effective_source_order(backend)) == {source.id for source in config.sources}
+ for backend in ("claude", "codex", "opencode")
+ )
+
+
+def test_follow_auto_adopts_new_sources_while_custom_stays_frozen(tmp_path):
+ service, store, _ = _service(tmp_path)
+ first = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "First",
+ "key": "sk-test-first-source",
+ }
+ )
+ )
+ first_id = first["source"]["id"]
+ assert {item["backend"] for item in first["adopted_by"]} == {
+ "claude",
+ "codex",
+ "opencode",
+ }
+
+ asyncio.run(
+ service.set_agent_sources(
+ "claude",
+ {"policy": "custom", "order": [first_id]},
+ )
+ )
+ second = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "openai",
+ "display_name": "Second",
+ "key": "sk-test-second-source",
+ }
+ )
+ )
+ second_id = second["source"]["id"]
+
+ assert store.config.agents["claude"].sources.order == [first_id]
+ assert "claude" not in {item["backend"] for item in second["adopted_by"]}
+ assert set(store.config.effective_source_order("codex")) == {
+ first_id,
+ second_id,
+ }
+
+ restored = asyncio.run(service.set_agent_sources("claude", {"policy": "follow"}))
+ assert restored["sources"]["policy"] == "follow"
+ assert restored["sources"]["order"] == store.config.recommended_source_order("claude")
@pytest.mark.parametrize(
@@ -1170,14 +1308,15 @@ def test_source_base_url_rejects_embedded_credentials(tmp_path, base_url):
with pytest.raises(ModelHubError) as exc_info:
asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "custom",
"display_name": "Unsafe relay",
"base_url": base_url,
"key": "sk-test-transient-only",
- }
+ },
)
)
@@ -1189,14 +1328,15 @@ def test_source_base_url_rejects_embedded_credentials(tmp_path, base_url):
def test_source_patch_rejects_credential_bearing_base_url(tmp_path):
service, store, _ = _service(tmp_path)
source = asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "custom",
"display_name": "Safe relay",
"base_url": "https://relay.example/v1?api-version=2026-07-23",
"key": "sk-test-transient-only",
- }
+ },
)
)
@@ -1218,13 +1358,14 @@ def test_source_display_names_reject_credential_material(tmp_path):
with pytest.raises(ModelHubError) as exc_info:
asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "anthropic",
"display_name": pasted_key,
"key": "sk-test-transient-only",
- }
+ },
)
)
assert exc_info.value.code == "discovery_failed"
@@ -1232,13 +1373,14 @@ def test_source_display_names_reject_credential_material(tmp_path):
assert adapter.secret_lengths == []
source = asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "anthropic",
"display_name": "Safe source",
"key": "sk-test-transient-only",
- }
+ },
)
)
with pytest.raises(ModelHubError) as exc_info:
@@ -1253,13 +1395,14 @@ def test_api_key_is_trimmed_once_and_empty_normalized_values_are_rejected(tmp_pa
normalized = "sk-test-trim-me"
source = asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "anthropic",
"display_name": "Trimmed source",
"key": f" \n{normalized}\t ",
- }
+ },
)
)
@@ -1268,13 +1411,14 @@ def test_api_key_is_trimmed_once_and_empty_normalized_values_are_rejected(tmp_pa
with pytest.raises(ModelHubError) as exc_info:
asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "anthropic",
"display_name": "Empty source",
"key": " \n\t ",
- }
+ },
)
)
@@ -1316,20 +1460,21 @@ def test_source_vendor_and_custom_model_ids_reject_credential_material(tmp_path)
},
):
with pytest.raises(ModelHubError) as exc_info:
- asyncio.run(service.create_source(payload))
+ asyncio.run(_create_source(service, payload))
assert exc_info.value.code == "discovery_failed"
assert store.config.sources == []
assert adapter.secret_lengths == []
source = asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "anthropic",
"display_name": "Safe source",
"key": "sk-test-transient-only",
- }
+ },
)
)
with pytest.raises(ModelHubError) as exc_info:
@@ -1342,14 +1487,15 @@ def test_source_vendor_and_custom_model_ids_reject_credential_material(tmp_path)
def test_source_patch_rejects_credential_bearing_discovered_model_id(tmp_path):
service, store, adapter = _service(tmp_path)
source = asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "custom",
"display_name": "Safe relay",
"base_url": "https://relay.example/v1",
"key": "sk-test-transient-only",
- }
+ },
)
)
@@ -1373,13 +1519,14 @@ def test_source_patch_rejects_credential_bearing_discovered_model_id(tmp_path):
def test_metadata_only_source_patch_does_not_require_engine_sync(tmp_path):
service, store, adapter = _service(tmp_path)
source = asyncio.run(
- service.create_source(
+ _create_source(
+ service,
{
"kind": "api_key",
"vendor": "anthropic",
"display_name": "Before rename",
"key": "sk-test-transient-only",
- }
+ },
)
)
sync_count = len(adapter.synced)
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index fc660bcf9..f6e7c3fc2 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -1,14 +1,17 @@
from __future__ import annotations
+import copy
import json
from dataclasses import fields
from pathlib import Path
import pytest
-from jsonschema import Draft7Validator, FormatChecker
+from jsonschema import Draft7Validator, FormatChecker, ValidationError
from config.v2_config import (
MODEL_HUB_ENABLED_ENV,
+ MODEL_HUB_LEGACY_CREATED_AT,
+ ModelHubAgentSourcesConfig,
ModelHubAgentSupplyConfig,
ModelHubConfig,
ModelHubMappingConfig,
@@ -42,14 +45,120 @@ def _canonical(payload: dict) -> bytes:
return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
+def _json_pointer(document: dict, pointer: str):
+ value = document
+ for token in pointer.lstrip("/").split("/"):
+ token = token.replace("~1", "/").replace("~0", "~")
+ value = value[int(token)] if isinstance(value, list) else value[token]
+ return value
+
+
+def _vocabulary(schema: dict, paths: list[str], *, exclude=()) -> set:
+ values = set()
+ for pointer in paths:
+ node = _json_pointer(schema, pointer)
+ values.update(node["enum"] if "enum" in node else [node["const"]])
+ return values - set(exclude)
+
+
+def _validate_mirror_entry(entry: dict, schemas: dict[str, dict]) -> None:
+ rule = entry["rule"]
+ if rule == "none":
+ assert entry["reason"]
+ return
+ if rule == "equality":
+ normalized = []
+ for item in entry["sets"]:
+ actual = _vocabulary(
+ schemas[item["schema"]],
+ item["paths"],
+ exclude=item.get("exclude", ()),
+ )
+ extras = set(item.get("extras", ()))
+ normalized.append(actual - extras)
+ assert actual == (actual - extras) | extras
+ assert all(values == normalized[0] for values in normalized[1:])
+ return
+ if rule == "mapping":
+ home = _vocabulary(
+ schemas[entry["home"]["schema"]],
+ [entry["home"]["path"]],
+ )
+ target = _vocabulary(
+ schemas[entry["target"]["schema"]],
+ [entry["target"]["path"]],
+ )
+ assert home == set(entry["mapping"])
+ assert target == set(entry["mapping"].values())
+ return
+ if rule == "partition":
+ home = _vocabulary(
+ schemas[entry["home"]["schema"]],
+ [entry["home"]["path"]],
+ )
+ member = _vocabulary(
+ schemas[entry["member"]["schema"]],
+ [entry["member"]["path"]],
+ )
+ exclusions = set(entry["exclusions"])
+ for item in entry["exclusion_sets"]:
+ exclusions |= _vocabulary(schemas[item["schema"]], [item["path"]])
+ assert not (member & exclusions)
+ assert home == member | exclusions
+ return
+ if rule == "bijection":
+ home = _vocabulary(
+ schemas[entry["home"]["schema"]],
+ [entry["home"]["path"]],
+ )
+ target = set()
+ for item in entry["target_sets"]:
+ target |= _vocabulary(schemas[item["schema"]], item["paths"])
+ assert set(entry["pairs"]) <= home
+ assert len(set(entry["pairs"].values())) == len(entry["pairs"])
+ assert target == set(entry["pairs"].values())
+ return
+ if rule == "projection":
+ home = _vocabulary(
+ schemas[entry["home"]["schema"]],
+ [entry["home"]["path"]],
+ exclude=entry["home"].get("exclude", ()),
+ )
+ for item in entry["targets"]:
+ target = _vocabulary(
+ schemas[item["schema"]],
+ [item["path"]],
+ exclude=item.get("exclude", ()),
+ )
+ assert target == home - set(item["drop_from_home"])
+ return
+ raise AssertionError(f"unknown mirror rule: {rule}")
+
+
+def _mirror_schemas(registry: dict) -> dict[str, dict]:
+ names = {
+ value["schema"]
+ for entry in registry["entries"]
+ for key in ("sets", "target_sets", "targets", "exclusion_sets")
+ for value in entry.get(key, [])
+ }
+ for entry in registry["entries"]:
+ for key in ("home", "target", "member"):
+ if key in entry:
+ names.add(entry[key]["schema"])
+ return {name: _schema(name) for name in names}
+
+
def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():
- assert Path("core/handlers/model_hub/adapter.py").read_bytes() == (
- CONTRACTS / "adapter-interface.py"
- ).read_bytes()
+ assert Path("core/handlers/model_hub/adapter.py").read_bytes() == (CONTRACTS / "adapter-interface.py").read_bytes()
for example in _schema("source.schema.json")["examples"]:
serialized = ModelHubSourceConfig.from_payload(example).to_payload()
- assert _canonical(serialized) == _canonical(example)
+ expected = json.loads(json.dumps(example))
+ expected.setdefault("created_at", MODEL_HUB_LEGACY_CREATED_AT)
+ if "usage" in expected:
+ expected["usage"].setdefault("projected_exhaust_at", None)
+ assert _canonical(serialized) == _canonical(expected)
_assert_valid("source.schema.json", serialized)
for example in _schema("agent-supply.schema.json")["examples"]:
@@ -63,6 +172,10 @@ def test_frozen_source_and_agent_examples_round_trip_byte_faithfully():
"builtin_models": example.get("builtin_models"),
"standard_vendors": example.get("standard_vendors"),
}
+ if "sources" not in example:
+ serialized.pop("sources")
+ else:
+ serialized["sources"]["eligibility"] = example["sources"].get("eligibility")
assert _canonical(serialized) == _canonical(example)
_assert_valid("agent-supply.schema.json", serialized)
@@ -76,6 +189,114 @@ def test_every_frozen_schema_example_is_valid_and_json_round_trips():
assert _canonical(json.loads(_canonical(example))) == _canonical(example)
+def test_v3_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"] == 3
+ assert [entry["id"] for entry in registry["entries"]] == [
+ "M1",
+ "M2",
+ "M3",
+ "M4",
+ "M5",
+ "M6",
+ "M7",
+ "N1",
+ ]
+ for entry in registry["entries"]:
+ _validate_mirror_entry(entry, schemas)
+
+
+def test_v3_mirror_registry_mutation_probes_detect_every_comparable_drift():
+ registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))
+ schemas = _mirror_schemas(registry)
+
+ for entry in registry["entries"]:
+ if entry["rule"] == "none":
+ continue
+ mutated = copy.deepcopy(schemas)
+ if entry["rule"] == "bijection":
+ location = entry["target_sets"][0]
+ pointer = location["paths"][0]
+ elif entry["rule"] == "equality":
+ location = entry["sets"][0]
+ pointer = location["paths"][0]
+ else:
+ location = entry["home"]
+ pointer = location["path"]
+ node = _json_pointer(mutated[location["schema"]], pointer)
+ assert "enum" in node, entry["id"]
+ node["enum"].append(f"mutation_{entry['id'].lower()}")
+
+ with pytest.raises(AssertionError):
+ _validate_mirror_entry(entry, mutated)
+
+
+def test_v3_shape_amendments_reject_the_false_states_they_replace():
+ supply_schema = _schema("agent-supply.schema.json")
+ supply_validator = Draft7Validator(supply_schema)
+ base_supply = {
+ "backend": "claude",
+ "mode": "hub",
+ "menu_kind": "fixed",
+ "selected_by_agent": None,
+ "selected_model_id": None,
+ "current": None,
+ "sources": {"policy": "follow", "order": [], "eligibility": []},
+ "supply_status": None,
+ "mappings": [],
+ "menu": None,
+ "model_supply": [],
+ "named_agents": [],
+ "builtin_models": [],
+ "standard_vendors": None,
+ }
+ supply_validator.validate(base_supply)
+
+ invented = {
+ **base_supply,
+ "selected_model_id": None,
+ "current": {
+ "model_id": "claude-opus-4-6",
+ "source_id": "src_anthkey01",
+ "channel": "hub",
+ },
+ }
+ with pytest.raises(ValidationError):
+ supply_validator.validate(invented)
+
+ invalid_reason = copy.deepcopy(base_supply)
+ invalid_reason["sources"]["eligibility"] = [
+ {
+ "source_id": "src_anthkey01",
+ "eligible": False,
+ "reason_key": "models.eligibility.subscription_wrong_clint",
+ }
+ ]
+ with pytest.raises(ValidationError):
+ supply_validator.validate(invalid_reason)
+
+ event_validator = Draft7Validator(_schema("resolution-event.schema.json"))
+ source_wide = _schema("resolution-event.schema.json")["examples"][1]
+ event_validator.validate(source_wide)
+ invalid_event = {**source_wide, "agent": "system", "kind": "supply_interrupted"}
+ with pytest.raises(ValidationError):
+ event_validator.validate(invalid_event)
+
+ probe = copy.deepcopy(_schema("probe-result.schema.json")["examples"][0])
+ probe["source_id"] = "direct"
+ with pytest.raises(ValidationError):
+ Draft7Validator(_schema("probe-result.schema.json")).validate(probe)
+
+ canceled = _schema("turn-provenance.schema.json")["examples"][-1]
+ Draft7Validator(_schema("turn-provenance.schema.json")).validate(canceled)
+ invented_failure = copy.deepcopy(canceled)
+ invented_failure["canceled_attempt"]["reason"] = "server_error"
+ with pytest.raises(ValidationError):
+ Draft7Validator(_schema("turn-provenance.schema.json")).validate(invented_failure)
+
+
def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmp_path):
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
source_example = {
@@ -86,7 +307,6 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm
}
hub_payload = {
"sources": [source_example],
- "priority_order": [source_example["id"]],
"agents": {
backend: ModelHubAgentSupplyConfig.default(backend, mode="hub").to_payload()
for backend in ("claude", "codex", "opencode")
@@ -106,6 +326,7 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm
source_usage_fields = {field.name for field in fields(ModelHubSourceUsageConfig)}
source_model_fields = {field.name for field in fields(ModelHubModelConfig)}
agent_fields = {field.name for field in fields(ModelHubAgentSupplyConfig)}
+ agent_sources_fields = {field.name for field in fields(ModelHubAgentSourcesConfig)}
mapping_fields = {field.name for field in fields(ModelHubMappingConfig)}
menu_fields = {field.name for field in fields(ModelHubMenuConfig)}
@@ -121,13 +342,12 @@ def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tm
assert source_usage_fields == set(serialized_source["usage"]), label
assert source_model_fields == set(serialized_source["models"][0]), label
assert agent_fields == set(serialized_hub["agents"]["claude"]), label
- assert mapping_fields == set(
- ModelHubMappingConfig("builtin", "target", True).to_payload()
- ), label
+ assert agent_sources_fields == set(serialized_hub["agents"]["claude"]["sources"]), label
+ assert mapping_fields == set(ModelHubMappingConfig("builtin", "target", True).to_payload()), label
assert menu_fields == set(serialized_hub["agents"]["opencode"]["menu"]), label
stale_hub_payload = json.loads(json.dumps(api_payload["model_hub"]))
- stale_hub_payload["priority_order"] = []
+ stale_hub_payload["priority_order"] = ["legacy-is-dropped"]
updated = api.save_config({"show_duration": True, "model_hub": stale_hub_payload})
assert updated.model_hub.to_payload() == loaded.model_hub.to_payload()
assert api.config_to_payload(updated)["model_hub"] == api_payload["model_hub"]
@@ -157,7 +377,6 @@ def test_hub_subscription_requires_server_recorded_consent():
source = {**source, "supply_channel": "hub"}
payload = {
"sources": [source],
- "priority_order": [source["id"]],
"agents": {},
"subscription_hub_experimental": True,
}
@@ -170,6 +389,182 @@ def test_hub_subscription_requires_server_recorded_consent():
raise AssertionError("hub-held subscription loaded without recorded consent")
+def test_legacy_global_priority_key_is_dropped_without_validation():
+ payload = ModelHubConfig().to_payload()
+ payload["priority_order"] = {"legacy": "shape-does-not-matter"}
+
+ loaded = ModelHubConfig.from_payload(payload)
+
+ assert "priority_order" not in loaded.to_payload()
+
+
+def test_agent_source_orders_validate_existence_eligibility_and_uniqueness():
+ source = {
+ **_schema("source.schema.json")["examples"][0],
+ "created_at": "2026-07-29T01:00:00Z",
+ }
+ base = ModelHubConfig().to_payload()
+ base["sources"] = [source]
+ base["agents"]["claude"]["sources"] = {
+ "policy": "custom",
+ "order": [source["id"]],
+ }
+
+ ModelHubConfig.from_payload(base)
+
+ for invalid_order in (
+ [source["id"], source["id"]],
+ ["src_missing001"],
+ ):
+ invalid = json.loads(json.dumps(base))
+ invalid["agents"]["claude"]["sources"]["order"] = invalid_order
+ with pytest.raises(ValueError):
+ ModelHubConfig.from_payload(invalid)
+
+ ineligible = json.loads(json.dumps(base))
+ ineligible["agents"]["codex"]["sources"] = {
+ "policy": "custom",
+ "order": [source["id"]],
+ }
+ with pytest.raises(ValueError):
+ ModelHubConfig.from_payload(ineligible)
+
+
+def _ordering_source(
+ source_id: str,
+ *,
+ kind: str,
+ vendor: str,
+ channel: str,
+ created_at: str = MODEL_HUB_LEGACY_CREATED_AT,
+) -> ModelHubSourceConfig:
+ return ModelHubSourceConfig(
+ id=source_id,
+ kind=kind,
+ vendor=vendor,
+ display_name=source_id,
+ protocol="anthropic" if vendor == "anthropic" else "openai_responses",
+ supply_channel=channel,
+ billing="monthly" if kind == "subscription" else "metered",
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[],
+ created_at=created_at,
+ experimental_consent_at=("2026-07-29T02:00:00Z" if kind == "subscription" and channel == "hub" else None),
+ )
+
+
+def test_recommended_order_is_backend_native_then_created_at_and_id():
+ native = _ordering_source(
+ "src_nativeaaa",
+ kind="subscription",
+ vendor="anthropic",
+ channel="native_cli",
+ )
+ hub_subscription = _ordering_source(
+ "src_hubsubaaa",
+ kind="subscription",
+ vendor="anthropic",
+ channel="hub",
+ )
+ wrong_vendor_subscription = _ordering_source(
+ "src_openaisub",
+ kind="subscription",
+ vendor="openai",
+ channel="native_cli",
+ )
+ legacy_b = _ordering_source(
+ "src_legacybbb",
+ kind="api_key",
+ vendor="openai",
+ channel="hub",
+ )
+ legacy_a = _ordering_source(
+ "src_legacyaaa",
+ kind="api_key",
+ vendor="anthropic",
+ channel="hub",
+ )
+ newer = _ordering_source(
+ "src_newer0001",
+ kind="api_key",
+ vendor="custom",
+ channel="hub",
+ created_at="2026-07-29T03:00:00Z",
+ )
+ same_time_b = _ordering_source(
+ "src_tiebbbb1",
+ kind="api_key",
+ vendor="custom",
+ channel="hub",
+ created_at="2026-07-29T04:00:00Z",
+ )
+ same_time_a = _ordering_source(
+ "src_tieaaaa1",
+ kind="api_key",
+ vendor="custom",
+ channel="hub",
+ created_at="2026-07-29T04:00:00Z",
+ )
+ config = ModelHubConfig(
+ sources=[
+ same_time_b,
+ newer,
+ wrong_vendor_subscription,
+ legacy_b,
+ hub_subscription,
+ same_time_a,
+ native,
+ legacy_a,
+ ],
+ subscription_hub_experimental=True,
+ )
+
+ assert config.recommended_source_order("claude") == [
+ native.id,
+ hub_subscription.id,
+ legacy_a.id,
+ legacy_b.id,
+ newer.id,
+ same_time_a.id,
+ same_time_b.id,
+ ]
+ assert config.recommended_source_order("codex") == [
+ wrong_vendor_subscription.id,
+ legacy_a.id,
+ legacy_b.id,
+ newer.id,
+ same_time_a.id,
+ same_time_b.id,
+ ]
+ assert config.recommended_source_order("opencode") == [
+ legacy_a.id,
+ legacy_b.id,
+ newer.id,
+ same_time_a.id,
+ same_time_b.id,
+ ]
+
+
+ ("status", "retry_at", "detail_key"),
+ [
+ ("standby", "2026-07-29T03:00:00Z", None),
+ ("cooldown", None, "models.source.cooldown.network"),
+ ("needs_action", None, "models.source.cooldown.network"),
+ ("error", None, None),
+ ],
+)
+def test_source_state_rejects_invalid_status_correlations(status, retry_at, detail_key):
+ with pytest.raises(ValueError):
+ ModelHubSourceStateConfig.from_payload(
+ {
+ "status": status,
+ "retry_at": retry_at,
+ "detail_key": detail_key,
+ }
+ )
+
+
def test_source_optional_fields_reject_schema_invalid_values():
source = _schema("source.schema.json")["examples"][0]
invalid_sources = []
diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.py
index f215c26e6..3a1199a6a 100644
--- a/tests/test_model_hub_injection.py
+++ b/tests/test_model_hub_injection.py
@@ -13,6 +13,7 @@ from unittest.mock import AsyncMock, Mock, patch
import pytest
from config.v2_config import (
+ ModelHubAgentSourcesConfig,
ModelHubAgentSupplyConfig,
ModelHubConfig,
ModelHubMappingConfig,
@@ -117,7 +118,11 @@ def _source(
protocol=protocol,
supply_channel=channel,
billing="monthly" if kind == "subscription" else "metered",
- state=ModelHubSourceStateConfig(status=state, retry_at=retry_at),
+ state=ModelHubSourceStateConfig(
+ status=state,
+ retry_at=retry_at,
+ detail_key=("models.source.error.unclassified" if state == "error" else None),
+ ),
models=[_model(model_id) for model_id in model_ids],
credential_ref=f"cred_{source_id}" if channel == "hub" else None,
)
@@ -125,11 +130,31 @@ def _source(
def _agents(*, mode: str = "hub") -> dict[str, ModelHubAgentSupplyConfig]:
return {
- backend: ModelHubAgentSupplyConfig.default(backend, mode=mode)
- for backend in ("claude", "codex", "opencode")
+ backend: ModelHubAgentSupplyConfig.default(backend, mode=mode) for backend in ("claude", "codex", "opencode")
}
+def _hub_config(
+ *,
+ sources: list[ModelHubSourceConfig],
+ agents: dict[str, ModelHubAgentSupplyConfig],
+ order: list[str] | None = None,
+) -> ModelHubConfig:
+ config = ModelHubConfig(sources=sources, agents=agents)
+ requested_order = order if order is not None else [source.id for source in sources]
+ by_id = {source.id: source for source in sources}
+ for backend, agent in agents.items():
+ agent.sources = ModelHubAgentSourcesConfig(
+ policy="custom",
+ order=[
+ source_id
+ for source_id in requested_order
+ if source_id in by_id and config.source_eligible_for_backend(by_id[source_id], backend)
+ ],
+ )
+ return config
+
+
def _service(
tmp_path: Path,
config: ModelHubConfig,
@@ -181,9 +206,9 @@ def test_mh_chan_001_native_quota_falls_back_then_recovers_next_turn(tmp_path: P
)
agents = _agents()
agents["codex"].mappings = [ModelHubMappingConfig("default", "gpt-5", True)]
- config = ModelHubConfig(
+ config = _hub_config(
sources=[native, hub],
- priority_order=[native.id, hub.id],
+ order=[native.id, hub.id],
agents=agents,
)
adapter = LaunchAdapter({hub.id: "route-hub"})
@@ -228,9 +253,9 @@ def test_mh_chan_001_hub_failure_cools_source_and_selects_backup(tmp_path: Path)
channel="hub",
model_ids=("gpt-5",),
)
- config = ModelHubConfig(
+ config = _hub_config(
sources=[first, backup],
- priority_order=[first.id, backup.id],
+ order=[first.id, backup.id],
agents=_agents(),
)
adapter = LaunchAdapter({first.id: "route-first", backup.id: "route-backup"})
@@ -276,9 +301,9 @@ def test_mh_chan_001_hub_to_native_switch_keeps_failure_reason(tmp_path: Path) -
)
service = _service(
tmp_path,
- ModelHubConfig(
+ _hub_config(
sources=[hub, native],
- priority_order=[hub.id, native.id],
+ order=[hub.id, native.id],
agents=_agents(),
),
LaunchAdapter({hub.id: "route-hub"}),
@@ -292,9 +317,7 @@ def test_mh_chan_001_hub_to_native_switch_keeps_failure_reason(tmp_path: Path) -
assert asyncio.run(router.record_native_failure(context, "usage quota exceeded")) is True
assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "native_cli"
- channel_switch = next(
- event for event in service.events.list(limit=10) if event["kind"] == "channel_switch"
- )
+ channel_switch = next(event for event in service.events.list(limit=10) if event["kind"] == "channel_switch")
assert channel_switch["reason"] == "quota_exhausted"
@@ -307,9 +330,9 @@ def test_mh_chan_001_native_launch_replays_pending_revocations(tmp_path: Path) -
channel="native_cli",
model_ids=("gpt-5",),
)
- config = ModelHubConfig(
+ config = _hub_config(
sources=[native],
- priority_order=[native.id],
+ order=[native.id],
agents=_agents(),
)
adapter = LaunchAdapter({})
@@ -345,9 +368,9 @@ def test_mh_chan_001_native_sources_only_dispatch_to_sanctioned_client(tmp_path:
channel="hub",
model_ids=("shared-model",),
)
- config = ModelHubConfig(
+ config = _hub_config(
sources=[native_claude, hub_openai],
- priority_order=[native_claude.id, hub_openai.id],
+ order=[native_claude.id, hub_openai.id],
agents=_agents(),
)
adapter = LaunchAdapter({hub_openai.id: "route-openai"})
@@ -361,23 +384,19 @@ def test_mh_chan_001_native_sources_only_dispatch_to_sanctioned_client(tmp_path:
assert (launch.channel, launch.source_id) == ("hub", hub_openai.id)
-def test_mh_chan_001_unconfigured_fresh_hub_preserves_native_launch(tmp_path: Path) -> None:
+def test_mh_chan_001_unconfigured_hub_is_interrupted(tmp_path: Path) -> None:
service = _service(
tmp_path,
- ModelHubConfig(sources=[], priority_order=[], agents=_agents()),
+ _hub_config(sources=[], order=[], agents=_agents()),
LaunchAdapter({}),
now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
)
- launch = asyncio.run(_router(service).resolve("codex", "gpt-5"))
-
- assert launch.channel == "direct"
- event = service.events.list(limit=10)[0]
- assert (event["kind"], event["to_source"]) == ("channel_switch", None)
-
- asyncio.run(_router(service).resolve("codex", "gpt-5"))
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(_router(service).resolve("codex", "gpt-5"))
- assert len(service.events.list(limit=10)) == 1
+ assert exc_info.value.code == "mapping_target_unavailable"
+ assert service.events.list(limit=10) == []
def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> None:
@@ -385,7 +404,7 @@ def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> None
agents = _agents(mode="direct")
adapter = LaunchAdapter({})
- config = ModelHubConfig(sources=[], priority_order=[], agents=agents)
+ config = _hub_config(sources=[], order=[], agents=agents)
service = _service(
tmp_path,
config,
@@ -398,14 +417,9 @@ def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> None
assert service.events.list(limit=10) == []
agents["codex"].mode = "hub"
- assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "direct"
- assert [event["kind"] for event in service.events.list(limit=10)] == [
- "channel_switch"
- ]
-
- asyncio.run(router.resolve("codex", "gpt-5"))
-
- assert len(service.events.list(limit=10)) == 1
+ with pytest.raises(ModelHubError, match="mapping_target_unavailable"):
+ asyncio.run(router.resolve("codex", "gpt-5"))
+ assert service.events.list(limit=10) == []
hub = _source(
"src_hub_after_direct",
@@ -416,7 +430,7 @@ def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> None
model_ids=("gpt-5",),
)
config.sources.append(hub)
- config.priority_order.append(hub.id)
+ config.agents["codex"].sources.order.append(hub.id)
adapter.prefixes[hub.id] = "route-hub"
assert asyncio.run(router.resolve("codex", "gpt-5")).channel == "hub"
assert service.events.list(limit=10)[0]["reason"] == "manual"
@@ -425,14 +439,14 @@ def test_hub_fallback_event_survives_direct_mode_history(tmp_path: Path) -> None
def test_recovered_turn_uses_post_wait_mode_for_events(tmp_path: Path) -> None:
"""MH-EVT-002: recovered resolution and telemetry use one config snapshot."""
- initial = ModelHubConfig(
+ initial = _hub_config(
sources=[],
- priority_order=[],
+ order=[],
agents=_agents(mode="hub"),
)
- recovered = ModelHubConfig(
+ recovered = _hub_config(
sources=[],
- priority_order=[],
+ order=[],
agents=_agents(mode="direct"),
)
service = _service(
@@ -463,12 +477,10 @@ def test_direct_to_healthy_hub_switch_is_manual(tmp_path: Path) -> None:
model_ids=("custom-gpt-5",),
)
agents = _agents(mode="direct")
- agents["codex"].mappings = [
- ModelHubMappingConfig("gpt-5", "custom-gpt-5", True)
- ]
+ agents["codex"].mappings = [ModelHubMappingConfig("gpt-5", "custom-gpt-5", True)]
service = _service(
tmp_path,
- ModelHubConfig(sources=[hub], priority_order=[hub.id], agents=agents),
+ _hub_config(sources=[hub], order=[hub.id], agents=agents),
LaunchAdapter({hub.id: "route-hub"}),
now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
)
@@ -498,22 +510,21 @@ def test_mh_chan_001_other_backend_source_does_not_activate_hub(tmp_path: Path)
)
service = _service(
tmp_path,
- ModelHubConfig(
+ _hub_config(
sources=[codex_native],
- priority_order=[codex_native.id],
+ order=[codex_native.id],
agents=_agents(),
),
LaunchAdapter({}),
now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
)
- launch = asyncio.run(_router(service).resolve("claude", "claude-opus"))
-
- assert launch.channel == "direct"
+ with pytest.raises(ModelHubError, match="mapping_target_unavailable"):
+ asyncio.run(_router(service).resolve("claude", "claude-opus"))
-def test_agent_projection_matches_next_turn_for_unmapped_fixed_backend(tmp_path: Path) -> None:
- """MH-CHAN-001: an unmapped fixed backend projects its direct launch."""
+def test_agent_projection_matches_interrupted_unmapped_fixed_backend(tmp_path: Path) -> None:
+ """MH-CHAN-001: an unmapped Hub backend remains fail closed."""
hub = _source(
"src_hub_display",
@@ -526,9 +537,9 @@ def test_agent_projection_matches_next_turn_for_unmapped_fixed_backend(tmp_path:
adapter = LaunchAdapter({hub.id: "route-hub"})
service = _service(
tmp_path,
- ModelHubConfig(
+ _hub_config(
sources=[hub],
- priority_order=[hub.id],
+ order=[hub.id],
agents=_agents(),
),
adapter,
@@ -536,21 +547,14 @@ def test_agent_projection_matches_next_turn_for_unmapped_fixed_backend(tmp_path:
)
service.store.requested_models["claude"] = "claude-opus-4-6"
- projected = next(
- agent for agent in service.list_agents() if agent["backend"] == "claude"
- )
+ projected = next(agent for agent in service.list_agents() if agent["backend"] == "claude")
router = _router(service)
- launch = asyncio.run(router.resolve("claude", "claude-opus-4-6"))
-
- assert launch.channel == "direct"
+ with pytest.raises(ModelHubError, match="mapping_target_unavailable"):
+ asyncio.run(router.resolve("claude", "claude-opus-4-6"))
assert projected["current"] is None
+ assert projected["supply_status"] == "interrupted"
assert adapter.starts == 0
- event = service.events.list(limit=10)[0]
- assert (event["kind"], event["to_source"]) == ("channel_switch", None)
-
- asyncio.run(router.resolve("claude", "claude-opus-4-6"))
-
- assert len(service.events.list(limit=10)) == 1
+ assert service.events.list(limit=10) == []
def test_agent_projection_uses_global_default_vibe_agent_model(tmp_path: Path) -> None:
@@ -566,23 +570,19 @@ def test_agent_projection_uses_global_default_vibe_agent_model(tmp_path: Path) -
)
service = _service(
tmp_path,
- ModelHubConfig(
+ _hub_config(
sources=[hub],
- priority_order=[hub.id],
+ order=[hub.id],
agents=_agents(),
),
LaunchAdapter({hub.id: "route-hub"}),
now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
)
service.store.requested_models["codex"] = "backend-default"
- service.requested_model_override = (
- lambda backend: "agent-model" if backend == "codex" else None
- )
+ service.requested_model_override = lambda backend: "agent-model" if backend == "codex" else None
router = _router(service)
- projected = next(
- agent for agent in service.list_agents() if agent["backend"] == "codex"
- )["current"]
+ projected = next(agent for agent in service.list_agents() if agent["backend"] == "codex")["current"]
launch = asyncio.run(router.resolve("codex", "agent-model"))
assert projected == {
@@ -604,9 +604,7 @@ def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Pa
model_ids=("mapped-model",),
)
fixed_agents = _agents()
- fixed_agents["claude"].mappings = [
- ModelHubMappingConfig("claude-native", "mapped-model", True)
- ]
+ fixed_agents["claude"].mappings = [ModelHubMappingConfig("claude-native", "mapped-model", True)]
direct_hub = _source(
"src_hub_direct",
@@ -632,9 +630,7 @@ def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Pa
view="featured",
checked=["anthropic/claude-opus", "custom/mapped-open"],
)
- opencode_agents["opencode"].mappings = [
- ModelHubMappingConfig("anthropic/claude-opus", "custom/mapped-open", True)
- ]
+ opencode_agents["opencode"].mappings = [ModelHubMappingConfig("anthropic/claude-opus", "custom/mapped-open", True)]
opencode_mapped = _source(
"src_hub_open_mapped",
kind="api_key",
@@ -679,9 +675,9 @@ def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Pa
(
"claude",
"claude-native",
- ModelHubConfig(
+ _hub_config(
sources=[fixed_hub],
- priority_order=[fixed_hub.id],
+ order=[fixed_hub.id],
agents=fixed_agents,
),
{"model_id": "mapped-model", "source_id": fixed_hub.id, "channel": "hub"},
@@ -689,9 +685,9 @@ def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Pa
(
"codex",
"gpt-5",
- ModelHubConfig(
+ _hub_config(
sources=[direct_hub],
- priority_order=[direct_hub.id],
+ order=[direct_hub.id],
agents=direct_agents,
),
None,
@@ -699,9 +695,9 @@ def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Pa
(
"opencode",
"claude-opus",
- ModelHubConfig(
+ _hub_config(
sources=[opencode_hub, opencode_mapped],
- priority_order=[opencode_mapped.id, opencode_hub.id],
+ order=[opencode_mapped.id, opencode_hub.id],
agents=opencode_agents,
),
{
@@ -713,9 +709,9 @@ def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Pa
(
"opencode",
"",
- ModelHubConfig(
+ _hub_config(
sources=[unavailable_open, available_open],
- priority_order=[unavailable_open.id, available_open.id],
+ order=[unavailable_open.id, available_open.id],
agents=default_open_agents,
),
{
@@ -727,9 +723,9 @@ def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Pa
(
"codex",
"gpt-5",
- ModelHubConfig(
+ _hub_config(
sources=[native],
- priority_order=[native.id],
+ order=[native.id],
agents=_agents(),
),
{"model_id": "gpt-5", "source_id": native.id, "channel": "native_cli"},
@@ -738,11 +734,7 @@ def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Pa
for backend, requested_model, config, expected in cases:
adapter = LaunchAdapter(
- {
- source.id: f"route-{source.id}"
- for source in config.sources
- if source.supply_channel == "hub"
- }
+ {source.id: f"route-{source.id}" for source in config.sources if source.supply_channel == "hub"}
)
service = _service(
tmp_path,
@@ -753,9 +745,7 @@ def test_agent_projection_and_runtime_router_share_resolution_table(tmp_path: Pa
service.store.requested_models[backend] = requested_model
router = _router(service)
- projected = next(
- agent for agent in service.list_agents() if agent["backend"] == backend
- )["current"]
+ projected = next(agent for agent in service.list_agents() if agent["backend"] == backend)["current"]
launch = asyncio.run(router.resolve(backend, requested_model))
actual = (
None
@@ -780,12 +770,10 @@ def test_mh_chan_001_configured_hub_stays_fail_closed_for_unavailable_model(tmp_
model_ids=("gpt-5",),
)
agents = _agents()
- agents["codex"].mappings = [
- ModelHubMappingConfig("unavailable-model", "configured-but-missing", True)
- ]
+ agents["codex"].mappings = [ModelHubMappingConfig("unavailable-model", "configured-but-missing", True)]
service = _service(
tmp_path,
- ModelHubConfig(sources=[hub], priority_order=[hub.id], agents=agents),
+ _hub_config(sources=[hub], order=[hub.id], agents=agents),
LaunchAdapter({hub.id: "route-hub"}),
now=lambda: datetime(2026, 7, 23, tzinfo=timezone.utc),
)
@@ -815,9 +803,9 @@ def test_mh_chan_001_invalid_native_runtime_skips_to_hub(tmp_path: Path) -> None
)
service = _service(
tmp_path,
- ModelHubConfig(
+ _hub_config(
sources=[native, hub],
- priority_order=[native.id, hub.id],
+ order=[native.id, hub.id],
agents=_agents(),
),
LaunchAdapter({hub.id: "route-hub"}),
@@ -825,9 +813,7 @@ def test_mh_chan_001_invalid_native_runtime_skips_to_hub(tmp_path: Path) -> None
)
launch = asyncio.run(
- _router(service, native_cli_ready=lambda backend: backend != "codex").resolve(
- "codex", "gpt-5"
- )
+ _router(service, native_cli_ready=lambda backend: backend != "codex").resolve("codex", "gpt-5")
)
assert (launch.channel, launch.source_id, launch.runtime_model) == (
@@ -864,9 +850,9 @@ def test_projection_rechecks_expired_native_readiness_before_recovery(
)
service = _service(
tmp_path,
- ModelHubConfig(
+ _hub_config(
sources=[native, hub],
- priority_order=[native.id, hub.id],
+ order=[native.id, hub.id],
agents=_agents(),
),
LaunchAdapter({hub.id: "route-hub"}),
@@ -875,9 +861,7 @@ def test_projection_rechecks_expired_native_readiness_before_recovery(
service.store.requested_models["codex"] = "gpt-5"
router = _router(service, native_cli_ready=lambda _backend: False)
- projected = next(
- agent for agent in service.list_agents() if agent["backend"] == "codex"
- )["current"]
+ projected = next(agent for agent in service.list_agents() if agent["backend"] == "codex")["current"]
launch = asyncio.run(router.resolve("codex", "gpt-5"))
assert projected == {
@@ -889,9 +873,7 @@ def test_projection_rechecks_expired_native_readiness_before_recovery(
assert native.state.status == "active"
-def test_mh_chan_001_codex_native_runtime_requires_chatgpt_oauth(
- tmp_path: Path, monkeypatch
-) -> None:
+def test_mh_chan_001_codex_native_runtime_requires_chatgpt_oauth(tmp_path: Path, monkeypatch) -> None:
codex_home = tmp_path / "codex-home"
codex_home.mkdir()
auth_path = codex_home / "auth.json"
@@ -955,9 +937,9 @@ def test_mh_chan_001_verified_codex_keyring_source_remains_routable(
)
service = _service(
tmp_path,
- ModelHubConfig(
+ _hub_config(
sources=[native],
- priority_order=[native.id],
+ order=[native.id],
agents=_agents(),
),
LaunchAdapter({}),
@@ -979,9 +961,7 @@ def test_mh_chan_001_verified_codex_keyring_source_remains_routable(
clock["now"] += timedelta(seconds=301)
service.store.requested_models["codex"] = "gpt-5"
- projected = next(
- agent for agent in service.list_agents() if agent["backend"] == "codex"
- )["current"]
+ projected = next(agent for agent in service.list_agents() if agent["backend"] == "codex")["current"]
assert native.state.status == "cooldown"
recovered = asyncio.run(router.resolve("codex", "gpt-5"))
@@ -1109,9 +1089,9 @@ def _opencode_config() -> ModelHubConfig:
view="featured",
checked=["anthropic/claude-opus", "custom/local-model"],
)
- return ModelHubConfig(
+ return _hub_config(
sources=[anthropic, custom],
- priority_order=[anthropic.id, custom.id],
+ order=[anthropic.id, custom.id],
agents=agents,
)
@@ -1154,7 +1134,8 @@ def test_mh_ovl_001_identifiers_stay_stable_across_all_perturbations(tmp_path: P
model_ids=("claude-opus",),
)
config.sources.append(backup)
- config.priority_order = [backup.id, *reversed(config.priority_order)]
+ opencode_order = config.agents["opencode"].sources.order
+ config.agents["opencode"].sources.order = [backup.id, *reversed(opencode_order)]
after_add_reorder = asyncio.run(router.prepare_opencode_overlay())
backup.state = ModelHubSourceStateConfig(
@@ -1163,7 +1144,7 @@ def test_mh_ovl_001_identifiers_stay_stable_across_all_perturbations(tmp_path: P
)
after_cooldown = asyncio.run(router.prepare_opencode_overlay())
config.sources.remove(backup)
- config.priority_order.remove(backup.id)
+ config.agents["opencode"].sources.order.remove(backup.id)
after_remove = asyncio.run(router.prepare_opencode_overlay())
after_engine_restart = asyncio.run(router.prepare_opencode_overlay())
@@ -1259,7 +1240,7 @@ def test_mh_ovl_001_unavailable_menu_entry_does_not_block_healthy_model(tmp_path
asyncio.run(router.resolve("opencode", "anthropic/claude-opus"))
config.sources.remove(anthropic)
- config.priority_order.remove(anthropic.id)
+ config.agents["opencode"].sources.order.remove(anthropic.id)
reduced_overlay = asyncio.run(router.prepare_opencode_overlay())
assert reduced_overlay is not None
assert reduced_overlay.checked_identifiers == ("custom/local-model",)
@@ -1288,9 +1269,9 @@ def test_mh_ovl_001_turn_uses_overlay_source_snapshot(tmp_path: Path) -> None:
view="featured",
checked=["anthropic/claude-opus"],
)
- config = ModelHubConfig(
+ config = _hub_config(
sources=[primary, backup],
- priority_order=[primary.id, backup.id],
+ order=[primary.id, backup.id],
agents=agents,
)
adapter = LaunchAdapter(
@@ -1309,7 +1290,7 @@ def test_mh_ovl_001_turn_uses_overlay_source_snapshot(tmp_path: Path) -> None:
overlay = asyncio.run(router.prepare_opencode_overlay())
assert overlay is not None
- config.priority_order = [backup.id, primary.id]
+ config.agents["opencode"].sources.order = [backup.id, primary.id]
launch = asyncio.run(
resolve_opencode_overlay_launch(
SimpleNamespace(model_hub_runtime=router),
@@ -1353,9 +1334,9 @@ def test_mh_chan_001_switch_telemetry_is_isolated_per_model_route(tmp_path: Path
channel="hub",
model_ids=("model-b",),
)
- config = ModelHubConfig(
+ config = _hub_config(
sources=[native_a, hub_a, hub_b],
- priority_order=[native_a.id, hub_a.id, hub_b.id],
+ order=[native_a.id, hub_a.id, hub_b.id],
agents=_agents(),
)
service = _service(
@@ -1486,7 +1467,9 @@ def test_mh_inj_opencode_config_env_is_hub_only(tmp_path: Path, monkeypatch) ->
process = SimpleNamespace(pid=4321, returncode=None)
with (
patch("modules.agents.opencode.server.server_environment", return_value={"AVIBE_TEST": "1"}),
- patch("modules.agents.opencode.server.asyncio.create_subprocess_exec", new=AsyncMock(return_value=process)) as spawn,
+ patch(
+ "modules.agents.opencode.server.asyncio.create_subprocess_exec", new=AsyncMock(return_value=process)
+ ) as spawn,
):
await manager._start_server()
return spawn.await_args.kwargs["env"]
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index f1ab960ce..0fbe4a2ec 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -8,6 +8,7 @@ from datetime import datetime, timedelta, timezone
import pytest
from config.v2_config import (
+ ModelHubAgentSourcesConfig,
ModelHubAgentSupplyConfig,
ModelHubConfig,
ModelHubMappingConfig,
@@ -23,6 +24,7 @@ from core.handlers.model_hub.adapter import (
)
from core.handlers.model_hub.classification import classify_outcome
from core.handlers.model_hub.events import BoundedEventLog, build_resolution_event
+from core.handlers.model_hub.resolver import resolve_model_hub_turn
from core.handlers.model_hub.revocations import CredentialRevocationJournal
from core.handlers.model_hub.service import ModelHubError, ModelHubService, _mask_credential
from vibe.i18n import t as i18n_t
@@ -165,15 +167,15 @@ def _service(tmp_path, adapter, *, agents=None, now=None):
_source("src_primary01", "Primary", billing="monthly"),
_source("src_backup001", "Backup"),
]
- config = ModelHubConfig(
- sources=sources,
- priority_order=[source.id for source in sources],
- agents=agents
- or {
- backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")
- for backend in ("claude", "codex", "opencode")
- },
- )
+ agents = agents or {
+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub") for backend in ("claude", "codex", "opencode")
+ }
+ config = ModelHubConfig(sources=sources, agents=agents)
+ for agent in agents.values():
+ agent.sources = ModelHubAgentSourcesConfig(
+ policy="custom",
+ order=[source.id for source in sources],
+ )
return ModelHubService(
store=MemoryStore(config),
adapter=adapter,
@@ -211,22 +213,14 @@ def _serialized_config(service) -> str:
def _assert_no_references_to(service, model_id: str) -> None:
persisted = service.store.load()
- mapping_targets = {
- mapping.target_model_id
- for agent in persisted.agents.values()
- for mapping in agent.mappings
- }
+ mapping_targets = {mapping.target_model_id for agent in persisted.agents.values() for mapping in agent.mappings}
menu_target_models = {
identifier.partition("/")[2]
for agent in persisted.agents.values()
if agent.menu is not None
for identifier in agent.menu.checked
}
- available_models = {
- model.id
- for source in persisted.sources
- for model in source.models
- }
+ available_models = {model.id for source in persisted.sources for model in source.models}
assert mapping_targets <= available_models
assert menu_target_models <= available_models
@@ -267,7 +261,7 @@ def test_quota_failure_cools_source_switches_and_emits_redacted_events(tmp_path)
RawOutcomeKind.HTTP_ERROR,
status=429,
code="quota_exhausted",
- message=f'upstream redaction failure included {fake_key}',
+ message=f"upstream redaction failure included {fake_key}",
),
_outcome(RawOutcomeKind.SUCCESS, status=200),
_outcome(RawOutcomeKind.SUCCESS, status=200),
@@ -321,9 +315,7 @@ def test_event_log_failure_does_not_abort_failover(tmp_path):
service = _service(tmp_path, adapter)
service.events = UnwritableEventLog()
- resolved = asyncio.run(
- service.resolve(backend="claude", model_id="claude-opus-4-6", request={})
- )
+ resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
assert resolved.source_id == "src_backup001"
assert service.store.load().sources[0].state.status == "cooldown"
@@ -390,8 +382,7 @@ def test_mapping_is_scoped_to_the_requesting_backend(tmp_path):
"""Scenario: MH-MAP-001."""
agents = {
- backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")
- for backend in ("claude", "codex", "opencode")
+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub") for backend in ("claude", "codex", "opencode")
}
agents["claude"].mappings = [
ModelHubMappingConfig(builtin_id="claude-native", target_model_id="claude-opus-4-6", enabled=True)
@@ -493,9 +484,7 @@ def test_persisted_hub_sources_sync_before_first_resolution(tmp_path):
adapter = RegistrationRequiredAdapter()
service = _service(tmp_path, adapter)
- resolved = asyncio.run(
- service.resolve(backend="claude", model_id="claude-opus-4-6", request={})
- )
+ resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
assert resolved.source_id == "src_primary01"
assert [binding.source_id for binding in adapter.synced[0]] == [
@@ -515,11 +504,98 @@ def test_agent_current_skips_cooldown_and_error_sources(tmp_path):
claude = next(agent for agent in service.list_agents() if agent["backend"] == "claude")
assert claude["current"]["source_id"] == "src_backup001"
- config.sources[1].state = ModelHubSourceStateConfig(status="error")
+ config.sources[1].state = ModelHubSourceStateConfig(
+ status="error",
+ detail_key="models.source.error.unclassified",
+ )
claude = next(agent for agent in service.list_agents() if agent["backend"] == "claude")
assert claude["current"] is None
+ ("first_state", "second_state", "expected_status", "expected_source"),
+ [
+ (
+ ModelHubSourceStateConfig(status="standby"),
+ ModelHubSourceStateConfig(status="standby"),
+ "ok",
+ "src_primary01",
+ ),
+ (
+ ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at="2026-07-23T03:05:00Z",
+ ),
+ ModelHubSourceStateConfig(status="standby"),
+ "degraded",
+ "src_backup001",
+ ),
+ (
+ ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at="2026-07-23T03:05:00Z",
+ ),
+ ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at="2026-07-23T03:06:00Z",
+ ),
+ "waiting",
+ None,
+ ),
+ (
+ ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at="2026-07-23T03:05:00Z",
+ ),
+ ModelHubSourceStateConfig(
+ status="needs_action",
+ detail_key="models.source.needs_action.credential_revoked",
+ ),
+ "interrupted",
+ None,
+ ),
+ ],
+)
+def test_supply_status_is_derived_from_blocker_causes(
+ tmp_path,
+ first_state,
+ second_state,
+ expected_status,
+ expected_source,
+):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ config.sources[0].state = first_state
+ config.sources[1].state = second_state
+
+ resolution = resolve_model_hub_turn(
+ config,
+ "claude",
+ "claude-opus-4-6",
+ now=datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
+ )
+
+ assert resolution.supply_status == expected_status
+ assert (resolution.source.id if resolution.source is not None else None) == expected_source
+
+
+def test_empty_enabled_subset_is_structurally_interrupted(tmp_path):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ config.agents["claude"].sources.order = []
+
+ resolution = resolve_model_hub_turn(
+ config,
+ "claude",
+ "claude-opus-4-6",
+ now=datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
+ )
+
+ assert resolution.matching_sources == ()
+ assert resolution.supply_status == "interrupted"
+ assert resolution.source is None
+
+
def test_native_source_is_dispatched_before_hub_and_cooldown_falls_through(tmp_path):
adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
service = _service(tmp_path, adapter)
@@ -527,9 +603,7 @@ def test_native_source_is_dispatched_before_hub_and_cooldown_falls_through(tmp_p
native.kind = "subscription"
native.supply_channel = "native_cli"
- resolved = asyncio.run(
- service.resolve(backend="claude", model_id="claude-opus-4-6", request={})
- )
+ resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
assert resolved.source_id == "src_primary01"
assert resolved.supply_channel == "native_cli"
@@ -540,9 +614,7 @@ def test_native_source_is_dispatched_before_hub_and_cooldown_falls_through(tmp_p
status="cooldown",
retry_at="2026-07-23T03:05:00Z",
)
- fallback = asyncio.run(
- service.resolve(backend="claude", model_id="claude-opus-4-6", request={})
- )
+ fallback = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
assert fallback.source_id == "src_backup001"
assert fallback.supply_channel == "hub"
@@ -558,9 +630,7 @@ def test_native_dispatch_attempts_pending_credential_revoke(tmp_path):
native.credential_ref = None
service.revocations.add("src_deleted", "cred_deleted")
- resolved = asyncio.run(
- service.resolve(backend="claude", model_id="claude-opus-4-6", request={})
- )
+ resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
assert resolved.source_id == "src_primary01"
assert resolved.supply_channel == "native_cli"
@@ -611,7 +681,7 @@ def test_source_creation_persists_before_engine_sync(tmp_path):
)
assert order == ["persist", "sync"]
- assert service.store.load().sources[-1].id == created["id"]
+ assert service.store.load().sources[-1].id == created["source"]["id"]
def test_source_creation_revokes_credential_when_persist_fails(tmp_path):
@@ -690,9 +760,7 @@ def test_failed_create_rollback_is_journaled_until_revoke_recovers(tmp_path):
adapter.fail_sync = False
adapter.fail_revoke = False
- resolved = asyncio.run(
- service.resolve(backend="claude", model_id="claude-opus-4-6", request={})
- )
+ resolved = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
assert resolved.source_id == "src_primary01"
assert adapter.revoked == ["cred_test", "cred_test"]
@@ -745,7 +813,7 @@ def test_source_delete_cascades_agent_model_references(tmp_path, force, mode):
persisted = service.store.load()
assert [source.id for source in persisted.sources] == ["src_backup001"]
- assert persisted.priority_order == ["src_backup001"]
+ assert all(agent.sources.order == ["src_backup001"] for agent in persisted.agents.values())
_assert_no_references_to(service, "retired-model")
if force:
agents = {agent["backend"]: agent for agent in service.list_agents()}
@@ -766,7 +834,8 @@ def test_deleting_last_hub_source_syncs_empty_binding_set(tmp_path):
service = _service(tmp_path, adapter)
config = service.store.load()
config.sources = [config.sources[0]]
- config.priority_order = [config.sources[0].id]
+ for agent in config.agents.values():
+ agent.sources.order = [config.sources[0].id]
asyncio.run(service.delete_source("src_primary01", force=True))
@@ -814,6 +883,8 @@ def test_restart_replays_credential_revoke_after_delete_commit(tmp_path):
native.kind = "subscription"
native.supply_channel = "native_cli"
native.credential_ref = None
+ service.store.load().agents["codex"].sources.order = ["src_primary01"]
+ service.store.load().agents["opencode"].sources.order = ["src_primary01"]
with pytest.raises(SimulatedProcessExit):
asyncio.run(service.delete_source("src_primary01", force=True))
@@ -829,9 +900,7 @@ def test_restart_replays_credential_revoke_after_delete_commit(tmp_path):
revocations=journal,
now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
)
- resolved = asyncio.run(
- restarted.resolve(backend="claude", model_id="claude-opus-4-6", request={})
- )
+ resolved = asyncio.run(restarted.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
assert resolved.source_id == "src_backup001"
assert resolved.supply_channel == "native_cli"
@@ -910,9 +979,7 @@ def test_custom_model_preserves_slash_qualified_upstream_id(tmp_path):
)
)
menu = asyncio.run(
- service.set_opencode_menu(
- {"view": "featured", "checked": ["openrouter/anthropic/claude-sonnet-4"]}
- )
+ service.set_opencode_menu({"view": "featured", "checked": ["openrouter/anthropic/claude-sonnet-4"]})
)
assert updated["models"][-1]["id"] == "anthropic/claude-sonnet-4"
@@ -954,6 +1021,9 @@ def test_mapping_and_delete_guards_use_backend_eligible_sources(tmp_path):
config.sources[1].supply_channel = "native_cli"
config.sources[1].vendor = "openai"
config.sources[1].models = [ModelHubModelConfig(id="gpt-5", provenance="discovered")]
+ config.agents["claude"].sources.order = ["src_primary01"]
+ config.agents["codex"].sources.order = ["src_backup001"]
+ config.agents["opencode"].sources.order = []
with pytest.raises(ModelHubError, match="mapping_target_unavailable"):
asyncio.run(
@@ -969,9 +1039,7 @@ def test_mapping_and_delete_guards_use_backend_eligible_sources(tmp_path):
)
)
- config.agents["claude"].mappings = [
- ModelHubMappingConfig("claude-native", "claude-opus-4-6", True)
- ]
+ config.agents["claude"].mappings = [ModelHubMappingConfig("claude-native", "claude-opus-4-6", True)]
with pytest.raises(ModelHubError) as exc_info:
asyncio.run(service.delete_source("src_primary01"))
assert exc_info.value.code == "mode_switch_blocked"
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index ea6ce479a..9de17dddf 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -517,7 +517,7 @@
"flow_not_found": "Authorization flow not found.",
"flow_expired": "Authorization flow expired.",
"discovery_failed": "Could not validate or discover this source.",
- "invalid_priority_order": "Priority must include every source exactly once.",
+ "invalid_source_order": "The source order contains an unavailable, ineligible, or duplicate source.",
"mapping_target_unavailable": "The selected model is unavailable for this backend.",
"mode_switch_blocked": "This operation is blocked by the current supply mode or selection.",
"engine_down": "The local Model Hub runtime is unavailable.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 3fc63d51f..6e40da8a2 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -517,7 +517,7 @@
"flow_not_found": "未找到授权流程。",
"flow_expired": "授权流程已过期。",
"discovery_failed": "无法验证或发现此来源。",
- "invalid_priority_order": "优先级必须完整且不重复地包含所有来源。",
+ "invalid_source_order": "来源顺序包含不可用、不适用或重复的来源。",
"mapping_target_unavailable": "所选模型无法用于此后端。",
"mode_switch_blocked": "当前供给模式或选择阻止了此操作。",
"engine_down": "本地模型中枢运行时不可用。",
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index 91084bc91..e4059f15e 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -93,15 +93,18 @@ class ModelHubRemoteService:
result = await _rpc("test_source", {"source_id": source_id})
return result["source"], result["discovered"]
- def priority(self) -> dict:
- return _rpc_sync("priority")
-
- async def set_priority(self, order: object) -> dict:
- return await _rpc("set_priority", {"order": order})
-
def list_agents(self) -> list[dict]:
return _rpc_sync("list_agents")
+ def get_agent_sources(self, backend: str) -> dict:
+ return _rpc_sync("get_agent_sources", {"backend": backend})
+
+ async def set_agent_sources(self, backend: str, sources: object) -> dict:
+ return await _rpc(
+ "set_agent_sources",
+ {"backend": backend, "sources": sources},
+ )
+
async def set_agent_mode(self, backend: str, mode: object) -> dict:
return await _rpc("set_agent_mode", {"backend": backend, "mode": mode})
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 8f9e4a3a4..678304c8c 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2166,9 +2166,16 @@ def reject_disabled_model_hub_api():
"""Keep the unreleased Model Hub REST surface dormant by default."""
from config.v2_config import is_model_hub_enabled
+ from core.handlers.model_hub.service import CONTRACT_VERSION
if request.path.startswith("/api/models/") and not is_model_hub_enabled():
- return jsonify({"ok": False, "contract_version": 1, "error": "feature_disabled"}), 404
+ return jsonify(
+ {
+ "ok": False,
+ "contract_version": CONTRACT_VERSION,
+ "error": "feature_disabled",
+ }
+ ), 404
return None
@@ -3127,11 +3134,15 @@ def _model_hub_service():
def _model_hub_success(**payload):
- return jsonify({"ok": True, "contract_version": 1, **payload})
+ from core.handlers.model_hub.service import CONTRACT_VERSION
+
+ return jsonify({"ok": True, "contract_version": CONTRACT_VERSION, **payload})
def _model_hub_error(exc):
- body = {"ok": False, "contract_version": 1, "error": exc.code}
+ from core.handlers.model_hub.service import CONTRACT_VERSION
+
+ body = {"ok": False, "contract_version": CONTRACT_VERSION, "error": exc.code}
if exc.detail:
body["detail"] = exc.detail
return jsonify(body), exc.status
@@ -3161,8 +3172,8 @@ async def model_hub_sources_post():
from core.handlers.model_hub import ModelHubError
try:
- source = await _model_hub_service().create_source(_model_hub_json_object())
- return _model_hub_success(source=source), 201
+ result = await _model_hub_service().create_source(_model_hub_json_object())
+ return _model_hub_success(**result), 201
except ModelHubError as exc:
return _model_hub_error(exc)
@@ -3201,36 +3212,36 @@ async def model_hub_sources_test(source_id):
return _model_hub_error(exc)
[email protected]("/api/models/priority", methods=["GET"])
-def model_hub_priority_get():
[email protected]("/api/models/agents", methods=["GET"])
+def model_hub_agents_get():
from core.handlers.model_hub import ModelHubError
try:
- priority = _model_hub_service().priority()
- return _model_hub_success(order=priority["order"])
+ return _model_hub_success(agents=_model_hub_service().list_agents())
except ModelHubError as exc:
return _model_hub_error(exc)
[email protected]("/api/models/priority", methods=["PUT"])
-async def model_hub_priority_put():
[email protected]("/api/models/agents/<backend>/sources", methods=["GET"])
+def model_hub_agent_sources_get(backend):
from core.handlers.model_hub import ModelHubError
try:
- priority = await _model_hub_service().set_priority(
- _model_hub_json_object("invalid_priority_order").get("order")
- )
- return _model_hub_success(order=priority["order"])
+ return _model_hub_success(agent=_model_hub_service().get_agent_sources(backend))
except ModelHubError as exc:
return _model_hub_error(exc)
[email protected]("/api/models/agents", methods=["GET"])
-def model_hub_agents_get():
[email protected]("/api/models/agents/<backend>/sources", methods=["PUT"])
+async def model_hub_agent_sources_put(backend):
from core.handlers.model_hub import ModelHubError
try:
- return _model_hub_success(agents=_model_hub_service().list_agents())
+ agent = await _model_hub_service().set_agent_sources(
+ backend,
+ _model_hub_json_object("invalid_source_order"),
+ )
+ return _model_hub_success(agent=agent)
except ModelHubError as exc:
return _model_hub_error(exc)
@@ -3322,7 +3333,7 @@ async def model_hub_oauth_start():
try:
return _model_hub_success(
- flow=await _model_hub_service().oauth_start(_model_hub_json_object("flow_not_found"))
+ **await _model_hub_service().oauth_start(_model_hub_json_object("flow_not_found"))
)
except ModelHubError as exc:
return _model_hub_error(exc)
@@ -3333,7 +3344,7 @@ async def model_hub_oauth_status(flow_id):
from core.handlers.model_hub import ModelHubError
try:
- return _model_hub_success(flow=await _model_hub_service().oauth_status(flow_id))
+ return _model_hub_success(**await _model_hub_service().oauth_status(flow_id))
except ModelHubError as exc:
return _model_hub_error(exc)
@@ -3344,7 +3355,7 @@ async def model_hub_oauth_submit():
try:
return _model_hub_success(
- flow=await _model_hub_service().oauth_submit(
+ **await _model_hub_service().oauth_submit(
_model_hub_json_object("flow_not_found", status=404)
)
)