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, kimi, and xai subscription vendors (#1931)
Max6bad0ca137ca
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 04f99c030..ef26f2b9c 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -136,6 +136,19 @@ from .usage import USAGE_DEFAULT_WINDOW_DAYS, BoundedUsageLedger, SourceIdentityCONTRACT_VERSION = 10+def seeded_source_name(vendor: str) -> str:+ """The name a newly created Source of ``vendor`` starts life with.++ One owner for both create paths. A vendor id is a routing key, not a name,+ so the shipped catalog's label is the seed wherever it lists the vendor —+ otherwise a subscription reads as ``xai`` beside an api-key Source of the+ same vendor reading ``xAI``. Falls back to the id for a vendor the catalog+ does not list, which is the only name that channel has. The user owns the+ field from here on; this is the seed, not the display rule.+ """+ return catalog_api_key_vendor_label(vendor) or vendor++def _storable_backend_model_metadata(display_name: object,reasoning_efforts: object,@@ -2705,7 +2718,7 @@ class ModelHubService:return flow, repair_resultawait self._create_oauth_source([],- display_name=binding.vendor,+ display_name=seeded_source_name(binding.vendor),billing="monthly",created_at=self.now().isoformat(),oauth_ref=flow_id,@@ -2760,7 +2773,7 @@ class ModelHubService:vendor = normalize_model_hub_vendor_id(vendor)except ValueError:raise ModelHubError("discovery_failed") from None- display_name = payload.get("display_name") or catalog_api_key_vendor_label(vendor) or vendor+ display_name = payload.get("display_name") or seeded_source_name(vendor)if kind not in {"subscription", "api_key"}:raise ModelHubError("discovery_failed")if (diff --git a/docs/plans/model-hub-subscription-vendors.md b/docs/plans/model-hub-subscription-vendors.mdnew file mode 100644index 000000000..c7740489f--- /dev/null+++ b/docs/plans/model-hub-subscription-vendors.md@@ -0,0 +1,199 @@+# Model Hub — subscription vendor expansion: Gemini, Kimi, xAI++Status: owner-directed 2026-09-07 (this conversation). Design authority for+the change. `docs/plans/model-hub.md` OAuth sections and+`docs/plans/model-hub-ui-spec.md` §1.4 receive dated amendments referencing+this file.++## Why++The Model Hub engine already implements OAuth login for more coding-plan+subscriptions than Avibe surfaces.++**Corrected 2026-09-07.** This section was drafted against CLIProxyAPI+v7.2.105 (`4a2eb54d`), which is not the pin the product ships:+`vibe/model_hub_runtime/cliproxyapi_manifest.json` has named **v7.2.149,+`2a6b87aca083a5bf498ac1f68a1b636c500d7aaa`** since #1862, and does so at both+this change's merge base and current master. Evidence about a commit users do+not run is not evidence about shipped behavior, so every engine citation in+this document — the route table below, the presentation forms, and the serving+protocols in the amendment — was re-read at `2a6b87ac` and is stated at that+commit. The two versions agree on all of it; the correction is to the+provenance, not to a conclusion. A future pin bump re-reads them again.++Verified at `2a6b87ac`, `internal/api/server_management.go:176-180`:++| Engine endpoint | Vendor | Avibe today |+| --- | --- | --- |+| `/anthropic-auth-url` | Anthropic (Claude plans) | shipped |+| `/codex-auth-url` | OpenAI (ChatGPT plans) | shipped |+| `/antigravity-auth-url` | Google (Gemini / Antigravity plans) | this change |+| `/kimi-auth-url` | Moonshot (Kimi Code plans) | this change |+| `/xai-auth-url` | xAI (Grok Build plans) | this change |++Shared machinery (`/get-auth-status`, `DELETE /oauth-session`) is+vendor-generic and already consumed by the §1.4 flow. No engine pin bump.++## Scope ruling++- New subscription vendors: `gemini`, `kimi`, `xai`. Labels: Gemini, Kimi,+ xAI. Owner ruling: the xAI product is always presented as "xAI", never+ "Grok".+- **Hub custody only.** None of the three has a native CLI backend in Avibe,+ so the native/hub channel choice does not exist for them: the §1.4 dialog+ presents them as hub-held Gateway upstreams with no channel selector and no+ takeover semantics. The `native_cli` singleton rule and Claude/ChatGPT+ custody recommendations are untouched.+- Vendor menu (frame 13) order: Claude 订阅, ChatGPT 订阅, Gemini, Kimi,+ xAI.+- The OAuth flow state machine (§1.4 forms A/B/C, polling, paste-back,+ reconciliation, error classes) is reused verbatim. No new flow states, no+ contract_version change. `OAuthFlow` shape unchanged.+- Vendor marks: reuse `vendorGlyph.tsx` marks (gemini mark ships with the+ api-key preset PR; kimi already exists). Subscription rows carry the vendor+ mark, consistent with the api-key picker. **Corrected 2026-09-07:** `xai`+ has no mark in `vendorMarks.ts` and gets the sanctioned monogram fallback;+ authoring one is a design deliverable, not part of this change.++## Engine channel mapping++`_OAUTH_ENDPOINTS` (vibe/model_hub_runtime/adapter.py) gains:++| vendor | endpoint | engine channel |+| --- | --- | --- |+| `gemini` | `/antigravity-auth-url` | antigravity |+| `kimi` | `/kimi-auth-url` | kimi |+| `xai` | `/xai-auth-url` | xai |++The exact tuple semantics follow the two existing rows; the implementation+must read them rather than guess, and must verify each new vendor's+presentation form (auth_url vs paste vs device code) against the engine+handlers at the pinned commit, then map it onto §1.4's existing forms.++**Verified 2026-09-07** in `internal/api/handlers/management/auth_files_provider_oauth.go`+at `2a6b87ac`. Avibe reads the form from the start *response* rather than from+a per-vendor table, so this record is evidence that the mapping holds at this+pin, not a shape the code depends on:++| vendor | handler | response | §1.4 form |+| --- | --- | --- | --- |+| `gemini` | `RequestAntigravityToken` (`:344`) | `{status, url, state}`; no `flow`. `RegisterOAuthSession(state, "antigravity")` (`:362`), saved `Provider: "antigravity"` (`:485`). `is_webui` starts a forwarder to the management `/antigravity/callback` (`:367-378`); the wait deadline is 5 minutes (`:387`), which is what Avibe's 300s default stands in for when the response omits `expires_in` | **C** — paste callback URL |+| `kimi` | `RequestKimiToken` (`:624`) | `state="kmi-<UnixNano>"` (`:630`), `flow:"device"`, `user_code` only when non-empty, `expires_in` only when > 0 (`:710-716`). Ignores `is_webui` | **B** — device code |+| `xai` | `RequestXAIToken` (`:511`) | `state="xai-<UnixNano>"` (`:517`), `flow:"device"`, `user_code` when non-empty, `expires_in` **always** — falling back to `xaiauth.MaxPollDuration` (`:613-620`). Ignores `is_webui` | **B** — device code |++Both provider identifiers in each `_OAUTH_ENDPOINTS` row are the vendor's+engine channel name, confirmed against `RegisterOAuthSession` and the saved+`Provider` field above.++## Amendment 2026-09-07 — how a hub-only subscription binds++**Defect this repairs.** As first drafted, Acceptance asked that the generic+§1.4 states "drive it to a bound hub Source" while Out of scope forbade "any+change to the protocol proof ladder". Read together those forbade the feature+they specified: a Source cannot be persisted without a protocol to reach its+upstream over, and neither of the two routes that supplied one admitted these+vendors, so every completed grant would authorize and then die in+`discovery_failed`. That is the same dead end this effort exists to remove.+The out-of-scope line was written about the **api-key observation ladder**+(the rung 1/2/3 response ladder behind `POST /api/models/sources`), which is a+different owner and stays untouched.++**Ruling.** A hub-only subscription binds with an **engine-declared serving+protocol**: a per-vendor pin naming the local surface the pinned engine serves+that auth kind on. This is product knowledge of exactly the kind the owner+already ratified for `vibe/data/api_key_vendors.json` — a fact about the+engine Avibe ships, read from its source and re-read at each pin bump — and+not an inference from the vendor's public API.++It applies only where no probe can reach: a hub subscription's credential+never leaves the engine, and the upstream behind it is the vendor's CLI plane+rather than an endpoint Avibe may synthesize a request against. Vendors with a+reachable upstream keep proving their protocol by response.++**Per-vendor pins**, read at the shipped pin `2a6b87ac` (v7.2.149). All three+are `openai_chat`, and each is one of the engine's own serving surfaces:++| vendor | engine evidence at `2a6b87ac` | protocol |+| --- | --- | --- |+| `gemini` | `internal/translator/antigravity/openai/chat-completions/init.go:9` registers `translator.Register(OpenAI, Antigravity, …)`, translating an OpenAI-chat request onto the antigravity upstream (`cloudcode-pa.googleapis.com/v1internal:generateContent`) | `openai_chat` |+| `kimi` | `internal/runtime/executor/kimi_executor.go:54` returns `FormatOpenAI` from `RequestToFormat`, `:119` translates to `openai`, `:150` calls the upstream's `/v1/chat/completions` | `openai_chat` |+| `xai` | `internal/runtime/executor/xai_executor_request.go:517` accepts `FormatOpenAI` and folds its output controls into the Responses body the executor sends to `/responses` (`xai_executor_execute.go:45`) | `openai_chat` |++The native upstream differs per vendor — Gemini's own wire format, Moonshot's+OpenAI-compatible endpoint, xAI's Responses API — and for gemini it is not in+Avibe's `SOURCE_PROTOCOLS` vocabulary at all. The pin therefore names the+**served** surface rather than the upstream one, and picking the surface the+gateway's engine client already speaks is what makes all three converge. Each+pin equals what `api_key_vendors.json` pins for the same vendor id: one+vendor, one protocol, whichever channel holds the credential. Keep the two+tables in agreement — a subscription pinned against its api-key sibling would+need `_validate_source_target` taught about a second pin.++**Semantics.** These rungs prove no response shape. Reachability and+authentication follow the engine-managed flow that just completed: the engine+accepted the credential, which is what completing the grant means, so the+observation is reachable and authenticated with the protocol supplied by the+pin, and model discovery then runs through the ordinary engine-held path.++**Invariant, not a list.** Every vendor that can start a flow binds by exactly+one of the two routes — response-backed observation, or an engine-declared+pin. A start row without a binding route is a flow that can begin and not end,+so the tests assert the partition rather than enumerating the members: a+vendor added to the start table alone fails a test instead of shipping a dead+end.++`contract_version` is unchanged. No new flow state, no `OAuthFlow` shape+change, no new API field.++## Acceptance++- 添加订阅 menu shows five vendors in the order above, marks included.+- Each new vendor's 去登录 obtains a flow through the engine endpoint above;+ the generic §1.4 states drive it to a bound hub Source; models supplied by+ that subscription appear as Gateway upstream supply.+- Claude/ChatGPT flows byte-equivalent (existing scenario cases stay green),+ with one recorded exception: **the seeded Source name** (amended 2026-09-07,+ below). Their flows, states, refusals, and persisted shape are untouched;+ only the name a *newly* created Source starts with changes, from `anthropic`+ / `openai` to the catalog's `Anthropic` / `OpenAI`. Existing Sources keep the+ name they hold, and the field stays user-editable.+- `tests/scenarios/auth_setup/catalog.yaml` gains rows for the three new+ vendors with closed-loop harness cases in+ `tests/scenarios/auth_setup/test_auth_setup_scenarios.py` (repo rule for+ multi-step auth flows); provider-specific parsing stays in focused unit+ tests.+- No live vendor OAuth is exercised in CI; harness cases run against stubbed+ engine management endpoints, matching the existing two vendors' pattern.++## Amendment 2026-09-07 — a Source is seeded with a name, not a routing key++A completed grant seeded the new Source's `display_name` from the vendor id, so+these subscriptions would have shipped as `gemini`, `kimi`, and `xai` — the last+of which contradicts the label ruling above in the very place the user reads it.++The fix is a deletion, not an addition: the api-key create path in the same file+already seeded from the shipped catalog's `label`, so the two sibling paths+disagreed and the subscription one was the outlier. Both now call one+`seeded_source_name(vendor)`, which is the catalog label where the catalog lists+the vendor and the id where it does not.++This reaches the two shipped vendors as well, and deliberately so: seeding only+the new three would leave `Gemini` beside `anthropic` in one list, and an+Anthropic api-key Source already reads `Anthropic` beside a Claude subscription+reading `anthropic`. Closing the whole class is smaller than three special+cases. `codex` has no catalog row and keeps its id, so the ChatGPT flow is+unchanged either way. Nothing renames an existing Source, and the field remains+user-owned — this is the seed, not a display rule, so no i18n row is involved+(a brand name is not localized copy).++Guarded as an invariant over the start table rather than per vendor: every+`_OAUTH_ENDPOINTS` vendor the catalog names must seed with that name, so a+vendor admitted later cannot ship named by its id.++## Out of scope++- Engine pin bump; Qwen Code / iFlow (not at this pin's route table).+- Native CLI custody for the new vendors.+- Any change to api-key presets or the api-key observation ladder (rescoped+ 2026-09-07; see the amendment above — OAuth hub binding is a separate owner+ and is in scope).diff --git a/tests/scenario_harness/model_hub_native_oauth.py b/tests/scenario_harness/model_hub_native_oauth.pyindex 1576071fa..0b7be9a4a 100644--- a/tests/scenario_harness/model_hub_native_oauth.py+++ b/tests/scenario_harness/model_hub_native_oauth.py@@ -1,18 +1,73 @@from __future__ import annotationsimport uuid+from dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any, Mappingfrom config.v2_config import ModelHubAgentSupplyConfig, ModelHubConfig-from core.handlers.model_hub.adapter import DiscoveredModel, OAuthFlowState+from core.handlers.model_hub.adapter import (+ DiscoveredModel,+ ObservationDiscovery,+ ObservationOutcome,+ OAuthFlowState,+ SourceObservation,+ make_source_observation,+)from core.handlers.model_hub.events import BoundedEventLog-from core.handlers.model_hub.native_oauth import AgentAuthNativeOAuthAdapter, _account_label, _signed_in+from core.handlers.model_hub.native_oauth import (+ AgentAuthNativeOAuthAdapter,+ _account_label,+ _signed_in,+ _VENDOR_BACKENDS,+)from core.handlers.model_hub.oauth import OAuthFlowRegistryfrom core.handlers.model_hub.revocations import CredentialRevocationJournal-from core.handlers.model_hub.service import ModelHubService, UnavailableEngineAdapter+from core.handlers.model_hub.service import (+ ModelHubService,+ UnavailableEngineAdapter,+ _NATIVE_VENDOR_BACKENDS,+)+from vibe.model_hub_runtime.adapter import _OAUTH_ENDPOINTS, hub_subscription_serving_protocol+++def native_custody_vendors() -> frozenset[str]:+ """Every vendor id a sanctioned CLI can hold custody of.++ Two tables state this fact — the service's route table and the native+ bridge's — and they are expected to agree. Unioning them means a drift+ widens native custody rather than inventing a hub-only vendor on top of it.+ """++ return frozenset(_NATIVE_VENDOR_BACKENDS) | frozenset(_VENDOR_BACKENDS)+++def hub_only_subscription_vendors() -> tuple[str, ...]:+ """The subscription vendors the hub channel owns outright.++ Derived, not listed: a vendor is hub-only when the engine can start an OAuth+ flow for it and no sanctioned CLI holds custody of that flow's grant.++ Custody is compared on the engine start ROW, not on the vendor id, because+ one vendor can answer to two names. ``codex`` and ``openai`` share an+ endpoint, a callback provider, and an auth provider, so they are the same+ subscription reached by two ids — and the natively-custodied one of the two+ claims the row for both. A vendor added to either product table lands here+ without anyone editing a scenario; a second name for an existing vendor does+ not.+ """++ custodied = native_custody_vendors()+ native_rows = {_OAUTH_ENDPOINTS[vendor] for vendor in custodied & set(_OAUTH_ENDPOINTS)}+ return tuple(+ sorted(+ vendor+ for vendor, row in _OAUTH_ENDPOINTS.items()+ if row not in native_rows+ )+ )class MemoryStore:@@ -172,21 +227,84 @@ class NativeOAuthScenarioHarness:)+@dataclass(frozen=True)+class HubOAuthStartForm:+ """What one start asks of the user, as the engine declares it.++ The real adapter reads this from the start response rather than from the+ vendor, so a case that wants a device flow sets the form and every vendor+ answers with it. There is deliberately no per-vendor table here: which form+ a given vendor was observed to issue is a fact about the pinned engine, and+ freezing a second copy of it in a harness would outlive the pin it came from.+ """++ expects: str = "paste_code"+ auth_url: str | None = "https://example.test/oauth"+ device_code: str | None = None+ instructions_key: str | None = "settings.models.oauth.pasteCode.hint"+++#: The engine refusal the real adapter ends on when a finished grant has no way+#: to establish a protocol: every probe candidate raised, nothing was received,+#: and so there is no reachability evidence at all. This is what a vendor with+#: neither a response probe nor an engine-declared serving pin reaches, which is+#: why it stays the default: it is the shape a *new* start row would produce+#: before it is given a binding route (AUTH-SETUP-117).+#: A case whose grant is supposed to bind sets `engine_served_observation`.+UNPROVEN_OAUTH_OBSERVATION = make_source_observation(+ outcome=ObservationOutcome.ADAPTER_ERROR,+ reachable=None,+ authenticated=None,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ models=(),+)+++def engine_served_observation(vendor: str, *, models: tuple[str, ...]) -> SourceObservation:+ """What the real adapter reports for a subscription bound by its serving pin.++ The protocol is read from the pin rather than restated, so a pin the engine+ changes at the next bump flows into the scenario instead of being asserted+ against a frozen copy of it. Reachability and authentication come from the+ engine-managed flow that just completed: it holds the credential, and+ completing the grant is it accepting the credential.+ """++ protocol = hub_subscription_serving_protocol(vendor)+ if protocol is None:+ raise AssertionError(f"{vendor} has no engine-declared serving protocol")+ return make_source_observation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol=protocol,+ discovery=ObservationDiscovery.SUCCEEDED,+ models=tuple(DiscoveredModel(id=model) for model in models),+ )++class FakeHubOAuthAdapter(UnavailableEngineAdapter):def __init__(self):self.flows: dict[str, OAuthFlowState] = {}self.synced = []+ self.start_form = HubOAuthStartForm()+ self.start_calls: list[str] = []+ self.observation = UNPROVEN_OAUTH_OBSERVATION+ self.observation_calls: list[tuple[str, str | None, tuple[str, ...]]] = []+ self.revoked: list[str] = []async def start_oauth(self, source_id: str, vendor: str) -> OAuthFlowState:+ self.start_calls.append(vendor)flow = OAuthFlowState(flow_id=f"hub_{uuid.uuid4().hex[:8]}",source_id=source_id,vendor=vendor,state="awaiting_action",- auth_url="https://example.test/oauth",- device_code=None,- expects="paste_code",- instructions_key="settings.models.oauth.pasteCode.hint",+ auth_url=self.start_form.auth_url,+ device_code=self.start_form.device_code,+ expects=self.start_form.expects,+ instructions_key=self.start_form.instructions_key,error_key=None,expires_at_iso="2026-07-25T00:15:00+00:00",credential_ref=None,@@ -203,6 +321,19 @@ class FakeHubOAuthAdapter(UnavailableEngineAdapter):async def discover_models(self, vendor, protocol, base_url, credential_ref):return (DiscoveredModel(id="claude-opus-4-6"),)+ async def observe_source(+ self,+ vendor: str,+ base_url: str | None,+ credential_ref: str,+ protocol_order,+ ) -> SourceObservation:+ self.observation_calls.append((vendor, base_url, tuple(protocol_order)))+ return self.observation++ async def revoke_credential(self, credential_ref: str) -> None:+ self.revoked.append(credential_ref)+def complete(self, flow_id: str) -> None:flow = self.flows[flow_id]self.flows[flow_id] = OAuthFlowState(diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex d5a21af56..3dc5aeb51 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -134,6 +134,34 @@ scenarios:layer: scenariobackend: sharedtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_custom_auto_policy_response_cannot_reject_or_exclude_credentials+ - id: AUTH-SETUP-115+ name: Hub-only subscription vendors start a hub-channel flow carrying the engine-declared presentation form+ status: covered+ kind: happy_path+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_hub_only_subscription_vendors_start_a_hub_flow_and_refuse_native_custody+ - id: AUTH-SETUP-116+ name: Hub-only subscription vendors refuse native_cli custody before any CLI login starts+ status: covered+ kind: negative_path+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_hub_only_subscription_vendors_start_a_hub_flow_and_refuse_native_custody+ - id: AUTH-SETUP-117+ name: Unproven hub-only subscription grant refuses cleanly, revoking the credential and leaving no Source+ status: covered+ kind: negative_path+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_unproven_hub_subscription_grant_refuses_and_leaves_no_source+ - id: AUTH-SETUP-118+ name: Hub-only subscription grant binds to a Gateway Source and supplies its models+ status: covered+ kind: happy_path+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_hub_subscription_grant_binds_a_source_and_supplies_its_models- id: AUTH-SETUP-201name: Re-entering setup replaces the active flowstatus: covereddiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex 50d4ba5ba..a02663071 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -39,7 +39,11 @@ from config.v2_config import ()from core.agent_auth_service import AgentAuthServicefrom core.handlers.model_hub.adapter import SOURCE_PROTOCOLS-from core.handlers.model_hub.service import ModelHubError+from core.handlers.model_hub.service import (+ ModelHubError,+ _NATIVE_VENDOR_BACKENDS,+ seeded_source_name,+)from core.show_pages import ShowPageStorefrom modules.agents.codex.agent import CodexAgentfrom tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcess@@ -48,7 +52,10 @@ from tests.ui_server_test_helpers import _save_config, csrf_headers, remote_sessfrom storage import remote_access_authorization_servicefrom tests.scenario_harness.model_hub_native_oauth import (HubOAuthScenarioHarness,+ HubOAuthStartForm,NativeOAuthScenarioHarness,+ engine_served_observation,+ hub_only_subscription_vendors,)from vibe.api import (get_claude_auth,@@ -63,7 +70,11 @@ from vibe.claude_config import (from vibe import remote_access, show_identity, ui_serverfrom vibe.ui_server import appfrom vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalog-from vibe.model_hub_runtime.adapter import _OAUTH_ENDPOINTS+from vibe.model_hub_runtime.adapter import (+ _OAUTH_ENDPOINTS,+ _OAUTH_OBSERVABLE_VENDORS,+ hub_subscription_serving_protocol,+)def test_auth_setup_catalog_priorities_reference_live_scenarios():@@ -1446,6 +1457,236 @@ class AgentAuthSetupScenarioTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(agent["sources"]["order"], [source.id])self.assertEqual(agent["supply_status"], "ok")+ async def test_hub_only_subscription_vendors_start_a_hub_flow_and_refuse_native_custody(self):+ """Scenario: AUTH-SETUP-115, AUTH-SETUP-116.++ The three hub-only subscription vendors take the same two-step journey+ the shipped ones do, only through the hub adapter: a start reaches the+ engine's own OAuth endpoint and comes back with the presentation form the+ engine declared, and the native channel refuses them before it would+ spawn any CLI login.++ Both halves are properties of the derived hub-only vocabulary, not of a+ list of vendor names, so a vendor that becomes hub-only later is covered+ by this case without editing it. The refusal is checked against the+ ``native_cli`` gate's own table too: a vendor that the native bridge+ cannot hand to a CLI is refused there, and if the two tables ever+ disagreed about who owns custody, this case would name the disagreement+ instead of quietly starting a CLI login.+ """+ vendors = hub_only_subscription_vendors()+ # Deriving the set proves nothing if it came back empty, and the two+ # shipped subscriptions are the rows that must stay out of it.+ self.assertTrue(vendors)+ self.assertFalse(set(vendors) & set(_NATIVE_VENDOR_BACKENDS))+ self.assertIn("anthropic", _NATIVE_VENDOR_BACKENDS)+ self.assertIn("openai", _NATIVE_VENDOR_BACKENDS)++ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)++ for form in (+ # Form C: the grant comes back through a redirect, so the flow asks+ # the user to paste the callback URL the provider landed on.+ HubOAuthStartForm(+ expects="paste_callback_url",+ auth_url="https://example.test/oauth",+ device_code=None,+ instructions_key=None,+ ),+ # Form B: the provider issued a device code, so there is nothing to+ # paste and the flow only has to be watched.+ HubOAuthStartForm(+ expects="none",+ auth_url="https://example.test/device",+ device_code="ABCD-1234",+ instructions_key=None,+ ),+ ):+ hub = HubOAuthScenarioHarness(Path(state_dir.name))+ hub.adapter.start_form = form+ native = NativeOAuthScenarioHarness(Path(state_dir.name))++ for vendor in vendors:+ with self.subTest(vendor=vendor, expects=form.expects):+ started = await hub.service.oauth_start(+ {"vendor": vendor, "channel": "hub"}+ )++ flow = started["flow"]+ self.assertEqual(flow["vendor"], vendor)+ self.assertEqual(flow["channel"], "hub")+ self.assertEqual(flow["intent"], "create")+ self.assertEqual(flow["state"], "awaiting_action")+ self.assertEqual(flow["presentation"]["expects"], form.expects)+ self.assertEqual(flow["presentation"]["auth_url"], form.auth_url)+ self.assertEqual(flow["presentation"]["device_code"], form.device_code)+ # The start reached the hub adapter — the engine's own OAuth+ # endpoint — and not a CLI login.+ self.assertEqual(hub.adapter.start_calls, [vendor])+ # Nothing persisted yet: a started flow is a claim on the+ # engine, not a Source.+ self.assertEqual(hub.store.config.sources, [])+ hub.adapter.start_calls.clear()++ with self.assertRaises(ModelHubError) as refused:+ await native.service.oauth_start(+ {"vendor": vendor, "channel": "native_cli"}+ )++ self.assertEqual(refused.exception.code, "engine_down")+ self.assertEqual(refused.exception.status, 503)+ self.assertEqual(native.agent_auth.start_calls, [])++ async def test_unproven_hub_subscription_grant_refuses_and_leaves_no_source(self):+ """Scenario: AUTH-SETUP-117.++ A finished grant is not a Source. Persisting one needs an interface to+ talk to the upstream over, and the hub path can learn it three ways: a+ response-backed protocol observation, an engine-declared serving pin, or+ a protocol fixed by the vendor's native backend. A grant that reaches+ none of them ends in an honest refusal, and, just as importantly, in a+ clean one: the credential the grant produced is revoked and the flow is+ forgotten, so a retry starts from nothing.++ This is the negative that guards the whole start table rather than any+ vendor in it. The refusal is driven by an observation the fake adapter is+ told to return — the same terminal product the real adapter reaches when+ it can neither probe an upstream nor read a pin — so the case states what+ the service does with an unbindable grant, which is exactly what a start+ row added without a binding route would produce. That such a row cannot+ exist today is asserted separately, as a partition over the start table,+ in ``tests/test_model_hub_runtime.py``; the happy path the three shipped+ vendors actually take is AUTH-SETUP-118.+ """+ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)+ harness = HubOAuthScenarioHarness(Path(state_dir.name))+ # The default observation is the unproven one, so this case needs no+ # setup at all; stating it keeps the intent visible next to the refusal.+ self.assertEqual(harness.adapter.observation.protocol, None)++ for vendor in hub_only_subscription_vendors():+ with self.subTest(vendor=vendor):+ started = await harness.service.oauth_start(+ {"vendor": vendor, "channel": "hub"}+ )+ flow_id = started["flow"]["flow_id"]+ source_id = started["flow"]["source_id"]+ harness.adapter.complete(flow_id)++ with self.assertRaises(ModelHubError) as refused:+ await harness.service.oauth_status(flow_id)++ self.assertEqual(refused.exception.code, "discovery_failed")+ self.assertEqual(refused.exception.status, 400)+ self.assertEqual(+ refused.exception.detail, "modelHub.errors.discovery_failed"+ )+ # Observation was attempted for the finished grant, across the+ # whole protocol order: the refusal is a proof that failed, not+ # a path that was never taken.+ self.assertEqual(+ harness.adapter.observation_calls,+ [(vendor, None, SOURCE_PROTOCOLS)],+ )+ # Clean: no Source, credential revoked and unjournaled, flow+ # forgotten so the same vendor can be started again.+ self.assertEqual(harness.store.config.sources, [])+ self.assertEqual(harness.adapter.revoked, ["cred_consent01"])+ self.assertEqual(harness.service.revocations.list(), [])+ with self.assertRaises(ModelHubError) as forgotten:+ await harness.service.oauth_status(flow_id)+ self.assertEqual(forgotten.exception.code, "flow_not_found")+ self.assertEqual(forgotten.exception.status, 404)++ retried = await harness.service.oauth_start(+ {"vendor": vendor, "channel": "hub"}+ )+ self.assertNotEqual(retried["flow"]["flow_id"], flow_id)+ self.assertNotEqual(retried["flow"]["source_id"], source_id)++ harness.adapter.start_calls.clear()+ harness.adapter.observation_calls.clear()+ harness.adapter.revoked.clear()++ async def test_hub_subscription_grant_binds_a_source_and_supplies_its_models(self):+ """Scenario: AUTH-SETUP-118.++ The happy path, end to end through the generic §1.4 states: authorize+ against a stubbed engine, and the finished grant becomes a hub Gateway+ Source carrying the engine-declared serving protocol, with the models+ that subscription supplies attached to it.++ The protocol is never named here. It comes from the same pin the adapter+ reads, so a pin the engine changes at the next bump flows into this case+ instead of being asserted against a frozen copy of it — and a vendor+ added to the pin table is covered without editing the case. The models+ are named, because a Source that binds and supplies nothing is not the+ outcome this scenario exists to prove.+ """+ state_dir = tempfile.TemporaryDirectory()+ self.addCleanup(state_dir.cleanup)++ for vendor in hub_only_subscription_vendors():+ with self.subTest(vendor=vendor):+ harness = HubOAuthScenarioHarness(Path(state_dir.name))+ harness.adapter.observation = engine_served_observation(+ vendor,+ models=(f"{vendor}-plan-model",),+ )++ started = await harness.service.oauth_start(+ {"vendor": vendor, "channel": "hub"}+ )+ flow_id = started["flow"]["flow_id"]+ harness.adapter.complete(flow_id)+ terminal = await harness.service.oauth_status(flow_id)++ self.assertEqual(terminal["flow"]["state"], "success")+ self.assertEqual(terminal["flow"]["intent"], "create")++ source = terminal["source"]+ self.assertEqual(source, harness.service.list_sources()[0])+ self.assertEqual(source["vendor"], vendor)+ self.assertEqual(source["supply_channel"], "hub")+ self.assertEqual(source["billing"], "monthly")+ self.assertIsNone(source["base_url"])+ self.assertEqual(+ source["protocol"],+ hub_subscription_serving_protocol(vendor),+ )+ # A name the user can read, not the routing key. Taken from the+ # same seed the api-key path uses, so this reads `xAI` and not+ # `xai` — asserted through the seed rather than a literal, for+ # the same reason as the protocol above.+ self.assertEqual(source["display_name"], seeded_source_name(vendor))+ self.assertEqual(source["credential_ref"], "cred_consent01")+ self.assertEqual(+ [model["id"] for model in source["models"]],+ [f"{vendor}-plan-model"],+ )+ self.assertEqual(+ [model["origin"] for model in source["models"]],+ ["discovered"],+ )+ # The grant was observed once, and the credential it produced was+ # kept: a bound Source is the opposite of AUTH-SETUP-117's clean+ # refusal, which revokes.+ self.assertEqual(len(harness.adapter.observation_calls), 1)+ observed_vendor, observed_base_url, _order = (+ harness.adapter.observation_calls[0]+ )+ self.assertEqual((observed_vendor, observed_base_url), (vendor, None))+ self.assertEqual(harness.adapter.revoked, [])+ self.assertEqual(harness.service.revocations.list(), [])+ # The Source reached the Gateway as an upstream, not just the+ # config file.+ self.assertEqual(+ [binding.source_id for binding in harness.adapter.synced[-1]],+ [source["id"]],+ )+async def test_lost_model_hub_oauth_start_response_reuses_nonce_flow(self):"""Scenario: AUTH-SETUP-210.@@ -2838,12 +3079,20 @@ def test_api_key_setup_does_not_schedule_a_model(],)@pytest.mark.parametrize("validation_before_auth", [False, True])[email protected]("vendor", tuple(_OAUTH_ENDPOINTS))[email protected]("vendor", sorted(_OAUTH_OBSERVABLE_VENDORS))@pytest.mark.parametrize("credential_valid", [True, False])def test_hub_oauth_model_free_observation_closed_loop(monkeypatch, tmp_path, caplog, status, body, validation_before_auth, vendor, credential_valid,):- """Scenario: AUTH-SETUP-113"""+ """Scenario: AUTH-SETUP-113++ Scoped to the vendors whose protocol is proved by a response, because what+ this asserts is a property of the request that proves it: no `model` field.+ A vendor bound by an engine-declared serving pin issues no such request at+ all — the completed grant is its evidence — so its closed loop is+ AUTH-SETUP-118. `_OAUTH_OBSERVABLE_VENDORS` keeps the routes apart rather+ than a list here.+ """from tests.test_model_hub_api import _servicefrom vibe.model_hub_runtime.adapter import CLIProxyEngineAdapterfrom vibe.model_hub_runtime.state import EngineStateStorediff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 6cca66d5a..5cf6c5320 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -74,6 +74,7 @@ from core.handlers.model_hub.service import (ModelHubService,ResolvedInvocation,project_opencode_public_model,+ seeded_source_name,)from core.handlers.model_hub.turn_gateway import (ModelHubTurnGateway,@@ -102,6 +103,9 @@ from vibe.i18n import t as i18n_tfrom vibe.model_hub_runtime.adapter import (_AuthenticationEvidence,CLIProxyEngineAdapter,+ hub_subscription_serving_protocol,+ _HUB_SUBSCRIPTION_PROTOCOLS,+ _OAUTH_ENDPOINTS,_parse_protocol_authenticated_evidence,_probe_protocol_response,_PROTOCOL_OBSERVATION_TAXONOMY,@@ -109,7 +113,11 @@ from vibe.model_hub_runtime.adapter import (_ProtocolObservationShape,_ProtocolProof,)-from vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalog+from vibe.model_hub_runtime.api_key_vendors import (+ api_key_vendor_catalog,+ catalog_api_key_vendor_label,+ pinned_api_key_protocol,+)from vibe.model_hub_runtime.client import EngineClientError, probe_modelsfrom vibe.model_hub_runtime.state import EngineStateStore@@ -7385,6 +7393,107 @@ def test_oauth_observation_does_not_use_api_key_catalog_pins_without_shape_proofassert [call.kwargs["protocol"] for call in oauth_probe.call_args_list] == list(SOURCE_PROTOCOLS)[email protected]("vendor", sorted(_HUB_SUBSCRIPTION_PROTOCOLS))+def test_hub_subscription_observation_binds_on_the_engine_declared_protocol(+ tmp_path: Path,+ vendor: str,+) -> None:+ """A pinned subscription binds without a probe, and asks for nothing else.++ The engine holds the credential and serves it on one surface, so there is no+ upstream Avibe may synthesize a request against — the completed grant is the+ reachability and authentication evidence, and the pin supplies the protocol.+ Seeding the whole pin table keeps a vendor added later covered without+ editing this test.+ """++ state_store = EngineStateStore(tmp_path / "engine-state")+ credential_ref = state_store.bind_oauth_credential(+ "src_hubsubscript",+ vendor,+ f"{vendor}-test.json",+ )+ client = Mock()++ def management_request(method, path, *, query=None, payload=None):+ if path == "/auth-files":+ return {+ "files": [+ {+ "id": f"{vendor}-test",+ "auth_index": "auth-index-test",+ "name": f"{vendor}-test.json",+ "provider": vendor,+ }+ ]+ }+ raise AssertionError((method, path))++ client.management_request.side_effect = management_request+ supervisor = Mock()+ supervisor.client.return_value = client+ adapter = CLIProxyEngineAdapter(+ supervisor=supervisor,+ state_store=state_store,+ )++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_oauth_protocol_response",+ side_effect=AssertionError("a pinned subscription must not be probed"),+ ),+ patch.object(+ adapter,+ "discover_models",+ new=AsyncMock(return_value=(DiscoveredModel(id=f"{vendor}-model"),)),+ ) as discover_models,+ ):+ observed = asyncio.run(+ adapter.observe_source(+ vendor,+ None,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ pinned = hub_subscription_serving_protocol(vendor)+ assert observed.outcome.value == "observed"+ assert observed.reachable is True+ assert observed.authenticated is True+ assert observed.protocol == pinned+ assert observed.model_ids == (f"{vendor}-model",)+ assert discover_models.await_args.args[:3] == (vendor, pinned, None)++[email protected]("vendor", sorted(_HUB_SUBSCRIPTION_PROTOCOLS))+def test_hub_subscription_pin_agrees_with_the_same_vendors_api_key_pin(vendor: str) -> None:+ """One vendor, one protocol, whichever channel holds the credential.++ `_validate_source_target` admits a Source with no base URL by consulting the+ api-key catalog pin, so a subscription pinned to a protocol its api-key+ sibling contradicts would need that validator taught about a second pin.+ Asserting the agreement here is cheaper than carrying that second pin.+ """++ assert hub_subscription_serving_protocol(vendor) == pinned_api_key_protocol(vendor)++[email protected]("vendor", sorted(_OAUTH_ENDPOINTS))+def test_oauth_source_is_seeded_with_its_vendors_catalog_label(vendor: str) -> None:+ """A vendor id is a routing key, so no Source may be named by one we can name.++ Seeded over the whole start table rather than the vendors this change adds:+ an OAuth vendor the catalog already lists cannot be admitted and then ship+ named `xai` beside an api-key Source of the same vendor reading `xAI`. The+ id survives as the seed only for a vendor the catalog does not list, which+ is the only name that channel has for it.+ """++ label = catalog_api_key_vendor_label(vendor)+ assert seeded_source_name(vendor) == (label if label is not None else vendor)++DEEPSEEK_AUTHENTICATION_ERROR_PAYLOAD = {"error": {"message": "Authentication Fails, Your api key: **** is invalid",diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 6d4ec20a3..dacc14890 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -29,6 +29,7 @@ from core.handlers.model_hub.adapter import (RawOutcomeKind,RetainedMaterialDisposition,RuntimePlatformUnsupportedError,+ SOURCE_PROTOCOLS,SourceBinding,)from core.handlers.model_hub.classification import (@@ -6512,57 +6513,139 @@ def test_model_discovery_translates_local_spool_failures(asyncio.run(run())- ("vendor", "endpoint"),- [- ("anthropic", "/anthropic-auth-url"),- ("openai", "/codex-auth-url"),- ("codex", "/codex-auth-url"),- ],-)-def test_oauth_start_uses_webui_callback_for_observable_vendors(- tmp_path: Path,- vendor: str,- endpoint: str,-) -> None:- class Client:- def __init__(self) -> None:- self.start_query = None+class _OAuthStartClient:+ """One engine client that answers whichever start endpoint it is asked for."""- def management_request(self, method, path, *, query=None, payload=None, timeout=None):- if path == "/auth-files":- return {"files": []}- if path == endpoint:- self.start_query = query- return {"state": "engine-state", "url": "https://example.test/oauth"}- raise AssertionError((method, path, query, payload, timeout))+ def __init__(self, response: dict[str, object]) -> None:+ self.response = response+ self.start_path: str | None = None+ self.start_query: object = None- class Supervisor:- def __init__(self, store: EngineStateStore, client: Client) -> None:- self.state_store = store- self._client = client+ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ if path == "/auth-files":+ return {"files": []}+ if path.endswith("-auth-url"):+ self.start_path = path+ self.start_query = query+ return dict(self.response)+ raise AssertionError((method, path, query, payload, timeout))- def client(self):- return self._client- async def run() -> None:- store = EngineStateStore(tmp_path / "state")- client = Client()+class _OAuthStartSupervisor:+ def __init__(self, store: EngineStateStore, client: _OAuthStartClient) -> None:+ self.state_store = store+ self._client = client++ def client(self) -> _OAuthStartClient:+ return self._client+++def _start_oauth_against(+ tmp_path: Path,+ vendor: str,+ response: dict[str, object],+) -> tuple[_OAuthStartClient, object]:+ async def run():+ store = EngineStateStore(tmp_path / f"state-{vendor}")+ client = _OAuthStartClient(response)adapter = CLIProxyEngineAdapter(- supervisor=Supervisor(store, client), # type: ignore[arg-type]+ supervisor=_OAuthStartSupervisor(store, client), # type: ignore[arg-type]state_store=store,)+ return client, await adapter.start_oauth("src_fixture123", vendor)- flow = await adapter.start_oauth("src_fixture123", vendor)+ return asyncio.run(run())- assert client.start_query == {"is_webui": "true"}- assert flow.expects == "paste_callback_url"- asyncio.run(run())[email protected]("vendor", sorted(runtime_adapter_module._OAUTH_ENDPOINTS))+def test_oauth_start_calls_the_endpoint_its_vendor_row_declares(+ tmp_path: Path,+ vendor: str,+) -> None:+ """Admission and routing are the vendor row's job, for every row.+ Seeding the whole table rather than a list of vendor names keeps a row added+ later covered without editing this test.+ """++ endpoint, _callback_provider, _auth_provider = runtime_adapter_module._OAUTH_ENDPOINTS[vendor]++ client, _flow = _start_oauth_against(+ tmp_path,+ vendor,+ {"state": "engine-state", "url": "https://example.test/oauth"},+ )++ assert client.start_path == endpoint+ assert client.start_query == {"is_webui": "true"}[email protected]("vendor", ["antigravity", "kimi", "xai"])-def test_oauth_start_rejects_engine_only_vendors_before_engine_work(++ ("response", "expects", "auth_url", "device_code"),+ [+ pytest.param(+ {"state": "engine-state", "url": "https://example.test/oauth"},+ "paste_callback_url",+ "https://example.test/oauth",+ None,+ id="redirect-callback",+ ),+ pytest.param(+ {+ "state": "engine-state",+ "flow": "device",+ "url": "https://example.test/device",+ "user_code": "ABCD-1234",+ "expires_in": 600,+ },+ "none",+ "https://example.test/device",+ "ABCD-1234",+ id="device-code",+ ),+ pytest.param(+ # xAI and Kimi omit `user_code` when the upstream returned none, so+ # `flow` alone has to carry the form.+ {"state": "engine-state", "flow": "device", "verification_uri": "https://example.test/device"},+ "none",+ "https://example.test/device",+ None,+ id="device-flow-without-a-code",+ ),+ ],+)[email protected]("vendor", sorted(runtime_adapter_module._OAUTH_ENDPOINTS))+def test_oauth_start_reads_the_presentation_form_from_the_engine_response(+ tmp_path: Path,+ vendor: str,+ response: dict[str, object],+ expects: str,+ auth_url: str,+ device_code: str | None,+) -> None:+ """What the flow asks of the user comes from the response, never the vendor.++ Every vendor is driven through every response shape on purpose: the form is a+ property of what the engine answered, so no vendor may carry its own table of+ what to render. That is also why the per-vendor forms observed at the pinned+ engine commit are recorded in the PR rather than frozen here — a form is only+ as current as the response that carried it.+ """++ _client, flow = _start_oauth_against(tmp_path, vendor, response)++ assert flow.expects == expects+ assert flow.auth_url == auth_url+ assert flow.device_code == device_code+++ "vendor",+ # `antigravity`, `claude`, and `grok` are names the engine answers to. None of+ # them is an Avibe vendor id, so admission by engine vocabulary is refused.+ ["antigravity", "claude", "grok", "qwen", "iflow", ""],+)+def test_oauth_start_rejects_vendors_no_row_admits_before_engine_work(tmp_path: Path,vendor: str,) -> None:@@ -6579,13 +6662,77 @@ def test_oauth_start_rejects_engine_only_vendors_before_engine_work(with pytest.raises(EngineStateError,- match="lacks Model Hub response-backed observation",+ match="lacks a Model Hub subscription flow",):await adapter.start_oauth("src_fixture123", vendor)+ assert vendor not in runtime_adapter_module._OAUTH_ENDPOINTSasyncio.run(run())[email protected]("vendor", sorted(runtime_adapter_module._OAUTH_ENDPOINTS))+def test_every_oauth_start_vendor_binds_by_exactly_one_route(+ vendor: str,+) -> None:+ """A flow that can start must be able to end, by one route or the other.++ A finished grant becomes a hub Source only once a protocol is established,+ and there are exactly two ways to establish one: probe the upstream and read+ the protocol out of the response, or take the engine-declared serving pin for+ a vendor whose credential never leaves the engine. This asserts the partition+ over the whole start table — every row takes one route, none takes both, none+ takes neither — so a vendor admitted to `_OAUTH_ENDPOINTS` without a binding+ route fails here instead of shipping a flow that authorizes and then dies in+ `discovery_failed`.++ The probe's own reach is pinned against `_OAUTH_OBSERVABLE_VENDORS` at the+ same time, by driving the real probe rather than restating the set: widening+ one without the other is a failure, not a silent change.+ """++ auth = runtime_adapter_module._AuthRecord(+ identity="account.json",+ auth_index="0",+ name="account.json",+ provider=vendor,+ fingerprint="fp",+ )++ class Client:+ def __init__(self) -> None:+ self.calls: list[str] = []++ def management_request(self, method, path, *, query=None, payload=None, timeout=None):+ self.calls.append(path)+ return {"status_code": 200, "body": json.dumps({"type": "message"})}++ observed: set[str] = set()+ for protocol in SOURCE_PROTOCOLS:+ client = Client()+ try:+ runtime_adapter_module._probe_oauth_protocol_response(+ client=client, # type: ignore[arg-type]+ auth=auth,+ vendor=vendor,+ protocol=protocol,+ )+ except EngineClientError as refused:+ assert refused.status_code == 404+ assert client.calls == []+ continue+ assert client.calls == ["/api-call"]+ observed.add(protocol)++ assert bool(observed) is (vendor in runtime_adapter_module._OAUTH_OBSERVABLE_VENDORS)++ pinned = runtime_adapter_module.hub_subscription_serving_protocol(vendor)+ assert (pinned is not None) != bool(observed), (+ f"{vendor} must bind by exactly one of a response probe or an engine-declared pin"+ )+ if pinned is not None:+ assert pinned in SOURCE_PROTOCOLS++def test_oauth_model_discovery_accepts_engine_definition_fields(tmp_path: Path) -> None:class Client:def management_request(self, method, path, *, query=None, payload=None, timeout=None):@@ -6952,11 +7099,15 @@ def test_oauth_flow_releases_provider_after_engine_failure_or_expiry(tmp_path: Pstate_store=store,)+ # An unadmitted vendor must not consume the provider slot. Named with an+ # engine-side name rather than an Avibe vendor id, because an Avibe id+ # that is unadmitted today is exactly what a vendor expansion admits+ # tomorrow — and then this stops testing a refusal at all.with pytest.raises(EngineStateError,- match="lacks Model Hub response-backed observation",+ match="lacks a Model Hub subscription flow",):- await adapter.start_oauth("src_fixture123", "gemini")+ await adapter.start_oauth("src_fixture123", "antigravity")failed_flow = await adapter.start_oauth("src_fixture123", "anthropic")supervisor.unavailable = Truediff --git a/ui/src/components/settings/models/OAuthConnectDialog.tsx b/ui/src/components/settings/models/OAuthConnectDialog.tsxindex c6aab3f48..2276f2457 100644--- a/ui/src/components/settings/models/OAuthConnectDialog.tsx+++ b/ui/src/components/settings/models/OAuthConnectDialog.tsx@@ -50,8 +50,8 @@ import {initialSubscriptionChannel,nativeSubscriptionSlotTaken,recommendedSubscriptionChannel,+ subscriptionChooser,subscriptionOptionOrder,- subscriptionVendorCopy,} from './subscriptionOptions';import { GuardGapList } from './GuardGapList';import { ACCENT_ICON, ACCENT_TILE } from './vendorMeta';@@ -156,6 +156,10 @@ export const OAuthConnectDialog: React.FC<{}, []);const accent = vendor === 'openai' ? 'gold' : 'mint';+ // The vendor's chooser copy, or null for a subscription no sanctioned CLI can+ // hold. Read once, outside the effect that consumes it: it is a fact about the+ // vendor, not about this open.+ const chooser = subscriptionChooser(vendor);// One derivation for 「which journey is this」, read by the start call, the// terminal handler and the title alike.const reauthId = reauth?.id ?? null;@@ -191,8 +195,13 @@ export const OAuthConnectDialog: React.FC<{const occupied = nativeSubscriptionSlotTaken(vendor, sources);setNativeSlotTaken(occupied);setChannel(initialSubscriptionChannel(vendor, sources));- setPhase('choose');- }, [isReauth, openSubject, reauth?.supply_channel, sources, vendor]);+ // A vendor with no chooser copy has no channel choice to put in front of the+ // user, so it opens straight into its flow — the same entry the re-auth+ // journey takes above. The gesture that allocated its provider tab was the+ // menu item that opened this dialog (PD-1), since there is no 去登录 here to+ // allocate one.+ setPhase(chooser === null ? 'flow' : 'choose');+ }, [chooser, isReauth, openSubject, reauth?.supply_channel, sources, vendor]);/*** One owner for 「the server moved the rows the page behind this dialog draws」,@@ -744,9 +753,13 @@ export const OAuthConnectDialog: React.FC<{}}, [flowActive, presentation?.auth_url]);- const choosing = !isReauth && phase === 'choose';- const vendorCopy = subscriptionVendorCopy(vendor);- const vendorName = vendor === 'openai' ? 'ChatGPT' : 'Claude';+ // The chooser is only for a vendor whose copy exists. A hub-held subscription+ // has no channel choice to make, so it opens straight into its flow (the open+ // effect above), and this guard is the render-side half of the same rule: a+ // chooser drawn for such a vendor would read every line off `null` and+ // interpolate i18n keys at the user. Narrowing on `chooser` here rather than on+ // a bare phase check is what makes that a type error, not a runtime one.+ const choosing = !isReauth && phase === 'choose' && chooser !== null;const recommended = recommendedSubscriptionChannel(vendor);const optionOrder = subscriptionOptionOrder(vendor);const optionRefs = React.useRef<Partial<Record<SupplyChannel, HTMLButtonElement | null>>>({});@@ -761,7 +774,9 @@ export const OAuthConnectDialog: React.FC<{window.requestAnimationFrame(() => optionRefs.current[next]?.focus());};- if (choosing) {+ if (choosing && chooser) {+ const vendorCopy = chooser.copy;+ const vendorName = chooser.brand;return (<DialogPrimitive.Root open={open} onOpenChange={(value) => !value && onClose()}><DialogPrimitive.Portal>diff --git a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsxindex 7fe060f13..e477078d3 100644--- a/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.render.test.tsx@@ -15,6 +15,7 @@ import type { ModelsSurfaceKind } from './modelHubSurfaceState';import { modelsApi } from './modelsApi';import { SOURCE_MUTATION_REPORT_PROJECTIONS } from './mutationSettlement';import { SettingsModelsPage } from './SettingsModelsPage';+import { hasNativeSubscriptionCustody, SUBSCRIPTION_VENDORS } from './subscriptionOptions';import { CONTRACT_VERSION, type AgentBackend, type AgentChain, type AgentSupply, type BackendModel, type RuntimeDependency, type RuntimeManifest, type Source, type UsageSummary } from './types';const directAgent = (backend: AgentBackend): AgentSupply => ({@@ -674,6 +675,58 @@ describe('SettingsModelsPage surface branches', () => {expect((await screen.findByRole('dialog')).textContent).toMatch(/Add Claude subscription|添加 anthropic 订阅/i);});+ it('lists every offered subscription vendor in frame 13 order, with a mark and only the badge it earns', async () => {+ renderPage([retainedSource]);++ await screen.findByText('Retained source');+ await userEvent.click(screen.getByRole('button', { name: /Add subscription|添加订阅/i }));+ const picker = await screen.findByRole('menu');+ const rows = within(picker).getAllByRole('menuitem');+ // The property: the menu offers exactly the vocabulary §1.4 can start a flow+ // for, in that vocabulary's order — read off the rendered rows, so a vendor+ // added to `SUBSCRIPTION_VENDORS` appears here without this test naming it.+ const rowLabels = rows.map((row) => row.querySelector('span[title]')?.getAttribute('title'));+ expect(rowLabels).toEqual(+ SUBSCRIPTION_VENDORS.map((vendor) => i18n.t(`settings.models.subscriptionPicker.vendor.${vendor}`)),+ );+ for (const row of rows) {+ // Each row carries the vendor's mark, consistent with the api-key picker.+ expect(row.querySelector('svg'), `${row.textContent} has no mark`).toBeTruthy();+ }+ // A hub-held vendor recommends nothing — its only custody is the hub — so it+ // draws no recommendation badge, while the two with a channel choice do.+ const badges = rows.map((row) => /Native recommended|Gateway recommended|推荐由/i.test(row.textContent ?? ''));+ expect(badges).toEqual(SUBSCRIPTION_VENDORS.map(hasNativeSubscriptionCustody));+ });++ it('opens a hub-only subscription straight into its flow, posted as a hub source', async () => {+ // A vendor no sanctioned CLI holds custody of has no channel choice, so §1.4+ // skips its chooser phase and starts the flow on open. The gesture that+ // allocated the provider tab was the menu item, not a 去登录 inside the dialog.+ const started = {+ flow_id: 'flow_hub_only',+ client_nonce: 'ofn_hub_only',+ vendor: 'gemini',+ channel: 'hub' as const,+ state: 'awaiting_action' as const,+ presentation: { expects: 'paste_callback_url' as const, auth_url: 'https://example.test/oauth' },+ expires_at: '2099-01-01T00:00:00Z',+ };+ const start = vi.spyOn(modelsApi, 'startOAuth').mockResolvedValue(started);+ vi.spyOn(modelsApi, 'getOAuthStatus').mockResolvedValue({ flow: started, created: null, repaired: null });+ renderPage([retainedSource]);++ await screen.findByText('Retained source');+ await userEvent.click(screen.getByRole('button', { name: /Add subscription|添加订阅/i }));+ await userEvent.click(await screen.findByRole('menuitem', { name: /^Gemini$/i }));++ // No chooser: no channel radio group rendered between the menu and the flow.+ expect(screen.queryByRole('radiogroup')).toBeNull();+ await waitFor(() => expect(start).toHaveBeenCalledTimes(1));+ expect(start.mock.calls[0]![0]).toBe('gemini');+ expect(start.mock.calls[0]![1]).toBe('hub');+ });+it('supports roving keyboard navigation in the subscription vendor picker', async () => {renderPage([retainedSource]);@@ -682,20 +735,29 @@ describe('SettingsModelsPage surface branches', () => {const trigger = screen.getByRole('button', { name: /Add subscription|添加订阅/i });await user.click(trigger);const picker = await screen.findByRole('menu');- const claude = within(picker).getByRole('menuitem', { name: /Claude subscription|Claude 订阅/i });- const chatgpt = within(picker).getByRole('menuitem', { name: /ChatGPT subscription|ChatGPT 订阅/i });-- await waitFor(() => expect(document.activeElement).toBe(claude));- expect(claude.getAttribute('tabindex')).toBe('0');- expect(chatgpt.getAttribute('tabindex')).toBe('-1');+ // Roving focus is a property of the row LIST, not of which vendor sits at+ // either end, so it is read off the rendered menuitems: first, second and+ // last. Hardcoding `chatgpt` as the End target held only while the menu had+ // two rows; naming the positions keeps it true for however many ship.+ const rows = within(picker).getAllByRole('menuitem');+ expect(rows.length).toBeGreaterThan(1);+ const [first, second] = rows;+ const last = rows[rows.length - 1]!;++ await waitFor(() => expect(document.activeElement).toBe(first));+ expect(first!.getAttribute('tabindex')).toBe('0');+ expect(second!.getAttribute('tabindex')).toBe('-1');await user.keyboard('{ArrowDown}');- expect(document.activeElement).toBe(chatgpt);+ expect(document.activeElement).toBe(second);await user.keyboard('{Home}');- expect(document.activeElement).toBe(claude);+ expect(document.activeElement).toBe(first);await user.keyboard('{End}');- expect(document.activeElement).toBe(chatgpt);+ expect(document.activeElement).toBe(last);await user.keyboard('{ArrowUp}');- expect(document.activeElement).toBe(claude);+ // From the last row, ArrowUp lands on the one before it — which is `first`+ // only when the menu has exactly two rows, so assert the neighbour, not the+ // head.+ expect(document.activeElement).toBe(rows[rows.length - 2]);});it('restores the Add subscription trigger when the vendor picker is dismissed', async () => {diff --git a/ui/src/components/settings/models/SettingsModelsPage.tsx b/ui/src/components/settings/models/SettingsModelsPage.tsxindex 4f9ab818a..8a602607a 100644--- a/ui/src/components/settings/models/SettingsModelsPage.tsx+++ b/ui/src/components/settings/models/SettingsModelsPage.tsx@@ -64,16 +64,20 @@ import {import { freshRuntimeProjection, pollRuntimeStatus, runtimeCanAttemptInstall, runtimeIsRunning, startRuntimeWithStatusRefresh } from './runtimeLifecycle';import { createRouteProjectionReconciler, type RouteProjectionStatus } from './routeProjectionReconciliation';import { useSourceMutationReport } from './useSourceMutationReport';+import { handOffProviderTab } from './providerTab';+import { SUBSCRIPTION_MENU_ROWS, hasNativeSubscriptionCustody } from './subscriptionOptions';+import { VendorGlyph } from './vendorGlyph';import { backendVisual } from './vendorMeta';import { USAGE_DEFAULT_WINDOW_DAYS, type AgentBackend, type AgentSupply, type ResolutionEvent, type RuntimeDependency, type Source, type UsageSummary } from './types';import type { UsageWindowOption } from './usageProjection';const CHAIN_READ_CONCURRENCY = 6;const EVENT_PAGE = 20;-const SUBSCRIPTION_PICKER_OPTIONS = [- { vendor: 'anthropic', recommendation: 'native' },- { vendor: 'openai', recommendation: 'gateway' },-] as const;+// Frame 13's rows, derived from the one subscription-vendor vocabulary rather+// than restated here. `subscriptionOptions.ts` owns which vendors are offered and+// what custody each has, so this menu cannot drift out of the same order the+// dialog's chooser reads.+const SUBSCRIPTION_PICKER_OPTIONS = SUBSCRIPTION_MENU_ROWS;type SubscriptionPickerVendor = (typeof SUBSCRIPTION_PICKER_OPTIONS)[number]['vendor'];const readChainRequests = async (requests: readonly ModelChainRequest[]): Promise<ModelChainIndex> => Object.fromEntries(@@ -1290,7 +1294,11 @@ export const SettingsModelsPage: React.FC = () => {>{SUBSCRIPTION_PICKER_OPTIONS.map(({ vendor, recommendation }, index) => {const vendorLabel = t(`settings.models.subscriptionPicker.vendor.${vendor}`);- const recommendationLabel = t(`settings.models.subscriptionPicker.recommendation.${recommendation}`);+ // A hub-only vendor has no native channel to recommend against, so+ // it carries no badge rather than a 网关推荐 over its only custody.+ const recommendationLabel = recommendation+ ? t(`settings.models.subscriptionPicker.recommendation.${recommendation}`)+ : null;return (<Buttonkey={vendor}@@ -1306,21 +1314,30 @@ export const SettingsModelsPage: React.FC = () => {tabIndex={subscriptionPickerIndex === index ? 0 : -1}onClick={() => {subscriptionPickerHandoffRef.current = true;+ // A hub-only vendor opens §1.4 straight into its flow — no+ // chooser phase, so no 去登录 gesture inside the dialog to+ // allocate the provider tab. This click is the journey's only+ // gesture, exactly as the re-auth confirm is, so the tab is+ // handed off here or the handoff is popup-blocked (PD-1).+ if (!hasNativeSubscriptionCustody(vendor)) handOffProviderTab();setSubscriptionPickerOpen(false);setSubscriptionVendor(vendor);}}>+ <VendorGlyph vendor={vendor} /><span className="min-w-0 flex-1 truncate text-[12.5px] font-semibold" title={vendorLabel}>{vendorLabel}</span>- <Badge- variant="recommendation"- className={cn(- recommendation === 'native'- ? 'model-hub-accent-tile--mint model-hub-accent-ink--mint border-transparent'- : 'model-hub-accent-pill--neutral',- )}- >- {recommendationLabel}- </Badge>+ {recommendationLabel && (+ <Badge+ variant="recommendation"+ className={cn(+ recommendation === 'native'+ ? 'model-hub-accent-tile--mint model-hub-accent-ink--mint border-transparent'+ : 'model-hub-accent-pill--neutral',+ )}+ >+ {recommendationLabel}+ </Badge>+ )}</Button>);})}diff --git a/ui/src/components/settings/models/subscriptionOptions.ts b/ui/src/components/settings/models/subscriptionOptions.tsindex 74e5ca1f2..01187e2e3 100644--- a/ui/src/components/settings/models/subscriptionOptions.ts+++ b/ui/src/components/settings/models/subscriptionOptions.ts@@ -1,9 +1,63 @@+// The subscription vendors the Web UI offers, and the custody facts about them.+//+// Two products name these vendors and neither is reachable from this file. The+// engine's `_OAUTH_ENDPOINTS` table decides which vendors a start may name, and+// the service's `_NATIVE_VENDOR_BACKENDS` route table decides which of those a+// sanctioned CLI can hold custody of; the server refuses a start nobody admits+// before any UI here could render one. The menu's job is narrower, and is the+// reason it lists at all: §1.4's whole chooser phase exists per vendor — the plan+// subtitle, which channel carries 推荐, the ToS note, the hint — and every one of+// those lines is client-owned brand copy. So a vendor appears here when the+// product offers it AND this file can say what choosing between its two channels+// means, and not before.+//+// `hub_only_subscription_vendors()` in `tests/scenario_harness/` derives the+// server's half of the same fact. The two are different questions — that one asks+// who owns custody, this one asks whether the chooser can speak for the vendor —+// so they are not the same list, and a vendor added to the engine's table is+// meant to need a decision here rather than to inherit one.import type { Source, SupplyChannel } from './types';+/** Menu order is frame 13's order: the two subscriptions the chooser has a+ * recommendation for, then the hub-held ones. It is not the engine table's order+ * and not the API-key catalog's A–Z — nothing here sorts, the frame ranked them. */+export const SUBSCRIPTION_VENDORS = ['anthropic', 'openai', 'gemini', 'kimi', 'xai'] as const;+export type SubscriptionVendor = (typeof SUBSCRIPTION_VENDORS)[number];++/** The vendors §1.4's chooser phase is written for.+ *+ * One table answers two questions that have one answer: whether a sanctioned CLI+ * can hold this subscription natively, and whether the client has the per-vendor+ * copy the chooser renders — subtitle, per-option consequence, ToS note, hint.+ * They are kept together because they are only ever decided together: a vendor+ * gains a chooser when Avibe sanctions a CLI for it and someone writes what the+ * choice costs, and a vendor without either is hub-held and starts straight into+ * its flow. Two tables would let them disagree, and the disagreement is not+ * cosmetic — the gesture that allocates the provider tab lives in the menu for a+ * vendor with no chooser and in the dialog for one with a chooser (PD-1).+ */+const SUBSCRIPTION_CHOOSER = {+ anthropic: { copy: 'claude', brand: 'Claude' },+ openai: { copy: 'chatgpt', brand: 'ChatGPT' },+} as const satisfies Record<string, { copy: SubscriptionVendorCopy; brand: string }>;++/** The copy family frame 04's chooser is written in, and the brand name its title+ * interpolates. `null` is the answer for a hub-held vendor, and it is the reason+ * this returns one: every line the chooser renders names a plan, a consequence of+ * a channel, or a ToS note, and a chooser rendered for a vendor with none of them+ * would interpolate an i18n key at the user. Returning `null` makes the type ask+ * each consumer which case it is in. */export type SubscriptionVendorCopy = 'claude' | 'chatgpt';-export const subscriptionVendorCopy = (vendor: string): SubscriptionVendorCopy =>- vendor === 'openai' ? 'chatgpt' : 'claude';+export type SubscriptionChooser = { copy: SubscriptionVendorCopy; brand: string };++export const subscriptionChooser = (vendor: string): SubscriptionChooser | null =>+ (SUBSCRIPTION_CHOOSER as Readonly<Record<string, SubscriptionChooser | undefined>>)[vendor] ?? null;++/** Whether a sanctioned CLI can hold this vendor's subscription natively, and so+ * whether §1.4 has a channel choice to put in front of the user at all. */+export const hasNativeSubscriptionCustody = (vendor: string): boolean =>+ subscriptionChooser(vendor) !== null;export const nativeSubscriptionSlotTaken = (vendor: string, sources: Source[]): boolean =>sources.some(@@ -13,8 +67,12 @@ export const nativeSubscriptionSlotTaken = (vendor: string, sources: Source[]):&& source.vendor === vendor,);-export const recommendedSubscriptionChannel = (vendor: string): SupplyChannel =>- vendor === 'openai' ? 'hub' : 'native_cli';+/** For a hub-held vendor the hub is not a fallback, it is the only custody there+ * is — which is also what its start is posted with. */+export const recommendedSubscriptionChannel = (vendor: string): SupplyChannel => {+ if (!hasNativeSubscriptionCustody(vendor)) return 'hub';+ return vendor === 'openai' ? 'hub' : 'native_cli';+};export const initialSubscriptionChannel = (vendor: string, sources: Source[]): SupplyChannel =>nativeSubscriptionSlotTaken(vendor, sources) ? 'hub' : recommendedSubscriptionChannel(vendor);@@ -23,3 +81,22 @@ export const subscriptionOptionOrder = (vendor: string): SupplyChannel[] =>recommendedSubscriptionChannel(vendor) === 'hub'? ['hub', 'native_cli']: ['native_cli', 'hub'];++/** Which channel the menu recommends, or `null` when the vendor has no native+ * channel to recommend against. A hub-held row carries no badge: 网关推荐 over the+ * only custody there is recommends nothing, and frame 13 draws a badge because+ * both of its rows had a choice to rank. */+export const subscriptionMenuRecommendation = (+ vendor: SubscriptionVendor,+): 'native' | 'gateway' | null => {+ if (!hasNativeSubscriptionCustody(vendor)) return null;+ return recommendedSubscriptionChannel(vendor) === 'hub' ? 'gateway' : 'native';+};++/** The menu's rows: every offered vendor with the badge it earns. Derived from the+ * vocabulary above so a vendor added there appears here with its custody already+ * decided, rather than needing a second list kept in the same order. */+export const SUBSCRIPTION_MENU_ROWS = SUBSCRIPTION_VENDORS.map((vendor) => ({+ vendor,+ recommendation: subscriptionMenuRecommendation(vendor),+})) as ReadonlyArray<{ vendor: SubscriptionVendor; recommendation: 'native' | 'gateway' | null }>;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 3d9008807..dc8aaed4f 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1142,7 +1142,10 @@"subscriptionPicker": {"vendor": {"anthropic": "Claude subscription",- "openai": "ChatGPT subscription"+ "openai": "ChatGPT subscription",+ "gemini": "Gemini",+ "kimi": "Kimi",+ "xai": "xAI"},"recommendation": {"native": "Native recommended",@@ -1549,6 +1552,9 @@"title": {"anthropic": "Connect Claude subscription","openai": "Connect ChatGPT subscription",+ "gemini": "Connect Gemini subscription",+ "kimi": "Connect Kimi subscription",+ "xai": "Connect xAI subscription","generic": "Connect subscription","reauth": "Sign in to “{{name}}” again"},diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex c5f5008c1..c3840bb3f 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1142,7 +1142,10 @@"subscriptionPicker": {"vendor": {"anthropic": "Claude 订阅",- "openai": "ChatGPT 订阅"+ "openai": "ChatGPT 订阅",+ "gemini": "Gemini",+ "kimi": "Kimi",+ "xai": "xAI"},"recommendation": {"native": "推荐由 Agent 管理",@@ -1549,6 +1552,9 @@"title": {"anthropic": "连接 Claude 订阅","openai": "连接 ChatGPT 订阅",+ "gemini": "连接 Gemini 订阅",+ "kimi": "连接 Kimi 订阅",+ "xai": "连接 xAI 订阅","generic": "连接订阅","reauth": "重新登录「{{name}}」"},diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex 99472fdf4..ce9d1d3c4 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -61,12 +61,65 @@ from vibe.model_hub_runtime.supervisor import ()+# The subscription vendors the engine can start an OAuth flow for, and the three+# names each one answers to on the way through it:+#+# management endpoint where the start request goes+# callback provider the name `POST /oauth-callback` accepts for the session+# the start registered, for the vendors that take one+# auth provider the `provider` the finished grant carries in+# `GET /auth-files`, which is how a flow finds its own+#+# The three can differ for one vendor — Claude starts at `/anthropic-auth-url`,+# answers a callback as `anthropic`, and lands as `claude` — so none of them is+# derivable from the Avibe vendor id, and each row states all three. What the+# flow *asks of the user* is not in here: it is read from the start response,+# which is the only thing that knows whether this vendor issued a device code or+# expects a redirect URL back._OAUTH_ENDPOINTS = {"anthropic": ("/anthropic-auth-url", "anthropic", "claude"),"openai": ("/codex-auth-url", "codex", "codex"),"codex": ("/codex-auth-url", "codex", "codex"),+ "gemini": ("/antigravity-auth-url", "antigravity", "antigravity"),+ "kimi": ("/kimi-auth-url", "kimi", "kimi"),+ "xai": ("/xai-auth-url", "xai", "xai"),+}++# The local surface the pinned engine serves a hub-held subscription on.+#+# A subscription's protocol is not a fact about the vendor's public API — it is a+# fact about how the engine that holds the credential exposes it to us, the same+# kind of shipped product knowledge as `vibe/data/api_key_vendors.json`. It is+# stated for the vendors whose grant no response probe can reach: the credential+# never leaves the engine, and the upstream behind it is the vendor's CLI plane+# rather than an endpoint Avibe may synthesize a request against.+#+# Read from the engine at the commit `cliproxyapi_manifest.json` pins+# (v7.2.149, `2a6b87ac`); each row is one of its serving surfaces, not a guess:+#+# gemini `internal/translator/antigravity/openai/chat-completions/init.go:9`+# registers `translator.Register(OpenAI, Antigravity, ...)`, so an+# OpenAI-chat request is translated to the antigravity upstream at+# `cloudcode-pa.googleapis.com/v1internal:generateContent`.+# kimi `internal/runtime/executor/kimi_executor.go:54` reports+# `FormatOpenAI` from `RequestToFormat`, `:119` translates to+# `openai`, and `:150` calls the upstream's `/v1/chat/completions`.+# xai `internal/runtime/executor/xai_executor_request.go:517` accepts+# `FormatOpenAI` and folds its output controls into the Responses body+# the executor sends to `/responses`+# (`internal/runtime/executor/xai_executor_execute.go:45`).+#+# All three land on `openai_chat`, which is also what the api-key catalog pins+# for the same three vendor ids — one vendor, one protocol, whichever channel+# holds the credential. That agreement is what lets `_validate_source_target`+# admit these Sources without a base URL, so keep the two tables consistent: a+# subscription pinned to a protocol its api-key sibling contradicts would need+# that validator taught about a second pin.+_HUB_SUBSCRIPTION_PROTOCOLS = {+ "gemini": "openai_chat",+ "kimi": "openai_chat",+ "xai": "openai_chat",}-_WEBUI_OAUTH_VENDORS = frozenset(_OAUTH_ENDPOINTS)_INSTALL_RECOVERY_WAIT_SECONDS = 30.0_INSTALL_RECOVERY_INITIAL_DELAY_SECONDS = 0.25_INSTALL_RECOVERY_MAX_DELAY_SECONDS = 4.0@@ -102,6 +155,19 @@ class _ProtocolEvidence:status: int | None = field(default=None, compare=False)+# What a finished hub subscription grant establishes on its own.+#+# The engine accepted the credential — that is what completing the grant means —+# so authentication is `ACCEPTED`. It says nothing about which protocol, because+# no request was made: `_HUB_SUBSCRIPTION_PROTOCOLS` supplies that instead, so+# the proof stays `UNPROVEN` and there is no response shape to record.+_ENGINE_SERVED_SUBSCRIPTION_EVIDENCE = _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ shape=_ProtocolObservationShape.NONE,+)++@dataclass(frozen=True)class _ProtocolEvidenceRule:statuses: frozenset[int]@@ -753,6 +819,17 @@ def _pairwise_positive_exclusion(evidence: _ProtocolEvidence) -> bool:)+def hub_subscription_serving_protocol(vendor: str) -> str | None:+ """The protocol a hub-held subscription for this vendor is served on.++ ``None`` for a vendor whose grant is proven by response instead of pinned,+ which is why callers ask this before deciding to probe rather than after+ failing to.+ """++ return _HUB_SUBSCRIPTION_PROTOCOLS.get(vendor.strip().lower())++def _protocol_is_persistable_without_shape_proof(*,credential_kind: str,@@ -760,6 +837,12 @@ def _protocol_is_persistable_without_shape_proof(protocol: str,protocol_order: Sequence[str],) -> bool:+ if credential_kind == "oauth":+ # A hub subscription's protocol is pinned rather than proven, so there is+ # no response shape to wait for. Nothing else about an OAuth credential+ # is persistable this way: an unpinned vendor returns False here and+ # stays on the probe.+ return hub_subscription_serving_protocol(vendor) == protocolif credential_kind != "api_key":return Falsepinned_protocol = pinned_api_key_protocol(vendor)@@ -799,6 +882,24 @@ def _anthropic_wrapperless_elimination_proof(return None+# The vendors whose finished OAuth grant is bound by *probing* it: the ones with+# a public upstream URL and header set the probe below can synthesize a request+# against, and read the protocol back out of the response.+#+# This is one of the two routes a grant binds by, not the whole admission. The+# other is `_HUB_SUBSCRIPTION_PROTOCOLS`, where the protocol is pinned from the+# engine's serving surface because there is no reachable upstream to ask. Every+# vendor `_OAUTH_ENDPOINTS` can sign in takes exactly one of the two — a flow+# that could start and then not bind would be a dead end — and+# `tests/test_model_hub_runtime.py` asserts that partition rather than listing+# the members, so a vendor added to the start table without a binding route+# fails a test instead of shipping.+#+# That test also pins the probe's actual behaviour against this set, so widening+# one without the other is a failure rather than a silent change.+_OAUTH_OBSERVABLE_VENDORS = frozenset({"anthropic", "openai", "codex"})++def _probe_oauth_protocol_response(*,client: EngineClient,@@ -1572,7 +1673,10 @@ class CLIProxyEngineAdapter:) -> SourceObservation:"""Observe sequentially and stop at the first persistable proof.- ``protocol_order`` orders attempts only. A protocol-specific response+ ``protocol_order`` orders attempts only, with one exception: a hub+ subscription whose serving protocol the engine declares is answered by+ that pin whenever the order contains it, because no other candidate+ could be served. A protocol-specific responsewith accepted authentication proves the current attempt and terminatesobservation. A shipped vendor catalog pin or a concrete `custom`declaration also terminates observation after a shaped success.@@ -1614,6 +1718,16 @@ class CLIProxyEngineAdapter:else:raise EngineStateError("credential does not match observation target")+ if credential_kind == "oauth":+ served_protocol = hub_subscription_serving_protocol(normalized_vendor)+ if served_protocol is not None and served_protocol in protocol_order:+ # A pinned subscription's protocol does not depend on the order it+ # is asked in: the engine serves this auth kind on one surface,+ # and every other candidate would only be attempted to be refused.+ # A caller that asks for an order excluding the pin is left on the+ # ordinary path, where it reaches that refusal for itself.+ protocol_order = (served_protocol,)+failures: list[EngineClientError] = []received_rejection = Falsereceived_proven_unknown = False@@ -1638,6 +1752,14 @@ class CLIProxyEngineAdapter:base_url=base_url,secret=secret or "",)+ elif credential_kind == "oauth" and owner_scoped_protocol:+ # A pinned subscription has no upstream to probe: the engine+ # holds the credential and serves it on the surface+ # `_HUB_SUBSCRIPTION_PROTOCOLS` names. The completed grant is+ # the evidence, so this stands in for a response that was+ # accepted without narrowing the protocol by shape — which is+ # what the pin is there to narrow instead.+ evidence = _ENGINE_SERVED_SUBSCRIPTION_EVIDENCEelse:assert oauth_auth is not Noneevidence = await asyncio.to_thread(@@ -1811,7 +1933,7 @@ class CLIProxyEngineAdapter:normalized_vendor = vendor.strip().lower()endpoint = _OAUTH_ENDPOINTS.get(normalized_vendor)if endpoint is None:- raise EngineStateError("OAuth vendor lacks Model Hub response-backed observation")+ raise EngineStateError("OAuth vendor lacks a Model Hub subscription flow")engine_endpoint, callback_provider, auth_provider = endpointwith self._oauth_lock:self._expire_oauth_flows_locked()@@ -1825,7 +1947,12 @@ class CLIProxyEngineAdapter:client.management_request,"GET",engine_endpoint,- query={"is_webui": "true"} if normalized_vendor in _WEBUI_OAUTH_VENDORS else None,+ # Every start Avibe makes is Web-UI-originated, which is all this+ # flag states. The engine decides what follows from it: a vendor+ # whose grant comes back through a redirect starts a forwarder+ # for it, and one that issues a device code has nothing to+ # forward and ignores the flag.+ query={"is_webui": "true"},)engine_state = str(payload.get("state") or "").strip()if not engine_state: