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): Gemini API keys speak the native google protocol (#3037)
Call Whited522e16a8451
diff --git a/config/v2_config.py b/config/v2_config.pyindex a3f1bf331..f1b2ec014 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -208,8 +208,63 @@ def normalize_model_hub_vendor_id(value: object) -> str:def validate_model_hub_protocol_vendor(vendor: str, protocol: str) -> None:"""Validate protocol/vendor combinations that are intrinsic to persisted shapes."""- if protocol == "google" and vendor != "custom":- raise ValueError("Google Sources require the custom vendor")+ if protocol == "google" and vendor not in {"custom", "gemini"}:+ raise ValueError("Google Sources require the custom or gemini vendor")+++# Google's OpenAI-compatible endpoint, the Gemini preset's endpoint before Gemini API keys spoke Gemini natively,+# and its native root (``vibe/data/api_key_vendors.json``; ``docs/plans/vibey-gemini-native.md`` §3).+_GEMINI_OPENAI_COMPATIBLE_ENDPOINT = ("https", "generativelanguage.googleapis.com", "/v1beta/openai")+GEMINI_NATIVE_BASE_URL = "https://generativelanguage.googleapis.com"+++def on_gemini_openai_compatible_endpoint(vendor: object, protocol: object, base_url: object) -> bool:+ """A Gemini API key bound to Google's official OpenAI-compatible endpoint, named or by default (a relay is not).++ Both the saved Source (``_migrate_gemini_native_sources``) and its engine credential binding+ (``EngineStateStore.sync_sources``) move from it to the native root by this one test.+ """++ if vendor != "gemini" or protocol != "openai_chat":+ return False+ if base_url is None:+ # The vendor's official endpoint, which was the OpenAI-compatible one.+ return True+ if not isinstance(base_url, str):+ return False+ try:+ parsed = urlsplit(base_url.strip())+ port = parsed.port+ except ValueError:+ return False+ endpoint = (parsed.scheme.lower(), (parsed.hostname or "").lower(), parsed.path.rstrip("/"))+ return endpoint == _GEMINI_OPENAI_COMPATIBLE_ENDPOINT and not parsed.query and port in (None, 443)+++def _migrate_gemini_native_sources(payload: dict) -> dict:+ """Move every Gemini API key saved on Google's OpenAI-compatible endpoint to the native protocol it now speaks.++ Only the protocol and the endpoint change. The Source keeps its id, credential, models and routes: a Gemini Source+ names its models as Google lists them on either surface (``models/<id>``). Idempotent: a moved Source no longer+ matches.+ """++ def moves(source: object) -> bool:+ return (+ isinstance(source, dict) and source.get("kind") == "api_key"+ and on_gemini_openai_compatible_endpoint(source.get("vendor"), source.get("protocol"), source.get("base_url"))+ )++ hub = payload.get("model_hub")+ sources = hub.get("sources") if isinstance(hub, dict) else None+ if not isinstance(sources, list) or not any(moves(source) for source in sources):+ return payload+ migrated_hub = dict(hub)+ migrated_hub["sources"] = [+ {**source, "protocol": "google", "base_url": GEMINI_NATIVE_BASE_URL} if moves(source) else source+ for source in sources+ ]+ return {**payload, "model_hub": migrated_hub}def model_hub_fixed_menu_ids(backend: str) -> tuple[str, ...]:@@ -780,6 +835,7 @@ def _migrate_opencode_active_turn_timeout_on_load(payload: dict) -> dict:def _migrate_config_payload_on_load(payload: dict) -> tuple[dict, bool, tuple[str, ...]]:migrated, changed, warnings = _migrate_legacy_model_hub_payload(payload)migrated, catalog_changed, catalog_warnings = _migrate_legacy_opencode_catalog(migrated)+ migrated = _migrate_gemini_native_sources(migrated)model_hub_changed = changed or catalog_changed or migrated.get("model_hub") != payload.get("model_hub")migrated = _migrate_opencode_active_turn_timeout_on_load(migrated)return migrated, model_hub_changed, (*warnings, *catalog_warnings)diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex ff0febf2a..d69771923 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 v21 (2026-10-21).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v22 (2026-10-27).This file is the canonical adapter boundary and must remain byte-identical to``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex d2bfc853f..90afcd486 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -2779,7 +2779,7 @@ class TurnCorrelationRegistry:self.store.put({- "contract_version": 21,+ "contract_version": 22,"turn_id": normalized_turn_id,"ts": ts or _utc_now_iso(),"agent": trace.agent,diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex c7cbaa34a..253f60ea3 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -273,7 +273,7 @@ from .usage import (local_usage_day,)-CONTRACT_VERSION = 21+CONTRACT_VERSION = 22def seeded_source_name(vendor: str) -> str:@@ -396,8 +396,8 @@ def _described_as_unfit_for_agent_turns(match: Mapping[str, Any]) -> bool:)-AGENT_CHAIN_CONTRACT_VERSION = 21-PROBE_RESULT_CONTRACT_VERSION = 21+AGENT_CHAIN_CONTRACT_VERSION = 22+PROBE_RESULT_CONTRACT_VERSION = 22_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15_SOURCE_PROBE_TIMEOUT_SECONDS = 60# Background inventory refresh. The first tick doubles as the startup delay, so@@ -1404,7 +1404,7 @@ def _runtime_payload(status: EngineStatus, *, enabled: bool) -> dict:manager = EngineRuntimeManager()return {- "contract_version": 21,+ "contract_version": 22,"enabled": enabled,"host_platform": status.host_platform or manager.host_platform(),"manifest": manager.contract_manifest(),diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 1fd601922..cb919b977 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -1,6 +1,21 @@# Model Hub contracts-Status: **contract_version 21**, 2026-10-26: keyless Exa activation (KEX-3)+Status: **contract_version 22**, 2026-10-27: Gemini API keys on the native `google` protocol+(`../vibey-gemini-native.md` §3). `gh-v3.2.3rc8` through `rc12` carry v21, so this opens v22.+- The `gemini` catalog row pins `google` on `https://generativelanguage.googleapis.com`; a `google` Source's vendor is+ `custom` or `gemini` (`source.schema.json`, `source-create.schema.json`, `google-protocol.md`).+- On load, a Gemini API-key Source saved on Google's official OpenAI-compatible endpoint (named or by default) moves+ to `google` on the native root: protocol and Base URL only. Its id, credential, models, routes and sessions are+ unchanged, because a Gemini Source keeps Google's `models/<id>` names on both surfaces; its engine entry routes each+ by that alias and calls the bare id upstream. Its Source identity changes, so stored opaque payloads stop replaying+ once and capability evidence restarts.+- A Gemini Source's image models register on an internal OpenAI-compatible entry of the same key and prefix, the+ only entry the engine's images endpoints serve; `IMAGE_PROTOCOLS` gains `google`.+- **Downgrade:** a release before v22 rejects a `google` Source whose vendor is `gemini`, so once a v22 build has+ written the moved Source, an older build cannot load Model Hub's Sources (the boundary of+ `../web-search-services.md` §12). Removing the Gemini Source before downgrading avoids it; release notes say so.++It builds on v21 (2026-10-26): keyless Exa activation (KEX-3)and web fetch readers, producers and coordinated activation (WF-1/2/3).`gh-v3.2.3rc3` through `rc7` carry v20, so the unreleased v21 event now includesits coordinated readers, producer, and default-on Exa search activation. The versioned@@ -392,7 +407,7 @@ comparison. A gate may not report success by comparing stale input with itself.## Version closure-`contract_version` 21 must coexist in all registered version locations on the same tested head:+`contract_version` 22 must coexist in all registered version locations on the same tested head:- `mirror-registry.json`- `agent-chain.schema.json`diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex ff0febf2a..d69771923 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 v21 (2026-10-21).+"""Model Hub EngineAdapter interface. FINAL CONTRACT v22 (2026-10-27).This file is the canonical adapter boundary and must remain byte-identical to``core/handlers/model_hub/adapter.py``. The adapter owns one-Source operations:diff --git a/docs/plans/model-hub-contracts/agent-chain.schema.json b/docs/plans/model-hub-contracts/agent-chain.schema.jsonindex 43cbdcedf..73a0d3345 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": 21 },+ "contract_version": { "const": 22 },"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },"model_id": { "type": "string" },"manual_override": {@@ -259,7 +259,7 @@],"examples": [{- "contract_version": 21,+ "contract_version": 22,"backend": "codex","model_id": "unlisted-model","manual_override": null,@@ -269,7 +269,7 @@"supply_state": "ok"},{- "contract_version": 21,+ "contract_version": 22,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -279,7 +279,7 @@"supply_state": "ok"},{- "contract_version": 21,+ "contract_version": 22,"backend": "claude","model_id": "claude-opus-4-6","manual_override": null,@@ -289,7 +289,7 @@"supply_state": "waiting"},{- "contract_version": 21,+ "contract_version": 22,"backend": "opencode","model_id": "glm-5.2","manual_override": { "hops": [{ "source_id": "src_relay9c1x", "model_id": "glm-5.2" }] },@@ -299,7 +299,7 @@"supply_state": "waiting"},{- "contract_version": 21,+ "contract_version": 22,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -309,7 +309,7 @@"supply_state": "interrupted"},{- "contract_version": 21,+ "contract_version": 22,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -319,7 +319,7 @@"supply_state": "interrupted"},{- "contract_version": 21,+ "contract_version": 22,"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 d5fd5f6d8..0846c6dc8 100644--- a/docs/plans/model-hub-contracts/api-response.schema.json+++ b/docs/plans/model-hub-contracts/api-response.schema.json@@ -63,7 +63,7 @@"required": ["ok", "contract_version", "probe"],"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"probe": {"$ref": "model-hub/source-probe-result.schema.json"}}},@@ -162,7 +162,7 @@"SuccessCore": {"properties": {"ok": {"const": true},- "contract_version": {"const": 21}+ "contract_version": {"const": 22}}},"SourceListResponse": {@@ -171,7 +171,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}}}},@@ -181,7 +181,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"observation": {"$ref": "model-hub/observation-result.schema.json"}}},@@ -191,7 +191,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"source": {"$ref": "#/definitions/SourceApi"},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}},"adopted_by": {"type": "array", "items": {"$ref": "#/definitions/AdoptedBy"}, "uniqueItems": true}@@ -203,7 +203,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"source": {"$ref": "#/definitions/SourceApi"}}},@@ -213,7 +213,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"source": {"$ref": "#/definitions/SourceApi"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -225,7 +225,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"source": {"allOf": [{"$ref": "#/definitions/SourceApi"},@@ -243,7 +243,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}}@@ -254,7 +254,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"agents": {"type": "array", "items": {"$ref": "#/definitions/AgentSupplyApi"}}}},@@ -264,7 +264,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"agent": {"$ref": "#/definitions/AgentSupplyApi"}}},@@ -281,7 +281,7 @@],"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"agent": {"$ref": "#/definitions/AgentSupplyApi"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}, "uniqueItems": true},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}, "uniqueItems": true}@@ -306,7 +306,7 @@"additionalProperties": false,"properties": {"ok": {"const": false},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"error": {"const": "candidate_suppliers_changed"},"detail": {"type": "string", "minLength": 1},"changed": {@@ -326,7 +326,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"agent": {"type": "object","required": ["backend", "mode", "catalog_models"],@@ -427,7 +427,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"candidates": {"type": "object","required": ["builtin", "providers", "in_list"],@@ -446,7 +446,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"matches": {"type": "array","maxItems": 8,@@ -480,7 +480,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"chain": {"$ref": "model-hub/agent-chain.schema.json"}}},@@ -490,7 +490,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"chains": {"type": "array", "items": {"$ref": "model-hub/agent-chain.schema.json"}}}},@@ -500,7 +500,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"chain": {"$ref": "model-hub/agent-chain.schema.json"},"removed_hops": {"type": "array", "items": {"$ref": "#/definitions/RouteHopRef"}},"interrupted": {"type": "array", "items": {"$ref": "#/definitions/SupplyGap"}}@@ -512,7 +512,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"probe": {"$ref": "model-hub/probe-result.schema.json"}}},@@ -522,7 +522,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"events": {"type": "array", "items": {"$ref": "model-hub/resolution-event.schema.json"}}}},@@ -532,7 +532,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"usage": {"$ref": "model-hub/usage-summary.schema.json"}}},@@ -542,7 +542,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"quota": {"$ref": "model-hub/quota-summary.schema.json"}}},@@ -552,7 +552,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"hosted_tools": {"$ref": "model-hub/hosted-tools-status.schema.json"}}},@@ -562,7 +562,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -584,7 +584,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -607,7 +607,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"flow": {"allOf": [{"$ref": "model-hub/oauth-flow.schema.json"},@@ -632,7 +632,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21}+ "contract_version": {"const": 22}}},"RuntimeApi": {@@ -654,7 +654,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"scan": {"$ref": "model-hub/migration-scan.schema.json"}}},@@ -664,7 +664,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"applied": {"type": "integer", "minimum": 0},"sources": {"type": "array", "items": {"$ref": "#/definitions/SourceApi"}},"added_to": {"type": "array", "items": {"$ref": "#/definitions/AddedTo"}}@@ -676,7 +676,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"provenance": {"$ref": "model-hub/turn-provenance.schema.json"}}},@@ -687,7 +687,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"provenance": {"anyOf": [{"$ref": "model-hub/turn-provenance.schema.json"},@@ -702,7 +702,7 @@"additionalProperties": false,"properties": {"ok": {"const": true},- "contract_version": {"const": 21},+ "contract_version": {"const": 22},"runtime": {"$ref": "#/definitions/RuntimeApi"}}}diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 703058c0d..1a7cf53ab 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` 21** — 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` 22** — 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: 21, ...}`.+Success envelope: `{ok: true, contract_version: 22, ...}`.Failure envelope:-`{ok: false, contract_version: 21, error: <machine_code>, detail?: <i18n_key>}`.+`{ok: false, contract_version: 22, 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` 21, the+The shared envelope and every versioned nested contract carry `contract_version` 22, theterminal value. Supported persisted config shapes and historical TurnProvenanceremain readable; ephemeral envelopes use only the terminal version.@@ -85,7 +85,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[], clean_api_keys?: boolean}` → `{applied, sources, added_to}` | Applies one grouped, server-owned custody transaction. It checks saved configuration and custody locally, copies API keys without upstream validation, upgrades an existing native subscription Source in place when present, and commits Source/Routes/backend mode atomically. API-key originals are kept unless cleanup was selected. 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` 21 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` 22 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. |@@ -768,7 +768,7 @@ The terminal result of both ordinary API-key creation and OAuth creation is:```json{"ok": true,- "contract_version": 21,+ "contract_version": 22,"source": {"id": "src_anthkey01","kind": "api_key",@@ -878,7 +878,7 @@ Every guarded Source/inventory mutation uses the §4.5 envelope matrix and the c```json{"ok": false,- "contract_version": 21,+ "contract_version": 22,"error": "source_last_supplier","would_remove_hops": [],"would_interrupt": [@@ -1017,7 +1017,7 @@ API-key success:```json{"ok": true,- "contract_version": 21,+ "contract_version": 22,"source": {"id": "src_relay9c1x","kind": "api_key",@@ -1112,7 +1112,7 @@ Status and submit return the same terminal shape:```json{"ok": true,- "contract_version": 21,+ "contract_version": 22,"flow": {"flow_id": "oaf_claude01","client_nonce": "ofn_01j5w8z7p4n6q2rt",@@ -1185,9 +1185,9 @@ a valid `interrupted` chain.```json{"ok": true,- "contract_version": 21,+ "contract_version": 22,"chain": {- "contract_version": 21,+ "contract_version": 22,"backend": "codex","model_id": "gpt-5.6","manual_override": null,@@ -1214,7 +1214,7 @@ In Direct mode both chain and probe refuse with:```json{"ok": false,- "contract_version": 21,+ "contract_version": 22,"error": "direct_mode","detail": "models.hub.direct_mode"}@@ -1228,9 +1228,9 @@ A successful probe nests its result:```json{"ok": true,- "contract_version": 21,+ "contract_version": 22,"probe": {- "contract_version": 21,+ "contract_version": 22,"backend": "claude","channel": "hub","reachable": false,@@ -1253,7 +1253,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 21,+ "contract_version": 22,"backend": "codex","channel": "native_cli","reachable": true,@@ -1266,7 +1266,7 @@ not-ready carries the closed i18n key `models.probe.native_cli_unavailable`.```json{- "contract_version": 21,+ "contract_version": 22,"backend": "codex","channel": "native_cli","reachable": false,@@ -1282,7 +1282,7 @@ No candidate is an API error with a typed model-scoped state:```json{"ok": false,- "contract_version": 21,+ "contract_version": 22,"error": "probe_no_candidate","detail": "models.probe.no_candidate.waiting","supply": {@@ -1473,7 +1473,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: 21, provenance: TurnProvenance | null}`;+Success uses exactly `{ok: true, contract_version: 22, provenance: TurnProvenance | null}`;there is no `success` field or envelope exception.Local `engine_down` records may also contain `local_error_detail`, an OS-generated@@ -1577,7 +1577,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 21,+ "contract_version": 22,"error": "provenance_unavailable","detail": "models.provenance.direct_mode"}@@ -1586,7 +1586,7 @@ ambiguous absence are explicit and distinguishable from an unknown turn:```json{"ok": false,- "contract_version": 21,+ "contract_version": 22,"error": "provenance_unavailable","detail": "models.provenance.attribution_ambiguous"}diff --git a/docs/plans/model-hub-contracts/google-protocol.md b/docs/plans/model-hub-contracts/google-protocol.mdindex 89fc9f123..7d99fb310 100644--- a/docs/plans/model-hub-contracts/google-protocol.md+++ b/docs/plans/model-hub-contracts/google-protocol.md@@ -9,12 +9,15 @@ to agent-core, change backend registration, or upgrade the engine.The complete protocol vocabulary includes `google`. New Google API-key Sourcesare admitted with `vendor: "custom"`, explicit `protocol: "google"`, an explicitBase URL and the usual transient `key` through the existing observe/create APIs.+Since v22 the `gemini` catalog row pins `google` on Google's native root, so a+Gemini API key is a `google` Source of vendor `gemini` (`../vibey-gemini-native.md`+§3), and one saved on the OpenAI-compatible endpoint moves to it on load.Existing vendor pins, subscriptions, OAuth and native CLI configuration do notchange. 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 Google vendor rule (`custom`, or the `gemini` catalog pin) 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@@ -23,8 +26,10 @@ because this executor appends paths rather than preserving a Base URL query.Discovery calls `<root>/v1beta/models`, supplies the held keyas `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+partial inventory must never replace a saved list. A `custom` Source's model names+lose only their `models/` API resource prefix; a `gemini` Source keeps Google's+`models/<id>` names, as its OpenAI-compatible listing always named them, and its+engine entry routes each by that alias while calling the bare id upstream. Inventory does not invent limits, vision supportor reasoning tiers.Google is not added to custom Auto detection: its inference endpoints require adiff --git a/docs/plans/model-hub-contracts/guard-refusal.schema.json b/docs/plans/model-hub-contracts/guard-refusal.schema.jsonindex d80ba256e..a9f069574 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": 21 },+ "contract_version": { "const": 22 },"error": {"enum": ["source_last_supplier",@@ -116,7 +116,7 @@"examples": [{"ok": false,- "contract_version": 21,+ "contract_version": 22,"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 9cab134cb..988a4bdb4 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": 21,+ "contract_version": 22,"input_generation": {"mode": "same_run_live_files","external_snapshot": "content_fingerprint_required"diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.jsonindex 80d325c96..c7d49f9de 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": 21 },+ "contract_version": { "const": 22 },"outcome": {"enum": ["observed",@@ -150,7 +150,7 @@],"examples": [{- "contract_version": 21,+ "contract_version": 22,"outcome": "observed","reachable": true,"authenticated": "authenticated",@@ -165,7 +165,7 @@]},{- "contract_version": 21,+ "contract_version": 22,"outcome": "authentication_failed","reachable": true,"authenticated": "rejected",@@ -175,7 +175,7 @@"model_metadata": []},{- "contract_version": 21,+ "contract_version": 22,"outcome": "ambiguous","reachable": true,"authenticated": "unknown",@@ -185,7 +185,7 @@"model_metadata": []},{- "contract_version": 21,+ "contract_version": 22,"outcome": "unreachable","reachable": false,"authenticated": "unknown",@@ -195,7 +195,7 @@"model_metadata": []},{- "contract_version": 21,+ "contract_version": 22,"outcome": "adapter_error","reachable": null,"authenticated": "unknown",@@ -205,7 +205,7 @@"model_metadata": []},{- "contract_version": 21,+ "contract_version": 22,"outcome": "timeout","reachable": null,"authenticated": "unknown",diff --git a/docs/plans/model-hub-contracts/probe-result.schema.json b/docs/plans/model-hub-contracts/probe-result.schema.jsonindex 2239e1417..5175772fc 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": 21 },+ "contract_version": { "const": 22 },"backend": { "enum": ["claude", "codex", "opencode", "vibey"] },"channel": { "enum": ["hub", "native_cli"] },"reachable": { "type": "boolean" },@@ -68,10 +68,10 @@}],"examples": [- { "contract_version": 21, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },- { "contract_version": 21, "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": 21, "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": 21, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },- { "contract_version": 21, "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": 22, "backend": "codex", "channel": "hub", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": 412, "error": null },+ { "contract_version": 22, "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": 22, "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": 22, "backend": "codex", "channel": "native_cli", "reachable": true, "source_id": "src_chatgptplus", "model_id": "gpt-5.6", "latency_ms": null, "error": null },+ { "contract_version": 22, "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 8fe2fd5fa..49b91bb58 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": 21 },+ "contract_version": { "const": 22 },"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": 21,+ "contract_version": 22,"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 59b6038a0..61c034ee1 100644--- a/docs/plans/model-hub-contracts/source-create.schema.json+++ b/docs/plans/model-hub-contracts/source-create.schema.json@@ -22,7 +22,7 @@},{"if": { "required": ["protocol"], "properties": { "protocol": { "const": "google" } } },- "then": { "properties": { "vendor": { "const": "custom" } } }+ "then": { "properties": { "vendor": { "enum": ["custom", "gemini"] } } }},{"if": {diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex 4c2c25a2c..fc39cdd40 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -530,7 +530,7 @@},{"if": { "properties": { "protocol": { "const": "google" } } },- "then": { "properties": { "vendor": { "const": "custom" } } }+ "then": { "properties": { "vendor": { "enum": ["custom", "gemini"] } } }},{"$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.",diff --git a/docs/plans/model-hub-contracts/turn-provenance.schema.json b/docs/plans/model-hub-contracts/turn-provenance.schema.jsonindex 6d423a9c7..5520166c9 100644--- a/docs/plans/model-hub-contracts/turn-provenance.schema.json+++ b/docs/plans/model-hub-contracts/turn-provenance.schema.json@@ -54,7 +54,7 @@"additionalProperties": false,"properties": {"contract_version": {- "enum": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],+ "enum": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],"$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."},@@ -527,7 +527,7 @@],"examples": [{- "contract_version": 21,+ "contract_version": 22,"turn_id": "turn_01k9x2m4","ts": "2026-07-29T06:32:11Z","agent": "claude",@@ -552,7 +552,7 @@"blockers": []},{- "contract_version": 21,+ "contract_version": 22,"turn_id": "turn_01k9x33p","ts": "2026-07-29T06:41:02Z","agent": "opencode",@@ -573,7 +573,7 @@"blockers": []},{- "contract_version": 21,+ "contract_version": 22,"turn_id": "turn_01k9x3zq","ts": "2026-07-29T06:48:20Z","agent": "codex",@@ -593,7 +593,7 @@]},{- "contract_version": 21,+ "contract_version": 22,"turn_id": "turn_01k9x4b7","ts": "2026-07-29T07:02:44Z","agent": "claude",@@ -613,7 +613,7 @@"blockers": []},{- "contract_version": 21,+ "contract_version": 22,"turn_id": "turn_modelmissing01","ts": "2026-09-05T17:31:10Z","agent": "claude",@@ -635,7 +635,7 @@"blockers": []},{- "contract_version": 21,+ "contract_version": 22,"turn_id": "turn_01k9x5ca","ts": "2026-07-29T07:08:00Z","agent": "codex",diff --git a/docs/plans/model-hub-vendor-preset-protocol.md b/docs/plans/model-hub-vendor-preset-protocol.mdindex a9a491231..60ebfe2ce 100644--- a/docs/plans/model-hub-vendor-preset-protocol.md+++ b/docs/plans/model-hub-vendor-preset-protocol.md@@ -64,8 +64,8 @@ where one is replayed.Mirror of `vibe/data/api_key_vendors.json`, which is the shipped artifactand the authority: on any drift — a cell, a missing row, or the row order —-the JSON wins and this table is what gets corrected (last synced 2026-09-08,-#1938). A data change belongs in the same PR as its row here. Vendor ids+the JSON wins and this table is what gets corrected (last synced 2026-10-27,+Gemini on `google`). A data change belongs in the same PR as its row here. Vendor idsreuse the `Source.vendor` pattern already named in `source.schema.json`(`anthropic|openai|zhipuai|kimi|xai|…`). Model-id prefix map in`vibe/data/model_vendors.json` is a different document (family → vendor for@@ -76,7 +76,7 @@ catalog backfill) and is not this picker.| `openai` | OpenAI | `https://api.openai.com/v1` | `openai_responses` || `anthropic` | Anthropic | `https://api.anthropic.com` | `anthropic` || `xai` | xAI | `https://api.x.ai/v1` | `openai_responses` |-| `gemini` | Gemini | `https://generativelanguage.googleapis.com/v1beta/openai` | `openai_chat` |+| `gemini` | Gemini | `https://generativelanguage.googleapis.com` | `google` || `deepseek` | DeepSeek | `https://api.deepseek.com` | `openai_chat` || `qwen` | Qwen | `https://dashscope.aliyuncs.com/compatible-mode/v1` | `openai_chat` || `kimi` | Kimi | `https://api.moonshot.cn/v1` | `openai_chat` |@@ -87,11 +87,10 @@ catalog backfill) and is not this picker.| `together` | Together | `https://api.together.xyz/v1` | `openai_chat` || `fireworks` | Fireworks | `https://api.fireworks.ai/inference/v1` | `openai_chat` |-`custom` is the dropdown default, not a catalog row. The `gemini` row is-Gemini's OpenAI-compatible surface, reached on that vendor's own-`/v1beta/openai` base URL; Gemini **native** stays deferred (not in the-three-protocol vocabulary, and still Out of scope below). The row and the-deferral are about different wire formats, not a contradiction.+`custom` is the dropdown default, not a catalog row. The `gemini` row was+Gemini's OpenAI-compatible surface (`/v1beta/openai`) until contract v22, which+pins it to the native `google` protocol on Google's root+(`vibey-gemini-native.md` §3); a Source saved on the old surface moves on load.Engine `_OFFICIAL_BASE_URLS` today only lists anthropic/openai/codex.This table is the replacement for api-key observation: look up bydiff --git a/docs/plans/vibey-gemini-native.md b/docs/plans/vibey-gemini-native.mdindex 8e09af6fa..5418dbca5 100644--- a/docs/plans/vibey-gemini-native.md+++ b/docs/plans/vibey-gemini-native.md@@ -86,14 +86,26 @@ conversion table is in `agent-core-contracts/conversion-tables.md` ("Google Gemi## 3. Gemini API keys on the `google` protocol (PR 2)-- `vibe/data/api_key_vendors.json`'s `gemini` row pins `google` on `https://generativelanguage.googleapis.com`.-- An existing official-endpoint `gemini` Source on `openai_chat` moves to `google`: protocol and base URL change,- its models are listed again natively, and every hop that names a `models/<id>` model of it names `<id>`. The- Source keeps its id, credential and routes; its identity changes, so stored opaque payloads stop replaying once- (the documented safe degradation, `model-hub-consumer.md` item 3).-- Gemini image models stay on the engine's images endpoint: the Source's engine registration adds an internal- OpenAI-compatible entry for its image models only. The user still sees one Source.-- The Web UI's protocol picker gains `google` (design frame first, `../avibe-docs/design.pen`).+Model Hub contract v22 (`model-hub-contracts/README.md`). Every Gemini API key speaks Gemini natively, existing ones+included (owner, 2026-10-27: "统一都走原生").++- `vibe/data/api_key_vendors.json`'s `gemini` row pins `google` on `https://generativelanguage.googleapis.com`, and a+ `google` Source's vendor is `custom` or `gemini`.+- **Names do not move.** A Gemini Source keeps Google's `models/<id>` names (its OpenAI-compatible listing always used+ them), so no hop, route key, menu row or Session changes. Discovery keeps them for the `gemini` vendor only (a+ `custom` Google Source keeps bare ids), and the engine's `gemini-api-key` entry routes each model by that alias while+ calling the bare id upstream (measured on the pinned engine: `prefix/models/gemini-4-argon` is served).+- **Existing keys move on load.** A Gemini API-key Source saved on Google's official OpenAI-compatible endpoint, named+ or by default, changes only its protocol and endpoint, through the shared on-load migration (projected on every+ load, persisted at service start, `model-hub-upgrade-config-compatibility.md`). A relay URL under the vendor keeps+ what it speaks. The Source's identity changes, so stored opaque payloads stop replaying once and its capability+ evidence restarts.+- **Images stay one Source.** The engine's images endpoints serve only image models an OpenAI-compatible entry flags,+ so a Gemini Source also registers its image models on an internal OpenAI-compatible entry of the same key and+ prefix, on Google's `/v1beta/openai` root (measured: both entries register under one prefix). `IMAGE_PROTOCOLS`+ gains `google`. A Chat relay serving Gemini keeps Gemini's image priors (`prior_vendors`).+- **Downgrade:** a release before v22 refuses a `gemini` Source on `google`, so once a v22 build has saved the moved+ Source an older build cannot load Model Hub's Sources; removing the Gemini Source first avoids it.## 4. Google Search as Gemini's native `web_search` (PR 3)@@ -113,7 +125,7 @@ conversion table is in `agent-core-contracts/conversion-tables.md` ("Google Gemi| PR | Scope | Visible result || --- | --- | --- || 1 | §2, this plan, the conversion table | A `google` Source (API-configured today) runs Vibey natively; no change for Chat Sources |-| 2 | §3 | Gemini keys run natively; images unchanged |+| 2 | §3 | Every Gemini key, existing ones included, runs natively; names, routes and images unchanged || 3 | §4 | Gemini models search with Google |Each PR is verified against the real Gemini API on the local regression environment. PR 2 and PR 3 are independentdiff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.mdindex 2f5393f78..c32244d91 100644--- a/docs/plans/vibey-hosted-tools.md+++ b/docs/plans/vibey-hosted-tools.md@@ -716,6 +716,8 @@ Unchanged from v1 §7.3 (owner decision, 2026-10-13 19:14), with the producer no- **A Gemini API key** (`gemini-2.5-flash-image`, `gemini-3-pro-image-preview`): the flagged entry reachesGoogle's OpenAI-compatible `images/generations`, the only image path Google documents on that layer (its chatroute does not return images for these models). No reference images: Google documents generation only.+ Since contract v22 the key speaks Gemini natively, and its image models stay on this path through an internal+ OpenAI-compatible entry of the same key and prefix (`vibey-gemini-native.md` §3).- **xAI grok-imagine is not reachable**: the engine's images handler accepts an xAI image model only under anempty, `xai` or `grok` prefix and then routes the bare id, which `force-model-prefix` never registers (unchangedin v8.0.28). That 400 is the engine's own refusal, recognized as local, never learned. xAI ships with no imagediff --git a/tests/e2e/test_model_hub_runtime.py b/tests/e2e/test_model_hub_runtime.pyindex 6f9844a45..2364720d4 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": 21,+ "contract_version": 22,"error": "feature_disabled",}diff --git a/tests/e2e/test_model_hub_sources.py b/tests/e2e/test_model_hub_sources.pyindex 08a9e13a3..d08966974 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 = 21+CONTRACT_VERSION = 22MENU_MODEL = "claude-sonnet-4-6"SYNTHETIC_API_KEY = "sk-model-hub-e2e-not-real"diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 49ba499f1..e9c55e03c 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -3893,6 +3893,8 @@ def test_api_key_setup_does_not_schedule_a_model("openai_chat": "/v1/chat/completions",}listing_path = "/v1beta/models" if protocol == "google" else "/v1/models"+ # A Gemini Source keeps the names Google lists; any other Google Source the bare ids.+ listed_id = "models/relay-model" if vendor == "gemini" else "relay-model"async def upstream(request):body = await request.json() if request.method == "POST" else None@@ -3966,7 +3968,7 @@ def test_api_key_setup_does_not_schedule_a_model(assert observation["outcome"] == "observed"assert observation["authenticated"] == "authenticated"assert observation["protocol"] == protocol- assert observation["models"] == ["relay-model"]+ assert observation["models"] == [listed_id]else:assert observation["outcome"] != "observed"assert observation["authenticated"] == "unknown"@@ -3992,7 +3994,7 @@ def test_api_key_setup_does_not_schedule_a_model(assert h.source["protocol"] == protocol# Both paths end up holding the listing's inventory; only the one# the listing authenticated ends up without the pending marker.- assert [model["id"] for model in h.source["models"]] == ["relay-model"]+ assert [model["id"] for model in h.source["models"]] == [listed_id]assert bool(h.source.get("verification_pending")) is not gated_inventoryassert state_store.read_api_key(h.source["credential_ref"]) == valid_keydiff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 4f974e291..4eb353f44 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -1101,7 +1101,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"] == 21+ assert runtime["contract_version"] == 22assert runtime["status"]["health"] == "ok"_assert_valid("runtime-dependency.schema.json", runtime)@@ -1408,7 +1408,7 @@ def test_runtime_start_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 21, "status": {"health": "ok"}}+ return {"contract_version": 22, "status": {"health": "ok"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1425,7 +1425,7 @@ def test_runtime_stop_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 21, "status": {"health": "not_started"}}+ return {"contract_version": 22, "status": {"health": "not_started"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1442,7 +1442,7 @@ def test_runtime_install_crosses_the_controller_rpc_boundary(monkeypatch):async def rpc(operation, payload=None):calls.append((operation, payload))- return {"contract_version": 21, "status": {"health": "installing"}}+ return {"contract_version": 22, "status": {"health": "installing"}}monkeypatch.setattr(model_hub_client, "_rpc", rpc)@@ -1460,7 +1460,7 @@ def test_runtime_dependency_ensure_crosses_the_controller_rpc_boundary(monkeypatdef rpc(operation, payload=None):calls.append((operation, payload))return {- "contract_version": 21,+ "contract_version": 22,"changed": True,"status": {"health": "not_started", "verified": True},}@@ -4934,7 +4934,7 @@ def test_agent_models_route_returns_only_picker_catalog_fields(monkeypatch):assert response.status_code == 200assert response.get_json() == {"ok": True,- "contract_version": 21,+ "contract_version": 22,"agent": {"backend": "codex","mode": "hub",@@ -10213,7 +10213,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"] == 21+ assert runtime["contract_version"] == 22_assert_valid("runtime-dependency.schema.json", runtime)diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 1eee29905..7baa8208e 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -5,7 +5,7 @@ import inspectimport jsonimport reimport stat-from dataclasses import fields+from dataclasses import fields, replacefrom itertools import productfrom pathlib import Path@@ -97,7 +97,7 @@ def test_auto_detect_asks_for_responses_before_chat():def test_unsaved_observation_schema_closes_all_terminal_shapes():schema = _schema("observation-result.schema.json")- assert schema["properties"]["contract_version"]["const"] == 21+ assert schema["properties"]["contract_version"]["const"] == 22assert tuple(schema["properties"]["outcome"]["enum"]) == tuple(member.value for member in ObservationOutcome)@@ -121,7 +121,7 @@ def test_observation_terminal_authority_and_schema_accept_the_same_products():def payload(observation: SourceObservation) -> dict:return {- "contract_version": 21,+ "contract_version": 22,"outcome": observation.outcome.value,"reachable": observation.reachable,"authenticated": (@@ -737,7 +737,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():route_refusal = {"ok": False,- "contract_version": 21,+ "contract_version": 22,"error": "source_in_route_chain","detail": "modelHub.errors.source_in_route_chain","would_remove_hops": [hop],@@ -753,7 +753,7 @@ def test_guard_refusal_error_requires_its_corresponding_nonempty_plan_array():}candidate_refusal = {"ok": False,- "contract_version": 21,+ "contract_version": 22,"error": "candidate_suppliers_changed","detail": "modelHub.errors.candidate_suppliers_changed","changed": {@@ -837,7 +837,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"] == 21+ assert registry["contract_version"] == 22ids = [entry["id"] for entry in registry["entries"]]assert idsassert len(ids) == len(set(ids))@@ -974,8 +974,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, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],- "expected": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21],+ "values": [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],+ "expected": [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],} in result["findings"]@@ -993,11 +993,11 @@ def _versioned_nodes(node):yield from _versioned_nodes(item)-def test_turn_provenance_keeps_released_v20_and_current_v21_read_shapes():- """KEX-1: the v21 mirror still accepts the released v20 provenance version."""+def test_turn_provenance_keeps_released_v21_and_current_v22_read_shapes():+ """The v22 mirror still accepts the released v21 provenance version."""schema = _schema("turn-provenance.schema.json")validator = Draft7Validator(schema)- for version in (20, 21):+ for version in (21, 22):example = copy.deepcopy(schema["examples"][0])example["contract_version"] = versionvalidator.validate(example)@@ -1354,7 +1354,7 @@ def test_v5_shape_amendments_reject_the_false_states_they_replace():with pytest.raises(ValidationError):chain_validator.validate(interrupted)exact_hop = {- "contract_version": 21,+ "contract_version": 22,"backend": "claude","model_id": "claude-opus-4-6","manual_override": None,@@ -2398,6 +2398,81 @@ def test_config_reload_does_not_overwrite_config_changed_during_migration(assert loaded.load_warnings and "changed during load" in loaded.load_warnings[0]+ "base_url",+ ["https://generativelanguage.googleapis.com/v1beta/openai", "https://GenerativeLanguage.googleapis.com:443/v1beta/openai/", None],+ ids=["named", "spelled", "default"],+)+def test_a_gemini_key_on_the_openai_compatible_endpoint_moves_to_gemini_on_load(monkeypatch, tmp_path, base_url):+ """vibey-gemini-native.md §3: a Gemini API key speaks Gemini natively. One saved on Google's official+ OpenAI-compatible endpoint changes only its protocol and endpoint: every model, route and session names the same+ `models/<id>` as before, and the engine credential it holds follows it the first time the engine syncs. A relay+ under the Gemini vendor keeps what it speaks."""++ from core.handlers.model_hub.adapter import SourceBinding+ from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore++ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ # The engine credentials an earlier release stored with these Sources.+ engine = EngineStateStore(tmp_path / "engine-state")+ refs = {+ "src_gemini0001": engine.store_api_key("gemini-key", vendor="gemini", protocol="openai_chat", base_url=base_url),+ "src_gemrelay01": engine.store_api_key(+ "relay-key", vendor="gemini", protocol="openai_chat", base_url="https://relay.example/v1beta/openai",+ ),+ }++ def gemini(source_id: str, url: str | None) -> dict:+ return ModelHubSourceConfig(+ id=source_id, kind="api_key", vendor="gemini", display_name="Gemini", protocol="openai_chat",+ supply_channel="hub", billing="metered", state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="models/gemini-4-argon", provenance="discovered")],+ base_url=url, credential_ref=refs[source_id],+ ).to_payload()++ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)+ official = gemini("src_gemini0001", base_url)+ relay = gemini("src_gemrelay01", "https://relay.example/v1beta/openai")+ payload["model_hub"]["sources"] = [official, relay]+ config_path = tmp_path / "config.json"+ original = json.dumps(payload)+ config_path.write_text(original, encoding="utf-8")++ projected = {source.id: source for source in V2Config.load(config_path=config_path).model_hub.sources}+ # An ordinary load projects the move without writing it.+ assert config_path.read_text(encoding="utf-8") == original+ moved = projected["src_gemini0001"]+ assert (moved.protocol, moved.base_url) == ("google", "https://generativelanguage.googleapis.com")+ assert [model.id for model in moved.models] == ["models/gemini-4-argon"]+ assert (moved.credential_ref, moved.vendor) == (refs["src_gemini0001"], "gemini")+ assert projected["src_gemrelay01"].to_payload() == relay++ def binding(source) -> SourceBinding:+ return SourceBinding(+ source_id=source.id, vendor=source.vendor, protocol=source.protocol, base_url=source.base_url,+ credential_ref=source.credential_ref, allowed_origins=(), model_ids=tuple(m.id for m in source.models),+ )++ records = engine.sync_sources([binding(source) for source in projected.values()])+ assert {record.source_id: record.protocol for record in records} == {+ "src_gemini0001": "google", "src_gemrelay01": "openai_chat",+ }+ moved_key = engine.credential_metadata(refs["src_gemini0001"])+ assert (moved_key["protocol"], moved_key["base_url"]) == ("google", "https://generativelanguage.googleapis.com")+ assert engine.read_api_key(refs["src_gemini0001"]) == "gemini-key"+ # Only the official endpoint's key follows: a relay's cannot be claimed by a native binding.+ with pytest.raises(EngineStateError, match="does not match"):+ engine.sync_sources([replace(binding(moved), credential_ref=refs["src_gemrelay01"])])++ V2Config.load(config_path=config_path, persist_migrations=True)+ persisted = {source["id"]: source for source in json.loads(config_path.read_text(encoding="utf-8"))["model_hub"]["sources"]}+ assert persisted["src_gemini0001"] == {+ **official, "protocol": "google", "base_url": "https://generativelanguage.googleapis.com",+ }+ assert persisted["src_gemrelay01"] == relay+ _assert_valid("source.schema.json", persisted["src_gemini0001"])++def test_config_reload_does_not_overwrite_config_changed_before_replace(monkeypatch,tmp_path,diff --git a/tests/test_model_hub_google.py b/tests/test_model_hub_google.pyindex 457488913..834fd7e46 100644--- a/tests/test_model_hub_google.py+++ b/tests/test_model_hub_google.py@@ -109,7 +109,7 @@ def test_google_source_roundtrips_and_uses_native_engine_registration(tmp_path,@pytest.mark.parametrize("vendor", ["relay-x", "openai"])@pytest.mark.parametrize("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."""+ """Unpinned vendors must not bypass Google's vendor rule: `custom`, or the `gemini` catalog pin."""source = _source("src_google001", "Google", vendor=vendor, protocol="google")source.base_url = "https://upstream.invalid"draft = {@@ -406,6 +406,10 @@ async def test_google_observation_uses_paginated_credential_witness_without_infeassert [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"]+ # A Gemini Source keeps the names Google lists, as its OpenAI-compatible listing always named them, so a+ # Source moved to this protocol keeps every saved route and session.+ models = await probe_models(vendor="gemini", protocol="google", base_url=base, secret="synthetic-key")+ assert [model.id for model in models] == ["models/gemini-first", "models/gemini-second"]assert all(method == "GET" for method, *_ in requests)assert all(query.keys() <= {"pageToken"} for _, _, query, _ in requests)diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 5e69e86bf..d8666722c 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -139,10 +139,12 @@ E64_SETTLEMENT_BOUNDARIES = json.loads((MODEL_HUB_FIXTURES / "e64_settlement_boundaries.json").read_text(encoding="utf-8"))NOW = datetime(2026, 7, 29, 12, 0, tzinfo=timezone.utc)+# A pin on a model-free Auto probe's interface; Gemini's native pin has only its model-list witness+# (covered by test_model_hub_google and the AUTH-SETUP-112 scenario).CATALOG_API_KEY_VENDOR_PROTOCOL_CASES = tuple(pytest.param(entry.id, entry.protocol, id=entry.id)for entry in api_key_vendor_catalog()- if entry.protocol in MODEL_PROTOCOLS+ if entry.protocol in MODEL_PROTOCOLS and entry.protocol != "google")@@ -5580,7 +5582,7 @@ def test_backend_failure_keeps_the_gateway_terminal_error_no_later_request_superdef test_released_backend_rejection_records_read_unchanged(tmp_path: Path) -> None:"""Records the earlier bridge wrote stay as written: no reason or phase is re-derived on read."""released = {- "contract_version": 21,+ "contract_version": 22,"turn_id": "turn_released_rejection","ts": NOW.isoformat(),"agent": "vibey",@@ -7056,7 +7058,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(_assert_valid("observation-result.schema.json",{- "contract_version": 21,+ "contract_version": 22,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -9590,7 +9592,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": 21,+ "contract_version": 22,"backend": "codex","channel": "native_cli","reachable": True,diff --git a/tests/test_model_hub_provenance.py b/tests/test_model_hub_provenance.pyindex 507cf271d..dbe51b54a 100644--- a/tests/test_model_hub_provenance.py+++ b/tests/test_model_hub_provenance.py@@ -261,7 +261,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": 21,+ "contract_version": 22,"turn_id": turn_id,"ts": "2026-09-06T00:00:00Z","agent": backend,@@ -707,6 +707,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": 21, "provenance": record}+ assert response.get_json() == {"ok": True, "contract_version": 22, "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 7bc177350..74090d9d5 100644--- a/tests/test_model_hub_resolution.py+++ b/tests/test_model_hub_resolution.py@@ -1808,7 +1808,7 @@ def test_service_accepts_authoritative_reachable_adapter_error(tmp_path):)assert result["observation"] == {- "contract_version": 21,+ "contract_version": 22,"outcome": "adapter_error","reachable": True,"authenticated": "unknown",@@ -1839,7 +1839,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": 21,+ "contract_version": 22,"outcome": "adapter_error","reachable": None,"authenticated": "unknown",diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 0953bb5d4..b1df0f8f8 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -1367,7 +1367,7 @@ def test_manifest_resolution_drives_admission_persistence_and_schema(installer=manager,state_store=EngineStateStore(tmp_path / "state"),)- projected = {"contract_version": 21, **supervisor.status()}+ projected = {"contract_version": 22, **supervisor.status()}schema = json.loads(Path("docs/plans/model-hub-contracts/runtime-dependency.schema.json").read_text(encoding="utf-8"@@ -1858,14 +1858,14 @@ def test_an_api_key_engine_entry_registers_its_vendors_image_models(tmp_path: Painstance_dir, runtime_secrets = store.prepare_instance("install-1")refs = {"openai": store.store_api_key("openai-secret", vendor="openai", protocol="openai_responses"),- "gemini": store.store_api_key("gemini-secret", vendor="gemini", protocol="openai_chat"),+ "gemini": store.store_api_key("gemini-secret", vendor="gemini", protocol="google"),"custom": store.store_api_key("custom-secret", base_url="https://api.example.test/v1"),}store.sync_sources([_binding(refs["openai"], source_id="src_openai0001", vendor="openai", protocol="openai_responses",base_url=None, model_ids=("gpt-6-astra",)),- _binding(refs["gemini"], source_id="src_gemini0001", vendor="gemini", protocol="openai_chat",- base_url=None, model_ids=("gemini-3-flash", "gemini-2.5-flash-image")),+ _binding(refs["gemini"], source_id="src_gemini0001", vendor="gemini", protocol="google",+ base_url=None, model_ids=("models/gemini-3-flash", "models/gemini-2.5-flash-image")),_binding(refs["custom"], source_id="src_custom0001", model_ids=("model-a", "gemini-2.5-flash-image", "gpt-image-2"),),@@ -1882,11 +1882,15 @@ def test_an_api_key_engine_entry_registers_its_vendors_image_models(tmp_path: Pa[openai] = payload["codex-api-key"]assert models(openai) == {"gpt-6-astra": None, "gpt-image-2": None}- custom, gemini = sorted(payload["openai-compatibility"], key=lambda entry: entry["base-url"])- # Listed as a chat model or not, an image model is flagged, and registered once.- assert models(gemini) == {- "gemini-3-flash": None, "gemini-2.5-flash-image": True, "gemini-3-pro-image-preview": True,+ custom, gemini_images = sorted(payload["openai-compatibility"], key=lambda entry: entry["base-url"])+ # A Gemini key speaks Gemini: its models keep Google's names as the alias they are routed by, the bare id as the+ # upstream name; its image models live on an internal OpenAI-compatible entry of the same key and prefix.+ [gemini] = payload["gemini-api-key"]+ assert {model["alias"]: model["name"] for model in gemini["models"]} == {+ "models/gemini-3-flash": "gemini-3-flash", "models/gemini-2.5-flash-image": "gemini-2.5-flash-image",}+ assert gemini_images["prefix"] == gemini["prefix"] and gemini_images["base-url"].endswith("/v1beta/openai")+ assert models(gemini_images) == {"gemini-2.5-flash-image": True, "gemini-3-pro-image-preview": True}# Gemini's image models are Chat Completions ones; GPT Image's vendor speaks Responses, so it stays a chat row.assert models(custom) == {"model-a": None, "gemini-2.5-flash-image": True, "gpt-image-2": None}sources = {source.source_id: source for source in store.list_sources()}@@ -2940,7 +2944,8 @@ def test_openai_compatibility_engine_base_url_uses_configured_api_root([pytest.param(entry.official_base_url, entry.protocol, id=entry.id)for entry in api_key_vendor_catalog()- if entry.protocol in MODEL_PROTOCOLS+ # Google has no model-free probe: its root is ``google_api_base_url``'s, with the version it appends.+ if entry.protocol in MODEL_PROTOCOLS and entry.protocol != "google"],)def test_catalog_official_base_url_composes_one_probe_endpoint(@@ -2985,6 +2990,9 @@ def test_catalog_official_base_url_composes_one_probe_endpoint(("deepseek", "https://API.DeepSeek.com/", "deepseek"),("deepseek", "https://api.deepseek.com:443/v1/", "deepseek"),("qwen", "https://dashscope.aliyuncs.com/compatible-mode/v1/", "alibaba-cn"),+ # Gemini's native root, with or without the version its engine entry appends.+ ("gemini", "https://generativelanguage.googleapis.com", "google"),+ ("gemini", "https://generativelanguage.googleapis.com/v1beta", "google"),# Any other endpoint may front another deployment.("deepseek", "https://api.deepseek.com/beta", None),("deepseek", "http://api.deepseek.com", None),@@ -3054,6 +3062,9 @@ def test_catalog_owned_api_key_sources_without_explicit_base_url_sync_and_write_if protocol == "openai_responses":assert payload["codex-api-key"][0]["base-url"] == expected_base_urlreturn+ if protocol == "google":+ assert payload["gemini-api-key"][0]["base-url"] == expected_base_url+ returnexpected_engine_base_url = expected_base_urlif not urlsplit(expected_engine_base_url).path.rstrip("/"):expected_engine_base_url = f"{expected_engine_base_url.rstrip('/')}/v1"diff --git a/tests/test_model_hub_search_chain.py b/tests/test_model_hub_search_chain.pyindex 601279299..857d25af8 100644--- a/tests/test_model_hub_search_chain.py+++ b/tests/test_model_hub_search_chain.py@@ -1273,7 +1273,7 @@ def test_retry_http_client_rpc_clears_only_the_service_fence_with_plain_success(response = client.post(f"/api/models/hosted-tools/web_search/services/{EXA}/retry", json={},headers=csrf_headers(client, "http://127.0.0.1:15131"))assert response.status_code == 200- assert response.get_json() == {"ok": True, "contract_version": 21}+ assert response.get_json() == {"ok": True, "contract_version": 22}assert calls == [("clear_service_cooldown", {"source_id": EXA, "service_id": None})]assert not service._service_cooldowns.current(source, "exa/search", generation)assert service.store.load().sources[0].state == source.statediff --git a/tests/test_model_hub_vibey_contract_matrix.py b/tests/test_model_hub_vibey_contract_matrix.pyindex 8684558fa..10f5c40bf 100644--- a/tests/test_model_hub_vibey_contract_matrix.py+++ b/tests/test_model_hub_vibey_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": 21, "backend": "claude", "channel": "native_cli", "reachable": True,+ "contract_version": 22, "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": 21, "backend": "vibey", "model_id": "fixture-model",+ "contract_version": 22, "backend": "vibey", "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": 21, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z",+ "contract_version": 22, "turn_id": "turn-fixture", "ts": "2026-10-02T07:00:00Z","agent": "vibey", "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/ui/e2e/chat-interactions/interactions.spec.ts b/ui/e2e/chat-interactions/interactions.spec.tsindex 0058e5e4a..2548865cf 100644--- a/ui/e2e/chat-interactions/interactions.spec.ts+++ b/ui/e2e/chat-interactions/interactions.spec.ts@@ -11,7 +11,7 @@ for (const lang of ['en', 'zh'] as const) {if (url.origin !== 'http://127.0.0.1:5227' || route.request().method() !== 'GET') return route.abort();if (url.pathname === `/api/models/turns/${TURN}/provenance`) {return route.fulfill({ json: { provenance: {- contract_version: 21, turn_id: TURN, agent: 'codex', requested_model_id: 'fixture-model',+ contract_version: 22, turn_id: TURN, agent: 'codex', requested_model_id: 'fixture-model',outcome: 'failed_terminal', failed_attempts: [], blockers: [],terminal_error: { source_id: 'fixture-source', configured_model_id: 'fixture-model', reason: 'engine_down' },} } });diff --git a/ui/e2e/model-catalog/gatewayFixture.tsx b/ui/e2e/model-catalog/gatewayFixture.tsxindex 06d4e8327..866529c09 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: 21, backend, model_id, route_origin: origins[index],+ contract_version: 22, 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: 21,+ contract_version: 22,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 2ca94cfbf..1b76191c8 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: 21, backend, model_id: modelId,+ contract_version: 22, 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 80f90528f..4cd358007 100644--- a/ui/e2e/model-routing-origin.spec.ts+++ b/ui/e2e/model-routing-origin.spec.ts@@ -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: 21, error: 'source_in_route_chain', ...plan });+ expect(await refused.json()).toMatchObject({ ok: false, contract_version: 22, 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 6f45395cb..f9010623f 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: 21, enabled: true, host_platform: 'linux',+ contract_version: 22, 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 9c0a4efd2..068a3a8af 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:21,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:22,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:21,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:22,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 2d5da9f9b..2a057143c 100644--- a/ui/e2e/onboarding-fidelity/provider-support.ts+++ b/ui/e2e/onboarding-fidelity/provider-support.ts@@ -130,7 +130,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: 21,+ contract_version: 22,enabled: true,host_platform: 'darwin',manifest: {diff --git a/ui/e2e/onboarding-fidelity/support.ts b/ui/e2e/onboarding-fidelity/support.tsindex cf465e9ec..2ca0050b3 100644--- a/ui/e2e/onboarding-fidelity/support.ts+++ b/ui/e2e/onboarding-fidelity/support.ts@@ -91,7 +91,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: 21, 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: 22, 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 bff7922e9..7769de3d0 100644--- a/ui/e2e/support/api.ts+++ b/ui/e2e/support/api.ts@@ -358,7 +358,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 !== 21 || !('provenance' in payload)) {+ if (payload.ok !== true || payload.contract_version !== 22 || !('provenance' in payload)) {throw new Error('Latest recorded turn did not use the v20 provenance envelope');}return payload.provenance;diff --git a/ui/e2e/workbench-general/geometry.spec.ts b/ui/e2e/workbench-general/geometry.spec.tsindex f98591a47..cc2dd81c9 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: 21,+ contract_version: 22,enabled: true,manifest: { name: 'cliproxyapi', resolution: 'resolved', version: 'fixture', source_sha: 'f'.repeat(40), assets: [] },status: { installed_version: 'fixture', verified: true, listening: { host: '127.0.0.1', port: 43123 }, health: 'ok' },diff --git a/ui/src/components/onboarding/AssistantSetup.test.tsx b/ui/src/components/onboarding/AssistantSetup.test.tsxindex cfe4a41d7..3f27de3bd 100644--- a/ui/src/components/onboarding/AssistantSetup.test.tsx+++ b/ui/src/components/onboarding/AssistantSetup.test.tsx@@ -50,7 +50,7 @@ const hubAgent = (enabled = true) => ({system_prompt: null, created_at: '', metadata: { builtin_default: true },});const hubChain = (modelId: string) => ({- contract_version: 21, backend: 'claude', model_id: 'opus-5',+ contract_version: 22, backend: 'claude', model_id: 'opus-5',manual_override: { hops: [{ source_id: 'src_a', model_id: modelId }] },route_origin: 'manual', current: { source_id: 'src_a', model_id: modelId },chain: [{ source_id: 'src_a', model_id: modelId, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],@@ -354,7 +354,7 @@ describe('assistant installation presentation', () => {mock.api.getVibeAgent.mockResolvedValue({ ok: true, agent });mock.models.listSources.mockResolvedValue([]);const chain = {- contract_version: 21, backend: 'claude', model_id: 'opus-5',+ contract_version: 22, backend: 'claude', model_id: 'opus-5',manual_override: { hops: [{ source_id: 'src_a', model_id: 'opus-5' }, { source_id: 'src_b', model_id: 'opus-5' }] },route_origin: 'manual', current: { source_id: 'src_a', model_id: 'opus-5' },chain: [diff --git a/ui/src/components/onboarding/BuiltinAssistant.test.tsx b/ui/src/components/onboarding/BuiltinAssistant.test.tsxindex f36381ef4..02d84951e 100644--- a/ui/src/components/onboarding/BuiltinAssistant.test.tsx+++ b/ui/src/components/onboarding/BuiltinAssistant.test.tsx@@ -65,7 +65,7 @@ const vibeyAgent = (model: string | null) => ({system_prompt: null, created_at: '', metadata: { builtin_default: true, lock_delete: true },});const chain = (modelId: string) => ({- contract_version: 21, backend: 'vibey', model_id: modelId,+ contract_version: 22, backend: 'vibey', model_id: modelId,manual_override: null, route_origin: 'automatic', current: { source_id: 'src_openai', model_id: modelId },chain: [{ source_id: 'src_openai', model_id: modelId, channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }],supply_state: 'ok',diff --git a/ui/src/components/onboarding/providers/ProvidersScreen.test.tsx b/ui/src/components/onboarding/providers/ProvidersScreen.test.tsxindex 1019e6b80..b902b155b 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: 21,+ contract_version: 22,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 ee8c78399..a0a8f5c1f 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: 21,+ contract_version: 22,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 ab1a79716..4e753cd9e 100644--- a/ui/src/components/settings/models/AgentCard.test.tsx+++ b/ui/src/components/settings/models/AgentCard.test.tsx@@ -17,7 +17,7 @@ import { freshRuntimeProjection } from './runtimeLifecycle';import type { AgentSupply, RuntimeDependency, Source } from './types';const runtime: RuntimeDependency = {- contract_version: 21,+ contract_version: 22,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 },};@@ -414,7 +414,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: 21, 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: 22, 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();@@ -434,7 +434,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: 21,+ contract_version: 22,backend: 'claude',model_id: 'claude-opus-4-6',current: { source_id: 'src_b', model_id: 'routed-opus' },@@ -467,7 +467,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: 21, 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: 22, 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();});@@ -475,7 +475,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: 21, 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: 22, 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();@@ -487,7 +487,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: 21, 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: 22, backend: 'claude', model_id: 'claude-opus-4-6', current: { source_id: 'src_b', model_id: 'claude-opus-4-6' }, chain: [{ source_id: 'src_a', model_id: 'claude-opus-4-6', channel: 'hub', health: 'cooldown', runnable: false, reason: null, retry_at: '2099-01-01T00:00:00Z' }, { source_id: 'src_b', model_id: 'claude-opus-4-6', channel: 'hub', health: 'healthy', runnable: true, reason: null, retry_at: null }], supply_state: 'ok' }) }} pendingBackends={new Set()} switchFailures={new Set()} connectingBackend={null} onConnectHub={vi.fn()} onSwitchDirect={vi.fn()} onOpenModels={onOpenModels} onOpenOrder={vi.fn()} onOpenRoute={vi.fn()} onProbeSettled={vi.fn()} /></I18nextProvider>);expect(screen.queryByText(/Adjust priority/i)).toBeNull();expect(screen.queryByRole('button', { name: /route chain/i })).toBeNull();expect(screen.queryByText(/Backup/)).toBeNull();diff --git a/ui/src/components/settings/models/BackendSupplyModeCard.test.tsx b/ui/src/components/settings/models/BackendSupplyModeCard.test.tsxindex fddd0cb66..130e9220c 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: 21,+ contract_version: 22,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 ab6fb148a..5bb25f5da 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: 21, backend, model_id: 'gpt-test', route_origin: routeOrigin,+ contract_version: 22, 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 35f548fc7..9d9be9790 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: 21,+ contract_version: 22,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 2ac937107..227ebfb4a 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: 21, turn_id: 'turn-recorded', ts: '2026-09-05T15:00:00Z', agent: 'codex', requested_model_id: 'requested-model',+ contract_version: 22, 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 1218027e2..5948d33f2 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: 21,+ contract_version: 22,...(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 ec214ff96..75fc374e5 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -49,7 +49,7 @@ const manifest = {} satisfies RuntimeManifest;const runtime: RuntimeDependency = {- contract_version: 21,+ contract_version: 22,manifest,status: { installed_version: '1', verified: true, health: 'ok' },};@@ -120,7 +120,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: 21,+ contract_version: 22,backend: 'codex',model_id: 'gpt-5.6-sol',current: { source_id: 'src_relay', model_id: 'gpt-5.6-sol' },@@ -224,7 +224,7 @@ const routedHubAgent: AgentSupply = {const routedChain: AgentChain = {manual_override: { hops: [{ source_id: retainedSource.id, model_id: routedModelId }] },route_origin: 'manual' as const,- contract_version: 21,+ contract_version: 22,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 94aefd059..a6c2ed601 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: 21,+ contract_version: 22,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: 21,+ contract_version: 22,backend: 'claude',model_id: 'model-a',current: { source_id: current, model_id: 'model-a' },diff --git a/ui/src/components/settings/models/apiFailure.test.ts b/ui/src/components/settings/models/apiFailure.test.tsindex 9ff39f631..e35d6dfb0 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: 21,+ contract_version: 22,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 386188d69..068d84c47 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: 21,+ contract_version: 22,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/routeProjectionReconciliation.test.ts b/ui/src/components/settings/models/routeProjectionReconciliation.test.tsindex 70cdd785b..f1b7c0172 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: 21,+ contract_version: 22,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 71fc9c52f..670131bb6 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: 21,+ contract_version: 22,host_platform: 'darwin-arm64',manifest: resolution === 'unresolved'? { name: 'cliproxyapi', resolution, assets: [] }diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex cf482f3c3..068087bce 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 = 21 as const;-export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21] as const;+export const CONTRACT_VERSION = 22 as const;+export const PERSISTED_TURN_CONTRACT_VERSIONS = [5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22] as const;export const AGENT_CHAIN_CONTRACT_VERSION = CONTRACT_VERSION;export const PROBE_RESULT_CONTRACT_VERSION = CONTRACT_VERSION;diff --git a/vibe/backend_model_catalog.py b/vibe/backend_model_catalog.pyindex a0df4f2b8..7c440167b 100644--- a/vibe/backend_model_catalog.py+++ b/vibe/backend_model_catalog.py@@ -684,8 +684,9 @@ IMAGE_MODEL_KINDS: tuple[str, ...] = ("api_key", "subscription")# What a call names itself; an image model's fixed request fields may not set them.IMAGE_CALL_FIELDS: frozenset[str] = frozenset({"model", "prompt", "size", "aspect_ratio", "n", "images", "stream"})# The protocols whose engine entries serve the images endpoints (vibey-hosted-tools.md §7.4): an image model is-# offered, registered and called on a Source of one of them only.-IMAGE_PROTOCOLS: frozenset[str] = frozenset({"openai_responses", "openai_chat"})+# offered, registered and called on a Source of one of them only. A Google Source registers its image models on an+# internal OpenAI-compatible entry of the same key (vibey-gemini-native.md §3).+IMAGE_PROTOCOLS: frozenset[str] = frozenset({"openai_responses", "openai_chat", "google"})IMAGE_MODEL_PARAMS: tuple[str, ...] = ("images", "n", "size")IMAGE_SIZE_FORMS: tuple[str, ...] = ("pixels", "ratio")# One line in every request's tool block: bounded so a catalog line cannot grow every prompt prefix.@@ -871,6 +872,11 @@ def hosted_tool_spec(vendor: str, protocol: str, model_id: str, tool: str) -> HoCUSTOM_VENDOR: Final = "custom"+# Protocols besides its catalog one that a vendor's routes were verified on: Gemini's image route runs on Google's+# OpenAI-compatible surface, which a Chat relay serving Gemini also speaks (vibey-gemini-native.md §3).+_ALSO_VERIFIED_ON: Final[Mapping[str, tuple[str, ...]]] = {"gemini": ("openai_chat",)}++def prior_vendors(vendor: str, protocol: str) -> tuple[str, ...]:"""The overlay vendors whose priors a Source of ``vendor`` and ``protocol`` may take (vibey-hosted-tools.md §3.1).@@ -884,7 +890,10 @@ def prior_vendors(vendor: str, protocol: str) -> tuple[str, ...]:return (vendor,)from vibe.model_hub_runtime.api_key_vendors import pinned_api_key_protocol- return tuple(name for name in bundled_provider_vendors() if pinned_api_key_protocol(name) == protocol)+ return tuple(+ name for name in bundled_provider_vendors()+ if pinned_api_key_protocol(name) == protocol or protocol in _ALSO_VERIFIED_ON.get(name, ())+ )def prior_vendor(vendor: str, protocol: str, model_id: str) -> str | None:diff --git a/vibe/data/api_key_vendors.json b/vibe/data/api_key_vendors.jsonindex ffe8dd20d..2a83c4e12 100644--- a/vibe/data/api_key_vendors.json+++ b/vibe/data/api_key_vendors.json@@ -20,8 +20,8 @@{"id": "gemini","label": "Gemini",- "official_base_url": "https://generativelanguage.googleapis.com/v1beta/openai",- "protocol": "openai_chat",+ "official_base_url": "https://generativelanguage.googleapis.com",+ "protocol": "google","models_dev_provider": "google"},{diff --git a/vibe/model_hub_runtime/api_key_vendors.py b/vibe/model_hub_runtime/api_key_vendors.pyindex 45485a12e..e54e3b42f 100644--- a/vibe/model_hub_runtime/api_key_vendors.py+++ b/vibe/model_hub_runtime/api_key_vendors.py@@ -353,8 +353,13 @@ def openai_compatible_endpoint(base_url: str) -> str:return endpoint-def _endpoint_identity(base_url: str) -> tuple[str, str, int | None, str, str] | None:- parts = urlsplit(openai_compatible_endpoint(base_url))+def _endpoint_identity(base_url: str, protocol: str | None = None) -> tuple[str, str, int | None, str, str] | None:+ try:+ # The root a Google Source's engine entry calls, and the API root every other protocol's does.+ root = google_api_base_url(base_url) if protocol == "google" else openai_compatible_endpoint(base_url)+ except ValueError:+ return None+ parts = urlsplit(root)try:port = parts.port or {"http": 80, "https": 443}.get(parts.scheme)except ValueError:@@ -365,7 +370,7 @@ def _endpoint_identity(base_url: str) -> tuple[str, str, int | None, str, str] |def official_models_dev_provider(vendor: str, base_url: str | None) -> str | None:- """The models.dev provider describing an ``openai_chat`` Source's upstream, or ``None``.+ """The models.dev provider describing a Source's upstream, or ``None``.Only a Source on its vendor's official endpoint is described by thatvendor's models.dev entries: a custom URL may front any deployment. The@@ -376,8 +381,8 @@ def official_models_dev_provider(vendor: str, base_url: str | None) -> str | Nonif entry is None or entry.models_dev_provider is None:return Noneif base_url is not None and (- _endpoint_identity(base_url) is None- or _endpoint_identity(base_url) != _endpoint_identity(entry.official_base_url)+ _endpoint_identity(base_url, entry.protocol) is None+ or _endpoint_identity(base_url, entry.protocol) != _endpoint_identity(entry.official_base_url, entry.protocol)):return Nonereturn entry.models_dev_provider@@ -392,8 +397,9 @@ def is_official_api_key_endpoint(vendor: str, base_url: str) -> bool:official = official_api_key_base_url(vendor)if official is None:return False- identity = _endpoint_identity(base_url)- return identity is not None and identity == _endpoint_identity(official)+ protocol = pinned_api_key_protocol(vendor)+ identity = _endpoint_identity(base_url, protocol)+ return identity is not None and identity == _endpoint_identity(official, protocol)def official_api_key_base_urls() -> dict[str, str]:diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 2ec46fafb..d0282ddd3 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport errno+import functoolsimport ioimport jsonimport logging@@ -1151,7 +1152,11 @@ async def probe_models(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)+ # A Gemini Source keeps the names Google lists (``models/<id>``), as it always has on the OpenAI-compatible+ # endpoint, so its saved routes and sessions name the same models on either surface.+ return await _probe_google_models(+ root, secret=secret, timeout=timeout, full_names=normalized_vendor == "gemini",+ )try:url = upstream_api_url(root, "/v1/models")credential = {} if secret is None else (@@ -1204,8 +1209,14 @@ 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."""+def _project_google_inventory(+ reader: BinaryIO, *, full_names: bool = False,+) -> tuple[tuple[DiscoveredModel, ...], str | None]:+ """Project routing identities and the continuation token, never model limits.++ A model's identity is its listed ``models/<id>`` name without the collection, or the whole name with+ ``full_names``.+ """names: dict[JSONScope, str] = {}objects: set[JSONScope] = set()valid_root = False@@ -1233,7 +1244,7 @@ def _project_google_inventory(reader: BinaryIO) -> tuple[tuple[DiscoveredModel,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:]+ names[scope] = value if full_names else value[7:]elif path == ("nextPageToken",):if event == "replace":page_token, valid_token = None, True@@ -1250,7 +1261,9 @@ def _project_google_inventory(reader: BinaryIO) -> tuple[tuple[DiscoveredModel,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, ...]:+async def _probe_google_models(+ root: str, *, secret: str | None, timeout: float, full_names: bool = False,+) -> tuple[DiscoveredModel, ...]:"""Follow only page tokens on the same declared, credential-gated endpoint."""try:url = google_api_base_url(root) + "/v1beta/models"@@ -1282,7 +1295,8 @@ async def _probe_google_models(root: str, *, secret: str | None, timeout: float)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,+ _project_before_deadline, body,+ functools.partial(_project_google_inventory, full_names=full_names), deadline=deadline,)models.update((model.id, model) for model in page)if page_token is None:diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.pyindex faba17ed8..b670bb07d 100644--- a/vibe/model_hub_runtime/config.py+++ b/vibe/model_hub_runtime/config.py@@ -169,7 +169,9 @@ def _append_source(# takes the first entry that matches, so models it cannot tell apart are# declared text-only together or not at all.images = image_model_ids(source)- routed = tuple(dict.fromkeys((*source.model_ids, *source.route_model_ids, *images)))+ # A Google Source's image models live on the internal OpenAI-compatible entry below, not the Gemini one.+ chat_images = () if source.protocol == "google" else images+ routed = tuple(dict.fromkeys((*source.model_ids, *source.route_model_ids, *chat_images)))marked = set(source.text_only_model_ids) if source.protocol == "openai_chat" else set()unmarked_names = {_engine_model_name(model) for model in routed if model not in marked}text_only = {model for model in marked if _engine_model_name(model) not in unmarked_names}@@ -191,18 +193,39 @@ def _append_source(entry["image"] = Truemodels.append(entry)if source.protocol == "google":- if not source.base_url:+ base_url = source.base_url or official_api_key_base_url(source.vendor)+ if not base_url:raise EngineStateError("Google source requires a base URL")+ root = google_api_base_url(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),+ "base-url": root,}if models:- entry["models"] = models+ # A Gemini Source names a model as Google lists it (``models/<id>``); the executor puts its name in the+ # upstream path itself, so the name is the bare id and the listed one is the alias it is routed by.+ entry["models"] = [{**model, "name": model["name"].removeprefix("models/")} for model in models]payload.setdefault("gemini-api-key", []).append(entry)+ if images:+ # The engine's images endpoints serve an image model only from an OpenAI-compatible entry that flags it+ # (CPA openai_images_handlers.go), so the same key also registers its image models on Google's+ # OpenAI-compatible root, under the Source's own prefix: still one Source and one credential.+ payload.setdefault("openai-compatibility", []).append(+ {+ "name": f"{source.prefix}-images",+ "prefix": source.prefix,+ "base-url": f"{root}/v1beta/openai",+ "api-key-entries": [{"api-key": api_key}],+ "models": [+ {"name": model, "alias": model, "display-name": reload_display_name(model, generation),+ "image": True}+ for model in images+ ],+ }+ )returnif source.protocol == "anthropic":base_url = source.base_urldiff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex aa008b1b5..2e9103502 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -15,7 +15,12 @@ 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, validate_model_hub_protocol_vendor+from config.v2_config import (+ GEMINI_NATIVE_BASE_URL,+ normalize_model_hub_base_url,+ on_gemini_openai_compatible_endpoint,+ validate_model_hub_protocol_vendor,+)from core import private_fsfrom core.handlers.model_hub.events import contains_credential_materialfrom core.handlers.model_hub.identifiers import model_id_without_credential_address@@ -605,6 +610,7 @@ class EngineStateStore:base_url,credential_kind=credential["kind"],)+ credential = self._follow_native_gemini(credential_ref, credential, vendor, protocol, base_url)if credential["kind"] == "api_key":if (credential.get("vendor") != vendor@@ -752,6 +758,30 @@ class EngineStateStore:self._write_sources([updated_record if source.source_id == source_id else source for source in sources])return updated_record+ def _follow_native_gemini(+ self, credential_ref: str, credential: dict[str, Any], vendor: str, protocol: str, base_url: str | None,+ ) -> dict[str, Any]:+ """The credential a Gemini Source moved to the native protocol is bound by, moved with it.++ ``_migrate_gemini_native_sources`` moves a Gemini API key's Source from Google's OpenAI-compatible endpoint to+ the native root; the key it holds is the same key on the same account, so its binding follows the first time+ the Source asks for it. Any other mismatch is still the caller's refusal.+ """++ if not (+ credential.get("kind") == "api_key"+ and vendor == "gemini" and protocol == "google"+ and base_url in (None, _validated_base_url(GEMINI_NATIVE_BASE_URL))+ and on_gemini_openai_compatible_endpoint(+ credential.get("vendor"), credential.get("protocol"), credential.get("base_url"),+ )+ ):+ return credential+ moved = {**credential, "protocol": protocol, "base_url": base_url}+ with self._lock:+ self._secure_write_json(self._credential_path(credential_ref), moved)+ return moved+def credential_metadata(self, credential_ref: str) -> dict[str, Any]:payload = self.credential_metadata_if_present(credential_ref)if payload is None:@@ -935,8 +965,10 @@ class EngineStateStore:protocol: str,base_url: str | None,) -> str | None:- metadata = self.credential_metadata(credential_ref)normalized_base_url = _validated_base_url(base_url)+ metadata = self._follow_native_gemini(+ credential_ref, self.credential_metadata(credential_ref), vendor.strip().lower(), protocol, normalized_base_url,+ )if (metadata["kind"] != "api_key"or metadata.get("vendor") != vendor.strip().lower()@@ -1687,7 +1719,7 @@ def _validate_source_target(if protocol == "google":try:validate_model_hub_protocol_vendor(vendor, protocol)- google_api_base_url(base_url)+ google_api_base_url(base_url or official_api_key_base_url(vendor))except ValueError as exc:raise EngineStateError(str(exc)) from Nonereturn