Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): add Google protocol consumer frontend (#2340)
Call White3b3e25278d45
diff --git a/config/v2_config.py b/config/v2_config.pyindex e46b79a6f..cf4fa407e 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -205,6 +205,12 @@ def normalize_model_hub_vendor_id(value: object) -> str:return vendor+def validate_model_hub_protocol_vendor(vendor: str, protocol: str) -> None:+ """Keep Google's v12 explicit custom admission consistent across consumers."""+ if protocol == "google" and vendor != "custom":+ raise ValueError("Google Sources require the custom vendor")++def model_hub_fixed_menu_ids(backend: str) -> tuple[str, ...]:"""Return the bundled fixed-menu ids used by persisted Hub routes."""@@ -2295,7 +2301,7 @@ class ModelHubSourceConfig:kind: Literal["subscription", "api_key"]vendor: strdisplay_name: str- protocol: Literal["anthropic", "openai_responses", "openai_chat"]+ protocol: Literal["anthropic", "openai_responses", "openai_chat", "google"]supply_channel: Literal["native_cli", "hub"]billing: Literal["monthly", "metered"]state: ModelHubSourceStateConfig@@ -2354,8 +2360,10 @@ class ModelHubSourceConfig:"anthropic","openai_responses","openai_chat",+ "google",}:raise ValueError("Config 'model_hub.sources.protocol' is invalid")+ validate_model_hub_protocol_vendor(vendor, protocol)if not isinstance(supply_channel, str) or supply_channel not in {"native_cli", "hub"}:raise ValueError("Config 'model_hub.sources.supply_channel' is invalid")if not isinstance(billing, str) or billing not in {"monthly", "metered"}:diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex bdcc5f7b3..2c68c625d 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 v11 (2026-10-02).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v12 (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:@@ -19,7 +19,7 @@ from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocfrom .stream_wire import ProtocolSSEState, ProtocolUsageReportENGINE_TRANSPORT_TIMEOUT_SECONDS: Final = 60.0-SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")+SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat", "google")OBSERVATION_OUTCOMES = ("observed","ambiguous",@@ -76,7 +76,7 @@ class SourceBinding:source_id: strvendor: str- protocol: str # "anthropic" | "openai_responses" | "openai_chat"+ protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "google"base_url: str | None # None => vendor official defaultcredential_ref: str # opaque handle; never secret materialallowed_origins: tuple[str, ...] # agent names allowed to draw on thisdiff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 3ee06484f..56457aee5 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -2333,7 +2333,7 @@ class TurnCorrelationRegistry:self.store.put({- "contract_version": 11,+ "contract_version": 12,"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.pyindex 4fb7883bf..e33618ef9 100644--- a/core/handlers/model_hub/request.py+++ b/core/handlers/model_hub/request.py@@ -77,6 +77,9 @@ def _plain_history(value: Any) -> Any:]return {"role": "assistant", "content": texts} if texts else Noneplain = {key: item for key, item in value.items() if key not in _OPAQUE_FIELDS}+ if plain.get("thought") is True:+ # Gemini's readable thought text is ordinary history across origins.+ plain.pop("thought")for field in ("content", "parts", "tool_calls"):if field in plain:plain[field] = _plain_history(plain[field])@@ -95,7 +98,7 @@ 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"):+ for field in ("messages", "input", "contents"):if field in payload:payload[field] = _plain_history(payload[field])if isinstance(request, ModelHubRequest):diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 1f11a50fc..62ad6dc16 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -38,6 +38,7 @@ from config.v2_config import (normalize_model_hub_base_url,normalize_model_hub_vendor_id,normalized_model_hub_override,+ validate_model_hub_protocol_vendor,validate_model_hub_source_client_nonce,)from core.agent_auth_service import BackendLoginInProgressError@@ -131,6 +132,7 @@ from .oauth import (from .pricing import VALUE_WINDOW_DAYS, PriceTable, load_price_table, quota_valuesfrom .quota import QuotaSourceRef, SubscriptionQuotaCache, SubscriptionQuotaErrorfrom .provenance import (+ REQUEST_NONFALLBACK_TURN_OUTCOME,BoundedProvenanceStore,ENGINE_DOWN_TURN_OUTCOME,ExactHopBlocker,@@ -171,7 +173,7 @@ from .usage import (local_usage_day,)-CONTRACT_VERSION = 11+CONTRACT_VERSION = 12def seeded_source_name(vendor: str) -> str:@@ -273,8 +275,8 @@ _MODELS_DEV_CANDIDATE_FIELDS = ()-AGENT_CHAIN_CONTRACT_VERSION = 11-PROBE_RESULT_CONTRACT_VERSION = 11+AGENT_CHAIN_CONTRACT_VERSION = 12+PROBE_RESULT_CONTRACT_VERSION = 12_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15_SOURCE_PROBE_TIMEOUT_SECONDS = 60_REORDER_ORDER_UNSET = object()@@ -614,6 +616,34 @@ class _InvocationPlanChanged(Exception):"""No transport was admitted; recompute the remaining effective route."""+class _InvocationUnsupported(_InvocationPlanChanged):+ """A request-specific transport limitation, not a Source health failure."""++ def __init__(self, reason: str) -> None:+ super().__init__(reason)+ self.reason = reason+++def _google_admission_skip_reason(+ frontend_protocol: str | None,+ source_protocol: str,+ model_id: str,+ stream: bool,+) -> str | None:+ """Pinned-engine facts; callers explicitly own where refusal applies."""+ if frontend_protocol != "google":+ return None+ # Pinned CPA splits the decoded action on every colon; escaping cannot+ # preserve a model colon through that parser.+ if ":" in model_id:+ return "google_model_path_unsupported"+ # CPA c404af96 omits finishReason on its Responses -> Gemini+ # response.completed conversion. Usage/EOF cannot supply that terminal.+ if stream and source_protocol == "openai_responses":+ return "google_stream_responses_unsupported"+ return None++class _RecoveryWindowClosed(Exception):"""The request may finish its admitted inference, but cannot start another."""@@ -926,7 +956,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:manager = EngineRuntimeManager()return {- "contract_version": 11,+ "contract_version": 12,"enabled": enabled,"host_platform": status.host_platform or manager.host_platform(),"manifest": manager.contract_manifest(),@@ -1902,13 +1932,20 @@ class ModelHubService:if pinned_protocol is not None:return (pinned_protocol,)if vendor == "custom":- return SOURCE_PROTOCOLS+ # Google is explicit API/config admission in v12, not a new+ # automatic probe or picker option. Its generation path needs+ # a model, which non-inference observation must not invent.+ return tuple(protocol for protocol in SOURCE_PROTOCOLS if protocol != "google")raise ModelHubError("discovery_failed")requested = payload.get("protocol")if not isinstance(requested, str) or requested not in SOURCE_PROTOCOLS:raise ModelHubError("discovery_failed")if pinned_protocol is not None and requested != pinned_protocol:raise ModelHubError("discovery_failed")+ try:+ validate_model_hub_protocol_vendor(vendor, requested)+ except ValueError:+ raise ModelHubError("discovery_failed") from Nonereturn (requested,)@staticmethod@@ -3497,7 +3534,7 @@ class ModelHubService:vendor=vendor,display_name=display_name,protocol=cast(- Literal["anthropic", "openai_responses", "openai_chat"],+ Literal["anthropic", "openai_responses", "openai_chat", "google"],protocol_order[0],),base_url=base_url,@@ -3556,7 +3593,7 @@ class ModelHubService:self._mark_source_unverified(source)if observation is not None:source.protocol = cast(- Literal["anthropic", "openai_responses", "openai_chat"],+ Literal["anthropic", "openai_responses", "openai_chat", "google"],observation.protocol,)if observation is not None and observation.discovery is ObservationDiscovery.SUCCEEDED:@@ -6197,6 +6234,11 @@ class ModelHubService:"max_output_tokens": output_tokens,"input": "ping",}+ elif request_protocol == "google":+ payload = {+ "contents": [{"role": "user", "parts": [{"text": "ping"}]}],+ "generationConfig": {"maxOutputTokens": output_tokens},+ }else:payload = {"model": model_id,@@ -6225,6 +6267,11 @@ class ModelHubService:or not any(model.id == model_id and not model.retired for model in source.models)):raise ModelHubError("mapping_target_unavailable", status=409)+ # Saved-Source tests are buffered and speak the Source protocol.+ # Check both initial selection and the locked post-prepare snapshot.+ reason = _google_admission_skip_reason(source.protocol, source.protocol, model_id, False)+ if reason is not None:+ raise ModelHubError(reason, status=422)return sourcehandle = None@@ -6445,6 +6492,10 @@ class ModelHubService:while True:try:return await self._probe_agent_once(backend, model_id)+ except _InvocationUnsupported as skipped:+ # Explicit probes select one hop, not a fallback turn. A+ # permanent local limitation cannot restart as route churn.+ raise ModelHubError(skipped.reason, status=422) from Noneexcept _InvocationPlanChanged:continue@@ -6511,6 +6562,10 @@ class ModelHubService:),}+ if backend == "avibe":+ reason = _google_admission_skip_reason(source.protocol, source.protocol, resolved_model, False)+ if reason is not None:+ raise _InvocationUnsupported(reason)await self._prepare_engine_for_demand()started_at = time.monotonic()settlement_generation = None@@ -7825,6 +7880,7 @@ class ModelHubService:stream: bool,backend: BackendName,excluded_source_ids: set[str],+ excluded_hops: set[tuple[str, str]] | None = None,supply_channel: Literal["hub"] | None = None,exact_retry: bool = False,on_admitted: Callable[[int], None] | None = None,@@ -7855,6 +7911,7 @@ class ModelHubService:candidates = [hop for hop in resolution.candidate_hopsif hop.source_id not in excluded_source_ids+ and (hop.source_id, hop.model_id) not in (excluded_hops or ())]candidate = next((@@ -7871,6 +7928,11 @@ class ModelHubService:raise _InvocationPlanChangedattempt_request = requestif backend == "avibe":+ reason = _google_admission_skip_reason(+ getattr(request, "protocol", None), source.protocol, model_id, stream,+ )+ if reason is not None:+ raise _InvocationUnsupported(reason)# 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.@@ -7916,6 +7978,7 @@ class ModelHubService:backend: str,requested_model_id: str,excluded_source_ids: set[str],+ excluded_hops: set[tuple[str, str]] | None = None,supply_channel: Literal["hub"] | None = None,exact_retry: bool = False,on_admitted: Callable[[int], None] | None = None,@@ -7961,6 +8024,7 @@ class ModelHubService:stream=stream,backend=cast(BackendName, backend),excluded_source_ids=excluded_source_ids,+ excluded_hops=excluded_hops,supply_channel=supply_channel,exact_retry=exact_retry,on_admitted=admitted,@@ -8169,7 +8233,10 @@ class ModelHubService:if backend not in MODEL_HUB_BACKENDS:raise ModelHubError("mapping_target_unavailable")engine_prepared = False- if self.revocations.list():+ # An entirely unsupported Google request must not reconcile the engine+ # or custody. Supported hops drain the journal in demand preparation.+ google_preflight = backend == "avibe" and getattr(request, "protocol", None) == "google"+ if not google_preflight and self.revocations.list():try:await self._ensure_engine_synced()except ModelHubError:@@ -8213,6 +8280,8 @@ class ModelHubService:window_closed = Falsenon_retryable_failure = Falseglobally_blocked_source_ids: set[str] = set()+ unsupported_hops: set[tuple[str, str]] = set()+ unsupported_reason: str | None = Nonewhile True:async with self._mutation_lock:if recovery_request is not None and recovery_request.expired:@@ -8223,7 +8292,11 @@ class ModelHubService:config, cast(BackendName, backend), model_id, supply_channel,)inspection = next(- (hop for hop in resolution.candidate_hops if hop.source_id not in globally_blocked_source_ids),+ (+ hop for hop in resolution.candidate_hops+ if hop.source_id not in globally_blocked_source_ids+ and (hop.source_id, hop.model_id) not in unsupported_hops+ ),None,)if inspection is None:@@ -8252,8 +8325,6 @@ class ModelHubService:outcome=None,supply_channel="native_cli",)- await self._prepare_engine_for_demand(already_synced=engine_prepared)- engine_prepared = Truesettlement_generation = Nonedef admitted(generation: int) -> None:@@ -8277,6 +8348,14 @@ class ModelHubService:)try:+ if backend == "avibe":+ reason = _google_admission_skip_reason(+ getattr(request, "protocol", None), source.protocol, target_model, stream,+ )+ if reason is not None:+ raise _InvocationUnsupported(reason)+ await self._prepare_engine_for_demand(already_synced=engine_prepared)+ engine_prepared = Truehandle, outcome, cancelled = await self._invoke(source=source,model_id=target_model,@@ -8285,10 +8364,19 @@ class ModelHubService:backend=backend,requested_model_id=model_id,excluded_source_ids=globally_blocked_source_ids,+ excluded_hops=unsupported_hops,supply_channel=supply_channel,on_admitted=admitted,recovery_request=recovery_request,)+ except _InvocationUnsupported as skipped:+ unsupported_reason = skipped.reason+ unsupported_hops.add((source.id, target_model))+ logger.info(+ "Model Hub skipped unsupported hop: %s", skipped.reason,+ extra={"reason": skipped.reason, "source_id": source.id, "model_id": target_model},+ )+ continueexcept _InvocationPlanChanged:continueexcept _RecoveryWindowClosed:@@ -8344,6 +8432,7 @@ class ModelHubService:backend=backend,requested_model_id=model_id,excluded_source_ids=globally_blocked_source_ids,+ excluded_hops=unsupported_hops,supply_channel=supply_channel,exact_retry=True,on_admitted=admitted,@@ -8493,6 +8582,12 @@ class ModelHubService:turn_outcome=ENGINE_DOWN_TURN_OUTCOME,local_error_detail=format_os_errno(outcome.os_errno),)+ if unsupported_reason is not None and failed_source is None:+ # No upstream attempt exists. Exhaustion would invent a failed+ # attempt (and a retryable supply state) for a local limitation.+ raise ModelHubError(+ unsupported_reason, status=422, turn_outcome=REQUEST_NONFALLBACK_TURN_OUTCOME,+ )final_config, final_resolution = self._inspect_terminal_chain(backend=cast(BackendName, backend),model_id=model_id,diff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.pyindex de9e8f61e..d864e8826 100644--- a/core/handlers/model_hub/stream_wire.py+++ b/core/handlers/model_hub/stream_wire.py@@ -366,6 +366,10 @@ def _chat_terminal_event(}+def _google_terminal_event(key: str, message: str, _next_sequence_number: int) -> dict[str, object]:+ return {"error": {"code": 500, "status": "INTERNAL", "message": message, "details": [{"reason": key}]}}++StreamTerminalOutcome = Literal["served", "failed_terminal"]ProtocolObservationOutcome = Literal["served", "failed_terminal", "protocol_error"]ErrorEnvelopePath = tuple[str, ...]@@ -474,6 +478,7 @@ class ProtocolTerminalEnvelope:error_envelope_paths: tuple[ErrorEnvelopePath, ...] = ()required_error_path: ErrorEnvelopePath | None = Nonerequired_error_code_path: ErrorEnvelopePath | None = None+ require_nonempty: bool = False@dataclass(frozen=True)@@ -518,9 +523,42 @@ class ProtocolStreamTaxonomy:# Project only these finite selectors and the result container's shape.buffered_success_selectors: tuple[tuple[JSONPath, tuple[str, ...]], ...] = ()buffered_output_array_path: JSONPath | None = None+ buffered_terminal_string_paths: tuple[JSONPath, ...] = ()PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {+ "google": ProtocolStreamTaxonomy(+ terminal_envelopes=(+ ProtocolTerminalEnvelope(None, ("error",), None, "failed_terminal", (("error",),)),+ ProtocolTerminalEnvelope("error", ("error",), None, "failed_terminal", (("error",),)),+ ProtocolTerminalEnvelope(+ None, ("candidates", "*", "finishReason"), None, "served", require_nonempty=True,+ ),+ ProtocolTerminalEnvelope(+ None, ("promptFeedback", "blockReason"), None, "served", require_nonempty=True,+ ),+ ),+ model_output_envelopes=(+ ProtocolModelOutputEnvelope(+ None, ("candidates", "*", "content", "parts"), None, require_nonempty=True,+ ),+ ),+ success_literal=None,+ sequence_number_path=None,+ buffered_error_envelope_paths=(("error",),),+ buffered_output_array_path=("candidates",),+ buffered_terminal_string_paths=(("promptFeedback", "blockReason"),),+ terminal_event_name=None,+ render_terminal_event=_google_terminal_event,+ usage=ProtocolUsageTaxonomy(+ # Gemini GenerateContentResponse. Prompt count includes cache;+ # thoughtsTokenCount is separate from candidatesTokenCount.+ container_paths=(("usageMetadata",),),+ input_paths=(("promptTokenCount",),),+ cached_input_paths=(("cachedContentTokenCount",),),+ output_paths=(("candidatesTokenCount",), ("thoughtsTokenCount",)),+ ),+ ),"anthropic": ProtocolStreamTaxonomy(terminal_envelopes=(ProtocolTerminalEnvelope(@@ -891,6 +929,7 @@ def _protocol_projection_paths(protocol: str) -> frozenset[JSONPath]:taxonomy = PROTOCOL_STREAM_TAXONOMY[protocol]paths: set[JSONPath] = {()}paths.update(path for path, _values in taxonomy.buffered_success_selectors)+ paths.update(taxonomy.buffered_terminal_string_paths)if taxonomy.buffered_output_array_path is not None:paths.add(taxonomy.buffered_output_array_path)for envelope in (*taxonomy.terminal_envelopes, *taxonomy.model_output_envelopes):@@ -922,11 +961,15 @@ def _buffered_recovery_verified(taxonomy: ProtocolStreamTaxonomy,scalars: Mapping[JSONPath, object],arrays: AbstractSet[JSONPath],+ nonempty: AbstractSet[JSONPath],) -> bool:"""Recognize a completed native result without validating every body field."""- return (- bool(taxonomy.buffered_success_selectors)+ return any(+ path in scalars and path in nonempty and (isinstance(scalars[path], str) or scalars[path] is None)+ for path in taxonomy.buffered_terminal_string_paths+ ) or (+ taxonomy.buffered_output_array_path is not Noneand taxonomy.buffered_output_array_path in arraysand all(scalars.get(path) in values for path, values in taxonomy.buffered_success_selectors))@@ -1032,7 +1075,7 @@ class ProtocolFactProjector:error_code_candidates=(code_candidates if matched_paths else ()),recovery_verified=(not matched_paths- and _buffered_recovery_verified(self.taxonomy, self._scalars, self._arrays)+ and _buffered_recovery_verified(self.taxonomy, self._scalars, self._arrays, self._nonempty)),)@@ -1175,6 +1218,16 @@ class ProtocolFactProjector:candidates: list[str] = []for error_path in error_paths:value = self._scalars.get((*error_path, field))+ if self.protocol == "google" and field == "code" and type(value) is int:+ # Gemini error.code carries an HTTP status even inside SSE.+ # Normalize only shaped native errors; classification retains+ # sole ownership of retry/health policy.+ value = {+ 400: "invalid_request_error", 401: "authentication_error",+ 403: "permission_error", 404: "not_found_error",+ 429: "rate_limit_error", 500: "server_error",+ 502: "server_error", 503: "server_error", 504: "server_error",+ }.get(value)if not isinstance(value, str):continueif self.machine_error_codes and value not in self.machine_error_codes:@@ -1297,6 +1350,7 @@ def observe_protocol_response(payload,selector_path=envelope.selector_path,selector_value=envelope.selector_value,+ require_nonempty=envelope.require_nonempty,):continueif envelope.required_error_path is not None and not any(@@ -1386,9 +1440,14 @@ class ProtocolSSEState:return self.terminal_outcome == "served" or self.model_output_starteddef _observe_frame(self, frame: SSEObservedFrame) -> None:+ observation = frame.observationif self.terminal_outcome is not None:+ # Google's finishReason completes model output, but the pinned+ # Chat -> Gemini translator can send billing in a following frame.+ # Preserve terminal truth; only that protocol's usage may advance.+ if self.protocol == "google" and self.terminal_outcome == "served" and observation.usage is not None:+ self.usage = observation.usage if self.usage is None else self.usage.merge(observation.usage)return- observation = frame.observationif observation.model_output_started:self.model_output_started = Trueif observation.usage is not None:diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex 280ad5b44..2c56e512e 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -597,6 +597,7 @@ class ModelHubTurnGateway:app = web.Application(client_max_size=client_max_size)app.router.add_get("/{backend}/v1/models", self._handle_models)app.router.add_post("/{backend}/v1/{endpoint:.*}", self._handle_request)+ app.router.add_post("/{backend}/v1beta/models/{google_action:.*}", self._handle_google_request)runner = web.AppRunner(app,access_log=None,@@ -624,7 +625,8 @@ class ModelHubTurnGateway:authorization = request.headers.get("Authorization", "")bearer = authorization[7:] if authorization.lower().startswith("bearer ") else ""api_key = request.headers.get("x-api-key", "")- for candidate in (bearer, api_key):+ google_key = request.headers.get("x-goog-api-key", "") if "google_action" in request.match_info else ""+ for candidate in (bearer, api_key, google_key):if candidate and self.correlation.authenticates(backend, candidate):return candidatereturn None@@ -660,6 +662,28 @@ class ModelHubTurnGateway:},)+ async def _handle_google_request(self, request: web.Request) -> web.StreamResponse:+ response = await self._handle_request(request)+ # Only locally rendered JSON endings need translation. This same+ # response already owns its status, retry metadata and admitted origin.+ # Streaming endings use the protocol taxonomy before committing bytes.+ if isinstance(response, web.Response) and not response.prepared and _LOCAL_ENDING in response:+ ending = response[_LOCAL_ENDING]+ response.text = json.dumps({+ "error": {+ "code": response.status,+ "status": {+ 400: "INVALID_ARGUMENT", 401: "UNAUTHENTICATED", 403: "PERMISSION_DENIED",+ 404: "NOT_FOUND", 409: "ABORTED", 413: "RESOURCE_EXHAUSTED",+ 422: "FAILED_PRECONDITION", 424: "FAILED_PRECONDITION",+ 429: "RESOURCE_EXHAUSTED", 503: "UNAVAILABLE", 504: "DEADLINE_EXCEEDED",+ }.get(response.status, "INTERNAL"),+ "message": ending.message,+ "details": [{"reason": ending.key}],+ },+ })+ return response+async def _handle_request(self, request: web.Request) -> web.StreamResponse:backend = request.match_info["backend"]token = self._authorized_token(request, backend)@@ -854,8 +878,15 @@ class ModelHubTurnGateway:execution: _TurnExecution,resources: AsyncExitStack,) -> web.StreamResponse:- endpoint = request.match_info["endpoint"].strip("/")- if backend not in MODEL_HUB_BACKENDS or endpoint not in _SUPPORTED_PATHS:+ endpoint = request.match_info.get("endpoint", "").strip("/")+ google_action = request.match_info.get("google_action")+ google_model, _, google_method = (google_action or "").rpartition(":")+ google_request = google_action is not None+ supported_path = (+ bool(google_model) and google_method in {"generateContent", "streamGenerateContent"}+ if google_request else endpoint in _SUPPORTED_PATHS+ )+ if backend not in MODEL_HUB_BACKENDS or not supported_path:terminalizer.fail("protocol_error")return self._terminal_error_response(execution,@@ -904,8 +935,20 @@ class ModelHubTurnGateway:code="invalid_request_error",turn_outcome=REQUEST_NONFALLBACK_TURN_OUTCOME,)- model_id = payload.get("model")- stream = payload.get("stream", False)+ model_id = google_model if google_request else payload.get("model")+ stream = google_method == "streamGenerateContent" if google_request else payload.get("stream", False)+ if google_request and (+ "model" in payload or "stream" in payload+ or any(+ value != "sse" or not stream+ for name in ("alt", "$alt") for value in request.query.getall(name, [])+ )+ ):+ terminalizer.fail("invalid_parameter")+ return self._terminal_error_response(+ execution, terminalizer, status=400, code="invalid_request_error",+ turn_outcome=REQUEST_NONFALLBACK_TURN_OUTCOME,+ )if not isinstance(model_id, str) or not model_id or not isinstance(stream, bool):terminalizer.fail("invalid_parameter")return self._terminal_error_response(@@ -953,7 +996,7 @@ class ModelHubTurnGateway:decision=decision,)- protocol = _REQUEST_PROTOCOLS[endpoint]+ protocol = "google" if google_request else _REQUEST_PROTOCOLS[endpoint]try:caller_headers = {name.lower(): value for name, value in request.headers.items() if name.lower() in FORWARDED_CALLER_HEADERSdiff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex bb2b83e9f..b40cbe6ec 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,8 +1,9 @@# Model Hub contracts-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+Status: **contract_version 12**, 2026-10-02: Google protocol vocabulary and Gemini+gateway frontend, with API/config-only Source admission. See+[`google-protocol.md`](google-protocol.md) and [`avibe-consumer.md`](avibe-consumer.md).+The approved routing contract is`../model-hub-routing-modes.md`, including the owner-approved Empty Route Inheritancecorrection `352486374`; API-key-only scope remains unchanged.@@ -44,9 +45,10 @@ commit is not evidence that the complete final protocol has landed.inherited routing through the same Restore/Undo/Save flow, never empty Manual.- A hop whose upstream `model_id` differs from its menu model is an explicit configuredmapping. There is no separate mapping object or runtime mapping event.-- The protocol vocabulary is exactly `anthropic | openai_responses | openai_chat`.- `base_url` already distinguishes official endpoints from relays and self-hosted- gateways; no fourth protocol value is defined.+- The protocol vocabulary is exactly `anthropic | openai_responses | openai_chat | google`.+ `base_url` distinguishes official endpoints from relays and self-hosted gateways.+ Google is explicitly declared through API/config; the three-option UI picker and+ custom Auto-detection set remain unchanged.- Source health is global and changes only from shaped explicit upstream classifications.Native CLI availability, exact-hop integrity, and bounded pre-first-byte connectionbackoff are live execution facts and never silently rewrite stored configuration.@@ -179,7 +181,7 @@ comparison. A gate may not report success by comparing stale input with itself.## Version closure-`contract_version` 11 must coexist in all registered version locations on the same tested head:+`contract_version` 12 must coexist in all registered version locations on the same tested head:- `mirror-registry.json`- `agent-chain.schema.json`@@ -215,7 +217,7 @@ persisted-shape rule that governs config files. It therefore accepts the releaseas a set ending at the terminal one, and nothing branches on which member a recordcarries.-The three-value protocol closure includes `source.schema.json`, `adapter-interface.py`,+The four-value protocol closure includes `source.schema.json`, `adapter-interface.py`,and the byte-identical `core/handlers/model_hub/adapter.py` on the same tested head.After implementation lands, these contracts are read-only for downstream lanes. An@@ -226,7 +228,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac| File | Authority and consumer role || --- | --- |-| `source.schema.json` | Source identity, channel, three protocols, state, usage, inventory, credential reference, and audit metadata. |+| `source.schema.json` | Source identity, channel, four protocols, state, usage, inventory, credential reference, and audit metadata. || `source-create.schema.json` | API-key Source creation request, transient credential boundary, optional single-protocol constraint, and lost-response correlation. || `agent-supply.schema.json` | Backend mode, default Source membership/order and sparse manual intent, configuration eligibility, model-supply and backend-health projections. || `backend-model.schema.json` | Backend Agent model identity, editable capability metadata, and server-owned lock/routeability projection. |@@ -248,6 +250,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac| `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. |+| `google-protocol.md` | Google API/config admission, native gateway paths, discovery, stream facts, and pinned-engine translation boundary. || `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. |diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex bdcc5f7b3..2c68c625d 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 v11 (2026-10-02).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v12 (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:@@ -19,7 +19,7 @@ from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocfrom .stream_wire import ProtocolSSEState, ProtocolUsageReportENGINE_TRANSPORT_TIMEOUT_SECONDS: Final = 60.0-SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")+SOURCE_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat", "google")OBSERVATION_OUTCOMES = ("observed","ambiguous",@@ -76,7 +76,7 @@ class SourceBinding:source_id: strvendor: str- protocol: str # "anthropic" | "openai_responses" | "openai_chat"+ protocol: str # "anthropic" | "openai_responses" | "openai_chat" | "google"base_url: str | None # None => vendor official defaultcredential_ref: str # opaque handle; never secret materialallowed_origins: tuple[str, ...] # agent names allowed to draw on thisdiff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex da5ff5da4..c3398c3db 100644--- a/docs/plans/model-hub-contracts/agent-chain.schema.json+++ b/docs/plans/model-hub-contracts/agent-chain.schema.json@@ -7,7 +7,7 @@"required": ["contract_version", "backend", "model_id", "manual_override", "route_origin", "chain", "current", "supply_state"],"additionalProperties": false,"properties": {- "contract_version": { "const": 11 },+ "contract_version": { "const": 12 },"backend": { "enum": ["claude", "codex", "opencode", "avibe"] },"model_id": { "type": "string" },"manual_override": {@@ -237,7 +237,7 @@],"examples": [{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "unlisted-model","manual_override": null,@@ -247,7 +247,7 @@"supply_state": "ok"},{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -257,7 +257,7 @@"supply_state": "ok"},{- "contract_version": 11,+ "contract_version": 12,"backend": "claude","model_id": "claude-opus-4-6","manual_override": null,@@ -267,7 +267,7 @@"supply_state": "waiting"},{- "contract_version": 11,+ "contract_version": 12,"backend": "opencode","model_id": "glm-5.2","manual_override": { "hops": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2" }] },@@ -277,7 +277,7 @@"supply_state": "waiting"},{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -287,7 +287,7 @@"supply_state": "interrupted"},{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -297,7 +297,7 @@"supply_state": "interrupted"},{- "contract_version": 11,+ "contract_version": 12,"backend": "claude","model_id": "claude-haiku-4-5","manual_override": null,diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.jsonindex 8d0d23da8..3e789ad14 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": 11},+ "contract_version": {"const": 12},"probe": {"$ref": "model-hub/source-probe-result.schema.json"}}},@@ -155,7 +155,7 @@"SuccessCore": {"properties": {"ok": {"const": true},- "contract_version": {"const": 11}+ "contract_version": {"const": 12}}},"SourceListResponse": {@@ -164,7 +164,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}}},@@ -174,7 +174,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"observation": {"$ref": "model-hub/observation-result.schema.json"}}},@@ -184,7 +184,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"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": 11},+ "contract_version": {"const": 12},"source": {"$ref": "#/definitions/SourceApi"}}},@@ -206,7 +206,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"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": 11},+ "contract_version": {"const": 12},"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": 11},+ "contract_version": {"const": 12},"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}}},@@ -239,7 +239,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"agent": {"$ref": "#/definitions/AgentSupplyApi"}}},@@ -256,7 +256,7 @@],"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"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": 11},+ "contract_version": {"const": 12},"error": {"const": "candidate_suppliers_changed"},"detail": {"type": "string", "minLength": 1},"changed": {@@ -301,7 +301,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"agent": {"type": "object","required": ["backend", "mode", "catalog_models"],@@ -402,7 +402,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"candidates": {"type": "object","required": ["builtin", "providers", "in_list"],@@ -421,7 +421,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"matches": {"type": "array","maxItems": 8,@@ -455,7 +455,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"chain": {"$ref": "model-hub/agent-chain.schema.json"}}},@@ -465,7 +465,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}}},@@ -475,7 +475,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"chain": {"$ref": "model-hub/agent-chain.schema.json"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -487,7 +487,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"probe": {"$ref": "model-hub/probe-result.schema.json"}}},@@ -497,7 +497,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}}},@@ -507,7 +507,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"usage": {"$ref": "model-hub/usage-summary.schema.json"}}},@@ -517,7 +517,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"quota": {"$ref": "model-hub/quota-summary.schema.json"}}},@@ -527,7 +527,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -549,7 +549,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -572,7 +572,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -597,7 +597,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11}+ "contract_version": {"const": 12}}},"RuntimeApi": {@@ -619,7 +619,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"scan": {"$ref": "model-hub/migration-scan.schema.json"}}},@@ -629,7 +629,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"applied": {"type": "integer", "minimum": 0},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}@@ -641,7 +641,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}}},@@ -652,7 +652,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"provenance": {"anyOf": [{"$ref": "model-hub/turn-provenance.schema.json"},@@ -667,7 +667,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 11},+ "contract_version": {"const": 12},"runtime": {"$ref": "#/definitions/RuntimeApi"}}}diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 997f32d7d..13ef88970 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; unknownAPI siblings retain the Owner default.-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.+Status: **Normative, `contract_version` 12** — 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: 11, ...}`.+Success envelope: `{ok: true, contract_version: 12, ...}`.Failure envelope:-`{ok: false, contract_version: 11, error: <machine_code>, detail?: <i18n_key>}`.+`{ok: false, contract_version: 12, 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,7 +24,7 @@ table. The contract guard requires the two endpoint sets to be identical, requirexercised HTTP response for every registry entry, and validates that response againstthe route's named schema.-The shared envelope and every versioned nested contract carry `contract_version` 11, the+The shared envelope and every versioned nested contract carry `contract_version` 12, theterminal value. Supported persisted config shapes and historical TurnProvenanceremain readable; ephemeral envelopes use only the terminal version.@@ -78,7 +78,7 @@ runtime open. Once models are configured it participates in the runtime Stop gua| 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` 11 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` 12 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 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. |@@ -167,8 +167,11 @@ create request:`base_url` may be null for an official vendor endpoint. `protocol`, when present,restricts observation to exactly that interface; omitting it selects the shipped vendor-pin when one exists, otherwise on `custom` it probes the authoritative three-value-order. Auto-detect on `custom` still requires a matching protocol-shaped upstream+pin when one exists, otherwise on `custom` it probes the three existing interfaces+in `anthropic`, `openai_responses`, `openai_chat` order. Google requires an explicit+`protocol: "google"` declaration and uses credential-gated native model listing,+without a model-free inference probe; see [`google-protocol.md`](google-protocol.md).+Auto-detect on `custom` still requires a matching protocol-shaped upstreamresponse. A supplied protocol is established when authentication succeeds and either`vendor` has a shipped catalog pin, the client declared that protocol on `custom`, ora matching protocol-shaped response proves it. The protocol probe is deliberately@@ -616,7 +619,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"source": {"id": "src_anthkey01","kind": "api_key",@@ -726,7 +729,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "source_last_supplier","would_remove_hops": [],"would_interrupt": [@@ -862,7 +865,7 @@ API-key success:```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"source": {"id": "src_relay9c1x","kind": "api_key",@@ -953,7 +956,7 @@ Status and submit return the same terminal shape:```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"flow": {"flow_id": "oaf_claude01","client_nonce": "ofn_01j5w8z7p4n6q2rt",@@ -1026,9 +1029,9 @@ a valid `interrupted` chain.```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"chain": {- "contract_version": 11,+ "contract_version": 12,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -1055,7 +1058,7 @@ In Direct mode both chain and probe refuse with:```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "direct_mode","detail": "models.hub.direct_mode"}@@ -1069,9 +1072,9 @@ A successful probe nests its result:```json{"ok": true,- "contract_version": 11,+ "contract_version": 12,"probe": {- "contract_version": 11,+ "contract_version": 12,"backend": "claude","channel": "hub","reachable": false,@@ -1094,7 +1097,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","channel": "native_cli","reachable": true,@@ -1107,7 +1110,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 11,+ "contract_version": 12,"backend": "codex","channel": "native_cli","reachable": false,@@ -1123,7 +1126,7 @@ No candidate is an API error with a typed model-scoped state:```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "probe_no_candidate","detail": "models.probe.no_candidate.waiting","supply": {@@ -1304,7 +1307,7 @@ The store retains at most 500 exactly attributed settled turns with its existingwrites. Ambiguous attribution remains excluded; this is not a log of every upstreamrequest. 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: 11, provenance: TurnProvenance | null}`;+Success uses exactly `{ok: true, contract_version: 12, provenance: TurnProvenance | null}`;there is no `success` field or envelope exception.Local `engine_down` records may also contain `local_error_detail`, an OS-generated@@ -1362,7 +1365,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "provenance_unavailable","detail": "models.provenance.direct_mode"}@@ -1371,7 +1374,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 11,+ "contract_version": 12,"error": "provenance_unavailable","detail": "models.provenance.attribution_ambiguous"}@@ -1705,7 +1708,7 @@ contract harness and API-boundary tests enforce:<!-- authority-consumer: turn.served turn.exhausted turn.request_nonfallback turn.engine_down turn.streamed_fallback turn.no_candidate.unconfigured turn.no_candidate.unlisted turn.no_candidate.blocked turn.canceled --><!-- authority-consumer: mutation.source_metadata mutation.credential_replace mutation.source_refresh mutation.model_create mutation.model_efforts mutation.model_delete mutation.source_delete mutation.route_replace mutation.route_restore mutation.default_sources --><!-- authority-consumer: import.keep_native import.copy_key import.reauth import.controlled -->-<!-- authority-consumer: protocol anthropic openai_responses openai_chat -->+<!-- authority-consumer: protocol anthropic openai_responses openai_chat google --><!-- authority-consumer: observation.outcome observed ambiguous unreachable authentication_failed adapter_error timeout --><!-- authority-consumer: observation.discovery succeeded failed not_attempted --><!-- authority-consumer: runtime.health ok degraded down not_installed installing not_started -->diff --git a/docs/plans/model-hub-contracts/avibe-consumer.md b/docs/plans/model-hub-contracts/avibe-consumer.mdindex 9cdda37b1..7c0949299 100644--- a/docs/plans/model-hub-contracts/avibe-consumer.md+++ b/docs/plans/model-hub-contracts/avibe-consumer.md@@ -183,8 +183,8 @@ The header needs no upstream credentials and is never forwarded upstream.- Contract authority/version closure, focused Python tests, and the existing UItype/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+The v11 consumer introduced the three existing protocols. The v12 extension in+[`google-protocol.md`](google-protocol.md) adds the Google runtime/engine frontend+together with the vocabulary, while preserving the origin delivery rules. There areno new UI elements in this lane. C-8 owns enabling the Avibe backend card and itsHub-only presentation; `cli_present` truthfully remains false here.diff --git a/docs/plans/model-hub-contracts/google-protocol.md b/docs/plans/model-hub-contracts/google-protocol.mdnew file mode 100644index 000000000..7682f2bae--- /dev/null+++ b/docs/plans/model-hub-contracts/google-protocol.md@@ -0,0 +1,158 @@+# Google protocol consumer extension++Normative for the v12 Model Hub contract. This extends the existing gateway,+EngineAdapter and pinned CPA transport; it does not add a provider implementation+to agent-core, change backend registration, or upgrade the engine.++## Source admission and observation++The complete protocol vocabulary includes `google`. New Google API-key Sources+are admitted with `vendor: "custom"`, explicit `protocol: "google"`, an explicit+Base URL and the usual transient `key` through the existing observe/create APIs.+Existing vendor pins, subscriptions, OAuth and native CLI configuration do not+change. The UI protocol picker still contains only its three approved options.+Existing Source details can label Google; its tier suggestions are empty.+The custom-only Google vendor rule is validated before API credential work and+at config/runtime Source admission; unverified save cannot bypass it. Source and+SourceCreate schemas enforce the same conditional.++The Base URL is the upstream origin or a proxy root, optionally ending in+`/v1beta`; that suffix is removed only for CPA configuration because its Gemini+executor appends it. Query-bearing roots are refused before Source registration,+because this executor appends paths rather than preserving a Base URL query.+Discovery calls `<root>/v1beta/models`, supplies the held key+as `x-goog-api-key`, and follows `nextPageToken` on that same endpoint. Redirects,+malformed pages and repeated continuation tokens fail the whole observation;+partial inventory must never replace a saved list. Model names lose only their+`models/` API resource prefix. Inventory does not invent limits, vision support+or reasoning tiers.++Google is not added to custom Auto detection: its inference endpoints require a+model in the path. Add-time observation performs no model call. For an explicitly+declared protocol, the existing credential witness rule applies: a listing that+accepts the supplied key and rejects the same uncredentialed request establishes+authentication; public lists do not. Explicit unverified save remains available.+A user-requested saved-model probe uses a Gemini `contents` request.++## Consumer and transport++`ModelHubLaunch.to_hop_resolution()` and the runtime router return `protocol: "google"`+and the gateway frontend Base URL ending in `/avibe/v1beta`. Required+`request_headers`, gateway token, runtime model, Source identity, provider identity+and nullable capabilities have exactly the same owners as in `avibe-consumer.md`.++The gateway accepts:++- `POST /<backend>/v1beta/models/<runtime_model>:generateContent`+- `POST /<backend>/v1beta/models/<runtime_model>:streamGenerateContent?alt=sse`++It also accepts omitted `alt` or `$alt=sse` on the streaming path, always using SSE.+Other `alt` values are refused before admission. Model and streaming mode come+from the path, not JSON `model` or `stream` fields; those fields are refused.+Callers percent-encode the runtime model as one path parameter. The engine client+likewise encodes model identity as data, retaining only its deliberate+`Source.prefix/model` boundary as a structural slash; dot segments and leading+slashes in admitted model ids must not change routing.+`countTokens`, embedding/batch APIs and query-string credential authentication are+not consumer endpoints. A caller uses the returned gateway token through Bearer+authentication or `x-goog-api-key`; upstream keys never cross this boundary.++The engine request routes `Source.prefix/model_id` in the URL and uses the Google+frontend regardless of the selected Source's protocol. CPA owns native or+cross-protocol request/response conversion. Avibe performs no duplicate translator.+The engine remains v7.3.16 at upstream `c404af96` with the existing Avibe patch.++### Pinned-engine limitations and admission skips++For **Avibe streaming only**, a Google frontend request cannot admit an+`openai_responses` Source hop: the pinned CPA Responses/Codex-to-Gemini translator+does not emit `finishReason` for `response.completed`. Before transport/recovery+admission, skip that hop with stable reason+`google_stream_responses_unsupported` and continue the request's effective chain.+The reason is recorded on the Model Hub service diagnostic log record's `reason`+field with the exact Source/model identity. A skip is not an upstream attempt:+no health transition, cooldown, metering, failed-attempt entry, or served origin+is fabricated. If all selectable hops were skipped without an upstream attempt,+return local HTTP 422 with that same machine reason and no served-hop header.+If actual upstream attempts failed too, ordinary exhaustion still owns the turn.++For **Avibe Google-frontend requests**, buffered or streaming, a selected original+model id containing `:` is also unsupported: CPA splits the decoded Google action+on every colon, so percent-encoding does not preserve that identity. Skip exactly+that hop with reason `google_model_path_unsupported` before transport, recovery+or attempt admission. Continue the chain, including a later supported model on+the same Source. Do not rename, truncate or normalize the configured model id.+This check precedes the streaming conversion check when both apply. If all hops+are skipped, the last skip reason is returned in the same local 422/no-origin+envelope. Logs retain each exact skipped identity and its reason.+An explicit Agent probe still tests only its selected hop: an unsupported+Google model returns the same controlled 422 reason instead of retrying a+permanent local limitation as a changed route.++Saved-Source probes are an explicit exception to the Avibe-only consumer+scope: they test one exact inventory model with a buffered request in the+Source's protocol. A Google Source model containing `:` returns local HTTP 422+with `google_model_path_unsupported`, not an upstream/model failure. It does not+try another model, admit a transport or attempt, settle recovery, verify the+credential, meter usage, or attach a served origin. The internal `opencode`+adapter-dispatch marker does not make this Model Hub operation a native CLI call.++One pure predicate owns the two engine limitations, from frontend protocol,+Source protocol, original model id and streaming mode. Avibe routing/Agent+probes and saved-Source probes explicitly apply it before engine preparation+and to the locked, revalidated snapshot immediately before adapter admission.+A request already known to be unsupported at preflight does not start/reconcile+the engine or drain credential custody; a supported fallback retains ordinary+demand preparation. A later configuration change is checked again before any+inference admission.+Source observation and inventory discovery remain model-free and do not apply+these inference-path checks.++Native CLI behavior is unchanged. Google buffered conversion, Google/Anthropic/+Chat streaming without model colons, and all other frontends served by a Google+Source are not skipped.+No usage frame or clean EOF is interpreted as a missing model terminal.+Fixing the engine and publishing a replacement managed-runtime asset is a+separate owner-authorized release operation, not part of this PR.++## Response facts and provenance++Google candidate content parts are model output; metadata alone is not. Native+`finishReason` or prompt blocking marks terminal completion; there is no `[DONE]`.+Native `error` envelopes (unnamed or CPA's `event: error`) are failures. The+existing no-fallback-after-output rule remains in force.+A buffered `promptFeedback.blockReason` completion needs no candidates array and+is positive recovery evidence, just like its streaming terminal. Empty, malformed+or error-bearing bodies do not gain recovery evidence from that field.++Token reports project `usageMetadata.promptTokenCount` (including its cached+subset), `cachedContentTokenCount`, and the sum of `candidatesTokenCount` and+`thoughtsTokenCount`. No report is guessed when the upstream provides none.+Both buffered and streaming responses share these facts with metering.++Local JSON failures use Google's numeric `error.code`, canonical `error.status`,+localized `error.message`, and `details[].reason` for the Model Hub machine code.+Late local streaming endings use the Google error envelope. All carriers retain+the v11 response-origin policy: `x-avibe-served-hop` comes only from the immutable+admitted invocation that actually supplied the response. Pre-admission/local+failures have no origin header.++Avibe fallback compares each admitted hop with the launch's primary origin.+For a different or unverifiable origin, Google `contents[].parts` lose opaque+signatures and visible thought text becomes ordinary text; tool arguments and+results are user data and remain intact. Same-origin requests retain signatures.+Cross-protocol fallback follows this same policy before CPA conversion.++## Validation and compatibility++The shared Source enum guard includes create, observation and Source-probe+contracts, runtime storage, config, adapter and UI type consumers. The new writer+generation is 12; persisted provenance generations 5 through 11 still load, and+released configuration fixtures retain their meaning. Only version literals+change in existing UI browser fixtures.++Owning tests cover config/runtime/YAML round trips, Google URL/body admission,+finite stream facts and metering, paginated credential witness/refusals,+same/different-origin gateway fallback and served provenance. Real pinned-engine+tests isolate all state and allow only loopback upstreams. UI validation uses the+existing hermetic Model Hub browser suite and production build.diff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.jsonindex a9ce4ae08..ac8441c88 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": 11 },+ "contract_version": { "const": 12 },"error": {"enum": ["source_last_supplier",@@ -116,7 +116,7 @@"examples": [{"ok": false,- "contract_version": 11,+ "contract_version": 12,"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/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.jsonindex b82b8e701..6e897811e 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": 11,+ "contract_version": 12,"input_generation": {"mode": "same_run_live_files","external_snapshot": "content_fingerprint_required"@@ -15,6 +15,7 @@"tests/e2e/test_model_hub*.py","ui/src/components/settings/models/types.ts","ui/src/components/settings/models/*.test.*",+ "ui/src/components/onboarding/providers/*.test.*","ui/e2e/**/*.ts","ui/e2e/**/*.tsx"],@@ -59,6 +60,18 @@"id": "A3","source_file": "docs/plans/model-hub-implementation.md","start_marker": "The final set contains no",+ "allowed_property_values": [+ {+ "file": "docs/plans/model-hub-contracts/source.schema.json",+ "property_path": ["allOf", 0, "then", "properties", "vendor"],+ "values": ["custom"]+ },+ {+ "file": "docs/plans/model-hub-contracts/source-create.schema.json",+ "property_path": ["allOf", 0, "then", "properties", "vendor"],+ "values": ["custom"]+ }+ ],"scope_globs": ["docs/plans/model-hub-contracts/*.schema.json"]@@ -569,6 +582,11 @@"file": "vibe/model_hub_runtime/state.py","name": "_PROTOCOLS"},+ {+ "kind": "python_string_assignment",+ "file": "vibe/model_hub_runtime/api_key_vendors.py",+ "name": "_SUPPORTED_PROTOCOLS"+ },{"kind": "python_string_assignment","file": "docs/plans/model-hub-contracts/adapter-interface.py",@@ -588,6 +606,17 @@"kind": "schema_vocabulary","schema": "source-create.schema.json","paths": ["/properties/protocol"]+ },+ {+ "kind": "schema_vocabulary",+ "schema": "source-probe-result.schema.json",+ "paths": ["/properties/protocol"]+ },+ {+ "kind": "schema_vocabulary",+ "schema": "observation-result.schema.json",+ "paths": ["/properties/protocol"],+ "exclude": [null]}]},diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.jsonindex 0888393b0..21efd8fb9 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": 11 },+ "contract_version": { "const": 12 },"outcome": {"enum": ["observed",@@ -31,7 +31,7 @@"authenticated": { "enum": ["authenticated", "rejected", "unknown"] },"protocol": {"type": ["string", "null"],- "enum": [null, "anthropic", "openai_responses", "openai_chat"]+ "enum": [null, "anthropic", "openai_responses", "openai_chat", "google"]},"discovery": { "enum": ["succeeded", "failed", "not_attempted"] },"models": {@@ -150,7 +150,7 @@],"examples": [{- "contract_version": 11,+ "contract_version": 12,"outcome": "observed","reachable": true,"authenticated": "authenticated",@@ -165,7 +165,7 @@]},{- "contract_version": 11,+ "contract_version": 12,"outcome": "authentication_failed","reachable": true,"authenticated": "rejected",@@ -175,7 +175,7 @@"model_metadata": []},{- "contract_version": 11,+ "contract_version": 12,"outcome": "ambiguous","reachable": true,"authenticated": "unknown",@@ -185,7 +185,7 @@"model_metadata": []},{- "contract_version": 11,+ "contract_version": 12,"outcome": "unreachable","reachable": false,"authenticated": "unknown",@@ -195,7 +195,7 @@"model_metadata": []},{- "contract_version": 11,+ "contract_version": 12,"outcome": "adapter_error","reachable": null,"authenticated": "unknown",@@ -205,7 +205,7 @@"model_metadata": []},{- "contract_version": 11,+ "contract_version": 12,"outcome": "timeout","reachable": null,"authenticated": "unknown",diff --git a/docs/plans/model-hub-contracts/opencode-overlay.md b/docs/plans/model-hub-contracts/opencode-overlay.mdindex f82ebbcbc..987505a25 100644--- a/docs/plans/model-hub-contracts/opencode-overlay.md+++ b/docs/plans/model-hub-contracts/opencode-overlay.md@@ -1,6 +1,6 @@# OpenCode overlay contract (v4, 2026-09-04)-<!-- authority-consumer: protocol anthropic openai_responses openai_chat -->+<!-- authority-consumer: protocol anthropic openai_responses openai_chat google -->How Avibe generates the OpenCode runtime config overlay in Gateway mode. Owner-lockedidentifier rules (spec §4.8 v4) restated as testable requirements. Supersedes the 07-23diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonindex fb57b3762..1de930514 100644--- a/docs/plans/model-hub-contracts/probe-result.schema.json+++ b/docs/plans/model-hub-contracts/probe-result.schema.json@@ -7,7 +7,7 @@"required": ["contract_version", "backend", "channel", "reachable", "source_id", "model_id", "latency_ms", "error"],"additionalProperties": false,"properties": {- "contract_version": { "const": 11 },+ "contract_version": { "const": 12 },"backend": { "enum": ["claude", "codex", "opencode", "avibe"] },"channel": { "enum": ["hub", "native_cli"] },"reachable": { "type": "boolean" },@@ -66,10 +66,10 @@}],"examples": [- { "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" }+ { "contract_version": 12, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },+ { "contract_version": 12, "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": 12, "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": 12, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },+ { "contract_version": 12, "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/runtime-dependency.schema.json b/docs/plans/model-hub-contracts/runtime-dependency.schema.jsonindex 70ddc128c..d90624711 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": 11 },+ "contract_version": { "const": 12 },"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": 11,+ "contract_version": 12,"host_platform": "darwin-arm64","manifest": {"name": "cliproxyapi",diff --git a/docs/plans/model-hub-contracts/source-create.schema.json b/docs/plans/model-hub-contracts/source-create.schema.jsonindex d3087432d..f9be7cf35 100644--- a/docs/plans/model-hub-contracts/source-create.schema.json+++ b/docs/plans/model-hub-contracts/source-create.schema.json@@ -6,6 +6,12 @@"type": "object","required": ["vendor", "key"],"additionalProperties": false,+ "allOf": [+ {+ "if": { "required": ["protocol"], "properties": { "protocol": { "const": "google" } } },+ "then": { "properties": { "vendor": { "const": "custom" } } }+ }+ ],"properties": {"save_unverified": {"type": "boolean",@@ -33,7 +39,7 @@"description": "Transient plaintext credential. It is never returned or persisted in Source state."},"protocol": {- "enum": ["anthropic", "openai_responses", "openai_chat"],+ "enum": ["anthropic", "openai_responses", "openai_chat", "google"],"description": "Optional user-selected interface. When present, observation probes exactly this protocol. Omission selects the shipped vendor pin when one exists; otherwise custom Auto requires matching response proof. Explicit unverified saving requires a catalog pin or a concrete custom declaration and never guesses a protocol."},"client_nonce": {diff --git a/docs/plans/model-hub-contracts/source-probe-result.schema.json b/docs/plans/model-hub-contracts/source-probe-result.schema.jsonindex 41f5cdd12..4b58e237a 100644--- a/docs/plans/model-hub-contracts/source-probe-result.schema.json+++ b/docs/plans/model-hub-contracts/source-probe-result.schema.json@@ -9,7 +9,7 @@"properties": {"source_id": {"type": "string", "minLength": 1},"model_id": {"type": "string", "minLength": 1},- "protocol": {"enum": ["anthropic", "openai_responses", "openai_chat"]},+ "protocol": {"enum": ["anthropic", "openai_responses", "openai_chat", "google"]},"reachable": {"type": "boolean"},"latency_ms": {"type": "integer", "minimum": 0},"error": {"type": ["string", "null"]}diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex d58e99133..03a0464fc 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -69,7 +69,8 @@"enum": ["anthropic","openai_responses",- "openai_chat"+ "openai_chat",+ "google"]},"base_url": {@@ -484,6 +485,10 @@}},"allOf": [+ {+ "if": { "properties": { "protocol": { "const": "google" } } },+ "then": { "properties": { "vendor": { "const": "custom" } } }+ },{"$comment": "v2 (07-29, review round 4): EXHAUSTIVE SWEEP of the kind / channel / credential correlations this file states in prose. Round 4 named two instances of the class (`projected_exhaust_at` unconstrained by `kind`, native-CLI reauth able to acquire a `credential_ref`); patching only those two would leave the rest of the same class writable, so every 'X only' / 'null for Y' sentence in this file is now a conditional. Three correlations are deliberately NOT constrained, recorded here so a later reader can tell judgement from oversight: `account_label` (display identity, may be populated for either kind by a later adapter rev — the prose scopes its PURPOSE to subscriptions, it does not forbid the field elsewhere); `usage.cycle_used_pct` / `month_spend_cents` against `billing` (a metered relay can bill in monthly cycles, and no rule here says otherwise); and `billing` against `kind` (a prepaid subscription and a monthly-invoiced key both exist upstream). Constraining those would be inventing product rules under cover of a review fix.","if": {diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonindex 4849398f2..92e997628 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, 11],+ "enum": [5, 6, 7, 8, 9, 10, 11, 12],"$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."},@@ -419,7 +419,7 @@],"examples": [{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_01k9x2m4","ts": "2026-07-29T06:32:11Z","agent": "claude",@@ -444,7 +444,7 @@"blockers": []},{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_01k9x33p","ts": "2026-07-29T06:41:02Z","agent": "opencode",@@ -465,7 +465,7 @@"blockers": []},{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_01k9x3zq","ts": "2026-07-29T06:48:20Z","agent": "codex",@@ -485,7 +485,7 @@]},{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_01k9x4b7","ts": "2026-07-29T07:02:44Z","agent": "claude",@@ -505,7 +505,7 @@"blockers": []},{- "contract_version": 11,+ "contract_version": 12,"turn_id": "turn_modelmissing01","ts": "2026-09-05T17:31:10Z","agent": "claude",@@ -527,7 +527,7 @@"blockers": []},{- "contract_version": 11,+ "contract_version": 12,"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.pyindex 66a3418a6..51e79814d 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -112,7 +112,7 @@ class ModelHubLaunch:"backend": self.backend,"requested_model": self.requested_model,"protocol": self.protocol,- "base_url": f"{self.gateway_base_url.rstrip('/')}/v1",+ "base_url": f"{self.gateway_base_url.rstrip('/')}/{'v1beta' if self.protocol == 'google' else 'v1'}","token": self.gateway_token,"runtime_model": self.runtime_model,"source_id": self.source_id,diff --git a/scripts/check_model_hub_authorities.py b/scripts/check_model_hub_authorities.pyindex 63ddc008b..489435f7e 100644--- a/scripts/check_model_hub_authorities.py+++ b/scripts/check_model_hub_authorities.py@@ -130,13 +130,25 @@ def _schema_property_names(source: AuthorityInput, relative: str) -> set[str]:return names-def _schema_decision_tokens(source: AuthorityInput, relative: str) -> set[str]:+def _schema_decision_tokens(+ source: AuthorityInput,+ relative: str,+ *,+ allowed_property_values: dict[tuple[str | int, ...], set[str]] | None = None,+) -> set[str]:"""Collect schema-controlled field names and closed values, never prose."""tokens: set[str] = set()- def walk(node: Any) -> None:+ def walk(node: Any, path: tuple[str | int, ...] = ()) -> None:if isinstance(node, dict):+ # Exceptions name an exact property schema, never a global token.+ # Field names/required entries stay guarded even at that location.+ allowed = (+ (allowed_property_values or {}).get(path, set())+ if len(path) >= 2 and path[-2] == "properties"+ else set()+ )properties = node.get("properties")if isinstance(properties, dict):tokens.update(properties)@@ -145,15 +157,15 @@ def _schema_decision_tokens(source: AuthorityInput, relative: str) -> set[str]:tokens.update(value for value in required if isinstance(value, str))enum = node.get("enum")if isinstance(enum, list):- tokens.update(value for value in enum if isinstance(value, str))+ tokens.update(value for value in enum if isinstance(value, str) and value not in allowed)const = node.get("const")- if isinstance(const, str):+ if isinstance(const, str) and const not in allowed:tokens.add(const)- for value in node.values():- walk(value)+ for key, value in node.items():+ walk(value, (*path, key))elif isinstance(node, list):- for value in node:- walk(value)+ for index, value in enumerate(node):+ walk(value, (*path, index))walk(source.json(relative))return tokens@@ -706,7 +718,14 @@ def check(root: Path = ROOT) -> dict[str, Any]:for pattern in absence["scope_globs"]:for path in source.glob(pattern):relative = path.relative_to(root).as_posix()- tokens = _schema_decision_tokens(source, relative)+ tokens = _schema_decision_tokens(+ source, relative,+ allowed_property_values={+ tuple(item["property_path"]): set(item["values"])+ for item in absence.get("allowed_property_values", ())+ if item["file"] == relative+ },+ )for term in sorted(terms & tokens):findings.append({diff --git a/tests/e2e/test_model_hub_google.py b/tests/e2e/test_model_hub_google.pynew file mode 100644index 000000000..58a64e83b--- /dev/null+++ b/tests/e2e/test_model_hub_google.py@@ -0,0 +1,145 @@+"""Google frontend against the shipped CPA binary, never a live vendor.++Unit transport mocks cannot prove CPA registration or translation: this layer+checks the real gateway/router/adapter/engine with only loopback fixture traffic.+"""++from __future__ import annotations++import json+from urllib.parse import quote++import aiohttp+from aiohttp import web+import pytest++from core.handlers.model_hub.provenance import SERVED_HOP_HEADER+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+from tests.e2e.drivers.mock_llm_upstream import _buffered_response, _stream_frames+from tests.e2e.test_model_hub_runtime import _isolated_engine_adapter+from tests.scenario_harness.model_hub import MemoryModelHubStore, service_for+from tests.test_model_hub_avibe_consumer import _avibe_service+from tests.test_model_hub_google import GOOGLE_RESPONSE, _server, _sse+from tests.test_model_hub_l3 import _source+++pytestmark = pytest.mark.e2e_model_hub++[email protected](("frontend", "protocol", "model_id"), [+ (frontend, protocol, "fixture-model")+ for frontend, protocol in [+ ("google", "google"), ("google", "anthropic"), ("google", "openai_responses"), ("google", "openai_chat"),+ ("anthropic", "google"), ("openai_responses", "google"), ("openai_chat", "google"),+ ]+] + [+ # CPA must receive the literal registered identity after HTTP normalization;+ # a Python loopback endpoint alone cannot prove the engine's route match.+ ("google", "openai_chat", model_id) for model_id in (+ "../fixture", "/fixture", "nested/../fixture", "fixture:free",+ )+])[email protected]("stream", [False, True])+async def test_real_google_frontend_uses_pinned_engine_and_reports_serving_origin(+ tmp_path, monkeypatch, frontend, protocol, model_id, stream,+):+ requests = []++ async def upstream(request):+ body = await request.json()+ requests.append((request.path, body, dict(request.headers)))+ google = protocol == "google"+ streaming = "streamGenerateContent" in request.path if google else body.get("stream")+ raw = (+ _sse(GOOGLE_RESPONSE) if google else b"".join(_stream_frames(protocol, body))+ ) if streaming else json.dumps(GOOGLE_RESPONSE if google else _buffered_response(protocol, body)).encode()+ if protocol == "openai_chat" and streaming:+ # The general three-protocol mock ends with [DONE] alone. Gemini+ # translation requires the upstream's native finish_reason too.+ raw = raw.replace(b"data: [DONE]", _sse({+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],+ }) + b"data: [DONE]")+ return web.Response(body=raw, content_type="text/event-stream" if streaming else "application/json")++ with _isolated_engine_adapter(tmp_path, monkeypatch) as adapter:+ async with _server(upstream) as root:+ source = _source("src_google001", "Fixture", vendor="custom", protocol=protocol, model_id=model_id)+ source.base_url = root + ("/v1" if protocol == "openai_responses" else "")+ source.credential_ref = adapter.state_store.store_api_key(+ "synthetic-google-integration", vendor="custom", protocol=protocol, base_url=source.base_url,+ )+ config = _avibe_service(tmp_path, [source]).store.config+ service = service_for(tmp_path, MemoryModelHubStore(config), adapter)+ await service.runtime_start()+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:real-google", turn_id="real-google")+ # The upstream determines the primary frontend. Ask the same+ # admitted gateway for Google to exercise CPA's conversion.+ base = hop["base_url"].rsplit("/", 1)[0]+ method = "streamGenerateContent?alt=sse" if stream else "generateContent"+ prompt = "真实 fixture: 上海"+ if frontend == "google":+ endpoint = f'/v1beta/models/{quote(hop["runtime_model"], safe="")}:{method}'+ body = {"contents": [{"role": "user", "parts": [{"text": prompt}]}]}+ else:+ endpoint = "/v1/" + {+ "anthropic": "messages", "openai_responses": "responses", "openai_chat": "chat/completions",+ }[frontend]+ body = {"model": hop["runtime_model"], "stream": stream}+ if frontend == "openai_responses":+ body.update(input=prompt, max_output_tokens=128)+ else:+ body.update(messages=[{"role": "user", "content": prompt}], max_tokens=128)+ async with aiohttp.ClientSession() as client:+ async with client.post(+ base + endpoint,+ headers={"Authorization": f'Bearer {hop["token"]}'}, json=body,+ ) as response:+ raw = await response.read()+ unsupported_reason = None+ if frontend == "google" and ":" in model_id:+ unsupported_reason = b"google_model_path_unsupported"+ elif frontend == "google" and protocol == "openai_responses" and stream:+ unsupported_reason = b"google_stream_responses_unsupported"+ if unsupported_reason is not None:+ assert response.status == 422, raw+ assert SERVED_HOP_HEADER not in response.headers+ assert unsupported_reason in raw+ assert requests == []+ return+ assert response.status == 200, raw+ if frontend == "google":+ assert b"candidates" in raw+ assert b"mock response" in raw or b"Answer" in raw+ origin = json.loads(response.headers[SERVED_HOP_HEADER])+ assert origin == {"provider": "custom", "api": protocol, "model": model_id}+ completion = router.settle_turn(+ "real-google", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-10-02T09:00:00Z",+ )+ if completion:+ await completion+ record = service.provenance.get("real-google")+ assert record["outcome"] == "served", (record, raw)+ assert record["served"]["origin"] == origin+ assert len(requests) == 1+ path, body, headers = requests[0]+ assert "真实 fixture: 上海" in json.dumps(body, ensure_ascii=False)+ if protocol == "google":+ assert path == f"/v1beta/models/{model_id}:{method.split('?')[0]}"+ assert headers["X-Goog-Api-Key"] == "synthetic-google-integration"+ # The pinned executor injects model and safetySettings;+ # frontend routing still comes only from the URL.+ assert body["model"] == model_id+ assert "stream" not in body+ else:+ assert body["model"] == model_id+ assert path == {+ "anthropic": "/v1/messages", "openai_responses": "/v1/responses",+ "openai_chat": "/v1/chat/completions",+ }[protocol]+ finally:+ await gateway.close()diff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.pyindex 171306de1..f1fed0516 100644--- a/tests/e2e/test_model_hub_runtime.py+++ b/tests/e2e/test_model_hub_runtime.py@@ -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": 11,+ "contract_version": 12,"error": "feature_disabled",}diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.pyindex e39cba107..05b947220 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 MockLLMUpstreampytestmark = pytest.mark.e2e_model_hub-CONTRACT_VERSION = 11+CONTRACT_VERSION = 12MENU_MODEL = "claude-sonnet-4-6"SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex e73ccd819..4b8c00367 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -114,7 +114,7 @@ scenarios:backend: sharedtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_catalog_api_key_setup_observe_then_create_closed_loop- id: AUTH-SETUP-112- name: API-key setup verifies from a credential-gated model list, or saves unverified with best-effort inventory, and never schedules a model+ name: API-key setup verifies from a credential-gated model list, or saves unverified with best-effort inventory, and never schedules a model; explicit Google uses GET-only native inventorystatus: coveredkind: happy_pathlayer: scenariodiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex ec825622b..e29c4e910 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -3673,6 +3673,7 @@ def test_api_key_setup_does_not_schedule_a_model("openai_responses": "/v1/responses","openai_chat": "/v1/chat/completions",}+ listing_path = "/v1beta/models" if protocol == "google" else "/v1/models"async def upstream(request):body = await request.json() if request.method == "POST" else None@@ -3680,6 +3681,8 @@ def test_api_key_setup_does_not_schedule_a_model(supplied_key = (request.headers.get("x-api-key")if protocol == "anthropic"+ else request.headers.get("x-goog-api-key")+ if protocol == "google"else request.headers.get("Authorization", "").removeprefix("Bearer ")) or ""observed_credentials.add(supplied_key)@@ -3698,6 +3701,8 @@ def test_api_key_setup_does_not_schedule_a_model(if supplied_key != valid_key and not (request.method == "GET" and public_inventory):return web.json_response({"code": "INVALID_API_KEY"}, status=401)if request.method == "GET":+ if protocol == "google":+ return web.json_response({"models": [{"name": "models/relay-model"}]})return web.json_response({"data": [{"id": "relay-model"}]})if "model" in body:return web.json_response(@@ -3710,8 +3715,13 @@ def test_api_key_setup_does_not_schedule_a_model()upstream_app = web.Application()- upstream_app.router.add_post(paths[protocol], upstream)- upstream_app.router.add_get("/v1/models", upstream)+ if protocol == "google":+ # An unexpected generation request must be observed, not hidden by+ # a 404: explicit Google observation has only a listing witness.+ upstream_app.router.add_post("/{path:.*}", upstream)+ else:+ upstream_app.router.add_post(paths[protocol], upstream)+ upstream_app.router.add_get(listing_path, upstream)web_runner = web.AppRunner(upstream_app)await web_runner.setup()site = web.TCPSite(web_runner, "127.0.0.1", 0)@@ -3758,7 +3768,7 @@ def test_api_key_setup_does_not_schedule_a_model(# The explicit save observes nothing. Its one request is the# best-effort inventory, which fills the Source without# answering the credential question the listing left open.- assert requests[before:] == [("GET", "/v1/models", None)]+ assert requests[before:] == [("GET", listing_path, None)]assert len(store.config.sources) == 1h.source = store.config.sources[0].to_payload()assert h.source["protocol"] == protocol@@ -3793,10 +3803,13 @@ def test_api_key_setup_does_not_schedule_a_model(# all, which is what tells a gated inventory from a public one."",}- assert all(- path == (paths[protocol] if method == "POST" else "/v1/models")- for method, path, _ in requests- )+ if protocol == "google":+ assert all((method, path, body) == ("GET", listing_path, None) for method, path, body in requests)+ else:+ assert all(+ path == (paths[protocol] if method == "POST" else "/v1/models")+ for method, path, _ in requests+ )assert all("model" not in body for _, _, body in requests if body is not None)finally:await web_runner.cleanup()diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 0e07840ae..4a04a59fa 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -1025,7 +1025,7 @@ def test_runtime_start_is_explicit_and_returns_v4_status(tmp_path):assert adapter.start_calls == 1assert store.config.enabled is Trueassert runtime["enabled"] is True- assert runtime["contract_version"] == 11+ assert runtime["contract_version"] == 12assert runtime["status"]["health"] == "ok"_assert_valid("runtime-dependency.schema.json", runtime)@@ -1332,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": 11, "status": {"health": "ok"}}+ return {"contract_version": 12, "status": {"health": "ok"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1349,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": 11, "status": {"health": "not_started"}}+ return {"contract_version": 12, "status": {"health": "not_started"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1366,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": 11, "status": {"health": "installing"}}+ return {"contract_version": 12, "status": {"health": "installing"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1384,7 +1384,7 @@ def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypatdef rpc(operation, payload=None):calls.append((operation, payload))return {- "contract_version": 11,+ "contract_version": 12,"changed": True,"status": {"health": "not_started", "verified": True},}@@ -4801,7 +4801,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):assert response.status_code == 200assert response.get_json() == {"ok": True,- "contract_version": 11,+ "contract_version": 12,"agent": {"backend": "codex","mode": "hub",@@ -9620,7 +9620,7 @@ def test_runtime_start_route_requires_csrf_before_starting_engine(monkeypatch, tassert accepted.status_code == 200runtime = accepted.get_json()["runtime"]assert adapter.start_calls == 1- assert runtime["contract_version"] == 11+ assert runtime["contract_version"] == 12_assert_valid("runtime-dependency.schema.json", runtime)diff --git a/tests/test_model_hub_authorities.py b/tests/test_model_hub_authorities.pyindex 8bd54f3a9..906dfbdf0 100644--- a/tests/test_model_hub_authorities.py+++ b/tests/test_model_hub_authorities.py@@ -2,6 +2,7 @@import astfrom collections import Counter+import copyimport jsonfrom pathlib import Pathimport subprocess@@ -142,6 +143,50 @@ def test_new_checks_observe_tracked_edits_and_new_importers(source_repo):]+def test_schema_value_exception_is_limited_to_the_declared_file_and_property_path(source_repo):+ """A valid Source vendor is not retired route policy; no other use is exempt."""+ root = source_repo+ registry = _registry(root)+ registry["schema_absence_checks"] = [{+ "id": "A3", "source_file": "normative.md", "start_marker": "Forbidden:",+ "scope_globs": ["**/*.schema.json"],+ "allowed_property_values": [{+ "file": "source.schema.json",+ "property_path": ["allOf", 0, "then", "properties", "vendor"],+ "values": ["custom"],+ }],+ }]+ _write(root, "docs/plans/model-hub-contracts/mirror-registry.json", json.dumps(registry))+ _write(root, "normative.md", "Forbidden: `follow | custom`, `retired_value`\n")+ baseline = {"allOf": [{"then": {"properties": {"vendor": {"const": "custom"}}}}]}+ _write(root, "source.schema.json", json.dumps(baseline))+ assert check(root)["ok"]++ for mutation, expected in [+ ({"properties": {"custom": {"type": "string"}}}, "custom"),+ ({"properties": {"policy": {"enum": ["custom"]}}}, "custom"),+ ({"properties": {"policy": {"const": "custom"}}}, "custom"),+ ({"properties": {"vendor": {"const": "custom"}}}, "custom"),+ ({"required": ["custom"]}, "custom"),+ ({"properties": {"policy": {"const": "follow"}}}, "follow"),+ ]:+ _write(root, "source.schema.json", json.dumps({**baseline, **mutation}))+ assert check(root)["findings"] == [{+ "kind": "retired_schema_token", "domain": "A3", "file": "source.schema.json", "value": expected,+ }]+ same_property = copy.deepcopy(baseline)+ same_property["allOf"][0]["then"]["properties"]["vendor"] = {"enum": ["custom", "retired_value"]}+ _write(root, "source.schema.json", json.dumps(same_property))+ assert check(root)["findings"] == [{+ "kind": "retired_schema_token", "domain": "A3", "file": "source.schema.json", "value": "retired_value",+ }]+ _write(root, "source.schema.json", json.dumps(baseline))+ _write(root, "other.schema.json", json.dumps(baseline))+ assert check(root)["findings"] == [{+ "kind": "retired_schema_token", "domain": "A3", "file": "other.schema.json", "value": "custom",+ }]++def test_reuses_first_read_and_consumer_tree_only_within_one_input(source_repo, monkeypatch):root = source_repooriginal_text = (diff --git a/tests/test_model_hub_avibe_contract_matrix.py b/tests/test_model_hub_avibe_contract_matrix.pyindex f425a614d..c27d7058a 100644--- a/tests/test_model_hub_avibe_contract_matrix.py+++ b/tests/test_model_hub_avibe_contract_matrix.py@@ -48,13 +48,13 @@ def _fixture(kind):# 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,+ "contract_version": 12, "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",+ "contract_version": 12, "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}],@@ -66,7 +66,7 @@ def _fixture(kind):"proposed_action": "import", "selected": False,}return {- "contract_version": 11, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z",+ "contract_version": 12, "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,diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex af5aa25b1..5ee90877b 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -82,19 +82,20 @@ def test_auto_detect_asks_for_responses_before_chat():labelled by the older surface it also still serves. Elimination consumesthis sequence pairwise, so the relative position is a contract rather thanan accident of how the tuple was typed: asserting it here makes a reorder a- deliberate change instead of a silent one. The whole vocabulary is asserted- to stay in the sequence so a protocol cannot drop out of detection either.+ deliberate change instead of a silent one. Google is explicitly declared:+ there is no model-free Gemini inference endpoint to add to this sequence."""auto_sequence = ModelHubService._observation_protocols("custom", {})- assert set(auto_sequence) == set(SOURCE_PROTOCOLS)+ assert set(auto_sequence) == set(SOURCE_PROTOCOLS) - {"google"}+ assert ModelHubService._observation_protocols("custom", {"protocol": "google"}) == ("google",)assert len(auto_sequence) == len(set(auto_sequence))assert auto_sequence.index("openai_responses") < auto_sequence.index("openai_chat")def test_unsaved_observation_schema_closes_all_terminal_shapes():schema = _schema("observation-result.schema.json")- assert schema["properties"]["contract_version"]["const"] == 11+ assert schema["properties"]["contract_version"]["const"] == 12assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(member.value for member in ObservationOutcome)@@ -118,7 +119,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():def payload(observation: SourceObservation) -> dict:return {- "contract_version": 11,+ "contract_version": 12,"outcome": observation.outcome.value,"reachable": observation.reachable,"authenticated": (@@ -698,7 +699,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():route_refusal = {"ok": False,- "contract_version": 11,+ "contract_version": 12,"error": "source_in_route_chain","detail": "modelHub.errors.source_in_route_chain","would_remove_hops": [hop],@@ -714,7 +715,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():}candidate_refusal = {"ok": False,- "contract_version": 11,+ "contract_version": 12,"error": "candidate_suppliers_changed","detail": "modelHub.errors.candidate_suppliers_changed","changed": {@@ -798,7 +799,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"] == 11+ assert registry["contract_version"] == 12ids = [entry["id"] for entry in registry["entries"]]assert idsassert len(ids) == len(set(ids))@@ -935,8 +936,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, 11],- "expected": [5, 6, 7, 8, 9, 10, 11],+ "values": [6, 7, 8, 9, 10, 11, 12],+ "expected": [5, 6, 7, 8, 9, 10, 11, 12],} in result["findings"]@@ -1247,7 +1248,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():with pytest.raises(ValidationError):chain_validator.validate(interrupted)exact_hop = {- "contract_version": 11,+ "contract_version": 12,"backend": "claude","model_id": "claude-opus-4-6","manual_override": None,diff --git a/tests/test_model_hub_google.py b/tests/test_model_hub_google.pynew file mode 100644index 000000000..f0643db9f--- /dev/null+++ b/tests/test_model_hub_google.py@@ -0,0 +1,604 @@+"""Google's native wire at Model Hub's actual owning boundaries.++The existing three-protocol tests cannot detect a fourth protocol being admitted+but misrouted through a JSON model/stream field, losing Gemini terminal/usage+facts, or forwarding primary-origin thought signatures after fallback.+"""++from __future__ import annotations++import copy+import io+import json+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock++import aiohttp+from aiohttp import web+import pytest+import yaml+from jsonschema import ValidationError++from config.v2_config import ModelHubModelConfig, ModelHubRouteConfig, ModelHubRouteHopConfig, ModelHubSourceConfig+from core.handlers.model_hub.adapter import ObservationOutcome, RawOutcomeKind, SourceBinding+from core.handlers.model_hub.provenance import SERVED_HOP_HEADER+from core.run_settlement import SETTLED_BY_TERMINAL_RESULT+from core.handlers.model_hub.stream_wire import (+ ProtocolSSEState,+ ProtocolUsageReport,+ observe_buffered_protocol_response,+)+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from core.handlers.model_hub.request import ModelHubRequest+from core.handlers.model_hub.service import ModelHubError+from modules.agents.model_hub import ModelHubRuntimeRouter+from tests.test_model_hub_avibe_consumer import _avibe_service, _validate+from tests.test_model_hub_l3 import InvokeHandle, LiveInvokeHandle, _outcome, _source+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter+from vibe.model_hub_runtime.client import EngineClient, EngineClientError, EngineConnection, probe_models+from vibe.model_hub_runtime.config import render_engine_config+from vibe.model_hub_runtime.state import EngineStateStore, RuntimeSecrets, SourceRecord+from vibe.model_hub_runtime.state import EngineStateError+++GOOGLE_RESPONSE = {+ "candidates": [{+ "content": {"role": "model", "parts": [{"text": "Answer: 上海"}]},+ "finishReason": "STOP",+ "index": 0,+ }],+ "usageMetadata": {+ "promptTokenCount": 12, "cachedContentTokenCount": 4,+ "candidatesTokenCount": 3, "thoughtsTokenCount": 2, "totalTokenCount": 17,+ },+}+++def _sse(payload):+ return b"data: " + json.dumps(payload, ensure_ascii=False).encode() + b"\n\n"+++@asynccontextmanager+async def _server(handler):+ app = web.Application()+ app.router.add_route("*", "/{path:.*}", handler)+ runner = web.AppRunner(app, access_log=None)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ try:+ port = site._server.sockets[0].getsockname()[1]+ yield f"http://127.0.0.1:{port}"+ finally:+ await runner.cleanup()++[email protected]("suffix", ["", "/v1beta"])+def test_google_source_roundtrips_and_uses_native_engine_registration(tmp_path, suffix):+ """Persisted Source, runtime state and CPA YAML must agree on one protocol."""+ source = _source("src_google001", "Google", vendor="custom", protocol="google")+ source.base_url = f"https://upstream.invalid/proxy{suffix}"+ payload = source.to_payload()+ assert ModelHubSourceConfig.from_payload(payload).to_payload() == payload+ _validate("source.schema.json", payload)+ store = EngineStateStore(tmp_path / "state")+ credential = store.store_api_key(+ "synthetic-google-key", vendor="custom", protocol="google", base_url=source.base_url,+ )+ record = SourceRecord(+ source_id=source.id, vendor="custom", protocol="google", base_url=source.base_url,+ credential_ref=credential, allowed_origins=(), model_ids=("gemini-fixture",), prefix="google-fixture",+ )+ store.replace_sources([record])+ assert store.list_sources() == [record]+ rendered = yaml.safe_load(render_engine_config(+ tmp_path / "config.yaml", host="127.0.0.1", port=12345, auth_dir=tmp_path / "auth",+ runtime_secrets=RuntimeSecrets("synthetic-management", "synthetic-gateway"),+ sources=[record], state_store=store,+ ))+ assert rendered["gemini-api-key"] == [{+ "api-key": "synthetic-google-key", "prefix": "google-fixture",+ "base-url": "https://upstream.invalid/proxy",+ "models": [{"name": "gemini-fixture", "alias": "gemini-fixture", "display-name": "gemini-fixture #0"}],+ }]+ assert "openai-compatibility" not in rendered++[email protected]("vendor", ["relay-x", "openai"])[email protected]("boundary", ["config", "schema", "create-schema", "observe", "create", "save", "runtime"])+async def test_google_vendor_refusal_is_shared_by_source_admission(tmp_path, vendor, boundary):+ """Unpinned vendors must not bypass Google's custom-only provider identity."""+ source = _source("src_google001", "Google", vendor=vendor, protocol="google")+ source.base_url = "https://upstream.invalid"+ draft = {+ "vendor": vendor, "protocol": "google", "base_url": source.base_url, "key": "synthetic-key",+ }+ if boundary == "config":+ with pytest.raises(ValueError, match="Google"):+ ModelHubSourceConfig.from_payload(source.to_payload())+ elif boundary in {"schema", "create-schema"}:+ with pytest.raises(ValidationError) as refused:+ _validate(+ "source.schema.json" if boundary == "schema" else "source-create.schema.json",+ source.to_payload() if boundary == "schema" else draft,+ )+ assert list(refused.value.absolute_path) == ["vendor"]+ elif boundary == "runtime":+ store = EngineStateStore(tmp_path / "state")+ credential = store.store_api_key(+ "synthetic-key", vendor=vendor, protocol="google", base_url=source.base_url,+ )+ with pytest.raises(EngineStateError, match="Google"):+ store.sync_sources([SourceBinding(+ source_id=source.id, vendor=vendor, protocol="google", base_url=source.base_url,+ credential_ref=credential, allowed_origins=(), model_ids=("gemini-fixture",),+ )])+ assert store.list_sources() == []+ else:+ from tests.test_model_hub_api import _service++ service, store, adapter = _service(tmp_path)+ with pytest.raises(ModelHubError):+ if boundary == "observe":+ await service.observe_source(draft)+ else:+ await service.create_source({+ **draft, "kind": "api_key", "save_unverified": boundary == "save",+ })+ assert store.config.sources == []+ assert adapter.credential_count == 0++[email protected]("base_url", [None, "https://upstream.invalid/v1beta?api-version=fixture"])+def test_google_target_refuses_unrenderable_roots_before_runtime_state_change(tmp_path, base_url):+ """Google has no vendor-default root, and CPA appends paths rather than joining query URLs."""+ store = EngineStateStore(tmp_path / "state")+ credential = store.store_api_key("synthetic-key", vendor="custom", protocol="google", base_url=base_url)+ with pytest.raises(EngineStateError, match="Google"):+ store.sync_sources([SourceBinding(+ source_id="src_google001", vendor="custom", protocol="google", base_url=base_url,+ credential_ref=credential, allowed_origins=(), model_ids=("gemini-fixture",),+ )])+ assert store.list_sources() == []++[email protected]("stream", [False, True])[email protected]("upstream_protocol", ["google", "anthropic", "openai_responses", "openai_chat"])[email protected]("model_id", ["vendor/model-中文", "../fixture", "/fixture", "nested/../fixture"])+async def test_google_engine_frontend_addresses_routed_model_in_url(stream, upstream_protocol, model_id):+ """CPA selects the upstream using its path, regardless of Source protocol."""+ received = []++ async def handle(request):+ received.append((request.path, dict(request.query), await request.json(), dict(request.headers)))+ return web.Response(+ body=_sse(GOOGLE_RESPONSE) if stream else json.dumps(GOOGLE_RESPONSE).encode(),+ content_type="text/event-stream" if stream else "application/json",+ )++ async with _server(handle) as root:+ client = EngineClient(EngineConnection(root, "unused-management", "synthetic-gateway"))+ source = SourceRecord(+ source_id="src_google001", vendor="custom", protocol=upstream_protocol,+ base_url="https://upstream.invalid", credential_ref="cred_google001",+ allowed_origins=(), model_ids=(model_id,), prefix="fixture",+ )+ payload = {"contents": [{"role": "user", "parts": [{"text": "hello"}]}]}+ handle = await client.invoke(source, model_id, payload, stream=stream, request_protocol="google")+ assert handle.stream is not None+ raw = b"".join([chunk async for chunk in handle.stream])+ await handle.close_stream()+ outcome = await handle.outcome()+ assert outcome.kind == RawOutcomeKind.SUCCESS+ assert outcome.usage == ProtocolUsageReport(input_tokens=12, cached_input_tokens=4, output_tokens=5)+ assert b"Answer" in raw+ path, query, body, headers = received[0]+ action = "streamGenerateContent" if stream else "generateContent"+ assert path == f"/v1beta/models/fixture/{model_id}:{action}"+ assert query == ({"alt": "sse"} if stream else {})+ assert body == payload+ assert headers["Authorization"] == "Bearer synthetic-gateway"++[email protected](("payload", "verified"), [+ (b'{"promptFeedback":{"blockReason":"SAFETY"}}', True),+ (b'{"promptFeedback":{"blockReason":"OTHER"},"usageMetadata":{"promptTokenCount":4}}', True),+ (b'{"promptFeedback":{"blockReason":""}}', False),+ (b'{"promptFeedback":{"blockReason":null}}', False),+ (b'{"promptFeedback":{"blockReason":"SAFETY"},"promptFeedback":{}}', False),+ (b'{"promptFeedback":{"blockReason":"SAFETY"}', False),+ (b'{"promptFeedback":{"blockReason":"SAFETY"},"error":{"code":503}}', False),+])+async def test_google_buffered_prompt_block_proves_recovery_without_candidates(payload, verified):+ """A native blocked completion restores health; metadata/malformed/error bodies cannot."""+ async def handle(request):+ return web.Response(body=payload, content_type="application/json")++ async with _server(handle) as root:+ source = SourceRecord(+ source_id="src_google001", vendor="custom", protocol="google", base_url=root,+ credential_ref="cred_google001", allowed_origins=(), model_ids=("fixture",), prefix="fixture",+ )+ client = EngineClient(EngineConnection(root, "unused", "synthetic-key"))+ result = await client.invoke(source, "fixture", {"contents": []}, stream=False)+ assert (await result.outcome()).recovery_verified is verified+ await result.close_stream()+++def test_google_stream_facts_do_not_confuse_metadata_with_output_or_drop_usage():+ """Google has no [DONE]; parts and finishReason carry the distinct facts."""+ state = ProtocolSSEState("google")+ state.observe(_sse({"modelVersion": "gemini-fixture", "usageMetadata": {"promptTokenCount": 12}}))+ assert not state.model_output_started+ assert state.terminal_observation() is None+ state.observe(_sse({"candidates": [{"content": {"role": "model", "parts": [+ {"functionCall": {"name": "lookup", "args": {"city": "上海"}}},+ ]}}]}))+ assert state.model_output_started+ assert state.terminal_observation() is None+ state.observe(_sse(GOOGLE_RESPONSE))+ terminal = state.terminal_observation()+ assert terminal.outcome == "served"+ assert terminal.usage == ProtocolUsageReport(input_tokens=12, cached_input_tokens=4, output_tokens=5)+ buffered = observe_buffered_protocol_response("google", io.BytesIO(json.dumps(GOOGLE_RESPONSE).encode()))+ assert buffered.recovery_verified+ assert buffered.usage == terminal.usage+ # Pinned CPA's Chat translator can emit a usage-only frame after finishReason.+ state.observe(_sse({"candidates": [], "usageMetadata": {+ "promptTokenCount": 20, "cachedContentTokenCount": 5, "candidatesTokenCount": 9,+ }}))+ assert state.terminal_observation().usage == ProtocolUsageReport(+ input_tokens=20, cached_input_tokens=5, output_tokens=9,+ )++[email protected]("event_name", ["", "event: error\n"])+def test_google_stream_error_is_terminal_not_a_success(event_name):+ """Both Gemini-native and CPA's named error envelope must stop delivery."""+ state = ProtocolSSEState("google")+ state.observe(event_name.encode() + _sse({+ "error": {"code": 503, "status": "UNAVAILABLE", "message": "fixture failure"},+ }))+ assert state.terminal_observation().outcome == "failed_terminal"+ assert not state.model_output_started++[email protected](("status", "code"), [(400, "invalid_request_error"), (429, "rate_limit_error"), (503, "server_error")])[email protected]("stream", [False, True])+async def test_google_native_error_codes_reach_existing_retry_classification(status, code, stream):+ """HTTP-200 error bodies must classify the same as their native Google status."""+ async def handle(request):+ payload = {"error": {"code": status, "message": "synthetic-error"}}+ return web.Response(+ body=_sse(payload) if stream else json.dumps(payload).encode(),+ content_type="text/event-stream" if stream else "application/json",+ )++ async with _server(handle) as root:+ client = EngineClient(EngineConnection(root, "unused", "synthetic-key"))+ source = SourceRecord(+ source_id="src_google001", vendor="custom", protocol="google", base_url=root,+ credential_ref="cred_google001", allowed_origins=(), model_ids=("gemini-fixture",), prefix="google",+ )+ result = await client.invoke(source, "gemini-fixture", {"contents": []}, stream=stream)+ outcome = await result.outcome()+ assert outcome.kind == RawOutcomeKind.HTTP_ERROR+ assert outcome.error_code == code+ assert not outcome.stream_started+ await result.close_stream()++[email protected](("stream", "fallback_protocol", "same_origin"), [+ (stream, protocol, same_origin)+ for stream in (False, True)+ for protocol in ("google", "anthropic", "openai_responses", "openai_chat")+ for same_origin in (False, True)+ if not (stream and protocol == "openai_responses" and not same_origin)+])+async def test_google_router_gateway_failover_preserves_visible_history_and_origin(+ tmp_path, stream, fallback_protocol, same_origin,+):+ """A real Google request resolves path identity, strips opacity, and reports the winning admission."""+ primary = _source("src_google001", "Primary", vendor="custom", protocol="google")+ fallback = _source(+ "src_fallback01", "Fallback", vendor="custom", protocol=fallback_protocol, model_id="fallback-model",+ )+ if same_origin:+ fallback.protocol = "google"+ fallback.models[0].id = primary.models[0].id+ raw = _sse(GOOGLE_RESPONSE) if stream else json.dumps(GOOGLE_RESPONSE).encode()+ 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), (raw,)),+ ])+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ signed = {"contents": [+ {"role": "model", "parts": [+ {"text": "Visible thought", "thought": True, "thoughtSignature": "opaque-thought"},+ {"functionCall": {"name": "verify", "args": {"signature": "user-data"}}, "thoughtSignature": "opaque-call"},+ ]},+ {"role": "user", "parts": [{"functionResponse": {"name": "verify", "response": {"signature": "user-data"}}}]},+ ]}+ plain = copy.deepcopy(signed)+ plain["contents"][0]["parts"][0] = {"text": "Visible thought"}+ plain["contents"][0]["parts"][1].pop("thoughtSignature")+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:google", turn_id="turn-google")+ _validate("hop-resolution.schema.json", hop)+ assert hop["base_url"].endswith("/avibe/v1beta")+ action = "streamGenerateContent?alt=sse" if stream else "generateContent"+ async with aiohttp.ClientSession() as client:+ async with client.post(+ f'{hop["base_url"]}/models/{hop["runtime_model"]}:{action}',+ json=signed, headers={"x-goog-api-key": hop["token"]},+ ) as response:+ assert response.status == 200, await response.text()+ assert await response.read() == raw+ origin = json.loads(response.headers[SERVED_HOP_HEADER])+ assert origin == {+ "provider": "custom", "api": fallback.protocol, "model": fallback.models[0].id,+ }+ assert service.adapter.requests[0] == signed+ assert service.adapter.requests[1] == (signed if same_origin else plain)+ assert all(request.protocol == "google" for request in service.adapter.requests)+ completion = router.settle_turn(+ "turn-google", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-10-02T08:00:00Z",+ )+ if completion:+ await completion+ record = service.provenance.get("turn-google")+ _validate("turn-provenance.schema.json", record)+ assert record["served"]["origin"] == origin+ finally:+ await gateway.close()++[email protected]("public", [False, True])+async def test_google_observation_uses_paginated_credential_witness_without_inference(tmp_path, public):+ """Only a declared, credential-gated listing proves auth; every page is truthful inventory."""+ requests = []++ async def handle(request):+ requests.append((request.method, request.path, dict(request.query), request.headers.get("x-goog-api-key")))+ assert request.method == "GET"+ assert request.path == "/proxy/v1beta/models"+ if not public and request.headers.get("x-goog-api-key") is None:+ return web.json_response({"error": {"code": 403, "status": "PERMISSION_DENIED"}}, status=403)+ if request.query.get("pageToken") == "next +/中文":+ return web.json_response({"models": [{"name": "models/gemini-second"}]})+ return web.json_response({+ "models": [{"name": "models/gemini-first"}], "nextPageToken": "next +/中文",+ })++ async with _server(handle) as root:+ store = EngineStateStore(tmp_path / "state")+ base = root + "/proxy/v1beta"+ credential = store.store_api_key("synthetic-key", vendor="custom", protocol="google", base_url=base)+ adapter = CLIProxyEngineAdapter(supervisor=SimpleNamespace(), state_store=store)+ observed = await adapter.observe_source("custom", base, credential, ("google",))+ if public:+ assert observed.outcome != ObservationOutcome.OBSERVED+ else:+ assert observed.outcome == ObservationOutcome.OBSERVED+ assert [model.id for model in observed.models] == ["gemini-first", "gemini-second"]+ models = await probe_models(vendor="custom", protocol="google", base_url=base, secret="synthetic-key")+ assert [model.id for model in models] == ["gemini-first", "gemini-second"]+ assert all(method == "GET" for method, *_ in requests)+ assert all(query.keys() <= {"pageToken"} for _, _, query, _ in requests)++[email protected]("bad_page", [+ b'{}', b'{"models":[null]}', b'{"models":[{"name":"gemini-invalid"}]}',+ b'{"models":[{"name":"models/good","name":null}]}',+ b'{"models":[],"nextPageToken":42}',+ b'{"models":[],"nextPageToken":"repeat"}',+])+async def test_google_discovery_never_publishes_partial_or_repeated_inventory(bad_page):+ """A bad continuation must not replace saved inventory with its first page."""+ calls = 0++ async def handle(request):+ nonlocal calls+ calls += 1+ if calls == 1:+ return web.json_response({"models": [{"name": "models/first"}], "nextPageToken": "repeat"})+ return web.Response(body=bad_page, content_type="application/json")++ async with _server(handle) as root:+ with pytest.raises(EngineClientError):+ await probe_models(vendor="custom", protocol="google", base_url=root, secret="synthetic-key")+ assert calls == 2+++async def test_google_discovery_does_not_follow_redirects_with_credentials():+ """Page tokens are data; redirects must never move a secret to another target."""+ destination_requests = []++ async def destination(request):+ destination_requests.append(request)+ return web.json_response({"models": []})++ async with _server(destination) as other:+ async def redirect(request):+ return web.Response(status=302, headers={"Location": other + "/capture"})++ async with _server(redirect) as root:+ with pytest.raises(EngineClientError, match="HTTP 302"):+ await probe_models(vendor="custom", protocol="google", base_url=root, secret="synthetic-key")+ assert destination_requests == []++[email protected](("suffix", "payload", "token_valid", "status"), [+ (":generateContent", {}, False, 401),+ (":countTokens", {}, True, 404),+ (":streamGenerateContent?alt=json", {}, True, 400),+ (":streamGenerateContent?alt=sse&alt=json", {}, True, 400),+ (":generateContent", {"model": "another-model"}, True, 400),+ (":generateContent", {"stream": True}, True, 400),+])+async def test_google_local_errors_are_native_and_never_admit_a_hop(tmp_path, suffix, payload, token_valid, status):+ """Native endpoint/query/body validation shares all pre-admission no-origin rules."""+ service = _avibe_service(tmp_path, [_source("src_google001", "Google", vendor="custom", protocol="google")], handles=[])+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="avibe:google-errors", turn_id="turn-invalid")+ async with aiohttp.ClientSession() as client:+ async with client.post(+ f'{hop["base_url"]}/models/{hop["runtime_model"]}{suffix}', json=payload,+ headers={"x-goog-api-key": hop["token"] if token_valid else "invalid"},+ ) as response:+ assert response.status == status+ assert SERVED_HOP_HEADER not in response.headers+ error = (await response.json())["error"]+ assert error["code"] == status+ assert isinstance(error["status"], str)+ assert error["message"]+ assert service.adapter.invocations == []+ finally:+ await gateway.close()+++async def test_google_saved_source_probe_speaks_the_declared_protocol(tmp_path):+ """Add-time discovery is not inference; an explicit model test is and needs Gemini's body."""+ service = _avibe_service(tmp_path, [_source("src_google001", "Google", vendor="custom", protocol="google")], handles=[+ InvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id="src_google001")),+ ])+ result = await service.probe_source("src_google001", {"model": "shared-model"})+ _validate("source-probe-result.schema.json", result)+ assert service.adapter.requests == [{+ "contents": [{"role": "user", "parts": [{"text": "ping"}]}],+ "generationConfig": {"maxOutputTokens": 128},+ }]++[email protected]("working_fallback", [False, True])[email protected](("protocol", "model_id", "stream", "reason"), [+ ("openai_responses", "shared-model", True, "google_stream_responses_unsupported"),+] + [+ (protocol, "fixture:free", stream, "google_model_path_unsupported")+ for protocol in ("google", "anthropic", "openai_chat", "openai_responses")+ for stream in (False, True)+])+async def test_google_skips_unsupported_hops_before_admission(+ tmp_path, caplog, working_fallback, protocol, model_id, stream, reason,+):+ """Unsupported conversion is a local skip, never an upstream failure or false success."""+ import logging++ caplog.set_level(logging.INFO, logger="core.handlers.model_hub.service")+ blocked = _source("src_blocked01", "Blocked", vendor="custom", protocol=protocol, model_id=model_id)+ good = _source("src_google001", "Google", vendor="custom", protocol="google", model_id="gemini-fixture")+ raw = _sse(GOOGLE_RESPONSE) if stream else json.dumps(GOOGLE_RESPONSE).encode()+ service = _avibe_service(tmp_path, [blocked, good] if working_fallback else [blocked], handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=good.id), (raw,)),+ ])+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="google:unsupported", turn_id="unsupported")+ base = hop["base_url"].rsplit("/", 1)[0] + "/v1beta"+ action = "streamGenerateContent?alt=sse" if stream else "generateContent"+ async with aiohttp.ClientSession() as client:+ async with client.post(+ f'{base}/models/{hop["runtime_model"]}:{action}',+ headers={"x-goog-api-key": hop["token"]},+ json={"contents": [{"role": "user", "parts": [{"text": "hello"}]}]},+ ) as response:+ if working_fallback:+ assert response.status == 200+ assert json.loads(response.headers[SERVED_HOP_HEADER])["api"] == "google"+ assert await response.read() == raw+ else:+ assert response.status == 422+ assert SERVED_HOP_HEADER not in response.headers+ assert (await response.json())["error"]["details"] == [+ {"reason": reason},+ ]+ assert [call[0] for call in service.adapter.invocations] == ([good.id] if working_fallback else [])+ assert blocked.state.status == "standby"+ assert any(getattr(record, "reason", None) == reason for record in caplog.records)+ completion = router.settle_turn(+ "unsupported", settled_by=SETTLED_BY_TERMINAL_RESULT, ts="2026-10-02T09:00:00Z",+ )+ if completion:+ await completion+ record = service.provenance.get("unsupported")+ _validate("turn-provenance.schema.json", record)+ assert record["failed_attempts"] == []+ assert record["served"]["source_id"] == good.id if working_fallback else record["served"] is None+ finally:+ await gateway.close()++[email protected](("backend", "protocol", "model_id"), [+ ("codex", "google", "shared-model"),+ ("codex", "google", "fixture:free"),+ ("avibe", "openai_chat", "fixture:free"),+])+async def test_other_frontends_and_native_paths_keep_their_admission_policy(tmp_path, backend, protocol, model_id):+ """The Google limitations must not silently broaden to native/other frontends."""+ source = _source("src_blocked01", "Native", protocol="openai_responses", model_id=model_id)+ service = _avibe_service(tmp_path, [source], handles=[+ InvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=source.id)),+ ])+ await service.resolve(+ backend=backend, model_id=service.store.requested_models[backend],+ request=ModelHubRequest({"contents": []}, protocol=protocol), stream=True,+ )+ assert [call[0] for call in service.adapter.invocations] == [source.id]+++async def test_google_unsupported_model_skip_keeps_next_model_on_the_same_source(tmp_path):+ """The colon restriction belongs to the exact hop, not the Source's healthy inventory."""+ source = _source("src_google001", "Google", vendor="custom", protocol="google", model_id="fixture:free")+ source.models.append(ModelHubModelConfig(id="safe-model", provenance="discovered"))+ service = _avibe_service(tmp_path, [source], handles=[+ InvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=source.id)),+ ])+ service.revocations.add("src_retired01", "cred_retired01")+ service.store.config.agents["avibe"].routes["menu-alias"] = ModelHubRouteConfig((+ ModelHubRouteHopConfig(source.id, "fixture:free"),+ ModelHubRouteHopConfig(source.id, "safe-model"),+ ))+ result = await service.resolve(+ backend="avibe", model_id="menu-alias",+ request=ModelHubRequest({"contents": []}, protocol="google"), stream=False,+ )+ assert result.model_id == "safe-model"+ assert service.adapter.invocations == [(source.id, "safe-model", "avibe")]+ assert service.revocations.list() == []++[email protected]("caller", ["turn", "agent_probe"])[email protected]("pending_revocation", [False, True])+async def test_google_unsupported_model_refusal_precedes_engine_work(tmp_path, caller, pending_revocation):+ """Local skips must not start an engine or alter custody before refusing."""+ source = _source("src_google001", "Google", vendor="custom", protocol="google", model_id="fixture:free")+ service = _avibe_service(tmp_path, [source])+ if pending_revocation:+ service.revocations.add("src_retired01", "cred_retired01")+ pending = service.revocations.list()+ before = copy.deepcopy(service.store.config.to_payload())+ generation = service._next_settlement_generation+ service._prepare_engine_for_demand = AsyncMock(wraps=service._prepare_engine_for_demand)+ service._ensure_engine_synced = AsyncMock(wraps=service._ensure_engine_synced)+ with pytest.raises(ModelHubError) as refused:+ if caller == "agent_probe":+ await service.probe_agent("avibe", "menu-alias")+ else:+ await service.resolve(+ backend="avibe", model_id="menu-alias",+ request=ModelHubRequest({"contents": []}, protocol="google"), stream=False,+ )+ assert refused.value.code == "google_model_path_unsupported"+ assert refused.value.status == 422+ assert refused.value.origin is None+ service._prepare_engine_for_demand.assert_not_awaited()+ service._ensure_engine_synced.assert_not_awaited()+ assert service.adapter.invocations == []+ assert service.store.config.to_payload() == before+ assert service.revocations.list() == pending+ assert service._next_settlement_generation == generationdiff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex a0a7861e2..bed1dea83 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -6207,6 +6207,11 @@ def test_production_adapter_retargets_api_keys_without_exposing_or_mutating_themassert asyncio.run(adapter.credential_supports_refresh(oauth_ref)) is True+# These existing evidence tests exercise model-free Auto probes, not Google's+# explicitly declared native model-list witness (covered by test_model_hub_google).+_MODEL_FREE_OBSERVATION_PROTOCOLS = ("anthropic", "openai_responses", "openai_chat")++def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(tmp_path: Path,) -> None:@@ -6215,7 +6220,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(credential_ref = state_store.store_api_key("test-observation-key",vendor="custom",- protocol=SOURCE_PROTOCOLS[-1],+ protocol=_MODEL_FREE_OBSERVATION_PROTOCOLS[-1],base_url=base_url,)adapter = CLIProxyEngineAdapter(@@ -6258,7 +6263,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(shape=_ProtocolObservationShape.NON_JSON,)- hinted_order = tuple(reversed(SOURCE_PROTOCOLS))+ hinted_order = tuple(reversed(_MODEL_FREE_OBSERVATION_PROTOCOLS))async def every_candidate_is_supported(**_kwargs) -> _ProtocolEvidence:return proven_accepted@@ -6371,14 +6376,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert ambiguous.outcome.value == "ambiguous"assert ambiguous.protocol is Noneassert ambiguous.authenticated is True- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()async def structured_unknown_sibling(**kwargs) -> _ProtocolEvidence:@@ -6403,14 +6408,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert ambiguous.outcome.value == "ambiguous"assert ambiguous.protocol is Noneassert ambiguous.authenticated is True- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()async def anthropic_server_error_blocks_openai_pairwise(**kwargs) -> _ProtocolEvidence:@@ -6437,14 +6442,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert ambiguous.outcome.value == "ambiguous"assert ambiguous.protocol is Noneassert ambiguous.authenticated is True- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()timeout = EngineClientError("protocol observation timed out", error_type="timeout")@@ -6473,14 +6478,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert ambiguous.outcome.value == "ambiguous"assert ambiguous.protocol is Noneassert ambiguous.authenticated is True- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()async def anthropic_competes_with_openai_pairwise(**kwargs) -> _ProtocolEvidence:@@ -6507,14 +6512,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert ambiguous.outcome.value == "ambiguous"assert ambiguous.protocol is Noneassert ambiguous.authenticated is True- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()unproven_rejected = _ProtocolEvidence(@@ -6546,14 +6551,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert ambiguous.outcome.value == "ambiguous"assert ambiguous.protocol is Noneassert ambiguous.authenticated is True- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()async def rejected_anthropic_allows_openai_pairwise(**kwargs) -> _ProtocolEvidence:@@ -6580,7 +6585,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))@@ -6588,7 +6593,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(assert observed.protocol == "openai_chat"assert observed.authenticated is Trueassert observed.model_ids == ("chat-only-model",)- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)assert inventory_probe.await_args.kwargs["protocol"] == "openai_chat"transient_non_json = _parse_protocol_authenticated_evidence(@@ -6625,14 +6630,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert ambiguous.outcome.value == "ambiguous"assert ambiguous.protocol is Noneassert ambiguous.authenticated is True- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()async def anthropic_wrapperless_then_absent_openai(**kwargs) -> _ProtocolEvidence:@@ -6659,14 +6664,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert observed.outcome.value == "observed"assert observed.protocol == "anthropic"assert observed.model_ids == ("relay-model",)- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)assert inventory_probe.await_args.kwargs["protocol"] == "anthropic"async def anthropic_wrapperless_with_rejected_openai(**kwargs) -> _ProtocolEvidence:@@ -6693,7 +6698,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))@@ -6701,7 +6706,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(assert observed.protocol == "anthropic"assert observed.authenticated is Trueassert observed.model_ids == ("anthropic-relay-model",)- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)assert inventory_probe.await_args.kwargs["protocol"] == "anthropic"credential_param_rejected = _parse_protocol_authenticated_evidence(@@ -6745,14 +6750,14 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert rejected.outcome.value == "authentication_failed"assert rejected.protocol is Noneassert rejected.authenticated is False- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()with (@@ -6808,7 +6813,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))@@ -6816,12 +6821,12 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(assert upstream_error.reachable is Trueassert upstream_error.authenticated is Noneassert upstream_error.protocol is None- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()_assert_valid("observation-result.schema.json",{- "contract_version": 11,+ "contract_version": 12,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -6832,7 +6837,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(},)- proved_protocol = SOURCE_PROTOCOLS[1]+ proved_protocol = _MODEL_FREE_OBSERVATION_PROTOCOLS[1]async def later_protocol_probe(**kwargs) -> _ProtocolEvidence:if kwargs["protocol"] != proved_protocol:@@ -6854,19 +6859,19 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert observed.outcome.value == "observed"assert observed.protocol == proved_protocolassert observed.model_ids == ("upstream-model",)- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS[:2])+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS[:2])assert inventory_probe.await_args.kwargs["protocol"] == proved_protocolassert inventory_probe.await_args.kwargs["base_url"] == base_url- rejected_protocol = SOURCE_PROTOCOLS[0]- accepted_protocol = SOURCE_PROTOCOLS[1]+ rejected_protocol = _MODEL_FREE_OBSERVATION_PROTOCOLS[0]+ accepted_protocol = _MODEL_FREE_OBSERVATION_PROTOCOLS[1]async def rejected_then_authenticated(**kwargs) -> _ProtocolEvidence:if kwargs["protocol"] == rejected_protocol:@@ -6890,7 +6895,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))@@ -6934,7 +6939,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof("custom",base_url,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))@@ -6942,7 +6947,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(assert rejected.reachable is Trueassert rejected.authenticated is Falseassert rejected.protocol is None- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()@@ -6990,14 +6995,14 @@ def test_source_observation_accepts_catalog_pin_and_custom_declaration_without_s"deepseek",None,catalog_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert observed.outcome.value == "observed"assert observed.protocol == "openai_chat"assert observed.model_ids == ("deepseek-chat",)- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)assert inventory_probe.await_args.kwargs["protocol"] == "openai_chat"with (@@ -7015,14 +7020,14 @@ def test_source_observation_accepts_catalog_pin_and_custom_declaration_without_s"custom","https://api.deepseek.com",custom_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))assert ambiguous.outcome.value == "ambiguous"assert ambiguous.protocol is Noneassert ambiguous.authenticated is True- assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)inventory_probe.assert_not_awaited()with (@@ -7113,7 +7118,7 @@ def test_qwen_catalog_pin_validation_remains_unverified("qwen",None,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,)inventory_kwargs = dict(inventory_probe.await_args.kwargs)finally:@@ -7128,7 +7133,7 @@ def test_qwen_catalog_pin_validation_remains_unverified(assert observed.model_ids == ()assert requests == [_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path- for protocol in SOURCE_PROTOCOLS+ for protocol in _MODEL_FREE_OBSERVATION_PROTOCOLS]assert inventory_kwargs["protocol"] == "openai_chat"@@ -7197,7 +7202,7 @@ def test_openrouter_catalog_pin_numeric_validation_remains_unverified("openrouter",None,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,)inventory_kwargs = dict(inventory_probe.await_args.kwargs)finally:@@ -7212,7 +7217,7 @@ def test_openrouter_catalog_pin_numeric_validation_remains_unverified(assert observed.model_ids == ()assert requests == [_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path- for protocol in SOURCE_PROTOCOLS+ for protocol in _MODEL_FREE_OBSERVATION_PROTOCOLS]assert inventory_kwargs["protocol"] == "openai_chat"@@ -7497,7 +7502,7 @@ def test_custom_auto_numeric_auth_failure_message_stays_authentication_failed("custom",origin,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,)inventory_probe.assert_not_awaited()finally:@@ -7512,7 +7517,7 @@ def test_custom_auto_numeric_auth_failure_message_stays_authentication_failed(assert observed.model_ids == ()assert requests == [_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path- for protocol in SOURCE_PROTOCOLS+ for protocol in _MODEL_FREE_OBSERVATION_PROTOCOLS]@@ -7786,7 +7791,7 @@ def test_auth_setup_executable_scenarios_are_registered() -> None:assert registered[scenario_id]["test"].endswith("::" + node.name)[email protected]("protocol", SOURCE_PROTOCOLS)[email protected]("protocol", _MODEL_FREE_OBSERVATION_PROTOCOLS)@pytest.mark.parametrize("status", [401, 403])@pytest.mark.parametrize("body", ['{"message":"Regional policy"}', '{"error":{"code":"invalid_api_key"}}'])def test_authentication_status_interpretation_preserves_evidence_role(@@ -7863,7 +7868,7 @@ def test_oauth_observation_uses_the_bound_auth_index_and_requires_response_proofvendor,None,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))@@ -7897,7 +7902,7 @@ def test_oauth_observation_uses_the_bound_auth_index_and_requires_response_proofvendor,None,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))@@ -7960,7 +7965,7 @@ def test_oauth_observation_does_not_use_api_key_catalog_pins_without_shape_proof"openai",None,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))@@ -7968,7 +7973,7 @@ def test_oauth_observation_does_not_use_api_key_catalog_pins_without_shape_proofassert ambiguous.protocol is Noneassert ambiguous.authenticated is Truediscover_models.assert_not_awaited()- assert [call.kwargs["protocol"] for call in oauth_probe.call_args_list] == list(SOURCE_PROTOCOLS)+ assert [call.kwargs["protocol"] for call in oauth_probe.call_args_list] == list(_MODEL_FREE_OBSERVATION_PROTOCOLS)@pytest.mark.parametrize("vendor", sorted(_HUB_SUBSCRIPTION_PROTOCOLS))@@ -8031,7 +8036,7 @@ def test_hub_subscription_observation_binds_on_the_engine_declared_protocol(vendor,None,credential_ref,- SOURCE_PROTOCOLS,+ _MODEL_FREE_OBSERVATION_PROTOCOLS,))@@ -8068,7 +8073,7 @@ def test_hub_subscription_projects_on_its_pin_whatever_the_api_key_pin_is(f"{vendor}-test.json",)protocol = hub_subscription_serving_protocol(vendor)- assert protocol in SOURCE_PROTOCOLS+ assert protocol in _MODEL_FREE_OBSERVATION_PROTOCOLSprojected = state_store.sync_sources([@@ -8484,7 +8489,7 @@ def test_openai_family_nested_numeric_auth_failure_message_is_rejected()[email protected]("protocol", SOURCE_PROTOCOLS)[email protected]("protocol", _MODEL_FREE_OBSERVATION_PROTOCOLS)@pytest.mark.parametrize("status", (400, 422))def test_request_error_with_credential_param_is_rejected(protocol: str,@@ -8586,7 +8591,7 @@ def test_request_error_404_and_non_json_responses_are_pairwise_exclusion_shapes(def test_top_level_authentication_rejection_is_classified_without_forging_protocol() -> None:body = json.dumps({"code": "INVALID_API_KEY", "message": "Invalid API key"})- for protocol in SOURCE_PROTOCOLS:+ for protocol in _MODEL_FREE_OBSERVATION_PROTOCOLS:assert _parse_protocol_authenticated_evidence(protocol,401,@@ -8616,7 +8621,7 @@ def test_protocol_observation_preserves_query_on_each_distinct_upstream_path() -assert site._server is not Noneport = site._server.sockets[0].getsockname()[1]try:- for protocol in SOURCE_PROTOCOLS:+ for protocol in _MODEL_FREE_OBSERVATION_PROTOCOLS:await _probe_protocol_response(vendor="custom",protocol=protocol,@@ -8630,11 +8635,11 @@ def test_protocol_observation_preserves_query_on_each_distinct_upstream_path() -requests = asyncio.run(scenario())paths = [path for path, _query, _body in requests]- assert len(paths) == len(SOURCE_PROTOCOLS)+ assert len(paths) == len(_MODEL_FREE_OBSERVATION_PROTOCOLS)assert len(set(paths)) == len(paths)assert {request_query for _path, request_query, _body in requests} == {query}# Model-free bodies fail request validation before a relay schedules capacity.- assert dict(zip(SOURCE_PROTOCOLS, (body for _path, _query, body in requests))) == {+ assert dict(zip(_MODEL_FREE_OBSERVATION_PROTOCOLS, (body for _path, _query, body in requests))) == {"anthropic": {"max_tokens": 0, "messages": []},"openai_responses": {},"openai_chat": {},@@ -8665,7 +8670,7 @@ def test_protocol_observation_classifies_from_the_body_not_the_status(status) ->base_url=f"http://127.0.0.1:{port}/v1",secret="test-observation-key",)- for protocol in SOURCE_PROTOCOLS+ for protocol in _MODEL_FREE_OBSERVATION_PROTOCOLS]finally:await runner.cleanup()@@ -8729,7 +8734,7 @@ def test_protocol_observation_adds_standard_v1_paths_to_a_bare_origin() -> None:assert site._server is not Noneport = site._server.sockets[0].getsockname()[1]try:- for protocol in SOURCE_PROTOCOLS:+ for protocol in _MODEL_FREE_OBSERVATION_PROTOCOLS:await _probe_protocol_response(vendor="custom",protocol=protocol,@@ -8742,7 +8747,7 @@ def test_protocol_observation_adds_standard_v1_paths_to_a_bare_origin() -> None:assert asyncio.run(scenario()) == [_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path- for protocol in SOURCE_PROTOCOLS+ for protocol in _MODEL_FREE_OBSERVATION_PROTOCOLS]@@ -9292,6 +9297,7 @@ def test_probe_2xx_native_auth_error_uses_classified_blocker_detail(({"model", "max_output_tokens", "input"}if source_protocol == "openai_responses"+ else {"contents", "generationConfig"} if source_protocol == "google"else {"model", "max_tokens", "messages"}),)@@ -9307,6 +9313,8 @@ def test_probe_request_matches_live_backend_protocol_matrix() -> None:source = _source("src_primary01", "Primary")source.protocol = source_protocol+ if source_protocol == "google":+ source.vendor = "custom"service = _service(tmp_path,sources=[source],@@ -9349,7 +9357,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": 11,+ "contract_version": 12,"backend": "codex","channel": "native_cli","reachable": True,diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.pyindex b45309472..ef5806cec 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_patdef _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": 11,+ "contract_version": 12,"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(monkeypatf"/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": 11, "provenance": record}+ assert response.get_json() == {"ok": True, "contract_version": 12, "provenance": record}assert store.config.to_payload() == beforeassert adapter.synced == []diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.pyindex 1f2a2de47..1696cd09b 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -1705,7 +1705,7 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):)assert result["observation"] == {- "contract_version": 11,+ "contract_version": 12,"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": 11,+ "contract_version": 12,"outcome": "adapter_error","reachable": None,"authenticated": "unknown",diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 3f61526d2..2ab4809f2 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": 11, **supervisor.status()}+ projected = {"contract_version": 12, **supervisor.status()}schema = json.loads(Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(encoding="utf-8"@@ -8136,7 +8136,8 @@ def test_every_oauth_start_vendor_binds_by_exactly_one_route(protocol=protocol,)except EngineClientError as refused:- assert refused.status_code == 404+ # Google admission is API-key-only; no OAuth probe was added.+ assert refused.status_code == (None if protocol == "google" else 404)assert client.calls == []continueassert client.calls == ["/api-call"]diff --git a/tests/test_model_hub_source_probe.py b/tests/test_model_hub_source_probe.pyindex fb61feb6a..cd5d0c1e3 100644--- a/tests/test_model_hub_source_probe.py+++ b/tests/test_model_hub_source_probe.py@@ -79,9 +79,15 @@ def test_probe_invokes_selected_source_even_without_agent_routes_and_isolates_faargs = adapter.invoke.call_args.argsassert args[:2] == (source_id, model_id)assert args[2].protocol == protocol- assert args[2]["model"] == model_id- budget_key = "max_output_tokens" if protocol == "openai_responses" else "max_tokens"- assert args[2][budget_key] == 128+ if protocol == "google":+ assert args[2] == {+ "contents": [{"role": "user", "parts": [{"text": "ping"}]}],+ "generationConfig": {"maxOutputTokens": 128},+ }+ else:+ assert args[2]["model"] == model_id+ budget_key = "max_output_tokens" if protocol == "openai_responses" else "max_tokens"+ assert args[2][budget_key] == 128assert args[3:] == (False, "opencode")adapter.discover_models.assert_not_awaited()after = store.config.to_payload()@@ -179,6 +185,78 @@ def test_probe_refuses_invalid_or_unknown_selection_before_runtime_work(tmp_pathadapter.invoke.assert_not_awaited()[email protected]("protocol", SOURCE_PROTOCOLS)[email protected]("model_id", ["fixture:free", "../fixture", "/fixture"])[email protected]("selection", ["initial", "reconciled"])+def test_saved_source_probe_checks_google_path_before_engine_and_at_admission(+ tmp_path, protocol, model_id, selection,+):+ """A saved-model test must not turn a known local limitation into upstream evidence.++ The protocol-only probe table missed special model identities and a Source+ changing while engine preparation yields the mutation lock.+ """+ service, store, adapter = _service(tmp_path)++ async def scenario():+ adapter.discover_models = AsyncMock(return_value=(DiscoveredModel(model_id),))+ saved = (await service.create_source(_draft(+ protocol=protocol if selection == "initial" else "openai_chat",+ )))["source"]+ store.config.sources[0].state = ModelHubSourceStateConfig(+ status="cooldown", retry_at="2026-07-23T02:59:00+00:00",+ detail_key="models.source.cooldown.server_error",+ )+ before = copy.deepcopy(store.config.to_payload())+ generation = service._next_settlement_generation+ events = service.events.list()+ original_prepare = service._prepare_engine_for_demand++ async def prepare():+ nonlocal before+ await original_prepare()+ if selection == "reconciled":+ # The saved Source is reloaded after demand preparation; the+ # request must use and check that current protocol snapshot.+ async with service._mutation_lock:+ changed = copy.deepcopy(store.config)+ changed.sources[0].protocol = protocol+ store.save(changed)+ before = copy.deepcopy(store.config.to_payload())++ service._prepare_engine_for_demand = AsyncMock(side_effect=prepare)+ adapter.invoke = AsyncMock(wraps=adapter.invoke)+ service._meter_call = AsyncMock(wraps=service._meter_call)+ service._verify_successful_source = AsyncMock(wraps=service._verify_successful_source)+ service._record_recovery_success = AsyncMock(wraps=service._record_recovery_success)+ if protocol == "google" and ":" in model_id:+ with pytest.raises(ModelHubError) as refused:+ await service.probe_source(saved["id"], {"model": model_id})+ assert refused.value.code == "google_model_path_unsupported"+ assert refused.value.status == 422+ assert refused.value.origin is None+ adapter.invoke.assert_not_awaited()+ service._meter_call.assert_not_awaited()+ service._verify_successful_source.assert_not_awaited()+ service._record_recovery_success.assert_not_awaited()+ assert store.config.to_payload() == before+ assert service._next_settlement_generation == generation+ assert service.events.list() == events+ assert service._prepare_engine_for_demand.await_count == (selection == "reconciled")+ else:+ answer = await service.probe_source(saved["id"], {"model": model_id})+ assert answer["reachable"]+ assert answer["protocol"] == protocol+ assert answer["model_id"] == model_id+ adapter.invoke.assert_awaited_once()+ assert adapter.invoke.call_args.args[1] == model_id+ assert adapter.invoke.call_args.args[2].protocol == protocol+ service._prepare_engine_for_demand.assert_awaited_once()+ assert not service._mutation_lock.locked()++ asyncio.run(scenario())++def test_manual_model_addition_never_calls_upstream_discovery(tmp_path):service, store, adapter = _service(tmp_path)source = asyncio.run(service.create_source(_draft()))["source"]@@ -223,6 +301,11 @@ def test_source_probe_crosses_real_adapter_and_http_transport(tmp_path, protocolasync def handler(request):body = await request.json()requests.append((request.path, body))+ if protocol == "google":+ return web.json_response({+ "candidates": [{"content": {"parts": [{"text": "pong"}]}, "finishReason": "STOP"}],+ "usageMetadata": {"promptTokenCount": 2, "candidatesTokenCount": 1},+ })return web.json_response({"choices": [{"message": {"content": "pong"}, "finish_reason": "stop"}],"content": [{"type": "text", "text": "pong"}],@@ -257,9 +340,17 @@ def test_source_probe_crosses_real_adapter_and_http_transport(tmp_path, protocolassert answer["reachable"]assert len(requests) == 1path, body = requests[0]- assert path == {"anthropic": "/v1/messages", "openai_chat": "/v1/chat/completions", "openai_responses": "/v1/responses"}[protocol]- assert body["model"] == f"{runtime_store.get_source(source['id']).prefix}/{model_id}"- assert body["stream"] is False+ routed_model = f"{runtime_store.get_source(source['id']).prefix}/{model_id}"+ if protocol == "google":+ assert path == f"/v1beta/models/{routed_model}:generateContent"+ assert body == {+ "contents": [{"role": "user", "parts": [{"text": "ping"}]}],+ "generationConfig": {"maxOutputTokens": 128},+ }+ else:+ assert path == {"anthropic": "/v1/messages", "openai_chat": "/v1/chat/completions", "openai_responses": "/v1/responses"}[protocol]+ assert body["model"] == routed_model+ assert body["stream"] is Falseassert transport._active_transports == 0assert not store.config.sources[0].verification_pendingservice._meter_call.assert_awaited_once()diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex 7af6e8d06..8b900af63 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -82,6 +82,32 @@ E64_SETTLEMENT_BOUNDARIES = json.loads((FIXTURES / "e64_settlement_boundaries.js# - https://platform.openai.com/docs/api-reference/responses-streaming# - https://platform.openai.com/docs/api-reference/chat/create#chat-create-streamSTREAM_ENVELOPE_FIXTURES = (+ {+ "protocol": "google", "terminal_fact": "failed_terminal", "event_name": None,+ "selector_path": ("error",), "selector_value": None, "error_paths": (("error",),),+ "payload": b'{"error":{"code":503,"status":"UNAVAILABLE"}}',+ "source": "https://ai.google.dev/api/generate-content",+ },+ {+ "protocol": "google", "terminal_fact": "failed_terminal", "event_name": "error",+ "selector_path": ("error",), "selector_value": None, "error_paths": (("error",),),+ "payload": b'{"error":{"code":503,"status":"UNAVAILABLE"}}',+ "source": "https://github.com/router-for-me/CLIProxyAPI/blob/c404af96/sdk/api/handlers/gemini/gemini_handlers.go",+ },+ {+ "protocol": "google", "terminal_fact": "served", "event_name": None,+ "selector_path": ("candidates", "*", "finishReason"), "selector_value": None,+ "require_nonempty": True, "error_paths": (),+ "payload": b'{"candidates":[{"finishReason":"STOP"}]}',+ "source": "https://ai.google.dev/api/generate-content#FinishReason",+ },+ {+ "protocol": "google", "terminal_fact": "served", "event_name": None,+ "selector_path": ("promptFeedback", "blockReason"), "selector_value": None,+ "require_nonempty": True, "error_paths": (),+ "payload": b'{"promptFeedback":{"blockReason":"SAFETY"}}',+ "source": "https://ai.google.dev/api/generate-content#BlockReason",+ },{"protocol": "anthropic","terminal_fact": "served",@@ -174,6 +200,7 @@ STREAM_ENVELOPE_FIXTURES = (},)MODEL_OUTPUT_ENVELOPE_FIXTURES = (+ ("google", None, ("candidates", "*", "content", "parts"), None, True),("anthropic", "content_block_start", ("type",), "content_block_start", False),("anthropic", "content_block_delta", ("type",), "content_block_delta", False),("openai_responses", "response.output_text.delta", ("type",), "response.output_text.delta", False),@@ -213,7 +240,7 @@ MODEL_OUTPUT_ENVELOPE_FIXTURES = (("openai_chat", None, ("choices", "*", "delta", "function_call"), None, True),)BUFFERED_ERROR_TRUST_ROOT_FIXTURES = {- protocol: (("error",),) for protocol in ("anthropic", "openai_responses", "openai_chat")+ protocol: (("error",),) for protocol in ("anthropic", "openai_responses", "openai_chat", "google")}ACCEPTED_SSE_LINE_ENDINGS = (b"\r\n", b"\n", b"\r")STREAM_BOUNDARY_DIMENSIONS = {@@ -1319,6 +1346,7 @@ def _assert_stream_taxonomy_matches(error_envelope_paths=fixture["error_paths"],required_error_path=fixture.get("required_error_path"),required_error_code_path=fixture.get("required_error_code_path"),+ require_nonempty=fixture.get("require_nonempty", False),)for fixture in fixturesif "literal" not in fixturediff --git a/ui/e2e/model-catalog/gatewayFixture.tsx b/ui/e2e/model-catalog/gatewayFixture.tsxindex 2a4b7dc47..4b8312830 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: 11, backend, model_id, route_origin: origins[index],+ contract_version: 12, 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: 11,+ contract_version: 12,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.tsxindex d207e015d..f66b83a97 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: 11, backend, model_id: modelId,+ contract_version: 12, 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.tsindex a986e549f..06beb76ba 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 expexpect(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(11);+ expect(body.contract_version).toBe(12);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 expwould_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: 11, error: 'source_in_route_chain', ...plan });+ expect(await refused.json()).toMatchObject({ ok: false, contract_version: 12, 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.tsindex 5c9f4bff5..a03ead302 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: 11, enabled: true, host_platform: 'linux',+ contract_version: 12, 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.tsindex bbd708ac7..1e4ad330d 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"]] asconst 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: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'});+ const chain=(b:string,hs=saved[b])=>({contract_version:12,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: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/runtime/status')return answer({ok:true,runtime:{contract_version:12,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.tsindex 230ef1215..b48def30b 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: 11,+ contract_version: 12,enabled: true,host_platform: 'darwin',manifest: {diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.tsindex df3fceac7..7903cfca9 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: 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('**/api/models/runtime/status', (route) => route.fulfill({ json: { ok: true, runtime: { contract_version: 12, 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.tsindex b8bcc9bf3..e827fc679 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 !== 11 || !('provenance' in payload)) {+ if (payload.ok !== true || payload.contract_version !== 12 || !('provenance' in payload)) {throw new Error('Latest recorded turn did not use the v10 provenance envelope');}return payload.provenance;diff --git a/ui/e2e/support/protocol-tiers.json b/ui/e2e/support/protocol-tiers.jsonindex e61313d71..3b4bf5501 100644--- a/ui/e2e/support/protocol-tiers.json+++ b/ui/e2e/support/protocol-tiers.json@@ -1,5 +1,6 @@{"anthropic": ["low", "medium", "high", "xhigh", "max"],"openai_responses": ["minimal", "low", "medium", "high", "xhigh"],- "openai_chat": ["minimal", "low", "medium", "high", "xhigh"]+ "openai_chat": ["minimal", "low", "medium", "high", "xhigh"],+ "google": []}diff --git a/ui/e2e/workbench-general/geometry.spec.ts b/ui/e2e/workbench-general/geometry.spec.tsindex f8ccb2244..e937ac5aa 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: 11,+ contract_version: 12,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/providers/ProvidersScreen.test.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsxindex 0fde4060b..e0454ea13 100644--- a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx+++ b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx@@ -79,7 +79,7 @@ const supply = (over: Partial<AgentSupply> & { backend: AgentSupply['backend'] }});const runtimeOf = (health: RuntimeHealth, over: Partial<RuntimeDependency> = {}): RuntimeDependency => ({- contract_version: 11,+ contract_version: 12,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: '1.0.0', source_sha: 'sha', assets: [] },status: { verified: true, health },...over,diff --git a/ui/src/components/onboarding/providers/providerStage.test.ts b/ui/src/components/onboarding/providers/providerStage.test.tsindex b24869d6d..ec793bb21 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: 11,+ contract_version: 12,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.tsxindex 80d47be11..4586f5b5c 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: 11,+ contract_version: 12,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: 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>);+ 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: 12, 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: 11,+ contract_version: 12,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: 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>);+ 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: 12, 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: 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>);+ 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: 12, 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: 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>);+ 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: 12, 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/ApiKeySourceForm.tsx b/ui/src/components/settings/models/ApiKeySourceForm.tsxindex ea270bad5..dfecd4a6c 100644--- a/ui/src/components/settings/models/ApiKeySourceForm.tsx+++ b/ui/src/components/settings/models/ApiKeySourceForm.tsx@@ -29,7 +29,7 @@ import {} from './apiKeySourceDraft';import { Field } from './dialogFields';import { ProtocolGlyph } from './protocolGlyph';-import { SOURCE_PROTOCOLS, type SourceProtocol } from './types';+import { SELECTABLE_SOURCE_PROTOCOLS, type SourceProtocol } from './types';import { VendorGlyph } from './vendorGlyph';// The form's own dressing travels with the form. Every class below is declared@@ -53,7 +53,7 @@ const ProtocolSegments: React.FC<{aria-label={t('settings.models.addKey.field.protocol')}className="model-hub-add-key-segments flex max-w-full flex-wrap">- {SOURCE_PROTOCOLS.map((item) => (+ {SELECTABLE_SOURCE_PROTOCOLS.map((item) => (<buttonkey={item}type="button"diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsxindex 07d7bdb8a..180974211 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: 11,+ contract_version: 12,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/RouteChainDialog.directEdit.test.tsx b/ui/src/components/settings/models/RouteChainDialog.directEdit.test.tsxindex d3dd1136f..3e75e5a8e 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: 11, backend, model_id: 'gpt-test', route_origin: routeOrigin,+ contract_version: 12, 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.tsxindex d9f4d7b82..cd5c4315d 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: 11,+ contract_version: 12,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.tsxindex 4dee8c726..30cd8179e 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: 11, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',+ contract_version: 12, 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.tsxindex 90176016a..63103c1f7 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: 11,+ contract_version: 12,...(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.tsxindex a38444214..ddf214de5 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -48,7 +48,7 @@ const manifest = {} satisfies RuntimeManifest;const runtime: RuntimeDependency = {- contract_version: 11,+ contract_version: 12,manifest,status: { installed_version: '1', verified: true, health: 'ok' },};@@ -119,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: 11,+ contract_version: 12,backend: 'codex',model_id: 'gpt-5.6-sol',current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },@@ -222,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: 11,+ contract_version: 12,backend: 'claude',model_id: routedModelId,current: { source_id: retainedSource.id, model_id: routedModelId },diff --git a/ui/src/components/settings/models/SupplyGraph.test.ts b/ui/src/components/settings/models/SupplyGraph.test.tsindex a2e1df5b3..365ec8414 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: 11,+ contract_version: 12,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: 11,+ contract_version: 12,backend: 'claude',model_id: 'model-a',current: { source_id: current, model_id: 'model-a' },diff --git a/ui/src/components/settings/models/addApiKeyState.ts b/ui/src/components/settings/models/addApiKeyState.tsindex 0b6b77e26..75879faf0 100644--- a/ui/src/components/settings/models/addApiKeyState.ts+++ b/ui/src/components/settings/models/addApiKeyState.ts@@ -2,6 +2,7 @@ import type { TranslationKey } from '@/i18n/types';import type { SourceProtocol } from './types';export const PROTOCOL_COPY_KEYS: Record<SourceProtocol, TranslationKey> = {+ google: 'settings.models.addKey.protocol.google',anthropic: 'settings.models.addKey.protocol.anthropicMessages',openai_responses: 'settings.models.addKey.protocol.openaiResponses',openai_chat: 'settings.models.addKey.protocol.openaiChatCompletions',diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.tsindex 61902b1b2..fa7e14c91 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: 11,+ contract_version: 12,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.tsindex 9ffe4994d..3ebedfed9 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: 11,+ contract_version: 12,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/manage.test.ts b/ui/src/components/settings/models/manage.test.tsindex 32ca7f54d..ebbc7f84f 100644--- a/ui/src/components/settings/models/manage.test.ts+++ b/ui/src/components/settings/models/manage.test.ts@@ -22,7 +22,7 @@ import {transitionManageStage,} from './manage';import type { ManageStage } from './manage';-import { SOURCE_PROTOCOLS } from './types';+import { SELECTABLE_SOURCE_PROTOCOLS } from './types';import type { Source, SourceProtocol } from './types';type ValidationCase = {@@ -238,12 +238,18 @@ describe('source management capabilities', () => {}});+ it('leaves API-only Google endpoint policy to the server too', () => {+ expect(assessSourceEdit(source({ vendor: 'custom', protocol: 'google' }), {+ displayName: source().display_name, baseUrl: '',+ })).toEqual({ valid: true, patch: { base_url: null }, reason: null });+ });+it('holds no vendor or protocol policy for an emptied endpoint', () => {const vendors = new Set(validationFixture.empty_targets.map((item) => item.vendor));const pairs = new Set(validationFixture.empty_targets.map((item) => `${item.vendor}:${item.protocol}`));- expect(pairs.size).toBe(vendors.size * SOURCE_PROTOCOLS.length);+ expect(pairs.size).toBe(vendors.size * SELECTABLE_SOURCE_PROTOCOLS.length);for (const vendor of vendors) {- for (const protocol of SOURCE_PROTOCOLS) expect(pairs.has(`${vendor}:${protocol}`)).toBe(true);+ for (const protocol of SELECTABLE_SOURCE_PROTOCOLS) expect(pairs.has(`${vendor}:${protocol}`)).toBe(true);}for (const item of validationFixture.empty_targets) {diff --git a/ui/src/components/settings/models/protocolGlyph.tsx b/ui/src/components/settings/models/protocolGlyph.tsxindex db8e83b19..75c261cb1 100644--- a/ui/src/components/settings/models/protocolGlyph.tsx+++ b/ui/src/components/settings/models/protocolGlyph.tsx@@ -26,7 +26,7 @@ export const ProtocolGlyph: React.FC<{ protocol: SourceProtocol; className?: strprotocol,className,}) => (- protocol === 'anthropic'+ protocol === 'google' ? null : protocol === 'anthropic'? <AnthropicGlyph className={className} />: <OpenAIGlyph className={className} />);diff --git a/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.ts b/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.tsindex 554827ada..20afd043b 100644--- a/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.ts+++ b/ui/src/components/settings/models/reasoningEffortVocabulary.mirror.test.ts@@ -74,7 +74,8 @@ describe('reasoning-effort vocabulary UI ↔ backend mirror', () => {});it('holds TIER_SUGGESTIONS equal to PROTOCOL_REASONING_EFFORT_DEFAULTS, or the frozen family lists while that name is absent', () => {- expect(TIER_SUGGESTIONS).toEqual(exportedDefaults ?? FROZEN_PROTOCOL_DEFAULTS);+ // Google has no family ladder: its API-only detail editor suggests nothing.+ expect(TIER_SUGGESTIONS).toEqual({ ...(exportedDefaults ?? FROZEN_PROTOCOL_DEFAULTS), google: [] });});it.each(['en', 'zh'] as const)('gives %s picker copy for every vocabulary value, in vocabulary order', (lng) => {diff --git a/ui/src/components/settings/models/routeProjectionReconciliation.test.ts b/ui/src/components/settings/models/routeProjectionReconciliation.test.tsindex bf6da53b7..d794c0ec8 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: 11,+ contract_version: 12,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.tsindex 23ff4039c..d4c914abb 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: 11,+ contract_version: 12,host_platform: 'darwin-arm64',manifest: resolution === 'unresolved'? { name: 'cliproxyapi', resolution, assets: [] }diff --git a/ui/src/components/settings/models/sourceModelContract.test.ts b/ui/src/components/settings/models/sourceModelContract.test.tsindex b39969194..ed9b543ed 100644--- a/ui/src/components/settings/models/sourceModelContract.test.ts+++ b/ui/src/components/settings/models/sourceModelContract.test.ts@@ -5,7 +5,7 @@ import { fileURLToPath } from 'node:url';import { describe, expect, expectTypeOf, it } from 'vitest';import { buildMockSources } from './mockData';-import { SOURCE_PROTOCOLS, type SourceProtocol } from './types';+import { SELECTABLE_SOURCE_PROTOCOLS, SOURCE_PROTOCOLS, type SourceProtocol } from './types';const SOURCE_SCHEMA = resolve(dirname(fileURLToPath(import.meta.url)),@@ -14,6 +14,11 @@ const SOURCE_SCHEMA = resolve();describe('Source model wire contract', () => {+ it('keeps the approved picker unchanged while Google is API/config-only', () => {+ expect(SELECTABLE_SOURCE_PROTOCOLS).toEqual(['anthropic', 'openai_responses', 'openai_chat']);+ expect(SOURCE_PROTOCOLS).toContain('google');+ });+it('offers exactly the protocols the Source schema accepts', () => {const schema = JSON.parse(readFileSync(SOURCE_SCHEMA, 'utf8'));expect([...SOURCE_PROTOCOLS].sort()).toEqual([...schema.properties.protocol.enum].sort());diff --git a/ui/src/components/settings/models/tierSuggestions.test.ts b/ui/src/components/settings/models/tierSuggestions.test.tsindex 8c38b6a73..b344810ad 100644--- a/ui/src/components/settings/models/tierSuggestions.test.ts+++ b/ui/src/components/settings/models/tierSuggestions.test.ts@@ -53,7 +53,8 @@ describe('unified reasoning-effort vocabulary', () => {expect(new Set(Object.keys(TIER_SUGGESTIONS))).toEqual(new Set(SOURCE_PROTOCOLS));for (const [protocol, tiers] of Object.entries(TIER_SUGGESTIONS)) {- expect(tiers.length, protocol).toBeGreaterThan(0);+ if (protocol === 'google') expect(tiers).toEqual([]);+ else expect(tiers.length, protocol).toBeGreaterThan(0);expect(new Set(tiers).size, protocol).toBe(tiers.length);expect(tiers.filter((tier) => vocabulary.includes(tier)), protocol).toEqual([...tiers]);expect([...tiers].sort((a, b) => rank(a) - rank(b)), protocol).toEqual([...tiers]);diff --git a/ui/src/components/settings/models/tierSuggestions.ts b/ui/src/components/settings/models/tierSuggestions.tsindex 5a3c2cb72..72593454c 100644--- a/ui/src/components/settings/models/tierSuggestions.ts+++ b/ui/src/components/settings/models/tierSuggestions.ts@@ -28,6 +28,7 @@ import type { SourceProtocol } from './types';* would take.*/export const TIER_SUGGESTIONS: Readonly<Record<SourceProtocol, readonly ReasoningEffort[]>> = {+ google: [], // No Google family ladder is claimed by Model Hub.anthropic: ['low', 'medium', 'high', 'xhigh', 'max'],openai_responses: ['minimal', 'low', 'medium', 'high', 'xhigh'],openai_chat: ['minimal', 'low', 'medium', 'high', 'xhigh'],diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex 7f655c4eb..1a059c16b 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 = 11 as const;-export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11] as const;+export const CONTRACT_VERSION = 12 as const;+export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11, 12] as const;export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;@@ -21,8 +21,11 @@ export const SOURCE_PROTOCOLS = ['anthropic','openai_responses','openai_chat',+ 'google',] as const;export type SourceProtocol = (typeof SOURCE_PROTOCOLS)[number];+// Google is API/config-only until its picker frame is approved.+export const SELECTABLE_SOURCE_PROTOCOLS = ['anthropic', 'openai_responses', 'openai_chat'] as const;export const SOURCE_DISPLAY_NAME_MAX_LENGTH = 64 as const;export type SupplyChannel = 'native_cli' | 'hub';/** v3 (§4.5): classified by whether the state heals itself. cooldown carries adiff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex a525929a8..cf3ced10c 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1883,6 +1883,7 @@"anthropicMessages": "Anthropic Messages","openaiResponses": "OpenAI Responses","openaiChatCompletions": "OpenAI Chat Completions",+ "google": "Google Gemini","idleHint": "Identified automatically once Base URL and API key are filled","detecting": "Identifying the interface…","manual": "Manually specify interface type",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 641060669..c63d113f4 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1883,6 +1883,7 @@"anthropicMessages": "Anthropic Messages","openaiResponses": "OpenAI Responses","openaiChatCompletions": "OpenAI Chat Completions",+ "google": "Google Gemini","idleHint": "填好 Base URL 和 API Key 后自动识别","detecting": "识别接口中…","manual": "手动指定接口类型",diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex 78ebd3c8b..bebda89f0 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -743,6 +743,11 @@ async def _probe_protocol_response("""Require a response from the candidate protocol's distinct request path."""validate_api_key_auth_scheme(vendor, protocol, base_url, secret, auth_scheme)+ if protocol == "google":+ # Gemini requires the model in the generation URL. Observation never+ # invents a model or schedules inference: an explicit declaration can+ # instead authenticate through the existing credential-gated listing.+ return _ProtocolEvidence(_ProtocolProof.UNPROVEN, _AuthenticationEvidence.UNKNOWN)root = base_url or _OFFICIAL_BASE_URLS.get(vendor)if not root:raise EngineClientError("source requires a base URL for protocol observation")diff --git a/vibe/model_hub_runtime/api_key_vendors.py b/vibe/model_hub_runtime/api_key_vendors.pyindex 3aa47a36f..4f678ae9f 100644--- a/vibe/model_hub_runtime/api_key_vendors.py+++ b/vibe/model_hub_runtime/api_key_vendors.py@@ -11,7 +11,7 @@ from urllib.parse import urlsplitfrom config.v2_config import normalize_model_hub_base_url, normalize_model_hub_vendor_id-_SUPPORTED_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat"}+_SUPPORTED_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat", "google"}_LEGACY_OFFICIAL_BASE_URLS = {# ``codex`` remains a supported legacy vendor alias outside the shipped# api-key vendor preset catalog. Runtime official-URL fallback must keep@@ -20,6 +20,16 @@ _LEGACY_OFFICIAL_BASE_URLS = {}+def google_api_base_url(base_url: str | None) -> str:+ """CPA's Gemini executor appends /v1beta itself, including on custom roots."""+ normalized = normalize_model_hub_base_url(base_url)+ if normalized is None:+ raise ValueError("Google source requires a base URL")+ if urlsplit(normalized).query:+ raise ValueError("Google source Base URL cannot contain a query")+ return normalized.removesuffix("/v1beta")++def _validated_cpa_anthropic_origin(base_url: str | None) -> bool:"""Share CPA's authority gate, rejecting ambiguous HTTP URL spellings."""if not isinstance(base_url, str) or any(ord(char) <= 32 or ord(char) == 127 for char in base_url):diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 8c6fd9699..6b05dae17 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -46,7 +46,11 @@ from core.handlers.model_hub.stream_wire import (ProtocolUsageReport,observe_buffered_protocol_response,)-from vibe.model_hub_runtime.api_key_vendors import official_api_key_base_urls, validate_api_key_auth_scheme+from vibe.model_hub_runtime.api_key_vendors import (+ google_api_base_url,+ official_api_key_base_urls,+ validate_api_key_auth_scheme,+)from vibe.model_hub_runtime.state import SourceRecord@@ -426,11 +430,24 @@ class EngineClient:on_request_sent: Callable[[], None] | None = None,) -> EngineInvokeHandle:request_protocol = request_protocol or source.protocol- endpoint = _endpoint_for_protocol(request_protocol)body = dict(request)routed_model = f"{source.prefix}/{model_id}"- body["model"] = routed_model- body["stream"] = stream+ if request_protocol == "google":+ # CPA (MIT), sdk/api/handlers/gemini/gemini_handlers.go at+ # c404af96: model/action live in the path; alt=sse selects framing.+ action = "streamGenerateContent" if stream else "generateContent"+ endpoint = (+ f"/v1beta/models/{urllib.parse.quote(source.prefix, safe='')}/"+ f"{urllib.parse.quote(model_id, safe='')}:{action}"+ )+ if stream:+ endpoint += "?alt=sse"+ body.pop("model", None)+ body.pop("stream", None)+ else:+ endpoint = _endpoint_for_protocol(request_protocol)+ body["model"] = routed_model+ body["stream"] = streamheaders = {key.lower(): value for key, value in (request_headers or {}).items() if key.lower() in FORWARDED_CALLER_HEADERS}@@ -856,6 +873,8 @@ async def probe_models(root = base_url or _OFFICIAL_BASE_URLS.get(normalized_vendor)if not root:raise EngineClientError("source requires a base URL for model discovery")+ if protocol == "google":+ return await _probe_google_models(root, secret=secret, timeout=timeout)try:url = upstream_api_url(root, "/v1/models")except (TypeError, ValueError):@@ -910,6 +929,98 @@ async def probe_models(return tuple(fallback_models)+def _project_google_inventory(reader: BinaryIO) -> tuple[tuple[DiscoveredModel, ...], str | None]:+ """Project routing identities and the continuation token, never model limits."""+ names: dict[JSONScope, str] = {}+ objects: set[JSONScope] = set()+ valid_root = False+ valid_models = False+ page_token: str | None = None+ valid_token = True++ def visit(path: JSONPath, event: JSONEvent, value: object, scope: JSONScope) -> None:+ nonlocal valid_root, valid_models, page_token, valid_token+ if path == () and event == "start_map":+ valid_root = True+ elif path == ("models",):+ if event == "replace":+ names.clear()+ objects.clear()+ valid_models = False+ elif event != "nonempty":+ valid_models = event == "start_array"+ elif path == ("models", "*"):+ if event == "replace":+ names.pop(scope, None)+ elif event in {"start_map", "scalar", "start_array"}:+ objects.add(scope)+ elif path == ("models", "*", "name"):+ if event == "replace":+ names.pop(scope, None)+ elif event == "scalar" and isinstance(value, str) and value.startswith("models/") and value[7:]:+ names[scope] = value[7:]+ elif path == ("nextPageToken",):+ if event == "replace":+ page_token, valid_token = None, True+ elif event != "nonempty":+ valid_token = event == "scalar" and isinstance(value, str)+ page_token = (value or None) if valid_token else None++ parsed = project_json_reader(+ reader, {(), ("models",), ("models", "*"), ("models", "*", "name"), ("nextPageToken",)}, visit,+ lossless_string_paths={("models", "*", "name"), ("nextPageToken",)},+ )+ if not parsed or not valid_root or not valid_models or not valid_token or objects != names.keys():+ raise EngineClientError("model discovery returned an invalid Google payload")+ return tuple(DiscoveredModel(id=name) for name in dict.fromkeys(names.values())), page_token+++async def _probe_google_models(root: str, *, secret: str | None, timeout: float) -> tuple[DiscoveredModel, ...]:+ """Follow only page tokens on the same declared, credential-gated endpoint."""+ try:+ url = google_api_base_url(root) + "/v1beta/models"+ except (TypeError, ValueError):+ raise EngineClientError("source base URL is invalid") from None+ headers = {"Accept": "application/json"}+ if secret is not None:+ headers["x-goog-api-key"] = secret+ deadline = time.monotonic() + timeout+ models: dict[str, DiscoveredModel] = {}+ seen_tokens: set[str] = set()+ page_token: str | None = None+ try:+ async with aiohttp.ClientSession(trust_env=False) as session:+ while True:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise asyncio.TimeoutError+ async with session.get(+ url, headers=headers, params={"pageToken": page_token} if page_token else {},+ allow_redirects=False, timeout=aiohttp.ClientTimeout(total=remaining),+ ) as response:+ if response.status >= 300:+ raise EngineClientError(+ f"model discovery returned HTTP {response.status}", status_code=response.status,+ )+ with tempfile.SpooledTemporaryFile(max_size=_PRELUDE_MEMORY_BYTES) as body:+ while chunk := await response.content.read(_STREAM_CHUNK_BYTES):+ await run_owned_in_thread(body.write, chunk)+ await run_owned_in_thread(body.seek, 0)+ page, page_token = await run_owned_in_thread(+ _project_before_deadline, body, _project_google_inventory, deadline=deadline,+ )+ models.update((model.id, model) for model in page)+ if page_token is None:+ return tuple(models.values())+ if page_token in seen_tokens:+ raise EngineClientError("model discovery repeated a Google page token")+ seen_tokens.add(page_token)+ except asyncio.TimeoutError:+ raise EngineClientError("model discovery timed out", error_type="timeout") from None+ except (aiohttp.ClientError, OSError):+ raise EngineClientError("model discovery failed", error_type="network_error") from None++def _project_model_inventory(reader: BinaryIO,) -> tuple[diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.pyindex f60130d91..d0ac51fb5 100644--- a/vibe/model_hub_runtime/config.py+++ b/vibe/model_hub_runtime/config.py@@ -9,6 +9,7 @@ import yamlfrom config.atomic_io import write_atomicfrom config.v2_config import normalize_model_hub_base_urlfrom vibe.model_hub_runtime.api_key_vendors import (+ google_api_base_url,official_api_key_base_url,openai_compatible_endpoint,validate_api_key_auth_scheme,@@ -146,6 +147,20 @@ def _append_source(if model in text_only:entry["input-modalities"] = ["text"]models.append(entry)+ if source.protocol == "google":+ if not source.base_url:+ raise EngineStateError("Google source requires a base URL")+ # CPA (MIT), internal/config/config_types.go: GeminiKey/GeminiModel,+ # pinned c404af96. The executor, not Avibe, owns protocol conversion.+ entry = {+ "api-key": api_key,+ "prefix": source.prefix,+ "base-url": google_api_base_url(source.base_url),+ }+ if models:+ entry["models"] = models+ payload.setdefault("gemini-api-key", []).append(entry)+ returnif source.protocol == "anthropic":base_url = source.base_urlif not base_url:diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex 5123a30d6..bb5b40fd8 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -15,10 +15,11 @@ from pathlib import Pathfrom typing import Any, Callable, Sequencefrom config.atomic_io import write_atomic-from config.v2_config import normalize_model_hub_base_url+from config.v2_config import normalize_model_hub_base_url, validate_model_hub_protocol_vendorfrom core.handlers.model_hub.events import contains_credential_materialfrom core.handlers.model_hub.identifiers import model_id_without_credential_addressfrom vibe.model_hub_runtime.api_key_vendors import (+ google_api_base_url,official_api_key_base_url,validate_api_key_auth_scheme,)@@ -29,7 +30,7 @@ logger = logging.getLogger(__name__)_CREDENTIAL_REF_RE = re.compile(r"^cred_[A-Za-z0-9_-]{6,128}$")_BEARER_CREDENTIAL_REF_RE = re.compile(r"^cred_auth_bearer_[0-9a-f]{32}$")_SOURCE_ID_RE = re.compile(r"^src_[a-z0-9]{8,}$")-_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat"}+_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat", "google"}class EngineStateError(RuntimeError):@@ -1622,6 +1623,13 @@ def _validate_source_target(if credential_kind != "api_key":return+ if protocol == "google":+ try:+ validate_model_hub_protocol_vendor(vendor, protocol)+ google_api_base_url(base_url)+ except ValueError as exc:+ raise EngineStateError(str(exc)) from None+ returnif base_url is not None:returnif official_api_key_base_url(vendor) is not None: