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 config API and resolution policy (#963)

Call White20682257889e
diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml
index 43a8edd31..7429d5edc 100644
--- a/.github/workflows/lint.yml
+++ b/.github/workflows/lint.yml
@@ -107,7 +107,7 @@ jobs:
uv.lock
- name: Install package and test deps
- run: uv pip install --system -e . pytest
+ run: uv pip install --system -e . pytest jsonschema
- name: Run unit tests shard ${{ matrix.shard }}/${{ matrix.shard-total }}
run: bash scripts/ci_unit_tests.sh "${{ matrix.shard }}" "${{ matrix.shard-total }}"
diff --git a/config/v2_config.py b/config/v2_config.py
index e2a17655d..2a7511bba 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -1,9 +1,11 @@
import json
import logging
import os
+import re
import tempfile
import threading
from dataclasses import dataclass, field, fields
+from datetime import datetime
from pathlib import Path
from typing import List, Literal, Optional, Union
@@ -77,6 +79,20 @@ MAX_CHAT_MESSAGE_FONT_SIZE_PX = 20
DEFAULT_AGENT_PROGRESS_STYLE = "off"
+def _validate_optional_datetime(value: object, field_path: str) -> Optional[str]:
+ if value is None:
+ return None
+ if not isinstance(value, str):
+ raise ValueError(f"Config '{field_path}' must be a date-time string or null")
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError as exc:
+ raise ValueError(f"Config '{field_path}' must be a valid date-time") from exc
+ if parsed.tzinfo is None:
+ raise ValueError(f"Config '{field_path}' must include a timezone")
+ return value
+
+
def _filter_dataclass_fields(dc_class, payload: dict) -> dict:
"""Filter payload to only include fields defined in dataclass."""
valid_fields = {f.name for f in fields(dc_class)}
@@ -304,6 +320,399 @@ class AgentsConfig:
avault: AVaultConfig = field(default_factory=AVaultConfig)
+@dataclass
+class ModelHubModelConfig:
+ id: str
+ provenance: Literal["discovered", "manual"]
+ display_name: Optional[str] = None
+ discovered_at: Optional[str] = None
+
+ @classmethod
+ def from_payload(cls, payload: dict) -> "ModelHubModelConfig":
+ if not isinstance(payload, dict):
+ raise ValueError("Config 'model_hub.sources.models' entries must be objects")
+ model_id = payload.get("id")
+ provenance = payload.get("provenance")
+ display_name = payload.get("display_name")
+ discovered_at = payload.get("discovered_at")
+ if not isinstance(model_id, str) or not model_id:
+ raise ValueError("Config 'model_hub.sources.models.id' must be a non-empty string")
+ if provenance not in {"discovered", "manual"}:
+ raise ValueError("Config 'model_hub.sources.models.provenance' is invalid")
+ if display_name is not None and not isinstance(display_name, str):
+ raise ValueError("Config 'model_hub.sources.models.display_name' must be a string or null")
+ return cls(
+ id=model_id,
+ provenance=provenance,
+ display_name=display_name,
+ discovered_at=_validate_optional_datetime(
+ discovered_at,
+ "model_hub.sources.models.discovered_at",
+ ),
+ )
+
+ def to_payload(self) -> dict:
+ return {
+ "id": self.id,
+ "display_name": self.display_name,
+ "provenance": self.provenance,
+ "discovered_at": self.discovered_at,
+ }
+
+
+@dataclass
+class ModelHubSourceStateConfig:
+ status: Literal["active", "standby", "cooldown", "error"] = "standby"
+ retry_at: Optional[str] = None
+ detail_key: Optional[str] = None
+
+ @classmethod
+ def from_payload(cls, payload: dict) -> "ModelHubSourceStateConfig":
+ if not isinstance(payload, dict):
+ raise ValueError("Config 'model_hub.sources.state' must be an object")
+ status = payload.get("status")
+ retry_at = payload.get("retry_at")
+ detail_key = payload.get("detail_key")
+ if status not in {"active", "standby", "cooldown", "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")
+ return cls(
+ status=status,
+ retry_at=_validate_optional_datetime(retry_at, "model_hub.sources.state.retry_at"),
+ detail_key=detail_key,
+ )
+
+ def to_payload(self) -> dict:
+ return {"status": self.status, "retry_at": self.retry_at, "detail_key": self.detail_key}
+
+
+@dataclass
+class ModelHubSourceUsageConfig:
+ cycle_used_pct: Optional[float] = None
+ month_spend_cents: Optional[int] = None
+ currency: Optional[str] = None
+
+ @classmethod
+ def from_payload(cls, payload: dict) -> "ModelHubSourceUsageConfig":
+ if not isinstance(payload, dict):
+ raise ValueError("Config 'model_hub.sources.usage' must be an object")
+ cycle_used_pct = payload.get("cycle_used_pct")
+ if cycle_used_pct is not None and (
+ isinstance(cycle_used_pct, bool)
+ or not isinstance(cycle_used_pct, (int, float))
+ or not 0 <= cycle_used_pct <= 100
+ ):
+ 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")
+ 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
+ ):
+ raise ValueError("Config 'model_hub.sources.usage.month_spend_cents' must be a non-negative integer")
+ if currency is not None and not isinstance(currency, str):
+ raise ValueError("Config 'model_hub.sources.usage.currency' must be a string or null")
+ return cls(
+ cycle_used_pct=cycle_used_pct,
+ month_spend_cents=month_spend_cents,
+ currency=currency,
+ )
+
+ def to_payload(self) -> dict:
+ return {
+ "cycle_used_pct": self.cycle_used_pct,
+ "month_spend_cents": self.month_spend_cents,
+ "currency": self.currency,
+ }
+
+
+@dataclass
+class ModelHubSourceConfig:
+ id: str
+ kind: Literal["subscription", "api_key"]
+ vendor: str
+ display_name: str
+ protocol: Literal["anthropic", "openai_responses", "openai_chat", "openai_compatible"]
+ supply_channel: Literal["native_cli", "hub"]
+ billing: Literal["monthly", "metered"]
+ state: ModelHubSourceStateConfig
+ models: list[ModelHubModelConfig]
+ base_url: Optional[str] = None
+ experimental_consent_at: Optional[str] = None
+ usage: Optional[ModelHubSourceUsageConfig] = None
+ credential_ref: Optional[str] = None
+ account_label: Optional[str] = None
+ masked_credential: Optional[str] = None
+
+ @classmethod
+ def from_payload(cls, payload: dict) -> "ModelHubSourceConfig":
+ if not isinstance(payload, dict):
+ raise ValueError("Config 'model_hub.sources' entries must be objects")
+ source_id = payload.get("id")
+ kind = payload.get("kind")
+ vendor = payload.get("vendor")
+ display_name = payload.get("display_name")
+ protocol = payload.get("protocol")
+ supply_channel = payload.get("supply_channel")
+ billing = payload.get("billing")
+ if not isinstance(source_id, str) or re.fullmatch(r"src_[a-z0-9]{8,}", source_id) is None:
+ raise ValueError("Config 'model_hub.sources.id' is invalid")
+ if kind not in {"subscription", "api_key"}:
+ raise ValueError("Config 'model_hub.sources.kind' is invalid")
+ if not isinstance(vendor, str) or not vendor:
+ raise ValueError("Config 'model_hub.sources.vendor' must be a non-empty string")
+ if not isinstance(display_name, str) or not display_name or len(display_name) > 64:
+ raise ValueError("Config 'model_hub.sources.display_name' is invalid")
+ if protocol not in {"anthropic", "openai_responses", "openai_chat", "openai_compatible"}:
+ raise ValueError("Config 'model_hub.sources.protocol' is invalid")
+ if supply_channel not in {"native_cli", "hub"}:
+ raise ValueError("Config 'model_hub.sources.supply_channel' is invalid")
+ if billing not in {"monthly", "metered"}:
+ raise ValueError("Config 'model_hub.sources.billing' is invalid")
+ models_payload = payload.get("models")
+ if not isinstance(models_payload, list):
+ raise ValueError("Config 'model_hub.sources.models' must be an array")
+ usage_payload = payload.get("usage")
+ base_url = payload.get("base_url")
+ consent_at = payload.get("experimental_consent_at")
+ credential_ref = payload.get("credential_ref")
+ account_label = payload.get("account_label")
+ masked_credential = payload.get("masked_credential")
+ 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):
+ raise ValueError("Config 'model_hub.sources.credential_ref' is invalid")
+ if account_label is not None and not isinstance(account_label, str):
+ raise ValueError("Config 'model_hub.sources.account_label' is invalid")
+ if masked_credential is not None and not isinstance(masked_credential, str):
+ raise ValueError("Config 'model_hub.sources.masked_credential' is invalid")
+ return cls(
+ id=source_id,
+ kind=kind,
+ vendor=vendor,
+ display_name=display_name,
+ protocol=protocol,
+ supply_channel=supply_channel,
+ billing=billing,
+ state=ModelHubSourceStateConfig.from_payload(payload.get("state")),
+ models=[ModelHubModelConfig.from_payload(model) for model in models_payload],
+ base_url=base_url,
+ experimental_consent_at=_validate_optional_datetime(
+ consent_at,
+ "model_hub.sources.experimental_consent_at",
+ ),
+ usage=ModelHubSourceUsageConfig.from_payload(usage_payload) if usage_payload is not None else None,
+ credential_ref=credential_ref,
+ account_label=account_label,
+ masked_credential=masked_credential,
+ )
+
+ def to_payload(self) -> dict:
+ payload = {
+ "id": self.id,
+ "kind": self.kind,
+ "vendor": self.vendor,
+ "display_name": self.display_name,
+ "protocol": self.protocol,
+ "base_url": self.base_url,
+ "supply_channel": self.supply_channel,
+ "billing": self.billing,
+ "state": self.state.to_payload(),
+ "models": [model.to_payload() for model in self.models],
+ "credential_ref": self.credential_ref,
+ "account_label": self.account_label,
+ "masked_credential": self.masked_credential,
+ }
+ if self.usage is not None:
+ payload["usage"] = self.usage.to_payload()
+ if self.experimental_consent_at is not None:
+ payload["experimental_consent_at"] = self.experimental_consent_at
+ return payload
+
+
+@dataclass
+class ModelHubMappingConfig:
+ builtin_id: str
+ target_model_id: str
+ enabled: bool
+
+ @classmethod
+ def from_payload(cls, payload: dict) -> "ModelHubMappingConfig":
+ if not isinstance(payload, dict):
+ raise ValueError("Config 'model_hub.agents.mappings' entries must be objects")
+ builtin_id = payload.get("builtin_id")
+ target_model_id = payload.get("target_model_id")
+ enabled = payload.get("enabled")
+ if not isinstance(builtin_id, str) or not builtin_id:
+ raise ValueError("Config 'model_hub.agents.mappings.builtin_id' is invalid")
+ if not isinstance(target_model_id, str) or not target_model_id:
+ raise ValueError("Config 'model_hub.agents.mappings.target_model_id' is invalid")
+ if not isinstance(enabled, bool):
+ raise ValueError("Config 'model_hub.agents.mappings.enabled' must be a boolean")
+ return cls(builtin_id=builtin_id, target_model_id=target_model_id, enabled=enabled)
+
+ def to_payload(self) -> dict:
+ return {
+ "builtin_id": self.builtin_id,
+ "target_model_id": self.target_model_id,
+ "enabled": self.enabled,
+ }
+
+
+@dataclass
+class ModelHubMenuConfig:
+ view: Literal["featured", "full"] = "featured"
+ checked: list[str] = field(default_factory=list)
+
+ @classmethod
+ def from_payload(cls, payload: dict) -> "ModelHubMenuConfig":
+ if not isinstance(payload, dict):
+ raise ValueError("Config 'model_hub.agents.menu' must be an object")
+ view = payload.get("view")
+ checked = payload.get("checked")
+ if view not in {"featured", "full"}:
+ raise ValueError("Config 'model_hub.agents.menu.view' is invalid")
+ if not isinstance(checked, list) or not all(isinstance(item, str) for item in checked):
+ raise ValueError("Config 'model_hub.agents.menu.checked' must be an array of strings")
+ if len(set(checked)) != len(checked):
+ raise ValueError("Config 'model_hub.agents.menu.checked' must be unique")
+ return cls(view=view, checked=list(checked))
+
+ def to_payload(self) -> dict:
+ return {"view": self.view, "checked": list(self.checked)}
+
+
+@dataclass
+class ModelHubAgentSupplyConfig:
+ backend: Literal["claude", "codex", "opencode"]
+ mode: Literal["hub", "direct"]
+ menu_kind: Literal["fixed", "open"]
+ mappings: list[ModelHubMappingConfig] = field(default_factory=list)
+ menu: Optional[ModelHubMenuConfig] = None
+
+ @classmethod
+ def default(cls, backend: str, *, mode: Literal["hub", "direct"]) -> "ModelHubAgentSupplyConfig":
+ if backend == "opencode":
+ return cls(backend="opencode", mode=mode, menu_kind="open", menu=ModelHubMenuConfig())
+ if backend not in {"claude", "codex"}:
+ raise ValueError(f"Unsupported Model Hub backend: {backend}")
+ return cls(backend=backend, mode=mode, menu_kind="fixed")
+
+ @classmethod
+ def from_payload(cls, payload: dict, *, expected_backend: Optional[str] = None) -> "ModelHubAgentSupplyConfig":
+ if not isinstance(payload, dict):
+ raise ValueError("Config 'model_hub.agents' entries must be objects")
+ backend = payload.get("backend") or expected_backend
+ mode = payload.get("mode")
+ menu_kind = payload.get("menu_kind")
+ if backend not in {"claude", "codex", "opencode"} or (
+ expected_backend is not None and backend != expected_backend
+ ):
+ raise ValueError("Config 'model_hub.agents.backend' is invalid")
+ if mode not in {"hub", "direct"}:
+ raise ValueError("Config 'model_hub.agents.mode' is invalid")
+ expected_menu_kind = "open" if backend == "opencode" else "fixed"
+ if menu_kind != expected_menu_kind:
+ raise ValueError("Config 'model_hub.agents.menu_kind' is invalid for backend")
+ mappings_payload = payload.get("mappings") or []
+ if not isinstance(mappings_payload, list):
+ raise ValueError("Config 'model_hub.agents.mappings' must be an array")
+ menu_payload = payload.get("menu")
+ if backend == "opencode" and menu_payload is None:
+ menu_payload = {"view": "featured", "checked": []}
+ if backend != "opencode" and menu_payload is not None:
+ raise ValueError("Config 'model_hub.agents.menu' is only valid for opencode")
+ return cls(
+ backend=backend,
+ mode=mode,
+ menu_kind=menu_kind,
+ mappings=[ModelHubMappingConfig.from_payload(mapping) for mapping in mappings_payload],
+ menu=ModelHubMenuConfig.from_payload(menu_payload) if menu_payload is not None else None,
+ )
+
+ def to_payload(self) -> dict:
+ return {
+ "backend": self.backend,
+ "mode": self.mode,
+ "menu_kind": self.menu_kind,
+ "mappings": [mapping.to_payload() for mapping in self.mappings],
+ "menu": self.menu.to_payload() if self.menu else None,
+ }
+
+
+@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")
+ }
+ )
+ subscription_hub_experimental: bool = False
+
+ @classmethod
+ def fresh(cls) -> "ModelHubConfig":
+ return cls(
+ agents={
+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")
+ for backend in ("claude", "codex", "opencode")
+ }
+ )
+
+ @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):
+ raise ValueError("Config 'model_hub.subscription_hub_experimental' must be a boolean")
+ sources = [ModelHubSourceConfig.from_payload(source) for source in sources_payload]
+ 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(),
+ expected_backend=backend,
+ )
+ for backend in ("claude", "codex", "opencode")
+ }
+ for source in sources:
+ if source.kind == "subscription" and source.supply_channel == "hub":
+ if not experimental or not source.experimental_consent_at:
+ 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(
+ sources=sources,
+ priority_order=list(priority_order),
+ agents=agents,
+ subscription_hub_experimental=experimental,
+ )
+
+ 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")},
+ "subscription_hub_experimental": self.subscription_hub_experimental,
+ }
+
+
@dataclass
class UiConfig:
setup_host: str = "127.0.0.1"
@@ -423,6 +832,7 @@ class V2Config:
slack: SlackConfig
runtime: RuntimeConfig
agents: AgentsConfig
+ model_hub: ModelHubConfig = field(default_factory=ModelHubConfig)
platform: str = "slack"
platforms: PlatformsConfig = field(default_factory=PlatformsConfig)
discord: Optional[DiscordConfig] = None
@@ -574,6 +984,14 @@ class V2Config:
avault=avault,
)
+ model_hub_payload = payload.get("model_hub")
+ if model_hub_payload is None:
+ # Existing installs predate Model Hub and must remain in Direct mode
+ # until the user explicitly migrates. Fresh defaults seed Hub mode.
+ model_hub = ModelHubConfig()
+ else:
+ model_hub = ModelHubConfig.from_payload(model_hub_payload)
+
ui_payload = payload.get("ui") or {}
if not isinstance(ui_payload, dict):
raise ValueError("Config 'ui' must be an object")
@@ -709,6 +1127,7 @@ class V2Config:
platform_configs={key: value for key, value in platform_configs.items() if value is not None},
runtime=runtime,
agents=agents,
+ model_hub=model_hub,
gateway=gateway,
ui=ui,
remote_access=remote_access,
@@ -770,6 +1189,7 @@ class V2Config:
"codex": self.agents.codex.__dict__,
"avault": self.agents.avault.__dict__,
},
+ "model_hub": self.model_hub.to_payload(),
"gateway": self.gateway.__dict__ if self.gateway else None,
"ui": self.ui.__dict__,
"remote_access": {
diff --git a/core/handlers/model_hub/__init__.py b/core/handlers/model_hub/__init__.py
new file mode 100644
index 000000000..be2e2d1c2
--- /dev/null
+++ b/core/handlers/model_hub/__init__.py
@@ -0,0 +1,6 @@
+"""Model Hub configuration, resolution policy, and API services."""
+
+from .adapter import EngineAdapter
+from .service import ModelHubError, ModelHubService, create_default_service
+
+__all__ = ["EngineAdapter", "ModelHubError", "ModelHubService", "create_default_service"]
diff --git a/core/handlers/model_hub/classification.py b/core/handlers/model_hub/classification.py
new file mode 100644
index 000000000..f5da47edf
--- /dev/null
+++ b/core/handlers/model_hub/classification.py
@@ -0,0 +1,86 @@
+"""Canonical, engine-independent Model Hub error classification."""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+from typing import Literal, Optional
+
+from .adapter import RawCallOutcome, RawOutcomeKind
+
+ResolutionAction = Literal["return", "surface", "refresh", "fallback"]
+ResolutionReason = Literal["quota_exhausted", "rate_limited", "server_error", "network"]
+
+_SURFACE_PATTERNS = re.compile(
+ r"(?:invalid[_ -]?(?:request|parameter)|validation[_ -]?error|context[_ -]?length|"
+ r"unsupported[_ -]?(?:protocol|tool)|protocol[_ -]?(?:error|mismatch)|"
+ r"tool[_ -]?(?:compat|choice|schema|use)|malformed[_ -]?(?:request|schema))",
+ re.IGNORECASE,
+)
+_QUOTA_PATTERNS = re.compile(
+ r"(?:quota[_ -]?(?:exhausted|exceeded)|insufficient[_ -]?(?:quota|credits)|"
+ r"billing[_ -]?(?:limit|exhausted)|usage[_ -]?limit|credit[_ -]?balance)",
+ re.IGNORECASE,
+)
+
+
+@dataclass(frozen=True)
+class ResolutionDecision:
+ action: ResolutionAction
+ reason: Optional[ResolutionReason] = None
+ error_code: Optional[str] = None
+ cooldown_seconds: int = 0
+
+
+def _error_text(outcome: RawCallOutcome) -> str:
+ return " ".join(value for value in (outcome.error_code, outcome.redacted_message) if isinstance(value, str))
+
+
+def classify_outcome(
+ outcome: RawCallOutcome,
+ *,
+ refresh_attempted: bool = False,
+) -> ResolutionDecision:
+ """Apply the signed taxonomy without persisting or exposing raw errors."""
+
+ if outcome.kind == RawOutcomeKind.SUCCESS:
+ return ResolutionDecision("return")
+
+ # A partial stream is already externally observable. Any transparent retry
+ # could duplicate tokens or tool calls, regardless of the failure category.
+ if outcome.stream_started:
+ return ResolutionDecision("surface", error_code="stream_interrupted")
+
+ if outcome.kind in {RawOutcomeKind.NETWORK_ERROR, RawOutcomeKind.TIMEOUT}:
+ return ResolutionDecision("fallback", reason="network", cooldown_seconds=30)
+ if outcome.kind == RawOutcomeKind.PROTOCOL_ERROR:
+ return ResolutionDecision("surface", error_code="upstream_protocol_error")
+
+ if outcome.http_status == 401:
+ if refresh_attempted:
+ return ResolutionDecision("surface", error_code="upstream_unauthorized")
+ return ResolutionDecision("refresh")
+
+ error_text = _error_text(outcome)
+ if _SURFACE_PATTERNS.search(error_text):
+ return ResolutionDecision("surface", error_code="upstream_request_invalid")
+
+ if _QUOTA_PATTERNS.search(error_text):
+ return ResolutionDecision(
+ "fallback",
+ reason="quota_exhausted",
+ cooldown_seconds=300,
+ )
+ if outcome.http_status == 429:
+ return ResolutionDecision(
+ "fallback",
+ reason="rate_limited",
+ cooldown_seconds=60,
+ )
+ if outcome.http_status is not None and 500 <= outcome.http_status < 600:
+ return ResolutionDecision(
+ "fallback",
+ reason="server_error",
+ cooldown_seconds=30,
+ )
+ return ResolutionDecision("surface", error_code="upstream_error")
diff --git a/core/handlers/model_hub/events.py b/core/handlers/model_hub/events.py
new file mode 100644
index 000000000..ea0a3360a
--- /dev/null
+++ b/core/handlers/model_hub/events.py
@@ -0,0 +1,169 @@
+"""Bounded, credential-free persistence for Model Hub resolution events."""
+
+from __future__ import annotations
+
+import json
+import os
+import re
+import tempfile
+import threading
+import uuid
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Literal, Optional
+
+from vibe.i18n import t as i18n_t
+
+EventAgent = Literal["claude", "codex", "opencode", "system"]
+EventKind = Literal["switch", "cooldown", "recover", "skip", "mapping_applied", "channel_switch"]
+EventReason = Literal["quota_exhausted", "rate_limited", "server_error", "network", "recovery", "manual", "mapping"]
+BillingNote = Literal["entered_metered", "left_metered"]
+
+_CREDENTIAL_PATTERNS = (
+ re.compile(r"(?i)\b(?:sk|rk|pk|sess|token)[-_][a-z0-9_-]{8,}\b"),
+ re.compile(
+ r"(?i)\b(?:authorization|api[_ -]?key|access[_ -]?token)\s*[:=]\s*"
+ r"(?:sk[-_][a-z0-9_-]{8,}|[a-z0-9._~+/=-]{16,})"
+ ),
+ re.compile(r"(?i)\bbearer\s+[a-z0-9._~+/=-]{8,}"),
+)
+
+
+def redact_credential_material(value: str) -> str:
+ redacted = value
+ for pattern in _CREDENTIAL_PATTERNS:
+ redacted = pattern.sub("[redacted]", redacted)
+ return redacted
+
+
+def contains_credential_material(value: object) -> bool:
+ rendered = json.dumps(value, ensure_ascii=False, sort_keys=True)
+ return any(pattern.search(rendered) for pattern in _CREDENTIAL_PATTERNS)
+
+
+@dataclass(frozen=True)
+class ResolutionEvent:
+ id: str
+ ts: str
+ agent: EventAgent
+ kind: EventKind
+ model_id: str
+ reason: EventReason
+ human_zh: str
+ human_en: str
+ from_source: Optional[str] = None
+ to_source: Optional[str] = None
+ billing_note: Optional[BillingNote] = None
+
+ def to_payload(self) -> dict:
+ return {
+ "id": self.id,
+ "ts": self.ts,
+ "agent": self.agent,
+ "kind": self.kind,
+ "model_id": self.model_id,
+ "from_source": self.from_source,
+ "to_source": self.to_source,
+ "reason": self.reason,
+ "billing_note": self.billing_note,
+ "human_zh": self.human_zh,
+ "human_en": self.human_en,
+ }
+
+
+def build_resolution_event(
+ *,
+ agent: EventAgent,
+ kind: EventKind,
+ model_id: str,
+ reason: EventReason,
+ from_source: Optional[str] = None,
+ to_source: Optional[str] = None,
+ from_label: Optional[str] = None,
+ to_label: Optional[str] = None,
+ billing_note: Optional[BillingNote] = None,
+ now: Optional[datetime] = None,
+) -> ResolutionEvent:
+ safe_from = redact_credential_material(from_label or from_source or "")
+ safe_to = redact_credential_material(to_label or to_source or "")
+
+ def render(lang: str) -> str:
+ template = {
+ "switch": "switch",
+ "cooldown": "cooldown",
+ "recover": "recover",
+ }.get(kind, "status")
+ return i18n_t(
+ f"modelHub.events.{template}",
+ lang,
+ from_source=safe_from or i18n_t("modelHub.events.sourceFallback", lang),
+ to_source=safe_to or i18n_t("modelHub.events.sourceFallback", lang),
+ reason=i18n_t(f"modelHub.events.reason.{reason}", lang),
+ )
+
+ human_en = render("en")
+ human_zh = render("zh")
+ event = ResolutionEvent(
+ id=f"evt_{uuid.uuid4().hex}",
+ ts=(now or datetime.now(timezone.utc)).isoformat(),
+ agent=agent,
+ kind=kind,
+ model_id=model_id,
+ reason=reason,
+ human_zh=human_zh[:200],
+ human_en=human_en[:200],
+ from_source=from_source,
+ to_source=to_source,
+ billing_note=billing_note,
+ )
+ if contains_credential_material(event.to_payload()):
+ raise ValueError("Resolution event contains credential material")
+ return event
+
+
+class BoundedEventLog:
+ def __init__(self, path: Path, *, max_entries: int = 500):
+ self.path = path
+ self.max_entries = max_entries
+ self._lock = threading.RLock()
+
+ def _read(self) -> list[dict]:
+ if not self.path.exists():
+ return []
+ try:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return []
+ if not isinstance(payload, list):
+ return []
+ return [item for item in payload if isinstance(item, dict) and not contains_credential_material(item)]
+
+ def _write(self, payload: list[dict]) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ content = json.dumps(payload[-self.max_entries :], ensure_ascii=False, separators=(",", ":"))
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=self.path.parent, delete=False) as tmp:
+ tmp.write(content)
+ tmp.flush()
+ os.fsync(tmp.fileno())
+ temp_name = tmp.name
+ os.chmod(temp_name, 0o600)
+ os.replace(temp_name, self.path)
+
+ def append(self, event: ResolutionEvent) -> None:
+ payload = event.to_payload()
+ if contains_credential_material(payload):
+ raise ValueError("Resolution event contains credential material")
+ with self._lock:
+ events = self._read()
+ events.append(payload)
+ self._write(events)
+
+ def list(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:
+ bounded_limit = max(1, min(limit, 100))
+ with self._lock:
+ newest_first = list(reversed(self._read()))
+ if before is not None:
+ index = next((idx for idx, event in enumerate(newest_first) if event.get("id") == before), None)
+ newest_first = newest_first[index + 1 :] if index is not None else []
+ return newest_first[:bounded_limit]
diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.py
new file mode 100644
index 000000000..1cbfd09d4
--- /dev/null
+++ b/core/handlers/model_hub/identifiers.py
@@ -0,0 +1,39 @@
+"""Stable Model Hub model identifiers shared by API and backend lanes."""
+
+from __future__ import annotations
+
+# Vendors with native, stable OpenCode provider identifiers. Compatible relays
+# and unrecognized vendors share the frozen contract's single custom/ prefix.
+STANDARD_OPENCODE_VENDOR_IDS = frozenset(
+ {
+ "anthropic",
+ "deepseek",
+ "github-copilot",
+ "google",
+ "groq",
+ "kimi",
+ "minimax",
+ "mistral",
+ "moonshot",
+ "openai",
+ "openrouter",
+ "together",
+ "xai",
+ "zhipuai",
+ }
+)
+
+
+def opencode_provider_id(vendor: str) -> str:
+ return vendor if vendor in STANDARD_OPENCODE_VENDOR_IDS else "custom"
+
+
+def opencode_model_id(vendor: str, model_id: str) -> str:
+ return f"{opencode_provider_id(vendor)}/{model_id}"
+
+
+def parse_opencode_model_id(identifier: str) -> tuple[str, str]:
+ provider, separator, model_id = identifier.partition("/")
+ if not separator or not provider or not model_id:
+ raise ValueError("Invalid OpenCode model identifier")
+ return provider, model_id
diff --git a/core/handlers/model_hub/oauth.py b/core/handlers/model_hub/oauth.py
new file mode 100644
index 000000000..6cd3817c4
--- /dev/null
+++ b/core/handlers/model_hub/oauth.py
@@ -0,0 +1,136 @@
+"""OAuth channel dispatch state for Model Hub."""
+
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+import threading
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Literal, Optional, Protocol
+
+from .adapter import OAuthFlowState
+
+OAuthChannel = Literal["native_cli", "hub"]
+
+
+@dataclass(frozen=True)
+class OAuthFlowBinding:
+ channel: OAuthChannel
+ source_id: Optional[str]
+ vendor: Optional[str]
+
+
+class OAuthAdapter(Protocol):
+ async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState: ...
+
+ async def oauth_status(self, flow_id: str) -> OAuthFlowState: ...
+
+ async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState: ...
+
+ async def cancel_oauth(self, flow_id: str) -> None: ...
+
+
+class NativeOAuthUnavailableError(RuntimeError):
+ pass
+
+
+class UnavailableNativeOAuthAdapter:
+ """L3 replaces this adapter when native CLI OAuth is wired."""
+
+ async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:
+ raise NativeOAuthUnavailableError
+
+ async def oauth_status(self, flow_id: str) -> OAuthFlowState:
+ raise NativeOAuthUnavailableError
+
+ async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:
+ raise NativeOAuthUnavailableError
+
+ async def cancel_oauth(self, flow_id: str) -> None:
+ raise NativeOAuthUnavailableError
+
+
+class OAuthFlowRegistry:
+ """Persist the non-secret source identity associated with each in-flight flow."""
+
+ def __init__(self, path: Path, *, max_entries: int = 100):
+ self.path = path
+ self.max_entries = max_entries
+ self._lock = threading.RLock()
+
+ def _read(self) -> dict[str, OAuthFlowBinding]:
+ if not self.path.exists():
+ return {}
+ try:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ if not isinstance(payload, dict):
+ return {}
+ flows = {}
+ for flow_id, value in payload.items():
+ if not isinstance(flow_id, str):
+ continue
+ if isinstance(value, str) and value in {"native_cli", "hub"}:
+ flows[flow_id] = OAuthFlowBinding(value, None, None)
+ continue
+ if not isinstance(value, dict):
+ continue
+ channel = value.get("channel")
+ source_id = value.get("source_id")
+ vendor = value.get("vendor")
+ if (
+ channel in {"native_cli", "hub"}
+ and (source_id is None or (isinstance(source_id, str) and source_id))
+ and (vendor is None or (isinstance(vendor, str) and vendor))
+ ):
+ flows[flow_id] = OAuthFlowBinding(channel, source_id, vendor)
+ return flows
+
+ def _write(self, payload: dict[str, OAuthFlowBinding]) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ bounded = dict(list(payload.items())[-self.max_entries :])
+ content = json.dumps(
+ {
+ flow_id: {
+ "channel": binding.channel,
+ "source_id": binding.source_id,
+ "vendor": binding.vendor,
+ }
+ for flow_id, binding in bounded.items()
+ },
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=self.path.parent, delete=False) as tmp:
+ tmp.write(content)
+ tmp.flush()
+ os.fsync(tmp.fileno())
+ temp_name = tmp.name
+ os.chmod(temp_name, 0o600)
+ os.replace(temp_name, self.path)
+
+ def remember(self, flow_id: str, channel: OAuthChannel, source_id: str, vendor: str) -> None:
+ with self._lock:
+ flows = self._read()
+ flows.pop(flow_id, None)
+ flows[flow_id] = OAuthFlowBinding(channel, source_id, vendor)
+ self._write(flows)
+
+ def channel(self, flow_id: str) -> OAuthChannel | None:
+ binding = self.binding(flow_id)
+ return binding.channel if binding is not None else None
+
+ def binding(self, flow_id: str) -> OAuthFlowBinding | None:
+ with self._lock:
+ return self._read().get(flow_id)
+
+ def forget(self, flow_id: str) -> None:
+ with self._lock:
+ flows = self._read()
+ if flow_id not in flows:
+ return
+ flows.pop(flow_id)
+ self._write(flows)
diff --git a/core/handlers/model_hub/revocations.py b/core/handlers/model_hub/revocations.py
new file mode 100644
index 000000000..dee985d96
--- /dev/null
+++ b/core/handlers/model_hub/revocations.py
@@ -0,0 +1,76 @@
+"""Crash-recoverable journal for engine-owned credential revocation."""
+
+from __future__ import annotations
+
+import json
+import os
+import tempfile
+import threading
+from dataclasses import dataclass
+from pathlib import Path
+
+
+@dataclass(frozen=True)
+class PendingCredentialRevocation:
+ source_id: str
+ credential_ref: str
+
+
+class CredentialRevocationJournal:
+ """Persist opaque credential refs until their engine cleanup succeeds."""
+
+ def __init__(self, path: Path):
+ self.path = path
+ self._lock = threading.RLock()
+
+ def _read(self) -> list[PendingCredentialRevocation]:
+ if not self.path.exists():
+ return []
+ try:
+ payload = json.loads(self.path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return []
+ if not isinstance(payload, list):
+ return []
+ return [
+ PendingCredentialRevocation(
+ source_id=item["source_id"],
+ credential_ref=item["credential_ref"],
+ )
+ for item in payload
+ if isinstance(item, dict)
+ and isinstance(item.get("source_id"), str)
+ and isinstance(item.get("credential_ref"), str)
+ ]
+
+ def _write(self, entries: list[PendingCredentialRevocation]) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ payload = [
+ {"source_id": entry.source_id, "credential_ref": entry.credential_ref}
+ for entry in entries
+ ]
+ content = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
+ with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=self.path.parent, delete=False) as tmp:
+ tmp.write(content)
+ tmp.flush()
+ os.fsync(tmp.fileno())
+ temp_name = tmp.name
+ os.chmod(temp_name, 0o600)
+ os.replace(temp_name, self.path)
+
+ def add(self, source_id: str, credential_ref: str) -> None:
+ with self._lock:
+ entries = [entry for entry in self._read() if entry.source_id != source_id]
+ entries.append(PendingCredentialRevocation(source_id, credential_ref))
+ self._write(entries)
+
+ def remove(self, source_id: str) -> None:
+ with self._lock:
+ entries = self._read()
+ remaining = [entry for entry in entries if entry.source_id != source_id]
+ if len(remaining) != len(entries):
+ self._write(remaining)
+
+ def list(self) -> list[PendingCredentialRevocation]:
+ with self._lock:
+ return self._read()
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
new file mode 100644
index 000000000..362e46d49
--- /dev/null
+++ b/core/handlers/model_hub/service.py
@@ -0,0 +1,1379 @@
+"""Model Hub aggregate service used by REST routes and backend injection."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import uuid
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+from typing import Any, Callable, Literal, Mapping, Optional, Protocol, cast
+from urllib.parse import parse_qsl, urlsplit
+
+from config import paths
+from config.v2_config import (
+ CONFIG_LOCK,
+ ModelHubAgentSupplyConfig,
+ ModelHubConfig,
+ ModelHubMappingConfig,
+ ModelHubMenuConfig,
+ ModelHubModelConfig,
+ ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
+ ModelHubSourceUsageConfig,
+ V2Config,
+)
+from core.services.settings import default_config
+from vibe.backend_model_catalog import backend_model_entries, load_bundled_catalog
+
+from .adapter import (
+ EngineAdapter,
+ EngineHealth,
+ EngineStatus,
+ InvokeHandle,
+ OAuthFlowState,
+ OriginNotAllowedError,
+ RawCallOutcome,
+ SourceBinding,
+)
+from .classification import ResolutionDecision, classify_outcome
+from .events import (
+ BoundedEventLog,
+ EventAgent,
+ EventReason,
+ build_resolution_event,
+ contains_credential_material,
+)
+from .identifiers import opencode_model_id, opencode_provider_id, parse_opencode_model_id
+from .oauth import (
+ NativeOAuthUnavailableError,
+ OAuthAdapter,
+ OAuthChannel,
+ OAuthFlowBinding,
+ OAuthFlowRegistry,
+ UnavailableNativeOAuthAdapter,
+)
+from .revocations import CredentialRevocationJournal
+
+CONTRACT_VERSION = 1
+logger = logging.getLogger(__name__)
+
+_NATIVE_VENDOR_BACKENDS = {"anthropic": "claude", "openai": "codex"}
+_CREDENTIAL_QUERY_KEYS = {
+ "access_token",
+ "api_key",
+ "apikey",
+ "auth",
+ "authorization",
+ "bearer",
+ "credential",
+ "key",
+ "password",
+ "passwd",
+ "secret",
+ "sig",
+ "signature",
+ "token",
+}
+
+_RUNTIME_MANIFEST = {
+ "name": "cliproxyapi",
+ "version": "v7.2.95",
+ "source_sha": "f71ec0eb6776854457892452cf28c47f0d658251",
+ "assets": [
+ {
+ "platform": "darwin-arm64",
+ "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/CLIProxyAPI_7.2.95_darwin_aarch64.tar.gz",
+ "size_bytes": 14384655,
+ "sha256": "c7ccc28b7db5d1799999a9e22725ccc6bd0e36d9aa023da6b52b7c1a71aad978",
+ },
+ {
+ "platform": "linux-amd64",
+ "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/CLIProxyAPI_7.2.95_linux_amd64.tar.gz",
+ "size_bytes": 15401775,
+ "sha256": "826604e2dbf11913b0f373047f7bca1829eb2bab8a45d3a1916cc2534c7a9fd5",
+ },
+ ],
+}
+
+
+class ModelHubError(Exception):
+ def __init__(self, code: str, *, status: int = 400):
+ detail_key = f"modelHub.errors.{code}"
+ super().__init__(detail_key)
+ self.code = code
+ self.status = status
+ self.detail = detail_key
+
+
+class EngineUnavailableError(RuntimeError):
+ pass
+
+
+class ModelHubConfigStore(Protocol):
+ def load(self) -> ModelHubConfig: ...
+
+ def save(self, config: ModelHubConfig) -> None: ...
+
+
+class V2ModelHubConfigStore:
+ def load(self) -> ModelHubConfig:
+ try:
+ return V2Config.load().model_hub
+ except FileNotFoundError:
+ return default_config().model_hub
+
+ def save(self, model_hub: ModelHubConfig) -> None:
+ with CONFIG_LOCK:
+ try:
+ config = V2Config.load()
+ except FileNotFoundError:
+ config = default_config()
+ config.model_hub = model_hub
+ config.save()
+
+
+class UnavailableEngineAdapter:
+ """Fail-closed placeholder until the L1 runtime implementation is present."""
+
+ async def ensure_installed(self) -> EngineStatus:
+ return await self.status()
+
+ async def start(self) -> EngineStatus:
+ raise EngineUnavailableError
+
+ async def stop(self) -> None:
+ return None
+
+ async def status(self) -> EngineStatus:
+ return EngineStatus(
+ health=EngineHealth.NOT_INSTALLED,
+ installed_version=None,
+ verified=False,
+ listen_host="127.0.0.1",
+ listen_port=None,
+ last_check_iso=None,
+ )
+
+ async def gateway_token(self) -> str:
+ raise EngineUnavailableError
+
+ async def provision_credential(self, vendor: str, protocol: str, secret: str, base_url: str | None) -> str:
+ raise EngineUnavailableError
+
+ async def revoke_credential(self, credential_ref: str) -> None:
+ raise EngineUnavailableError
+
+ async def sync_sources(self, bindings) -> None:
+ raise EngineUnavailableError
+
+ async def discover_models(self, vendor: str, protocol: str, base_url: str | None, credential_ref: str):
+ raise EngineUnavailableError
+
+ async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:
+ raise EngineUnavailableError
+
+ async def oauth_status(self, flow_id: str) -> OAuthFlowState:
+ raise EngineUnavailableError
+
+ async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:
+ raise EngineUnavailableError
+
+ async def cancel_oauth(self, flow_id: str) -> None:
+ raise EngineUnavailableError
+
+ async def invoke(
+ self,
+ source_id: str,
+ model_id: str,
+ request: Mapping[str, Any],
+ stream: bool,
+ origin: str,
+ ) -> InvokeHandle:
+ raise EngineUnavailableError
+
+
+@dataclass(frozen=True)
+class ResolvedInvocation:
+ source_id: str
+ model_id: str
+ handle: Optional[InvokeHandle]
+ outcome: Optional[RawCallOutcome]
+ supply_channel: Literal["native_cli", "hub"] = "hub"
+
+
+def _utc_now() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def _source_id() -> str:
+ return f"src_{uuid.uuid4().hex[:12]}"
+
+
+def _parse_datetime(value: str) -> datetime:
+ return datetime.fromisoformat(value.replace("Z", "+00:00"))
+
+
+def _mask_credential(value: str) -> str:
+ """Create the one-way display mask frozen by the source contract."""
+ normalized = value.strip()
+ if len(normalized) <= 4:
+ return "…" + ("•" * len(normalized))
+ prefix_length = min(7, len(normalized) - 5)
+ return f"{normalized[:prefix_length]}…{normalized[-4:]}"
+
+
+def _validated_base_url(value: object) -> Optional[str]:
+ if value is None:
+ return None
+ if not isinstance(value, str) or not value.strip():
+ raise ModelHubError("discovery_failed")
+ try:
+ parsed = urlsplit(value)
+ hostname = parsed.hostname
+ except ValueError:
+ raise ModelHubError("discovery_failed") from None
+ if (
+ parsed.scheme.lower() not in {"http", "https"}
+ or not hostname
+ or parsed.username is not None
+ or parsed.password is not None
+ or parsed.fragment
+ or contains_credential_material(value)
+ ):
+ raise ModelHubError("discovery_failed")
+ for key, _ in parse_qsl(parsed.query, keep_blank_values=True):
+ normalized = key.strip().lower().replace("-", "_").replace(".", "_")
+ if normalized in _CREDENTIAL_QUERY_KEYS or any(
+ marker in normalized
+ for marker in (
+ "api_key",
+ "access_token",
+ "auth_token",
+ "token",
+ "authorization",
+ "signature",
+ "secret",
+ "password",
+ "credential",
+ )
+ ):
+ raise ModelHubError("discovery_failed")
+ return value
+
+
+def _native_model_ids(vendor: str) -> tuple[str, ...]:
+ backend = _NATIVE_VENDOR_BACKENDS.get(vendor)
+ if backend is None:
+ return ()
+ catalog = load_bundled_catalog()
+ return tuple(entry["id"] for entry in backend_model_entries(backend, catalog))
+
+
+def _default_protocol(vendor: str) -> str:
+ if vendor == "anthropic":
+ return "anthropic"
+ if vendor == "openai":
+ return "openai_responses"
+ return "openai_compatible"
+
+
+def _allowed_origins(source: ModelHubSourceConfig) -> tuple[str, ...]:
+ if source.kind == "api_key":
+ return ()
+ if source.vendor == "anthropic":
+ return ("claude",)
+ if source.vendor == "openai":
+ return ("codex",)
+ return ()
+
+
+def _binding(source: ModelHubSourceConfig) -> SourceBinding:
+ if not source.credential_ref:
+ raise ModelHubError("engine_down", status=503)
+ allowed_origins = _allowed_origins(source)
+ if source.kind == "subscription" and not allowed_origins:
+ raise ModelHubError("mode_switch_blocked", status=409)
+ return SourceBinding(
+ source_id=source.id,
+ vendor=source.vendor,
+ protocol=source.protocol,
+ base_url=source.base_url,
+ credential_ref=source.credential_ref,
+ allowed_origins=allowed_origins,
+ model_ids=tuple(model.id for model in source.models),
+ )
+
+
+def _oauth_payload(flow: OAuthFlowState, *, channel: str) -> dict:
+ return {
+ "flow_id": flow.flow_id,
+ "source_id": flow.source_id,
+ "vendor": flow.vendor,
+ "channel": channel,
+ "state": flow.state,
+ "presentation": {
+ "auth_url": flow.auth_url,
+ "device_code": flow.device_code,
+ "expects": flow.expects,
+ "instructions_key": flow.instructions_key,
+ },
+ "error_key": flow.error_key,
+ "expires_at": flow.expires_at_iso,
+ }
+
+
+def _runtime_payload(status: EngineStatus) -> dict:
+ return {
+ "manifest": _RUNTIME_MANIFEST,
+ "status": {
+ "installed_version": status.installed_version,
+ "verified": status.verified,
+ "listening": (
+ {"host": status.listen_host, "port": status.listen_port}
+ if status.listen_port is not None
+ else None
+ ),
+ "health": status.health.value,
+ "last_check": status.last_check_iso,
+ },
+ }
+
+
+class ModelHubService:
+ def __init__(
+ self,
+ *,
+ store: ModelHubConfigStore,
+ adapter: EngineAdapter,
+ events: BoundedEventLog,
+ native_oauth_adapter: Optional[OAuthAdapter] = None,
+ oauth_flows: Optional[OAuthFlowRegistry] = None,
+ revocations: Optional[CredentialRevocationJournal] = None,
+ now: Callable[[], datetime] = _utc_now,
+ ):
+ self.store = store
+ self.adapter = adapter
+ self.events = events
+ self.native_oauth_adapter = native_oauth_adapter or UnavailableNativeOAuthAdapter()
+ self.oauth_flows = oauth_flows or OAuthFlowRegistry(paths.get_state_dir() / "model_hub_oauth_flows.json")
+ self.revocations = revocations or CredentialRevocationJournal(
+ paths.get_state_dir() / "model_hub_pending_revocations.json"
+ )
+ self.now = now
+ self._mutation_lock = asyncio.Lock()
+ self._engine_synced = False
+
+ @staticmethod
+ def _source(config: ModelHubConfig, source_id: str) -> ModelHubSourceConfig:
+ source = next((item for item in config.sources if item.id == source_id), None)
+ if source is None:
+ raise ModelHubError("source_not_found", status=404)
+ return source
+
+ @staticmethod
+ def _agent(config: ModelHubConfig, backend: str) -> ModelHubAgentSupplyConfig:
+ agent = config.agents.get(backend)
+ if agent is None:
+ raise ModelHubError("mode_switch_blocked")
+ return agent
+
+ async def _engine_call(self, awaitable):
+ try:
+ return await awaitable
+ except OriginNotAllowedError:
+ raise ModelHubError("mode_switch_blocked", status=409) from None
+ except EngineUnavailableError:
+ raise ModelHubError("engine_down", status=503) from None
+ except NativeOAuthUnavailableError:
+ raise ModelHubError("engine_down", status=503) from None
+ except ModelHubError:
+ raise
+ except Exception:
+ # Engine failures may carry upstream context. Never expose or log it.
+ raise ModelHubError("engine_down", status=503) from None
+
+ async def _oauth_call(self, awaitable, *, flow_id: Optional[str] = None):
+ try:
+ return await awaitable
+ except KeyError:
+ if flow_id is not None:
+ self.oauth_flows.forget(flow_id)
+ raise ModelHubError("flow_not_found", status=404) from None
+ except (EngineUnavailableError, NativeOAuthUnavailableError):
+ raise ModelHubError("engine_down", status=503) from None
+ except ModelHubError:
+ raise
+ except Exception:
+ raise ModelHubError("engine_down", status=503) from None
+
+ def _bindings(self, config: ModelHubConfig) -> list[SourceBinding]:
+ return [_binding(source) for source in config.sources if source.supply_channel == "hub"]
+
+ @staticmethod
+ def _clone_config(config: ModelHubConfig) -> ModelHubConfig:
+ return ModelHubConfig.from_payload(config.to_payload())
+
+ async def _sync_sources(self, config: ModelHubConfig, *, force_empty: bool = False) -> None:
+ bindings = self._bindings(config)
+ if not bindings and not force_empty:
+ return
+ await self._engine_call(self.adapter.sync_sources(bindings))
+
+ async def _commit_synced(self, previous: ModelHubConfig, updated: ModelHubConfig) -> None:
+ """Persist the authoritative config before updating its engine projection."""
+
+ self._engine_synced = False
+ previous_bindings = self._bindings(previous)
+ updated_bindings = self._bindings(updated)
+ self.store.save(updated)
+ try:
+ await self._sync_sources(updated, force_empty=bool(previous_bindings))
+ except Exception:
+ self.store.save(previous)
+ try:
+ await self._sync_sources(previous, force_empty=bool(updated_bindings))
+ except ModelHubError:
+ self._engine_synced = False
+ else:
+ self._engine_synced = True
+ raise
+ self._engine_synced = True
+
+ async def _ensure_engine_synced(self) -> None:
+ pending_revocations = self.revocations.list()
+ if self._engine_synced and not pending_revocations:
+ return
+ async with self._mutation_lock:
+ pending_revocations = self.revocations.list()
+ if self._engine_synced and not pending_revocations:
+ return
+ config = self.store.load()
+ await self._sync_sources(config, force_empty=bool(pending_revocations))
+ active_source_ids = {source.id for source in config.sources}
+ for pending in pending_revocations:
+ if pending.source_id in active_source_ids:
+ self.revocations.remove(pending.source_id)
+ continue
+ await self._engine_call(self.adapter.revoke_credential(pending.credential_ref))
+ self.revocations.remove(pending.source_id)
+ self._engine_synced = True
+
+ def _oauth_adapter(self, channel: OAuthChannel) -> OAuthAdapter:
+ if channel == "hub":
+ return self.adapter
+ return self.native_oauth_adapter
+
+ def _oauth_channel(self, flow_id: str) -> OAuthChannel:
+ return self._oauth_binding(flow_id).channel
+
+ def _oauth_binding(self, flow_id: str) -> OAuthFlowBinding:
+ binding = self.oauth_flows.binding(flow_id)
+ if binding is None:
+ raise ModelHubError("flow_not_found", status=404)
+ return binding
+
+ async def _oauth_status(self, flow_id: str, channel: OAuthChannel) -> OAuthFlowState:
+ return await self._oauth_call(
+ self._oauth_adapter(channel).oauth_status(flow_id),
+ flow_id=flow_id,
+ )
+
+ async def _discover(self, source: ModelHubSourceConfig) -> list[str]:
+ if not source.credential_ref:
+ return [model.id for model in source.models]
+ return list(
+ await self._engine_call(
+ self.adapter.discover_models(
+ source.vendor,
+ source.protocol,
+ source.base_url,
+ source.credential_ref,
+ )
+ )
+ )
+
+ def _record_event(self, **event_fields: Any) -> None:
+ try:
+ self.events.append(build_resolution_event(**event_fields))
+ except Exception:
+ # Resolution telemetry is best effort and must never affect routing.
+ logger.warning("Failed to persist Model Hub resolution event")
+
+ async def _rollback_credential(self, source_id: str, credential_ref: str) -> None:
+ self.revocations.add(source_id, credential_ref)
+ try:
+ await self.adapter.revoke_credential(credential_ref)
+ except Exception:
+ return
+ try:
+ self.revocations.remove(source_id)
+ except OSError:
+ # A replayed revoke is safer than losing the only durable ref.
+ pass
+
+ def _raise_if_flow_expired(self, flow_id: str, flow: OAuthFlowState) -> None:
+ if not flow.expires_at_iso or flow.state in {"success", "failed", "cancelled"}:
+ return
+ try:
+ expired = _parse_datetime(flow.expires_at_iso) <= self.now()
+ except ValueError:
+ return
+ if expired:
+ self.oauth_flows.forget(flow_id)
+ raise ModelHubError("flow_expired", status=410)
+
+ def _apply_discovered_models(
+ self,
+ source: ModelHubSourceConfig,
+ manual_models: list[ModelHubModelConfig],
+ discovered: list[str],
+ ) -> None:
+ if any(
+ not isinstance(model_id, str)
+ or not model_id
+ or contains_credential_material(model_id)
+ for model_id in discovered
+ ):
+ raise ModelHubError("discovery_failed")
+ discovered_at = self.now().isoformat()
+ manual_model_ids = {model.id for model in manual_models}
+ source.models = [
+ ModelHubModelConfig(id=model_id, provenance="discovered", discovered_at=discovered_at)
+ for model_id in discovered
+ if model_id not in manual_model_ids
+ ] + manual_models
+
+ async def _commit_new_source_locked(
+ self,
+ source: ModelHubSourceConfig,
+ *,
+ consented: bool,
+ previous: Optional[ModelHubConfig] = None,
+ ) -> None:
+ previous = previous or self.store.load()
+ config = self._clone_config(previous)
+ 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)
+ if consented:
+ config.subscription_hub_experimental = True
+ await self._commit_synced(previous, config)
+
+ async def _create_oauth_source(
+ self,
+ source: ModelHubSourceConfig,
+ manual_models: list[ModelHubModelConfig],
+ *,
+ oauth_ref: str,
+ channel: Literal["native_cli", "hub"],
+ vendor: str,
+ consented: bool,
+ ) -> dict:
+ # Claim and consume a completed flow under the aggregate lock. This
+ # prevents a duplicate browser retry from revoking the winning source's
+ # credential while still retaining rollback ownership before discovery.
+ async with self._mutation_lock:
+ rollback_credential_ref: Optional[str] = None
+ persisted = False
+ try:
+ binding = self._oauth_binding(oauth_ref)
+ if binding.channel != channel:
+ raise ModelHubError("flow_not_found", status=404)
+ flow = await self._oauth_status(oauth_ref, binding.channel)
+ if flow.state != "success" or (channel == "hub" and not flow.credential_ref):
+ raise ModelHubError("flow_not_found", status=404)
+ if (
+ flow.vendor != vendor
+ or flow.vendor != binding.vendor
+ or flow.source_id != binding.source_id
+ ):
+ raise ModelHubError("flow_not_found", status=404)
+
+ source.id = flow.source_id
+ previous = self.store.load()
+ if any(item.id == source.id for item in previous.sources):
+ raise ModelHubError("migration_item_conflict", status=409)
+ if channel == "hub":
+ source.credential_ref = cast(str, flow.credential_ref)
+ rollback_credential_ref = source.credential_ref
+
+ discovered = (
+ await self._discover(source)
+ if channel == "hub"
+ else list(_native_model_ids(vendor))
+ )
+ if channel == "native_cli" and not discovered:
+ raise ModelHubError("discovery_failed")
+ self._apply_discovered_models(source, manual_models, discovered)
+ await self._commit_new_source_locked(
+ source,
+ consented=consented,
+ previous=previous,
+ )
+ persisted = True
+ try:
+ self.oauth_flows.forget(oauth_ref)
+ except OSError:
+ pass
+ return source.to_payload()
+ except Exception:
+ if rollback_credential_ref is not None and not persisted:
+ await self._rollback_credential(source.id, rollback_credential_ref)
+ try:
+ self.oauth_flows.forget(oauth_ref)
+ except OSError:
+ pass
+ raise
+
+ 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]
+
+ async def create_source(self, payload: dict) -> dict:
+ if not isinstance(payload, dict):
+ raise ModelHubError("discovery_failed")
+ forbidden = {
+ "id",
+ "credential_ref",
+ "account_label",
+ "masked_credential",
+ "experimental_consent_at",
+ "state",
+ "usage",
+ } & set(payload)
+ if forbidden:
+ raise ModelHubError("discovery_failed")
+ kind = payload.get("kind")
+ vendor = payload.get("vendor")
+ display_name = payload.get("display_name") or vendor
+ if (
+ kind not in {"subscription", "api_key"}
+ or not isinstance(vendor, str)
+ or not vendor
+ or contains_credential_material(vendor)
+ ):
+ raise ModelHubError("discovery_failed")
+ if (
+ not isinstance(display_name, str)
+ or not display_name
+ or len(display_name) > 64
+ or contains_credential_material(display_name)
+ ):
+ raise ModelHubError("discovery_failed")
+ channel = payload.get("supply_channel") or ("native_cli" if kind == "subscription" else "hub")
+ if channel not in {"native_cli", "hub"} or (kind == "api_key" and channel != "hub"):
+ raise ModelHubError("discovery_failed")
+ if channel == "native_cli" and vendor not in _NATIVE_VENDOR_BACKENDS:
+ raise ModelHubError("discovery_failed")
+ consented = payload.get("experimental_consent") is True
+ if "experimental_consent" in payload and not isinstance(payload.get("experimental_consent"), bool):
+ raise ModelHubError("consent_required")
+ if kind == "subscription" and channel == "hub" and not consented:
+ raise ModelHubError("consent_required", status=409)
+ if consented and not (kind == "subscription" and channel == "hub"):
+ raise ModelHubError("consent_required")
+
+ protocol = payload.get("protocol") or _default_protocol(vendor)
+ billing = payload.get("billing") or ("monthly" if kind == "subscription" else "metered")
+ models_payload = payload.get("models", [])
+ if not isinstance(models_payload, list):
+ raise ModelHubError("discovery_failed")
+ base_url = _validated_base_url(payload.get("base_url"))
+ if kind == "subscription" and base_url is not None:
+ raise ModelHubError("discovery_failed")
+ try:
+ manual_models = [ModelHubModelConfig.from_payload(model) for model in models_payload]
+ if any(
+ model.provenance != "manual"
+ or contains_credential_material(model.id)
+ or contains_credential_material(model.display_name or "")
+ for model in manual_models
+ ):
+ raise ValueError("Client-declared source models must use manual provenance")
+ source = ModelHubSourceConfig(
+ id=_source_id(),
+ kind=kind,
+ vendor=vendor,
+ display_name=display_name,
+ protocol=protocol,
+ base_url=base_url,
+ supply_channel=channel,
+ experimental_consent_at=self.now().isoformat() if consented else None,
+ billing=billing,
+ state=ModelHubSourceStateConfig(status="standby"),
+ usage=ModelHubSourceUsageConfig(),
+ models=manual_models,
+ )
+ source = ModelHubSourceConfig.from_payload(source.to_payload())
+ except (TypeError, ValueError):
+ raise ModelHubError("discovery_failed") from None
+
+ credential_value = payload.get("key")
+ oauth_ref = payload.get("oauth_flow_ref")
+ if credential_value is not None:
+ if not isinstance(credential_value, str):
+ raise ModelHubError("discovery_failed")
+ credential_value = credential_value.strip()
+ if oauth_ref is not None and not isinstance(oauth_ref, str):
+ raise ModelHubError("flow_not_found", status=404)
+ if kind == "subscription" and credential_value is not None:
+ raise ModelHubError("discovery_failed")
+ if kind == "api_key" and oauth_ref is not None:
+ raise ModelHubError("discovery_failed")
+ if kind == "api_key" and not credential_value:
+ 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,
+ )
+ if kind == "subscription":
+ raise ModelHubError("flow_not_found", status=404)
+
+ rollback_credential_ref = await self._engine_call(
+ self.adapter.provision_credential(vendor, protocol, cast(str, credential_value), source.base_url)
+ )
+ source.credential_ref = rollback_credential_ref
+ source.masked_credential = _mask_credential(cast(str, credential_value))
+ persisted = False
+ try:
+ discovered = await self._discover(source)
+ self._apply_discovered_models(source, manual_models, discovered)
+ async with self._mutation_lock:
+ await self._commit_new_source_locked(source, consented=consented)
+ persisted = True
+ return source.to_payload()
+ except Exception:
+ if not persisted:
+ await self._rollback_credential(source.id, rollback_credential_ref)
+ raise
+
+ async def patch_source(self, source_id: str, payload: dict) -> dict:
+ if not isinstance(payload, dict) or set(payload) - {"display_name", "base_url"}:
+ raise ModelHubError("discovery_failed")
+ base_url = _validated_base_url(payload.get("base_url")) if "base_url" in payload else None
+ async with self._mutation_lock:
+ previous = self.store.load()
+ config = self._clone_config(previous)
+ source = self._source(config, source_id)
+ if "display_name" in payload:
+ display_name = payload["display_name"]
+ if (
+ not isinstance(display_name, str)
+ or not display_name
+ or len(display_name) > 64
+ or contains_credential_material(display_name)
+ ):
+ raise ModelHubError("discovery_failed")
+ source.display_name = display_name
+ if "base_url" in payload:
+ if source.kind != "api_key":
+ raise ModelHubError("discovery_failed")
+ source.base_url = base_url
+ discovered = await self._discover(source)
+ manual = [model for model in source.models if model.provenance == "manual"]
+ self._apply_discovered_models(source, manual, discovered)
+ if "base_url" in payload:
+ await self._commit_synced(previous, config)
+ else:
+ self.store.save(config)
+ return source.to_payload()
+
+ @staticmethod
+ def _selected_targets(agent: ModelHubAgentSupplyConfig) -> list[tuple[Optional[str], str]]:
+ if agent.backend == "opencode" and agent.menu:
+ targets = []
+ for identifier in agent.menu.checked:
+ try:
+ provider, model_id = parse_opencode_model_id(identifier)
+ except ValueError:
+ continue
+ else:
+ targets.append((provider, model_id))
+ return targets
+ return [(None, mapping.target_model_id) for mapping in agent.mappings if mapping.enabled]
+
+ def _only_selected_model_supplier(
+ self,
+ config: ModelHubConfig,
+ source: ModelHubSourceConfig,
+ model_id: str,
+ ) -> bool:
+ for agent in config.agents.values():
+ if agent.mode != "hub":
+ continue
+ for provider, target_model_id in self._selected_targets(agent):
+ if target_model_id != model_id or (
+ provider is not None and provider != opencode_provider_id(source.vendor)
+ ):
+ continue
+ suppliers = [
+ candidate
+ for candidate in config.sources
+ if self._eligible_for_agent(candidate, agent.backend)
+ and (provider is None or opencode_provider_id(candidate.vendor) == provider)
+ and any(item.id == model_id for item in candidate.models)
+ ]
+ if len(suppliers) == 1 and suppliers[0].id == source.id:
+ return True
+ return False
+
+ def _only_selected_supplier(self, config: ModelHubConfig, source: ModelHubSourceConfig) -> bool:
+ return any(self._only_selected_model_supplier(config, source, model.id) for model in source.models)
+
+ async def delete_source(self, source_id: str, *, force: bool = False) -> None:
+ async with self._mutation_lock:
+ previous = self.store.load()
+ config = self._clone_config(previous)
+ source = self._source(config, source_id)
+ 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]
+ if source.credential_ref:
+ self.revocations.add(source.id, source.credential_ref)
+ try:
+ await self._commit_synced(previous, config)
+ except Exception:
+ self.revocations.remove(source.id)
+ raise
+ try:
+ if source.credential_ref:
+ await self._engine_call(self.adapter.revoke_credential(source.credential_ref))
+ except ModelHubError:
+ restored = False
+ try:
+ self.store.save(previous)
+ restored = True
+ self._engine_synced = False
+ await self._sync_sources(previous)
+ self._engine_synced = True
+ finally:
+ if restored:
+ self.revocations.remove(source.id)
+ raise
+ self.revocations.remove(source.id)
+
+ async def test_source(self, source_id: str) -> tuple[dict, int]:
+ async with self._mutation_lock:
+ previous = self.store.load()
+ config = self._clone_config(previous)
+ source = self._source(config, source_id)
+ if source.supply_channel == "native_cli":
+ raise ModelHubError("discovery_failed")
+ model_ids = await self._discover(source)
+ manual = [model for model in source.models if model.provenance == "manual"]
+ self._apply_discovered_models(source, manual, model_ids)
+ source.state = ModelHubSourceStateConfig(status="standby")
+ 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:
+ if source.kind == "api_key":
+ return source.supply_channel == "hub"
+ return backend in _allowed_origins(source)
+
+ def _source_available(self, source: ModelHubSourceConfig) -> bool:
+ if source.state.status == "error":
+ return False
+ if source.state.status != "cooldown":
+ return True
+ try:
+ return _parse_datetime(source.state.retry_at or "") <= self.now()
+ except ValueError:
+ return False
+
+ def _agent_payload(self, config: ModelHubConfig, agent: ModelHubAgentSupplyConfig) -> dict:
+ current = None
+ if agent.mode == "hub":
+ if agent.backend == "opencode" and (agent.menu is None or not agent.menu.checked):
+ return {**agent.to_payload(), "current": None}
+ provider = None
+ target = next((mapping.target_model_id for mapping in agent.mappings if mapping.enabled), None)
+ if target is None and agent.menu and agent.menu.checked:
+ try:
+ provider, target = parse_opencode_model_id(agent.menu.checked[0])
+ except ValueError:
+ provider = None
+ by_id = {source.id: source for source in config.sources}
+ for source_id in config.priority_order:
+ source = by_id[source_id]
+ if not self._eligible_for_agent(source, agent.backend):
+ continue
+ if not self._source_available(source):
+ continue
+ if provider is not None and opencode_provider_id(source.vendor) != provider:
+ continue
+ model = next((model for model in source.models if target is None or model.id == target), None)
+ if model is not None:
+ current = {"model_id": model.id, "source_id": source.id, "channel": source.supply_channel}
+ break
+ return {**agent.to_payload(), "current": current}
+
+ def list_agents(self) -> list[dict]:
+ config = self.store.load()
+ return [self._agent_payload(config, config.agents[backend]) for backend in ("claude", "codex", "opencode")]
+
+ async def set_agent_mode(self, backend: str, mode: object) -> dict:
+ if mode not in {"hub", "direct"}:
+ raise ModelHubError("mode_switch_blocked")
+ async with self._mutation_lock:
+ config = self.store.load()
+ agent = self._agent(config, backend)
+ agent.mode = mode
+ self.store.save(config)
+ return self._agent_payload(config, agent)
+
+ async def set_mappings(self, backend: str, mappings: object) -> dict:
+ async with self._mutation_lock:
+ config = self.store.load()
+ agent = self._agent(config, backend)
+ if agent.menu_kind != "fixed" or not isinstance(mappings, list):
+ raise ModelHubError("mapping_target_unavailable")
+ try:
+ parsed = [ModelHubMappingConfig.from_payload(mapping) for mapping in mappings]
+ except ValueError as exc:
+ raise ModelHubError("mapping_target_unavailable") from exc
+ available = {
+ model.id
+ for source in config.sources
+ if self._eligible_for_agent(source, backend)
+ for model in source.models
+ }
+ if any(mapping.enabled and mapping.target_model_id not in available for mapping in parsed):
+ raise ModelHubError("mapping_target_unavailable")
+ agent.mappings = parsed
+ self.store.save(config)
+ return self._agent_payload(config, agent)
+
+ async def set_opencode_menu(self, menu: object) -> dict:
+ async with self._mutation_lock:
+ config = self.store.load()
+ agent = config.agents["opencode"]
+ try:
+ parsed = ModelHubMenuConfig.from_payload(cast(dict, menu))
+ except (TypeError, ValueError) as exc:
+ raise ModelHubError("mapping_target_unavailable") from exc
+ available = {
+ opencode_model_id(source.vendor, model.id)
+ for source in config.sources
+ if self._eligible_for_agent(source, "opencode")
+ for model in source.models
+ }
+ if any(identifier not in available for identifier in parsed.checked):
+ raise ModelHubError("mapping_target_unavailable")
+ agent.menu = parsed
+ self.store.save(config)
+ return self._agent_payload(config, agent)
+
+ async def add_custom_model(self, payload: dict) -> dict:
+ if not isinstance(payload, dict):
+ raise ModelHubError("source_not_found", status=404)
+ model_id = payload.get("model_id")
+ display_name = payload.get("display_name")
+ if (
+ not isinstance(model_id, str)
+ or not model_id
+ or contains_credential_material(model_id)
+ ):
+ raise ModelHubError("mapping_target_unavailable")
+ if display_name is not None and (
+ not isinstance(display_name, str) or contains_credential_material(display_name)
+ ):
+ raise ModelHubError("mapping_target_unavailable")
+ async with self._mutation_lock:
+ previous = self.store.load()
+ config = self._clone_config(previous)
+ source = self._source(config, str(payload.get("source_id") or ""))
+ existing = next((model for model in source.models if model.id == model_id), None)
+ if existing is None:
+ source.models.append(
+ ModelHubModelConfig(
+ id=model_id,
+ display_name=display_name,
+ provenance="manual",
+ discovered_at=None,
+ )
+ )
+ elif existing.provenance == "manual":
+ existing.display_name = display_name
+ await self._commit_synced(previous, config)
+ return source.to_payload()
+
+ async def delete_custom_model(self, source_id: object, model_id: object) -> dict:
+ if not isinstance(model_id, str) or not model_id:
+ raise ModelHubError("mapping_target_unavailable")
+ async with self._mutation_lock:
+ previous = self.store.load()
+ config = self._clone_config(previous)
+ source = self._source(config, str(source_id or ""))
+ manual = next(
+ (model for model in source.models if model.id == model_id and model.provenance == "manual"),
+ None,
+ )
+ if manual is not None and self._only_selected_model_supplier(config, source, model_id):
+ raise ModelHubError("mode_switch_blocked", status=409)
+ source.models = [
+ model
+ for model in source.models
+ if not (model.id == model_id and model.provenance == "manual")
+ ]
+ await self._commit_synced(previous, config)
+ return source.to_payload()
+
+ def list_events(self, *, limit: int = 20, before: Optional[str] = None) -> list[dict]:
+ return self.events.list(limit=limit, before=before)
+
+ async def oauth_start(self, payload: dict) -> dict:
+ vendor = payload.get("vendor") if isinstance(payload, dict) else None
+ channel = payload.get("channel") if isinstance(payload, dict) else None
+ if not isinstance(vendor, str) or channel not in {"native_cli", "hub"}:
+ raise ModelHubError("flow_not_found", status=400)
+ consented = payload.get("experimental_consent") is True
+ if "experimental_consent" in payload and not isinstance(payload.get("experimental_consent"), bool):
+ raise ModelHubError("consent_required")
+ if channel == "hub" and not consented:
+ raise ModelHubError("consent_required", status=409)
+ if consented and channel != "hub":
+ raise ModelHubError("consent_required")
+ oauth_channel = cast(OAuthChannel, channel)
+ pending_source_id = _source_id()
+ flow = await self._oauth_call(
+ self._oauth_adapter(oauth_channel).start_oauth(pending_source_id, vendor)
+ )
+ if flow.source_id != pending_source_id or flow.vendor != vendor:
+ raise ModelHubError("flow_not_found", status=502)
+ self.oauth_flows.remember(flow.flow_id, oauth_channel, pending_source_id, vendor)
+ if channel == "hub" and consented:
+ async with self._mutation_lock:
+ config = self.store.load()
+ config.subscription_hub_experimental = True
+ self.store.save(config)
+ return _oauth_payload(flow, channel=channel)
+
+ async def oauth_status(self, flow_id: str) -> dict:
+ channel = self._oauth_channel(flow_id)
+ flow = await self._oauth_status(flow_id, channel)
+ self._raise_if_flow_expired(flow_id, flow)
+ return _oauth_payload(flow, channel=channel)
+
+ async def oauth_submit(self, payload: dict) -> dict:
+ flow_id = payload.get("flow_id") if isinstance(payload, dict) else None
+ value = payload.get("value") if isinstance(payload, dict) else None
+ if not isinstance(flow_id, str) or not isinstance(value, str):
+ raise ModelHubError("flow_not_found", status=404)
+ channel = self._oauth_channel(flow_id)
+ current = await self._oauth_status(flow_id, channel)
+ self._raise_if_flow_expired(flow_id, current)
+ flow = await self._oauth_call(
+ self._oauth_adapter(channel).submit_oauth(flow_id, value),
+ flow_id=flow_id,
+ )
+ return _oauth_payload(flow, channel=channel)
+
+ async def oauth_cancel(self, flow_id: object) -> None:
+ if not isinstance(flow_id, str):
+ raise ModelHubError("flow_not_found", status=404)
+ channel = self._oauth_channel(flow_id)
+ await self._oauth_call(
+ self._oauth_adapter(channel).cancel_oauth(flow_id),
+ flow_id=flow_id,
+ )
+ self.oauth_flows.forget(flow_id)
+
+ async def runtime_status(self) -> dict:
+ return _runtime_payload(await self._engine_call(self.adapter.status()))
+
+ def migration_scan(self) -> dict:
+ # L6 supplies the native-config scanner. Empty is valid and read-only.
+ return {"items": []}
+
+ def migration_apply(self, item_ids: object) -> dict:
+ if not isinstance(item_ids, list) or item_ids:
+ raise ModelHubError("migration_item_conflict", status=409)
+ return {"applied": 0, "sources": self.list_sources()}
+
+ async def _resolution_candidates(
+ self,
+ backend: str,
+ model_id: str,
+ *,
+ provider: Optional[str] = None,
+ ) -> list[ModelHubSourceConfig]:
+ async with self._mutation_lock:
+ config = self.store.load()
+ by_id = {source.id: source for source in config.sources}
+ candidates: list[ModelHubSourceConfig] = []
+ config_changed = False
+ for source_id in config.priority_order:
+ source = by_id[source_id]
+ matches_request = (
+ self._eligible_for_agent(source, backend)
+ and (provider is None or opencode_provider_id(source.vendor) == provider)
+ and any(model.id == model_id for model in source.models)
+ )
+ if not matches_request:
+ continue
+ if source.state.status == "cooldown":
+ try:
+ retry_at = _parse_datetime(source.state.retry_at or "")
+ except ValueError:
+ retry_at = self.now() + timedelta(days=1)
+ if retry_at > self.now():
+ continue
+ source.state = ModelHubSourceStateConfig(status="standby")
+ config_changed = True
+ self._record_event(
+ agent=cast(EventAgent, backend),
+ kind="recover",
+ model_id=model_id,
+ reason="recovery",
+ to_source=source.id,
+ to_label=source.display_name,
+ now=self.now(),
+ )
+ if source.state.status != "error":
+ candidates.append(source)
+ if config_changed:
+ self.store.save(config)
+ return candidates
+
+ async def _cooldown(
+ self,
+ source: ModelHubSourceConfig,
+ decision: ResolutionDecision,
+ *,
+ agent: EventAgent,
+ model_id: str,
+ ) -> None:
+ async with self._mutation_lock:
+ config = self.store.load()
+ try:
+ current = self._source(config, source.id)
+ except ModelHubError:
+ return
+ current.state = ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at=(self.now() + timedelta(seconds=decision.cooldown_seconds)).isoformat(),
+ detail_key=f"models.source.cooldown.{decision.reason}",
+ )
+ self.store.save(config)
+ self._record_event(
+ agent=agent,
+ kind="cooldown",
+ model_id=model_id,
+ reason=cast(EventReason, decision.reason),
+ from_source=current.id,
+ from_label=current.display_name,
+ now=self.now(),
+ )
+
+ def _emit_switch(
+ self,
+ *,
+ agent: EventAgent,
+ model_id: str,
+ failed_source: Optional[ModelHubSourceConfig],
+ failed_reason: Optional[EventReason],
+ source: ModelHubSourceConfig,
+ ) -> None:
+ if failed_source is None or failed_reason is None:
+ return
+ billing_note = (
+ "entered_metered" if failed_source.billing == "monthly" and source.billing == "metered" else None
+ )
+ self._record_event(
+ agent=agent,
+ kind="switch",
+ model_id=model_id,
+ reason=failed_reason,
+ from_source=failed_source.id,
+ to_source=source.id,
+ from_label=failed_source.display_name,
+ to_label=source.display_name,
+ billing_note=billing_note,
+ now=self.now(),
+ )
+
+ async def _invoke(
+ self,
+ *,
+ source: ModelHubSourceConfig,
+ model_id: str,
+ request: Mapping[str, Any],
+ stream: bool,
+ backend: str,
+ ) -> tuple[InvokeHandle, Optional[RawCallOutcome]]:
+ handle = await self._engine_call(
+ self.adapter.invoke(source.id, model_id, request, stream, backend)
+ )
+ if handle.stream is not None:
+ return handle, None
+ return handle, await self._engine_call(handle.outcome())
+
+ async def resolve(
+ self,
+ *,
+ backend: str,
+ model_id: str,
+ request: Mapping[str, Any],
+ stream: bool = False,
+ ) -> ResolvedInvocation:
+ if backend not in {"claude", "codex", "opencode"}:
+ raise ModelHubError("mapping_target_unavailable")
+ config = self.store.load()
+ agent = self._agent(config, backend)
+ if agent.mode != "hub":
+ raise ModelHubError("mode_switch_blocked", status=409)
+ target_model = next(
+ (
+ mapping.target_model_id
+ for mapping in agent.mappings
+ if mapping.enabled and mapping.builtin_id == model_id
+ ),
+ model_id,
+ )
+ mapping_applied = target_model != model_id
+ provider = None
+ if backend == "opencode":
+ try:
+ provider, target_model = parse_opencode_model_id(target_model)
+ except ValueError:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ selected_identifier = f"{provider}/{target_model}"
+ if agent.menu is None or selected_identifier not in agent.menu.checked:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ event_agent = cast(EventAgent, backend)
+ if mapping_applied:
+ self._record_event(
+ agent=event_agent,
+ kind="mapping_applied",
+ model_id=target_model,
+ reason="mapping",
+ from_label=model_id,
+ now=self.now(),
+ )
+ candidates = await self._resolution_candidates(backend, target_model, provider=provider)
+ if not candidates:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+
+ failed_source: Optional[ModelHubSourceConfig] = None
+ failed_reason: Optional[EventReason] = None
+ for source in candidates:
+ if source.supply_channel == "native_cli":
+ if self.revocations.list():
+ try:
+ await self._ensure_engine_synced()
+ except ModelHubError:
+ # Credential cleanup remains durable; native routing is independent.
+ pass
+ self._emit_switch(
+ agent=event_agent,
+ model_id=target_model,
+ failed_source=failed_source,
+ failed_reason=failed_reason,
+ source=source,
+ )
+ return ResolvedInvocation(
+ source.id,
+ target_model,
+ None,
+ None,
+ supply_channel="native_cli",
+ )
+ await self._ensure_engine_synced()
+ handle, outcome = await self._invoke(
+ source=source,
+ model_id=target_model,
+ request=request,
+ stream=stream,
+ backend=backend,
+ )
+ if outcome is None:
+ self._emit_switch(
+ agent=event_agent,
+ model_id=target_model,
+ failed_source=failed_source,
+ failed_reason=failed_reason,
+ source=source,
+ )
+ return ResolvedInvocation(source.id, target_model, handle, None)
+ decision = classify_outcome(outcome)
+ if decision.action == "refresh":
+ # The engine refreshes its credential internally; L2 retries the
+ # exact same source once and never falls through on a second 401.
+ handle, outcome = await self._invoke(
+ source=source,
+ model_id=target_model,
+ request=request,
+ stream=stream,
+ backend=backend,
+ )
+ if outcome is None:
+ self._emit_switch(
+ agent=event_agent,
+ model_id=target_model,
+ failed_source=failed_source,
+ failed_reason=failed_reason,
+ source=source,
+ )
+ return ResolvedInvocation(source.id, target_model, handle, None)
+ decision = classify_outcome(outcome, refresh_attempted=True)
+ if decision.action == "return":
+ self._emit_switch(
+ agent=event_agent,
+ model_id=target_model,
+ failed_source=failed_source,
+ failed_reason=failed_reason,
+ source=source,
+ )
+ return ResolvedInvocation(source.id, target_model, handle, outcome)
+ if decision.action == "fallback":
+ await self._cooldown(source, decision, agent=event_agent, model_id=target_model)
+ failed_source = source
+ failed_reason = cast(EventReason, decision.reason)
+ continue
+ raise ModelHubError(decision.error_code or "engine_down", status=502)
+ raise ModelHubError("engine_down", status=503)
+
+
+def create_default_service(
+ *,
+ adapter: Optional[EngineAdapter] = None,
+ native_oauth_adapter: Optional[OAuthAdapter] = None,
+) -> ModelHubService:
+ return ModelHubService(
+ store=V2ModelHubConfigStore(),
+ adapter=adapter or UnavailableEngineAdapter(),
+ events=BoundedEventLog(paths.get_state_dir() / "model_hub_resolution_events.json"),
+ native_oauth_adapter=native_oauth_adapter,
+ oauth_flows=OAuthFlowRegistry(paths.get_state_dir() / "model_hub_oauth_flows.json"),
+ revocations=CredentialRevocationJournal(paths.get_state_dir() / "model_hub_pending_revocations.json"),
+ )
diff --git a/core/services/settings.py b/core/services/settings.py
index 6a9bce332..5112d45ca 100644
--- a/core/services/settings.py
+++ b/core/services/settings.py
@@ -31,6 +31,7 @@ from config.v2_config import (
AgentsConfig,
ClaudeConfig,
CodexConfig,
+ ModelHubConfig,
OpenCodeConfig,
PlatformsConfig,
RuntimeConfig,
@@ -78,6 +79,7 @@ def default_config() -> V2Config:
claude=ClaudeConfig(enabled=True, cli_path="claude"),
codex=CodexConfig(enabled=False, cli_path="codex"),
),
+ model_hub=ModelHubConfig.fresh(),
)
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
new file mode 100644
index 000000000..5119b6949
--- /dev/null
+++ b/docs/plans/model-hub-contracts/README.md
@@ -0,0 +1,65 @@
+# Model Hub — Interface Contracts
+
+Status: **FROZEN v1** · 2026-07-23 10:45 (+08:00) · change only via orchestrator
+Derived from: signed spec (`../model-hub.md`), implementation plan
+(`../model-hub-implementation.md`), spike S1 engine survey
+(branch `spike/model-hub-engine`, `docs/plans/model-hub-engine-survey.md`),
+spike S2 ToS review (branch `spike/model-hub-tos`,
+`docs/plans/model-hub-tos-review.md`).
+
+## Resolved decision (owner, 2026-07-23 10:33)
+
+**Hybrid supply by default + consent-gated experimental hub-held subscriptions.**
+Subscription sources default `supply_channel: "native_cli"` (per-turn channel
+dispatch; the CLI's own sanctioned OAuth burns the quota); api_key sources are
+`"hub"`. Additionally, subscription login INTO the engine (hub-held, incl.
+Claude) ships as an **experimental feature behind
+`subscription_hub_experimental`** with explicit ban-risk consent (copy: S2 §9)
+and per-source opt-in — never enabled silently, always visibly marked. The
+`allowed_origins`-style client binding applies to native_cli sources
+(sanctioned client only) and to any experimental hub-held subscription.
+
+Everything else reflects S1 findings:
+runtime-declared OAuth presentation (S1 gap ③), adapter-owned redacted
+resolution events with the engine usage feed disabled (S1 gap ② — the feed
+leaks inbound keys), model provenance + cooldown fields, authoritative ordered
+priority, and a standalone managed-dependency manifest/status contract.
+
+## Freeze protocol
+
+- After the owner decision, the orchestrator commits these files with message
+ `docs(model-hub): freeze interface contracts v1` 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.
+
+## Files
+
+| File | Consumers |
+| --- | --- |
+| `source.schema.json` | L2 API, L4 UI |
+| `priority.schema.json` | L2, L4 |
+| `agent-supply.schema.json` | L2, L3 injection, L4/L5 UI |
+| `resolution-event.schema.json` | L2 (adapter-owned), L4 UI, L1 adapter |
+| `oauth-flow.schema.json` | L2, L4 UI, L1 engine adapter |
+| `migration-scan.schema.json` | L6, L5 UI |
+| `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). |
+| `api.md` | all |
+| `opencode-overlay.md` | L3, L7 (identifier-stability tests) |
+| `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). |
+
+## Security invariants (from S1/S2, non-negotiable)
+
+1. No credential material ever appears in any payload defined here —
+ sources expose `credential_ref` only; events are adapter-redacted.
+ Clarified 07-23 12:10 (L4 finding): non-reversible display data IS
+ permitted — `account_label` (subscription identity from the sanctioned
+ auth surface) and `masked_credential` (≤7-char prefix + "…" + last 4,
+ computed once at provisioning, never re-derivable) exist precisely so
+ the UI never needs anything stronger.
+2. The engine's own usage feed stays disabled; events originate from our
+ adapter (S1 gap ②).
+3. `allowed_origins`-style client binding is enforced in code: subscription
+ sources are never eligible for agents outside their sanctioned client
+ (S2; server-side enforcement exists for Claude anyway).
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
new file mode 100644
index 000000000..3d238c5b4
--- /dev/null
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -0,0 +1,225 @@
+"""Model Hub — EngineAdapter interface. FROZEN CONTRACT v1.2 (2026-07-23 11:12 +08:00).
+
+v1.2 changelog (L1 implementation findings — credential & model lifecycle):
+- Secret provisioning path closed: ``provision_credential`` moves an API-key
+ secret (transient parameter, never logged, never persisted by L2) into the
+ ENGINE-OWNED store and returns the opaque ``credential_ref``;
+ ``revoke_credential`` releases it on source deletion. L2's config persists
+ refs only. Flow: provision → discover (probe) → persist Source → sync.
+- ``SourceBinding.model_ids`` added: the declared supply list (discovered +
+ manual custom entries) — required by the engine's generic/API-key config.
+- ``discover_models`` re-signed as a PROBE (vendor/protocol/base_url/
+ credential_ref) so discovery works BEFORE registration; it no longer takes
+ a ``source_id``.
+
+v1.1 changelog (L1 review findings, routed via orchestrator):
+- OAuth surface added with DETERMINISTIC source binding: ``start_oauth`` takes
+ the pre-created (pending) ``source_id``; a ``success`` ``OAuthFlowState``
+ carries the resulting opaque ``credential_ref``. Concurrent same-vendor
+ flows can never cross-bind.
+- Client binding made enforceable at the engine boundary:
+ ``SourceBinding.allowed_origins`` + ``invoke(origin=...)`` +
+ ``OriginNotAllowedError`` (adapter-side backstop; L2's resolver filters
+ first — defense in depth per README invariant 3).
+
+Canonical text: docs/plans/model-hub-contracts/adapter-interface.py (this file).
+Dual-copy rule: BOTH lane L1 and lane L2 copy this file VERBATIM to
+``core/handlers/model_hub/adapter.py`` in their branches (byte-identical, so the
+merge is a no-op). L2 owns the in-repo copy on master thereafter. Any change
+routes through the orchestrator and bumps the version line above.
+
+Seam semantics (from spike S1, binding):
+- L1 implements this protocol (engine facade). L1 must NOT classify errors,
+ retry, or fall back across sources — per-source invocation only; the
+ engine's internal fallback and usage feed stay disabled/bypassed.
+- L2 consumes it: picks exactly one source per call (priority resolution),
+ classifies ``RawCallOutcome`` into the canonical taxonomy, emits redacted
+ resolution events.
+- No credential material may appear in any field defined here.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from enum import Enum
+from typing import Any, AsyncIterator, Mapping, Protocol, Sequence
+
+
+class EngineHealth(str, Enum):
+ OK = "ok"
+ DEGRADED = "degraded"
+ DOWN = "down"
+ NOT_INSTALLED = "not_installed"
+
+
+@dataclass(frozen=True)
+class EngineStatus:
+ health: EngineHealth
+ installed_version: str | None
+ verified: bool
+ listen_host: str # always "127.0.0.1"
+ listen_port: int | None
+ last_check_iso: str | None
+
+
+@dataclass(frozen=True)
+class SourceBinding:
+ """Engine-side registration of one hub-channel source (projection of config)."""
+
+ source_id: str
+ vendor: str
+ protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "openai_compatible"
+ base_url: str | None # None => vendor official default
+ credential_ref: str # opaque handle; never secret material
+ allowed_origins: tuple[str, ...] # agent names allowed to draw on this
+ # source. Empty tuple = unrestricted (api_key default). Subscription
+ # sources MUST be non-empty (README invariant 3); L2 populates, L1
+ # enforces as backstop.
+ model_ids: tuple[str, ...] # declared supply list (discovered + manual
+ # custom entries); required by the engine's generic/API-key config. Bare
+ # model ids, no provider prefix.
+
+
+class OriginNotAllowedError(Exception):
+ """Raised by the adapter when ``invoke(origin=...)`` violates the source's
+ ``allowed_origins``. A programming/policy error — never converted into a
+ ``RawCallOutcome`` and never triggers fallback."""
+
+
+class RawOutcomeKind(str, Enum):
+ SUCCESS = "success"
+ HTTP_ERROR = "http_error"
+ NETWORK_ERROR = "network_error"
+ TIMEOUT = "timeout"
+ PROTOCOL_ERROR = "protocol_error" # malformed/unparseable upstream response
+
+
+@dataclass(frozen=True)
+class RawCallOutcome:
+ """Uninterpreted per-call result. Classification is L2's job, not L1's."""
+
+ kind: RawOutcomeKind
+ http_status: int | None
+ error_code: str | None # upstream machine code if parseable, else None
+ redacted_message: str | None # L1 guarantees no credential material
+ stream_started: bool
+ model_id: str
+ source_id: str
+
+
+@dataclass(frozen=True)
+class OAuthFlowState:
+ """Engine-held (experimental hub-channel) subscription OAuth flow state.
+
+ Deterministic binding: the flow is created FOR a pre-existing pending
+ ``source_id`` and, on ``state == "success"``, carries the opaque
+ ``credential_ref`` of the auth record the engine created — L2 binds it to
+ that source and never guesses, even with concurrent same-vendor flows.
+ Mirrors ``oauth-flow.schema.json`` presentation semantics
+ (runtime-declared; UI renders from ``expects``).
+ """
+
+ flow_id: str
+ source_id: str
+ vendor: str
+ state: str # "starting" | "awaiting_action" | "verifying" | "success" | "failed" | "cancelled"
+ auth_url: str | None
+ device_code: str | None
+ expects: str # "none" | "paste_code" | "paste_callback_url"
+ instructions_key: str | None
+ error_key: str | None
+ expires_at_iso: str | None
+ credential_ref: str | None # set iff state == "success"
+
+
+class InvokeHandle(Protocol):
+ """One in-flight upstream call.
+
+ ``stream`` is None iff the call failed before the first byte (outcome is
+ then immediately awaitable). When ``stream`` is not None, the caller must
+ consume it; ``outcome()`` resolves after the stream ends and reports
+ ``stream_started=True`` — per spec §4.2 no transparent retry then.
+ """
+
+ @property
+ def stream(self) -> AsyncIterator[bytes] | None: ...
+
+ async def outcome(self) -> RawCallOutcome: ...
+
+
+class EngineAdapter(Protocol):
+ # --- lifecycle -------------------------------------------------------
+ async def ensure_installed(self) -> EngineStatus: ...
+
+ async def start(self) -> EngineStatus: ...
+
+ async def stop(self) -> None: ...
+
+ async def status(self) -> EngineStatus: ...
+
+ # --- gateway ---------------------------------------------------------
+ async def gateway_token(self) -> str:
+ """Local gateway token for backend injection (the ONLY credential
+ backends ever receive)."""
+ ...
+
+ # --- credential provisioning (engine-owned store) ---------------------
+ async def provision_credential(
+ self,
+ vendor: str,
+ protocol: str,
+ secret: str,
+ base_url: str | None,
+ ) -> str:
+ """Store an API-key secret in the ENGINE-OWNED credential store and
+ return the opaque ``credential_ref``.
+
+ ``secret`` is transient: the adapter must never log it; L2 must never
+ persist it (config stores refs only). OAuth credentials never pass
+ through here — they are created engine-side by the OAuth flow and
+ surfaced via ``OAuthFlowState.credential_ref``."""
+ ...
+
+ async def revoke_credential(self, credential_ref: str) -> None:
+ """Release the stored credential (source deletion / key replacement)."""
+ ...
+
+ # --- source registry (L2 calls on every config change) ---------------
+ async def sync_sources(self, bindings: Sequence[SourceBinding]) -> None: ...
+
+ async def discover_models(
+ self,
+ vendor: str,
+ protocol: str,
+ base_url: str | None,
+ credential_ref: str,
+ ) -> Sequence[str]:
+ """PROBE the upstream for supplyable model ids. Works before any
+ registration (test-and-add flow: provision → discover → persist →
+ sync); does not require or create a source binding."""
+ ...
+
+ # --- engine-held subscription OAuth (experimental flag only) ----------
+ async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState: ...
+
+ async def oauth_status(self, flow_id: str) -> OAuthFlowState: ...
+
+ async def submit_oauth(self, flow_id: str, value: str) -> OAuthFlowState:
+ """``value`` per ``expects``: pasted code or callback URL."""
+ ...
+
+ async def cancel_oauth(self, flow_id: str) -> None: ...
+
+ # --- invocation primitive (exactly one source; no engine fallback) ---
+ async def invoke(
+ self,
+ source_id: str,
+ model_id: str,
+ request: Mapping[str, Any],
+ stream: bool,
+ origin: str,
+ ) -> InvokeHandle:
+ """``origin`` = requesting agent name ("claude"|"codex"|"opencode"|...).
+ Raises ``OriginNotAllowedError`` when the binding's ``allowed_origins``
+ excludes it (backstop; L2 must have filtered already)."""
+ ...
diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.json
new file mode 100644
index 000000000..3e6e74810
--- /dev/null
+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json
@@ -0,0 +1,75 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/agent-supply.schema.json",
+ "title": "AgentSupply",
+ "description": "Per-backend supply status & configuration (spec §4.3, frames 01r/04/05r).",
+ "type": "object",
+ "required": ["backend", "mode", "menu_kind"],
+ "additionalProperties": false,
+ "properties": {
+ "backend": { "enum": ["claude", "codex", "opencode"] },
+ "mode": {
+ "enum": ["hub", "direct"],
+ "description": "中枢/直连. Existing users stay direct until they migrate; fresh installs default hub (plan §4). Under Option 1, hub mode for claude still consumes the subscription via the native channel per turn."
+ },
+ "menu_kind": { "enum": ["fixed", "open"] },
+ "current": {
+ "type": ["object", "null"],
+ "description": "What the next turn would use (frame 01r composite pill). null when mode=direct.",
+ "required": ["model_id", "source_id", "channel"],
+ "additionalProperties": false,
+ "properties": {
+ "model_id": { "type": "string" },
+ "source_id": { "type": "string" },
+ "channel": { "enum": ["native_cli", "hub"] }
+ }
+ },
+ "mappings": {
+ "type": "array",
+ "description": "fixed-menu backends only; per-agent scope (spec §4.2). Absent entry = 跟随原生 (identity).",
+ "items": {
+ "type": "object",
+ "required": ["builtin_id", "target_model_id", "enabled"],
+ "additionalProperties": false,
+ "properties": {
+ "builtin_id": { "type": "string", "description": "real built-in model id, e.g. claude-opus-4-6" },
+ "target_model_id": { "type": "string" },
+ "enabled": { "type": "boolean" }
+ }
+ }
+ },
+ "menu": {
+ "type": ["object", "null"],
+ "description": "open-menu backends only (frame 05r).",
+ "required": ["view", "checked"],
+ "additionalProperties": false,
+ "properties": {
+ "view": { "enum": ["featured", "full"] },
+ "checked": {
+ "type": "array",
+ "description": "prefixed identifiers, e.g. zhipuai/glm-5.2 (see opencode-overlay.md)",
+ "items": { "type": "string", "pattern": "^[a-z0-9_-]+/.+$" },
+ "uniqueItems": true
+ }
+ }
+ }
+ },
+ "examples": [
+ {
+ "backend": "claude",
+ "mode": "hub",
+ "menu_kind": "fixed",
+ "current": { "model_id": "claude-opus-4-6", "source_id": "src_claudepro1", "channel": "native_cli" },
+ "mappings": [ { "builtin_id": "claude-opus-4-6", "target_model_id": "glm-5.2", "enabled": false } ],
+ "menu": null
+ },
+ {
+ "backend": "opencode",
+ "mode": "hub",
+ "menu_kind": "open",
+ "current": { "model_id": "glm-5.2", "source_id": "src_zhipukey01", "channel": "hub" },
+ "mappings": [],
+ "menu": { "view": "featured", "checked": ["anthropic/claude-opus-4-6", "openai/gpt-5.6", "zhipuai/glm-5.2", "zhipuai/glm-5.2-air"] }
+ }
+ ]
+}
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
new file mode 100644
index 000000000..242e0e45d
--- /dev/null
+++ b/docs/plans/model-hub-contracts/api.md
@@ -0,0 +1,39 @@
+# 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: 1`. Auth follows existing UI-server
+session auth; localhost curl is rejected the same way as other `/api/*` routes.
+
+| Method & path | Req / Resp schema | Notes |
+| --- | --- | --- |
+| GET `/api/models/sources` | → `{sources: Source[]}` | list, ordered by priority |
+| POST `/api/models/sources` | `SourceCreate` (kind, vendor, base_url?, key? / oauth flow ref) → `Source` | api_key create validates + discovers models (test-and-add, frame 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. |
+| PATCH `/api/models/sources/<id>` | partial Source (display_name, base_url) → `Source` | never accepts credential material in plaintext beyond initial create |
+| DELETE `/api/models/sources/<id>` | → `{ok}` | refuses while source is the only supplier of a checked/ mapped model unless `force=true` |
+| POST `/api/models/sources/<id>/test` | → `{ok, discovered: n}` | re-discovery |
+| PUT `/api/models/priority` | `Priority` → `Priority` | authoritative full order; server re-echoes canonical order |
+| GET `/api/models/agents` | → `{agents: AgentSupply[]}` | includes `current` per backend |
+| 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 |
+| POST `/api/models/custom-models` | `{source_id, model_id, display_name?}` → `Source` | appends manual-provenance model entry (frame 08) |
+| DELETE `/api/models/custom-models` | `{source_id, model_id}` → `Source` | |
+| GET `/api/models/events?limit=n&before=<id>` | → `{events: ResolutionEvent[]}` | adapter-owned feed (最近切换) |
+| POST `/api/models/oauth/start` | `{vendor, channel}` → `OAuthFlow` | runtime-declared presentation |
+| GET `/api/models/oauth/status/<flow_id>` | → `OAuthFlow` | 2s polling, server holds flow |
+| POST `/api/models/oauth/submit` | `{flow_id, value}` → `OAuthFlow` | value = pasted code or callback URL per `presentation.expects` |
+| POST `/api/models/oauth/cancel` | `{flow_id}` → `{ok}` | |
+| POST `/api/models/migration/scan` | → `MigrationScan` | read-only |
+| POST `/api/models/migration/apply` | `{item_ids: []}` → `{applied: n, sources: Source[]}` | copy-only; originals untouched (tested) |
+| GET `/api/models/runtime/status` | → `RuntimeDependency` | engine manifest + health |
+
+Error codes (minimum set): `source_not_found`, `flow_not_found`, `flow_expired`,
+`discovery_failed`, `invalid_priority_order` (must be a permutation),
+`mapping_target_unavailable`, `mode_switch_blocked`, `engine_down`,
+`consent_required` (hub-held subscription paths while the experimental flag is
+unset), `migration_item_conflict`.
+
+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.
diff --git a/docs/plans/model-hub-contracts/migration-scan.schema.json b/docs/plans/model-hub-contracts/migration-scan.schema.json
new file mode 100644
index 000000000..e9bdaeac9
--- /dev/null
+++ b/docs/plans/model-hub-contracts/migration-scan.schema.json
@@ -0,0 +1,40 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/migration-scan.schema.json",
+ "title": "MigrationScan",
+ "description": "Result of scanning native backend configs (spec §6, frame 03). Non-destructive: apply copies only; originals are never modified or deleted (tested property, plan M4).",
+ "type": "object",
+ "required": ["items"],
+ "additionalProperties": false,
+ "properties": {
+ "items": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["id", "backend", "kind", "masked_detail", "proposed_action", "selected"],
+ "additionalProperties": false,
+ "properties": {
+ "id": { "type": "string" },
+ "backend": { "enum": ["claude", "codex", "opencode"] },
+ "kind": { "enum": ["api_key", "oauth_native", "opencode_provider"] },
+ "masked_detail": { "type": "string", "description": "e.g. 'sk-…dd3c + 自定义 Base URL'; never full secrets" },
+ "proposed_action": {
+ "enum": ["import", "controlled_import", "keep_native", "reauth"],
+ "description": "Option 1: Claude oauth_native → keep_native (sanctioned as-is; NOT re-authed into the hub). Codex auth.json → controlled_import behind the consent-gated flag, else keep_native. Keys/base URLs → import."
+ },
+ "selected": { "type": "boolean" },
+ "notes_key": { "type": ["string", "null"], "description": "i18n key for the row's secondary line" }
+ }
+ }
+ }
+ },
+ "examples": [
+ {
+ "items": [
+ { "id": "mig_1", "backend": "claude", "kind": "api_key", "masked_detail": "sk-…dd3c + custom base URL", "proposed_action": "import", "selected": true, "notes_key": null },
+ { "id": "mig_2", "backend": "claude", "kind": "oauth_native", "masked_detail": "Claude 账号登录(OAuth)", "proposed_action": "keep_native", "selected": true, "notes_key": "models.migration.keep_native.sanctioned" },
+ { "id": "mig_3", "backend": "opencode", "kind": "opencode_provider", "masked_detail": "智谱 API Key · glm-…c31b", "proposed_action": "import", "selected": true, "notes_key": null }
+ ]
+ }
+ ]
+}
diff --git a/docs/plans/model-hub-contracts/oauth-flow.schema.json b/docs/plans/model-hub-contracts/oauth-flow.schema.json
new file mode 100644
index 000000000..60ecad2e7
--- /dev/null
+++ b/docs/plans/model-hub-contracts/oauth-flow.schema.json
@@ -0,0 +1,45 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/oauth-flow.schema.json",
+ "title": "OAuthFlow",
+ "description": "Subscription-connect flow state. RUNTIME-DECLARED presentation (S1 gap ③): the server declares what to show and what it expects back; the UI renders declaratively and never keys off a vendor→form table. UI shell semantics mirror the existing BackendOAuthPanel (2s poll, 15-min timeout, cancel). Forms A/B/C from spec §5 frame 09 are presentation patterns the declaration composes: A = auth_url + expects paste_code; B = auth_url + device_code + expects none; C = auth_url + expects paste_callback_url. Under Option 1, native_cli subscription connect drives the CLI's own login through this same shape.",
+ "type": "object",
+ "required": ["flow_id", "vendor", "channel", "state", "presentation"],
+ "additionalProperties": false,
+ "properties": {
+ "flow_id": { "type": "string" },
+ "source_id": { "type": ["string", "null"], "description": "v1.1: pending Source this flow binds to (deterministic association; hub-channel flows always set it)" },
+ "vendor": { "type": "string" },
+ "channel": { "enum": ["native_cli", "hub"], "description": "where the resulting credential will live; hub-held subscriptions only behind the consent-gated experimental flag (S2)" },
+ "state": { "enum": ["starting", "awaiting_action", "verifying", "success", "failed", "cancelled"] },
+ "presentation": {
+ "type": "object",
+ "required": ["expects"],
+ "additionalProperties": false,
+ "properties": {
+ "auth_url": { "type": ["string", "null"] },
+ "device_code": { "type": ["string", "null"] },
+ "expects": { "enum": ["none", "paste_code", "paste_callback_url"] },
+ "instructions_key": { "type": ["string", "null"], "description": "i18n key for the step-2 helper line" }
+ }
+ },
+ "error_key": { "type": ["string", "null"], "description": "i18n key; raw upstream errors never surface" },
+ "expires_at": { "type": ["string", "null"], "format": "date-time" }
+ },
+ "examples": [
+ {
+ "flow_id": "oaf_claude01",
+ "vendor": "anthropic",
+ "channel": "native_cli",
+ "state": "awaiting_action",
+ "presentation": {
+ "auth_url": "https://claude.ai/oauth/authorize?code=true&...",
+ "device_code": null,
+ "expects": "paste_code",
+ "instructions_key": "models.oauth.claude.paste_code"
+ },
+ "error_key": null,
+ "expires_at": "2026-07-23T04:15:00+08:00"
+ }
+ ]
+}
diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.md
new file mode 100644
index 000000000..f3c1fd705
--- /dev/null
+++ b/docs/plans/model-hub-contracts/opencode-overlay.md
@@ -0,0 +1,47 @@
+# OpenCode overlay contract
+
+How Avibe generates the OpenCode runtime config overlay (`OPENCODE_CONFIG`) in
+hub mode. Owner-locked identifier rules (spec §4.4) restated as testable
+requirements.
+
+## Provider entries
+
+- One provider entry per **standard vendor id** present in any hub-channel
+ source's model list: `anthropic`, `openai`, `zhipuai`, … Models whose vendor
+ cannot be identified go under a single `custom` provider.
+- No `avibe-` namespace anywhere (owner 07-23). Identifiers read exactly like
+ native OpenCode: `anthropic/claude-opus-4-6`, `zhipuai/glm-5.2`,
+ `custom/<model-id>`.
+- Each generated entry redirects transport to the local hub (base URL
+ `127.0.0.1:<port>` + per-protocol path) and injects the **local gateway
+ token** (never upstream credentials). Protocol/SDK per entry follows the
+ vendor's protocol as recorded on the supplying source(s).
+- Subscription-backed vendors: under Option 1, subscription sources are
+ `native_cli` channel and therefore **never** materialize as OpenCode
+ providers. `anthropic/…` in OpenCode is eligible only when a hub-channel
+ (api_key) source supplies those models. This enforces S2 scenario (b)
+ (Claude sub → non-Claude-Code clients: prohibited) structurally, in
+ addition to the code-level `allowed_origins` guard.
+
+## Menu projection
+
+- The generated provider entries enumerate exactly the models `checked` in
+ `agent-supply.menu` (plus display names). `featured|full` is a UI view
+ state; the overlay always reflects `checked`.
+- Custom model entries (manual provenance) appear under their source's vendor
+ prefix, or `custom/` when the vendor is unidentifiable.
+
+## Stability invariant (test requirement, L7)
+
+For a fixed set of checked models, the generated identifier strings are
+byte-identical across: hub⇄direct mode switches, source add/remove/reorder,
+source cooldown/failover, and engine restarts. A scenario test asserts this by
+diffing generated overlays under each perturbation.
+
+## Long-lived `opencode serve`
+
+The overlay content hash is recorded in process metadata at launch. When the
+effective overlay changes (menu edit, source vendor set change), Avibe waits
+for active work to finish, then restarts the serve process; a
+`resolution-event` of kind `channel_switch`/`switch` is NOT emitted for
+restarts (they are config events, not supply switches).
diff --git a/docs/plans/model-hub-contracts/priority.schema.json b/docs/plans/model-hub-contracts/priority.schema.json
new file mode 100644
index 000000000..dab60adf8
--- /dev/null
+++ b/docs/plans/model-hub-contracts/priority.schema.json
@@ -0,0 +1,21 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/priority.schema.json",
+ "title": "Priority",
+ "description": "The single global spend order (spec §4.2). Authoritative and fully ordered: the server always returns the complete order after any mutation; clients never compute partial reorders (S1 freeze item: authoritative ordered priority). Per-request candidates = this order filtered by 'source supplies the requested model' and channel eligibility.",
+ "type": "object",
+ "required": ["contract_version", "order"],
+ "additionalProperties": false,
+ "properties": {
+ "contract_version": { "const": 1 },
+ "order": {
+ "type": "array",
+ "description": "source ids, position 0 = spend first; MUST contain every non-deleted source exactly once",
+ "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/resolution-event.schema.json b/docs/plans/model-hub-contracts/resolution-event.schema.json
new file mode 100644
index 000000000..14c366e5d
--- /dev/null
+++ b/docs/plans/model-hub-contracts/resolution-event.schema.json
@@ -0,0 +1,40 @@
+{
+ "$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.",
+ "type": "object",
+ "required": ["id", "ts", "agent", "kind", "model_id", "reason", "human_zh", "human_en"],
+ "additionalProperties": false,
+ "properties": {
+ "id": { "type": "string" },
+ "ts": { "type": "string", "format": "date-time" },
+ "agent": { "enum": ["claude", "codex", "opencode", "system"] },
+ "kind": { "enum": ["switch", "cooldown", "recover", "skip", "mapping_applied", "channel_switch"] },
+ "model_id": { "type": "string" },
+ "from_source": { "type": ["string", "null"] },
+ "to_source": { "type": ["string", "null"] },
+ "reason": {
+ "enum": ["quota_exhausted", "rate_limited", "server_error", "network", "recovery", "manual", "mapping"],
+ "description": "Canonical error classification lives in the adapter (S1 gap ①): param/protocol/tool-compat errors surface to the caller and never produce switch events."
+ },
+ "billing_note": { "enum": [null, "entered_metered", "left_metered"], "description": "drives the gold dot in frame 01r" },
+ "human_zh": { "type": "string", "maxLength": 200 },
+ "human_en": { "type": "string", "maxLength": 200 }
+ },
+ "examples": [
+ {
+ "id": "evt_20260723a",
+ "ts": "2026-07-23T06:32:00+08:00",
+ "agent": "claude",
+ "kind": "switch",
+ "model_id": "claude-opus-4-6",
+ "from_source": "src_claudepro1",
+ "to_source": "src_anthkey01",
+ "reason": "quota_exhausted",
+ "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)"
+ }
+ ]
+}
diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
new file mode 100644
index 000000000..643b2eff2
--- /dev/null
+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
@@ -0,0 +1,75 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/runtime-dependency.schema.json",
+ "title": "RuntimeDependency",
+ "description": "Managed engine dependency manifest + status (spec §8; S3 verdict: generalize the Show Runtime managed-archive installer, effort M; process/health/config stay per-runtime). Pinned values below are the S1 survey result and are normative until the next explicit re-pin.",
+ "type": "object",
+ "required": ["manifest", "status"],
+ "additionalProperties": false,
+ "properties": {
+ "manifest": {
+ "type": "object",
+ "required": ["name", "version", "source_sha", "assets"],
+ "additionalProperties": false,
+ "properties": {
+ "name": { "const": "cliproxyapi" },
+ "version": { "type": "string" },
+ "source_sha": { "type": "string", "pattern": "^[0-9a-f]{40}$" },
+ "assets": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": ["platform", "url", "size_bytes", "sha256"],
+ "additionalProperties": false,
+ "properties": {
+ "platform": { "enum": ["darwin-arm64", "linux-amd64"] },
+ "url": { "type": "string" },
+ "size_bytes": { "type": "integer" },
+ "sha256": { "type": "string", "pattern": "^[0-9a-f]{64}$" }
+ }
+ }
+ }
+ }
+ },
+ "status": {
+ "type": "object",
+ "required": ["installed_version", "verified", "health"],
+ "additionalProperties": false,
+ "properties": {
+ "installed_version": { "type": ["string", "null"] },
+ "verified": { "type": "boolean", "description": "SHA256 of installed binary matches manifest" },
+ "listening": {
+ "type": ["object", "null"],
+ "required": ["host", "port"],
+ "additionalProperties": false,
+ "properties": {
+ "host": { "const": "127.0.0.1" },
+ "port": { "type": "integer" }
+ }
+ },
+ "health": { "enum": ["ok", "degraded", "down", "not_installed"] },
+ "last_check": { "type": ["string", "null"], "format": "date-time" }
+ }
+ }
+ },
+ "examples": [
+ {
+ "manifest": {
+ "name": "cliproxyapi",
+ "version": "v7.2.95",
+ "source_sha": "f71ec0eb6776854457892452cf28c47f0d658251",
+ "assets": [
+ { "platform": "darwin-arm64", "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/<darwin-arm64-asset>", "size_bytes": 14384655, "sha256": "c7ccc28b7db5d1799999a9e22725ccc6bd0e36d9aa023da6b52b7c1a71aad978" },
+ { "platform": "linux-amd64", "url": "https://github.com/router-for-me/CLIProxyAPI/releases/download/v7.2.95/<linux-amd64-asset>", "size_bytes": 15401775, "sha256": "826604e2dbf11913b0f373047f7bca1829eb2bab8a45d3a1916cc2534c7a9fd5" }
+ ]
+ },
+ "status": {
+ "installed_version": "v7.2.95",
+ "verified": true,
+ "listening": { "host": "127.0.0.1", "port": 15220 },
+ "health": "ok",
+ "last_check": "2026-07-23T03:40:00+08:00"
+ }
+ }
+ ]
+}
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
new file mode 100644
index 000000000..91537394b
--- /dev/null
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -0,0 +1,256 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/source.schema.json",
+ "title": "Source",
+ "description": "A supply source. Two kinds only (spec §3). 'Relay stations' are api_key sources with a custom base_url, never a third kind.",
+ "type": "object",
+ "required": [
+ "id",
+ "kind",
+ "vendor",
+ "display_name",
+ "protocol",
+ "supply_channel",
+ "billing",
+ "state",
+ "models"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "type": "string",
+ "pattern": "^src_[a-z0-9]{8,}$"
+ },
+ "kind": {
+ "enum": [
+ "subscription",
+ "api_key"
+ ]
+ },
+ "vendor": {
+ "type": "string",
+ "description": "Standard vendor id (anthropic|openai|zhipuai|kimi|xai|...) or 'custom'. Also the OpenCode provider prefix (see opencode-overlay.md)."
+ },
+ "display_name": {
+ "type": "string",
+ "maxLength": 64
+ },
+ "protocol": {
+ "enum": [
+ "anthropic",
+ "openai_responses",
+ "openai_chat",
+ "openai_compatible"
+ ]
+ },
+ "base_url": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "api_key kind only. null = vendor official default. Custom value covers relays/self-hosted gateways."
+ },
+ "supply_channel": {
+ "enum": [
+ "native_cli",
+ "hub"
+ ],
+ "description": "Resolved 2026-07-23 (README): subscription→native_cli by default (sanctioned CLI-held OAuth, per-turn dispatch), api_key→hub. Any hub-held subscription (Claude AND ChatGPT) requires the subscription_hub_experimental flag + recorded per-source consent; UI marks such sources 实验."
+ },
+ "experimental_consent_at": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "date-time",
+ "description": "Set iff this is a hub-held subscription the user explicitly consented to (subscription_hub_experimental). null otherwise."
+ },
+ "billing": {
+ "enum": [
+ "monthly",
+ "metered"
+ ]
+ },
+ "state": {
+ "type": "object",
+ "required": [
+ "status"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "status": {
+ "enum": [
+ "active",
+ "standby",
+ "cooldown",
+ "error"
+ ]
+ },
+ "retry_at": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "date-time"
+ },
+ "detail_key": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "i18n key, never raw upstream error text"
+ }
+ }
+ },
+ "usage": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "cycle_used_pct": {
+ "type": [
+ "number",
+ "null"
+ ],
+ "minimum": 0,
+ "maximum": 100
+ },
+ "month_spend_cents": {
+ "type": [
+ "integer",
+ "null"
+ ],
+ "minimum": 0
+ },
+ "currency": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "ISO 4217, e.g. CNY/USD"
+ }
+ }
+ },
+ "models": {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "required": [
+ "id",
+ "provenance"
+ ],
+ "additionalProperties": false,
+ "properties": {
+ "id": {
+ "type": "string",
+ "description": "Bare model id (no provider prefix)"
+ },
+ "display_name": {
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "provenance": {
+ "enum": [
+ "discovered",
+ "manual"
+ ],
+ "description": "manual = custom model entry (spec §5 frame 08)"
+ },
+ "discovered_at": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "format": "date-time"
+ }
+ }
+ }
+ },
+ "credential_ref": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "Opaque handle. Secret material NEVER appears in any payload (README invariant 1). null for native_cli sources (credential lives in the CLI's own store)."
+ },
+ "account_label": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "v1.1 (07-23 12:10, L4 finding): human display identity for subscription sources (e.g. '[email protected]'), for the row's mono sub-line (frame 01r). Populated from the sanctioned CLI auth surface for native_cli sources; MAY stay null for hub-held experimental sources until a later adapter rev. Never secret material."
+ },
+ "masked_credential": {
+ "type": [
+ "string",
+ "null"
+ ],
+ "description": "v1.1 (07-23 12:10, L4 finding): non-reversible display mask for api_key sources, computed by L2 ONCE at provisioning from the transient secret (rule: ≤7-char prefix + '…' + last 4, e.g. 'sk-ant-…8f2A') and persisted as display data only. Never re-derivable, never secret material."
+ }
+ },
+ "examples": [
+ {
+ "id": "src_claudepro1",
+ "kind": "subscription",
+ "vendor": "anthropic",
+ "display_name": "Claude Pro 订阅",
+ "protocol": "anthropic",
+ "base_url": null,
+ "supply_channel": "native_cli",
+ "billing": "monthly",
+ "state": {
+ "status": "active",
+ "retry_at": null,
+ "detail_key": null
+ },
+ "usage": {
+ "cycle_used_pct": 62,
+ "month_spend_cents": null,
+ "currency": null
+ },
+ "models": [
+ {
+ "id": "claude-opus-4-6",
+ "display_name": "Opus 4.6",
+ "provenance": "discovered",
+ "discovered_at": "2026-07-23T03:00:00Z"
+ }
+ ],
+ "credential_ref": null,
+ "account_label": "[email protected]",
+ "masked_credential": null
+ },
+ {
+ "id": "src_relay9c1x",
+ "kind": "api_key",
+ "vendor": "custom",
+ "display_name": "relay.example",
+ "protocol": "openai_compatible",
+ "base_url": "https://relay.example/v1",
+ "supply_channel": "hub",
+ "billing": "metered",
+ "state": {
+ "status": "cooldown",
+ "retry_at": "2026-07-23T04:00:00Z",
+ "detail_key": "models.source.cooldown.timeout"
+ },
+ "usage": {
+ "cycle_used_pct": null,
+ "month_spend_cents": 320,
+ "currency": "CNY"
+ },
+ "models": [
+ {
+ "id": "glm-5.2-air",
+ "display_name": "GLM 5.2 Air",
+ "provenance": "manual",
+ "discovered_at": null
+ }
+ ],
+ "credential_ref": "cred_a1b2c3",
+ "account_label": null,
+ "masked_credential": "key …9c1"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/docs/plans/model-hub-implementation.md b/docs/plans/model-hub-implementation.md
new file mode 100644
index 000000000..004b92606
--- /dev/null
+++ b/docs/plans/model-hub-implementation.md
@@ -0,0 +1,146 @@
+# Model Hub — Implementation Plan
+
+Status: draft v1 · 2026-07-23 · follows the signed product spec
+Spec (signed 2026-07-23): `docs/plans/model-hub.md`
+Design source: `../avibe-docs/design.pen` frames `产品改造 V4 01r – 09`
+Lane workflow standard: `~/vibe-remote-project/.agents/skills/pr-delivery-loop/SKILL.md`
+
+---
+
+## 0. Ground rules for this effort
+
+- Contracts freeze **before** parallel lanes open (§2). Deviations route through
+ the orchestrator, never lane-to-lane.
+- Every lane: own worktree (`.worktrees/avibe/<branch>/`), one branch one PR,
+ non-draft, Codex-bot review loop owned by the lane, zero unresolved threads
+ on head before hand-back. Orchestrator does final review + merge.
+- Serializer completeness rule (issue #939 lesson): every new config field must
+ be covered by `config_to_payload` and the CI completeness guards in the same PR.
+- User-facing strings via `ui/src/i18n/en.json` + `zh.json` (zh copy comes from
+ the V4 mocks verbatim; en needs a wording pass — Hub / Direct locked).
+- User-facing verification happens in the local Incus regression environment
+ only; hub behavior additionally gets scenario-level automation (§5).
+
+## 1. Milestones (dependency order)
+
+| M | Content | Exit gate |
+| --- | --- | --- |
+| M0 | **De-risk spikes** (serial, small) | spike reports merged as docs |
+| M1 | Hub core: engine runtime + config schema + REST API + event log | contract tests green; engine runs supervised on 127.0.0.1 |
+| M2 | Backend injection: Claude env / Codex `-c` / OpenCode overlay + Direct-mode preservation & mode switch | per-backend scenario tests green in both modes |
+| M3 | UI: Models page, source dialogs, OAuth connect, backend supply-mode card, model menus, migration dialog | pixel check vs design.pen; `npm run build` gate |
+| M4 | Migration backend (scan/import/re-auth) + wizard & banner triggers + empty states | non-destructive property proven by tests (originals byte-identical) |
+| M5 | E2E scenario sweep + Incus regression + user docs (avibe-docs EN/ZH) | owner acceptance checklist (spec §11) passes end-to-end |
+
+M0 spikes:
+- **S1 engine capability re-verification** (spec §8): pin current CPA release,
+ verify from source: OAuth vendor list & flow shapes (map to connect forms
+ A/B/C), protocol conversion matrix, model listing, auth file formats,
+ management API. Output: `docs/plans/model-hub-engine-survey.md` + pinned
+ version/SHA256. Blocks M1 scope decisions.
+- **S2 subscription-reuse ToS & billing review** (spec §10.2): product-risk
+ memo per vendor. Blocks *defaults* for subscription flows, not the build.
+- **S3 runtime-dependency reuse audit**: confirm the Show Runtime managed-
+ dependency machinery (manifest, download, verify, prepare) generalizes;
+ decide reuse vs sibling implementation. Half-day, folds into S1 report.
+
+## 2. Contracts to freeze (files, before lanes open)
+
+Location: `docs/plans/model-hub-contracts/` — JSON Schema + one example payload
+per type. UI and backend lanes both cite these; changes go through the
+orchestrator only.
+
+1. `source.schema.json` — Source: id, kind(subscription|api_key), vendor,
+ protocol, base_url?, display_name, billing(monthly|metered), state
+ (active|standby|cooldown{retry_at}), usage(cycle_pct?|month_spend?),
+ models[] (supplied model ids), custom_models[].
+2. `priority.schema.json` — ordered source-id list (single global list).
+3. `agent-supply.schema.json` — per backend: mode(hub|direct), menu_kind
+ (fixed|open), current{model_id, source_id}?, mappings[] (fixed-menu only:
+ builtin_id → target_model_id), menu{featured|full, checked_ids[]} (open only).
+4. `resolution-event.schema.json` — 最近切换 entry: ts, agent, from_source,
+ to_source?, reason(quota|error|recovery|cooldown_skip), billing_impact?.
+5. `oauth-flow.schema.json` — flow_id, form(A_paste_code|B_device_code|
+ C_callback_replay), state machine states, url?, device_code?, error?;
+ mirrors existing `BackendOAuthPanel` semantics.
+6. `migration-scan.schema.json` — per backend: detected items(kind, masked
+ detail, action(import|reauth|controlled_import), selected).
+7. `api.md` — REST endpoint list (paths, verbs, request/response schema refs,
+ error envelope): sources CRUD + test/discovery, priority reorder, agent
+ mode switch, mappings CRUD, menu config, custom models, events feed,
+ migration scan/apply, oauth start/status/submit/cancel.
+8. `opencode-overlay.md` — generated provider entries (standard vendor ids +
+ `custom/`), transport redirection, gateway token injection, serve
+ config-hash restart rule; identifier stability invariant stated as a test
+ requirement.
+
+## 3. Lanes
+
+Dispatch preference (owner 2026-07-13): balance claude/codex; rigor-critical
+backend → codex-lean; product-voice / design-fidelity UI → claude-lean.
+Every brief cites: spec, this plan, the contracts dir, repo `AGENTS.md`,
+`pr-delivery-loop` SKILL — all by absolute path — plus explicit file scope and
+no-touch zones.
+
+| Lane | Executor lean | Scope (files) | Depends on |
+| --- | --- | --- | --- |
+| L1 engine runtime & credentials | codex | new `vibe/model_hub_runtime/` (or Show-Runtime generalization per S3), engine supervisor, key/token generation, fail-closed + Direct escape | S1/S3 |
+| L2 config schema + API + events | codex | `config/v2_config.py` (sole owner), new `core/handlers/model_hub*.py`, REST endpoints, serializer guards, event log store | contracts; L1 interface |
+| L3 backend injection & modes | codex | `modules/agents/claude_agent.py` / `codex/` / `opencode/` (env, `-c`, overlay + serve hash), mode plumbing; Direct path untouched-by-default proof | L2 API |
+| L4 UI: Models page + sources + OAuth connect | claude | `ui/src/components/settings/models/**` (new dir), add-source menu/dialogs, OAuth dialog reusing `BackendOAuthPanel` shell | contracts |
+| L5 UI: menus + mapping + backend card + migration dialog | claude | `ui/src/components/settings/models/menus/**`, backend page 供给方式 card, migration dialog | contracts; L4 shared primitives |
+| L6 migration backend | codex | scan/import of native configs (Claude settings.json, Codex auth.json controlled import, opencode providers), re-auth orchestration, non-destructive tests | L2 |
+| L7 scenario tests + regression + docs + availability guard | either (split) | `tests/scenarios/model_hub/**` catalog + harness, Incus verification script hooks, `avibe-docs` user docs EN/ZH; **engine-asset availability guard** (decided 07-23: mirror pinned CPA assets into Avibe-owned release storage pre-GA, manifest → mirror URLs, upstream as provenance; same manifest-verified backup/recovery pattern as Show Runtime) + **platform-set expansion** (07-23 13:13, from L1 review: add linux-arm64 / darwin-x64 assets — pin + SHA256 + schema platform-enum rev — together with the mirror work; until then unsupported hosts fail closed with Direct as escape hatch, scenario `model_hub_engine_platform_unsupported`) | all |
+
+No-touch zones: only L2 edits `config/v2_config.py`; only L3 edits
+`modules/agents/**`; L4/L5 split `ui/src/components/settings/**` by
+subdirectory as listed; nobody edits contracts in-lane.
+
+Sequencing: S1–S3 → freeze contracts → L1+L2 start (codex ×2) with L4 in
+parallel (claude); L3/L5 join as their dependencies stabilize; L6 after L2;
+L7 continuous, finalizes last. Rough sizes: L1 M, L2 L, L3 M, L4 L, L5 M,
+L6 M, L7 M.
+
+## 4. Product gates
+
+- **Resolved (owner 2026-07-23 10:33, after S2):** default = hybrid supply —
+ subscription sources are `native_cli` channel (per-turn channel dispatch,
+ CLI-sanctioned OAuth); hub-held subscription login (incl. Claude-in-engine)
+ ships ONLY behind `subscription_hub_experimental` with explicit ban-risk
+ consent (copy from S2 §9) and per-source opt-in. API-key paths ungated.
+ L3 owns channel dispatch; L2 owns the flag + consent recording; L4 owns
+ the consent dialog + 实验 marking.
+- Cross-vendor auto-fallback remains default-off experimental (spec §9);
+ no lane builds UI for it beyond the advanced placeholder row.
+- Mode default: existing users stay in Direct until they migrate (no silent
+ flips); fresh installs default to Hub. Wizard/banner triggers per spec §6.
+
+## 5. Verification layers
+
+- **Unit**: resolution projection, serializer completeness, overlay generation
+ (identifier stability invariant), migration parsers.
+- **Contract**: REST API against `model-hub-contracts` schemas (both
+ directions), engine adapter against pinned engine version.
+- **Scenario**: `tests/scenarios/model_hub/catalog.yaml` — at minimum:
+ quota-exhausted failover & recovery switchback, priority reorder takes
+ effect next turn, mapping applies to CC only, OpenCode identifier stability
+ across mode switch, migration non-destructiveness, OAuth forms A/B/C happy
+ path + timeout/cancel. Scenario IDs appear in PR descriptions.
+- **Behavioral (Incus)**: real backend turns in both modes; 最近切换 log
+ reflects induced quota errors; UI pixel pass vs exported V4 frames.
+
+## 6. Open items carried from spec §10
+
+1. Remaining mocks (empty state / Dark / mobile / copy pass) — feed L4/L5;
+ not blocking lane start (contracts govern behavior, mocks govern polish).
+2. en.json wording pass (Hub / Direct locked; rest of EN copy during L4/L5).
+3. `design.pen` V4 frames must be saved (Cmd+S) before L4/L5 dispatch — lanes
+ verify against the exported frames.
+
+## 7. Kickoff checklist (orchestrator)
+
+- [ ] Owner approves this plan (lanes, sequencing, gates).
+- [ ] design.pen saved; V4 frames re-exported into a stable reference dir.
+- [ ] S1–S3 dispatched (S1/S3 codex, S2 research either).
+- [ ] Contracts dir authored from S1 output; frozen and announced.
+- [ ] L1/L2/L4 briefs written (scope, no-touch, contracts, review protocol) and dispatched.
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
new file mode 100644
index 000000000..c7187a937
--- /dev/null
+++ b/docs/plans/model-hub.md
@@ -0,0 +1,239 @@
+# Model Hub — Product Spec
+
+Status: **signed** (2026-07-23 02:58) · amended v1.1 (2026-07-23 10:40) per spike
+S2 findings — subscription supply channels & the consent-gated experimental flag
+(owner decision 10:33: hybrid supply by default; hub-held Claude subscription
+login offered ONLY as a consent-gated experimental feature)
+Owner decisions incorporated through: 2026-07-23 10:33 (+08:00)
+Design source: `../avibe-docs/design.pen`, frames `产品改造 V4 01r – V4 09` (Light)
+Discussion record: Show Page of session `sesb7r2qwb4z4` (rounds 1–10, with superseded
+explorations V2/V3 archived inline)
+
+---
+
+## 1. Background
+
+Today each agent backend (Claude Code / Codex / OpenCode) carries its own
+provider configuration, and Avibe edits the user's **native** CLI config files
+(`settings.json`, `config.toml`, opencode config). Credentials, base URLs and
+model choices are scattered per backend; users must understand each CLI's
+config model; Avibe mutates user-owned files.
+
+Meanwhile many users own **subscriptions** (Claude Pro/Max, ChatGPT Plus/Pro)
+plus one or more **API keys** (official vendors or OpenAI/Anthropic-compatible
+endpoints). They want subscription quota consumed first, automatic fallback
+when it runs out, automatic switch-back on recovery — without understanding
+base URLs, protocol conversion, account pools or routers.
+
+## 2. Product promise (user-facing, locked)
+
+1. Connect a source once — every Agent can use it.
+2. Subscriptions are consumed first (already paid); when quota runs out
+ Avibe switches to the next source automatically and switches back on
+ recovery. Work never stalls. (Mechanism, v1.1: per-turn channel dispatch —
+ subscriptions burn via the CLI's sanctioned native channel; the hub
+ arbitrates the api-key tier. See §4.1/§4.2.)
+3. Priority order is user-owned: the list order **is** the spending order.
+ Nothing is hard-coded; paid sources are always visibly marked.
+
+Core persona: individual users who already pay for Claude Pro/Max or ChatGPT
+Plus/Pro ("spend what I bought first"). Secondary: API-key-only users.
+Explicit non-persona: relay-station operators ("站长") — Avibe ships no
+operations console.
+
+## 3. Vocabulary (locked; UI copy uses ONLY these nouns)
+
+| Concept | zh | en | Notes |
+| --- | --- | --- | --- |
+| The settings surface | 模型 | Models | Single nav entry between 通讯平台 and 后端 |
+| Where tokens come from | 来源 | Source | Two kinds only: 订阅账号 (subscription account, OAuth) and API Key (key + editable base URL) |
+| Spend order | 优先级 | Priority | One global draggable list; order = spend order |
+| Supply mode per backend | 中枢模式 / 直连模式 | Hub / Direct | Hub = default & recommended; Direct = legacy native-config mode, kept but not recommended |
+
+Banned from UI copy: 网关/gateway, 路由/router, 逻辑模型, Provider(作为界面
+名词), 账号池, 中转站(as a **category**; the word may appear only inside
+helper copy as an example use-case for a custom base URL). "Relay station" is
+NOT a source type — it is an API Key with a custom base URL (owner decision
+07-23; avoids the unanswerable official/unofficial classification for
+OpenAI/Anthropic-compatible vendor endpoints).
+
+## 4. Architecture: upstream / hub / downstream
+
+### 4.1 Upstream — Sources (global, will keep growing)
+
+Each source carries: kind (subscription | api_key), credential, protocol
+(anthropic | openai | openai_compatible …), an editable base URL (api_key
+kind; prefilled for known vendors), a **model list** it can supply
+(auto-discovered where possible, e.g. `/models`; manually extendable via
+custom model entries), billing type (包月 | 按量 ¥), state
+(active | standby | cooling-down with retry ETA), and usage (subscription
+cycle % / monthly spend).
+
+**Supply channel (amended v1.1, per S2 ToS review).** Each source has a
+`supply_channel`:
+
+- `native_cli` — the credential lives in the CLI's own sanctioned store and
+ quota is consumed by launching the CLI in its native form. Default for
+ subscription sources (mandatory-default for Claude subscriptions:
+ Anthropic prohibits and server-enforces credential use outside Claude
+ Code; see `model-hub-tos-review.md`).
+- `hub` — the engine holds the credential and re-originates requests.
+ Default for api_key sources. For subscription sources this channel is
+ available ONLY behind the consent-gated experimental flag
+ (`subscription_hub_experimental`): explicit ban-risk consent copy (S2 §9),
+ per-source opt-in, visible "experimental" marking in the source row.
+ This applies to Claude and ChatGPT subscriptions alike; the flag ships,
+ but nothing enables it silently.
+
+The same model may be supplied by multiple sources; that is exactly what the
+global priority list arbitrates.
+
+### 4.2 Hub — request resolution (step 0 + three steps)
+
+0. **Channel dispatch (amended v1.1)** — per turn, before launch: if the
+ top-priority eligible source for the requesting agent is `native_cli`
+ (e.g. a healthy Claude subscription for Claude Code), launch the CLI
+ natively with zero injection — sanctioned form, hub untouched. If that
+ source is quota-exhausted/cooling (inferred from prior native-turn errors
+ plus recovery timers), launch with hub injection so steps 1–3 arbitrate
+ the hub-channel tier. Recovery flips the next turn back. This is possible
+ because Avibe launches backends per request; switching never happens
+ mid-process. `native_cli` sources are eligible only for their sanctioned
+ client (Claude sub → Claude Code); enforced in code via
+ `allowed_origins`-style binding.
+1. **Mapping** — requested model ID → actual model. Identity by default.
+ Only fixed-menu agents (Claude Code / Codex) can override, per-agent
+ (e.g. Claude Code's `claude-opus-4-6` → `glm-5.2`). Mapping is an explicit,
+ deterministic user choice.
+2. **Candidates** — all sources able to supply that model, ordered by the
+ single global priority list (filtered per request; no per-model priority).
+3. **Supply** — use candidate #1; on quota-exhausted/429, transient 5xx or
+ network failure enter cooldown and take the next; switch back on recovery.
+ Convert protocol when needed. Every switch is appended to the
+ human-readable 最近切换 log.
+
+Error taxonomy (no blind fallback): parameter/protocol/tool-compat errors
+surface to the caller; 401 → refresh then retry; 429 / explicit quota
+exhaustion / transient 5xx / network → cooldown + next candidate. Once
+streaming has started, no transparent retry.
+
+**Mapping ≠ automatic cross-vendor fallback.** The latter ("Claude quota
+gone → serve GPT") stays an experimental, default-off advanced flag with
+visible per-event marking, pending capability/ToS verification. Architecture
+reserves `allowed_origins` to restrict which clients a subscription
+credential may serve.
+
+### 4.3 Downstream — Agents
+
+| Agent | Menu | Notes |
+| --- | --- | --- |
+| Claude Code | fixed (built-in model IDs) | wants another vendor's model ⇒ per-agent mapping in its 模型菜单 |
+| Codex | fixed | same |
+| OpenCode + future in-house agents | open | follows upstream model lists; supports user-defined custom model entries |
+
+### 4.4 OpenCode identifier scheme (locked 07-23)
+
+OpenCode models are `provider/model-id`. Rules:
+
+- The provider segment uses the **standard vendor id** (`anthropic/`,
+ `openai/`, `zhipuai/`, …) — identical to native OpenCode usage. No
+ `avibe-` namespace (owner: keep it simple). Unrecognizable vendors fall
+ back to a single `custom/` provider.
+- Hub mode merely redirects those providers' transport to the local hub in
+ the generated runtime config overlay. Therefore **identifiers are stable
+ across Hub/Direct switches and across source add/remove/failover** —
+ never encode a concrete source into the provider segment.
+- Users never hand-assemble the string. Menu checkboxes pick models; the
+ custom-model form generates and previews the identifier (source + model ID
+ in → `zhipuai/glm-5.2-air` out). A custom model entry is, in data terms, a
+ supplement to that source's supply list.
+
+## 5. Surfaces (design.pen V4 frames)
+
+| # | Frame | Content contract |
+| --- | --- | --- |
+| 01r | 设置 · 模型 main page | One page, two bands. **来源**: global list; drag handle + priority number; per-row icon, name, mono sub (account/key id; cooldown ETA lives here), usage column (subscription progress bar / monthly ¥), fixed-width aligned chip columns 包月/按量¥ and 使用中/备用/暂不可用; supply list appears ONLY as hover tooltip on icon/title; header = one-line policy sentence + status pill; 添加来源 button in card header. **Agent**: one row per backend — name + 菜单固定/菜单开放 badge, current supply as a composite pill `model | ● source` (UI, not copy; friendly names here), mode chip 中枢 Hub / 直连 Direct, action 模型菜单 / 接入中枢. Below: 最近切换 (3 rows, human phrasing, view-all) and a single 高级 row (跨厂商自动顶替 default-off · 请求日志 · 诊断). |
+| 02 | 后端 · Claude Code | 供给方式 card: two radio options — 中枢模式 Hub (推荐·默认; supply managed on Models page; native config untouched; "打开模型页") and 直连模式 Direct (legacy behavior preserved verbatim; detect strip "检测到既有直连配置 → 导入中枢…"). CLI path + connectivity test cards unchanged from current page. |
+| 03 | 迁移对话框 | Non-destructive: per-item checklist grouped by backend. API keys + base URLs → direct import; subscription OAuth → **keep_native** by default (v1.1: stays in the CLI's sanctioned store and becomes a native_cli source; hub-held import only via the consent-gated experimental flag); Codex `auth.json` → controlled import behind the same flag. Footer promise: originals never modified/deleted; Direct always available. Triggers: first open after upgrade, setup wizard, backend-page banner. |
+| 06r/07 | 添加来源 | Dropdown menu on the button (no type-chooser dialog): 连接 Claude 订阅 / 连接 ChatGPT 订阅 / 添加 API Key…. The API Key form is the only form dialog: vendor select (official vendors prefill base URL; 自定义 for compatible endpoints), key, base URL, test-and-add with model-discovery feedback ("发现 23 个可用模型"). |
+| 09 | 连接订阅 | Reuses the existing `BackendOAuthPanel` / `AgentAuthService` state machine (start → 2s-poll → awaiting → verifying → success/failed/cancelled; 15-min timeout; cancel). Three declared flow forms, one shell: **A** paste auth code (Claude), **B** device code, self-completing (ChatGPT/Copilot), **C** paste redirected callback URL for replay (loopback unreachable from remote browsers). URL and device code always carry copy buttons (remote/phone operation). New OAuth subscriptions = declare a form, inherit the shell. |
+| 04 | 模型菜单 · Claude Code | Mapping table: left = built-in real model IDs (mono, not editable), right = supply (default 跟随原生 · 按优先级供给; override e.g. → `glm-5.2` with per-row reset and a persistent capability warning: thinking/cache/tool semantics not fully equivalent). Per-agent scope. 恢复全部默认 in footer. |
+| 05r | 模型菜单 · OpenCode | Grouped BY provider prefix (`anthropic/` · `openai/` · `zhipuai/` + plain-language annotation) — one taxonomy, full identifier visible by construction (group prefix + mono row ID); friendly name is secondary text. 精选/全量 toggle (default featured); checkbox = appears in OpenCode's model picker; colored dots = supplying sources; custom rows carry 自定义 badge + edit. |
+| 08 | 添加自定义模型 | Fields: source, model ID, optional display name → live identifier preview with the vendor-id rule above. |
+
+Pending mocks (not blocking sign-off): first-run empty state, Dark variants,
+mobile, plus a full copy pass under the rule **"if UI style can express it,
+don't write copy"** (established 07-22 and applied to 01r).
+
+## 6. Modes & migration
+
+- **Hub (default)**: Avibe injects runtime-only configuration into processes
+ it launches (env vars for Claude Code; `-c` overrides for Codex app-server;
+ `OPENCODE_CONFIG` overlay for OpenCode, gateway-config hash tracked for
+ long-lived `opencode serve`). Native user configs are never written.
+- **Direct (legacy, kept, not recommended)**: current behavior preserved —
+ per-backend native config editing (auth tabs, API key + base URL, writes to
+ `settings.json` etc.), useful for diagnostics and self-managed setups.
+- Backends can differ in mode; the Models page Agent rows surface per-backend
+ mode with one-click 接入中枢.
+- Migration is copy-only and reversible; see frame 03 contract above.
+
+## 7. Security boundaries (amended v1.1)
+
+- Three credential rings, never mixed: management key (Avibe→engine admin
+ API), local gateway token (the only thing backends receive), upstream
+ credentials (API keys and — only under the consent-gated experimental
+ flag — subscription OAuth tokens; engine-held, local runtime dir with
+ restricted permissions, not `~/.cli-proxy-api`). By default the engine
+ never holds subscription OAuth tokens: `native_cli` subscriptions keep
+ their credential in the CLI's own sanctioned store (spec §4.1).
+- Credentials never enter Avibe Cloud, IM messages or logs. Static keys may
+ integrate with Avibe Vault; no duplicate key entry across surfaces.
+- Gateway failure is fail-closed; Direct mode is the explicit escape hatch.
+
+## 8. Data plane
+
+The hub's data plane is a **replaceable, Avibe-managed, versioned runtime
+dependency** (current candidate: CLIProxyAPI ~14 MiB download / ~41 MiB
+binary): pinned version + SHA256, 127.0.0.1-only listener, random management
+key and gateway token, lifecycle owned by Avibe. Its YAML/auth files/manage
+UI are **not** product surface. The capability matrix (supported OAuth
+vendors, protocol conversions, model-fallback plugin maturity) was a
+point-in-time survey and MUST be re-verified from source/docs at
+implementation time; subscription reuse across clients/vendors additionally
+requires billing/quota/ban-risk and ToS review before any default-on
+behavior.
+
+## 9. Explicit non-goals (v1)
+
+- No per-model priority ordering (global list only, filtered per request).
+- No automatic cross-vendor substitution by default (advanced flag,
+ experimental, visible marking).
+- No billing-grade accounting, multi-tenant pools, or operator consoles.
+- No third source category ("relay" merged into API Key).
+
+## 10. Open items
+
+1. Remaining mocks: empty state / Dark / mobile / copy pass (§5 pending);
+ plus V4-01r/06r/09 touch-ups for supply channels: source-row 原生供给
+ note, experimental marking, and the consent dialog for
+ `subscription_hub_experimental` (copy from S2 §9).
+2. ~~ToS + billing verification~~ **Done (spike S2, 2026-07-23)** —
+ `model-hub-tos-review.md`; verdicts folded into §4.1/§4.2/§7. Residual:
+ keep the consent copy in sync with vendor terms at release time.
+3. ~~Data-plane capability re-verification~~ **Done (spike S1, 2026-07-23)**
+ — `model-hub-engine-survey.md`; engine pinned v7.2.95, OAuth is
+ runtime-declared (contracts), adapter owns error classification & events.
+4. Naming final check in EN locale: Hub / Direct wording in en.json
+ (中文已定: 中枢/直连; alternates 托管/自管、统一/独立 were considered and
+ dropped).
+5. Implementation plan & lane split (separate doc once this spec is signed).
+
+## 11. Owner acceptance checklist (~10 min)
+
+- [ ] §2 promises and §3 vocabulary match intent; nothing else leaks into UI copy.
+- [ ] §4.2 resolution rules: mapping/priority split, error taxonomy, no-retry-after-stream.
+- [ ] §4.4 identifier rules (vendor ids, `custom/` fallback, stability guarantee).
+- [ ] §5 frame contracts match the V4 mocks you reviewed (01r/02/03/04/05r/06r/07/08/09).
+- [ ] §6 Direct mode preservation + migration triggers acceptable.
+- [ ] §8 data-plane posture (managed dependency, re-verify caveat) acceptable.
diff --git a/pyproject.toml b/pyproject.toml
index 246b6b725..9ae751f5d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -143,5 +143,6 @@ markers = [
[dependency-groups]
dev = [
+ "jsonschema>=4.26.0",
"pytest>=9.0.3",
]
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 2f59953e4..6c7b1373b 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -8,6 +8,16 @@ navigation:
- Read that capability's observations.yaml.
- Read the listed scenario test files before changing production code.
capabilities:
+ - id: model_hub
+ name: Model Hub source resolution and supply configuration
+ status: active
+ catalog: tests/scenarios/model_hub/catalog.yaml
+ observations: tests/scenarios/model_hub/observations.yaml
+ scenario_tests: []
+ unit_or_contract_tests:
+ - tests/test_model_hub_api.py
+ - tests/test_model_hub_config.py
+ - tests/test_model_hub_resolution.py
- id: harness_failure_recovery
name: Harness per-Session failure recovery
status: active
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
new file mode 100644
index 000000000..f3af8aafe
--- /dev/null
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -0,0 +1,73 @@
+version: 1
+capability:
+ id: model_hub
+ name: Model Hub source resolution and supply configuration
+ canonical_tests:
+ - tests/test_model_hub_api.py
+ - tests/test_model_hub_config.py
+ - tests/test_model_hub_resolution.py
+status_legend:
+ covered: closed-loop scenario coverage exists
+ partial: unit or contract coverage exists but the cross-lane loop is incomplete
+ gap: owned by a later lane or integration pass
+scenarios:
+ - id: MH-RES-001
+ name: Quota-exhausted failover and recovery switchback
+ status: partial
+ kind: recovery
+ 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
+ kind: ordering
+ layer: unit_contract
+ test: tests/test_model_hub_api.py::test_model_hub_rest_api_contract
+ - id: MH-MAP-001
+ name: Mapping applies to Claude Code only
+ status: partial
+ kind: mapping
+ layer: unit_contract
+ test: tests/test_model_hub_resolution.py::test_mapping_is_scoped_to_the_requesting_backend
+ - id: MH-OC-001
+ name: OpenCode identifiers stay stable across mode switches
+ status: gap
+ kind: stability
+ layer: scenario
+ - id: MH-MIG-001
+ name: Migration copies without modifying native configuration
+ status: gap
+ kind: migration
+ layer: scenario
+ - id: MH-OAUTH-A-001
+ name: Paste-code OAuth happy path
+ status: partial
+ kind: oauth
+ layer: contract
+ test: tests/test_model_hub_api.py::test_model_hub_rest_api_contract
+ - id: MH-OAUTH-B-001
+ name: Device-code OAuth happy path
+ status: gap
+ kind: oauth
+ layer: scenario
+ - id: MH-OAUTH-C-001
+ name: Callback-replay OAuth happy path
+ status: gap
+ kind: oauth
+ layer: scenario
+ - id: MH-OAUTH-ERR-001
+ name: OAuth timeout and cancel terminate cleanly
+ status: partial
+ kind: timeout_cancel
+ layer: contract
+ test: tests/test_model_hub_api.py::test_model_hub_rest_api_contract
+next_priority:
+ - MH-RES-001
+ - MH-PRI-001
+ - MH-MAP-001
+ - MH-OC-001
+ - MH-MIG-001
+ - MH-OAUTH-A-001
+ - MH-OAUTH-B-001
+ - MH-OAUTH-C-001
+ - MH-OAUTH-ERR-001
diff --git a/tests/scenarios/model_hub/observations.yaml b/tests/scenarios/model_hub/observations.yaml
new file mode 100644
index 000000000..4fd666c7c
--- /dev/null
+++ b/tests/scenarios/model_hub/observations.yaml
@@ -0,0 +1,20 @@
+version: 1
+capability: model_hub
+observations:
+ - id: MH-OBS-001
+ source: engine-survey-s1
+ summary: Engine fallback is broader than the signed taxonomy, so the adapter owns the per-source candidate loop.
+ affects:
+ - MH-RES-001
+ - id: MH-OBS-002
+ source: engine-survey-s1
+ summary: Engine usage events contain inbound credential material and remain disabled; Model Hub emits its own redacted events.
+ affects:
+ - MH-RES-001
+ - id: MH-OBS-003
+ source: engine-survey-s1
+ summary: OAuth presentation is runtime-declared rather than inferred from a vendor table.
+ affects:
+ - MH-OAUTH-A-001
+ - MH-OAUTH-B-001
+ - MH-OAUTH-C-001
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
new file mode 100644
index 000000000..e7ad4ccbd
--- /dev/null
+++ b/tests/test_model_hub_api.py
@@ -0,0 +1,1072 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from datetime import datetime, timezone
+from pathlib import Path
+
+import pytest
+from jsonschema import Draft7Validator, FormatChecker
+
+from config.v2_config import (
+ ModelHubAgentSupplyConfig,
+ ModelHubConfig,
+ ModelHubSourceStateConfig,
+)
+from core.handlers.model_hub.adapter import (
+ EngineHealth,
+ EngineStatus,
+ OAuthFlowState,
+ RawCallOutcome,
+ RawOutcomeKind,
+)
+from core.handlers.model_hub.events import BoundedEventLog, ResolutionEvent
+from core.handlers.model_hub.oauth import OAuthFlowRegistry
+from core.handlers.model_hub.revocations import CredentialRevocationJournal
+from core.handlers.model_hub.service import ModelHubError, ModelHubService
+from tests.ui_server_test_helpers import csrf_headers
+from vibe import ui_server
+from vibe.ui_server import app
+
+CONTRACTS = Path("docs/plans/model-hub-contracts")
+
+
+def _schema(name: str) -> dict:
+ return json.loads((CONTRACTS / name).read_text(encoding="utf-8"))
+
+
+def _assert_valid(name: str, payload: dict) -> None:
+ errors = sorted(
+ Draft7Validator(_schema(name), format_checker=FormatChecker()).iter_errors(payload),
+ key=lambda error: list(error.path),
+ )
+ assert not errors, [error.message for error in errors]
+
+
+class MemoryStore:
+ def __init__(self):
+ self.config = ModelHubConfig(
+ agents={
+ backend: ModelHubAgentSupplyConfig.default(backend, mode="hub")
+ for backend in ("claude", "codex", "opencode")
+ }
+ )
+
+ def load(self):
+ return self.config
+
+ def save(self, config):
+ self.config = config
+
+
+class FakeInvokeHandle:
+ def __init__(self, outcome):
+ self._outcome = outcome
+
+ @property
+ def stream(self):
+ return None
+
+ async def outcome(self):
+ return self._outcome
+
+
+class FakeAdapter:
+ def __init__(self):
+ self.secret_lengths = []
+ self.revoked = []
+ self.cancelled = []
+ self.synced = []
+ self.flows = {}
+ self.fail_sync = False
+ self.fail_cancel = False
+
+ async def ensure_installed(self):
+ return await self.status()
+
+ async def start(self):
+ return await self.status()
+
+ async def stop(self):
+ return None
+
+ async def status(self):
+ return EngineStatus(
+ health=EngineHealth.OK,
+ installed_version="v7.2.95",
+ verified=True,
+ listen_host="127.0.0.1",
+ listen_port=15220,
+ last_check_iso="2026-07-23T03:40:00+00:00",
+ )
+
+ async def gateway_token(self):
+ return "local-gateway-test-token"
+
+ async def provision_credential(self, vendor, protocol, secret, base_url):
+ self.secret_lengths.append(len(secret))
+ return "cred_test123"
+
+ async def revoke_credential(self, credential_ref):
+ self.revoked.append(credential_ref)
+
+ async def sync_sources(self, bindings):
+ self.synced.append(tuple(bindings))
+ if self.fail_sync:
+ raise RuntimeError("upstream failure with sk-secret-material")
+
+ async def discover_models(self, vendor, protocol, base_url, credential_ref):
+ return ("claude-opus-4-6", "claude-sonnet-4-6")
+
+ async def invoke(self, source_id, model_id, request, stream, origin):
+ return FakeInvokeHandle(
+ RawCallOutcome(
+ kind=RawOutcomeKind.SUCCESS,
+ http_status=200,
+ error_code=None,
+ redacted_message=None,
+ stream_started=False,
+ model_id=model_id,
+ source_id=source_id,
+ )
+ )
+
+ def _flow(self, source_id, flow_id):
+ return OAuthFlowState(
+ flow_id=flow_id,
+ source_id=source_id,
+ vendor="anthropic",
+ state="awaiting_action",
+ auth_url="https://claude.ai/oauth/authorize?test=true",
+ device_code=None,
+ expects="paste_code",
+ instructions_key="models.oauth.claude.paste_code",
+ error_key=None,
+ expires_at_iso="2026-07-23T04:15:00+00:00",
+ credential_ref=None,
+ )
+
+ async def start_oauth(self, source_id, vendor):
+ flow = self._flow(source_id, f"oaf_{len(self.flows) + 1:08d}")
+ flow = OAuthFlowState(**{**flow.__dict__, "vendor": vendor})
+ self.flows[flow.flow_id] = flow
+ return flow
+
+ async def oauth_status(self, flow_id):
+ return self.flows[flow_id]
+
+ async def submit_oauth(self, flow_id, value):
+ self.secret_lengths.append(len(value))
+ flow = OAuthFlowState(**{**self.flows[flow_id].__dict__, "state": "verifying"})
+ self.flows[flow_id] = flow
+ return flow
+
+ async def cancel_oauth(self, flow_id):
+ self.cancelled.append(flow_id)
+ if self.fail_cancel:
+ raise RuntimeError("temporary engine failure")
+
+
+def _service(tmp_path):
+ store = MemoryStore()
+ adapter = FakeAdapter()
+ service = ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "events.json"),
+ native_oauth_adapter=adapter,
+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
+ now=lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc),
+ )
+ return service, store, adapter
+
+
+def _assert_envelope(payload: dict, *, ok: bool = True):
+ assert payload["ok"] is ok
+ assert payload["contract_version"] == 1
+
+
+def test_model_hub_rest_api_contract(monkeypatch, tmp_path):
+ """Scenarios: MH-PRI-001, MH-OAUTH-A-001, MH-OAUTH-ERR-001."""
+
+ service, store, adapter = _service(tmp_path)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+ headers = csrf_headers(client, base_url)
+
+ response = client.get("/api/models/sources", base_url=base_url)
+ body = response.get_json()
+ _assert_envelope(body)
+ assert body["sources"] == []
+
+ response = client.post(
+ "/api/models/sources",
+ json={
+ "kind": "subscription",
+ "vendor": "anthropic",
+ "display_name": "Experimental subscription",
+ "supply_channel": "hub",
+ },
+ headers=headers,
+ base_url=base_url,
+ )
+ error = response.get_json()
+ assert response.status_code == 409
+ _assert_envelope(error, ok=False)
+ assert error["error"] == "consent_required"
+ assert error["detail"] == "modelHub.errors.consent_required"
+
+ fake_key = "sk-test-never-persist-this"
+ response = client.post(
+ "/api/models/sources",
+ json={
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Anthropic API Key",
+ "protocol": "anthropic",
+ "key": fake_key,
+ },
+ headers=headers,
+ base_url=base_url,
+ )
+ assert response.status_code == 201
+ body = response.get_json()
+ _assert_envelope(body)
+ source = body["source"]
+ _assert_valid("source.schema.json", source)
+ source_id = source["id"]
+ assert source["masked_credential"] == "sk-test…this"
+ assert fake_key not in json.dumps(store.config.to_payload())
+ assert adapter.secret_lengths[0] == len(fake_key)
+
+ response = client.put(
+ "/api/models/priority",
+ json={"order": []},
+ headers=headers,
+ base_url=base_url,
+ )
+ error = response.get_json()
+ _assert_envelope(error, ok=False)
+ assert error["error"] == "invalid_priority_order"
+
+ response = client.put(
+ "/api/models/priority",
+ json={"order": [source_id]},
+ headers=headers,
+ base_url=base_url,
+ )
+ priority = response.get_json()
+ _assert_envelope(priority)
+ _assert_valid("priority.schema.json", {"contract_version": 1, "order": priority["order"]})
+
+ response = client.patch(
+ f"/api/models/sources/{source_id}",
+ json={"display_name": "Primary Anthropic"},
+ headers=headers,
+ base_url=base_url,
+ )
+ _assert_valid("source.schema.json", response.get_json()["source"])
+
+ response = client.post(
+ f"/api/models/sources/{source_id}/test",
+ headers=headers,
+ base_url=base_url,
+ )
+ body = response.get_json()
+ _assert_envelope(body)
+ assert body["discovered"] == 2
+
+ response = client.post(
+ "/api/models/custom-models",
+ json={"source_id": source_id, "model_id": "custom-model", "display_name": "Custom Model"},
+ headers=headers,
+ base_url=base_url,
+ )
+ assert response.status_code == 201
+ _assert_valid("source.schema.json", response.get_json()["source"])
+
+ response = client.put(
+ "/api/models/agents/claude/mappings",
+ json={
+ "mappings": [
+ {"builtin_id": "claude-native", "target_model_id": "custom-model", "enabled": True}
+ ]
+ },
+ headers=headers,
+ base_url=base_url,
+ )
+ _assert_valid("agent-supply.schema.json", response.get_json()["agent"])
+
+ response = client.put(
+ "/api/models/agents/opencode/menu",
+ json={"menu": {"view": "featured", "checked": ["anthropic/custom-model"]}},
+ headers=headers,
+ base_url=base_url,
+ )
+ _assert_valid("agent-supply.schema.json", response.get_json()["agent"])
+
+ response = client.patch(
+ "/api/models/agents/codex/mode",
+ json={"mode": "direct"},
+ headers=headers,
+ base_url=base_url,
+ )
+ assert response.get_json()["agent"]["current"] is None
+
+ agents = client.get("/api/models/agents", base_url=base_url).get_json()["agents"]
+ assert len(agents) == 3
+ for agent in agents:
+ _assert_valid("agent-supply.schema.json", agent)
+
+ event_example = _schema("resolution-event.schema.json")["examples"][0]
+ service.events.append(ResolutionEvent(**event_example))
+ events = client.get("/api/models/events?limit=1", base_url=base_url).get_json()["events"]
+ assert events == [event_example]
+ _assert_valid("resolution-event.schema.json", events[0])
+
+ response = client.post(
+ "/api/models/oauth/start",
+ json={"vendor": "anthropic", "channel": "native_cli"},
+ headers=headers,
+ base_url=base_url,
+ )
+ flow = response.get_json()["flow"]
+ _assert_valid("oauth-flow.schema.json", flow)
+
+ flow = client.get(f"/api/models/oauth/status/{flow['flow_id']}", base_url=base_url).get_json()["flow"]
+ _assert_valid("oauth-flow.schema.json", flow)
+
+ restarted = ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "events.json"),
+ native_oauth_adapter=adapter,
+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
+ 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"
+
+ flow = client.post(
+ "/api/models/oauth/submit",
+ json={"flow_id": flow["flow_id"], "value": "secret-auth-code"},
+ headers=headers,
+ base_url=base_url,
+ ).get_json()["flow"]
+ _assert_valid("oauth-flow.schema.json", flow)
+ 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"]},
+ headers=headers,
+ base_url=base_url,
+ )
+ _assert_envelope(response.get_json())
+ assert adapter.cancelled == [flow["flow_id"]]
+ response = client.get(f"/api/models/oauth/status/{flow['flow_id']}", base_url=base_url)
+ assert response.status_code == 404
+ assert response.get_json()["error"] == "flow_not_found"
+
+ expired = client.post(
+ "/api/models/oauth/start",
+ json={"vendor": "anthropic", "channel": "native_cli"},
+ headers=headers,
+ base_url=base_url,
+ ).get_json()["flow"]
+ adapter.flows[expired["flow_id"]] = OAuthFlowState(
+ **{**adapter.flows[expired["flow_id"]].__dict__, "expires_at_iso": "2026-07-23T02:59:00+00:00"}
+ )
+ response = client.get(f"/api/models/oauth/status/{expired['flow_id']}", base_url=base_url)
+ assert response.status_code == 410
+ assert response.get_json()["error"] == "flow_expired"
+
+ response = client.post(
+ "/api/models/oauth/start",
+ json={"vendor": "anthropic", "channel": "hub", "experimental_consent": True},
+ headers=headers,
+ base_url=base_url,
+ )
+ hub_flow = response.get_json()["flow"]
+ _assert_valid("oauth-flow.schema.json", hub_flow)
+ assert store.config.subscription_hub_experimental is True
+ adapter.flows[hub_flow["flow_id"]] = OAuthFlowState(
+ **{
+ **adapter.flows[hub_flow["flow_id"]].__dict__,
+ "state": "success",
+ "credential_ref": "cred_oauth_test",
+ }
+ )
+ response = client.post(
+ "/api/models/sources",
+ json={
+ "kind": "subscription",
+ "vendor": "anthropic",
+ "display_name": "Experimental subscription",
+ "supply_channel": "hub",
+ "oauth_flow_ref": hub_flow["flow_id"],
+ "experimental_consent": True,
+ },
+ headers=headers,
+ base_url=base_url,
+ )
+ assert response.status_code == 201
+ consented_source = response.get_json()["source"]
+ _assert_valid("source.schema.json", consented_source)
+ assert consented_source["experimental_consent_at"] == "2026-07-23T03:00:00+00:00"
+ assert service.oauth_flows.channel(hub_flow["flow_id"]) is None
+
+ scan = client.post("/api/models/migration/scan", headers=headers, base_url=base_url).get_json()
+ _assert_valid("migration-scan.schema.json", {"items": scan["items"]})
+ applied = client.post(
+ "/api/models/migration/apply",
+ json={"item_ids": []},
+ headers=headers,
+ base_url=base_url,
+ ).get_json()
+ _assert_envelope(applied)
+ assert applied["applied"] == 0
+
+ runtime = client.get("/api/models/runtime/status", base_url=base_url).get_json()["runtime"]
+ _assert_valid("runtime-dependency.schema.json", runtime)
+ assert all("<" not in asset["url"] for asset in runtime["manifest"]["assets"])
+
+ response = client.delete(
+ "/api/models/custom-models",
+ json={"source_id": source_id, "model_id": "custom-model"},
+ headers=headers,
+ base_url=base_url,
+ )
+ assert response.status_code == 409
+ assert response.get_json()["error"] == "mode_switch_blocked"
+
+ response = client.put(
+ "/api/models/agents/claude/mappings",
+ json={"mappings": []},
+ headers=headers,
+ base_url=base_url,
+ )
+ _assert_envelope(response.get_json())
+ response = client.put(
+ "/api/models/agents/opencode/menu",
+ json={"menu": {"view": "featured", "checked": []}},
+ headers=headers,
+ base_url=base_url,
+ )
+ _assert_envelope(response.get_json())
+ response = client.delete(
+ "/api/models/custom-models",
+ json={"source_id": source_id, "model_id": "custom-model"},
+ headers=headers,
+ base_url=base_url,
+ )
+ _assert_valid("source.schema.json", response.get_json()["source"])
+
+ response = client.delete(
+ f"/api/models/sources/{source_id}?force=true",
+ headers=headers,
+ base_url=base_url,
+ )
+ _assert_envelope(response.get_json())
+ assert adapter.revoked == ["cred_test123"]
+
+
+ ("path", "method", "error"),
+ [
+ ("/api/models/sources/src_test0001", "patch", "discovery_failed"),
+ ("/api/models/priority", "put", "invalid_priority_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"),
+ ],
+)
+def test_model_hub_routes_reject_non_object_json_with_error_envelope(
+ monkeypatch,
+ tmp_path,
+ path,
+ method,
+ error,
+):
+ service, _, _ = _service(tmp_path)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+
+ for payload in ([], None):
+ response = getattr(client, method)(
+ path,
+ json=payload,
+ headers=csrf_headers(client, base_url),
+ base_url=base_url,
+ )
+
+ assert response.status_code == 400
+ body = response.get_json()
+ _assert_envelope(body, ok=False)
+ assert body["error"] == error
+
+
+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}
+ )
+ )
+ adapter.flows[flow["flow_id"]] = OAuthFlowState(
+ **{
+ **adapter.flows[flow["flow_id"]].__dict__,
+ "state": "success",
+ "credential_ref": "cred_oauth_rollback",
+ }
+ )
+ adapter.fail_sync = True
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.create_source(
+ {
+ "kind": "subscription",
+ "vendor": "anthropic",
+ "display_name": "Rollback subscription",
+ "supply_channel": "hub",
+ "oauth_flow_ref": flow["flow_id"],
+ "experimental_consent": True,
+ }
+ )
+ )
+
+ assert exc_info.value.code == "engine_down"
+ assert exc_info.value.__cause__ is None
+ assert adapter.revoked == ["cred_oauth_rollback"]
+ assert store.config.sources == []
+ assert service.oauth_flows.channel(flow["flow_id"]) is None
+
+
+def test_concurrent_completed_hub_oauth_flow_has_single_credential_owner(tmp_path):
+ async def run_race():
+ class BlockingSyncAdapter(FakeAdapter):
+ def __init__(self):
+ super().__init__()
+ self.sync_started = asyncio.Event()
+ self.release_sync = asyncio.Event()
+ self.block_next_sync = False
+
+ async def sync_sources(self, bindings):
+ self.synced.append(tuple(bindings))
+ if self.block_next_sync:
+ self.block_next_sync = False
+ self.sync_started.set()
+ await self.release_sync.wait()
+
+ store = MemoryStore()
+ adapter = BlockingSyncAdapter()
+ service = ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "events.json"),
+ 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}
+ )
+ adapter.flows[flow["flow_id"]] = OAuthFlowState(
+ **{
+ **adapter.flows[flow["flow_id"]].__dict__,
+ "state": "success",
+ "credential_ref": "cred_oauth_single_owner",
+ }
+ )
+ payload = {
+ "kind": "subscription",
+ "vendor": "anthropic",
+ "display_name": "Single owner",
+ "supply_channel": "hub",
+ "oauth_flow_ref": flow["flow_id"],
+ "experimental_consent": True,
+ }
+
+ adapter.block_next_sync = True
+ first = asyncio.create_task(service.create_source(payload))
+ await adapter.sync_started.wait()
+ second = asyncio.create_task(service.create_source(payload))
+ await asyncio.sleep(0)
+ adapter.release_sync.set()
+ return await asyncio.gather(first, second, return_exceptions=True), store, adapter
+
+ results, store, adapter = asyncio.run(run_race())
+
+ assert sum(isinstance(result, dict) for result in results) == 1
+ failures = [result for result in results if isinstance(result, ModelHubError)]
+ assert len(failures) == 1
+ assert failures[0].code == "flow_not_found"
+ assert len(store.config.sources) == 1
+ assert store.config.sources[0].credential_ref == "cred_oauth_single_owner"
+ assert adapter.revoked == []
+
+
+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"})
+ adapter.fail_cancel = True
+ with pytest.raises(ModelHubError) as exc_info:
+ await service.oauth_cancel(flow["flow_id"])
+ assert exc_info.value.code == "engine_down"
+ assert service.oauth_flows.channel(flow["flow_id"]) == "native_cli"
+
+ adapter.fail_cancel = False
+ await service.oauth_cancel(flow["flow_id"])
+ return service, adapter, flow["flow_id"]
+
+ service, adapter, flow_id = asyncio.run(run_cancel_retry())
+
+ assert service.oauth_flows.channel(flow_id) is None
+ assert adapter.cancelled == [flow_id, flow_id]
+
+
+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"}))
+ binding = service.oauth_flows.binding(flow["flow_id"])
+
+ assert binding is not None
+ assert binding.source_id == flow["source_id"]
+ assert binding.vendor == "anthropic"
+
+ adapter.flows[flow["flow_id"]] = OAuthFlowState(
+ **{
+ **adapter.flows[flow["flow_id"]].__dict__,
+ "source_id": "src_wrong0001",
+ "state": "success",
+ }
+ )
+ restarted = ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "restarted-events.json"),
+ native_oauth_adapter=adapter,
+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
+ )
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ restarted.create_source(
+ {
+ "kind": "subscription",
+ "vendor": "anthropic",
+ "display_name": "Wrong pending source",
+ "supply_channel": "native_cli",
+ "oauth_flow_ref": flow["flow_id"],
+ }
+ )
+ )
+
+ assert exc_info.value.code == "flow_not_found"
+ assert store.config.sources == []
+
+
+def test_native_oauth_cannot_record_experimental_hub_consent(tmp_path):
+ service, store, adapter = _service(tmp_path)
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.oauth_start(
+ {
+ "vendor": "anthropic",
+ "channel": "native_cli",
+ "experimental_consent": True,
+ }
+ )
+ )
+
+ assert exc_info.value.code == "consent_required"
+ assert store.config.subscription_hub_experimental is False
+ assert adapter.flows == {}
+
+
+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"}))
+ adapter.flows[flow["flow_id"]] = OAuthFlowState(
+ **{
+ **adapter.flows[flow["flow_id"]].__dict__,
+ "expires_at_iso": "2026-07-23T02:59:00+00:00",
+ }
+ )
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.oauth_submit({"flow_id": flow["flow_id"], "value": "stale-code"}))
+
+ assert exc_info.value.code == "flow_expired"
+ assert adapter.secret_lengths == []
+ assert service.oauth_flows.channel(flow["flow_id"]) is None
+
+
+def test_model_hub_mutations_use_existing_origin_and_csrf_guards(monkeypatch, tmp_path):
+ service, _, _ = _service(tmp_path)
+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
+ client = app.test_client()
+ base_url = "http://127.0.0.1:15131"
+
+ model_response = client.post("/api/models/migration/scan", base_url=base_url)
+ config_response = client.post("/api/config", json={}, base_url=base_url)
+
+ assert model_response.status_code == config_response.status_code == 403
+ assert model_response.get_json() == config_response.get_json()
+
+
+def test_native_source_configuration_does_not_require_l1_engine(tmp_path):
+ store = MemoryStore()
+ native = FakeAdapter()
+ native.fail_sync = True
+ service = ModelHubService(
+ store=store,
+ adapter=native,
+ events=BoundedEventLog(tmp_path / "events.json"),
+ native_oauth_adapter=native,
+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
+ 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"}
+ )
+ source = asyncio.run(
+ service.create_source(
+ {
+ "kind": "subscription",
+ "vendor": "anthropic",
+ "display_name": "Claude native",
+ "supply_channel": "native_cli",
+ "oauth_flow_ref": flow["flow_id"],
+ }
+ )
+ )
+
+ _assert_valid("source.schema.json", source)
+ 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 resolved.source_id == source["id"]
+ assert resolved.supply_channel == "native_cli"
+ assert native.synced == []
+
+ store.config.sources[0].state = ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at="2026-07-23T03:05:00Z",
+ )
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.test_source(source["id"]))
+
+ assert exc_info.value.code == "discovery_failed"
+ assert store.config.sources[0].state.status == "cooldown"
+ assert store.config.sources[0].state.retry_at == "2026-07-23T03:05:00Z"
+ assert native.synced == []
+
+
+def test_concurrent_source_creates_preserve_both_aggregate_updates(tmp_path):
+ async def run_creates():
+ class ConcurrentAdapter(FakeAdapter):
+ def __init__(self):
+ super().__init__()
+ self.discover_started = 0
+ self.all_discovering = asyncio.Event()
+
+ async def provision_credential(self, vendor, protocol, secret, base_url):
+ credential_ref = f"cred_concurrent_{len(self.secret_lengths)}"
+ self.secret_lengths.append(len(secret))
+ return credential_ref
+
+ async def discover_models(self, vendor, protocol, base_url, credential_ref):
+ self.discover_started += 1
+ if self.discover_started == 2:
+ self.all_discovering.set()
+ await self.all_discovering.wait()
+ return ("claude-opus-4-6",)
+
+ store = MemoryStore()
+ adapter = ConcurrentAdapter()
+ service = ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "events.json"),
+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
+ )
+ created = await asyncio.gather(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Concurrent A",
+ "key": "sk-test-concurrent-a",
+ }
+ ),
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Concurrent B",
+ "key": "sk-test-concurrent-b",
+ }
+ ),
+ )
+ return created, store.config
+
+ created, config = asyncio.run(run_creates())
+
+ 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}
+
+
+ "base_url",
+ [
+ "https://user:[email protected]/v1",
+ "https://relay.example/v1?api_key=sk-test-never-persist-this",
+ "https://relay.example/v1?X-Amz-Signature=abcdef123456",
+ "https://relay.example/v1?oauth_signature=abcdef123456",
+ "https://relay.example/v1?x-authorization=opaque-value",
+ "https://relay.example/v1?target=sk-test-never-persist-this",
+ ],
+)
+def test_source_base_url_rejects_embedded_credentials(tmp_path, base_url):
+ service, store, adapter = _service(tmp_path)
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "custom",
+ "display_name": "Unsafe relay",
+ "base_url": base_url,
+ "key": "sk-test-transient-only",
+ }
+ )
+ )
+
+ assert exc_info.value.code == "discovery_failed"
+ assert store.config.sources == []
+ assert adapter.secret_lengths == []
+
+
+def test_source_patch_rejects_credential_bearing_base_url(tmp_path):
+ service, store, _ = _service(tmp_path)
+ source = asyncio.run(
+ service.create_source(
+ {
+ "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",
+ }
+ )
+ )
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.patch_source(
+ source["id"],
+ {"base_url": "https://relay.example/v1?access_token=do-not-store"},
+ )
+ )
+
+ assert exc_info.value.code == "discovery_failed"
+ assert store.config.sources[0].base_url == "https://relay.example/v1?api-version=2026-07-23"
+
+
+def test_source_display_names_reject_credential_material(tmp_path):
+ service, store, adapter = _service(tmp_path)
+ pasted_key = "sk-test-never-persist-this"
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": pasted_key,
+ "key": "sk-test-transient-only",
+ }
+ )
+ )
+ assert exc_info.value.code == "discovery_failed"
+ assert store.config.sources == []
+ assert adapter.secret_lengths == []
+
+ source = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Safe source",
+ "key": "sk-test-transient-only",
+ }
+ )
+ )
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.patch_source(source["id"], {"display_name": pasted_key}))
+ assert exc_info.value.code == "discovery_failed"
+ assert store.config.sources[0].display_name == "Safe source"
+ assert pasted_key not in json.dumps(store.config.to_payload())
+
+
+def test_api_key_is_trimmed_once_and_empty_normalized_values_are_rejected(tmp_path):
+ service, store, adapter = _service(tmp_path)
+ normalized = "sk-test-trim-me"
+
+ source = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Trimmed source",
+ "key": f" \n{normalized}\t ",
+ }
+ )
+ )
+
+ assert adapter.secret_lengths == [len(normalized)]
+ assert source["masked_credential"] == "sk-test…m-me"
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Empty source",
+ "key": " \n\t ",
+ }
+ )
+ )
+
+ assert exc_info.value.code == "discovery_failed"
+ assert adapter.secret_lengths == [len(normalized)]
+ assert [source.display_name for source in store.config.sources] == ["Trimmed source"]
+
+
+def test_source_vendor_and_custom_model_ids_reject_credential_material(tmp_path):
+ service, store, adapter = _service(tmp_path)
+ pasted_key = "sk-model-never-persist-this"
+
+ for payload in (
+ {
+ "kind": "api_key",
+ "vendor": pasted_key,
+ "display_name": "Safe source",
+ "key": "sk-test-transient-only",
+ },
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Safe source",
+ "key": "sk-test-transient-only",
+ "models": [{"id": pasted_key, "provenance": "manual"}],
+ },
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Safe source",
+ "key": "sk-test-transient-only",
+ "models": [
+ {
+ "id": "safe-model-id",
+ "display_name": pasted_key,
+ "provenance": "manual",
+ }
+ ],
+ },
+ ):
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.create_source(payload))
+ assert exc_info.value.code == "discovery_failed"
+
+ assert store.config.sources == []
+ assert adapter.secret_lengths == []
+
+ source = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Safe source",
+ "key": "sk-test-transient-only",
+ }
+ )
+ )
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.add_custom_model({"source_id": source["id"], "model_id": pasted_key}))
+
+ assert exc_info.value.code == "mapping_target_unavailable"
+ assert pasted_key not in json.dumps(store.config.to_payload())
+
+
+def test_source_patch_rejects_credential_bearing_discovered_model_id(tmp_path):
+ service, store, adapter = _service(tmp_path)
+ source = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "custom",
+ "display_name": "Safe relay",
+ "base_url": "https://relay.example/v1",
+ "key": "sk-test-transient-only",
+ }
+ )
+ )
+
+ async def credential_bearing_models(vendor, protocol, base_url, credential_ref):
+ return ("sk-model-never-persist-this",)
+
+ adapter.discover_models = credential_bearing_models
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.patch_source(
+ source["id"],
+ {"base_url": "https://other-relay.example/v1"},
+ )
+ )
+
+ assert exc_info.value.code == "discovery_failed"
+ assert store.config.sources[0].base_url == "https://relay.example/v1"
+ assert "sk-model-never-persist-this" not in json.dumps(store.config.to_payload())
+
+
+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(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Before rename",
+ "key": "sk-test-transient-only",
+ }
+ )
+ )
+ sync_count = len(adapter.synced)
+ adapter.fail_sync = True
+
+ updated = asyncio.run(service.patch_source(source["id"], {"display_name": "After rename"}))
+
+ assert updated["display_name"] == "After rename"
+ assert store.config.sources[0].display_name == "After rename"
+ assert len(adapter.synced) == sync_count
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
new file mode 100644
index 000000000..6dabd7083
--- /dev/null
+++ b/tests/test_model_hub_config.py
@@ -0,0 +1,189 @@
+from __future__ import annotations
+
+import json
+from dataclasses import fields
+from pathlib import Path
+
+from jsonschema import Draft7Validator, FormatChecker
+
+from config.v2_config import (
+ ModelHubAgentSupplyConfig,
+ ModelHubConfig,
+ ModelHubMappingConfig,
+ ModelHubMenuConfig,
+ ModelHubModelConfig,
+ ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
+ ModelHubSourceUsageConfig,
+ V2Config,
+)
+from core.services.settings import default_config
+from vibe import api
+
+CONTRACTS = Path("docs/plans/model-hub-contracts")
+
+
+def _schema(name: str) -> dict:
+ return json.loads((CONTRACTS / name).read_text(encoding="utf-8"))
+
+
+def _assert_valid(name: str, payload: dict) -> None:
+ errors = sorted(
+ Draft7Validator(_schema(name), format_checker=FormatChecker()).iter_errors(payload),
+ key=lambda error: list(error.path),
+ )
+ assert not errors, [error.message for error in errors]
+
+
+def _canonical(payload: dict) -> bytes:
+ return json.dumps(payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
+
+
+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()
+
+ for example in _schema("source.schema.json")["examples"]:
+ serialized = ModelHubSourceConfig.from_payload(example).to_payload()
+ assert _canonical(serialized) == _canonical(example)
+ _assert_valid("source.schema.json", serialized)
+
+ for example in _schema("agent-supply.schema.json")["examples"]:
+ agent = ModelHubAgentSupplyConfig.from_payload(example)
+ serialized = {**agent.to_payload(), "current": example.get("current")}
+ assert _canonical(serialized) == _canonical(example)
+ _assert_valid("agent-supply.schema.json", serialized)
+
+
+def test_every_frozen_schema_example_is_valid_and_json_round_trips():
+ for path in sorted(CONTRACTS.glob("*.schema.json")):
+ schema = json.loads(path.read_text(encoding="utf-8"))
+ validator = Draft7Validator(schema, format_checker=FormatChecker())
+ for example in schema.get("examples", []):
+ validator.validate(example)
+ assert _canonical(json.loads(_canonical(example))) == _canonical(example)
+
+
+def test_model_hub_config_round_trip_and_serializer_completeness(monkeypatch, tmp_path):
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ source_example = {
+ **_schema("source.schema.json")["examples"][0],
+ "supply_channel": "hub",
+ "experimental_consent_at": "2026-07-23T03:00:00Z",
+ "credential_ref": "cred_serializer_test",
+ }
+ 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")
+ },
+ "subscription_hub_experimental": True,
+ }
+ config = default_config()
+ config.model_hub = ModelHubConfig.from_payload(hub_payload)
+ config.save()
+
+ loaded = V2Config.load()
+ disk_payload = json.loads(Path(tmp_path, "config", "config.json").read_text(encoding="utf-8"))
+ api_payload = api.config_to_payload(loaded)
+ expected_root = {field.name for field in fields(ModelHubConfig)}
+ source_fields = {field.name for field in fields(ModelHubSourceConfig)}
+ source_state_fields = {field.name for field in fields(ModelHubSourceStateConfig)}
+ 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)}
+ mapping_fields = {field.name for field in fields(ModelHubMappingConfig)}
+ menu_fields = {field.name for field in fields(ModelHubMenuConfig)}
+
+ assert expected_root == set(api_payload["model_hub"])
+ assert expected_root == set(disk_payload["model_hub"])
+ for label, serialized_hub in (
+ ("config_to_payload", api_payload["model_hub"]),
+ ("V2Config.save", disk_payload["model_hub"]),
+ ):
+ serialized_source = serialized_hub["sources"][0]
+ assert source_fields == set(serialized_source), label
+ assert source_state_fields == set(serialized_source["state"]), label
+ 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 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"] = []
+ 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"]
+
+
+def test_legacy_config_defaults_direct_while_fresh_config_defaults_hub():
+ payload = api.config_to_payload(default_config(), include_secrets=True)
+ payload.pop("model_hub")
+ legacy = V2Config.from_payload(payload)
+
+ assert {agent.mode for agent in legacy.model_hub.agents.values()} == {"direct"}
+ assert {agent.mode for agent in default_config().model_hub.agents.values()} == {"hub"}
+
+
+def test_hub_subscription_requires_server_recorded_consent():
+ source = _schema("source.schema.json")["examples"][0]
+ source = {**source, "supply_channel": "hub"}
+ payload = {
+ "sources": [source],
+ "priority_order": [source["id"]],
+ "agents": {},
+ "subscription_hub_experimental": True,
+ }
+
+ try:
+ ModelHubConfig.from_payload(payload)
+ except ValueError as exc:
+ assert "recorded experimental consent" in str(exc)
+ else:
+ raise AssertionError("hub-held subscription loaded without recorded consent")
+
+
+def test_source_optional_fields_reject_schema_invalid_values():
+ source = _schema("source.schema.json")["examples"][0]
+ invalid_sources = []
+
+ invalid = json.loads(json.dumps(source))
+ invalid["models"][0]["display_name"] = 1
+ invalid_sources.append(invalid)
+
+ invalid = json.loads(json.dumps(source))
+ invalid["models"][0]["discovered_at"] = "2026-07-23T03:00:00"
+ invalid_sources.append(invalid)
+
+ invalid = json.loads(json.dumps(source))
+ invalid["state"]["detail_key"] = 1
+ invalid_sources.append(invalid)
+
+ invalid = json.loads(json.dumps(source))
+ invalid["usage"]["currency"] = 1
+ invalid_sources.append(invalid)
+
+ invalid = json.loads(json.dumps(source))
+ invalid["experimental_consent_at"] = 1
+ invalid_sources.append(invalid)
+
+ invalid = json.loads(json.dumps(source))
+ invalid["account_label"] = 1
+ invalid_sources.append(invalid)
+
+ invalid = json.loads(json.dumps(source))
+ invalid["masked_credential"] = 1
+ invalid_sources.append(invalid)
+
+ for invalid in invalid_sources:
+ try:
+ ModelHubSourceConfig.from_payload(invalid)
+ except ValueError:
+ continue
+ raise AssertionError(f"schema-invalid optional field was accepted: {invalid}")
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
new file mode 100644
index 000000000..c17be815f
--- /dev/null
+++ b/tests/test_model_hub_resolution.py
@@ -0,0 +1,880 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from collections import deque
+from datetime import datetime, timedelta, timezone
+
+import pytest
+
+from config.v2_config import (
+ ModelHubAgentSupplyConfig,
+ ModelHubConfig,
+ ModelHubMappingConfig,
+ ModelHubModelConfig,
+ ModelHubSourceConfig,
+ ModelHubSourceStateConfig,
+)
+from core.handlers.model_hub.adapter import (
+ EngineHealth,
+ EngineStatus,
+ RawCallOutcome,
+ RawOutcomeKind,
+)
+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.revocations import CredentialRevocationJournal
+from core.handlers.model_hub.service import ModelHubError, ModelHubService, _mask_credential
+from vibe.i18n import t as i18n_t
+
+
+class MemoryStore:
+ def __init__(self, config: ModelHubConfig):
+ self.config = config
+ self.fail_save = False
+
+ def load(self) -> ModelHubConfig:
+ return self.config
+
+ def save(self, config: ModelHubConfig) -> None:
+ if self.fail_save:
+ raise OSError("save failed")
+ self.config = config
+
+
+class FakeAdapter:
+ def __init__(self, outcomes):
+ self.outcomes = deque(outcomes)
+ self.invocations = []
+ self.synced = []
+ self.revoked = []
+ self.provisioned = []
+ self.fail_sync = False
+ self.fail_revoke = False
+
+ async def ensure_installed(self):
+ return await self.status()
+
+ async def start(self):
+ return await self.status()
+
+ async def stop(self):
+ return None
+
+ async def status(self):
+ return EngineStatus(EngineHealth.OK, "v7.2.95", True, "127.0.0.1", 15220, None)
+
+ async def gateway_token(self):
+ return "local-test-token"
+
+ async def provision_credential(self, vendor, protocol, secret, base_url):
+ self.provisioned.append((vendor, protocol, base_url))
+ return "cred_test"
+
+ async def revoke_credential(self, credential_ref):
+ self.revoked.append(credential_ref)
+ if self.fail_revoke:
+ raise RuntimeError("revoke failed")
+ return None
+
+ async def sync_sources(self, bindings):
+ self.synced.append(tuple(bindings))
+ if self.fail_sync:
+ raise RuntimeError("sync failed")
+
+ async def discover_models(self, vendor, protocol, base_url, credential_ref):
+ return ("claude-opus-4-6",)
+
+ async def invoke(self, source_id, model_id, request, stream, origin):
+ self.invocations.append((source_id, model_id, origin))
+ result = self.outcomes.popleft()
+ return result if isinstance(result, FakeInvokeHandle) else FakeInvokeHandle(result)
+
+ async def start_oauth(self, source_id, vendor):
+ raise AssertionError
+
+ async def oauth_status(self, flow_id):
+ raise AssertionError
+
+ async def submit_oauth(self, flow_id, value):
+ raise AssertionError
+
+ async def cancel_oauth(self, flow_id):
+ raise AssertionError
+
+
+class FakeInvokeHandle:
+ def __init__(self, outcome, stream=None):
+ self._outcome = outcome
+ self._stream = stream
+
+ @property
+ def stream(self):
+ return self._stream
+
+ async def outcome(self):
+ return self._outcome
+
+
+ ("secret", "expected"),
+ [
+ ("sk-test-never-persist-this", "sk-test…this"),
+ ("abcde", "…bcde"),
+ ("abcd", "…••••"),
+ ],
+)
+def test_credential_display_mask_never_exposes_the_whole_secret(secret, expected):
+ assert _mask_credential(secret) == expected
+ assert secret != expected
+
+
+def _outcome(kind, *, status=None, code=None, message=None, stream_started=False):
+ return RawCallOutcome(
+ kind=kind,
+ http_status=status,
+ error_code=code,
+ redacted_message=message,
+ stream_started=stream_started,
+ model_id="claude-opus-4-6",
+ source_id="src_primary01",
+ )
+
+
+def _source(source_id: str, display_name: str, *, billing: str = "metered") -> ModelHubSourceConfig:
+ return ModelHubSourceConfig(
+ id=source_id,
+ kind="api_key",
+ vendor="anthropic",
+ display_name=display_name,
+ protocol="anthropic",
+ supply_channel="hub",
+ billing=billing,
+ state=ModelHubSourceStateConfig(status="standby"),
+ models=[ModelHubModelConfig(id="claude-opus-4-6", provenance="discovered")],
+ credential_ref=f"cred_{source_id}",
+ )
+
+
+def _service(tmp_path, adapter, *, agents=None, now=None):
+ sources = [
+ _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")
+ },
+ )
+ return ModelHubService(
+ store=MemoryStore(config),
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "events.json", max_entries=5),
+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
+ now=now or (lambda: datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc)),
+ )
+
+
+ ("outcome", "refresh_attempted", "action", "reason"),
+ [
+ (_outcome(RawOutcomeKind.SUCCESS, status=200), False, "return", None),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="invalid_parameter"), False, "surface", None),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=422, code="tool_schema_error"), False, "surface", None),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=401), False, "refresh", None),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=401), True, "surface", None),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=401, code="invalid_request"), False, "refresh", None),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=401, code="invalid_request"), True, "surface", None),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=429), False, "fallback", "rate_limited"),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=403, code="quota_exhausted"), False, "fallback", "quota_exhausted"),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=503), False, "fallback", "server_error"),
+ (_outcome(RawOutcomeKind.NETWORK_ERROR), False, "fallback", "network"),
+ (_outcome(RawOutcomeKind.HTTP_ERROR, status=429, stream_started=True), False, "surface", None),
+ ],
+)
+def test_error_classification_table(outcome, refresh_attempted, action, reason):
+ decision = classify_outcome(outcome, refresh_attempted=refresh_attempted)
+ assert decision.action == action
+ assert decision.reason == reason
+
+
+def test_quota_failure_cools_source_switches_and_emits_redacted_events(tmp_path):
+ """Scenario: MH-RES-001."""
+
+ fake_key = "sk-live-super-secret-material"
+ clock = [datetime(2026, 7, 23, 3, 0, tzinfo=timezone.utc)]
+ adapter = FakeAdapter(
+ [
+ _outcome(
+ RawOutcomeKind.HTTP_ERROR,
+ status=429,
+ code="quota_exhausted",
+ message=f'upstream redaction failure included {fake_key}',
+ ),
+ _outcome(RawOutcomeKind.SUCCESS, status=200),
+ _outcome(RawOutcomeKind.SUCCESS, status=200),
+ ]
+ )
+ service = _service(tmp_path, adapter, now=lambda: clock[0])
+
+ resolved = asyncio.run(
+ service.resolve(
+ backend="claude",
+ model_id="claude-opus-4-6",
+ request={"messages": []},
+ )
+ )
+
+ assert resolved.source_id == "src_backup001"
+ assert [call[0] for call in adapter.invocations] == ["src_primary01", "src_backup001"]
+ assert service.store.load().sources[0].state.status == "cooldown"
+ persisted = (tmp_path / "events.json").read_text(encoding="utf-8")
+ assert fake_key not in persisted
+ events = service.list_events(limit=10)
+ assert [event["kind"] for event in events] == ["switch", "cooldown"]
+
+ clock[0] += timedelta(minutes=6)
+ recovered = asyncio.run(
+ service.resolve(
+ backend="claude",
+ model_id="claude-opus-4-6",
+ request={"messages": []},
+ )
+ )
+ assert recovered.source_id == "src_primary01"
+ assert service.store.load().sources[0].state.status == "standby"
+ assert service.list_events(limit=10)[0]["kind"] == "recover"
+
+
+def test_event_log_failure_does_not_abort_failover(tmp_path):
+ class UnwritableEventLog:
+ def append(self, event):
+ raise OSError("read-only state")
+
+ def list(self, *, limit=20, before=None):
+ return []
+
+ adapter = FakeAdapter(
+ [
+ _outcome(RawOutcomeKind.HTTP_ERROR, status=429),
+ _outcome(RawOutcomeKind.SUCCESS, status=200),
+ ]
+ )
+ service = _service(tmp_path, adapter)
+ service.events = UnwritableEventLog()
+
+ 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"
+ assert [call[0] for call in adapter.invocations] == ["src_primary01", "src_backup001"]
+
+
+def test_401_refreshes_exactly_once_before_returning(tmp_path):
+ adapter = FakeAdapter(
+ [
+ _outcome(RawOutcomeKind.HTTP_ERROR, status=401),
+ _outcome(RawOutcomeKind.SUCCESS, status=200),
+ ]
+ )
+ service = _service(tmp_path, adapter)
+
+ result = asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
+
+ assert result.source_id == "src_primary01"
+ assert len(adapter.invocations) == 2
+
+
+def test_refreshed_fallback_stream_emits_switch_event(tmp_path):
+ async def stream_bytes():
+ yield b"ok"
+
+ adapter = FakeAdapter(
+ [
+ _outcome(RawOutcomeKind.HTTP_ERROR, status=429),
+ _outcome(RawOutcomeKind.HTTP_ERROR, status=401),
+ FakeInvokeHandle(
+ _outcome(RawOutcomeKind.SUCCESS, status=200, stream_started=True),
+ stream=stream_bytes(),
+ ),
+ ]
+ )
+ service = _service(tmp_path, adapter)
+
+ result = asyncio.run(
+ service.resolve(
+ backend="claude",
+ model_id="claude-opus-4-6",
+ request={},
+ stream=True,
+ )
+ )
+
+ assert result.source_id == "src_backup001"
+ assert [event["kind"] for event in service.list_events(limit=10)] == ["switch", "cooldown"]
+
+
+def test_parameter_error_and_started_stream_never_fallback(tmp_path):
+ for outcome in (
+ _outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="invalid_parameter"),
+ _outcome(RawOutcomeKind.HTTP_ERROR, status=429, stream_started=True),
+ ):
+ adapter = FakeAdapter([outcome])
+ service = _service(tmp_path, adapter)
+ with pytest.raises(ModelHubError):
+ asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}, stream=True))
+ assert len(adapter.invocations) == 1
+
+
+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")
+ }
+ agents["claude"].mappings = [
+ ModelHubMappingConfig(builtin_id="claude-native", target_model_id="claude-opus-4-6", enabled=True)
+ ]
+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
+ service = _service(tmp_path, adapter, agents=agents)
+
+ result = asyncio.run(service.resolve(backend="claude", model_id="claude-native", request={}))
+
+ assert result.model_id == "claude-opus-4-6"
+ assert agents["codex"].mappings == []
+
+
+def test_opencode_provider_prefix_selects_matching_source_and_current_payload(tmp_path):
+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
+ service = _service(tmp_path, adapter)
+ config = service.store.load()
+ config.sources[0].vendor = "custom"
+ config.sources[0].state = ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at="2026-07-23T02:59:00Z",
+ )
+ config.sources[1].vendor = "anthropic"
+ config.agents["opencode"].menu.checked = ["anthropic/claude-opus-4-6"]
+
+ current = next(agent for agent in service.list_agents() if agent["backend"] == "opencode")["current"]
+ resolved = asyncio.run(
+ service.resolve(
+ backend="opencode",
+ model_id="anthropic/claude-opus-4-6",
+ request={},
+ )
+ )
+
+ assert current["source_id"] == "src_backup001"
+ assert resolved.source_id == "src_backup001"
+ assert adapter.invocations == [("src_backup001", "claude-opus-4-6", "opencode")]
+ assert service.list_events(limit=10) == []
+ assert config.sources[0].state.status == "cooldown"
+
+
+def test_opencode_unknown_vendor_uses_custom_provider_identifier(tmp_path):
+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
+ service = _service(tmp_path, adapter)
+ config = service.store.load()
+ config.sources[0].vendor = "relaycorp"
+ config.agents["opencode"].menu.checked = ["custom/claude-opus-4-6"]
+
+ menu = asyncio.run(service.set_opencode_menu(config.agents["opencode"].menu.to_payload()))
+ current = next(agent for agent in service.list_agents() if agent["backend"] == "opencode")["current"]
+ resolved = asyncio.run(
+ service.resolve(
+ backend="opencode",
+ model_id="custom/claude-opus-4-6",
+ request={},
+ )
+ )
+
+ assert menu["menu"]["checked"] == ["custom/claude-opus-4-6"]
+ assert current["source_id"] == "src_primary01"
+ assert resolved.source_id == "src_primary01"
+
+
+def test_opencode_resolution_rejects_models_outside_checked_menu(tmp_path):
+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
+ service = _service(tmp_path, adapter)
+ service.store.load().agents["opencode"].menu.checked = []
+
+ current = next(agent for agent in service.list_agents() if agent["backend"] == "opencode")["current"]
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.resolve(
+ backend="opencode",
+ model_id="anthropic/claude-opus-4-6",
+ request={},
+ )
+ )
+
+ assert exc_info.value.code == "mapping_target_unavailable"
+ assert current is None
+ assert adapter.invocations == []
+
+
+def test_persisted_hub_sources_sync_before_first_resolution(tmp_path):
+ class RegistrationRequiredAdapter(FakeAdapter):
+ def __init__(self):
+ super().__init__([_outcome(RawOutcomeKind.SUCCESS, status=200)])
+ self.registered = set()
+
+ async def sync_sources(self, bindings):
+ await super().sync_sources(bindings)
+ self.registered = {binding.source_id for binding in bindings}
+
+ async def invoke(self, source_id, model_id, request, stream, origin):
+ assert source_id in self.registered
+ return await super().invoke(source_id, model_id, request, stream, origin)
+
+ adapter = RegistrationRequiredAdapter()
+ service = _service(tmp_path, adapter)
+
+ 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]] == [
+ "src_primary01",
+ "src_backup001",
+ ]
+
+
+def test_agent_current_skips_cooldown_and_error_sources(tmp_path):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ config.sources[0].state = ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at="2026-07-23T03:05:00Z",
+ )
+
+ 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")
+ claude = next(agent for agent in service.list_agents() if agent["backend"] == "claude")
+ assert claude["current"] 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)
+ native = service.store.load().sources[0]
+ native.kind = "subscription"
+ native.supply_channel = "native_cli"
+
+ 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"
+ assert resolved.handle is None
+ assert adapter.invocations == []
+
+ native.state = ModelHubSourceStateConfig(
+ status="cooldown",
+ retry_at="2026-07-23T03:05:00Z",
+ )
+ 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"
+ assert adapter.invocations == [("src_backup001", "claude-opus-4-6", "claude")]
+
+
+def test_native_dispatch_attempts_pending_credential_revoke(tmp_path):
+ adapter = FakeAdapter([])
+ service = _service(tmp_path, adapter)
+ native = service.store.load().sources[0]
+ native.kind = "subscription"
+ native.supply_channel = "native_cli"
+ 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={})
+ )
+
+ assert resolved.source_id == "src_primary01"
+ assert resolved.supply_channel == "native_cli"
+ assert adapter.revoked == ["cred_deleted"]
+ assert service.revocations.list() == []
+ assert adapter.invocations == []
+
+
+def test_direct_mode_never_enters_hub_resolution(tmp_path):
+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
+ service = _service(tmp_path, adapter)
+ service.store.load().agents["claude"].mode = "direct"
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.resolve(backend="claude", model_id="claude-opus-4-6", request={}))
+
+ assert exc_info.value.code == "mode_switch_blocked"
+ assert adapter.invocations == []
+
+
+def test_source_creation_persists_before_engine_sync(tmp_path):
+ order = []
+
+ class OrderingAdapter(FakeAdapter):
+ async def sync_sources(self, bindings):
+ order.append("sync")
+ assert len(service.store.load().sources) == 3
+ await super().sync_sources(bindings)
+
+ adapter = OrderingAdapter([])
+ service = _service(tmp_path, adapter)
+ save = service.store.save
+
+ def record_save(config):
+ save(config)
+ order.append("persist")
+
+ service.store.save = record_save
+ created = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Ordered source",
+ "key": "sk-test-transient-only",
+ }
+ )
+ )
+
+ assert order == ["persist", "sync"]
+ assert service.store.load().sources[-1].id == created["id"]
+
+
+def test_source_creation_revokes_credential_when_persist_fails(tmp_path):
+ adapter = FakeAdapter([])
+ service = _service(tmp_path, adapter)
+ original_ids = [source.id for source in service.store.load().sources]
+ service.store.fail_save = True
+
+ with pytest.raises(OSError, match="save failed"):
+ asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Unpersisted source",
+ "key": "sk-test-transient-only",
+ }
+ )
+ )
+
+ assert [source.id for source in service.store.load().sources] == original_ids
+ assert adapter.synced == []
+ assert adapter.revoked == ["cred_test"]
+ assert service.revocations.list() == []
+
+
+def test_source_creation_is_not_persisted_when_engine_sync_fails(tmp_path):
+ adapter = FakeAdapter([])
+ adapter.fail_sync = True
+ service = _service(tmp_path, adapter)
+ for source in service.store.load().sources:
+ source.credential_ref = f"cred_{source.id}"
+ original_ids = [source.id for source in service.store.load().sources]
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Uncommitted",
+ "key": "sk-test-transaction-only",
+ }
+ )
+ )
+
+ assert exc_info.value.code == "engine_down"
+ assert exc_info.value.__cause__ is None
+ assert exc_info.value.__suppress_context__ is True
+ assert [source.id for source in service.store.load().sources] == original_ids
+ assert adapter.revoked == ["cred_test"]
+
+
+def test_failed_create_rollback_is_journaled_until_revoke_recovers(tmp_path):
+ adapter = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
+ adapter.fail_sync = True
+ adapter.fail_revoke = True
+ service = _service(tmp_path, adapter)
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "anthropic",
+ "display_name": "Rollback source",
+ "key": "sk-test-transaction-only",
+ }
+ )
+ )
+
+ assert exc_info.value.code == "engine_down"
+ pending = service.revocations.list()
+ assert len(pending) == 1
+ assert pending[0].credential_ref == "cred_test"
+
+ adapter.fail_sync = False
+ adapter.fail_revoke = False
+ 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"]
+ assert service.revocations.list() == []
+
+
+def test_subscription_source_rejects_api_key_credentials(tmp_path):
+ adapter = FakeAdapter([])
+ service = _service(tmp_path, adapter)
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(
+ service.create_source(
+ {
+ "kind": "subscription",
+ "vendor": "anthropic",
+ "display_name": "Invalid subscription",
+ "key": "sk-test-must-not-be-provisioned",
+ }
+ )
+ )
+
+ assert exc_info.value.code == "discovery_failed"
+ assert adapter.provisioned == []
+
+
+def test_source_delete_does_not_revoke_when_config_save_fails(tmp_path):
+ adapter = FakeAdapter([])
+ service = _service(tmp_path, adapter)
+ service.store.load().sources[0].credential_ref = "cred_primary"
+ service.store.load().sources[1].credential_ref = "cred_backup"
+ service.store.fail_save = True
+
+ with pytest.raises(OSError, match="save failed"):
+ asyncio.run(service.delete_source("src_primary01", force=True))
+
+ assert adapter.revoked == []
+ assert [source.id for source in service.store.load().sources] == ["src_primary01", "src_backup001"]
+
+
+def test_deleting_last_hub_source_syncs_empty_binding_set(tmp_path):
+ adapter = FakeAdapter([])
+ service = _service(tmp_path, adapter)
+ config = service.store.load()
+ config.sources = [config.sources[0]]
+ config.priority_order = [config.sources[0].id]
+
+ asyncio.run(service.delete_source("src_primary01", force=True))
+
+ assert adapter.synced == [()]
+ assert adapter.revoked == ["cred_src_primary01"]
+ assert service.store.load().sources == []
+
+
+def test_source_reference_survives_failed_credential_revoke(tmp_path):
+ adapter = FakeAdapter([])
+ service = _service(tmp_path, adapter)
+ service.store.load().sources[0].credential_ref = "cred_primary"
+ service.store.load().sources[1].credential_ref = "cred_backup"
+ adapter.fail_revoke = True
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.delete_source("src_primary01", force=True))
+
+ assert exc_info.value.code == "engine_down"
+ assert [source.id for source in service.store.load().sources] == ["src_primary01", "src_backup001"]
+ assert [tuple(binding.source_id for binding in batch) for batch in adapter.synced] == [
+ ("src_backup001",),
+ ("src_primary01", "src_backup001"),
+ ]
+
+
+def test_restart_replays_credential_revoke_after_delete_commit(tmp_path):
+ class SimulatedProcessExit(BaseException):
+ pass
+
+ class CrashingAdapter(FakeAdapter):
+ async def revoke_credential(self, credential_ref):
+ raise SimulatedProcessExit
+
+ journal = CredentialRevocationJournal(tmp_path / "revocations.json")
+ crashing = CrashingAdapter([])
+ service = _service(tmp_path, crashing)
+ service.revocations = journal
+ native = service.store.load().sources[1]
+ native.kind = "subscription"
+ native.supply_channel = "native_cli"
+ native.credential_ref = None
+
+ with pytest.raises(SimulatedProcessExit):
+ asyncio.run(service.delete_source("src_primary01", force=True))
+
+ assert [source.id for source in service.store.load().sources] == ["src_backup001"]
+ assert journal.list()[0].credential_ref == "cred_src_primary01"
+
+ recovered = FakeAdapter([_outcome(RawOutcomeKind.SUCCESS, status=200)])
+ restarted = ModelHubService(
+ store=service.store,
+ adapter=recovered,
+ events=BoundedEventLog(tmp_path / "restarted-events.json"),
+ 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={})
+ )
+
+ assert resolved.source_id == "src_backup001"
+ assert resolved.supply_channel == "native_cli"
+ assert recovered.synced == [()]
+ assert recovered.revoked == ["cred_src_primary01"]
+ assert journal.list() == []
+
+
+def test_selected_custom_model_cannot_be_deleted(tmp_path):
+ adapter = FakeAdapter([])
+ service = _service(tmp_path, adapter)
+ config = service.store.load()
+ config.sources[0].models.append(ModelHubModelConfig(id="manual-model", provenance="manual"))
+ config.agents["opencode"].menu.checked = ["anthropic/manual-model"]
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.delete_custom_model("src_primary01", "manual-model"))
+
+ assert exc_info.value.code == "mode_switch_blocked"
+ assert any(model.id == "manual-model" for model in service.store.load().sources[0].models)
+
+
+def test_custom_model_preserves_slash_qualified_upstream_id(tmp_path):
+ service = _service(tmp_path, FakeAdapter([]))
+ source = service.store.load().sources[0]
+ source.vendor = "openrouter"
+ for configured_source in service.store.load().sources:
+ configured_source.credential_ref = f"cred_{configured_source.id}"
+
+ updated = asyncio.run(
+ service.add_custom_model(
+ {
+ "source_id": source.id,
+ "model_id": "anthropic/claude-sonnet-4",
+ "display_name": "Claude Sonnet 4",
+ }
+ )
+ )
+ menu = asyncio.run(
+ service.set_opencode_menu(
+ {"view": "featured", "checked": ["openrouter/anthropic/claude-sonnet-4"]}
+ )
+ )
+
+ assert updated["models"][-1]["id"] == "anthropic/claude-sonnet-4"
+ assert menu["menu"]["checked"] == ["openrouter/anthropic/claude-sonnet-4"]
+
+
+def test_resolution_event_copy_comes_from_backend_i18n(tmp_path):
+ event = build_resolution_event(
+ agent="system",
+ kind="cooldown",
+ model_id="test-model",
+ reason="network",
+ from_label="Primary",
+ )
+
+ assert event.human_en == i18n_t(
+ "modelHub.events.cooldown",
+ "en",
+ from_source="Primary",
+ to_source=i18n_t("modelHub.events.sourceFallback", "en"),
+ reason=i18n_t("modelHub.events.reason.network", "en"),
+ )
+ assert event.human_zh == i18n_t(
+ "modelHub.events.cooldown",
+ "zh",
+ from_source="Primary",
+ to_source=i18n_t("modelHub.events.sourceFallback", "zh"),
+ reason=i18n_t("modelHub.events.reason.network", "zh"),
+ )
+
+
+def test_mapping_and_delete_guards_use_backend_eligible_sources(tmp_path):
+ service = _service(tmp_path, FakeAdapter([]))
+ config = service.store.load()
+ config.sources[0].kind = "subscription"
+ config.sources[0].supply_channel = "native_cli"
+ config.sources[0].vendor = "anthropic"
+ config.sources[1].kind = "subscription"
+ config.sources[1].supply_channel = "native_cli"
+ config.sources[1].vendor = "openai"
+ config.sources[1].models = [ModelHubModelConfig(id="gpt-5", provenance="discovered")]
+
+ with pytest.raises(ModelHubError, match="mapping_target_unavailable"):
+ asyncio.run(
+ service.set_mappings(
+ "codex",
+ [
+ {
+ "builtin_id": "gpt-5",
+ "target_model_id": "claude-opus-4-6",
+ "enabled": 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"
+
+ config.agents["claude"].mode = "direct"
+ asyncio.run(service.delete_source("src_primary01"))
+ assert [source.id for source in service.store.load().sources] == ["src_backup001"]
+
+
+def test_event_log_is_bounded_and_sanitizes_labels(tmp_path):
+ log = BoundedEventLog(tmp_path / "events.json", max_entries=2)
+ for index in range(3):
+ log.append(
+ build_resolution_event(
+ agent="system",
+ kind="cooldown",
+ model_id=f"model-{index}",
+ reason="network",
+ from_source=f"src_source0{index}",
+ from_label=(
+ "Bearer abcdefghijklmnop"
+ if index == 2
+ else "Anthropic API Key"
+ if index == 1
+ else f"Source {index}"
+ ),
+ )
+ )
+
+ events = json.loads((tmp_path / "events.json").read_text(encoding="utf-8"))
+ assert len(events) == 2
+ assert "abcdefghijklmnop" not in json.dumps(events)
diff --git a/uv.lock b/uv.lock
index ae222c1cb..a017e9b50 100644
--- a/uv.lock
+++ b/uv.lock
@@ -331,6 +331,7 @@ dependencies = [
[package.dev-dependencies]
dev = [
+ { name = "jsonschema" },
{ name = "pytest" },
]
@@ -368,7 +369,10 @@ requires-dist = [
]
[package.metadata.requires-dev]
-dev = [{ name = "pytest", specifier = ">=9.0.3" }]
+dev = [
+ { name = "jsonschema", specifier = ">=4.26.0" },
+ { name = "pytest", specifier = ">=9.0.3" },
+]
[[package]]
name = "certifi"
diff --git a/vibe/api.py b/vibe/api.py
index c4aa8cdf2..d36cbeb9f 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -831,6 +831,12 @@ def save_config(payload: dict) -> V2Config:
if not isinstance(payload, dict):
raise ValueError("Config payload must be an object")
+ # Model Hub mutations must pass through ModelHubService so runtime source
+ # bindings and credential lifecycle stay in sync with the persisted config.
+ # Generic settings pages round-trip GET /api/config, so treat this section
+ # as a read-only projection here rather than accepting a potentially stale
+ # client snapshot.
+ payload = {key: value for key, value in payload.items() if key != "model_hub"}
payload = _strip_agent_auth_fields(payload)
payload = _strip_preserved_config_secrets(payload)
payload = _mark_explicit_audio_asr_enabled(payload)
@@ -1015,6 +1021,7 @@ def config_to_payload(config: V2Config, *, include_secrets: bool = False) -> dic
# resets ``agents.avault.cli_path`` to the dataclass default.
"avault": config.agents.avault.__dict__,
},
+ "model_hub": config.model_hub.to_payload(),
"gateway": _project_secret_fields(
config.gateway.__dict__ if config.gateway else None,
_GATEWAY_SECRET_FIELDS,
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 6eccde3b6..d48b8a24a 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -474,6 +474,41 @@
"routingSaving": "Saving routing settings...",
"routingCanceled": "Routing update canceled."
},
+ "modelHub": {
+ "errors": {
+ "source_not_found": "Model source not found.",
+ "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.",
+ "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.",
+ "consent_required": "Explicit consent is required for experimental subscription routing.",
+ "migration_item_conflict": "This migration item conflicts with current Model Hub state.",
+ "stream_interrupted": "The upstream stream was interrupted.",
+ "upstream_protocol_error": "The upstream response did not match the expected protocol.",
+ "upstream_request_invalid": "The upstream service rejected the request.",
+ "upstream_unauthorized": "The upstream service rejected authorization after refresh.",
+ "upstream_error": "The upstream service returned an error."
+ },
+ "events": {
+ "sourceFallback": "source",
+ "switch": "{from_source}: {reason} -> switched to {to_source}",
+ "cooldown": "{from_source}: {reason}; cooling down",
+ "recover": "{to_source}: recovered and available",
+ "status": "{from_source}: {reason}",
+ "reason": {
+ "quota_exhausted": "quota exhausted",
+ "rate_limited": "rate limited",
+ "server_error": "upstream server unavailable",
+ "network": "network unavailable",
+ "recovery": "recovered",
+ "manual": "manual change",
+ "mapping": "model mapping applied"
+ }
+ }
+ },
"remote_access": {
"oauth_error": {
"sign_in_again": "Sign in again",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 5f4a6a1ca..43a172ca3 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -474,6 +474,41 @@
"routingSaving": "正在保存 Agent 路由设置...",
"routingCanceled": "已取消更新 Agent 路由设置。"
},
+ "modelHub": {
+ "errors": {
+ "source_not_found": "未找到模型来源。",
+ "flow_not_found": "未找到授权流程。",
+ "flow_expired": "授权流程已过期。",
+ "discovery_failed": "无法验证或发现此来源。",
+ "invalid_priority_order": "优先级必须完整且不重复地包含所有来源。",
+ "mapping_target_unavailable": "所选模型无法用于此后端。",
+ "mode_switch_blocked": "当前供给模式或选择阻止了此操作。",
+ "engine_down": "本地模型中枢运行时不可用。",
+ "consent_required": "实验性订阅路由需要明确同意。",
+ "migration_item_conflict": "此迁移项与当前模型中枢状态冲突。",
+ "stream_interrupted": "上游流已中断。",
+ "upstream_protocol_error": "上游响应不符合预期协议。",
+ "upstream_request_invalid": "上游服务拒绝了请求。",
+ "upstream_unauthorized": "刷新后上游服务仍拒绝授权。",
+ "upstream_error": "上游服务返回错误。"
+ },
+ "events": {
+ "sourceFallback": "来源",
+ "switch": "{from_source}:{reason} -> 已切到 {to_source}",
+ "cooldown": "{from_source}:{reason},暂时冷却",
+ "recover": "{to_source}:已恢复可用",
+ "status": "{from_source}:{reason}",
+ "reason": {
+ "quota_exhausted": "额度用完",
+ "rate_limited": "请求受限",
+ "server_error": "上游服务暂不可用",
+ "network": "网络暂不可用",
+ "recovery": "已恢复",
+ "manual": "手动调整",
+ "mapping": "已应用模型映射"
+ }
+ }
+ },
"remote_access": {
"oauth_error": {
"sign_in_again": "重新登录",
diff --git a/vibe/runtime.py b/vibe/runtime.py
index 654adadb8..40000a5ad 100644
--- a/vibe/runtime.py
+++ b/vibe/runtime.py
@@ -121,6 +121,8 @@ def ensure_dirs():
def default_config():
+ from config.v2_config import ModelHubConfig
+
work_dir = Path.home() / "work"
work_dir.mkdir(parents=True, exist_ok=True)
return V2Config(
@@ -133,6 +135,7 @@ def default_config():
claude=ClaudeConfig(enabled=True, cli_path="claude"),
codex=CodexConfig(enabled=False, cli_path="codex"),
),
+ model_hub=ModelHubConfig.fresh(),
)
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 551c8cd54..b26f44097 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -3019,6 +3019,270 @@ def config_get():
return jsonify(api.config_to_payload(config))
+_MODEL_HUB_ENGINE_ADAPTER = None
+_MODEL_HUB_NATIVE_OAUTH_ADAPTER = None
+_MODEL_HUB_SERVICE = None
+
+
+def _model_hub_service():
+ from core.handlers.model_hub import create_default_service
+
+ global _MODEL_HUB_SERVICE
+ if _MODEL_HUB_SERVICE is None:
+ _MODEL_HUB_SERVICE = create_default_service(
+ adapter=_MODEL_HUB_ENGINE_ADAPTER,
+ native_oauth_adapter=_MODEL_HUB_NATIVE_OAUTH_ADAPTER,
+ )
+ return _MODEL_HUB_SERVICE
+
+
+def _model_hub_success(**payload):
+ return jsonify({"ok": True, "contract_version": 1, **payload})
+
+
+def _model_hub_error(exc):
+ body = {"ok": False, "contract_version": 1, "error": exc.code}
+ if exc.detail:
+ body["detail"] = exc.detail
+ return jsonify(body), exc.status
+
+
+def _model_hub_json_object(error: str = "discovery_failed", *, status: int = 400):
+ from core.handlers.model_hub import ModelHubError
+
+ payload = request.json
+ if not isinstance(payload, dict):
+ raise ModelHubError(error, status=status)
+ return payload
+
+
[email protected]("/api/models/sources", methods=["GET"])
+def model_hub_sources_get():
+ return _model_hub_success(sources=_model_hub_service().list_sources())
+
+
[email protected]("/api/models/sources", methods=["POST"])
+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
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/sources/<source_id>", methods=["PATCH"])
+async def model_hub_sources_patch(source_id):
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ source = await _model_hub_service().patch_source(source_id, _model_hub_json_object())
+ return _model_hub_success(source=source)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/sources/<source_id>", methods=["DELETE"])
+async def model_hub_sources_delete(source_id):
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ force = str(request.args.get("force") or "").lower() in _TRUE_BOOL_STRINGS
+ await _model_hub_service().delete_source(source_id, force=force)
+ return _model_hub_success()
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/sources/<source_id>/test", methods=["POST"])
+async def model_hub_sources_test(source_id):
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ _, discovered = await _model_hub_service().test_source(source_id)
+ return _model_hub_success(discovered=discovered)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/priority", methods=["GET"])
+def model_hub_priority_get():
+ priority = _model_hub_service().priority()
+ return _model_hub_success(order=priority["order"])
+
+
[email protected]("/api/models/priority", methods=["PUT"])
+async def model_hub_priority_put():
+ 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"])
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/agents", methods=["GET"])
+def model_hub_agents_get():
+ return _model_hub_success(agents=_model_hub_service().list_agents())
+
+
[email protected]("/api/models/agents/<backend>/mode", methods=["PATCH"])
+async def model_hub_agent_mode_patch(backend):
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ agent = await _model_hub_service().set_agent_mode(
+ backend,
+ _model_hub_json_object("mode_switch_blocked").get("mode"),
+ )
+ return _model_hub_success(agent=agent)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/agents/<backend>/mappings", methods=["PUT"])
+async def model_hub_agent_mappings_put(backend):
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ agent = await _model_hub_service().set_mappings(
+ backend,
+ _model_hub_json_object("mapping_target_unavailable").get("mappings"),
+ )
+ return _model_hub_success(agent=agent)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/agents/opencode/menu", methods=["PUT"])
+async def model_hub_opencode_menu_put():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ agent = await _model_hub_service().set_opencode_menu(
+ _model_hub_json_object("mapping_target_unavailable").get("menu")
+ )
+ return _model_hub_success(agent=agent)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/custom-models", methods=["POST"])
+async def model_hub_custom_models_post():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ source = await _model_hub_service().add_custom_model(
+ _model_hub_json_object("source_not_found", status=404)
+ )
+ return _model_hub_success(source=source), 201
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/custom-models", methods=["DELETE"])
+async def model_hub_custom_models_delete():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ payload = _model_hub_json_object("mapping_target_unavailable")
+ source = await _model_hub_service().delete_custom_model(payload.get("source_id"), payload.get("model_id"))
+ return _model_hub_success(source=source)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/events", methods=["GET"])
+def model_hub_events_get():
+ try:
+ limit = int(request.args.get("limit") or 20)
+ except (TypeError, ValueError):
+ limit = 20
+ events = _model_hub_service().list_events(limit=limit, before=request.args.get("before") or None)
+ return _model_hub_success(events=events)
+
+
[email protected]("/api/models/oauth/start", methods=["POST"])
+async def model_hub_oauth_start():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ return _model_hub_success(
+ flow=await _model_hub_service().oauth_start(_model_hub_json_object("flow_not_found"))
+ )
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/oauth/status/<flow_id>", methods=["GET"])
+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))
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/oauth/submit", methods=["POST"])
+async def model_hub_oauth_submit():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ return _model_hub_success(
+ flow=await _model_hub_service().oauth_submit(
+ _model_hub_json_object("flow_not_found", status=404)
+ )
+ )
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/oauth/cancel", methods=["POST"])
+async def model_hub_oauth_cancel():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ await _model_hub_service().oauth_cancel(
+ _model_hub_json_object("flow_not_found", status=404).get("flow_id")
+ )
+ return _model_hub_success()
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/migration/scan", methods=["POST"])
+def model_hub_migration_scan():
+ return _model_hub_success(**_model_hub_service().migration_scan())
+
+
[email protected]("/api/models/migration/apply", methods=["POST"])
+def model_hub_migration_apply():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ result = _model_hub_service().migration_apply(
+ _model_hub_json_object("migration_item_conflict", status=409).get("item_ids")
+ )
+ return _model_hub_success(**result)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
[email protected]("/api/models/runtime/status", methods=["GET"])
+async def model_hub_runtime_status():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ return _model_hub_success(runtime=await _model_hub_service().runtime_status())
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+
@app.route("/api/platforms", methods=["GET"])
def platforms_get():
from vibe import api