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 Avibe consumer resolution and served-hop reports (#2336)

Call Whitec671b58bc68f
diff --git a/config/v2_config.py b/config/v2_config.py
index 88bf6457c..e46b79a6f 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -176,7 +176,7 @@ MIN_CHAT_MESSAGE_FONT_SIZE_PX = 12
MAX_CHAT_MESSAGE_FONT_SIZE_PX = 20
DEFAULT_AGENT_PROGRESS_STYLE = "off"
MODEL_HUB_ENABLED_ENV = "VIBE_MODEL_HUB_ENABLED"
-MODEL_HUB_BACKENDS = ("claude", "codex", "opencode")
+MODEL_HUB_BACKENDS = ("claude", "codex", "opencode", "avibe")
MODEL_HUB_LEGACY_CREATED_AT = "1970-01-01T00:00:00Z"
_LEGACY_CLAUDE_FAMILY_ALIASES = {
"opus": "opus",
@@ -2791,7 +2791,7 @@ class ModelHubAgentSourcesConfig:
@dataclass
class ModelHubAgentSupplyConfig:
- backend: Literal["claude", "codex", "opencode"]
+ backend: Literal["claude", "codex", "opencode", "avibe"]
mode: Literal["hub", "direct"]
menu_kind: Literal["fixed", "open"]
sources: ModelHubAgentSourcesConfig = field(default_factory=ModelHubAgentSourcesConfig)
@@ -2802,6 +2802,8 @@ class ModelHubAgentSupplyConfig:
@classmethod
def default(cls, backend: str, *, mode: Literal["hub", "direct"]) -> "ModelHubAgentSupplyConfig":
+ if backend == "avibe":
+ return cls(backend="avibe", mode="hub", menu_kind="fixed")
if backend == "opencode":
return cls(
backend="opencode",
@@ -2843,12 +2845,14 @@ class ModelHubAgentSupplyConfig:
backend = expected_backend if raw_backend is None else raw_backend
mode = payload.get("mode")
menu_kind = payload.get("menu_kind")
- if not isinstance(backend, str) or backend not in {"claude", "codex", "opencode"} or (
+ if not isinstance(backend, str) or backend not in MODEL_HUB_BACKENDS or (
expected_backend is not None and backend != expected_backend
):
raise ValueError("Config 'model_hub.agents.backend' is invalid")
if not isinstance(mode, str) or mode not in {"hub", "direct"}:
raise ValueError("Config 'model_hub.agents.mode' is invalid")
+ if backend == "avibe" and mode != "hub":
+ raise ValueError("Config 'model_hub.agents.avibe.mode' must be hub")
expected_menu_kind = "open" if backend == "opencode" else "fixed"
if not isinstance(menu_kind, str) or menu_kind != expected_menu_kind:
raise ValueError("Config 'model_hub.agents.menu_kind' is invalid for backend")
@@ -2990,6 +2994,11 @@ class ModelHubConfig:
# an unrelated save must not acknowledge an upgrade it did not perform.
runtime_default_applied: bool = True
+ def __post_init__(self) -> None:
+ # Existing in-process config producers may still supply the released
+ # three-backend shape, just like older on-disk configurations.
+ self.agents.setdefault("avibe", ModelHubAgentSupplyConfig.default("avibe", mode="hub"))
+
@staticmethod
def source_eligible_for_backend(
source: ModelHubSourceConfig,
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 29a68f361..bdcc5f7b3 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -1,4 +1,4 @@
-"""Model Hub EngineAdapter interface. FINAL CONTRACT v10 (2026-09-06).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v11 (2026-10-02).
This file is the canonical adapter boundary and must remain byte-identical to
``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:
diff --git a/core/handlers/model_hub/events.py b/core/handlers/model_hub/events.py
index c415d6848..02b2d12c3 100644
--- a/core/handlers/model_hub/events.py
+++ b/core/handlers/model_hub/events.py
@@ -15,7 +15,7 @@ from vibe.i18n import t as i18n_t
from .state_file import write_state_document
-EventAgent = Literal["claude", "codex", "opencode", "system"]
+EventAgent = Literal["claude", "codex", "opencode", "avibe", "system"]
EventKind = Literal[
"switch",
"cooldown",
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index c9b800742..3ee06484f 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -12,7 +12,7 @@ from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Iterable, Literal, Mapping, Optional
-from config.v2_config import ModelHubConfig
+from config.v2_config import MODEL_HUB_BACKENDS, ModelHubConfig
from core.os_errors import format_os_errno
from core.run_settlement import (
@@ -36,16 +36,46 @@ from .events import (
SOURCE_DETAIL_EVENT_REASONS,
event_reason_label,
)
-from .resolver import ModelHubTurnResolution, parse_model_hub_timestamp, source_eligible_for_backend
+from .resolver import BackendName, ModelHubTurnResolution, parse_model_hub_timestamp, source_eligible_for_backend
from .state_file import write_state_document
-BackendName = Literal["claude", "codex", "opencode"]
SupplyChannel = Literal["native_cli", "hub"]
SupplyState = Literal["waiting", "interrupted"]
ScopeKey = tuple[BackendName, str]
logger = logging.getLogger(__name__)
+SERVED_HOP_HEADER = "x-avibe-served-hop"
+SERVED_HOP_HEADER_MAX_BYTES = 4096
+
+
+class ServedHopHeaderTooLarge(ValueError):
+ """The exact origin cannot be transported in the bounded consumer header."""
+
+
+class PreparedGatewayRouteConflict(ValueError):
+ """An Avibe launch would replace another request's still-owned route."""
+
+
+@dataclass(frozen=True)
+class HopOrigin:
+ """Source identity captured at admission, before mutable config can change."""
+
+ provider: str
+ api: str
+ model: str
+
+ def payload(self) -> dict[str, str]:
+ return {"provider": self.provider, "api": self.api, "model": self.model}
+
+ def response_headers(self) -> dict[str, str]:
+ # JSON escapes keep arbitrary Unicode model ids safe in HTTP headers.
+ value = json.dumps(self.payload(), ensure_ascii=True, separators=(",", ":"))
+ # ensure_ascii makes character count equal to wire byte count.
+ if len(value) > SERVED_HOP_HEADER_MAX_BYTES:
+ raise ServedHopHeaderTooLarge("Served-hop header exceeds its transport bound")
+ return {SERVED_HOP_HEADER: value}
+
@dataclass(frozen=True)
class AttemptIdentity:
@@ -54,6 +84,7 @@ class AttemptIdentity:
channel: SupplyChannel
stripped_reasoning_efforts: tuple[str, ...] = ()
declared_reasoning_efforts: tuple[str, ...] = ()
+ origin: HopOrigin | None = None
def payload(self) -> dict:
payload = {
@@ -68,6 +99,8 @@ class AttemptIdentity:
payload["declared_reasoning_efforts"] = list(
self.declared_reasoning_efforts
)
+ if self.origin is not None:
+ payload["origin"] = self.origin.payload()
return payload
@@ -582,6 +615,9 @@ class TurnTrace:
# is actually awaiting an upstream result, and the loser settles with no
# record of what served it.
pending_attempts: dict[str, AttemptIdentity] = field(default_factory=dict)
+ # Attempts can settle before their HTTP request exits, or be absent while
+ # recovery waits. Route replacement must wait for the whole request.
+ gateway_requests: set[str] = field(default_factory=set)
model_supply_state: Optional[SupplyState] = None
blockers: list[dict] = field(default_factory=list)
gateway_source_id: Optional[str] = None
@@ -633,6 +669,7 @@ class PreparedGatewayRoute:
resolved_model_id: str
source_id: str
gateway_request_model_id: str
+ primary_origin: HopOrigin | None = None
@dataclass(frozen=True)
@@ -678,6 +715,8 @@ class GatewayTurnTerminalizer:
request_id=self._request_id,
request_metadata=self._request_metadata,
)
+ self._prepared_turn_id = self.turn_id
+ self.primary_origin = registry.gateway_primary_origin(backend=backend, token=token)
self._stream_started = False
self._attempt_started = False
self._downstream_canceled = False
@@ -688,13 +727,16 @@ class GatewayTurnTerminalizer:
return self
def __exit__(self, exc_type, _exc, _traceback) -> None:
- if self._downstream_canceled or exc_type is asyncio.CancelledError:
- return
- self._registry._terminalize_gateway_exit(
- self.turn_id,
- request_id=self._request_id,
- stream_started=self._stream_started,
- )
+ try:
+ if self._downstream_canceled or exc_type is asyncio.CancelledError:
+ return
+ self._registry._terminalize_gateway_exit(
+ self.turn_id,
+ request_id=self._request_id,
+ stream_started=self._stream_started,
+ )
+ finally:
+ self._registry.close_gateway_request(self._prepared_turn_id, request_id=self._request_id)
def resolution_model(self, gateway_model_id: str) -> Optional[str]:
"""Return the uniquely prepared caller model for this gateway request."""
@@ -708,6 +750,8 @@ class GatewayTurnTerminalizer:
request_metadata=self._request_metadata,
)
self.turn_id = routing.owner_turn_id
+ if self.turn_id is None:
+ self._registry.close_gateway_request(self._prepared_turn_id, request_id=self._request_id)
if self.turn_id is None and self.on_attribution_released is not None:
release, self.on_attribution_released = self.on_attribution_released, None
release()
@@ -756,6 +800,7 @@ class GatewayTurnTerminalizer:
via_mapping: bool,
stripped_reasoning_efforts: tuple[str, ...] = (),
declared_reasoning_efforts: tuple[str, ...] = (),
+ origin: HopOrigin | None = None,
) -> None:
self._attempt_started = True
self._registry.begin_attempt(
@@ -766,6 +811,7 @@ class GatewayTurnTerminalizer:
via_mapping=via_mapping,
stripped_reasoning_efforts=stripped_reasoning_efforts,
declared_reasoning_efforts=declared_reasoning_efforts,
+ origin=origin,
request_id=self._request_id,
)
@@ -1000,7 +1046,7 @@ class TurnCorrelationRegistry:
@staticmethod
def _scope_key(backend: str, process_scope: str) -> ScopeKey:
- if backend not in {"claude", "codex", "opencode"}:
+ if backend not in MODEL_HUB_BACKENDS:
raise ValueError("unsupported backend")
normalized = str(process_scope or "").strip()
if not normalized:
@@ -1140,6 +1186,13 @@ class TurnCorrelationRegistry:
)
return token
+ def gateway_primary_origin(self, *, backend: str, token: str) -> HopOrigin | None:
+ """Read the immutable launch origin, independent of live turn ownership."""
+
+ with self._lock:
+ credential = self._credential(backend, token)
+ return credential.route.primary_origin if credential and credential.route else None
+
def _explicit_route(
self,
*,
@@ -1375,6 +1428,7 @@ class TurnCorrelationRegistry:
source_id: str,
via_mapping: bool,
gateway_request_model_id: str | None = None,
+ primary_origin: HopOrigin | None = None,
) -> str:
"""Register a route and return its legacy credential or explicit handle."""
@@ -1393,6 +1447,7 @@ class TurnCorrelationRegistry:
resolved_model_id=resolved_model_id,
source_id=source_id,
gateway_request_model_id=request_model_id,
+ primary_origin=primary_origin,
)
if scope.request_scoped:
@@ -1421,8 +1476,30 @@ class TurnCorrelationRegistry:
else:
exact = self._exact_turn(backend, token)
if exact is None:
+ if backend == "avibe":
+ # A consumer launch without a tracked turn still needs
+ # its alias and primary origin bound to this credential.
+ return self._route_credential(key, scope, prepared)
return token
route_turn_id = exact[0]
+ existing = scope.prepared_routes.get(route_turn_id)
+ if backend == "avibe" and existing is not None and existing != prepared:
+ trace = self._readable_trace(route_turn_id, backend)
+ if (
+ trace is None
+ or trace.requested_model_id != requested_model_id
+ or trace.gateway_requests
+ or trace.pending_attempts
+ or trace.recovery_requests
+ ):
+ raise PreparedGatewayRouteConflict("Avibe route is still owned or its alias changed")
+ # Keep the turn's attempt history and outcome. Only the launch
+ # snapshot changes; old credentials can route but cannot claim
+ # this newly prepared identity.
+ scope.prepared_routes.pop(route_turn_id)
+ trace.gateway_source_id = None
+ trace.gateway_request_model_id = None
+ trace.gateway_model_id = None
launch_token = self._route_credential(key, scope, prepared)
self._register_prepared_gateway_route(
scope=scope,
@@ -1761,6 +1838,12 @@ class TurnCorrelationRegistry:
or trace.gateway_model_id is None
):
return None
+ if backend == "avibe":
+ if credential.route != scope.prepared_routes.get(turn_id):
+ # A superseded credential must not poison the successor
+ # even when malformed JSON fails before body attribution.
+ return None
+ trace.gateway_requests.add(request_id)
trace.pending_attempts[request_id] = AttemptIdentity(
source_id=trace.gateway_source_id,
resolved_model_id=trace.gateway_model_id,
@@ -1768,6 +1851,14 @@ class TurnCorrelationRegistry:
)
return turn_id
+ def close_gateway_request(self, turn_id: str | None, *, request_id: str) -> None:
+ """Release request lifetime independently of its last attempt outcome."""
+
+ with self._lock:
+ trace = self._traces.get(turn_id)
+ if trace is not None:
+ trace.gateway_requests.discard(request_id)
+
def clear_prepared_attempt(
self,
turn_id: Optional[str],
@@ -1868,6 +1959,8 @@ class TurnCorrelationRegistry:
resolved_model_id: str,
via_mapping: bool,
) -> None:
+ if backend == "avibe":
+ raise ValueError("avibe attempts require the hub channel")
token = self.credentials(backend, process_scope, turn_id)
normalized_turn_id = str(turn_id or "").strip()
if not normalized_turn_id:
@@ -1974,6 +2067,7 @@ class TurnCorrelationRegistry:
stripped_reasoning_efforts: tuple[str, ...] = (),
declared_reasoning_efforts: tuple[str, ...] = (),
request_id: str = TURN_REQUEST,
+ origin: HopOrigin | None = None,
) -> None:
if turn_id is None:
return
@@ -1981,6 +2075,8 @@ class TurnCorrelationRegistry:
trace = self._traces.get(turn_id)
if trace is None or trace.outcome_frozen:
return
+ if trace.agent == "avibe" and channel != "hub":
+ raise ValueError("avibe attempts require the hub channel")
# Admission supersedes earlier supply failures, not their attempt history.
trace.model_supply_state = None
trace.blockers = []
@@ -1992,6 +2088,7 @@ class TurnCorrelationRegistry:
channel=channel,
stripped_reasoning_efforts=stripped_reasoning_efforts,
declared_reasoning_efforts=declared_reasoning_efforts,
+ origin=origin,
)
def fail_native_attempt(
@@ -2236,7 +2333,7 @@ class TurnCorrelationRegistry:
self.store.put(
{
- "contract_version": 10,
+ "contract_version": 11,
"turn_id": normalized_turn_id,
"ts": ts or _utc_now_iso(),
"agent": trace.agent,
diff --git a/core/handlers/model_hub/request.py b/core/handlers/model_hub/request.py
index fc36f26c4..4fb7883bf 100644
--- a/core/handlers/model_hub/request.py
+++ b/core/handlers/model_hub/request.py
@@ -2,7 +2,10 @@
from __future__ import annotations
-from typing import Any, Final, Mapping
+from typing import TYPE_CHECKING, Any, Final, Mapping
+
+if TYPE_CHECKING:
+ from .provenance import HopOrigin
# Caller headers that cross from an agent CLI's request to the local engine.
# Protocol capability headers select request features. ``user-agent`` keeps
@@ -29,7 +32,75 @@ class ModelHubRequest(dict[str, Any]):
*,
protocol: str,
headers: Mapping[str, str] | None = None,
+ primary_origin: HopOrigin | None = None,
) -> None:
super().__init__(payload)
self.protocol = protocol
self.headers = dict(headers or {})
+ # Launch snapshot, not wire JSON. Every retry compares against this
+ # origin, even when resolution restarts after cooldown/config changes.
+ self.primary_origin = primary_origin
+
+
+_OPAQUE_FIELDS = frozenset({"signature", "thoughtSignature", "thought_signature", "encrypted_content"})
+
+
+def _plain_metadata(value: Any) -> Any:
+ """Remove opaque fields only within protocol-owned extension metadata."""
+
+ if isinstance(value, dict):
+ return {key: _plain_metadata(item) for key, item in value.items() if key not in _OPAQUE_FIELDS}
+ if isinstance(value, list):
+ return [_plain_metadata(item) for item in value]
+ return value
+
+
+def _plain_history(value: Any) -> Any:
+ if isinstance(value, list):
+ return [plain for item in value if (plain := _plain_history(item)) is not None]
+ if not isinstance(value, dict):
+ return value
+ kind = value.get("type")
+ if kind == "redacted_thinking":
+ return None
+ if kind == "thinking":
+ text = value.get("thinking", value.get("text"))
+ return {"type": "text", "text": text} if isinstance(text, str) and text else None
+ if kind == "reasoning":
+ # Responses summaries (and visible reasoning content) are readable
+ # history, not portable reasoning items. Never replay their item ids.
+ texts = [
+ {"type": "output_text", "text": part["text"]}
+ for field in ("summary", "content")
+ for part in (value.get(field) if isinstance(value.get(field), list) else [])
+ if isinstance(part, dict) and isinstance(part.get("text"), str) and part["text"]
+ ]
+ return {"role": "assistant", "content": texts} if texts else None
+ plain = {key: item for key, item in value.items() if key not in _OPAQUE_FIELDS}
+ for field in ("content", "parts", "tool_calls"):
+ if field in plain:
+ plain[field] = _plain_history(plain[field])
+ if "extra_content" in plain:
+ plain["extra_content"] = _plain_metadata(plain["extra_content"])
+ if plain.get("role") == "assistant" and plain.get("content") == [] and not plain.get("tool_calls"):
+ # A redacted-only assistant turn has no portable content. Leaving an
+ # empty message behind would make an otherwise valid history invalid.
+ return None
+ # Tool input/arguments/results, schemas, and arbitrary user data are not
+ # protocol blocks: a user field named "signature" there must survive.
+ return plain
+
+
+def without_opaque_history(request: Mapping[str, Any]) -> Mapping[str, Any]:
+ """Copy a request's history for an unverified/different Avibe hop origin."""
+
+ payload = dict(request)
+ for field in ("messages", "input"):
+ if field in payload:
+ payload[field] = _plain_history(payload[field])
+ if isinstance(request, ModelHubRequest):
+ return ModelHubRequest(
+ payload, protocol=request.protocol, headers=request.headers,
+ primary_origin=request.primary_origin,
+ )
+ return payload
diff --git a/core/handlers/model_hub/resolver.py b/core/handlers/model_hub/resolver.py
index 7a38c53b0..57536e79c 100644
--- a/core/handlers/model_hub/resolver.py
+++ b/core/handlers/model_hub/resolver.py
@@ -17,7 +17,7 @@ from config.v2_config import (
)
-BackendName = Literal["claude", "codex", "opencode"]
+BackendName = Literal["claude", "codex", "opencode", "avibe"]
ResolutionChannel = Literal["direct", "native_cli", "hub", "unavailable"]
SupplyStatus = Literal["ok", "degraded", "waiting", "interrupted"]
RouteOrigin = Literal["automatic", "manual", "passthrough"]
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index 16ef286e9..1f11a50fc 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -134,12 +134,14 @@ from .provenance import (
BoundedProvenanceStore,
ENGINE_DOWN_TURN_OUTCOME,
ExactHopBlocker,
+ HopOrigin,
+ ServedHopHeaderTooLarge,
TurnOutcomeProjectionInput,
exact_hop_blockers,
no_candidate_decision,
produce_turn_outcome,
)
-from .request import ModelHubRequest
+from .request import ModelHubRequest, without_opaque_history
from .reasoning_tiers import resolve_reasoning_tiers
from .stream_wire import ProtocolSSEState
from .resolver import (
@@ -169,7 +171,7 @@ from .usage import (
local_usage_day,
)
-CONTRACT_VERSION = 10
+CONTRACT_VERSION = 11
def seeded_source_name(vendor: str) -> str:
@@ -271,8 +273,8 @@ _MODELS_DEV_CANDIDATE_FIELDS = (
)
-AGENT_CHAIN_CONTRACT_VERSION = 10
-PROBE_RESULT_CONTRACT_VERSION = 10
+AGENT_CHAIN_CONTRACT_VERSION = 11
+PROBE_RESULT_CONTRACT_VERSION = 11
_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15
_SOURCE_PROBE_TIMEOUT_SECONDS = 60
_REORDER_ORDER_UNSET = object()
@@ -364,6 +366,7 @@ class ModelHubError(Exception):
blockers: Iterable[ExactHopBlocker] = (),
turn_outcome: TurnOutcomeProjectionInput | None = None,
local_error_detail: str | None = None,
+ origin: HopOrigin | None = None,
):
detail_key = detail or f"modelHub.errors.{code}"
super().__init__(detail_key)
@@ -375,6 +378,9 @@ class ModelHubError(Exception):
self.blockers = tuple(blockers)
self.turn_outcome = turn_outcome
self.local_error_detail = local_error_detail
+ # Only surfaced upstream responses carry an admitted, immutable origin.
+ # Local refusals/exhaustion must not inherit the last attempted hop.
+ self.origin = origin
def turn_refusal(error: BaseException | None) -> TurnOutcomeProjectionInput | None:
@@ -625,6 +631,7 @@ class ResolvedInvocation:
credential_ref: Optional[str] = None
settlement_generation: Optional[int] = None
verification_pending: Optional[str] = None
+ origin: HopOrigin | None = None
@dataclass(frozen=True)
@@ -647,6 +654,7 @@ AttemptObserver = Callable[
Optional[ResolutionDecision],
tuple[str, ...],
tuple[str, ...],
+ Optional[HopOrigin],
],
None,
]
@@ -918,7 +926,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:
manager = EngineRuntimeManager()
return {
- "contract_version": 10,
+ "contract_version": 11,
"enabled": enabled,
"host_platform": status.host_platform or manager.host_platform(),
"manifest": manager.contract_manifest(),
@@ -1697,7 +1705,7 @@ class ModelHubService:
except (TakeoverStateError, OSError):
# Unknown recovery state cannot authorize any native credential
# writer or native launch. Controller recovery preserves this gate.
- self.migration_blocked_backends.update(MODEL_HUB_BACKENDS)
+ self.migration_blocked_backends.update(("claude", "codex", "opencode"))
raise ModelHubError("migration_item_conflict", status=409) from None
task = self._runtime_resume_task
if task is None or task.done():
@@ -4784,6 +4792,7 @@ class ModelHubService:
# Suppliers speak first, models.dev fills what they left unsaid, and
# an unstated ladder falls back to the tiers the backend's request
# protocol accepts, unless models.dev says the model cannot reason.
+ # Avibe has no native protocol pin and must not receive guessed tiers.
enrichment = (
{field: match[field] for field in _MODELS_DEV_CANDIDATE_FIELDS}
if match is not None
@@ -4796,7 +4805,7 @@ class ModelHubService:
display_name = display_name or (match or {}).get("display_name")
if not reasoning_efforts and match is not None:
reasoning_efforts = list(match["reasoning_efforts"])
- if not reasoning_efforts and enrichment.get("supports_reasoning") is not False:
+ if backend != "avibe" and not reasoning_efforts and enrichment.get("supports_reasoning") is not False:
request_protocol = _FIXED_BACKEND_PROTOCOLS.get(
backend
) or native_protocol_for_model_id(model_id)
@@ -4965,7 +4974,7 @@ class ModelHubService:
live_recovery = self.recovery.annotations(config)
return [
self._agent_payload(config, config.agents[backend], live_recovery=live_recovery)
- for backend in ("claude", "codex", "opencode")
+ for backend in MODEL_HUB_BACKENDS
]
def refresh_cli_presence(
@@ -4982,6 +4991,8 @@ class ModelHubService:
logger.warning("Model Hub CLI presence refresh failed", exc_info=True)
def _cli_present(self, backend: BackendName) -> bool:
+ if backend == "avibe":
+ return False
if self.cli_present_override is None:
return False
try:
@@ -5071,7 +5082,7 @@ class ModelHubService:
)
async def set_agent_mode(self, backend: str, mode: object) -> dict:
- if mode not in {"hub", "direct"}:
+ if mode not in {"hub", "direct"} or (backend == "avibe" and mode != "hub"):
raise ModelHubError("mode_switch_blocked")
from core.backend_restart import NativeMigrationBlockedError
@@ -7201,6 +7212,7 @@ class ModelHubService:
backend
for backend, agent in previous.agents.items()
if agent.mode == "hub"
+ and (backend != "avibe" or agent.models)
)
if hub_backends:
raise ModelHubError(
@@ -7242,7 +7254,7 @@ class ModelHubService:
clean_native_stores=(self.migration_journal.completed() or {}).get("clean_native_stores"),
retained_native_ids=(self.migration_journal.completed() or {}).get("retained_native_ids"),
legacy_auth=(
- self.store.native_auth_snapshot(MODEL_HUB_BACKENDS)
+ self.store.native_auth_snapshot(("claude", "codex", "opencode"))
if isinstance(self.store, V2ModelHubConfigStore) else None
),
)
@@ -7296,7 +7308,7 @@ class ModelHubService:
try:
pending = self.migration_journal.load()
except (TakeoverStateError, OSError):
- self.migration_blocked_backends.update(MODEL_HUB_BACKENDS)
+ self.migration_blocked_backends.update(("claude", "codex", "opencode"))
raise ModelHubError("migration_configuration_blocked", status=409) from None
if pending is not None and pending["phase"] == "exposed":
raise ModelHubError("migration_recovery_pending", status=409) from None
@@ -7857,6 +7869,18 @@ class ModelHubService:
or candidate.model_id != model_id
):
raise _InvocationPlanChanged
+ attempt_request = request
+ if backend == "avibe":
+ # Validate the exact rechecked admission snapshot for every
+ # hop, including fallback/refresh. Persisted ids stay intact;
+ # refusal must precede a transport, attempt, or recovery slot.
+ try:
+ origin = HopOrigin(source.vendor, source.protocol, model_id)
+ origin.response_headers()
+ except ServedHopHeaderTooLarge:
+ raise ModelHubError("served_hop_too_large", status=422) from None
+ if getattr(request, "primary_origin", None) != origin:
+ attempt_request = without_opaque_history(request)
if self._engine_synced:
if recovery_request is not None and recovery_request.expired:
raise _RecoveryWindowClosed
@@ -7866,7 +7890,7 @@ class ModelHubService:
# Lock order matches config sync. The adapter hands exclusion
# back only after owning the transport that sync must drain.
return await self._engine_call(self.adapter.invoke(
- source.id, model_id, request, stream, backend, on_admitted=admitted,
+ source.id, model_id, attempt_request, stream, backend, on_admitted=admitted,
))
except BaseException:
self.recovery.release(source.id, generation)
@@ -8011,6 +8035,7 @@ class ModelHubService:
decision,
(),
(),
+ HopOrigin(source.vendor, source.protocol, source_model_id) if backend == "avibe" else None,
)
if decision.action == "fallback" or (
decision.action == "surface"
@@ -8141,7 +8166,7 @@ class ModelHubService:
attempt_observer: Optional[AttemptObserver] = None,
recovery_request: RecoveryRequest | None = None,
) -> ResolvedInvocation:
- if backend not in {"claude", "codex", "opencode"}:
+ if backend not in MODEL_HUB_BACKENDS:
raise ModelHubError("mapping_target_unavailable")
engine_prepared = False
if self.revocations.list():
@@ -8208,6 +8233,7 @@ class ModelHubService:
if source is None or target_model is None:
raise AssertionError("runnable hop must have an exact identity")
verification_pending = source.verification_pending
+ origin = HopOrigin(source.vendor, source.protocol, target_model) if backend == "avibe" else None
if source.supply_channel == "native_cli":
self._emit_switch(
agent=event_agent,
@@ -8247,6 +8273,7 @@ class ModelHubService:
None,
(),
(),
+ origin,
)
try:
@@ -8289,6 +8316,7 @@ class ModelHubService:
credential_ref=source.credential_ref,
settlement_generation=settlement_generation,
verification_pending=verification_pending,
+ origin=origin,
)
decision = await self._classify_source_outcome(source, outcome)
if cancelled is not None:
@@ -8323,7 +8351,7 @@ class ModelHubService:
)
except _InvocationPlanChanged:
if attempt_observer is not None:
- attempt_observer(source.id, target_model, "hub", False, outcome, decision, (), ())
+ attempt_observer(source.id, target_model, "hub", False, outcome, decision, (), (), origin)
continue
except _RecoveryWindowClosed:
window_closed = not non_retryable_failure
@@ -8350,6 +8378,7 @@ class ModelHubService:
credential_ref=source.credential_ref,
settlement_generation=settlement_generation,
verification_pending=verification_pending,
+ origin=origin,
)
decision = classify_outcome(outcome, refresh_attempted=True)
if cancelled is not None:
@@ -8374,6 +8403,7 @@ class ModelHubService:
decision,
(),
(),
+ origin,
)
if decision.action == "return":
if self._verified_recovery_outcome(outcome):
@@ -8402,6 +8432,7 @@ class ModelHubService:
credential_ref=source.credential_ref,
settlement_generation=settlement_generation,
verification_pending=verification_pending,
+ origin=origin,
)
if decision.action == "surface":
self.recovery.release(source.id, settlement_generation)
@@ -8418,6 +8449,11 @@ class ModelHubService:
)
raise ModelHubError(
decision.error_code or outcome.error_code or "engine_down",
+ origin=(
+ origin if settlement_generation is not None
+ and terminal_outcome_category(outcome, decision) != "engine_down"
+ else None
+ ),
local_error_detail=format_os_errno(outcome.os_errno),
status=decision.downstream_status or (
outcome.http_status
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 889703917..280ad5b44 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -20,6 +20,7 @@ from aiohttp import web
from packaging.version import Version
from config import paths
+from config.v2_config import MODEL_HUB_BACKENDS
from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
from vibe.i18n import t as i18n_t
@@ -35,6 +36,8 @@ from .provenance import (
BoundedProvenanceStore,
ENGINE_DOWN_TURN_OUTCOME,
GatewayTurnTerminalizer,
+ HopOrigin,
+ PreparedGatewayRouteConflict,
REQUEST_NONFALLBACK_TURN_OUTCOME,
TurnOutcomeProjectionInput,
TurnCorrelationRegistry,
@@ -107,6 +110,16 @@ def _gateway_utc_now() -> datetime:
return datetime.now(timezone.utc)
+def _response_origin_headers(carrier: ResolvedInvocation | ModelHubError) -> dict[str, str]:
+ """Publish only this response's admitted producer, whichever carrier won.
+
+ Local errors and native callers have no origin. Neither a primary snapshot,
+ mutable config nor a preceding attempt can supply one on their behalf.
+ """
+
+ return carrier.origin.response_headers() if carrier.origin is not None else {}
+
+
def _rewind_and_measure(payload: BinaryIO) -> int:
payload.seek(0, 2)
size = payload.tell()
@@ -502,9 +515,20 @@ class ModelHubTurnGateway:
via_mapping: bool = False,
gateway_request_model_id: Optional[str] = None,
request_scoped: bool = False,
+ primary_origin: HopOrigin | None = None,
) -> tuple[str, str]:
- if backend not in {"claude", "codex", "opencode"}:
+ if backend not in MODEL_HUB_BACKENDS:
raise ModelHubError("mapping_target_unavailable", status=409)
+ if backend == "avibe" and turn_id:
+ # The caller may read EOF before the previous handler's owned
+ # teardown exits. Drain already-settled responses, not live model
+ # work; the registry still refuses any remaining overlap.
+ finishing = [
+ owned.done for owned in self._turn_requests.get(turn_id, ())
+ if owned.execution.settlement_recorded or owned.execution.terminal_fact_committed
+ ]
+ if finishing:
+ await asyncio.wait(finishing, timeout=self._transport_timeout)
scope = str(process_scope or "").strip() or f"{backend}:untracked"
token = self.correlation.credentials(
backend, scope, turn_id, request_scoped=request_scoped,
@@ -513,16 +537,20 @@ class ModelHubTurnGateway:
# Credential-bound clients carry their route in authentication.
# Multiplexed Codex keeps authentication stable and carries this
# route's handle on each request instead.
- route_token = self.correlation.prepare_gateway_turn(
- backend=backend,
- token=token,
- turn_id=turn_id,
- requested_model_id=requested_model_id,
- resolved_model_id=resolved_model_id,
- source_id=source_id,
- via_mapping=via_mapping,
- gateway_request_model_id=gateway_request_model_id,
- )
+ try:
+ route_token = self.correlation.prepare_gateway_turn(
+ backend=backend,
+ token=token,
+ turn_id=turn_id,
+ requested_model_id=requested_model_id,
+ resolved_model_id=resolved_model_id,
+ source_id=source_id,
+ via_mapping=via_mapping,
+ gateway_request_model_id=gateway_request_model_id,
+ primary_origin=primary_origin,
+ )
+ except PreparedGatewayRouteConflict:
+ raise ModelHubError("mapping_target_unavailable", status=409) from None
if not request_scoped:
token = route_token
await self._ensure_started()
@@ -827,7 +855,7 @@ class ModelHubTurnGateway:
resources: AsyncExitStack,
) -> web.StreamResponse:
endpoint = request.match_info["endpoint"].strip("/")
- if backend not in {"claude", "codex", "opencode"} or endpoint not in _SUPPORTED_PATHS:
+ if backend not in MODEL_HUB_BACKENDS or endpoint not in _SUPPORTED_PATHS:
terminalizer.fail("protocol_error")
return self._terminal_error_response(
execution,
@@ -907,6 +935,7 @@ class ModelHubTurnGateway:
decision,
stripped_reasoning_efforts: tuple[str, ...],
declared_reasoning_efforts: tuple[str, ...],
+ origin: HopOrigin | None,
) -> None:
if outcome is None or decision is None:
terminalizer.begin_attempt(
@@ -916,6 +945,7 @@ class ModelHubTurnGateway:
via_mapping=via_mapping,
stripped_reasoning_efforts=stripped_reasoning_efforts,
declared_reasoning_efforts=declared_reasoning_efforts,
+ origin=origin,
)
return
terminalizer.finish_attempt(
@@ -940,6 +970,7 @@ class ModelHubTurnGateway:
payload,
protocol=protocol,
headers=caller_headers,
+ primary_origin=terminalizer.primary_origin,
),
stream=stream,
supply_channel="hub",
@@ -978,18 +1009,16 @@ class ModelHubTurnGateway:
headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},
)
response[_LOCAL_ENDING] = _RenderedTurnOutcome(RECOVERY_EXHAUSTED_CODE, RECOVERY_EXHAUSTED_MESSAGE)
- return await self._through_committed_stream(execution, protocol, response)
- return await self._through_committed_stream(
- execution,
- protocol,
- self._terminal_error_response(
+ else:
+ response = self._terminal_error_response(
execution,
terminalizer,
status=exc.status,
code=exc.code,
turn_outcome=turn_outcome,
- ),
- )
+ )
+ response.headers.update(_response_origin_headers(exc))
+ return await self._through_committed_stream(execution, protocol, response)
if execution.handle is not None:
# The execution boundary must own cleanup before an awaited health
@@ -1029,7 +1058,7 @@ class ModelHubTurnGateway:
writes to the response.
"""
- if not stream or protocol != "anthropic":
+ if not stream or protocol != "anthropic" or request.match_info["backend"] == "avibe":
yield
return
resolution_ended = asyncio.get_running_loop().create_future()
@@ -1093,20 +1122,28 @@ class ModelHubTurnGateway:
) -> web.StreamResponse:
if resolved.supply_channel != "hub":
return self._error_response(status=409, code="mode_switch_blocked")
+ # Resolution has crossed the engine's first-output barrier or already
+ # settled successfully: this request can no longer fail over. The same
+ # admitted origin is held by its provenance attempt.
+ origin_headers = _response_origin_headers(resolved)
if resolved.outcome is not None:
# A call that reached the resolver's own hands has already been
# metered there; its body never becomes this gateway's to forward.
- return self._outcome_response(resolved.outcome)
+ response = self._outcome_response(resolved.outcome)
+ response.headers.update(origin_headers)
+ return response
handle = resolved.handle
if handle is None or handle.stream is None:
terminalizer.engine_down()
- return self._terminal_error_response(
+ response = self._terminal_error_response(
execution,
terminalizer,
status=502,
code="engine_down",
turn_outcome=ENGINE_DOWN_TURN_OUTCOME,
)
+ response.headers.update(origin_headers)
+ return response
if not stream:
try:
@@ -1134,7 +1171,10 @@ class ModelHubTurnGateway:
body = await run_owned_in_thread(response_payload.read)
response = web.Response(
status=200, body=body, content_type="application/json",
- headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},
+ headers={
+ "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
+ **origin_headers,
+ },
)
else:
response = web.StreamResponse(
@@ -1142,6 +1182,7 @@ class ModelHubTurnGateway:
headers={
"Cache-Control": "no-store", "Content-Length": str(response_size),
"Content-Type": "application/json", "X-Content-Type-Options": "nosniff",
+ **origin_headers,
},
)
await self._downstream_io(response.prepare(request))
@@ -1172,23 +1213,26 @@ class ModelHubTurnGateway:
# Do not send a second HTTP response after committed headers.
execution.buffered_response.force_close()
return execution.buffered_response
+ failure.headers.update(origin_headers)
return failure
rendered = self._commit_and_render_handle_settlement(execution, terminalizer, settlement)
if response is None:
assert settlement.decision is not None
- return self._outcome_response(
+ response = self._outcome_response(
outcome,
error_code=settlement.decision.error_code,
status_override=settlement.decision.downstream_status,
rendered=rendered,
)
+ response.headers.update(origin_headers)
+ return response
if response is execution.buffered_response:
await self._downstream_io(response.write_eof())
return response
response = execution.stream_response
if response is None:
- response = web.StreamResponse(status=200, headers=_SSE_RESPONSE_HEADERS)
+ response = web.StreamResponse(status=200, headers={**_SSE_RESPONSE_HEADERS, **origin_headers})
await self._downstream_io(response.prepare(request))
wire_state = ProtocolSSEState(protocol)
execution.wire_state = wire_state
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 25d611f16..bb2b83e9f 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -1,7 +1,8 @@
# Model Hub contracts
-Status: **contract_version 10**, 2026-09-06: sparse manual overrides, shared effective
-planning and guarded Restore/default membership. The approved routing contract is
+Status: **contract_version 11**, 2026-10-02: Avibe Agent Hub-only consumer, primary-hop
+resolution, and response origin linked to the served attempt. See
+[`avibe-consumer.md`](avibe-consumer.md). The approved routing contract is
`../model-hub-routing-modes.md`, including the owner-approved Empty Route Inheritance
correction `352486374`; API-key-only scope remains unchanged.
@@ -110,6 +111,9 @@ No underlying engine expansion or OAuth alias substitution is part of this chang
Sources.
8. Direct mode and a Native hop are distinct. Direct bypasses Gateway for the backend;
Native is one configured hop inside Gateway mode.
+9. The `avibe` backend is Hub-only and never consumes a native CLI Source or launch
+ overlay. Its empty catalog added on upgrade changes no existing backend intent.
+ Response origin is captured at admission and shared with the recorded attempt.
### Takeover producer/consumer closure
@@ -175,7 +179,7 @@ comparison. A gate may not report success by comparing stale input with itself.
## Version closure
-`contract_version` 10 must coexist in all registered version locations on the same tested head:
+`contract_version` 11 must coexist in all registered version locations on the same tested head:
- `mirror-registry.json`
- `agent-chain.schema.json`
@@ -243,4 +247,8 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| `opencode-overlay.md` | Stable OpenCode provider/model identifiers and effective-hop overlay behavior. |
| `adapter-interface.py` | Adapter protocol, observation, credential, discovery, invocation, cleanup, and classification boundary. |
| `mirror-registry.json` | Executable authority/mirror registry and terminal contract version. |
+| `avibe-consumer.md` | C-6 launch projection, capability authority, served-hop response headers, and delivery boundaries. |
+| `avibe-boundary-matrix.json` | Executable Avibe backend/channel audit: all declared schema shapes, runtime admission owners, and Hub-only refusal cases. |
+| `hop-resolution.schema.json` | Ephemeral in-process Avibe consumer result, including gateway-only credentials and nullable capabilities. |
+| `hop-origin.schema.json` | Non-secret response origin shared by the HTTP response header and provenance attempt. |
| `README.md` | This ownership, version-closure, and contract-index document. |
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 29a68f361..bdcc5f7b3 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -1,4 +1,4 @@
-"""Model Hub EngineAdapter interface. FINAL CONTRACT v10 (2026-09-06).
+"""Model Hub EngineAdapter interface. FINAL CONTRACT v11 (2026-10-02).
This file is the canonical adapter boundary and must remain byte-identical to
``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:
diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.json
index cb5542736..da5ff5da4 100644
--- a/docs/plans/model-hub-contracts/agent-chain.schema.json
+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json
@@ -7,8 +7,8 @@
"required": ["contract_version", "backend", "model_id", "manual_override", "route_origin", "chain", "current", "supply_state"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 10 },
- "backend": { "enum": ["claude", "codex", "opencode"] },
+ "contract_version": { "const": 11 },
+ "backend": { "enum": ["claude", "codex", "opencode", "avibe"] },
"model_id": { "type": "string" },
"manual_override": {
"description": "Normalized nonempty manual override, or null for inherited routing. Valid empty saved values and preview inputs normalize to null without a read-time write. Preview reports normalized draft intent. Nonempty equality with generated hops never determines intent; there is no empty-disable state.",
@@ -161,6 +161,10 @@
}
},
"allOf": [
+ {
+ "if": { "properties": { "backend": { "const": "avibe" } }, "required": ["backend"] },
+ "then": { "properties": { "chain": { "items": { "properties": { "channel": { "const": "hub" } } } } } }
+ },
{
"if": { "properties": { "manual_override": { "type": "object" } }, "required": ["manual_override"] },
"then": { "properties": { "chain": { "minItems": 1 }, "route_origin": { "const": "manual" } } }
@@ -233,7 +237,7 @@
],
"examples": [
{
- "contract_version": 10,
+ "contract_version": 11,
"backend": "codex",
"model_id": "unlisted-model",
"manual_override": null,
@@ -243,7 +247,7 @@
"supply_state": "ok"
},
{
- "contract_version": 10,
+ "contract_version": 11,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -253,7 +257,7 @@
"supply_state": "ok"
},
{
- "contract_version": 10,
+ "contract_version": 11,
"backend": "claude",
"model_id": "claude-opus-4-6",
"manual_override": null,
@@ -263,7 +267,7 @@
"supply_state": "waiting"
},
{
- "contract_version": 10,
+ "contract_version": 11,
"backend": "opencode",
"model_id": "glm-5.2",
"manual_override": { "hops": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2" }] },
@@ -273,7 +277,7 @@
"supply_state": "waiting"
},
{
- "contract_version": 10,
+ "contract_version": 11,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -283,7 +287,7 @@
"supply_state": "interrupted"
},
{
- "contract_version": 10,
+ "contract_version": 11,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -293,7 +297,7 @@
"supply_state": "interrupted"
},
{
- "contract_version": 10,
+ "contract_version": 11,
"backend": "claude",
"model_id": "claude-haiku-4-5",
"manual_override": null,
diff --git a/docs/plans/model-hub-contracts/agent-supply.schema.json b/docs/plans/model-hub-contracts/agent-supply.schema.json
index 9cbcda95e..f54bdd37c 100644
--- a/docs/plans/model-hub-contracts/agent-supply.schema.json
+++ b/docs/plans/model-hub-contracts/agent-supply.schema.json
@@ -7,7 +7,7 @@
"required": ["backend", "mode", "menu_kind"],
"additionalProperties": false,
"properties": {
- "backend": { "enum": ["claude", "codex", "opencode"] },
+ "backend": { "enum": ["claude", "codex", "opencode", "avibe"] },
"cli_present": {
"type": "boolean",
"description": "Server-authoritative fact that this backend's configured CLI executable is present on the Avibe host. It does not prove login, process readiness, or Source health. OPTIONAL in the reusable schema and REQUIRED on AgentSupply API payloads."
@@ -353,9 +353,13 @@
"then": { "properties": { "menu_kind": { "const": "open" } } }
},
{
- "if": { "properties": { "backend": { "enum": ["claude", "codex"] } }, "required": ["backend"] },
+ "if": { "properties": { "backend": { "enum": ["claude", "codex", "avibe"] } }, "required": ["backend"] },
"then": { "properties": { "menu_kind": { "const": "fixed" } } }
},
+ {
+ "if": { "properties": { "backend": { "const": "avibe" } }, "required": ["backend"] },
+ "then": { "properties": { "mode": { "const": "hub" }, "cli_present": { "const": false } } }
+ },
{
"$comment": "BackendModel has no discriminator, so the containing catalog owns native_protocol presence.",
"if": { "properties": { "backend": { "const": "opencode" } }, "required": ["backend"] },
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 0daf55dcb..8d0d23da8 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -56,7 +56,7 @@
"required": ["ok", "contract_version", "probe"],
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"probe": {"$ref": "model-hub/source-probe-result.schema.json"}
}
},
@@ -114,7 +114,7 @@
"required": ["backend", "menu_model", "source_id", "model_id", "position"],
"additionalProperties": false,
"properties": {
- "backend": {"enum": ["claude", "codex", "opencode"]},
+ "backend": {"enum": ["claude", "codex", "opencode", "avibe"]},
"menu_model": {"type": "string", "minLength": 1},
"source_id": {"type": "string", "pattern": "^src_[a-z0-9]{8,}$"},
"model_id": {"type": "string", "minLength": 1},
@@ -126,7 +126,7 @@
"required": ["backend", "menu_model"],
"additionalProperties": false,
"properties": {
- "backend": {"enum": ["claude", "codex", "opencode"]},
+ "backend": {"enum": ["claude", "codex", "opencode", "avibe"]},
"menu_model": {"type": "string", "minLength": 1}
}
},
@@ -135,7 +135,7 @@
"required": ["backend", "menu_model", "source_id", "model_id", "position"],
"additionalProperties": false,
"properties": {
- "backend": {"enum": ["claude", "codex", "opencode"]},
+ "backend": {"enum": ["claude", "codex", "opencode", "avibe"]},
"menu_model": {"type": "string", "minLength": 1},
"source_id": {"type": "string", "pattern": "^src_[a-z0-9]{8,}$"},
"model_id": {"type": "string", "minLength": 1},
@@ -147,7 +147,7 @@
"required": ["backend", "model_id", "agents"],
"additionalProperties": false,
"properties": {
- "backend": {"enum": ["claude", "codex", "opencode"]},
+ "backend": {"enum": ["claude", "codex", "opencode", "avibe"]},
"model_id": {"type": "string", "minLength": 1},
"agents": {"type": "array", "items": {"type": "string", "minLength": 1}, "uniqueItems": true}
}
@@ -155,7 +155,7 @@
"SuccessCore": {
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10}
+ "contract_version": {"const": 11}
}
},
"SourceListResponse": {
@@ -164,7 +164,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}
}
},
@@ -174,7 +174,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"observation": {"$ref": "model-hub/observation-result.schema.json"}
}
},
@@ -184,7 +184,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"source": {"$ref": "#/definitions/SourceApi"},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},
"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}
@@ -196,7 +196,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"source": {"$ref": "#/definitions/SourceApi"}
}
},
@@ -206,7 +206,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"source": {"$ref": "#/definitions/SourceApi"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -218,7 +218,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
}
@@ -229,7 +229,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}
}
},
@@ -239,7 +239,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"agent": {"$ref": "#/definitions/AgentSupplyApi"}
}
},
@@ -256,7 +256,7 @@
],
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"agent": {"$ref": "#/definitions/AgentSupplyApi"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}
@@ -281,7 +281,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": false},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"error": {"const": "candidate_suppliers_changed"},
"detail": {"type": "string", "minLength": 1},
"changed": {
@@ -301,12 +301,16 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"agent": {
"type": "object",
"required": ["backend", "mode", "catalog_models"],
"additionalProperties": false,
"allOf": [
+ {
+ "if": { "properties": { "backend": { "const": "avibe" } }, "required": ["backend"] },
+ "then": { "properties": { "mode": { "const": "hub" } } }
+ },
{
"if": { "properties": { "backend": { "const": "opencode" } }, "required": ["backend"] },
"then": {
@@ -336,7 +340,7 @@
}
],
"properties": {
- "backend": {"enum": ["claude", "codex", "opencode"]},
+ "backend": {"enum": ["claude", "codex", "opencode", "avibe"]},
"mode": {"enum": ["hub", "direct"]},
"catalog_models": {
"type": "array",
@@ -398,7 +402,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"candidates": {
"type": "object",
"required": ["builtin", "providers", "in_list"],
@@ -417,7 +421,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"matches": {
"type": "array",
"maxItems": 8,
@@ -451,7 +455,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"chain": {"$ref": "model-hub/agent-chain.schema.json"}
}
},
@@ -461,7 +465,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}
}
},
@@ -471,7 +475,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"chain": {"$ref": "model-hub/agent-chain.schema.json"},
"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},
"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}
@@ -483,7 +487,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"probe": {"$ref": "model-hub/probe-result.schema.json"}
}
},
@@ -493,7 +497,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}
}
},
@@ -503,7 +507,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"usage": {"$ref": "model-hub/usage-summary.schema.json"}
}
},
@@ -513,7 +517,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"quota": {"$ref": "model-hub/quota-summary.schema.json"}
}
},
@@ -523,7 +527,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -545,7 +549,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -568,7 +572,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"flow": {
"allOf": [
{"$ref": "model-hub/oauth-flow.schema.json"},
@@ -593,7 +597,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10}
+ "contract_version": {"const": 11}
}
},
"RuntimeApi": {
@@ -615,7 +619,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"scan": {"$ref": "model-hub/migration-scan.schema.json"}
}
},
@@ -625,7 +629,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"applied": {"type": "integer", "minimum": 0},
"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},
"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}
@@ -637,7 +641,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}
}
},
@@ -648,7 +652,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"provenance": {
"anyOf": [
{"$ref": "model-hub/turn-provenance.schema.json"},
@@ -663,7 +667,7 @@
"additionalProperties": false,
"properties": {
"ok": {"const": true},
- "contract_version": {"const": 10},
+ "contract_version": {"const": 11},
"runtime": {"$ref": "#/definitions/RuntimeApi"}
}
}
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 9fe4bbe66..997f32d7d 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -8,11 +8,11 @@ credential redaction and supply-impact confirmation rules still apply; unknown
API siblings retain the Owner default.
-Status: **Normative, `contract_version` 10** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.
+Status: **Normative, `contract_version` 11** — Model Hub implementations must conform, and the response conformance guard enumerates this route table and validates one real server response for every route.
-Success envelope: `{ok: true, contract_version: 10, ...}`.
+Success envelope: `{ok: true, contract_version: 11, ...}`.
Failure envelope:
-`{ok: false, contract_version: 10, error: <machine_code>, detail?: <i18n_key>}`.
+`{ok: false, contract_version: 11, error: <machine_code>, detail?: <i18n_key>}`.
`detail` is always a string. Structured error data lives in a named sibling.
Guarded mutation refusals specialize that envelope through
`guard-refusal.schema.json`; both report arrays are required and together form the plan
@@ -24,10 +24,17 @@ table. The contract guard requires the two endpoint sets to be identical, requir
exercised HTTP response for every registry entry, and validates that response against
the route's named schema.
-The shared envelope and every versioned nested contract carry `contract_version` 10, the
+The shared envelope and every versioned nested contract carry `contract_version` 11, the
terminal value. Supported persisted config shapes and historical TurnProvenance
remain readable; ephemeral envelopes use only the terminal version.
+The backend vocabulary includes `avibe`. It is always Hub mode, has no native CLI
+(`cli_present: false`), and accepts no `native_cli` Source. Its runtime consumer
+API and `x-avibe-served-hop` response header are specified in
+[`avibe-consumer.md`](avibe-consumer.md); these are not new management endpoints.
+The empty Avibe catalog added for older configurations does not hold the shared
+runtime open. Once models are configured it participates in the runtime Stop guard.
+
## Route table
| Method and path | Request → response | Normative notes |
@@ -71,10 +78,10 @@ remain readable; ephemeral envelopes use only the terminal version.
| POST `/api/models/migration/scan` | → `{scan: MigrationScan}` | Read-only. |
| POST `/api/models/migration/apply` | `{item_ids: string[]}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It validates selected items before withdrawal, upgrades an existing native Source in place when present, commits Source/Routes/backend mode atomically, and removes only replaced native material. Pre-exposure failure is reversible; post-exposure recovery is forward-only and keeps the backend blocked until terminalized. |
| GET `/api/models/turns/<turn_id>/provenance` | → `{provenance: TurnProvenance}` or documented absence error | Debug read for exactly attributed Hub turns. |
-| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 10 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
+| GET `/api/models/runtime/status` | → `{runtime: RuntimeDependency}` | Read-only managed engine status. The nested object carries `contract_version` 11 and persisted user intent in `enabled`; `not_started` is installed lazy-start idleness, not an alarm. |
| POST `/api/models/runtime/install` | → `{runtime: RuntimeDependency}` | Idempotently starts server-owned installation. It returns and persists `installing`; reload reads the same state. Uses the existing mutation authentication and CSRF guards. |
| POST `/api/models/runtime/start` | → `{runtime: RuntimeDependency}` | Persists `enabled: true` and explicitly starts the managed engine. Service startup restores this intent; runtime availability has no separate enable-confirmation step. Uses the existing mutation authentication and CSRF guards; status reads never start it. |
-| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any Agent backend is configured for Hub mode, so disabling the shared runtime cannot strand a configured route. |
+| POST `/api/models/runtime/stop` | → `{runtime: RuntimeDependency}` | Explicitly stops the managed engine, persists `enabled: false`, and returns it to `not_started`. The mutation is rejected with `runtime_in_use` while any native backend is configured for Hub mode or Avibe has catalog models, so disabling the shared runtime cannot strand a configured route. An empty Avibe catalog does not keep the runtime open. |
The removed product-global route `PUT /api/models/priority` has no replacement. Sources
PUT and compatibility chains/reorder share backend-default semantics and effective guards,
@@ -609,7 +616,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:
```json
{
"ok": true,
- "contract_version": 10,
+ "contract_version": 11,
"source": {
"id": "src_anthkey01",
"kind": "api_key",
@@ -719,7 +726,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c
```json
{
"ok": false,
- "contract_version": 10,
+ "contract_version": 11,
"error": "source_last_supplier",
"would_remove_hops": [],
"would_interrupt": [
@@ -855,7 +862,7 @@ API-key success:
```json
{
"ok": true,
- "contract_version": 10,
+ "contract_version": 11,
"source": {
"id": "src_relay9c1x",
"kind": "api_key",
@@ -946,7 +953,7 @@ Status and submit return the same terminal shape:
```json
{
"ok": true,
- "contract_version": 10,
+ "contract_version": 11,
"flow": {
"flow_id": "oaf_claude01",
"client_nonce": "ofn_01j5w8z7p4n6q2rt",
@@ -1019,9 +1026,9 @@ a valid `interrupted` chain.
```json
{
"ok": true,
- "contract_version": 10,
+ "contract_version": 11,
"chain": {
- "contract_version": 10,
+ "contract_version": 11,
"backend": "codex",
"model_id": "gpt-5.6",
"manual_override": null,
@@ -1048,7 +1055,7 @@ In Direct mode both chain and probe refuse with:
```json
{
"ok": false,
- "contract_version": 10,
+ "contract_version": 11,
"error": "direct_mode",
"detail": "models.hub.direct_mode"
}
@@ -1062,9 +1069,9 @@ A successful probe nests its result:
```json
{
"ok": true,
- "contract_version": 10,
+ "contract_version": 11,
"probe": {
- "contract_version": 10,
+ "contract_version": 11,
"backend": "claude",
"channel": "hub",
"reachable": false,
@@ -1087,7 +1094,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 10,
+ "contract_version": 11,
"backend": "codex",
"channel": "native_cli",
"reachable": true,
@@ -1100,7 +1107,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.
```json
{
- "contract_version": 10,
+ "contract_version": 11,
"backend": "codex",
"channel": "native_cli",
"reachable": false,
@@ -1116,7 +1123,7 @@ No candidate is an API error with a typed model-scoped state:
```json
{
"ok": false,
- "contract_version": 10,
+ "contract_version": 11,
"error": "probe_no_candidate",
"detail": "models.probe.no_candidate.waiting",
"supply": {
@@ -1297,7 +1304,7 @@ The store retains at most 500 exactly attributed settled turns with its existing
writes. Ambiguous attribution remains excluded; this is not a log of every upstream
request. Null means no matching retained record, including eviction. A newer served,
canceled or other record without a terminal error supersedes older error display.
-Success uses exactly `{ok: true, contract_version: 10, provenance: TurnProvenance | null}`;
+Success uses exactly `{ok: true, contract_version: 11, provenance: TurnProvenance | null}`;
there is no `success` field or envelope exception.
Local `engine_down` records may also contain `local_error_detail`, an OS-generated
@@ -1355,7 +1362,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 10,
+ "contract_version": 11,
"error": "provenance_unavailable",
"detail": "models.provenance.direct_mode"
}
@@ -1364,7 +1371,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:
```json
{
"ok": false,
- "contract_version": 10,
+ "contract_version": 11,
"error": "provenance_unavailable",
"detail": "models.provenance.attribution_ambiguous"
}
diff --git a/docs/plans/model-hub-contracts/avibe-boundary-matrix.json b/docs/plans/model-hub-contracts/avibe-boundary-matrix.json
new file mode 100644
index 000000000..d36e41c16
--- /dev/null
+++ b/docs/plans/model-hub-contracts/avibe-boundary-matrix.json
@@ -0,0 +1,83 @@
+{
+ "description": "C-6 backend/channel audit. Each backend discriminator declared by a schema has exactly one row; references inherit their named schema. Tests discover new discriminator sites and execute every listed refusal.",
+ "boundaries": [
+ {
+ "schema": "agent-supply.schema.json", "pointer": "", "backend": "backend",
+ "policy": "hub-only", "runtime": "ModelHubAgentSupplyConfig.from_payload; ModelHubService.set_agent_mode/list_agents",
+ "runtime_cases": ["mode", "source_order"],
+ "refusals": [
+ {"fixture": "supply", "path": ["mode"], "value": "direct"},
+ {"fixture": "supply", "path": ["cli_present"], "value": true}
+ ]
+ },
+ {
+ "schema": "agent-chain.schema.json", "pointer": "", "backend": "backend",
+ "policy": "hub-only", "runtime": "ModelHubConfig.from_payload; effective_model_route; inspect_exact_hop; ModelHubService.set_agent_chain",
+ "runtime_cases": ["route_write", "resolve", "resolve_hop"],
+ "refusals": [{"fixture": "chain", "path": ["chain", 0, "channel"], "value": "native_cli"}]
+ },
+ {
+ "schema": "probe-result.schema.json", "pointer": "", "backend": "backend",
+ "policy": "hub-only", "runtime": "ModelHubService.probe_agent -> inspected runnable hop",
+ "runtime_cases": ["probe"],
+ "refusals": [{"fixture": "probe", "path": ["backend"], "value": "avibe"}]
+ },
+ {
+ "schema": "turn-provenance.schema.json", "pointer": "", "backend": "agent",
+ "policy": "hub-only", "runtime": "ModelHubService._invoke_admitted/resolve_with_recovery; GatewayTurnTerminalizer; TurnCorrelationRegistry",
+ "runtime_cases": ["recovery", "native_attempt", "attempt_channel"],
+ "refusals": [
+ {"fixture": "exhausted", "path": ["failed_attempts", 0, "channel"], "value": "native_cli"},
+ {"fixture": "served", "path": ["served", "channel"], "value": "native_cli"},
+ {"fixture": "failed_terminal", "path": ["terminal_error", "channel"], "value": "native_cli"},
+ {"fixture": "canceled", "path": ["canceled_attempt", "channel"], "value": "native_cli"}
+ ],
+ "notes": "Null local terminal attribution and canceled-before-admission remain valid. Recovery uses the same hub-only admission and attempt slots; its live annotation carries no channel."
+ },
+ {
+ "schema": "api-response.schema.json", "pointer": "/definitions/AgentCatalogResponse/properties/agent", "backend": "backend",
+ "policy": "hub-only", "runtime": "ModelHubService.set_agent_models -> ModelHubAgentSupplyConfig",
+ "refusals": [{"fixture": "catalog", "path": ["mode"], "value": "direct"}]
+ },
+ {
+ "schema": "api-response.schema.json", "pointer": "/definitions/AddedTo", "backend": "backend",
+ "policy": "reference", "runtime": "ModelHubService Source adoption -> source_eligible_for_backend",
+ "notes": "References have no transport channel and cannot independently grant invocation."
+ },
+ {
+ "schema": "api-response.schema.json", "pointer": "/definitions/AdoptedBy", "backend": "backend",
+ "policy": "reference", "runtime": "ModelHubService Source adoption -> effective_model_route"
+ },
+ {
+ "schema": "api-response.schema.json", "pointer": "/definitions/RouteHopRef", "backend": "backend",
+ "policy": "reference", "runtime": "ModelHubService guard planning -> effective_model_route"
+ },
+ {
+ "schema": "api-response.schema.json", "pointer": "/definitions/SupplyGap", "backend": "backend",
+ "policy": "reference", "runtime": "ModelHubService guard planning -> inspect_exact_hop"
+ },
+ {
+ "schema": "guard-refusal.schema.json", "pointer": "/definitions/RouteHopRef", "backend": "backend",
+ "policy": "reference", "runtime": "ModelHubService guard planning -> effective_model_route"
+ },
+ {
+ "schema": "guard-refusal.schema.json", "pointer": "/definitions/SupplyGap", "backend": "backend",
+ "policy": "reference", "runtime": "ModelHubService guard planning -> inspect_exact_hop"
+ },
+ {
+ "schema": "source.schema.json", "pointer": "/properties/adopted_by/items", "backend": "backend",
+ "policy": "reference", "runtime": "ModelHubService Source adoption -> effective_model_route",
+ "notes": "Source.supply_channel is source-global, not the channel of a reference. Avibe references are created only through eligible Hub routes."
+ },
+ {
+ "schema": "resolution-event.schema.json", "pointer": "", "backend": "agent",
+ "policy": "reference", "runtime": "ModelHubService classified attempt events and router transitions",
+ "notes": "Events carry backend/reason, not a transport grant or channel; system remains source-scoped."
+ },
+ {
+ "schema": "migration-scan.schema.json", "pointer": "/properties/items/items", "backend": "backend",
+ "policy": "native-only", "runtime": "ModelHubService native migration scanner",
+ "refusals": [{"fixture": "migration", "path": ["backend"], "value": "avibe"}]
+ }
+ ]
+}
diff --git a/docs/plans/model-hub-contracts/avibe-consumer.md b/docs/plans/model-hub-contracts/avibe-consumer.md
new file mode 100644
index 000000000..9cdda37b1
--- /dev/null
+++ b/docs/plans/model-hub-contracts/avibe-consumer.md
@@ -0,0 +1,190 @@
+# Avibe Agent consumer
+
+Change contract for C-6, 2026-10-02. This is the Model Hub producer contract for
+the consumer requirements in docs PR #2333. Backend registration and the Agent
+adapter remain C-8 work.
+
+## Resolution
+
+`ModelHubRuntimeRouter.resolve_hop(requested_model, *, process_scope, turn_id=None)`
+returns the serialized `HopResolution` in `hop-resolution.schema.json`. It calls
+the existing `resolve("avibe", ...)`; `ModelHubLaunch.to_hop_resolution()` projects
+that launch. There is no second planner, credential store, or upstream client.
+
+The backend id is `avibe`. It has a fixed catalog (ordinary editable model rows),
+no native protocol pin, no native CLI, and no Direct mode. Its default catalog and
+source order are empty. Old configurations acquire only that empty Hub row;
+existing backend modes, model metadata, routes, source order, and runtime intent
+remain unchanged. An empty Avibe catalog does not prevent an explicit runtime Stop.
+
+The primary currently selected hop owns `protocol`, `provider` (the Source's vendor
+identity), and `source_id`. `base_url` is the loopback gateway's `/avibe/v1` API root;
+the consumer appends `messages`, `chat/completions`, or `responses` according to
+`protocol`. `runtime_model` is the exact prepared request model; the route credential
+retains the caller's catalog alias through remapping and failover. The token is
+in-memory only and excluded from the launch repr. `request_headers` is a required
+map (empty when unused) carrying any gateway correlation metadata; it is never
+omitted. The caller supplies a Session-specific process scope
+and the current Avibe turn id for durable turn provenance, then retires the scope
+through the existing router lifecycle when the consumer shuts down.
+
+Planning capabilities retain the requested catalog row's authority, including for
+aliases. Unknown `context_window`, `max_output_tokens`, `supports_tools`, and
+`supports_reasoning` remain null. A nonempty input modality list yields
+`supports_images = ("image" in input_modalities)`; an empty list yields null.
+All capability fields are required in the response, even when their value is
+unknown. There is currently no separate stored input cap, so `input_limit` is
+present with value null, never omitted.
+`reasoning_efforts` remains the configured list, or empty when reasoning is
+explicitly disabled. No upstream limit or capability is guessed from a model name,
+a different hop, or a native CLI default.
+
+The consumer resolves once per run and again after a retryable failure. Failover,
+recovery, Source health, and credentials remain owned by Model Hub.
+
+Candidate admission also preserves this capability authority: Source metadata
+first, then exact catalog metadata. Avibe never receives the native-backend
+protocol/model-family default reasoning ladder. An undeclared ladder is empty;
+undeclared boolean/numeric capabilities remain null.
+
+## Request origin and sequential retry
+
+The prepared route credential retains the immutable primary `(provider, api,
+model)` from launch, including untracked launches without a turn id. This origin
+travels as in-memory request metadata, never as upstream JSON or a caller-supplied
+header. Each revalidated Avibe attempt compares its admitted origin against that
+original primary, including fallback, credential refresh, and recovery walks.
+
+If any origin component differs, or the primary origin cannot be verified, the
+gateway strips opaque history **before engine invocation and protocol conversion**:
+
+- Block `signature`, `thoughtSignature`, `thought_signature`, and encrypted
+ reasoning payloads are removed, including protocol-owned tool-call extensions.
+- Anthropic `redacted_thinking` blocks and opaque-only reasoning items are dropped.
+- Visible thinking and Responses reasoning summaries become ordinary assistant
+ text; their text survives, but reasoning item identities do not.
+- Tool ids, arguments, results, and unrelated request options remain unchanged.
+ A tool argument named `signature` is user data, not protocol metadata.
+
+Same-origin fallback, even on another Source, retains the original history. Each
+attempt gets its own cleaned history; cleaning never mutates the original request
+that a later same-origin attempt might reuse. Native callers retain their existing
+history behavior.
+
+After a request completes, the consumer may resolve the **same catalog alias and
+turn** again to obtain a different primary hop. The existing turn keeps its attempt
+history and final successful served origin while replacing only its prepared
+launch snapshot. A prior response's remaining owned teardown is drained before
+replacement; an overlapping live request or a changed alias is refused with
+`409 mapping_target_unavailable` before a model call, without poisoning the first
+request's attribution. Retired route credentials may still route late continuations
+but cannot claim or invalidate the replacement's identity, even for malformed JSON.
+Native route-conflict and ambiguity rules are unchanged.
+
+## Hub-only boundary audit
+
+`avibe-boundary-matrix.json` is the executable audit table. It lists every schema
+that declares a backend discriminator, its runtime owner, and the refusal cases.
+Tests discover discriminator sites and run the listed schema/runtime refusals;
+adding a new shape without a policy fails the audit.
+
+| Boundary | Avibe invariant |
+| --- | --- |
+| Supply/config/catalog | Hub mode; no CLI presence, Direct mode, or native protocol pin |
+| Source order/manual route | Native Sources rejected by the shared eligibility owner |
+| Chain/probe | Only Hub channels; no native runnable candidate or native probe result |
+| Attempts/served/canceled | Only Hub channels at admission and provenance recording |
+| Terminal/local failures | Hub producer or null local attribution, never native CLI |
+| Recovery | Reuses the same Hub admission and attempt slots; live annotation adds no channel |
+| Guard/adoption/event references | Reference or diagnostic identity, not a separate transport grant |
+| Native migration scan | Avibe absent; released native shapes remain unchanged |
+
+## Response origin
+
+Every Avibe model response that the gateway serves carries the response header
+`x-avibe-served-hop`. Its value is compact ASCII-escaped JSON:
+
+```json
+{"provider":"openai","api":"openai_responses","model":"upstream-model"}
+```
+
+The exact object is `hop-origin.schema.json`. The provider and protocol are
+captured from the Source snapshot used at attempt admission, and the model is the
+configured upstream target of that attempt. The same immutable `HopOrigin` travels
+with `ResolvedInvocation` and the request's `AttemptIdentity`; successful settlement
+stores it as the required `TurnProvenance.served.origin` for Avibe. Historical and
+native records may omit origin; Avibe has no pre-v11 historical record.
+Failed/canceled attempts can also retain that snapshot, without implying success.
+For a turn making several model requests, each response header names its own
+request's hop; the turn-level `served` retains the last successful attempt under
+the existing settlement rules.
+
+Headers are committed after resolution reaches the engine's first-output barrier
+and before any response bytes. Avibe never takes the early Anthropic keepalive
+path, whose headers could otherwise leave before a fallback hop is known.
+Native CLI keepalive and HTTP-status behavior remain unchanged. Buffered and
+streaming Avibe responses use the same origin header, including tool-only answers.
+The header identifies the producer; a later stream error is still terminal and
+does not certify a successful response.
+Local errors before a serving hop exists have no origin header; they cannot
+claim an upstream producer.
+
+The exact header value is bounded to **4096 ASCII bytes**, including JSON syntax
+and escapes (excluding the header name and HTTP framing). Every Avibe hop is
+checked against this bound at invocation admission, including fallback and
+credential-refresh attempts. An oversized value is refused with HTTP `422` and
+machine error `served_hop_too_large`, before invoking that hop: no attempt, Source
+health penalty, or served-hop header is fabricated. Earlier failed attempts remain
+recorded. The gateway uses its existing localized generic error copy. Identifiers
+are never truncated; persisted config/history loading and native CLI/gateway
+consumers retain their existing identifier rules. Resolving a launch alone does
+not invoke a model and does not enforce this transport-only bound.
+
+Buffered and bodyless terminal upstream failures retain the admitted origin
+header as well. A bodyless upstream terminal response leaves resolution through
+`ModelHubError`, which carries the same immutable admitted origin. Both outcome
+carriers use one response-origin header policy. Local engine failures,
+pre-admission refusals, and local exhaustion responses carry no origin even when
+an earlier hop was attempted; the gateway never substitutes the last attempted
+hop or looks up current Source metadata to invent a producer.
+A local delivery failure after admission can report that known producer in the
+header without changing the existing engine-down provenance rule (which leaves
+Source attribution null rather than blaming the upstream for a local failure).
+
+Consumers parse this header before committing a response. The wire protocol stays
+the requested frontend protocol; `origin.api != requested protocol` explicitly
+identifies cross-protocol conversion. Consumers record the reported upstream
+origin, never the original primary hop. Missing or invalid origin follows C-2's
+unverified-origin rule (drop opaque signatures/redacted thinking).
+
+No management HTTP endpoint, persistent request lookup, or transcript copy is added.
+The header needs no upstream credentials and is never forwarded upstream.
+
+## Validation and delivery boundaries
+
+- Released-shape loading: old modes/routes/capabilities survive without mutation;
+ the new row is empty Hub, and native-cli Sources remain ineligible.
+- Real loopback gateway requests through the existing service, with hermetic engine
+ fixtures: primary protocol resolution, cross-protocol failover, non-ASCII origin,
+ slow Anthropic resolution, buffered/streamed bodies, and concurrent requests.
+- The same attempt's response header and persisted served origin agree, even if
+ Source metadata changes while the response is in flight.
+- One explicit mandatory-field table removes every promised resolution field,
+ capability field, and served identity/origin field from real produced values.
+ Native records from each supported persisted generation still load without an
+ origin. The terminal response table crosses result carrier, body availability,
+ upstream/local cause, primary/fallback hop, and native/Avibe backend.
+- Cross-origin histories are checked at engine admission across all three existing
+ frontends, same/different protocol fallback, recovery, and launch-time config
+ changes. Same-origin and native histories retain their payloads.
+- Candidate-to-catalog-to-launch tests protect unknown/explicit capabilities.
+ Real gateway retries, overlap refusal, and valid/malformed late credentials
+ protect sequential route replacement.
+- Contract authority/version closure, focused Python tests, and the existing UI
+ type/build checks run before push.
+
+Known by design: this first PR supports the three existing protocols. Google
+requires a second PR covering the runtime/engine frontend as well as vocabulary;
+adding only an enum would claim a transport that cannot serve requests. There are
+no new UI elements in this lane. C-8 owns enabling the Avibe backend card and its
+Hub-only presentation; `cli_present` truthfully remains false here.
diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.json
index 28ec82266..a9ce4ae08 100644
--- a/docs/plans/model-hub-contracts/guard-refusal.schema.json
+++ b/docs/plans/model-hub-contracts/guard-refusal.schema.json
@@ -61,7 +61,7 @@
],
"properties": {
"ok": { "const": false },
- "contract_version": { "const": 10 },
+ "contract_version": { "const": 11 },
"error": {
"enum": [
"source_last_supplier",
@@ -90,7 +90,7 @@
"required": ["backend", "menu_model", "source_id", "model_id", "position"],
"additionalProperties": false,
"properties": {
- "backend": { "enum": ["claude", "codex", "opencode"] },
+ "backend": { "enum": ["claude", "codex", "opencode", "avibe"] },
"menu_model": { "type": "string", "minLength": 1 },
"source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
"model_id": { "type": "string", "minLength": 1 },
@@ -102,7 +102,7 @@
"required": ["backend", "model_id", "agents"],
"additionalProperties": false,
"properties": {
- "backend": { "enum": ["claude", "codex", "opencode"] },
+ "backend": { "enum": ["claude", "codex", "opencode", "avibe"] },
"model_id": { "type": "string", "minLength": 1 },
"agents": {
"type": "array",
@@ -116,7 +116,7 @@
"examples": [
{
"ok": false,
- "contract_version": 10,
+ "contract_version": 11,
"error": "source_model_in_route_chain",
"detail": "modelHub.errors.source_model_in_route_chain",
"would_remove_hops": [
diff --git a/docs/plans/model-hub-contracts/hop-origin.schema.json b/docs/plans/model-hub-contracts/hop-origin.schema.json
new file mode 100644
index 000000000..8689986c3
--- /dev/null
+++ b/docs/plans/model-hub-contracts/hop-origin.schema.json
@@ -0,0 +1,14 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/hop-origin.schema.json",
+ "title": "HopOrigin",
+ "description": "Upstream identity captured at admission. Serialized in x-avibe-served-hop and the same provenance attempt's origin.",
+ "type": "object",
+ "required": ["provider", "api", "model"],
+ "additionalProperties": false,
+ "properties": {
+ "provider": { "type": "string", "minLength": 1 },
+ "api": { "$ref": "source.schema.json#/properties/protocol" },
+ "model": { "type": "string", "minLength": 1 }
+ }
+}
diff --git a/docs/plans/model-hub-contracts/hop-resolution.schema.json b/docs/plans/model-hub-contracts/hop-resolution.schema.json
new file mode 100644
index 000000000..fc938afd5
--- /dev/null
+++ b/docs/plans/model-hub-contracts/hop-resolution.schema.json
@@ -0,0 +1,34 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/hop-resolution.schema.json",
+ "title": "HopResolution",
+ "description": "C-6 runtime consumer projection of ModelHubLaunch. Unknown planning metadata remains null; credentials are in-memory only.",
+ "type": "object",
+ "required": ["backend", "requested_model", "protocol", "base_url", "token", "runtime_model", "source_id", "provider", "request_headers", "capabilities"],
+ "additionalProperties": false,
+ "properties": {
+ "backend": { "const": "avibe" },
+ "requested_model": { "type": "string" },
+ "protocol": { "$ref": "source.schema.json#/properties/protocol" },
+ "base_url": { "type": "string", "format": "uri" },
+ "token": { "type": "string" },
+ "runtime_model": { "type": "string" },
+ "source_id": { "type": "string" },
+ "provider": { "type": "string" },
+ "request_headers": { "type": "object", "additionalProperties": { "type": "string" } },
+ "capabilities": {
+ "type": "object",
+ "required": ["context_window", "input_limit", "max_output_tokens", "supports_tools", "supports_images", "supports_reasoning", "reasoning_efforts"],
+ "additionalProperties": false,
+ "properties": {
+ "context_window": { "type": ["integer", "null"], "minimum": 1 },
+ "input_limit": { "type": ["integer", "null"], "minimum": 1 },
+ "max_output_tokens": { "type": ["integer", "null"], "minimum": 1 },
+ "supports_tools": { "type": ["boolean", "null"] },
+ "supports_images": { "type": ["boolean", "null"] },
+ "supports_reasoning": { "type": ["boolean", "null"] },
+ "reasoning_efforts": { "type": "array", "items": { "type": "string" } }
+ }
+ }
+ }
+}
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.json
index c60dd94f3..b82b8e701 100644
--- a/docs/plans/model-hub-contracts/mirror-registry.json
+++ b/docs/plans/model-hub-contracts/mirror-registry.json
@@ -1,5 +1,5 @@
{
- "contract_version": 10,
+ "contract_version": 11,
"input_generation": {
"mode": "same_run_live_files",
"external_snapshot": "content_fingerprint_required"
@@ -14,7 +14,9 @@
"tests/test_model_hub*.py",
"tests/e2e/test_model_hub*.py",
"ui/src/components/settings/models/types.ts",
- "ui/src/components/settings/models/*.test.*"
+ "ui/src/components/settings/models/*.test.*",
+ "ui/e2e/**/*.ts",
+ "ui/e2e/**/*.tsx"
],
"required_literal_files": [
"core/handlers/model_hub/service.py",
diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.json
index 4fe8225c0..0888393b0 100644
--- a/docs/plans/model-hub-contracts/observation-result.schema.json
+++ b/docs/plans/model-hub-contracts/observation-result.schema.json
@@ -16,7 +16,7 @@
],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 10 },
+ "contract_version": { "const": 11 },
"outcome": {
"enum": [
"observed",
@@ -150,7 +150,7 @@
],
"examples": [
{
- "contract_version": 10,
+ "contract_version": 11,
"outcome": "observed",
"reachable": true,
"authenticated": "authenticated",
@@ -165,7 +165,7 @@
]
},
{
- "contract_version": 10,
+ "contract_version": 11,
"outcome": "authentication_failed",
"reachable": true,
"authenticated": "rejected",
@@ -175,7 +175,7 @@
"model_metadata": []
},
{
- "contract_version": 10,
+ "contract_version": 11,
"outcome": "ambiguous",
"reachable": true,
"authenticated": "unknown",
@@ -185,7 +185,7 @@
"model_metadata": []
},
{
- "contract_version": 10,
+ "contract_version": 11,
"outcome": "unreachable",
"reachable": false,
"authenticated": "unknown",
@@ -195,7 +195,7 @@
"model_metadata": []
},
{
- "contract_version": 10,
+ "contract_version": 11,
"outcome": "adapter_error",
"reachable": null,
"authenticated": "unknown",
@@ -205,7 +205,7 @@
"model_metadata": []
},
{
- "contract_version": 10,
+ "contract_version": 11,
"outcome": "timeout",
"reachable": null,
"authenticated": "unknown",
diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.json
index 1d7375dff..fb57b3762 100644
--- a/docs/plans/model-hub-contracts/probe-result.schema.json
+++ b/docs/plans/model-hub-contracts/probe-result.schema.json
@@ -7,8 +7,8 @@
"required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "error"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 10 },
- "backend": { "enum": ["claude", "codex", "opencode"] },
+ "contract_version": { "const": 11 },
+ "backend": { "enum": ["claude", "codex", "opencode", "avibe"] },
"channel": { "enum": ["hub", "native_cli"] },
"reachable": { "type": "boolean" },
"source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
@@ -32,6 +32,10 @@
}
},
"allOf": [
+ {
+ "if": { "properties": { "backend": { "const": "avibe" } }, "required": ["backend"] },
+ "then": { "properties": { "channel": { "const": "hub" } } }
+ },
{
"if": { "properties": { "channel": { "const": "hub" }, "reachable": { "const": true } }, "required": ["channel", "reachable"] },
"then": { "properties": { "latency_ms": { "type": "integer" }, "error": { "type": "null" } } }
@@ -62,10 +66,10 @@
}
],
"examples": [
- { "contract_version": 10, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
- { "contract_version": 10, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },
- { "contract_version": 10, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },
- { "contract_version": 10, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
- { "contract_version": 10, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }
+ { "contract_version": 11, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },
+ { "contract_version": 11, "backend": "claude", "channel": "hub", "reachable": false, "source_id": "src_relay9c1x", "model_id": "glm-5.2", "latency_ms": 287, "error": "models.source.needs_action.balance_exhausted" },
+ { "contract_version": 11, "backend": "codex", "channel": "hub", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.source.backoff.connection_failed" },
+ { "contract_version": 11, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },
+ { "contract_version": 11, "backend": "codex", "channel": "native_cli", "reachable": false, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": "models.probe.native_cli_unavailable" }
]
}
diff --git a/docs/plans/model-hub-contracts/resolution-event.schema.json b/docs/plans/model-hub-contracts/resolution-event.schema.json
index cd2ae4e77..e54d20ccf 100644
--- a/docs/plans/model-hub-contracts/resolution-event.schema.json
+++ b/docs/plans/model-hub-contracts/resolution-event.schema.json
@@ -10,7 +10,7 @@
"id": { "type": "string" },
"ts": { "type": "string", "format": "date-time" },
"agent": {
- "enum": ["claude", "codex", "opencode", "system"],
+ "enum": ["claude", "codex", "opencode", "avibe", "system"],
"description": "The discovering backend, or system for a source-scoped non-turn operation. system is never valid for backend-scoped supply_interrupted. Mirrors the backend vocabulary with the one declared extra system."
},
"kind": {
@@ -84,7 +84,7 @@
"then": {
"required": ["agent", "model_id", "severity"],
"properties": {
- "agent": { "enum": ["claude", "codex", "opencode"] },
+ "agent": { "enum": ["claude", "codex", "opencode", "avibe"] },
"model_id": { "type": "string" },
"severity": { "const": "action_required" },
"from_source": { "type": "null" },
diff --git a/docs/plans/model-hub-contracts/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
index b5c03e7cc..70ddc128c 100644
--- a/docs/plans/model-hub-contracts/runtime-dependency.schema.json
+++ b/docs/plans/model-hub-contracts/runtime-dependency.schema.json
@@ -7,7 +7,7 @@
"required": ["contract_version", "manifest", "status"],
"additionalProperties": false,
"properties": {
- "contract_version": { "const": 10 },
+ "contract_version": { "const": 11 },
"enabled": {
"type": "boolean",
"description": "Persisted user intent for the managed gateway. Fresh/default configuration is true; explicit stop persists false."
@@ -131,7 +131,7 @@
},
"examples": [
{
- "contract_version": 10,
+ "contract_version": 11,
"host_platform": "darwin-arm64",
"manifest": {
"name": "cliproxyapi",
diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.json
index 87b4f74aa..d58e99133 100644
--- a/docs/plans/model-hub-contracts/source.schema.json
+++ b/docs/plans/model-hub-contracts/source.schema.json
@@ -452,7 +452,7 @@
"additionalProperties": false,
"properties": {
"backend": {
- "enum": ["claude", "codex", "opencode"]
+ "enum": ["claude", "codex", "opencode", "avibe"]
},
"menu_model": {
"type": "string",
diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.json
index 826bf93bc..4849398f2 100644
--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json
+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json
@@ -36,7 +36,7 @@
"additionalProperties": false,
"properties": {
"contract_version": {
- "enum": [5, 6, 7, 8, 9, 10],
+ "enum": [5, 6, 7, 8, 9, 10, 11],
"$comment": "The only versioned object written to disk, so released versions form a set rather than a constant. Historical records validate after the existing persistence-read normalization of retired reasons; tests/fixtures/model_hub/released_v5_permission_denied.json exercises that boundary, not raw-file validation. Reading preserves the writer generation and requires no new route fields. New records carry the terminal member. Other versioned objects are ephemeral envelopes pinned to that value alone.",
"description": "Generation that wrote this record. Readers retain every supported released value, apply existing retired-reason normalization independently of version, and do not require route_origin or manual_override."
},
@@ -50,7 +50,7 @@
"description": "When the FSM settled the turn."
},
"agent": {
- "enum": ["claude", "codex", "opencode"],
+ "enum": ["claude", "codex", "opencode", "avibe"],
"description": "Backend identifier. Mirrors AgentSupply.backend exactly."
},
"requested_model_id": {
@@ -88,6 +88,7 @@
"channel": { "enum": ["native_cli", "hub"] },
"stripped_reasoning_efforts": { "$ref": "#/definitions/strippedReasoningEfforts" },
"declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" },
+ "origin": { "$ref": "hop-origin.schema.json" },
"http_status": {
"type": "integer",
"minimum": 100,
@@ -128,7 +129,8 @@
"configured_model_id": { "type": "string" },
"channel": { "enum": ["native_cli", "hub"] },
"stripped_reasoning_efforts": { "$ref": "#/definitions/strippedReasoningEfforts" },
- "declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" }
+ "declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" },
+ "origin": { "$ref": "hop-origin.schema.json" }
},
"dependencies": {
"stripped_reasoning_efforts": ["declared_reasoning_efforts"],
@@ -157,6 +159,7 @@
"channel": { "enum": ["native_cli", "hub", null] },
"stripped_reasoning_efforts": { "$ref": "#/definitions/strippedReasoningEfforts" },
"declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" },
+ "origin": { "$ref": "hop-origin.schema.json" },
"reason": {
"enum": [
"invalid_parameter",
@@ -257,7 +260,8 @@
"configured_model_id": { "type": "string" },
"channel": { "enum": ["native_cli", "hub"] },
"stripped_reasoning_efforts": { "$ref": "#/definitions/strippedReasoningEfforts" },
- "declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" }
+ "declared_reasoning_efforts": { "$ref": "#/definitions/declaredReasoningEfforts" },
+ "origin": { "$ref": "hop-origin.schema.json" }
},
"dependencies": {
"stripped_reasoning_efforts": ["declared_reasoning_efforts"],
@@ -297,6 +301,17 @@
}
},
"allOf": [
+ {
+ "if": { "properties": { "agent": { "const": "avibe" } }, "required": ["agent"] },
+ "then": {
+ "properties": {
+ "failed_attempts": { "items": { "properties": { "channel": { "const": "hub" } } } },
+ "served": { "required": ["origin"], "properties": { "channel": { "const": "hub" } } },
+ "terminal_error": { "properties": { "channel": { "enum": ["hub", null] } } },
+ "canceled_attempt": { "properties": { "channel": { "const": "hub" } } }
+ }
+ }
+ },
{
"if": {
"properties": { "outcome": { "const": "served" } },
@@ -404,7 +419,7 @@
],
"examples": [
{
- "contract_version": 10,
+ "contract_version": 11,
"turn_id": "turn_01k9x2m4",
"ts": "2026-07-29T06:32:11Z",
"agent": "claude",
@@ -429,7 +444,7 @@
"blockers": []
},
{
- "contract_version": 10,
+ "contract_version": 11,
"turn_id": "turn_01k9x33p",
"ts": "2026-07-29T06:41:02Z",
"agent": "opencode",
@@ -450,7 +465,7 @@
"blockers": []
},
{
- "contract_version": 10,
+ "contract_version": 11,
"turn_id": "turn_01k9x3zq",
"ts": "2026-07-29T06:48:20Z",
"agent": "codex",
@@ -470,7 +485,7 @@
]
},
{
- "contract_version": 10,
+ "contract_version": 11,
"turn_id": "turn_01k9x4b7",
"ts": "2026-07-29T07:02:44Z",
"agent": "claude",
@@ -490,7 +505,7 @@
"blockers": []
},
{
- "contract_version": 10,
+ "contract_version": 11,
"turn_id": "turn_modelmissing01",
"ts": "2026-09-05T17:31:10Z",
"agent": "claude",
@@ -512,7 +527,7 @@
"blockers": []
},
{
- "contract_version": 10,
+ "contract_version": 11,
"turn_id": "turn_01k9x5ca",
"ts": "2026-07-29T07:08:00Z",
"agent": "codex",
diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.py
index 9f6c03b0d..66a3418a6 100644
--- a/modules/agents/model_hub.py
+++ b/modules/agents/model_hub.py
@@ -14,7 +14,7 @@ from typing import Any, Callable, Literal, Mapping, Optional, cast
from config import paths
from config.atomic_io import write_atomic
-from config.v2_config import ModelHubConfig, ModelHubSourceConfig
+from config.v2_config import MODEL_HUB_BACKENDS, ModelHubConfig, ModelHubSourceConfig
from core.handlers.model_hub.classification import ResolutionDecision
from core.handlers.model_hub.events import (
EventAgent,
@@ -26,6 +26,7 @@ from core.handlers.model_hub.identifiers import (
)
from core.handlers.model_hub.provenance import (
ENGINE_DOWN_TURN_OUTCOME,
+ HopOrigin,
PreparedGatewayRoute,
TurnOutcomeProjectionInput,
exact_hop_blockers,
@@ -85,7 +86,7 @@ class ModelHubLaunch:
runtime_model: str
source_id: Optional[str] = None
gateway_base_url: Optional[str] = None
- gateway_token: Optional[str] = None
+ gateway_token: Optional[str] = field(default=None, repr=False)
gateway_request_metadata: dict[str, str] = field(default_factory=dict, repr=False)
context_window: Optional[int] = None
max_output_tokens: Optional[int] = None
@@ -93,6 +94,40 @@ class ModelHubLaunch:
supports_reasoning: Optional[bool] = None
reasoning_efforts: tuple[str, ...] = ()
settlement_generation: Optional[int] = field(default=None, repr=False)
+ protocol: Optional[str] = None
+ provider: Optional[str] = None
+ input_limit: Optional[int] = None
+ supports_images: Optional[bool] = None
+
+ def to_hop_resolution(self) -> dict[str, Any]:
+ """Project C-6 from the same launch that owns routing and credentials."""
+
+ if (
+ self.backend != "avibe" or self.channel != "hub"
+ or not self.protocol or not self.provider or not self.source_id
+ or not self.gateway_base_url or not self.gateway_token
+ ):
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ return {
+ "backend": self.backend,
+ "requested_model": self.requested_model,
+ "protocol": self.protocol,
+ "base_url": f"{self.gateway_base_url.rstrip('/')}/v1",
+ "token": self.gateway_token,
+ "runtime_model": self.runtime_model,
+ "source_id": self.source_id,
+ "provider": self.provider,
+ "request_headers": dict(self.gateway_request_metadata),
+ "capabilities": {
+ "context_window": self.context_window,
+ "input_limit": self.input_limit,
+ "max_output_tokens": self.max_output_tokens,
+ "supports_tools": self.supports_tools,
+ "supports_images": self.supports_images,
+ "supports_reasoning": self.supports_reasoning,
+ "reasoning_efforts": list(self.reasoning_efforts),
+ },
+ }
@property
def fingerprint(self) -> str:
@@ -191,8 +226,9 @@ def bind_persisted_launch(context: Any, payload: object) -> ModelHubLaunch | Non
source_id = payload.get("source_id")
target_model = payload.get("target_model")
if (
- backend not in {"claude", "codex", "opencode"}
+ backend not in MODEL_HUB_BACKENDS
or channel not in {"native_cli", "hub"}
+ or (backend == "avibe" and channel != "hub")
or not isinstance(source_id, str)
or not source_id
or not isinstance(target_model, str)
@@ -223,7 +259,7 @@ def claude_settings_for_launch(base_settings: str, launch: ModelHubLaunch | None
keeps the user's own Claude preferences while the Hub owns the connection.
"""
- if launch is None or launch.channel != "hub":
+ if launch is None or launch.backend == "avibe" or launch.channel != "hub":
return base_settings
settings = json.loads(base_settings)
connection_env = build_claude_hub_env({}, launch)
@@ -269,6 +305,8 @@ async def resolve_model_hub_launch(
)
_hold_unrunnable_input(context, failure)
raise failure from None
+ if backend == "avibe":
+ raise ModelHubError("engine_down", status=503, turn_outcome=ENGINE_DOWN_TURN_OUTCOME)
return ModelHubLaunch(
backend=backend,
channel="direct",
@@ -372,7 +410,7 @@ def build_claude_hub_env(
) -> dict[str, str]:
"""Return Claude environment overrides for the resolved Hub launch."""
- if launch.channel == "direct":
+ if launch.backend == "avibe" or launch.channel == "direct":
return dict(base_env)
if launch.channel == "hub":
if not launch.gateway_base_url or not launch.gateway_token:
@@ -422,7 +460,7 @@ def build_codex_hub_launch(
) -> tuple[list[str], dict[str, str] | None]:
"""Return app-server global overrides and environment for a Hub turn."""
- if launch.channel != "hub" or not launch.gateway_base_url or not launch.gateway_token:
+ if launch.backend == "avibe" or launch.channel != "hub" or not launch.gateway_base_url or not launch.gateway_token:
return list(base_args), None
if model_catalog_path is None:
raise ValueError("Codex Model Hub launches require a provider-safe model catalog")
@@ -518,6 +556,8 @@ class ModelHubRuntimeRouter:
*,
verified_oauth: bool = False,
) -> bool:
+ if backend == "avibe":
+ return False
runtime_config = getattr(load_config_or_default().agents, backend)
cli_path = str(getattr(runtime_config, "cli_path", "") or "").strip()
if (
@@ -675,6 +715,7 @@ class ModelHubRuntimeRouter:
source_id: Optional[str] = None,
via_mapping: bool = False,
gateway_request_model_id: Optional[str] = None,
+ primary_origin: HopOrigin | None = None,
) -> tuple[str, str]:
if self.turn_gateway is not None:
return await self.turn_gateway.endpoint(
@@ -687,6 +728,7 @@ class ModelHubRuntimeRouter:
via_mapping=via_mapping,
gateway_request_model_id=gateway_request_model_id,
request_scoped=backend == "codex",
+ **({"primary_origin": primary_origin} if primary_origin is not None else {}),
)
await self.service._ensure_engine_synced()
status = await self.service._engine_call(self.service.adapter.start())
@@ -941,6 +983,12 @@ class ModelHubRuntimeRouter:
) -> ModelHubLaunch:
requested_model = str(requested_model or "").strip()
config = self.service.store.load()
+ if backend == "avibe" and (
+ config.agents[backend].mode != "hub" or self.turn_gateway is None
+ ):
+ # An in-process consumer requires the routing gateway, including
+ # failover and served-hop attribution; the raw engine is not one.
+ raise ModelHubError("mapping_target_unavailable", status=409)
config, resolution = await self._resolve_turn(
config,
backend,
@@ -1035,6 +1083,10 @@ class ModelHubRuntimeRouter:
source_id=source.id,
via_mapping=False,
gateway_request_model_id=runtime_model,
+ primary_origin=(
+ HopOrigin(source.vendor, source.protocol, target_model)
+ if backend == "avibe" else None
+ ),
)
if self.turn_gateway is None:
prefix = await self._source_prefix(source.id)
@@ -1066,10 +1118,31 @@ class ModelHubRuntimeRouter:
supports_tools=supports_tools,
supports_reasoning=supports_reasoning,
reasoning_efforts=reasoning_efforts,
+ protocol=source.protocol,
+ provider=source.vendor,
+ supports_images=(
+ "image" in backend_model.input_modalities
+ if backend_model is not None and backend_model.input_modalities
+ else None
+ ),
)
self._emit_transition(launch, config)
return launch
+ async def resolve_hop(
+ self,
+ requested_model: str,
+ *,
+ process_scope: str,
+ turn_id: Optional[str] = None,
+ ) -> dict[str, Any]:
+ """Resolve the Avibe Agent endpoint without any native CLI overlay."""
+
+ launch = await self.resolve(
+ "avibe", requested_model, process_scope=process_scope, turn_id=turn_id,
+ )
+ return launch.to_hop_resolution()
+
async def resolve_opencode_overlay_launch(
self,
overlay: OpenCodeOverlay,
diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.py
index ce4f21cff..171306de1 100644
--- a/tests/e2e/test_model_hub_runtime.py
+++ b/tests/e2e/test_model_hub_runtime.py
@@ -57,11 +57,11 @@ def _seed_stopped_runtime(app: ModelHubTestApp) -> None:
"""Keep installation from inheriting the fresh-install runtime intent."""
script = """
-from config.v2_config import MODEL_HUB_BACKENDS, V2Config
+from config.v2_config import V2Config
config = V2Config.default()
config.model_hub.enabled = False
-for backend in MODEL_HUB_BACKENDS:
+for backend in ("claude", "codex", "opencode"):
config.model_hub.agents[backend].mode = "direct"
config.update.auto_update = False
config.update.check_interval_minutes = 0
@@ -684,7 +684,7 @@ def test_a1_feature_flag_disables_the_complete_models_api(
assert response.status == 404, (method, path, body)
assert body == {
"ok": False,
- "contract_version": 10,
+ "contract_version": 11,
"error": "feature_disabled",
}
diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.py
index dedc15da2..e39cba107 100644
--- a/tests/e2e/test_model_hub_sources.py
+++ b/tests/e2e/test_model_hub_sources.py
@@ -13,7 +13,7 @@ from tests.e2e.drivers.mock_llm_upstream import MockLLMUpstream
pytestmark = pytest.mark.e2e_model_hub
-CONTRACT_VERSION = 10
+CONTRACT_VERSION = 11
MENU_MODEL = "claude-sonnet-4-6"
SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"
diff --git a/tests/e2e/test_model_hub_usage_events.py b/tests/e2e/test_model_hub_usage_events.py
index 9c46fb398..e376ce07a 100644
--- a/tests/e2e/test_model_hub_usage_events.py
+++ b/tests/e2e/test_model_hub_usage_events.py
@@ -32,12 +32,12 @@ def usage_analytics_app(model_hub_app_factory):
"-c",
"""
from config.v2_config import (
- MODEL_HUB_BACKENDS, ModelHubModelConfig, ModelHubSourceConfig,
+ ModelHubModelConfig, ModelHubSourceConfig,
ModelHubSourceStateConfig, V2Config,
)
config = V2Config.default()
config.model_hub.enabled = False
-for backend in MODEL_HUB_BACKENDS:
+for backend in ("claude", "codex", "opencode"):
config.model_hub.agents[backend].mode = "direct"
config.model_hub.sources = [
ModelHubSourceConfig(
diff --git a/tests/fixtures/model_hub/released_pre_avibe_consumer.json b/tests/fixtures/model_hub/released_pre_avibe_consumer.json
new file mode 100644
index 000000000..0f3bc75ab
--- /dev/null
+++ b/tests/fixtures/model_hub/released_pre_avibe_consumer.json
@@ -0,0 +1,45 @@
+{
+ "enabled": false,
+ "runtime_default_applied": true,
+ "sources": [
+ {
+ "id": "src_released01",
+ "kind": "api_key",
+ "vendor": "custom",
+ "display_name": "Existing provider",
+ "protocol": "openai_chat",
+ "supply_channel": "hub",
+ "billing": "metered",
+ "state": { "status": "standby" },
+ "models": [{ "id": "模型/β", "origin": "manual", "reasoning_efforts": [] }],
+ "credential_ref": "cred_released01"
+ }
+ ],
+ "agents": {
+ "claude": {
+ "backend": "claude",
+ "mode": "direct",
+ "menu_kind": "fixed",
+ "sources": { "order": [] },
+ "routes": {},
+ "models": [{ "id": "custom-claude", "context_window": 100000 }]
+ },
+ "codex": {
+ "backend": "codex",
+ "mode": "hub",
+ "menu_kind": "fixed",
+ "sources": { "order": ["src_released01"] },
+ "routes": { "custom-codex": { "hops": [{ "source_id": "src_released01", "model_id": "模型/β" }] } },
+ "models": [{ "id": "custom-codex", "max_output_tokens": 4096, "supports_tools": false }]
+ },
+ "opencode": {
+ "backend": "opencode",
+ "mode": "direct",
+ "menu_kind": "open",
+ "sources": { "order": [] },
+ "routes": { "dormant": { "hops": [{ "source_id": "src_released01", "model_id": "模型/β" }] } },
+ "menu": { "view": "featured", "checked": [] },
+ "models": []
+ }
+ }
+}
diff --git a/tests/scenario_harness/auth_setup.py b/tests/scenario_harness/auth_setup.py
index 480663af7..1fac6cad0 100644
--- a/tests/scenario_harness/auth_setup.py
+++ b/tests/scenario_harness/auth_setup.py
@@ -10,8 +10,8 @@ def save_direct_auth_config(config: V2Config | None = None) -> V2Config:
config = V2Config.load()
except FileNotFoundError:
config = V2Config.default()
- for agent in config.model_hub.agents.values():
- agent.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ config.model_hub.agents[backend].mode = "direct"
config.save()
return config
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index fe76845e0..bf5b289a8 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -49,6 +49,7 @@ capabilities:
unit_or_contract_tests:
- tests/test_model_hub_api.py
- tests/test_model_hub_admission.py
+ - tests/test_model_hub_avibe_consumer.py
- tests/test_model_hub_config.py
- tests/test_model_hub_legacy_opencode_migration.py
- tests/test_model_hub_persisted_migration.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index e08b604cb..5c02a0c1d 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -4,6 +4,7 @@ capability:
name: Model Hub configured routes and turn outcomes
canonical_tests:
- tests/test_model_hub_api.py
+ - tests/test_model_hub_avibe_consumer.py
- tests/test_model_hub_config.py
- tests/test_model_hub_legacy_opencode_migration.py
- tests/test_member_management_parity.py
@@ -110,6 +111,61 @@ status_legend:
expected_fail: false
priority: false
scenarios:
+ - id: MH-AVIBE-001
+ name: Avibe resolves the primary native protocol and nullable alias capabilities without a CLI overlay
+ status: covered
+ kind: compatibility
+ layer: contract
+ test: tests/test_model_hub_avibe_consumer.py::test_hop_resolution_uses_primary_protocol_and_alias_capabilities
+ - id: MH-AVIBE-002
+ name: Avibe receives the actual served hop before consuming a cross-protocol fallback response
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_model_hub_avibe_consumer.py::test_failover_origin_is_available_before_body_and_matches_served_attempt
+ related_tests:
+ - tests/test_model_hub_avibe_consumer.py::test_terminal_response_origin_follows_its_carrier
+ - tests/test_model_hub_avibe_consumer.py::test_origin_header_limit_is_checked_before_each_avibe_hop
+ - tests/test_model_hub_avibe_consumer.py::test_served_hop_transport_bound_does_not_restrict_native_clients
+ - tests/test_model_hub_avibe_consumer.py::test_slow_anthropic_resolution_waits_to_publish_origin_and_keeps_source_snapshot
+ - tests/test_model_hub_avibe_consumer.py::test_concurrent_responses_keep_their_own_origin
+ - id: MH-AVIBE-003
+ name: Released three-backend configs gain only an empty Avibe Hub row without changing existing routes
+ status: covered
+ kind: compatibility
+ layer: contract
+ test: tests/test_model_hub_avibe_consumer.py::test_released_config_adds_only_empty_avibe_supply
+ - id: MH-AVIBE-004
+ name: Avibe refuses native CLI sources and Direct mode
+ status: covered
+ kind: validation
+ layer: contract
+ test: tests/test_model_hub_avibe_consumer.py::test_native_cli_and_direct_are_not_avibe_channels
+ related_tests:
+ - tests/test_model_hub_avibe_consumer.py::test_avibe_candidate_capabilities_survive_catalog_admission_without_guesses
+ - tests/test_model_hub_avibe_contract_matrix.py::test_avibe_matrix_covers_every_declared_backend_shape
+ - tests/test_model_hub_avibe_contract_matrix.py::test_avibe_channel_matrix_rejects_impossible_shapes_without_changing_native
+ - tests/test_model_hub_avibe_contract_matrix.py::test_avibe_runtime_matrix_refuses_native_admission
+ - tests/test_model_hub_api.py::test_runtime_stop_protects_configured_avibe_models
+ - tests/test_model_hub_api.py::test_runtime_stop_returns_explicit_not_started_state
+ - id: MH-AVIBE-005
+ name: Avibe failover strips opaque history only for a different or unverified origin
+ status: covered
+ kind: compatibility
+ layer: contract
+ test: tests/test_model_hub_avibe_consumer.py::test_failover_strips_opaque_history_only_when_origin_changes
+ related_tests:
+ - tests/test_model_hub_avibe_consumer.py::test_opaque_history_uses_launch_snapshot_without_requiring_turn_attribution
+ - tests/test_model_hub_avibe_consumer.py::test_opaque_history_origin_survives_recovery_walks
+ - tests/test_model_hub_avibe_consumer.py::test_native_history_is_not_scrubbed_by_avibe_origin_policy
+ - id: MH-AVIBE-006
+ name: Sequential Avibe retries replace a completed route without losing turn provenance
+ status: covered
+ kind: recovery
+ layer: contract
+ test: tests/test_model_hub_avibe_consumer.py::test_sequential_avibe_retry_replaces_route_and_retains_served_provenance
+ related_tests:
+ - tests/test_model_hub_avibe_consumer.py::test_avibe_route_replacement_refuses_overlap_without_poisoning_current_request
- id: MH-CODEX-ROUTING-001
name: Shared Codex authentication stays stable while concurrent aliases route and settle independently
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
index fd9c664df..5a640ffdf 100644
--- a/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_live_resolution_scenarios.py
@@ -231,7 +231,8 @@ def _config(*sources: ModelHubSourceConfig) -> ModelHubConfig:
for backend in ("claude", "codex", "opencode")
},
)
- for backend, agent in config.agents.items():
+ for backend in ("claude", "codex", "opencode"):
+ agent = config.agents[backend]
eligible_sources = tuple(
source
for source in sources
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index a22b64cf4..07e1f359a 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -38,8 +38,8 @@ class _IsolatedClaudeConfigDirMixin:
from config.v2_config import V2Config
config = V2Config.default()
- for supply in config.model_hub.agents.values():
- supply.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ config.model_hub.agents[backend].mode = "direct"
config.save()
def tearDown(self):
diff --git a/tests/test_backend_connection.py b/tests/test_backend_connection.py
index f5d4d0a8f..279652f55 100644
--- a/tests/test_backend_connection.py
+++ b/tests/test_backend_connection.py
@@ -61,8 +61,8 @@ def connection(monkeypatch, tmp_path):
config.agents.claude.enabled = True
config.agents.codex.enabled = True
config.agents.opencode.enabled = True
- for supply in config.model_hub.agents.values():
- supply.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ config.model_hub.agents[backend].mode = "direct"
config.save()
monkeypatch.setattr(api, "load_config", lambda: config)
monkeypatch.setattr(api, "resolve_cli_path", lambda _: str(tmp_path / "助手 cli"))
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index d0706b91d..862aaef55 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -6328,6 +6328,7 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
"OPENAI_API_KEY": "native-token",
}
launch = SimpleNamespace(
+ backend="codex",
channel="hub",
gateway_base_url="http://127.0.0.1:18443",
gateway_token="gateway-token",
@@ -6495,6 +6496,7 @@ class CodexTransportCwdStalenessTests(unittest.IsolatedAsyncioTestCase):
return_value=SimpleNamespace(blocks_transport_replacement=True)
)
launch = SimpleNamespace(
+ backend="codex",
channel="hub",
fingerprint="hub:replacement",
gateway_base_url="http://127.0.0.1:8317",
diff --git a/tests/test_codex_catalog_retention.py b/tests/test_codex_catalog_retention.py
index 0e86a6d6e..f7e2aa332 100644
--- a/tests/test_codex_catalog_retention.py
+++ b/tests/test_codex_catalog_retention.py
@@ -319,7 +319,7 @@ async def test_agent_launch_keeps_pin_across_invalidation_and_reuses_transport(m
# An extra argument must not override the path whose lifetime we protect.
value.codex_config.extra_args = ["-c", 'model_catalog_json="/obsolete/catalog.json"']
launch = SimpleNamespace(
- channel="hub", fingerprint="hub:test",
+ backend="codex", channel="hub", fingerprint="hub:test",
gateway_base_url="http://127.0.0.1:1", gateway_token="fixture-only",
)
starting = asyncio.create_task(value._get_or_create_transport(str(tmp_path), launch))
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index b0e325402..0e07840ae 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -817,8 +817,8 @@ def test_every_model_hub_endpoint_returns_its_contract_response(
client, base_url = _remote_model_hub_client(isolated_home, role=role, kind=kind)
service = _seed_response_conformance_service(tmp_path)
if endpoint == "POST /api/models/runtime/stop":
- for agent in service.store.config.agents.values():
- agent.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ service.store.config.agents[backend].mode = "direct"
admitted = access not in {"organization-editor", "organization-viewer"} or (
access == "organization-editor"
and endpoint == "GET /api/models/agents/<backend>/models"
@@ -1025,12 +1025,12 @@ def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):
assert adapter.start_calls == 1
assert store.config.enabled is True
assert runtime["enabled"] is True
- assert runtime["contract_version"] == 10
+ assert runtime["contract_version"] == 11
assert runtime["status"]["health"] == "ok"
_assert_valid("runtime-dependency.schema.json", runtime)
-def test_runtime_stop_requires_every_backend_to_be_direct(tmp_path):
+def test_runtime_stop_requires_native_backends_to_be_direct(tmp_path):
service, _store, adapter = _service(tmp_path)
with pytest.raises(ModelHubError) as exc_info:
@@ -1042,11 +1042,27 @@ def test_runtime_stop_requires_every_backend_to_be_direct(tmp_path):
assert adapter.stop_runtime_calls == 0
+def test_runtime_stop_protects_configured_avibe_models(tmp_path):
+ # The new empty Hub row must not strand old installations in the runtime,
+ # but adding a consumer model makes its engine dependency real.
+ service, store, adapter = _service(tmp_path)
+ for backend in ("claude", "codex", "opencode"):
+ store.config.agents[backend].mode = "direct"
+ store.config.agents["avibe"].models = [ModelHubBackendModelConfig(id="agent-model")]
+
+ with pytest.raises(ModelHubError) as exc_info:
+ asyncio.run(service.runtime_stop())
+
+ assert exc_info.value.code == "runtime_in_use"
+ assert exc_info.value.data == {"backends": ["avibe"]}
+ assert adapter.stop_runtime_calls == 0
+
+
def test_runtime_stop_returns_explicit_not_started_state(tmp_path):
service, store, adapter = _service(tmp_path)
store.config.enabled = True
- for agent in store.config.agents.values():
- agent.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ store.config.agents[backend].mode = "direct"
runtime = asyncio.run(service.runtime_stop())
@@ -1124,8 +1140,8 @@ def test_runtime_recovery_does_not_wait_for_the_engine_download(tmp_path, ending
if ending == "runtime_stop":
# An explicit stop is served during the download, and the resume
# then honors it instead of starting the engine.
- for agent in store.config.agents.values():
- agent.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ store.config.agents[backend].mode = "direct"
payload = await asyncio.wait_for(service.runtime_stop(), 1)
assert payload["enabled"] is False
adapter.release.set()
@@ -1316,7 +1332,7 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 10, "status": {"health": "ok"}}
+ return {"contract_version": 11, "status": {"health": "ok"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1333,7 +1349,7 @@ def test_runtime_stop_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 10, "status": {"health": "not_started"}}
+ return {"contract_version": 11, "status": {"health": "not_started"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1350,7 +1366,7 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):
async def rpc(operation, payload=None):
calls.append((operation, payload))
- return {"contract_version": 10, "status": {"health": "installing"}}
+ return {"contract_version": 11, "status": {"health": "installing"}}
monkeypatch.setattr(model_hub_client, "_rpc", rpc)
@@ -1368,7 +1384,7 @@ def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypat
def rpc(operation, payload=None):
calls.append((operation, payload))
return {
- "contract_version": 10,
+ "contract_version": 11,
"changed": True,
"status": {"health": "not_started", "verified": True},
}
@@ -1505,8 +1521,8 @@ def test_runtime_stop_is_allowlisted_by_controller_rpc(tmp_path):
from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
service, store, adapter = _service(tmp_path)
- for agent in store.config.agents.values():
- agent.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ store.config.agents[backend].mode = "direct"
runtime = asyncio.run(dispatch_model_hub_rpc(service, "runtime_stop", {}))
@@ -4466,6 +4482,7 @@ def test_agents_endpoint_projects_cli_presence_from_runtime(tmp_path):
"claude": True,
"codex": True,
"opencode": False,
+ "avibe": False,
}
@@ -4784,7 +4801,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):
assert response.status_code == 200
assert response.get_json() == {
"ok": True,
- "contract_version": 10,
+ "contract_version": 11,
"agent": {
"backend": "codex",
"mode": "hub",
@@ -4855,6 +4872,7 @@ def test_agents_endpoint_projects_each_enabled_named_agent_live(tmp_path):
"claude": [("pm", "claude-sonnet-4-6"), ("reviewer", "claude-opus-4-6")],
"codex": [("codex", "gpt-5.3-codex")],
"opencode": [],
+ "avibe": [],
}[backend]
store.config.agents["claude"].routes["claude-sonnet-4-6"] = ModelHubRouteConfig(
hops=[
@@ -5323,8 +5341,8 @@ def test_runtime_start_recomputes_text_only_marks_from_the_current_catalog_copy(
# The copy refreshes while the engine keeps its projection; a stop and a
# start later, the model is known to accept images.
_cache_models_dev({"deepseek": {_PROJECTION_MODEL: {"modalities": {"input": ["text", "image"]}}}})
- for agent in store.config.agents.values():
- agent.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ store.config.agents[backend].mode = "direct"
asyncio.run(service.runtime_stop())
asyncio.run(service.runtime_start())
@@ -9602,14 +9620,14 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, t
assert accepted.status_code == 200
runtime = accepted.get_json()["runtime"]
assert adapter.start_calls == 1
- assert runtime["contract_version"] == 10
+ assert runtime["contract_version"] == 11
_assert_valid("runtime-dependency.schema.json", runtime)
def test_runtime_stop_route_requires_csrf_before_stopping_engine(monkeypatch, tmp_path):
service, store, adapter = _service(tmp_path)
- for agent in store.config.agents.values():
- agent.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ store.config.agents[backend].mode = "direct"
monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
client = app.test_client()
base_url = "http://127.0.0.1:15131"
diff --git a/tests/test_model_hub_avibe_consumer.py b/tests/test_model_hub_avibe_consumer.py
new file mode 100644
index 000000000..fe3bd076a
--- /dev/null
+++ b/tests/test_model_hub_avibe_consumer.py
@@ -0,0 +1,1027 @@
+"""C-6 at the existing config, launch and HTTP/provenance owning boundaries.
+
+Released fixtures previously fail backend admission. Existing CLI fixtures do not
+protect a native-protocol in-process consumer, nullable capabilities, or an origin
+header emitted before a slow stream and tied to the actual fallback attempt.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import copy
+import json
+from dataclasses import replace
+from datetime import timedelta
+from pathlib import Path
+from types import SimpleNamespace
+
+import aiohttp
+import pytest
+from jsonschema import Draft7Validator, ValidationError
+from referencing import Registry, Resource
+
+from config.v2_config import (
+ ModelHubBackendModelConfig,
+ ModelHubConfig,
+ ModelHubRouteConfig,
+ ModelHubRouteHopConfig,
+)
+from core.handlers.model_hub.adapter import RawOutcomeKind
+from core.handlers.model_hub.provenance import BoundedProvenanceStore, HopOrigin, SERVED_HOP_HEADER
+from core.handlers.model_hub.request import ModelHubRequest
+from core.handlers.model_hub.service import ModelHubError
+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT
+from modules.agents.model_hub import (
+ ModelHubRuntimeRouter,
+ bind_persisted_launch,
+ build_claude_hub_env,
+ build_codex_hub_launch,
+ claude_settings_for_launch,
+ resolve_model_hub_launch,
+)
+from tests.test_model_hub_l3 import (
+ InvokeHandle,
+ LiveInvokeHandle,
+ NOW,
+ _canonicalize_fixed_test_routes,
+ _outcome,
+ _service,
+ _source,
+)
+
+
+CONTRACTS = Path(__file__).parents[1] / "docs/plans/model-hub-contracts"
+FIXTURES = Path(__file__).parent / "fixtures/model_hub"
+PROTOCOL_ENDPOINTS = {
+ "anthropic": "messages",
+ "openai_chat": "chat/completions",
+ "openai_responses": "responses",
+}
+# Consumer promises, deliberately independent of the producer schema. Positive
+# payload validation and the channel matrix cannot detect a missing requirement.
+MANDATORY_FIELDS = {
+ "hop-resolution.schema.json": {
+ (): (
+ "backend", "requested_model", "protocol", "base_url", "token",
+ "runtime_model", "source_id", "provider", "request_headers", "capabilities",
+ ),
+ ("capabilities",): (
+ "context_window", "input_limit", "max_output_tokens", "supports_tools",
+ "supports_images", "supports_reasoning", "reasoning_efforts",
+ ),
+ },
+ "turn-provenance.schema.json": {
+ (): (
+ "contract_version", "turn_id", "ts", "agent", "requested_model_id",
+ "outcome", "failed_attempts", "served", "terminal_error", "canceled_attempt",
+ "model_supply_state", "blockers",
+ ),
+ ("served",): ("source_id", "configured_model_id", "channel", "origin"),
+ ("served", "origin"): ("provider", "api", "model"),
+ },
+}
+
+
+def _validate(schema_name, value):
+ resources = {}
+ for path in CONTRACTS.glob("*.schema.json"):
+ payload = json.loads(path.read_text())
+ resources[payload.get("$id", path.name)] = Resource.from_contents(payload)
+ schema = json.loads((CONTRACTS / schema_name).read_text())
+ Draft7Validator(schema, registry=Registry().with_resources(resources.items())).validate(value)
+
+
+def _assert_mandatory_fields(schema_name, payload):
+ for path, fields in MANDATORY_FIELDS[schema_name].items():
+ for field in fields:
+ incomplete = copy.deepcopy(payload)
+ target = incomplete
+ for key in path:
+ target = target[key]
+ target.pop(field)
+ with pytest.raises(ValidationError) as missing:
+ _validate(schema_name, incomplete)
+ assert missing.value.validator == "required"
+ assert list(missing.value.absolute_path) == list(path)
+ assert missing.value.message == f"'{field}' is a required property"
+
+
+def _avibe_service(tmp_path, sources, *, handles=()):
+ service = _service(tmp_path, sources=sources, live_handles=list(handles))
+ _canonicalize_fixed_test_routes(service)
+ agent = service.store.config.agents["avibe"]
+ agent.models = [ModelHubBackendModelConfig(id="menu-alias")]
+ agent.sources.order = [source.id for source in sources if source.supply_channel == "hub"]
+ agent.routes["menu-alias"] = ModelHubRouteConfig(tuple(
+ ModelHubRouteHopConfig(source.id, source.models[0].id)
+ for source in sources if source.supply_channel == "hub"
+ ))
+ service.store.requested_models["avibe"] = "menu-alias"
+ return service
+
+
+def _body(protocol, stream):
+ if not stream:
+ return json.dumps({"id": "fixture-answer", "content": "answer"}).encode()
+ if protocol == "anthropic":
+ return (
+ b'event: message_start\ndata: {"type":"message_start","message":{"id":"msg_1","usage":'
+ b'{"input_tokens":2,"output_tokens":0}}}\n\n'
+ b'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,'
+ b'"delta":{"type":"text_delta","text":"answer"}}\n\n'
+ b'event: message_delta\ndata: {"type":"message_delta","delta":{"stop_reason":"end_turn"},'
+ b'"usage":{"output_tokens":1}}\n\n'
+ b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
+ )
+ if protocol == "openai_chat":
+ return (
+ b'data: {"choices":[{"index":0,"delta":{"content":"answer"},"finish_reason":null}]}\n\n'
+ b'data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n'
+ b'data: [DONE]\n\n'
+ )
+ return (
+ b'event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"answer"}\n\n'
+ b'event: response.completed\ndata: {"type":"response.completed","response":'
+ b'{"id":"resp_1","status":"completed","usage":{"input_tokens":2,"output_tokens":1}}}\n\n'
+ )
+
+
+def _signed_history(protocol):
+ """Wire-shaped histories and their explicit, non-opaque equivalents."""
+ if protocol == "anthropic":
+ call = {"type": "tool_use", "id": "call_1", "name": "verify", "input": {"signature": "user-data"}}
+ result = {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_1", "content": "ok"}]}
+ return (
+ {"messages": [{"role": "assistant", "content": [
+ {"type": "thinking", "thinking": "Visible reasoning", "signature": "opaque-thinking"},
+ {"type": "redacted_thinking", "data": "opaque-redacted"},
+ {"type": "text", "text": "Answer", "signature": "opaque-text"},
+ {**call, "thoughtSignature": "opaque-call"},
+ ]}, result, {"role": "assistant", "content": [{"type": "redacted_thinking", "data": "opaque-only"}]}]},
+ {"messages": [{"role": "assistant", "content": [
+ {"type": "text", "text": "Visible reasoning"}, {"type": "text", "text": "Answer"}, call,
+ ]}, result]},
+ )
+ if protocol == "openai_responses":
+ call = {"type": "function_call", "call_id": "call_1", "name": "verify", "arguments": '{"signature":"user-data"}'}
+ result = {"type": "function_call_output", "call_id": "call_1", "output": "ok"}
+ return (
+ {"input": [
+ {"type": "reasoning", "id": "rs_1", "encrypted_content": "opaque-reasoning",
+ "summary": [{"type": "summary_text", "text": "Visible reasoning"}]},
+ {"type": "reasoning", "id": "rs_hidden", "encrypted_content": "opaque-only", "summary": []},
+ {"type": "message", "role": "assistant", "content": [
+ {"type": "output_text", "text": "Answer", "signature": "opaque-text"},
+ ]},
+ {**call, "signature": "opaque-call"}, result,
+ ], "store": False},
+ {"input": [
+ {"role": "assistant", "content": [{"type": "output_text", "text": "Visible reasoning"}]},
+ {"type": "message", "role": "assistant", "content": [{"type": "output_text", "text": "Answer"}]},
+ call, result,
+ ], "store": False},
+ )
+ call = {"type": "function", "id": "call_1", "function": {"name": "verify", "arguments": '{"signature":"user-data"}'}}
+ result = {"role": "tool", "tool_call_id": "call_1", "content": "ok"}
+ return (
+ {"messages": [{"role": "assistant",
+ "content": [{"type": "text", "text": "Answer", "thoughtSignature": "opaque-text"}],
+ "tool_calls": [{**call, "extra_content": {"google": {"thought_signature": "opaque-call"}}}]},
+ result]},
+ {"messages": [{"role": "assistant", "content": [{"type": "text", "text": "Answer"}],
+ "tool_calls": [{**call, "extra_content": {"google": {}}}]}, result]},
+ )
+
+
[email protected]("protocol", PROTOCOL_ENDPOINTS)
[email protected]("change", ["same_origin", "provider", "api", "model"])
+async def test_failover_strips_opaque_history_only_when_origin_changes(tmp_path, protocol, change):
+ """MH-AVIBE-005: the engine must never receive primary-signed history at another origin.
+
+ Origin-report tests alone do not inspect the outgoing history at admission.
+ Source identity alone is not origin identity; preserve ordinary tool data.
+ """
+ primary = _source("src_primary01", "Primary", vendor="anthropic", protocol=protocol)
+ fallback_protocol = "anthropic" if protocol != "anthropic" else "openai_responses"
+ fallback = _source(
+ "src_fallback01", "Fallback",
+ vendor="custom" if change == "provider" else primary.vendor,
+ protocol=fallback_protocol if change == "api" else protocol,
+ model_id="another-model" if change == "model" else "shared-model",
+ )
+ service = _avibe_service(tmp_path, [primary, fallback], handles=[
+ InvokeHandle(_outcome(RawOutcomeKind.HTTP_ERROR, status=429, code="rate_limit_error")),
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=fallback.id), (b"{}",)),
+ ])
+ signed, plain = _signed_history(protocol)
+ original = copy.deepcopy(signed)
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:opaque", turn_id="turn-opaque")
+ common = {"model": hop["runtime_model"], "stream": False, "temperature": 0.25}
+ async with aiohttp.ClientSession() as client:
+ async with client.post(
+ f'{hop["base_url"]}/{PROTOCOL_ENDPOINTS[protocol]}',
+ headers={
+ "Authorization": f'Bearer {hop["token"]}',
+ "anthropic-beta": "fixture-beta",
+ "User-Agent": "fixture-agent",
+ },
+ json={**common, **signed},
+ ) as response:
+ assert response.status == 200
+ assert await response.read() == b"{}"
+ assert json.loads(response.headers[SERVED_HOP_HEADER]) == {
+ "provider": fallback.vendor, "api": fallback.protocol, "model": fallback.models[0].id,
+ }
+ assert [entry[0] for entry in service.adapter.invocations] == [primary.id, fallback.id]
+ assert service.adapter.requests[0] == {**common, **original}
+ assert service.adapter.requests[1] == {**common, **(original if change == "same_origin" else plain)}
+ assert all(request.protocol == protocol for request in service.adapter.requests)
+ assert all(request.headers == {
+ "anthropic-beta": "fixture-beta", "user-agent": "fixture-agent",
+ } for request in service.adapter.requests)
+ assert signed == original
+ finally:
+ await gateway.close()
+
+
[email protected]("turn_id", ["turn-snapshot", None])
[email protected]("origin_state", ["unchanged", "changed", "unverified"])
+async def test_opaque_history_uses_launch_snapshot_without_requiring_turn_attribution(tmp_path, turn_id, origin_state):
+ """MH-AVIBE-005: config reload and untracked calls cannot invent primary provenance.
+
+ A fallback-only case cannot catch snapshot recomputation at HTTP arrival or
+ loss of the route credential when no dispatched turn is being tracked.
+ """
+ primary = _source("src_primary01", "Primary", vendor="anthropic", protocol="anthropic")
+ service = _avibe_service(tmp_path, [primary], handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS), (b"{}",)),
+ ])
+ signed, plain = _signed_history("anthropic")
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ if origin_state == "unverified":
+ base, token = await gateway.endpoint("avibe", process_scope="avibe:unverified")
+ base_url, model = f"{base}/v1", "menu-alias"
+ else:
+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:snapshot", turn_id=turn_id)
+ base_url, model, token = hop["base_url"], hop["runtime_model"], hop["token"]
+ if origin_state == "changed":
+ service.store.config.sources[0].vendor = "custom"
+ async with aiohttp.ClientSession() as client:
+ async with client.post(
+ f"{base_url}/messages",
+ headers={"Authorization": f"Bearer {token}"},
+ json={"model": model, **signed},
+ ) as response:
+ assert response.status == 200
+ assert await response.read() == b"{}"
+ assert service.adapter.requests[0]["messages"] == (
+ signed if origin_state == "unchanged" else plain
+ )["messages"]
+ finally:
+ await gateway.close()
+
+
[email protected]("recovered_hop", ["primary", "fallback"])
+async def test_opaque_history_origin_survives_recovery_walks(tmp_path, recovered_hop):
+ """MH-AVIBE-005: retries keep the launch origin and never mutate signed input.
+
+ Single-walk failover misses both a fresh resolver walk trusting its new first
+ candidate and a destructive scrub leaking back into same-origin recovery.
+ """
+ primary = _source("src_primary01", "Primary", vendor="anthropic", protocol="anthropic")
+ fallback = _source("src_fallback01", "Fallback", vendor="custom", protocol="anthropic")
+ service = _avibe_service(tmp_path, [primary, fallback], handles=[
+ InvokeHandle(_outcome(RawOutcomeKind.HTTP_ERROR, status=503, source_id=primary.id)),
+ InvokeHandle(_outcome(RawOutcomeKind.HTTP_ERROR, status=503, source_id=fallback.id)),
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS), (b"{}",)),
+ ])
+ service.recovery.window_seconds = 120
+ clock = {"now": NOW}
+ service.now = lambda: clock["now"]
+ waits = []
+
+ async def advance(delay):
+ waits.append(delay)
+ clock["now"] += timedelta(seconds=delay)
+ if recovered_hop == "fallback":
+ service.store.config.agents["avibe"].routes["menu-alias"] = ModelHubRouteConfig((
+ ModelHubRouteHopConfig(fallback.id, "shared-model"),
+ ))
+
+ service.recovery.sleep = advance
+ signed, plain = _signed_history("anthropic")
+ gateway = ModelHubTurnGateway(service, now=lambda: clock["now"])
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:recovery", turn_id="turn-recovery")
+ async with aiohttp.ClientSession() as client:
+ async with client.post(
+ f'{hop["base_url"]}/messages',
+ headers={"Authorization": f'Bearer {hop["token"]}'},
+ json={"model": hop["runtime_model"], **signed},
+ ) as response:
+ assert response.status == 200
+ assert await response.read() == b"{}"
+ assert waits == [30.0]
+ assert [entry[0] for entry in service.adapter.invocations] == [
+ primary.id, fallback.id, primary.id if recovered_hop == "primary" else fallback.id,
+ ]
+ assert [request["messages"] for request in service.adapter.requests] == [
+ signed["messages"], plain["messages"],
+ (signed if recovered_hop == "primary" else plain)["messages"],
+ ]
+ finally:
+ await gateway.close()
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+async def test_native_history_is_not_scrubbed_by_avibe_origin_policy(tmp_path, backend):
+ """Native callers have no primary-origin metadata; their existing policy stays intact."""
+ protocol = {"claude": "anthropic", "codex": "openai_responses", "opencode": "openai_chat"}[backend]
+ primary = _source("src_primary01", "Primary", protocol=protocol)
+ fallback = _source("src_fallback01", "Fallback", vendor="custom", protocol=protocol)
+ service = _service(tmp_path, sources=[primary, fallback], outcomes=[
+ _outcome(RawOutcomeKind.HTTP_ERROR, status=429),
+ _outcome(RawOutcomeKind.SUCCESS),
+ ])
+ selected = _canonicalize_fixed_test_routes(service)
+ signed, _plain = _signed_history(protocol)
+ original = copy.deepcopy(signed)
+ await service.resolve(
+ backend=backend, model_id=selected.get(backend, "shared-model"),
+ request=ModelHubRequest(signed, protocol=protocol), stream=False,
+ )
+ assert [entry[0] for entry in service.adapter.invocations] == [primary.id, fallback.id]
+ assert service.adapter.requests == [original, original]
+
+
[email protected]("metadata", ["unknown", "source", "catalog"])
+async def test_avibe_candidate_capabilities_survive_catalog_admission_without_guesses(tmp_path, metadata):
+ """MH-AVIBE-001: candidate -> persisted catalog -> launch preserves authority.
+
+ Hand-populated launch fixtures never exercise the candidate model-family
+ default, which must not invent a reasoning ladder for a relay model.
+ """
+ source = _source("src_primary01", "Primary", protocol="openai_chat", model_id="claude-unknown")
+ if metadata == "source":
+ source.models[0].reasoning_efforts = ["high"]
+ service = _avibe_service(tmp_path, [source])
+ service.store.config.agents["avibe"].models = []
+ service.store.config.agents["avibe"].routes = {}
+ service.models_dev_catalog = lambda: (
+ {"fixture": {"models": {"claude-unknown": {
+ "reasoning": True, "reasoning_options": [{"type": "effort", "values": ["medium"]}],
+ }}}}
+ if metadata == "catalog" else {}
+ )
+ candidate, = service.agent_model_candidates("avibe")["providers"]
+ desired = {key: value for key, value in candidate.items() if key != "suppliers"}
+ await service.set_agent_models("avibe", [], [desired])
+ gateway = ModelHubTurnGateway(service)
+ try:
+ hop = await ModelHubRuntimeRouter(service=service, turn_gateway=gateway).resolve_hop(
+ "claude-unknown", process_scope="avibe:candidate", turn_id="turn-candidate",
+ )
+ assert hop["protocol"] == "openai_chat"
+ assert hop["capabilities"]["reasoning_efforts"] == {
+ "unknown": [], "source": ["high"], "catalog": ["medium"],
+ }[metadata]
+ assert hop["capabilities"]["supports_reasoning"] is (True if metadata == "catalog" else None)
+ assert hop["capabilities"]["input_limit"] is None
+ finally:
+ await gateway.close()
+
+
[email protected]("late_request", ["malformed", "valid"])
+async def test_sequential_avibe_retry_replaces_route_and_retains_served_provenance(tmp_path, late_request):
+ """MH-AVIBE-006: a retryable partial response can resolve a new hop in one turn.
+
+ One-request failover never re-prepares a route, so it misses the native
+ one-launch assumption marking an otherwise successful Avibe turn ambiguous.
+ """
+ primary = _source("src_primary01", "Primary", vendor="anthropic", protocol="anthropic")
+ fallback = _source("src_fallback01", "Fallback", model_id="next-model")
+ late = _source("src_late00001", "Late continuation", model_id="late-model")
+ partial = b'event: content_block_delta\ndata: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"partial"}}\n\n'
+ service = _avibe_service(tmp_path, [primary, fallback, late], handles=[
+ LiveInvokeHandle(_outcome(
+ RawOutcomeKind.HTTP_ERROR, status=429, code="rate_limit_error",
+ source_id=primary.id, stream_started=True,
+ ), (partial,)),
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=fallback.id), (b"{}",)),
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=late.id), (b"{}",)),
+ ])
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ turn_id = "turn-sequential"
+ try:
+ initial = await router.resolve_hop("menu-alias", process_scope="avibe:retry", turn_id=turn_id)
+ async with aiohttp.ClientSession() as client:
+ async with client.post(
+ f'{initial["base_url"]}/messages',
+ headers={"Authorization": f'Bearer {initial["token"]}'},
+ json={"model": initial["runtime_model"], "stream": True, "messages": []},
+ ) as response:
+ assert response.status == 200
+ assert b"partial" in await response.read()
+ retry = await router.resolve_hop("menu-alias", process_scope="avibe:retry", turn_id=turn_id)
+ assert retry["source_id"] == fallback.id
+ async with client.post(
+ f'{retry["base_url"]}/responses',
+ headers={"Authorization": f'Bearer {retry["token"]}'},
+ json={"model": retry["runtime_model"], "input": "retry"},
+ ) as response:
+ assert response.status == 200
+ await response.read()
+ origin = json.loads(response.headers[SERVED_HOP_HEADER])
+ # A late old credential must not arm/poison the retry's attribution,
+ # even if the request is invalid before the model is parsed.
+ service.store.config.agents["avibe"].routes["menu-alias"] = ModelHubRouteConfig((
+ ModelHubRouteHopConfig(late.id, "late-model"),
+ ))
+ async with client.post(
+ f'{initial["base_url"]}/messages',
+ headers={"Authorization": f'Bearer {initial["token"]}'},
+ **(
+ {"data": "invalid json"} if late_request == "malformed"
+ else {"json": {"model": initial["runtime_model"], "messages": []}}
+ ),
+ ) as response:
+ assert response.status == (400 if late_request == "malformed" else 200)
+ await response.read()
+ if late_request == "valid":
+ assert json.loads(response.headers[SERVED_HOP_HEADER])["model"] == "late-model"
+ completion = router.settle_turn(turn_id, settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat())
+ if completion:
+ await completion
+ record = service.provenance.get(turn_id)
+ assert record is not None
+ assert record["outcome"] == "served"
+ assert record["served"]["source_id"] == fallback.id
+ assert record["served"]["origin"] == origin
+ _validate("turn-provenance.schema.json", record)
+ finally:
+ await gateway.close()
+
+
+async def test_avibe_route_replacement_refuses_overlap_without_poisoning_current_request(tmp_path):
+ """MH-AVIBE-006: a new launch cannot take an in-flight request's turn identity."""
+ primary = _source("src_primary01", "Primary", vendor="anthropic", protocol="anthropic")
+ fallback = _source("src_fallback01", "Fallback", protocol="anthropic", model_id="next-model")
+ service = _avibe_service(tmp_path, [primary, fallback], handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)),
+ ])
+ entered, release = asyncio.Event(), asyncio.Event()
+ invoke = service.adapter.invoke
+
+ async def held(*args, **kwargs):
+ result = await invoke(*args, **kwargs)
+ entered.set()
+ await release.wait()
+ return result
+
+ service.adapter.invoke = held
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ turn_id = "turn-overlap"
+ try:
+ first = await router.resolve_hop("menu-alias", process_scope="avibe:overlap", turn_id=turn_id)
+ async with aiohttp.ClientSession() as client:
+ pending = asyncio.create_task(client.post(
+ f'{first["base_url"]}/messages',
+ headers={"Authorization": f'Bearer {first["token"]}'},
+ json={"model": first["runtime_model"], "messages": []},
+ ))
+ try:
+ await asyncio.wait_for(entered.wait(), 2)
+ service.store.config.agents["avibe"].routes["menu-alias"] = ModelHubRouteConfig((
+ ModelHubRouteHopConfig(fallback.id, "next-model"),
+ ))
+ with pytest.raises(ModelHubError) as conflict:
+ await router.resolve_hop("menu-alias", process_scope="avibe:overlap", turn_id=turn_id)
+ assert conflict.value.status == 409
+ finally:
+ release.set()
+ response = await pending
+ assert response.status == 200
+ await response.read()
+ response.release()
+ completion = router.settle_turn(turn_id, settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat())
+ if completion:
+ await completion
+ record = service.provenance.get(turn_id)
+ assert record is not None
+ assert record["served"]["source_id"] == primary.id
+ finally:
+ await gateway.close()
+
+
+def test_released_config_adds_only_empty_avibe_supply():
+ """MH-AVIBE-003: preserve shipped native rows and add an empty Hub consumer."""
+ released = json.loads((FIXTURES / "released_pre_avibe_consumer.json").read_text())
+ before = copy.deepcopy(released)
+ config = ModelHubConfig.from_payload(released)
+ assert released == before
+ assert set(config.agents) == {"claude", "codex", "opencode", "avibe"}
+ for backend in ("claude", "codex", "opencode"):
+ agent = config.agents[backend]
+ original = before["agents"][backend]
+ assert (agent.backend, agent.mode, agent.menu_kind, agent.sources.order) == (
+ backend, original["mode"], original["menu_kind"], original["sources"]["order"],
+ )
+ assert {
+ model_id: [(hop.source_id, hop.model_id) for hop in route.hops]
+ for model_id, route in agent.routes.items()
+ } == {
+ model_id: [(hop["source_id"], hop["model_id"]) for hop in route["hops"]]
+ for model_id, route in original["routes"].items()
+ }
+ assert [model.id for model in agent.models] == [model["id"] for model in original["models"]]
+ assert config.agents["claude"].models[0].context_window == 100000
+ assert config.agents["codex"].models[0].max_output_tokens == 4096
+ assert config.agents["codex"].models[0].supports_tools is False
+ assert config.agents["opencode"].menu.checked == []
+ avibe = config.agents["avibe"]
+ assert (avibe.mode, avibe.menu_kind, avibe.models, avibe.sources.order, avibe.routes) == (
+ "hub", "fixed", [], [], {},
+ )
+ assert config.enabled is before["enabled"]
+ assert ModelHubConfig.from_payload(config.to_payload()).to_payload() == config.to_payload()
+
+
+def test_native_cli_and_direct_are_not_avibe_channels(tmp_path):
+ """MH-AVIBE-004: neither invalid persisted state nor routing can select a CLI."""
+ native = _source("src_native001", "Native", channel="native_cli", vendor="anthropic", protocol="anthropic")
+ service = _avibe_service(tmp_path, [native])
+ config = service.store.load()
+ assert not ModelHubConfig.source_eligible_for_backend(native, "avibe")
+ agent = config.agents["avibe"]
+ agent.routes["menu-alias"] = ModelHubRouteConfig((ModelHubRouteHopConfig(native.id, "shared-model"),))
+ chain = service.agent_chain("avibe", "menu-alias")
+ assert chain["current"] is None
+ assert chain["supply_state"] == "interrupted"
+ with pytest.raises(ValueError, match="ineligible"):
+ ModelHubConfig.from_payload(config.to_payload())
+ agent.routes.clear()
+ agent.mode = "direct"
+ with pytest.raises(ValueError, match="must be hub"):
+ ModelHubConfig.from_payload(config.to_payload())
+ assert bind_persisted_launch(SimpleNamespace(), {
+ "backend": "avibe", "channel": "native_cli", "source_id": native.id, "target_model": "shared-model",
+ }) is None
+
+
[email protected]("protocol", PROTOCOL_ENDPOINTS)
[email protected]("known", [False, True])
+async def test_hop_resolution_uses_primary_protocol_and_alias_capabilities(tmp_path, protocol, known):
+ """MH-AVIBE-001: the launch boundary owns protocol, identity and planning metadata."""
+ source = _source("src_primary01", "Primary", protocol=protocol, model_id="upstream-model")
+ service = _avibe_service(tmp_path, [source])
+ if known:
+ service.store.config.agents["avibe"].models[0] = ModelHubBackendModelConfig(
+ id="menu-alias", context_window=128000, max_output_tokens=4096,
+ input_modalities=["text", "image"], supports_tools=True, supports_reasoning=False,
+ reasoning_efforts=["high"],
+ )
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:test", turn_id="turn-hop")
+ _validate("hop-resolution.schema.json", hop)
+ assert hop["protocol"] == protocol
+ assert hop["provider"] == "openai"
+ assert hop["base_url"].endswith("/avibe/v1")
+ assert hop["runtime_model"] == "upstream-model"
+ assert hop["source_id"] == source.id
+ assert hop["capabilities"] == {
+ "context_window": 128000 if known else None,
+ "input_limit": None,
+ "max_output_tokens": 4096 if known else None,
+ "supports_tools": True if known else None,
+ "supports_images": True if known else None,
+ "supports_reasoning": False if known else None,
+ "reasoning_efforts": [],
+ }
+ _assert_mandatory_fields("hop-resolution.schema.json", hop)
+ launch = await router.resolve("avibe", "menu-alias", process_scope="avibe:test", turn_id="turn-hop")
+ assert hop["token"] not in repr(launch)
+ assert build_claude_hub_env({"PATH": "/fixture"}, launch) == {"PATH": "/fixture"}
+ assert build_codex_hub_launch(["fixture"], {}, launch) == (["fixture"], None)
+ assert claude_settings_for_launch("{}", launch) == "{}"
+ assert service.list_agents()[-1]["cli_present"] is False
+ with pytest.raises(ModelHubError):
+ await service.set_agent_mode("avibe", "direct")
+ with pytest.raises(ModelHubError):
+ await ModelHubRuntimeRouter(service=service).resolve("avibe", "menu-alias")
+ with pytest.raises(ModelHubError):
+ await resolve_model_hub_launch(SimpleNamespace(), "avibe", "menu-alias")
+ finally:
+ await gateway.close()
+
+
[email protected]("protocol", PROTOCOL_ENDPOINTS)
[email protected]("delivery", ["buffered", "stream", "settled"])
+async def test_failover_origin_is_available_before_body_and_matches_served_attempt(tmp_path, protocol, delivery):
+ """MH-AVIBE-002: HTTP headers identify the same fallback attempt that is persisted."""
+ stream = delivery == "stream"
+ fallback_protocol = "openai_responses" if protocol != "openai_responses" else "anthropic"
+ first = _source("src_primary01", "Primary", vendor="custom", protocol=protocol)
+ second = _source(
+ "src_fallback01", "Fallback", vendor="anthropic", protocol=fallback_protocol, model_id="模型/β",
+ )
+ answer = b"{}" if delivery == "settled" else _body(protocol, stream)
+ success = _outcome(RawOutcomeKind.SUCCESS, source_id=second.id, stream_started=stream)
+ service = _avibe_service(tmp_path, [first, second], handles=[
+ InvokeHandle(_outcome(RawOutcomeKind.HTTP_ERROR, status=429, code="rate_limit_error", source_id=first.id)),
+ InvokeHandle(success) if delivery == "settled" else LiveInvokeHandle(success, (answer,)),
+ ])
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:test", turn_id="turn-fallback")
+ async with aiohttp.ClientSession() as client:
+ async with client.post(
+ f'{hop["base_url"]}/{PROTOCOL_ENDPOINTS[protocol]}',
+ headers={"Authorization": f'Bearer {hop["token"]}'},
+ json={"model": hop["runtime_model"], "stream": stream, "messages": []},
+ ) as response:
+ assert response.status == 200, await response.text() if response.status != 200 else ""
+ origin = json.loads(response.headers[SERVED_HOP_HEADER])
+ assert origin == {"provider": "anthropic", "api": fallback_protocol, "model": "模型/β"}
+ assert response.headers[SERVED_HOP_HEADER].isascii()
+ assert await response.read() == answer
+ completion = router.settle_turn(
+ "turn-fallback", settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat(),
+ )
+ if completion:
+ await completion
+ record = service.provenance.get("turn-fallback")
+ _validate("turn-provenance.schema.json", record)
+ _assert_mandatory_fields("turn-provenance.schema.json", record)
+ # The new Avibe promise must not tighten native or released records.
+ # Exercise the persistence reader, not only in-memory schema payloads.
+ history = []
+ for backend in ("claude", "codex", "opencode"):
+ for version in (5, 6, 7, 8, 9, 10, 11):
+ native = copy.deepcopy(record)
+ native.update(agent=backend, contract_version=version, turn_id=f"{backend}-{version}")
+ native["served"].pop("origin")
+ for attempt in native["failed_attempts"]:
+ attempt.pop("origin", None)
+ history.append(native)
+ history_path = tmp_path / "native-history.json"
+ history_path.write_text(json.dumps(history))
+ history_store = BoundedProvenanceStore(history_path)
+ for native in history:
+ loaded = history_store.get(native["turn_id"])
+ assert loaded == native
+ _validate("turn-provenance.schema.json", loaded)
+ assert record["served"]["origin"] == origin
+ assert record["served"]["source_id"] == second.id
+ assert record["failed_attempts"][0]["source_id"] == first.id
+ assert [entry[0] for entry in service.adapter.invocations] == [first.id, second.id]
+ assert all(request.protocol == protocol for request in service.adapter.requests)
+ assert all(SERVED_HOP_HEADER not in request.headers for request in service.adapter.requests)
+ finally:
+ await gateway.close()
+
+
[email protected]("backend", ["avibe", "claude", "codex", "opencode"])
[email protected]("fallback", [False, True])
+ "failure,carrier,body_available,cause,expected_status,has_producer",
+ [
+ ("upstream_terminal", "resolved", True, "upstream", 400, True),
+ ("local_spool", "resolved", True, "local", 502, True),
+ ("bodyless_terminal", "error", False, "upstream", 400, True),
+ ("bodyless_protocol", "error", False, "upstream", 502, True),
+ ("bodyless_local", "error", False, "local", 502, False),
+ ("exhaustion", "error", False, "local", 503, False),
+ ("pre_admission", "error", False, "local", 502, False),
+ ],
+)
+async def test_terminal_response_origin_follows_its_carrier(
+ tmp_path, monkeypatch, backend, fallback, failure, carrier, body_available, cause,
+ expected_status, has_producer,
+):
+ """MH-AVIBE-002: response origin follows evidence, not the last attempted hop.
+
+ The old buffered-only test missed the error carrier. The feasible terminal
+ matrix separates upstream errors from local endings, including local delivery
+ failure after acquiring a known producer's body. Native clients stay unchanged.
+ """
+ source = _source(
+ "src_primary01", "Primary", vendor="anthropic", protocol="anthropic",
+ model_id="模型/β" if backend == "avibe" else "shared-model",
+ )
+ outcomes = {
+ "upstream_terminal": _outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="invalid_request_error", source_id=source.id),
+ "local_spool": _outcome(RawOutcomeKind.SUCCESS, source_id=source.id),
+ "bodyless_terminal": _outcome(RawOutcomeKind.HTTP_ERROR, status=400, code="invalid_request_error", source_id=source.id),
+ "bodyless_protocol": _outcome(RawOutcomeKind.PROTOCOL_ERROR, source_id=source.id),
+ "bodyless_local": _outcome(RawOutcomeKind.NETWORK_ERROR, status=502, code="engine_down", source_id=source.id),
+ "exhaustion": _outcome(RawOutcomeKind.HTTP_ERROR, status=429, code="rate_limit_error", source_id=source.id),
+ "pre_admission": _outcome(RawOutcomeKind.NETWORK_ERROR, status=502, code="engine_down", source_id=source.id),
+ }
+ handle = LiveInvokeHandle(outcomes[failure], (b"{}",)) if body_available else InvokeHandle(outcomes[failure])
+ sources, handles = [source], [handle]
+ if fallback:
+ first = _source("src_fallback01", "First", vendor="custom", protocol="openai_chat")
+ sources.insert(0, first)
+ handles.insert(0, InvokeHandle(_outcome(
+ RawOutcomeKind.HTTP_ERROR, status=429, code="rate_limit_error", source_id=first.id,
+ )))
+ service = _avibe_service(tmp_path, sources, handles=handles)
+ observed_carriers = []
+ resolve = service.resolve_with_recovery
+
+ async def observe_carrier(**kwargs):
+ try:
+ result = await resolve(**kwargs)
+ except ModelHubError:
+ observed_carriers.append("error")
+ raise
+ observed_carriers.append("resolved")
+ return result
+
+ monkeypatch.setattr(service, "resolve_with_recovery", observe_carrier)
+ if failure == "pre_admission":
+ invoke = service.adapter.invoke
+
+ async def fail_before_admission(*args, **kwargs):
+ if args[0] == source.id:
+ # Engine-local completion without admitting an upstream call.
+ return InvokeHandle(outcomes[failure])
+ return await invoke(*args, **kwargs)
+
+ monkeypatch.setattr(service.adapter, "invoke", fail_before_admission)
+ if failure == "local_spool":
+ def unavailable_spool(*args, **kwargs):
+ raise OSError("fixture spool unavailable")
+
+ monkeypatch.setattr(
+ "core.handlers.model_hub.turn_gateway.tempfile.SpooledTemporaryFile", unavailable_spool,
+ )
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ turn_id = "turn-terminal-carrier"
+ try:
+ launch = await router.resolve(
+ backend, service.store.requested_models[backend], process_scope=f"{backend}:test", turn_id=turn_id,
+ )
+ protocol = "anthropic" if backend in {"avibe", "claude"} else "openai_responses"
+ # Avibe's frontend uses the primary's protocol; fallback can differ.
+ if backend == "avibe":
+ protocol = launch.protocol
+ headers = {"Authorization": f"Bearer {launch.gateway_token}"}
+ if launch.gateway_request_metadata:
+ headers["x-codex-turn-metadata"] = json.dumps(launch.gateway_request_metadata)
+ async with aiohttp.ClientSession() as client:
+ async with client.post(
+ f"{launch.gateway_base_url}/v1/{PROTOCOL_ENDPOINTS[protocol]}",
+ headers=headers,
+ json={"model": launch.runtime_model, "stream": False, "messages": []},
+ ) as response:
+ assert response.status == expected_status
+ origin = None
+ if backend == "avibe" and has_producer:
+ origin = json.loads(response.headers[SERVED_HOP_HEADER])
+ assert origin == {"provider": "anthropic", "api": "anthropic", "model": "模型/β"}
+ else:
+ assert SERVED_HOP_HEADER not in response.headers
+ assert (await response.json())["error"]
+ completion = router.settle_turn(
+ turn_id, settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat(),
+ )
+ if completion:
+ await completion
+ assert observed_carriers == [carrier]
+ assert [entry[0] for entry in service.adapter.invocations] == (
+ ([sources[0].id] if fallback else []) + ([] if failure == "pre_admission" else [source.id])
+ )
+ record = service.provenance.get(turn_id)
+ if backend == "opencode":
+ # The native shared server has no exact turn discriminator.
+ assert record is None
+ return
+ _validate("turn-provenance.schema.json", record)
+ assert record["outcome"] == ("exhausted" if failure == "exhaustion" else "failed_terminal")
+ if cause == "upstream":
+ assert record["terminal_error"]["source_id"] == source.id
+ if backend == "avibe":
+ assert record["terminal_error"]["origin"] == origin
+ else:
+ assert "origin" not in record["terminal_error"]
+ elif failure == "exhaustion":
+ assert record["terminal_error"] is None
+ else:
+ # Existing engine-down provenance deliberately does not blame the
+ # upstream Source for local delivery failure, despite a known producer.
+ assert record["terminal_error"]["reason"] == "engine_down"
+ assert record["terminal_error"]["source_id"] is None
+ finally:
+ await gateway.close()
+
+
[email protected]("fallback", [False, True])
[email protected]("model_id,allowed", [
+ pytest.param("a" * 4044, True, id="exact-bound"), # 52 bytes of JSON envelope.
+ pytest.param("a" * 4045, False, id="one-over"),
+ pytest.param("模" * 1350, False, id="unicode-expansion"),
+])
+async def test_origin_header_limit_is_checked_before_each_avibe_hop(tmp_path, model_id, allowed, fallback):
+ """MH-AVIBE-002: transport bounds must reject a hop before any upstream work.
+
+ Short-ID cases cannot expose client header parse failure or a fallback bypass.
+ Persisted-shape acceptance is independent of the Avibe transport restriction.
+ """
+ target = _source("src_target001", "Target", protocol="openai_chat", model_id=model_id)
+ sources = [target]
+ handles = []
+ if fallback:
+ first = _source("src_primary01", "Primary", protocol="anthropic")
+ sources.insert(0, first)
+ handles.append(InvokeHandle(_outcome(
+ RawOutcomeKind.HTTP_ERROR, status=429, code="rate_limit_error", source_id=first.id,
+ )))
+ handles.append(LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=target.id), (b"{}",)))
+ service = _avibe_service(tmp_path, sources, handles=handles)
+ reloaded = ModelHubConfig.from_payload(service.store.config.to_payload())
+ assert reloaded.sources[-1].models[0].id == model_id
+ assert reloaded.agents["avibe"].routes["menu-alias"].hops[-1].model_id == model_id
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:test", turn_id="turn-header-bound")
+ async with aiohttp.ClientSession() as client:
+ async with client.post(
+ f'{hop["base_url"]}/{PROTOCOL_ENDPOINTS[hop["protocol"]]}',
+ headers={"Authorization": f'Bearer {hop["token"]}'},
+ json={"model": hop["runtime_model"], "stream": False, "messages": []},
+ ) as response:
+ if allowed:
+ assert response.status == 200
+ assert len(response.headers[SERVED_HOP_HEADER].encode("ascii")) == 4096
+ assert json.loads(response.headers[SERVED_HOP_HEADER])["model"] == model_id
+ assert await response.read() == b"{}"
+ else:
+ assert response.status == 422
+ assert SERVED_HOP_HEADER not in response.headers
+ assert (await response.json())["error"]["code"] == "served_hop_too_large"
+ assert [entry[0] for entry in service.adapter.invocations] == (
+ ([sources[0].id] if fallback else []) + ([target.id] if allowed else [])
+ )
+ assert target.state.status == "standby"
+ finally:
+ await gateway.close()
+
+
[email protected]("backend", ["claude", "codex", "opencode"])
+async def test_served_hop_transport_bound_does_not_restrict_native_clients(tmp_path, backend):
+ """Native consumers never emit this header, so their valid IDs remain callable."""
+ source = _source("src_primary01", "Primary", model_id="模" * 1400)
+ service = _service(tmp_path, sources=[source], outcomes=[_outcome(RawOutcomeKind.SUCCESS)])
+ selected = _canonicalize_fixed_test_routes(service)
+ resolved = await service.resolve(
+ backend=backend, model_id=selected.get(backend, "shared-model"), request={}, stream=False,
+ )
+ assert resolved.origin is None
+ assert resolved.model_id == source.models[0].id
+ assert service.adapter.invocations == [(source.id, source.models[0].id, backend)]
+
+
+async def test_slow_anthropic_resolution_waits_to_publish_origin_and_keeps_source_snapshot(tmp_path, monkeypatch):
+ monkeypatch.setattr("core.handlers.model_hub.turn_gateway._EARLY_STREAM_COMMIT_SECONDS", 0.001)
+ source = _source("src_primary01", "Primary", vendor="anthropic", protocol="anthropic")
+ answer = _body("anthropic", True)
+ service = _avibe_service(tmp_path, [source], handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, stream_started=True), (answer,)),
+ ])
+ entered, release = asyncio.Event(), asyncio.Event()
+ invoke = service.adapter.invoke
+
+ async def held(*args, **kwargs):
+ handle = await invoke(*args, **kwargs)
+ entered.set()
+ await release.wait()
+ return handle
+
+ service.adapter.invoke = held
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ task = None
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:test", turn_id="turn-slow")
+ async with aiohttp.ClientSession() as client:
+ task = asyncio.create_task(client.post(
+ f'{hop["base_url"]}/messages', headers={"x-api-key": hop["token"]},
+ json={"model": hop["runtime_model"], "stream": True, "messages": []},
+ ))
+ await asyncio.wait_for(entered.wait(), 2)
+ with pytest.raises(asyncio.TimeoutError):
+ await asyncio.wait_for(asyncio.shield(task), 0.05)
+ # Replace the persisted Source after admission: response metadata
+ # must describe the actual invocation, not the latest config read.
+ service.store.config.sources = [replace(source, vendor="custom", protocol="openai_chat")]
+ release.set()
+ response = await asyncio.wait_for(task, 2)
+ async with response:
+ origin = json.loads(response.headers[SERVED_HOP_HEADER])
+ assert origin == HopOrigin("anthropic", "anthropic", "shared-model").payload()
+ assert await response.read() == answer
+ completion = router.settle_turn("turn-slow", settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat())
+ if completion:
+ await completion
+ assert service.provenance.get("turn-slow")["served"]["origin"] == origin
+ finally:
+ release.set()
+ if task is not None and not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ await gateway.close()
+
+
+async def test_concurrent_responses_keep_their_own_origin(tmp_path):
+ """Interleaving requests must not borrow a gateway-wide 'last served' hop."""
+ first = _source("src_primary01", "First", vendor="openai", protocol="openai_chat", model_id="model-one")
+ second = _source("src_second001", "Second", vendor="anthropic", protocol="anthropic", model_id="model-two")
+ service = _avibe_service(tmp_path, [first, second], handles=[
+ LiveInvokeHandle(
+ _outcome(RawOutcomeKind.SUCCESS, source_id=source.id, stream_started=True),
+ (_body(source.protocol, True),),
+ )
+ for source in (first, second)
+ ])
+ agent = service.store.config.agents["avibe"]
+ agent.models.append(ModelHubBackendModelConfig(id="second-alias"))
+ agent.routes["menu-alias"] = ModelHubRouteConfig((ModelHubRouteHopConfig(first.id, "model-one"),))
+ agent.routes["second-alias"] = ModelHubRouteConfig((ModelHubRouteHopConfig(second.id, "model-two"),))
+ entered, release = asyncio.Event(), asyncio.Event()
+ original_invoke = service.adapter.invoke
+
+ async def invoke(*args, **kwargs):
+ handle = await original_invoke(*args, **kwargs)
+ if args[0] == first.id:
+ entered.set()
+ await release.wait()
+ return handle
+
+ service.adapter.invoke = invoke
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ pending = None
+ try:
+ hops = [
+ await router.resolve_hop(alias, process_scope=f"avibe:session-{index}", turn_id=f"turn-{index}")
+ for index, alias in enumerate(("menu-alias", "second-alias"))
+ ]
+ async with aiohttp.ClientSession() as client:
+ async def read(hop):
+ async with client.post(
+ f'{hop["base_url"]}/{PROTOCOL_ENDPOINTS[hop["protocol"]]}',
+ headers={"Authorization": f'Bearer {hop["token"]}'},
+ json={"model": hop["runtime_model"], "stream": True, "messages": []},
+ ) as response:
+ assert response.status == 200
+ origin = json.loads(response.headers[SERVED_HOP_HEADER])
+ assert await response.read() == _body(hop["protocol"], True)
+ return origin
+
+ pending = asyncio.create_task(read(hops[0]))
+ await asyncio.wait_for(entered.wait(), 2)
+ second_origin = await asyncio.wait_for(read(hops[1]), 2)
+ release.set()
+ first_origin = await asyncio.wait_for(pending, 2)
+ assert first_origin == {"provider": "openai", "api": "openai_chat", "model": "model-one"}
+ assert second_origin == {"provider": "anthropic", "api": "anthropic", "model": "model-two"}
+ for index, origin in enumerate((first_origin, second_origin)):
+ completion = router.settle_turn(f"turn-{index}", settled_by=SETTLED_BY_TERMINAL_RESULT, ts=NOW.isoformat())
+ if completion:
+ await completion
+ assert service.provenance.get(f"turn-{index}")["served"]["origin"] == origin
+ finally:
+ release.set()
+ if pending is not None and not pending.done():
+ pending.cancel()
+ await asyncio.gather(pending, return_exceptions=True)
+ await gateway.close()
diff --git a/tests/test_model_hub_avibe_contract_matrix.py b/tests/test_model_hub_avibe_contract_matrix.py
new file mode 100644
index 000000000..f425a614d
--- /dev/null
+++ b/tests/test_model_hub_avibe_contract_matrix.py
@@ -0,0 +1,210 @@
+"""MH-AVIBE-004: schemas cannot certify a transport Avibe cannot use.
+
+Positive Hub payloads miss illegal discriminator/channel combinations. The
+producer-owned audit table drives refusals and must cover newly declared shapes.
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+
+import pytest
+from jsonschema import Draft7Validator, ValidationError
+from referencing import Registry, Resource
+
+from config.v2_config import ModelHubRouteConfig, ModelHubRouteHopConfig
+from core.handlers.model_hub.service import ModelHubError
+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+from modules.agents.model_hub import ModelHubRuntimeRouter
+from tests.test_model_hub_avibe_consumer import CONTRACTS, _avibe_service, _source
+
+
+MATRIX = json.loads((CONTRACTS / "avibe-boundary-matrix.json").read_text())["boundaries"]
+
+
+def _schema(row):
+ resources = {}
+ for path in CONTRACTS.glob("*.schema.json"):
+ value = json.loads(path.read_text())
+ resources[value["$id"]] = Resource.from_contents(value)
+ root = json.loads((CONTRACTS / row["schema"]).read_text())
+ return Draft7Validator(
+ {"$ref": root["$id"] + "#" + row["pointer"]},
+ registry=Registry().with_resources(resources.items()),
+ )
+
+
+def _fixture(kind):
+ identity = {
+ "source_id": "src_fixture01", "configured_model_id": "fixture-model", "channel": "hub",
+ "origin": {"provider": "anthropic", "api": "anthropic", "model": "fixture-model"},
+ }
+ if kind == "supply":
+ return {"backend": "avibe", "mode": "hub", "menu_kind": "fixed", "cli_present": False}
+ if kind == "catalog":
+ return {"backend": "avibe", "mode": "hub", "catalog_models": []}
+ if kind == "probe":
+ # Start from a valid native response so no Hub latency constraint can
+ # accidentally reject the Avibe/native pairing for an unrelated cause.
+ return {
+ "contract_version": 11, "backend": "claude", "channel": "native_cli", "reachable": True,
+ "source_id": "src_fixture01", "model_id": "fixture-model", "latency_ms": None,
+ "error": None,
+ }
+ if kind == "chain":
+ return {
+ "contract_version": 11, "backend": "avibe", "model_id": "fixture-model",
+ "manual_override": None, "route_origin": "automatic",
+ "chain": [{"source_id": "src_fixture01", "model_id": "fixture-model", "channel": "hub",
+ "health": "healthy", "runnable": True, "reason": None, "retry_at": None}],
+ "current": {"source_id": "src_fixture01", "model_id": "fixture-model"}, "supply_state": "ok",
+ }
+ if kind == "migration":
+ return {
+ "id": "fixture", "backend": "claude", "kind": "api_key", "masked_detail": "fixture",
+ "proposed_action": "import", "selected": False,
+ }
+ return {
+ "contract_version": 11, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z",
+ "agent": "avibe", "requested_model_id": "fixture-model", "outcome": kind,
+ "failed_attempts": [{**identity, "reason": "rate_limited"}] if kind == "exhausted" else [],
+ "served": identity if kind == "served" else None,
+ "terminal_error": (
+ {**identity, "reason": "protocol_error", "stream_started": False}
+ if kind == "failed_terminal" else None
+ ),
+ "canceled_attempt": identity if kind == "canceled" else None,
+ "model_supply_state": None, "blockers": [],
+ }
+
+
+def test_avibe_matrix_covers_every_declared_backend_shape():
+ def declared(node, pointer=""):
+ if not isinstance(node, dict):
+ return
+ for field in ("backend", "agent"):
+ enum = node.get("properties", {}).get(field, {}).get("enum", [])
+ if {"claude", "codex", "opencode", "avibe"} & set(enum):
+ yield pointer, field
+ # Traverse shape definitions, not if/then discriminator constraints.
+ for field in ("properties", "definitions", "$defs"):
+ for name, child in node.get(field, {}).items():
+ yield from declared(child, f"{pointer}/{field}/{name}")
+ if "items" in node:
+ yield from declared(node["items"], f"{pointer}/items")
+ for field in ("allOf", "anyOf", "oneOf"):
+ for index, child in enumerate(node.get(field, [])):
+ yield from declared(child, f"{pointer}/{field}/{index}")
+
+ sites = {
+ (path.name, pointer, field)
+ for path in CONTRACTS.glob("*.schema.json")
+ for pointer, field in declared(json.loads(path.read_text()))
+ }
+ assert {(row["schema"], row["pointer"], row["backend"]) for row in MATRIX} == sites
+ assert len(MATRIX) == len(sites)
+ for row in MATRIX:
+ assert row["policy"] in {"hub-only", "native-only", "reference"}
+ assert row["runtime"]
+ assert bool(row.get("refusals")) == (row["policy"] != "reference")
+
+
+ ("row", "refusal"),
+ [(row, refusal) for row in MATRIX for refusal in row.get("refusals", [])],
+ ids=[
+ f'{row["schema"]}:{refusal["fixture"]}:{refusal["path"]}'
+ for row in MATRIX for refusal in row.get("refusals", [])
+ ],
+)
+def test_avibe_channel_matrix_rejects_impossible_shapes_without_changing_native(row, refusal):
+ validator = _schema(row)
+ payload = _fixture(refusal["fixture"])
+ validator.validate(payload)
+ invalid = copy.deepcopy(payload)
+ target = invalid
+ for key in refusal["path"][:-1]:
+ target = target[key]
+ target[refusal["path"][-1]] = refusal["value"]
+ with pytest.raises(ValidationError):
+ validator.validate(invalid)
+ if row["policy"] != "native-only":
+ invalid[row["backend"]] = "claude"
+ validator.validate(invalid)
+
+
+def test_avibe_local_terminal_and_pre_admission_cancel_remain_nullable():
+ row = next(row for row in MATRIX if row["schema"] == "turn-provenance.schema.json")
+ validator = _schema(row)
+ payload = _fixture("failed_terminal")
+ payload["terminal_error"] = {
+ "source_id": None, "configured_model_id": None, "channel": None,
+ "reason": "engine_down", "stream_started": False,
+ }
+ validator.validate(payload)
+ payload = _fixture("canceled")
+ payload["canceled_attempt"] = None
+ validator.validate(payload)
+
+
[email protected]("case", [case for row in MATRIX for case in row.get("runtime_cases", [])])
+async def test_avibe_runtime_matrix_refuses_native_admission(tmp_path, case):
+ """Admission, not just serialization, must refuse impossible transports."""
+ native = _source("src_native001", "Native", channel="native_cli", vendor="anthropic", protocol="anthropic")
+ service = _avibe_service(tmp_path, [native])
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ route = ModelHubRouteConfig((ModelHubRouteHopConfig(native.id, "shared-model"),))
+ try:
+ if case in {"native_attempt", "attempt_channel"}:
+ # The recording boundary must not let an accidental future caller
+ # manufacture native Avibe provenance after normal routing refused.
+ if case == "native_attempt":
+ with pytest.raises(ValueError, match="avibe.*hub"):
+ gateway.correlation.begin_native_attempt(
+ backend="avibe", process_scope="avibe:matrix", turn_id="turn-matrix",
+ requested_model_id="menu-alias", source_id=native.id,
+ resolved_model_id="shared-model", via_mapping=False,
+ )
+ else:
+ await gateway.endpoint(
+ "avibe", process_scope="avibe:matrix", turn_id="turn-matrix",
+ requested_model_id="menu-alias", source_id=native.id, resolved_model_id="shared-model",
+ )
+ with pytest.raises(ValueError, match="avibe.*hub"):
+ gateway.correlation.begin_attempt(
+ "turn-matrix", source_id=native.id, resolved_model_id="shared-model",
+ channel="native_cli", via_mapping=False,
+ )
+ else:
+ with pytest.raises(ModelHubError) as refusal:
+ if case == "mode":
+ await service.set_agent_mode("avibe", "direct")
+ elif case == "source_order":
+ await service.set_agent_sources("avibe", {"order": [native.id]})
+ elif case == "route_write":
+ await service.set_agent_chain("avibe", "menu-alias", route.to_payload())
+ else:
+ # Corrupt in-process route still cannot bypass live
+ # admission (persisted config rejects it on load).
+ service.store.config.agents["avibe"].routes["menu-alias"] = route
+ if case == "probe":
+ await service.probe_agent("avibe", "menu-alias")
+ elif case == "resolve_hop":
+ await router.resolve_hop("menu-alias", process_scope="avibe:matrix")
+ elif case in {"resolve", "recovery"}:
+ service.recovery.window_seconds = 120 if case == "recovery" else 0
+ await service.resolve_with_recovery(
+ backend="avibe", model_id="menu-alias", request={}, stream=False,
+ )
+ else:
+ raise AssertionError(f"Unhandled runtime boundary: {case}")
+ assert refusal.value.code in {
+ "mode_switch_blocked", "invalid_source_order", "mapping_target_unavailable",
+ "probe_no_candidate", "no_candidate",
+ }
+ assert service.adapter.invocations == []
+ finally:
+ await gateway.close()
diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.py
index d736b0376..af5aa25b1 100644
--- a/tests/test_model_hub_config.py
+++ b/tests/test_model_hub_config.py
@@ -94,7 +94,7 @@ def test_auto_detect_asks_for_responses_before_chat():
def test_unsaved_observation_schema_closes_all_terminal_shapes():
schema = _schema("observation-result.schema.json")
- assert schema["properties"]["contract_version"]["const"] == 10
+ assert schema["properties"]["contract_version"]["const"] == 11
assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(
member.value for member in ObservationOutcome
)
@@ -118,7 +118,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():
def payload(observation: SourceObservation) -> dict:
return {
- "contract_version": 10,
+ "contract_version": 11,
"outcome": observation.outcome.value,
"reachable": observation.reachable,
"authenticated": (
@@ -698,7 +698,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
route_refusal = {
"ok": False,
- "contract_version": 10,
+ "contract_version": 11,
"error": "source_in_route_chain",
"detail": "modelHub.errors.source_in_route_chain",
"would_remove_hops": [hop],
@@ -714,7 +714,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():
}
candidate_refusal = {
"ok": False,
- "contract_version": 10,
+ "contract_version": 11,
"error": "candidate_suppliers_changed",
"detail": "modelHub.errors.candidate_suppliers_changed",
"changed": {
@@ -798,7 +798,7 @@ def test_v8_mirror_registry_is_executable_and_complete():
registry = json.loads((CONTRACTS / "mirror-registry.json").read_text(encoding="utf-8"))
schemas = _mirror_schemas(registry)
- assert registry["contract_version"] == 10
+ assert registry["contract_version"] == 11
ids = [entry["id"] for entry in registry["entries"]]
assert ids
assert len(ids) == len(set(ids))
@@ -935,8 +935,8 @@ def test_model_hub_authority_closure_anchors_the_persisted_version_floor(monkeyp
"kind": "contract_version_schema_drift",
"domain": "V1",
"file": "docs/plans/model-hub-contracts/turn-provenance.schema.json",
- "values": [6, 7, 8, 9, 10],
- "expected": [5, 6, 7, 8, 9, 10],
+ "values": [6, 7, 8, 9, 10, 11],
+ "expected": [5, 6, 7, 8, 9, 10, 11],
} in result["findings"]
@@ -1247,7 +1247,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():
with pytest.raises(ValidationError):
chain_validator.validate(interrupted)
exact_hop = {
- "contract_version": 10,
+ "contract_version": 11,
"backend": "claude",
"model_id": "claude-opus-4-6",
"manual_override": None,
@@ -1482,7 +1482,7 @@ def _legacy_model_hub_payload(current: dict) -> dict:
agents = {}
for backend, agent in current["agents"].items():
- if backend == "opencode":
+ if backend not in {"claude", "codex"}:
continue
agents[backend] = {
"backend": agent["backend"],
@@ -2743,7 +2743,8 @@ def test_legacy_configs_stay_direct_while_fresh_configs_default_to_gateway():
payload.pop("model_hub")
legacy = V2Config.from_payload(payload)
- assert {agent.mode for agent in legacy.model_hub.agents.values()} == {"direct"}
+ assert {legacy.model_hub.agents[backend].mode for backend in ("claude", "codex", "opencode")} == {"direct"}
+ assert legacy.model_hub.agents["avibe"].mode == "hub"
assert {agent.mode for agent in default_config().model_hub.agents.values()} == {"hub"}
assert default_config().model_hub.enabled is True
assert default_config().model_hub.runtime_default_applied is True
@@ -3161,7 +3162,8 @@ def test_invalid_empty_route_key_keeps_v2_recovery_fence(tmp_path, backend, bad_
assert loaded.load_warnings
assert "model_hub" in loaded.recovered_sections
assert loaded.model_hub.sources == []
- assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert all(loaded.model_hub.agents[backend].mode == "direct" for backend in ("claude", "codex", "opencode"))
+ assert loaded.model_hub.agents["avibe"].mode == "hub"
assert path.read_bytes() == before
# #2079: the fence is on the recovered section, not on every save.
loaded.save(config_path=path)
diff --git a/tests/test_model_hub_config_read_compatibility.py b/tests/test_model_hub_config_read_compatibility.py
index 9d4d343ac..10151cc91 100644
--- a/tests/test_model_hub_config_read_compatibility.py
+++ b/tests/test_model_hub_config_read_compatibility.py
@@ -277,8 +277,8 @@ def test_unrelated_writer_keeps_upgrade_pending_until_startup(writer, marker, en
def pending_runtime_service(tmp_path, *, enabled, marker):
path, _ = legacy_config(enabled=enabled)
payload = json.loads(path.read_text(encoding="utf-8"))
- for backend in payload["model_hub"]["agents"].values():
- backend["mode"] = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ payload["model_hub"]["agents"][backend]["mode"] = "direct"
if marker is False:
payload["model_hub"]["runtime_default_applied"] = False
path.write_text(json.dumps(payload), encoding="utf-8")
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index 5457bf626..a0a7861e2 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -6821,7 +6821,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(
_assert_valid(
"observation-result.schema.json",
{
- "contract_version": 10,
+ "contract_version": 11,
"outcome": "adapter_error",
"reachable": True,
"authenticated": "unknown",
@@ -9349,7 +9349,7 @@ def test_native_chain_visibility_and_probe_readiness(tmp_path: Path) -> None:
probe = asyncio.run(service.probe_agent("codex", "shared-model"))
assert probe == {
- "contract_version": 10,
+ "contract_version": 11,
"backend": "codex",
"channel": "native_cli",
"reachable": True,
diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.py
index 7e6f1a153..b45309472 100644
--- a/tests/test_model_hub_provenance.py
+++ b/tests/test_model_hub_provenance.py
@@ -200,7 +200,7 @@ def test_live_recovery_snapshots_never_revive_invalid_or_terminal_owners(tmp_pat
def _record(turn_id, *, backend="claude", model=MODEL, outcome="failed_terminal"):
identity = {"source_id": "src_deleted01", "configured_model_id": "unknown-model", "channel": "hub"}
return {
- "contract_version": 10,
+ "contract_version": 11,
"turn_id": turn_id,
"ts": "2026-09-06T00:00:00Z",
"agent": backend,
@@ -395,6 +395,6 @@ def test_model_history_client_rpc_http_share_nullable_read_only_result(monkeypat
f"/api/models/agents/claude/provenance?model={MODEL}", headers=csrf_headers(client, origin), base_url=origin
)
assert response.status_code == 200
- assert response.get_json() == {"ok": True, "contract_version": 10, "provenance": record}
+ assert response.get_json() == {"ok": True, "contract_version": 11, "provenance": record}
assert store.config.to_payload() == before
assert adapter.synced == []
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index 157946f54..1f2a2de47 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -454,7 +454,7 @@ def test_hub_subscription_is_cross_backend_eligible_and_origin_unrestricted():
config.agents["codex"].sources.order = [source.id]
assert all(ModelHubConfig.source_eligible_for_backend(source, backend) for backend in ("claude", "codex", "opencode"))
- assert allowed_origins(source) == ("claude", "codex", "opencode")
+ assert allowed_origins(source) == ("claude", "codex", "opencode", "avibe")
resolution = resolve_model_hub_turn(config, "codex", "shared-model")
assert resolution.source is source
@@ -1033,8 +1033,8 @@ def test_runtime_preserves_reasoning_intent_across_provider_fallback(tmp_path, e
assert adapter.invocation_requests[1].headers == {"x-test": "preserved"}
started = [attempt for attempt in observed_attempts if attempt[4] is None]
assert [attempt[0] for attempt in started] == [first.id, second.id]
- assert started[0][6:] == ((), ())
- assert started[1][6:] == ((), ())
+ assert started[0][6:] == ((), (), None)
+ assert started[1][6:] == ((), (), None)
@pytest.mark.parametrize("payload", [
@@ -1705,7 +1705,7 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):
)
assert result["observation"] == {
- "contract_version": 10,
+ "contract_version": 11,
"outcome": "adapter_error",
"reachable": True,
"authenticated": "unknown",
@@ -1736,7 +1736,7 @@ def test_unknown_adapter_error_does_not_claim_connection(tmp_path):
assert exc.value.code == "discovery_failed"
assert exc.value.detail == "modelHub.errors.adapter_error"
assert exc.value.data["observation"] == {
- "contract_version": 10,
+ "contract_version": 11,
"outcome": "adapter_error",
"reachable": None,
"authenticated": "unknown",
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index 89d3b45a3..3f61526d2 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -1319,7 +1319,7 @@ def test_manifest_resolution_drives_admission_persistence_and_schema(
installer=manager,
state_store=EngineStateStore(tmp_path / "state"),
)
- projected = {"contract_version": 10, **supervisor.status()}
+ projected = {"contract_version": 11, **supervisor.status()}
schema = json.loads(
Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(
encoding="utf-8"
diff --git a/tests/test_model_hub_runtime_default_upgrade.py b/tests/test_model_hub_runtime_default_upgrade.py
index 52d5084a4..155681cf1 100644
--- a/tests/test_model_hub_runtime_default_upgrade.py
+++ b/tests/test_model_hub_runtime_default_upgrade.py
@@ -13,7 +13,14 @@ from unittest.mock import AsyncMock, Mock
import pytest
from config import v2_config
-from config.v2_config import MODEL_HUB_BACKENDS, ModelHubConfig, V2Config, update_config_fields
+from config.v2_config import ModelHubConfig, V2Config, update_config_fields
+
+
+EMPTY_AVIBE_SUPPLY = {
+ "backend": "avibe", "mode": "hub", "menu_kind": "fixed",
+ "sources": {"order": []}, "routes": {}, "menu": None,
+ "models": [], "removed_model_ids": [],
+}
def legacy_payload(tmp_path, *, enabled=False):
@@ -22,7 +29,8 @@ def legacy_payload(tmp_path, *, enabled=False):
payload = read_config(fixture_path)
payload["model_hub"].pop("runtime_default_applied")
payload["model_hub"]["enabled"] = enabled
- for backend in MODEL_HUB_BACKENDS:
+ payload["model_hub"]["agents"].pop("avibe")
+ for backend in ("claude", "codex", "opencode"):
payload["model_hub"]["agents"][backend]["mode"] = "direct"
# Synthetic state proves the upgrade does not clear credentials or change
# launch auth mode. No native credential stores are ever opened.
@@ -46,7 +54,9 @@ def read_config(path):
def assert_no_native_change(original, upgraded):
assert upgraded["agents"] == original["agents"]
- assert upgraded["model_hub"]["agents"] == original["model_hub"]["agents"]
+ assert upgraded["model_hub"]["agents"] == {
+ **original["model_hub"]["agents"], "avibe": EMPTY_AVIBE_SUPPLY,
+ }
assert upgraded["model_hub"]["sources"] == original["model_hub"]["sources"]
assert {key: value for key, value in upgraded.items() if key != "model_hub"} == {
key: value for key, value in original.items() if key != "model_hub"
@@ -132,8 +142,9 @@ def test_legacy_omissions_never_consent_to_native_takeover(tmp_path, shape):
assert loaded.load_warnings == ()
assert loaded.model_hub.enabled is True
assert loaded.model_hub.runtime_default_applied is True
- expected = {"claude": "hub", "codex": "direct", "opencode": "direct"} if shape == "missing-backend" else {
- name: "direct" for name in MODEL_HUB_BACKENDS
+ expected = {
+ "claude": "hub" if shape == "missing-backend" else "direct",
+ "codex": "direct", "opencode": "direct", "avibe": "hub",
}
assert {name: agent.mode for name, agent in loaded.model_hub.agents.items()} == expected
assert read_config(path)["agents"] == original["agents"]
@@ -153,7 +164,8 @@ def test_runtime_stop_after_upgrade_survives_subsequent_loads(tmp_path):
loaded = V2Config.load(config_path=path)
assert loaded.model_hub.enabled is False
assert loaded.model_hub.runtime_default_applied is True
- assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert all(loaded.model_hub.agents[backend].mode == "direct" for backend in ("claude", "codex", "opencode"))
+ assert loaded.model_hub.agents["avibe"].mode == "hub"
assert path.read_bytes() == persisted
assert len(list(path.parent.glob("config.json.bak-*"))) == 1
@@ -195,7 +207,9 @@ def test_service_runtime_stop_round_trips_real_store_with_fake_runtime(tmp_path,
assert loaded.model_hub.runtime_default_applied is True
assert path.read_bytes() == persisted
assert read_config(path)["agents"] == payload["agents"]
- assert read_config(path)["model_hub"]["agents"] == payload["model_hub"]["agents"]
+ assert read_config(path)["model_hub"]["agents"] == {
+ **payload["model_hub"]["agents"], "avibe": EMPTY_AVIBE_SUPPLY,
+ }
def test_new_explicit_stop_is_not_reinterpreted_as_old_default(tmp_path):
@@ -227,7 +241,8 @@ def test_invalid_marker_is_strict_and_disk_recovery_does_not_activate(tmp_path,
loaded = V2Config.load(config_path=path)
assert loaded.model_hub.enabled is False
- assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert all(loaded.model_hub.agents[backend].mode == "direct" for backend in ("claude", "codex", "opencode"))
+ assert loaded.model_hub.agents["avibe"].mode == "hub"
assert "model_hub" in loaded.recovered_sections
assert loaded.load_warnings
assert path.read_bytes() == original
@@ -247,7 +262,8 @@ def test_malformed_optional_section_is_not_upgraded_or_rewritten(tmp_path, bad_h
path, original = write_config(tmp_path, payload)
loaded = V2Config.load(config_path=path)
assert loaded.model_hub.enabled is False
- assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert all(loaded.model_hub.agents[backend].mode == "direct" for backend in ("claude", "codex", "opencode"))
+ assert loaded.model_hub.agents["avibe"].mode == "hub"
assert loaded.load_warnings and not loaded.whole_config_recovery
assert path.read_bytes() == original
@@ -259,7 +275,8 @@ def test_whole_config_recovery_does_not_apply_fresh_install_defaults(tmp_path, r
loaded = V2Config.load(config_path=path)
assert loaded.whole_config_recovery
assert loaded.model_hub.enabled is False
- assert all(agent.mode == "direct" for agent in loaded.model_hub.agents.values())
+ assert all(loaded.model_hub.agents[backend].mode == "direct" for backend in ("claude", "codex", "opencode"))
+ assert loaded.model_hub.agents["avibe"].mode == "hub"
assert loaded.load_warnings
assert path.read_bytes() == raw
diff --git a/tests/test_model_hub_source_probe.py b/tests/test_model_hub_source_probe.py
index 5dd72e830..fb61feb6a 100644
--- a/tests/test_model_hub_source_probe.py
+++ b/tests/test_model_hub_source_probe.py
@@ -51,7 +51,8 @@ def test_probe_invokes_selected_source_even_without_agent_routes_and_isolates_fa
async def scenario():
result = (await service.create_source(_draft(protocol=protocol)))["source"]
for agent in store.config.agents.values():
- agent.mode = "direct"
+ if agent.backend != "avibe":
+ agent.mode = "direct"
agent.sources.order = []
source_id = result["id"]
model_id = result["models"][0]["id"]
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 65584aa4c..7af6e8d06 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -1187,10 +1187,17 @@ def test_machine_error_field_access_has_one_extractor() -> None:
if path.name == "migration.py":
continue # its ``type`` field is an auth-record kind, not an error code
tree = _tree(path)
+ # Request history discriminates content blocks, not error envelopes.
+ # Exempt only that function's type reads; code reads and the rest of
+ # request.py remain subject to the extraction-owner guard.
+ history = _functions(tree).get("_plain_history") if path.name == "request.py" else None
+ history_nodes = set(ast.walk(history)) if history is not None else set()
for node in ast.walk(tree):
if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
continue
if node.func.attr == "get" and node.args and isinstance(node.args[0], ast.Constant):
+ if node in history_nodes and node.args[0].value == "type":
+ continue
assert node.args[0].value not in {"type", "code"}, (path, node.lineno)
diff --git a/tests/test_native_login_single_flight.py b/tests/test_native_login_single_flight.py
index f64253570..f72d3a447 100644
--- a/tests/test_native_login_single_flight.py
+++ b/tests/test_native_login_single_flight.py
@@ -46,8 +46,8 @@ def _direct_native_auth_config(monkeypatch, tmp_path) -> None:
home = tmp_path / "avibe-home"
monkeypatch.setenv("AVIBE_HOME", str(home))
config = V2Config.default()
- for agent in config.model_hub.agents.values():
- agent.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ config.model_hub.agents[backend].mode = "direct"
config.save(config_path=home / "config" / "config.json")
diff --git a/tests/test_native_takeover_lifecycle.py b/tests/test_native_takeover_lifecycle.py
index 7925f1749..38ce1f72a 100644
--- a/tests/test_native_takeover_lifecycle.py
+++ b/tests/test_native_takeover_lifecycle.py
@@ -581,8 +581,8 @@ def auth_service(monkeypatch):
from config.v2_config import V2Config
config = V2Config.default()
- for supply in config.model_hub.agents.values():
- supply.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ config.model_hub.agents[backend].mode = "direct"
config.save()
monkeypatch.setattr(AgentAuthService, "_recover_interrupted_claude_oauth_settings_backup", lambda self: None)
return AgentAuthService(SimpleNamespace(config=SimpleNamespace()))
diff --git a/tests/test_native_writer_custody.py b/tests/test_native_writer_custody.py
index 4526b42b2..c3e0cc291 100644
--- a/tests/test_native_writer_custody.py
+++ b/tests/test_native_writer_custody.py
@@ -39,8 +39,8 @@ def no_live_operations(monkeypatch):
def saved_config(*, mode="hub", enabled=True, source=None):
config = V2Config.default()
config.model_hub.enabled = enabled
- for supply in config.model_hub.agents.values():
- supply.mode = mode
+ for backend in ("claude", "codex", "opencode"):
+ config.model_hub.agents[backend].mode = mode
if source is not None:
config.model_hub.sources = [source]
config.save()
diff --git a/tests/test_settings_disk_fallback.py b/tests/test_settings_disk_fallback.py
index 8781e8e41..63da12286 100644
--- a/tests/test_settings_disk_fallback.py
+++ b/tests/test_settings_disk_fallback.py
@@ -35,8 +35,8 @@ def _direct_config(**kwargs):
from config.v2_config import V2Config
config = V2Config(**kwargs) if kwargs else V2Config.default()
- for supply in config.model_hub.agents.values():
- supply.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ config.model_hub.agents[backend].mode = "direct"
return config
diff --git a/tests/test_web_oauth_flow.py b/tests/test_web_oauth_flow.py
index 4ec967816..f041cf4ce 100644
--- a/tests/test_web_oauth_flow.py
+++ b/tests/test_web_oauth_flow.py
@@ -44,8 +44,8 @@ def _direct_config():
from config.v2_config import V2Config
config = V2Config.default()
- for supply in config.model_hub.agents.values():
- supply.mode = "direct"
+ for backend in ("claude", "codex", "opencode"):
+ config.model_hub.agents[backend].mode = "direct"
return config
diff --git a/ui/e2e/model-catalog/gatewayFixture.tsx b/ui/e2e/model-catalog/gatewayFixture.tsx
index fa777a9c4..2a4b7dc47 100644
--- a/ui/e2e/model-catalog/gatewayFixture.tsx
+++ b/ui/e2e/model-catalog/gatewayFixture.tsx
@@ -35,13 +35,13 @@ export function GatewayFixture() {
}],
};
const chains = Object.fromEntries(ids.map((model_id, index) => [modelChainKey(backend, model_id), readyRegion<AgentChain>({
- contract_version: 10, backend, model_id, route_origin: origins[index],
+ contract_version: 11, backend, model_id, route_origin: origins[index],
manual_override: origins[index] === 'manual' ? { hops: [{ source_id: source.id, model_id }] } : null,
current: { source_id: source.id, model_id }, supply_state: 'ok',
chain: [{ source_id: source.id, model_id, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],
})]));
const runtime = freshRuntimeProjection(readyRegion({
- contract_version: 10,
+ contract_version: 11,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },
}));
diff --git a/ui/e2e/model-catalog/routeFixture.tsx b/ui/e2e/model-catalog/routeFixture.tsx
index 132bda5ff..d207e015d 100644
--- a/ui/e2e/model-catalog/routeFixture.tsx
+++ b/ui/e2e/model-catalog/routeFixture.tsx
@@ -28,7 +28,7 @@ const supply: AgentSupply = {
sources: { order: sources.map((source) => source.id), eligibility: sources.map((source) => ({ source_id: source.id, eligible: true })) },
};
const makeChain = (hops: RouteHop[], manual: boolean): AgentChain => ({
- contract_version: 10, backend, model_id: modelId,
+ contract_version: 11, backend, model_id: modelId,
manual_override: manual ? { hops } : null,
route_origin: manual ? 'manual' : origin === 'passthrough' ? 'passthrough' : 'automatic',
current: hops[0] ?? null, supply_state: hops.length ? 'ok' : 'interrupted',
diff --git a/ui/e2e/model-routing-origin.spec.ts b/ui/e2e/model-routing-origin.spec.ts
index 7c03bd8d6..a986e549f 100644
--- a/ui/e2e/model-routing-origin.spec.ts
+++ b/ui/e2e/model-routing-origin.spec.ts
@@ -39,7 +39,7 @@ test('MH-ROUTING-007 follow-defaults switch, undo, cancel, and save preserve exp
expect(response.request().postDataJSON()).toEqual({ manual_override: null });
const body = await response.json() as { ok: boolean; contract_version: number; chain: AgentChain };
expect(body.ok).toBe(true);
- expect(body.contract_version).toBe(10);
+ expect(body.contract_version).toBe(11);
expect(body.chain.manual_override).toBeNull();
expect(body.chain.route_origin).toBe(inherited.route_origin);
expect(identities(body.chain)).toEqual(identities(inherited));
@@ -102,7 +102,7 @@ test('MH-ROUTING-007 follow-defaults switch, undo, cancel, and save preserve exp
would_remove_hops: [{ backend: gateway.backend, menu_model: gateway.model, ...manual.hops[0], position: 1 }],
would_interrupt: [],
};
- expect(await refused.json()).toMatchObject({ ok: false, contract_version: 10, error: 'source_in_route_chain', ...plan });
+ expect(await refused.json()).toMatchObject({ ok: false, contract_version: 11, error: 'source_in_route_chain', ...plan });
expect((await api.agentChain(gateway.backend, gateway.model)).manual_override).toEqual(manual);
// The one question is its own modal over the chain the user was editing.
const guard = hub.dialogTitled(copy('guard.title.saveRoute', { menuModel: gateway.model }));
diff --git a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts
index b31ee308e..5c9f4bff5 100644
--- a/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts
+++ b/ui/e2e/onboarding-fidelity/hub-ownership.spec.ts
@@ -92,7 +92,7 @@ for (const width of [1200, 390]) {
if (path === '/api/models/runtime/status') return answer({
ok: true,
runtime: {
- contract_version: 10, enabled: true, host_platform: 'linux',
+ contract_version: 11, enabled: true, host_platform: 'linux',
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'a'.repeat(40), assets: [] },
status: { installed_version: 'fixture', verified: true, health: 'ok' },
},
diff --git a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts
index 9e80cb2da..bbd708ac7 100644
--- a/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts
+++ b/ui/e2e/onboarding-fidelity/pm-main-flow.spec.ts
@@ -18,7 +18,7 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] as
const config=()=>({version:'v2',mode:'self_host',setup_completed:completed,setup_state:{needs_setup:!completed},capabilities:{model_hub:{enabled:true}},platforms:{primary:'slack',enabled:[]},runtime:{},agents:Object.fromEntries(['claude','codex','opencode'].map(b=>[b,{enabled:b!=='opencode',cli_path:b}])),agent:{default_cwd:'/fixture/work'},model_hub:{enabled:true,runtime_default_applied:true}});
const source={id:'src_fixture',kind:'api_key',vendor:'openai',display_name:'Fixture source',protocol:'openai_chat',supply_channel:'hub',billing:'metered',state:{status:'active'},masked_credential:'fixture-only',models:hops.map(h=>({id:h.model_id,display_name:h.model_id==='gpt-5'?'GPT-5':undefined,origin:'discovered',reasoning_efforts:[],reasoning_efforts_source:null})),last_discovered_at:null};
const supply=(b:string)=>({backend:b,cli_present:true,mode:'hub',menu_kind:'fixed',sources:{order:[source.id],eligibility:[{source_id:source.id,eligible:true}]},routes:{},builtin_models:[],catalog_models:[],menu:null,model_supply:[],named_agents:[{name:b,effective_model_id:agent(b).model,supply_status:saved[b].length?'ok':'unavailable'}],supply_status:saved[b].length?'ok':'unavailable'});
- const chain=(b:string,hs=saved[b])=>({contract_version:10,backend:b,model_id:agent(b).model,manual_override:hs.length?{hops:hs}:null,route_origin:hs.length?'manual':'automatic',current:hs[0]??null,chain:hs.map(h=>({...h,channel:'hub',health:'healthy',runnable:true,reason:null,retry_at:null})),supply_state:hs.length?'ok':'unavailable'});
+ const chain=(b:string,hs=saved[b])=>({contract_version:11,backend:b,model_id:agent(b).model,manual_override:hs.length?{hops:hs}:null,route_origin:hs.length?'manual':'automatic',current:hs[0]??null,chain:hs.map(h=>({...h,channel:'hub',health:'healthy',runnable:true,reason:null,retry_at:null})),supply_state:hs.length?'ok':'unavailable'});
await page.addInitScript(()=>localStorage.setItem('i18nextLng','en'));
await page.route(`${ORIGIN}/api/**`,async route=>{
const req=route.request(),path=new URL(req.url()).pathname;
@@ -34,7 +34,7 @@ for (const [width,chosen] of [[1200,"claude"],[390,"claude"],[1200,"codex"]] as
}
if(path==='/api/agents')return answer({ok:true,default_agent_name:defaultName,agents:[agent('claude'),agent('codex')]});
if(/^\/api\/agents\/(claude|codex)$/.test(path))return answer({ok:true,agent:agent(path.split('/').at(-1)!),default_agent_name:defaultName});
- if(path==='/api/models/runtime/status')return answer({ok:true,runtime:{contract_version:10,enabled:true,host_platform:'linux',manifest:{name:'cliproxyapi',resolution:'resolved',version:'fixture',source_sha:'a'.repeat(40),assets:[]},status:{installed_version:'fixture',verified:true,health:'ok'}}});
+ if(path==='/api/models/runtime/status')return answer({ok:true,runtime:{contract_version:11,enabled:true,host_platform:'linux',manifest:{name:'cliproxyapi',resolution:'resolved',version:'fixture',source_sha:'a'.repeat(40),assets:[]},status:{installed_version:'fixture',verified:true,health:'ok'}}});
if(path==='/api/models/sources')return answer({ok:true,sources:[source]});
if(path==='/api/models/agents')return answer({ok:true,agents:[supply('claude'),supply('codex')]});
if(/\/api\/models\/agents\/(claude|codex)\/chains$/.test(path)){
diff --git a/ui/e2e/onboarding-fidelity/provider-support.ts b/ui/e2e/onboarding-fidelity/provider-support.ts
index 1d84c92bf..230ef1215 100644
--- a/ui/e2e/onboarding-fidelity/provider-support.ts
+++ b/ui/e2e/onboarding-fidelity/provider-support.ts
@@ -129,7 +129,7 @@ const CONFIG = {
/** Installed, verified and serving: the screen's `gatewayIntent` reads `running` and
* starts no install, which is the state every proof below is about something else. */
const RUNTIME = {
- contract_version: 10,
+ contract_version: 11,
enabled: true,
host_platform: 'darwin',
manifest: {
diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.ts
index fec47b15c..df3fceac7 100644
--- a/ui/e2e/onboarding-fidelity/support.ts
+++ b/ui/e2e/onboarding-fidelity/support.ts
@@ -84,7 +84,7 @@ export async function serveProduct(page: Page) {
const backend = new URL(route.request().url()).pathname.split('/')[4];
return route.fulfill({ json: { ok: true, agent: { backend, mode: 'direct', sources: { order: [], eligibility: [] }, routes: {}, builtin_models: [], catalog_models: [], named_agents: [], menu: null, model_supply: [], supply_status: 'unavailable' } } });
});
- await page.route('**/api/models/runtime/status', (route) => route.fulfill({ json: { ok: true, runtime: { contract_version: 10, enabled: true, host_platform: 'linux', manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', assets: [] }, status: { installed_version: 'fixture', verified: true, health: 'ok' } } } }));
+ await page.route('**/api/models/runtime/status', (route) => route.fulfill({ json: { ok: true, runtime: { contract_version: 11, enabled: true, host_platform: 'linux', manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', assets: [] }, status: { installed_version: 'fixture', verified: true, health: 'ok' } } } }));
await page.route(`${ORIGIN}/status`, (route) => route.fulfill({ json: { state: 'running' } }));
await page.route('**/api/backend/*/connection', (route) => route.fulfill({ json: { ok: true, backend: new URL(route.request().url()).pathname.split('/').at(-2), installed: true, enabled: true, auth: 'none', application: 'applied', ready: false, entry_eligible: false } }));
await page.route('**/api/config', (route) => route.fulfill({ json: CONFIG }));
diff --git a/ui/e2e/support/api.ts b/ui/e2e/support/api.ts
index ce24de00e..b8bcc9bf3 100644
--- a/ui/e2e/support/api.ts
+++ b/ui/e2e/support/api.ts
@@ -355,7 +355,7 @@ export class HubApi {
const payload = await this.read<{ ok: boolean; contract_version: number; provenance: RecordedTurn | null }>(
`/api/models/agents/${backend}/provenance?model=${encodeURIComponent(model)}`,
);
- if (payload.ok !== true || payload.contract_version !== 10 || !('provenance' in payload)) {
+ if (payload.ok !== true || payload.contract_version !== 11 || !('provenance' in payload)) {
throw new Error('Latest recorded turn did not use the v10 provenance envelope');
}
return payload.provenance;
diff --git a/ui/e2e/workbench-general/geometry.spec.ts b/ui/e2e/workbench-general/geometry.spec.ts
index 42dfde07b..f8ccb2244 100644
--- a/ui/e2e/workbench-general/geometry.spec.ts
+++ b/ui/e2e/workbench-general/geometry.spec.ts
@@ -48,7 +48,7 @@ const MODEL_HUB_AGENT = {
};
const MODEL_HUB_RUNTIME = {
- contract_version: 10,
+ contract_version: 11,
enabled: true,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'f'.repeat(40), assets: [] },
status: { installed_version: 'fixture', verified: true, listening: { host: '127.0.0.1', port: 43123 }, health: 'ok' },
diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsx
index 27df2b283..e50b42723 100644
--- a/ui/src/components/onboarding/AssistantSetup.test.tsx
+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx
@@ -47,7 +47,7 @@ const hubAgent = (enabled = true) => ({
system_prompt: null, created_at: '', metadata: { builtin_default: true },
});
const hubChain = (modelId: string) => ({
- contract_version: 10, backend: 'claude', model_id: 'opus-5',
+ contract_version: 11, backend: 'claude', model_id: 'opus-5',
manual_override: { hops: [{ source_id: 'src_a', model_id: modelId }] },
route_origin: 'manual', current: { source_id: 'src_a', model_id: modelId },
chain: [{ source_id: 'src_a', model_id: modelId, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],
@@ -330,7 +330,7 @@ describe('assistant installation presentation', () => {
mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });
mock.models.listSources.mockResolvedValue([]);
const chain = {
- contract_version: 10, backend: 'claude', model_id: 'opus-5',
+ contract_version: 11, backend: 'claude', model_id: 'opus-5',
manual_override: { hops: [{ source_id: 'src_a', model_id: 'opus-5' }, { source_id: 'src_b', model_id: 'opus-5' }] },
route_origin: 'manual', current: { source_id: 'src_a', model_id: 'opus-5' },
chain: [
diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx
index 3e39aa1d0..0fde4060b 100644
--- a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx
+++ b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx
@@ -29,7 +29,7 @@ import {
import { providerBrandLabel } from '@/components/settings/providers/providerIdentity';
import { isMigrationDismissed, writeMigrationDismissed } from '@/lib/modelHubMigrationDismiss';
import type {
- AgentBackend,
+ NativeCliBackend,
AgentSupply,
MigrationItem,
RuntimeDependency,
@@ -79,7 +79,7 @@ const supply = (over: Partial<AgentSupply> & { backend: AgentSupply['backend'] }
});
const runtimeOf = (health: RuntimeHealth, over: Partial<RuntimeDependency> = {}): RuntimeDependency => ({
- contract_version: 10,
+ contract_version: 11,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },
status: { verified: true, health },
...over,
@@ -1109,8 +1109,8 @@ describe('ProvidersScreen — what an import leaves behind', () => {
});
it('clears only the identities in a linked group when its card is explicitly selected', async () => {
- const linkedA = { ...CODEX_KEY, required_backends: ['codex', 'opencode'] as AgentBackend[] };
- const linkedB = { ...OPENCODE_KEY, required_backends: ['codex', 'opencode'] as AgentBackend[] };
+ const linkedA = { ...CODEX_KEY, required_backends: ['codex', 'opencode'] as NativeCliBackend[] };
+ const linkedB = { ...OPENCODE_KEY, required_backends: ['codex', 'opencode'] as NativeCliBackend[] };
serve({ scan: [linkedA, linkedB] });
writeMigrationDismissed([linkedA, linkedB]);
renderScreen();
diff --git a/ui/src/components/onboarding/providers/gatewayBootstrap.ts b/ui/src/components/onboarding/providers/gatewayBootstrap.ts
index 01a42d243..5a09cb6b3 100644
--- a/ui/src/components/onboarding/providers/gatewayBootstrap.ts
+++ b/ui/src/components/onboarding/providers/gatewayBootstrap.ts
@@ -20,7 +20,7 @@
// `_recover_runtime_owners()` with the installer admission that belongs on the
// server. This observes that outcome; asking for a second unconditional install
// would race the recovery that is still finishing.
-import type { AgentBackend, RuntimeDependency } from '@/components/settings/models/types';
+import type { NativeCliBackend, RuntimeDependency } from '@/components/settings/models/types';
import type { BackendConnectionState } from '@/context/ApiContext';
import {
errorDetail,
@@ -68,7 +68,7 @@ const isRecord = (value: unknown): value is Record<string, unknown> =>
export type GatewayBootstrapDeps = {
/** The CSRF-aware `apiFetch`, injected so the sequence is testable as itself. */
fetch: (input: string, init?: RequestInit) => Promise<Response>;
- getBackendConnection: (backend: AgentBackend) => Promise<BackendConnectionState>;
+ getBackendConnection: (backend: NativeCliBackend) => Promise<BackendConnectionState>;
/** `useStatus().control`, which already rejects a non-2xx response. */
control: (action: string) => Promise<unknown>;
getRuntimeStatus: () => Promise<RuntimeDependency>;
@@ -83,7 +83,7 @@ export type GatewayBootstrapResult = { config: SetupConfigSnapshot; runtime: Run
*/
export async function bootstrapGateway(
deps: GatewayBootstrapDeps,
- backend: AgentBackend,
+ backend: NativeCliBackend,
): Promise<GatewayBootstrapResult> {
// 1. Seed, exactly once. A definitive refusal throws from inside it; anything else
// leaves a write to account for, and accounting for a write is reading.
@@ -226,7 +226,7 @@ async function seedConfig(deps: GatewayBootstrapDeps): Promise<GatewayBootstrapE
async function readConnection(
deps: GatewayBootstrapDeps,
- backend: AgentBackend,
+ backend: NativeCliBackend,
): Promise<BackendConnectionState> {
let connection: BackendConnectionState;
try {
diff --git a/ui/src/components/onboarding/providers/providerStage.test.ts b/ui/src/components/onboarding/providers/providerStage.test.ts
index 0b67c8e67..b24869d6d 100644
--- a/ui/src/components/onboarding/providers/providerStage.test.ts
+++ b/ui/src/components/onboarding/providers/providerStage.test.ts
@@ -660,7 +660,7 @@ describe('adoptionBackend', () => {
});
const runtime = (health: RuntimeHealth, over: Partial<RuntimeDependency> = {}): RuntimeDependency => ({
- contract_version: 10,
+ contract_version: 11,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },
status: { verified: true, health },
...over,
diff --git a/ui/src/components/settings/models/AgentCard.test.tsx b/ui/src/components/settings/models/AgentCard.test.tsx
index 14aa9fa62..80d47be11 100644
--- a/ui/src/components/settings/models/AgentCard.test.tsx
+++ b/ui/src/components/settings/models/AgentCard.test.tsx
@@ -16,7 +16,7 @@ import { freshRuntimeProjection } from './runtimeLifecycle';
import type { AgentSupply, RuntimeDependency, Source } from './types';
const runtime: RuntimeDependency = {
- contract_version: 10,
+ contract_version: 11,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },
};
@@ -374,7 +374,7 @@ describe('AgentCard', () => {
['zh', 'Backup → claude-opus-4-6(已自动切换)', '打开 claude-opus-4-6 的路由 · Backup → claude-opus-4-6(已自动切换)'],
] as const)('derives and announces takeover from the exact current hop in %s', (lng, mappingCopy, accessibleName) => {
const key = modelChainKey('claude', 'claude-opus-4-6');
- render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 10, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={localeInstance(lng)}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 11, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.getByText(/Backup/)).toBeTruthy();
expect(screen.getByTitle(mappingCopy)).toBeTruthy();
expect(screen.getByRole('button', { name: accessibleName })).toBeTruthy();
@@ -394,7 +394,7 @@ describe('AgentCard', () => {
sources={[source('src_b', 'Backup source')]}
chains={{
[key]: readyRegion({ manual_override: {hops:[{source_id:'src_b',model_id:'routed-opus'}]}, route_origin: "manual" as const,
- contract_version: 10,
+ contract_version: 11,
backend: 'claude',
model_id: 'claude-opus-4-6',
current: { source_id: 'src_b', model_id: 'routed-opus' },
@@ -427,7 +427,7 @@ describe('AgentCard', () => {
it('does not call a later current hop takeover unless the head is unavailable for cooldown', () => {
const key = modelChainKey('claude', 'claude-opus-4-6');
- render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 10, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 11, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'native_cli', health: 'healthy', runnable: false, reason: 'native_cli_unavailable', retry_at: null }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.getByText(/Backup/)).toBeTruthy();
expect(screen.queryByText(/takeover/i)).toBeNull();
});
@@ -435,7 +435,7 @@ describe('AgentCard', () => {
it('hides current and takeover projections while the runtime is stopped', () => {
const key = modelChainKey('claude', 'claude-opus-4-6');
const stopped = { ...runtime, status: { ...runtime.status, health: 'down' as const } };
- render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 10, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><RuntimeAgentCard runtime={freshRuntimeProjection(readyRegion(stopped))} agents={[hubAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 11, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={vi.fn()} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.queryByText(/Backup/)).toBeNull();
expect(screen.queryByText(/takeover/i)).toBeNull();
@@ -447,7 +447,7 @@ describe('AgentCard', () => {
const onOpenModels = vi.fn();
const key = modelChainKey('claude', 'claude-opus-4-6');
const directAgent: AgentSupply = { ...hubAgent, mode: 'direct', sources: null, routes: null, supply_status: null, model_supply: null };
- render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 10, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
+ render(<I18nextProvider i18n={i18n}><AgentCard agents={[directAgent]} sources={[source('src_a', 'Primary'), source('src_b', 'Backup')]} chains={{ [key]: readyRegion({ manual_override: {hops:[{source_id:'src_a',model_id:'claude-opus-4-6'},{source_id:'src_b',model_id:'claude-opus-4-6'}]}, route_origin: "manual" as const, contract_version: 11, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);
expect(screen.queryByText(/Adjust priority/i)).toBeNull();
expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();
expect(screen.queryByText(/Backup/)).toBeNull();
diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx
index def27aaf2..07d7bdb8a 100644
--- a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx
+++ b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx
@@ -34,7 +34,7 @@ const CLAUDE_KEY: MigrationItem = {
};
const RUNTIME: RuntimeDependency = {
- contract_version: 10,
+ contract_version: 11,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },
status: { installed_version: '1', verified: true, health: 'ok' },
};
diff --git a/ui/src/components/settings/models/MigrationDialog.tsx b/ui/src/components/settings/models/MigrationDialog.tsx
index 7a665d8c5..c2dc5e8f9 100644
--- a/ui/src/components/settings/models/MigrationDialog.tsx
+++ b/ui/src/components/settings/models/MigrationDialog.tsx
@@ -32,7 +32,7 @@ import { apiFailure, modelsApi } from './modelsApi';
import { serverText } from './serverCopy';
import { VendorGlyph } from './vendorGlyph';
import { ACCENT_ICON, ACCENT_TILE, type Accent } from './vendorMeta';
-import type { AgentBackend, MigrationItem } from './types';
+import type { AgentBackend, MigrationItem, NativeCliBackend } from './types';
// Older payloads cannot identify the exact file or store. Name only the
// backend's configuration when the server supplies no file locators.
@@ -40,7 +40,7 @@ const SOURCE_KEY = {
claude: 'settings.models.migration.source.claude',
codex: 'settings.models.migration.source.codex',
opencode: 'settings.models.migration.source.opencode',
-} as const satisfies Record<AgentBackend, TranslationKey>;
+} as const satisfies Record<NativeCliBackend, TranslationKey>;
const sourcePaths = (item: MigrationItem): string[] => [...new Set(item.source_paths ?? [])];
diff --git a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx
index 986294eae..d3dd1136f 100644
--- a/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsx
@@ -17,7 +17,7 @@ const sources: Source[] = ['a', 'b'].map((id) => ({
}));
const hops = sources.map((source) => ({ source_id: source.id, model_id: 'gpt-test' }));
const makeChain = (backend: AgentSupply['backend'], routeOrigin: 'automatic' | 'passthrough' | 'manual'): AgentChain => ({
- contract_version: 10, backend, model_id: 'gpt-test', route_origin: routeOrigin,
+ contract_version: 11, backend, model_id: 'gpt-test', route_origin: routeOrigin,
manual_override: routeOrigin === 'manual' ? { hops } : null,
current: hops[0], supply_state: 'ok',
chain: hops.map((hop) => ({ ...hop, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null })),
diff --git a/ui/src/components/settings/models/RouteChainDialog.test.tsx b/ui/src/components/settings/models/RouteChainDialog.test.tsx
index 6365d3783..d9f4d7b82 100644
--- a/ui/src/components/settings/models/RouteChainDialog.test.tsx
+++ b/ui/src/components/settings/models/RouteChainDialog.test.tsx
@@ -57,7 +57,7 @@ const sources: Source[] = [
},
];
const chain: AgentChain = { manual_override: {hops:[{source_id:"src_a",model_id:"claude-opus-5"},{source_id:"src_b",model_id:"opus-5"}]}, route_origin: "manual" as const,
- contract_version: 10,
+ contract_version: 11,
backend: "claude",
model_id: "opus-5",
current: { source_id: "src_b", model_id: "opus-5" },
diff --git a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
index a23392323..4dee8c726 100644
--- a/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
+++ b/ui/src/components/settings/models/RouteRecordedTurn.test.tsx
@@ -15,7 +15,7 @@ import { PERSISTED_TURN_CONTRACT_VERSIONS } from './types';
import type { RouteHop, TurnProvenance } from './types';
const record: TurnProvenance = {
- contract_version: 10, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',
+ contract_version: 11, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',
outcome: 'failed_terminal', failed_attempts: [], served: null, canceled_attempt: null, model_supply_state: null, blockers: [],
terminal_error: { source_id: 'src_historical', configured_model_id: 'historical-model', channel: 'hub', reason: 'invalid_parameter', stream_started: false, http_status: 404, upstream_error_code: 'model_not_found' },
};
diff --git a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
index 6ff7e69ee..90176016a 100644
--- a/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
+++ b/ui/src/components/settings/models/RuntimeNotStartedAction.test.tsx
@@ -31,7 +31,7 @@ const runtime = (
? 'unresolved' as const
: hostPlatform === 'linux-amd64' ? 'unsupported' as const : 'resolved' as const;
return {
- contract_version: 10,
+ contract_version: 11,
...(hostPlatform === undefined ? {} : { host_platform: hostPlatform }),
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
index 76c1d8ad2..a38444214 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx
@@ -35,6 +35,10 @@ const directAgent = (backend: AgentBackend): AgentSupply => ({
menu_kind: backend === 'opencode' ? 'open' : 'fixed',
});
+const emptyAvibeAgent: AgentSupply = {
+ backend: 'avibe', cli_present: false, mode: 'hub', menu_kind: 'fixed', catalog_models: [],
+};
+
// Named separately from `runtime` so it keeps the arm of `RuntimeManifest` it
// was written as. Reached through `runtime.manifest` it is the whole union, and
// re-resolving a spread of that lands on the `unresolved` arm, which carries no
@@ -44,7 +48,7 @@ const manifest = {
} satisfies RuntimeManifest;
const runtime: RuntimeDependency = {
- contract_version: 10,
+ contract_version: 11,
manifest,
status: { installed_version: '1', verified: true, health: 'ok' },
};
@@ -115,7 +119,7 @@ const takeoverAgent: AgentSupply = {
};
const takeoverChain: AgentChain = { manual_override: {hops:[{source_id:'src_head',model_id:'gpt-5.6-sol'},{source_id:'src_relay',model_id:'gpt-5.6-sol'}]}, route_origin: "manual" as const,
- contract_version: 10,
+ contract_version: 11,
backend: 'codex',
model_id: 'gpt-5.6-sol',
current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },
@@ -218,7 +222,7 @@ const routedHubAgent: AgentSupply = {
const routedChain: AgentChain = {
manual_override: { hops: [{ source_id: retainedSource.id, model_id: routedModelId }] },
route_origin: 'manual' as const,
- contract_version: 10,
+ contract_version: 11,
backend: 'claude',
model_id: routedModelId,
current: { source_id: retainedSource.id, model_id: routedModelId },
@@ -263,6 +267,7 @@ const renderPage = (
directAgent('claude'),
directAgent('codex'),
directAgent('opencode'),
+ emptyAvibeAgent,
]);
vi.spyOn(modelsApi, 'getRuntimeStatus').mockResolvedValue(runtimeValue);
vi.spyOn(modelsApi, 'listEvents').mockResolvedValue([]);
@@ -911,6 +916,35 @@ describe('SettingsModelsPage surface branches', () => {
expect(await screen.findByText('Retained source')).toBeTruthy();
});
+ // Upgrades always return an empty Avibe row. Existing native-only responses
+ // missed both the lost Direct landing and the unusable runtime Stop control.
+ it.each([false, true])('MH-AVIBE-003 derives runtime use from Avibe catalog presence: %s', async (configured) => {
+ const catalogModel: BackendModel = {
+ id: 'menu-alias', display_name: null, origin: 'manual', models_dev_id: null,
+ context_window: null, max_output_tokens: null, input_modalities: [], output_modalities: [],
+ supports_tools: null, supports_reasoning: null, reasoning_efforts: [], locked: false, routeable: true,
+ };
+ renderPage([], [
+ directAgent('claude'), directAgent('codex'), directAgent('opencode'),
+ { ...emptyAvibeAgent, catalog_models: configured ? [catalogModel] : [] },
+ ]);
+ const stop = vi.spyOn(modelsApi, 'stopRuntime').mockResolvedValue({ ...runtime, enabled: false });
+ const toggle = await screen.findByRole('switch', {
+ name: configured ? /Avibe models use|Avibe 的模型通过/i : /Turn model gateway off|关闭模型网关/i,
+ });
+ expect((toggle as HTMLButtonElement).disabled).toBe(configured);
+ if (configured) {
+ expect(screen.queryByText(/^All 3 backends are direct$|^3 个后端均为直连$/i)).toBeNull();
+ await userEvent.click(toggle);
+ expect(stop).not.toHaveBeenCalled();
+ } else {
+ expect(await screen.findByText(/^All 3 backends are direct$|^3 个后端均为直连$/i)).toBeTruthy();
+ expect(screen.getAllByRole('button', { name: /^Switch to Gateway$|^切换到模型网关$/i })).toHaveLength(3);
+ await userEvent.click(toggle);
+ await waitFor(() => expect(stop).toHaveBeenCalledOnce());
+ }
+ });
+
it('renders Frame 01 with tabs when retained sources remain under all-direct backends', async () => {
renderPage([retainedSource]);
diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsx
index e9cdba388..bb5773f4e 100644
--- a/ui/src/components/settings/models/SettingsModelsPage.tsx
+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx
@@ -24,7 +24,7 @@ import { routeChainMatchesAttempt } from './routeChainDraft';
import { SourceDetailPanel } from './SourceDetailPanel';
import { SourceOrderDrawer } from './SourceOrderDrawer';
import { SourcesCard } from './SourcesCard';
-import { modelsSurfaceKindFromReads } from './modelHubSurfaceState';
+import { agentUsesHubRuntime, modelsSurfaceKindFromReads } from './modelHubSurfaceState';
import { focusDialogReturn, focusModelHubProjection } from './modelHubFocus';
import { MODEL_HUB_MANAGE_PARAM } from './modelHubRoutes';
import { buildSupplyRelations } from './supplyRelations';
@@ -73,7 +73,7 @@ import { groupMigrationCandidates } from './migrationGrouping';
import { SUBSCRIPTION_MENU_ROWS } from './subscriptionOptions';
import { VendorGlyph } from './vendorGlyph';
import { backendVisual } from './vendorMeta';
-import { USAGE_DEFAULT_WINDOW, type AgentBackend, type AgentMode, type AgentSupply, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageReport, type UsageWindowKey } from './types';
+import { USAGE_DEFAULT_WINDOW, type AgentBackend, type AgentMode, type AgentSupply, type NativeCliBackend, type ResolutionEvent, type QuotaSummary, type RuntimeDependency, type Source, type UsageReport, type UsageWindowKey } from './types';
const CHAIN_READ_CONCURRENCY = 6;
const EVENT_PAGE = 20;
@@ -346,7 +346,7 @@ const HubTabs: React.FC<{ tab: HubTab; onChange: (tab: HubTab) => void }> = ({ t
};
const DirectHome: React.FC<{
- agents: AgentSupply[];
+ agents: (AgentSupply & { backend: NativeCliBackend })[];
switchFailures: ReadonlySet<string>;
connectingBackend: string | null;
onSwitch: (agent: AgentSupply) => void;
@@ -1155,8 +1155,10 @@ export const SettingsModelsPage: React.FC = () => {
? failRegionRead(supplyRead)
: supplyRead;
const directEmpty = modelsSurfaceKindFromReads(supplyDisplayRead, sourcesDisplayRead) === 'direct_empty';
- const installedAgents = agents.filter((agent) => agent.cli_present);
- const hubBackends = agents.filter((agent) => agent.mode === 'hub').map((agent) => agent.backend);
+ const installedAgents = agents.filter(
+ (agent): agent is AgentSupply & { backend: NativeCliBackend } => agent.backend !== 'avibe' && agent.cli_present,
+ );
+ const hubBackends = agents.filter(agentUsesHubRuntime).map((agent) => agent.backend);
const activeBackends = supplyRead.kind === 'ready' ? new Set(hubBackends) : undefined;
const stopBlocked = runtimeEnabled && (supplyRead.kind !== 'ready' || hubBackends.length > 0);
const runtimeSwitchUnsupported = !runtimeEnabled
@@ -1170,7 +1172,9 @@ export const SettingsModelsPage: React.FC = () => {
|| stopBlocked;
const runtimeSwitchLabel = stopBlocked
? supplyRead.kind === 'ready'
- ? t('settings.models.shell.toggle.stopBlocked', { names: hubBackends.join(', ') })
+ ? hubBackends.includes('avibe')
+ ? t('settings.models.shell.toggle.stopAvibeBlocked')
+ : t('settings.models.shell.toggle.stopBlocked', { names: hubBackends.join(', ') })
: t('settings.models.shell.toggle.stopUnavailable')
: runtimeEnabled
? t('settings.models.shell.toggle.turnOff')
diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.ts
index 410fc8761..a2e1df5b3 100644
--- a/ui/src/components/settings/models/SupplyGraph.test.ts
+++ b/ui/src/components/settings/models/SupplyGraph.test.ts
@@ -7,7 +7,7 @@ import { buildSupplyRelations as buildRelations } from './supplyRelations';
import type { AgentChain, AgentSupply, RuntimeDependency, Source } from './types';
const runtime: RuntimeDependency = {
- contract_version: 10,
+ contract_version: 11,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'fixture', assets: [] },
status: { installed_version: '1.0.0', verified: true, listening: null, health: 'ok', last_check: null },
};
@@ -47,7 +47,7 @@ const agent: AgentSupply = {
};
const chain = (current: string, headHealth: AgentChain['chain'][number]['health'] = 'healthy', headRunnable = true, reason: AgentChain['chain'][number]['reason'] = null): AgentChain => ({ manual_override: {hops:[{source_id:'native',model_id:'model-a'},{source_id:'relay',model_id:'model-a'},{source_id:'unused',model_id:'model-a'}]}, route_origin: "manual" as const,
- contract_version: 10,
+ contract_version: 11,
backend: 'claude',
model_id: 'model-a',
current: { source_id: current, model_id: 'model-a' },
diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.ts
index 4f7a73c93..61902b1b2 100644
--- a/ui/src/components/settings/models/apiFailure.test.ts
+++ b/ui/src/components/settings/models/apiFailure.test.ts
@@ -33,7 +33,7 @@ afterEach(() => {
describe('apiFailure — whether the route named the failure', () => {
it('posts installation to the dedicated runtime route', async () => {
const runtime = {
- contract_version: 10,
+ contract_version: 11,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'sha', assets: [] },
status: { installed_version: null, verified: false, listening: null, health: 'installing', last_check: null },
} as const;
diff --git a/ui/src/components/settings/models/gatewayAdoption.test.ts b/ui/src/components/settings/models/gatewayAdoption.test.ts
index c478e56b5..9ffe4994d 100644
--- a/ui/src/components/settings/models/gatewayAdoption.test.ts
+++ b/ui/src/components/settings/models/gatewayAdoption.test.ts
@@ -14,7 +14,7 @@ const agent = (mode: AgentSupply['mode']): AgentSupply => ({
});
const runtime = (health: RuntimeDependency['status']['health']): RuntimeDependency => ({
- contract_version: 10,
+ contract_version: 11,
manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1', source_sha: 'a'.repeat(40), assets: [] },
status: { installed_version: health === 'not_installed' ? null : '1', verified: health !== 'not_installed', health },
});
diff --git a/ui/src/components/settings/models/modelHubSurfaceState.ts b/ui/src/components/settings/models/modelHubSurfaceState.ts
index 17e3531a8..ca0074780 100644
--- a/ui/src/components/settings/models/modelHubSurfaceState.ts
+++ b/ui/src/components/settings/models/modelHubSurfaceState.ts
@@ -3,8 +3,12 @@ import type { AgentSupply, Source } from './types';
export type ModelsSurfaceKind = 'direct_empty' | 'gateway';
+/** Match runtime_stop: the upgrade-added empty Avibe catalog holds no runtime. */
+export const agentUsesHubRuntime = (agent: AgentSupply): boolean =>
+ agent.mode === 'hub' && (agent.backend !== 'avibe' || (agent.catalog_models?.length ?? 0) > 0);
+
export const modelsSurfaceKind = (agents: AgentSupply[], sources: Source[]): ModelsSurfaceKind =>
- agents.every((agent) => agent.mode === 'direct') && sources.length === 0
+ !agents.some(agentUsesHubRuntime) && sources.length === 0
? 'direct_empty'
: 'gateway';
diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts b/ui/src/components/settings/models/routeProjectionReconciliation.test.ts
index 05f54508d..bf6da53b7 100644
--- a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts
+++ b/ui/src/components/settings/models/routeProjectionReconciliation.test.ts
@@ -24,7 +24,7 @@ const source: Source = {
};
const report: RouteReport = {
chain: {
- contract_version: 10,
+ contract_version: 11,
backend: "claude",
model_id: "模型/opus",
manual_override: null,
diff --git a/ui/src/components/settings/models/runtimeLifecycle.test.ts b/ui/src/components/settings/models/runtimeLifecycle.test.ts
index b4ba4b3c3..23ff4039c 100644
--- a/ui/src/components/settings/models/runtimeLifecycle.test.ts
+++ b/ui/src/components/settings/models/runtimeLifecycle.test.ts
@@ -11,7 +11,7 @@ const asset = (platform: 'darwin-arm64' | 'linux-amd64') => ({
});
const runtime = (resolution: 'resolved' | 'unresolved' | 'unsupported'): RuntimeDependency => ({
- contract_version: 10,
+ contract_version: 11,
host_platform: 'darwin-arm64',
manifest: resolution === 'unresolved'
? { name: 'cliproxyapi', resolution, assets: [] }
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index ef0dafd43..7f655c4eb 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -10,8 +10,8 @@
// and the PR records the server implementation and feature-flag activation
// edge. The client never synthesizes a fallback payload shape.
-export const CONTRACT_VERSION = 10 as const;
-export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10] as const;
+export const CONTRACT_VERSION = 11 as const;
+export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11] as const;
export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;
export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;
@@ -152,7 +152,8 @@ export type Source = {
// per-backend subset, carried by `AgentSupply.sources` below.
// ── agent-supply.schema.json ────────────────────────────────────────────
-export type AgentBackend = 'claude' | 'codex' | 'opencode';
+export type NativeCliBackend = 'claude' | 'codex' | 'opencode';
+export type AgentBackend = NativeCliBackend | 'avibe';
export type AgentMode = 'hub' | 'direct';
export type MenuKind = 'fixed' | 'open';
@@ -456,7 +457,7 @@ export type MigrationAction = 'import' | 'controlled_import' | 'keep_native' | '
export type MigrationItem = {
id: string;
- backend: AgentBackend;
+ backend: NativeCliBackend;
kind: MigrationKind;
/** e.g. "sk-…dd3c + 自定义 Base URL"; never full secrets. */
masked_detail: string;
@@ -480,7 +481,7 @@ export type MigrationItem = {
source_paths?: string[];
/** Server-computed transitive closure of backends sharing persisted shell
* assignments. They must migrate together. Missing/empty means this backend. */
- required_backends?: AgentBackend[];
+ required_backends?: NativeCliBackend[];
/** The backend's native config cannot be parsed, so Hub mode would fail every
* launch: the row blocks its whole consent group. Optional for older servers. */
config_blocker?: boolean;
@@ -605,6 +606,7 @@ export type RecordedAttempt = {
channel: SupplyChannel;
stripped_reasoning_efforts?: string[];
declared_reasoning_efforts?: string[];
+ origin?: { provider: string; api: SourceProtocol; model: string };
};
export type TurnProvenance = {
contract_version: (typeof PERSISTED_TURN_CONTRACT_VERSIONS)[number];
@@ -625,6 +627,7 @@ export type TurnProvenance = {
http_status?: number | null;
upstream_error_code?: string | null;
local_error_detail?: string;
+ origin?: { provider: string; api: SourceProtocol; model: string };
stripped_reasoning_efforts?: string[];
declared_reasoning_efforts?: string[];
} | null;
diff --git a/ui/src/components/settings/models/vendorMeta.ts b/ui/src/components/settings/models/vendorMeta.ts
index 9b2a6a4df..92f08e931 100644
--- a/ui/src/components/settings/models/vendorMeta.ts
+++ b/ui/src/components/settings/models/vendorMeta.ts
@@ -73,18 +73,21 @@ export const BACKEND_IDENTITY_ACCENT = {
claude: 'cyan',
codex: 'mint',
opencode: 'violet',
+ avibe: 'muted',
} as const satisfies Record<AgentBackend, Accent>;
const BACKEND_ICON: Record<AgentBackend, IconType> = {
claude: Sparkles,
codex: Bot,
opencode: Terminal,
+ avibe: Bot,
};
const BACKEND_VISUAL: Record<AgentBackend, BackendVisual> = {
claude: { Icon: BACKEND_ICON.claude, accent: BACKEND_IDENTITY_ACCENT.claude },
codex: { Icon: BACKEND_ICON.codex, accent: BACKEND_IDENTITY_ACCENT.codex },
opencode: { Icon: BACKEND_ICON.opencode, accent: BACKEND_IDENTITY_ACCENT.opencode },
+ avibe: { Icon: BACKEND_ICON.avibe, accent: BACKEND_IDENTITY_ACCENT.avibe },
};
export function backendVisual(backend: AgentBackend): BackendVisual {
diff --git a/ui/src/components/steps/AgentDetection.tsx b/ui/src/components/steps/AgentDetection.tsx
index fa5702e28..98800f385 100644
--- a/ui/src/components/steps/AgentDetection.tsx
+++ b/ui/src/components/steps/AgentDetection.tsx
@@ -63,6 +63,10 @@ type AgentState = {
status?: 'unknown' | 'ok' | 'missing';
};
+type NativeRouteChainSelection = RouteChainSelection & {
+ agent: AgentSupply & { backend: RuntimeBackendId };
+};
+
/**
* The verdict of the latest settled enable write, and the intent that earned it.
*
@@ -137,7 +141,7 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
setInstallResults((prev) => (prev[name] ? { ...prev, [name]: undefined } : prev));
// Which backend's "Configure provider" modal is open (wizard mode only).
const [providerModal, setProviderModal] = useState<{ backend: RuntimeBackendId; method: 'oauth' | 'api_key' } | null>(null);
- const [routeSelection, setRouteSelection] = useState<RouteChainSelection | null>(null);
+ const [routeSelection, setRouteSelection] = useState<NativeRouteChainSelection | null>(null);
const committedRouteRefresh = useRef(false);
const canEditSetupRoute = Boolean(onNavigate && agentReads);
const [routeRead, setRouteRead] = useState<{
@@ -920,7 +924,9 @@ export const AgentDetection: React.FC<AgentDetectionProps> = ({ data, onNext, on
const hubRoute = mode === 'hub';
const openRoute = () => {
if (mode !== 'hub' || !routeTargetReady(name)) return;
- const supply = routeRead.supplies.find((row) => row.backend === name);
+ const supply = routeRead.supplies.find(
+ (row): row is NativeRouteChainSelection['agent'] => row.backend === name,
+ );
const modelId = routeRead.models[name];
if (supply?.mode === 'hub' && modelId) {
setRouteSelection({ agent: supply, modelId,
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 1999490cb..a525929a8 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -881,6 +881,7 @@
"turnOn": "Turn model gateway on",
"turnOff": "Turn model gateway off",
"stopBlocked": "Switch {{names}} to Direct before turning the model gateway off",
+ "stopAvibeBlocked": "Avibe models use the model gateway; remove them before turning it off.",
"stopUnavailable": "Agent routing status is unavailable; the model gateway cannot be turned off yet"
},
"closed": {
@@ -2076,7 +2077,8 @@
"backends": {
"claude": "Claude Code",
"codex": "Codex",
- "opencode": "OpenCode"
+ "opencode": "OpenCode",
+ "avibe": "Avibe Agent"
},
"sourceTest": {
"open": "Test",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1ad82ac3a..641060669 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -881,6 +881,7 @@
"turnOn": "开启模型网关",
"turnOff": "关闭模型网关",
"stopBlocked": "请先将 {{names}} 切换为直连,再关闭模型网关",
+ "stopAvibeBlocked": "Avibe 的模型通过模型网关运行,请先移除这些模型再关闭网关。",
"stopUnavailable": "暂时无法读取 Agent 路由状态,当前不能关闭模型网关"
},
"closed": {
@@ -2076,7 +2077,8 @@
"backends": {
"claude": "Claude Code",
"codex": "Codex",
- "opencode": "OpenCode"
+ "opencode": "OpenCode",
+ "avibe": "Avibe Agent"
},
"sourceTest": {
"open": "测试",
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index db9107f8d..f8e490f1d 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -910,7 +910,8 @@
"backends": {
"claude": "Claude Code",
"codex": "Codex",
- "opencode": "OpenCode"
+ "opencode": "OpenCode",
+ "avibe": "Avibe Agent"
},
"errors": {
"source_not_found": "Model source not found.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index b77916c07..ed8a71329 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -910,7 +910,8 @@
"backends": {
"claude": "Claude Code",
"codex": "Codex",
- "opencode": "OpenCode"
+ "opencode": "OpenCode",
+ "avibe": "Avibe Agent"
},
"errors": {
"source_not_found": "未找到模型供应商。",