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): catalog-pin and declared-protocol observation (#1844)
Max883604545cf8
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex fa4a2b36a..c9b2cbdc6 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -491,9 +491,14 @@ class EngineAdapter(Protocol):) -> SourceObservation:"""Observe connectivity, authentication, protocol, and inventory.- ``protocol_order`` only orders probes. A returned protocol must be- proven by a real upstream response; it cannot be inferred from vendor- metadata, Base URL, or the first candidate.+ ``protocol_order`` either enumerates Auto-detect probes or names one+ owner-constrained protocol. A returned protocol may be established by+ a protocol-shaped upstream response, by a shipped API-key vendor pin,+ or by a concrete `custom` declaration. The latter two require a+ response from that exact path plus the September 4, 2026 auth ladder:+ 401/403 reject, while 2xx and request-error 400/404/422 accept even+ if the response shape itself stays generic. `custom` Auto detect still+ requires response-backed proof; order alone never proves a protocol."""...diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 92874bae1..7e019139a 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -42,6 +42,10 @@ from core.services.settings import default_configfrom storage.db import get_cached_sqlite_enginefrom storage.models import agent_sessions, messagesfrom vibe.backend_model_catalog import bundled_catalog_reasoning_efforts_by_model+from vibe.model_hub_runtime.api_key_vendors import (+ catalog_api_key_vendor_label,+ pinned_api_key_protocol,+)from .adapter import (DiscoveredModel,@@ -1266,12 +1270,22 @@ class ModelHubService:)@staticmethod- def _observation_protocols(payload: Mapping[str, Any]) -> tuple[str, ...]:+ def _observation_protocols(+ vendor: str,+ payload: Mapping[str, Any],+ ) -> tuple[str, ...]:+ pinned_protocol = pinned_api_key_protocol(vendor)if "protocol" not in payload:- return SOURCE_PROTOCOLS+ if pinned_protocol is not None:+ return (pinned_protocol,)+ if vendor == "custom":+ return SOURCE_PROTOCOLS+ raise ModelHubError("discovery_failed")requested = payload.get("protocol")if not isinstance(requested, str) or requested not in SOURCE_PROTOCOLS:raise ModelHubError("discovery_failed")+ if pinned_protocol is not None and requested != pinned_protocol:+ raise ModelHubError("discovery_failed")return (requested,)@staticmethod@@ -1373,7 +1387,7 @@ class ModelHubService:credential_ref: str,protocol_order: tuple[str, ...],) -> SourceObservation:- """Require response-backed protocol evidence before Source persistence."""+ """Require a persistable protocol owner before Source persistence."""observation = await self._observe_provisioned_credential(vendor,@@ -1427,7 +1441,7 @@ class ModelHubService:key = payload.get("key")if not isinstance(key, str) or not key.strip():raise ModelHubError("discovery_failed")- protocol_order = self._observation_protocols(payload)+ protocol_order = self._observation_protocols(vendor, payload)transient_ref = await _provision_transient_credential_with_cancellation_ownership(self,vendor,@@ -2652,11 +2666,11 @@ class ModelHubService:raise ModelHubError("discovery_failed")kind = payload.get("kind")vendor = payload.get("vendor")- display_name = payload.get("display_name") or vendortry: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 vendorif kind not in {"subscription", "api_key"}:raise ModelHubError("discovery_failed")if (@@ -2735,7 +2749,7 @@ class ModelHubService:raise ModelHubError("discovery_failed")protocol_order: tuple[str, ...] | None = Noneif kind == "api_key":- protocol_order = self._observation_protocols(payload)+ protocol_order = self._observation_protocols(vendor, payload)if oauth_ref:return self._source_creation_result(diff --git a/docs/plans/model-hub-add-key-confirmation-flow.md b/docs/plans/model-hub-add-key-confirmation-flow.mdnew file mode 100644index 000000000..a67e35c52--- /dev/null+++ b/docs/plans/model-hub-add-key-confirmation-flow.md@@ -0,0 +1,181 @@+# Model Hub — Add-API-key: detect-then-confirm flow++Status: owner-approved 2026-09-03 (this conversation). This file is the design+authority for the change; `docs/plans/model-hub-ui-spec.md` §1.5 is the surface+spec and receives a dated amendment from this plan (see "Spec amendment").++## Background++The Add-API-key dialog currently shows 接口类型 (interface type) as the second+form field, above Base URL and API key — implying the user must know the+interface before connecting. The owner ruled:++1. Move the interface-type control **below the API key field**.+2. It is not an input the user owes the product; it is a **detection result the+ product owes the user**, confirmed before saving: fill Name / Base URL /+ API key → automatic detection → user confirms.+3. The fetched model list is **not displayed** in the dialog (count only,+ exactly as today). Full list maintenance stays on Source details.++## Approved interaction++### Field order++名称(可选) → Base URL → API Key → 接口类型 (result area, last).++### Interface-type area states++| State | Presentation |+| --- | --- |+| Idle (Base URL or key empty) | Dimmed row: value 自动探测, hint "填好 Base URL 和 API Key 后自动识别". Manual-override disclosure available. |+| Ready (inputs filled, no result yet) | Same row, undimmed. Manual-override disclosure available. |+| Detecting | Spinner row "识别接口中…" |+| Identified | Mint strip: `✓ <Protocol> · 拉到 N 个模型` (or `<Protocol> · 已经连接,但这个供应商没有可用模型` for zero). Manual-override disclosure below. |+| Undetermined (state ④) | Existing gold strip + the four-segment selector **expanded in place** (retry stays disabled while Auto remains selected — existing rule). |+| Inventory (state ⑤) | Existing behavior unchanged (advisory strip, 仍要添加 path). |++Manual override is a collapsed disclosure "手动指定接口类型" holding the existing+four-segment selector (Auto + Anthropic Messages / OpenAI Responses / OpenAI+Chat Completions). Selecting a concrete protocol is a **declaration**+(2026-09-04): persistence requires authentication on that path, not a+protocol-shaped response. Auto detect still requires matching response proof.+Changing the selection invalidates any existing result (existing `editProtocol`+behavior); no auto re-probe. See `docs/plans/model-hub-vendor-preset-protocol.md`.++### Two-step primary++- Primary reads **检测 / Detect** while there is no fresh result. Disabled+ unless Base URL + API key are non-empty and the name is valid (same validity+ as today's 添加).+- Detect runs the existing observation probe (`observeApiKeySource`). It is+ non-persisting; cancel while detecting aborts and returns to the form with+ values intact.+- On an identified result the primary becomes **确认添加 / Confirm & add**:+ persists directly with the proved protocol (`persist(seq,+ report.protocol ?? undefined)`). The server repeats its own observation+ inside the create attempt, so no client-side re-probe is needed.+- Editing Base URL, API key, or the protocol selection after a result+ invalidates it (existing edit handlers) and returns the primary to Detect.++### The origin axis is retired++The pull/add origin distinction existed to protect one promise: 拉取型号 was+可选, so "nothing you do here commits anything" had to hold for the whole+pull branch (spec §1.5 "Origin is an axis, not a state"). The optional test+button is removed by this change — Detect is a mandatory step of the single+add flow — so the axis has no remaining work:++- 拉取模型 / Fetch models button and its hint are deleted; Detect absorbs+ their role (and finally surfaces the detected protocol, which today's+ result strip omits).+- Every outcome state may offer its persisting exit under the existing+ protocol-proof equality: ③/④ still refuse to save; ⑤ still offers+ 仍要添加 (its gate becomes "inventory outcome with a proved protocol", no+ longer origin-scoped).+- Cancel semantics: while detecting → abort to form; in an outcome state or+ during persist → existing behavior (dismiss; persist-stage cancel stays+ blocked).++The invariant is: **every persisting exit requires a protocol established on+the 2026-09-04 ladder** (catalog pin, user declaration, or matching response+proof; spec §1.5, E-3/E-5, `docs/plans/model-hub-vendor-preset-protocol.md`).++### Protocol glyphs (added by owner ruling, same conversation)++Every surface in this dialog that names a concrete interface type carries that+protocol family's brand glyph, at a glance (一眼识别):++- **Rule**: the glyph marks the **protocol family** — Anthropic Messages gets+ the Anthropic mark, OpenAI Responses and OpenAI Chat Completions get the+ OpenAI mark. It says "this endpoint speaks the Anthropic/OpenAI interface",+ not "this endpoint is operated by that company"; a relay speaking+ `openai_chat` shows the OpenAI glyph because that is the interface it was+ proved to speak. Auto detect (自动探测) carries no glyph.+- **Surfaces**: the manual-override segment options, the identified result+ strip (glyph before the protocol label), and ④'s expanded selector options.+- **Rendering**: inline-SVG React components in one new module+ (`protocolGlyph.tsx`), monochrome `currentColor`, ~14px, sized with the+ label's ink tokens so Light/Dark both work. No image assets, no new+ dependency; path data from the published simple-icons marks.+- This does not touch `vendorMeta.ts`'s stance that source-row identity is+ semantic, not vendor branding: the glyph belongs to the interface-type+ surface only.++### Unchanged++- Replace-key mode (whole lower branch of the dialog) — untouched.+- Backend contracts: `observe` / `create` routes, `SourceCreate` schema,+ `client_nonce`, `accept_unavailable_inventory` producer (⑤'s 仍要添加+ remains its only producer).+- Failure copy and strips for ③ auth/network/unclassified/engineDown,+ persist_failure, save_unconfirmed reconciliation.+- No model list rendering in the dialog — count only.+- Name-default fill behavior stays exactly as today (out of scope).++## Copy changes (en + zh, same change)++| Key | 中文 | English | Note |+| --- | --- | --- | --- |+| `addKey.subtitle` (new text) | 先检测连接与接口,确认后添加 | Detect the connection and interface first, then confirm to add | replaces old subtitle |+| `addKey.detect` (new) | 检测 | Detect | primary, step 1 |+| `addKey.confirm` (new) | 确认添加 | Confirm & add | primary, step 2 |+| `addKey.protocol.idleHint` (new) | 填好 Base URL 和 API Key 后自动识别 | Identified automatically once Base URL and API key are filled | idle/ready row hint |+| `addKey.protocol.detecting` (new) | 识别接口中… | Identifying the interface… | detecting row |+| `addKey.protocol.manual` (new) | 手动指定接口类型 | Manually specify interface type | disclosure label |+| `addKey.saving` (new) | 保存中… | Saving… | persist stage title |+| `addKey.saving.detail` (new) | 正在保存这个来源 | Saving this source | persist stage detail |+| `addKey.field.protocol.hint` | 不确定时用自动探测;已知类型时只验证所选接口 | unchanged | moves to the disclosure area |+| `addKey.pull.result*` / `pull.empty` | unchanged | unchanged | composed after the protocol label |+| removed | `addKey.test`, `addKey.test.hint`, `addKey.submit` | | delete from both locales |++Identified strip composes in JSX: `{protocolLabel} · {t(pull.result, {count})}`+(or `pull.empty`), so no new pluralization keys are needed.++## Spec amendment++`docs/plans/model-hub-ui-spec.md` §1.5 gets a dated owner-ruling block+(2026-09-03) recording: selector relocation below API key as a result area with+manual disclosure; two-step primary; removal of 拉取型号 and retirement of the+origin axis (with the rationale above); protocol-family glyphs on every+interface-type surface; copy-table rows updated accordingly.+Amend surgically (ruling block + copy table + the superseded element-inventory+rows); do not rewrite the section.++## Test expectations++- `AddApiKeyDialog.test.tsx`: update to the two-step flow; keep/extend contract+ coverage — protocol constraint forwarded to observe; persist payload shape+ unchanged (protocol from the proved report; `accept_unavailable_inventory`+ only from ⑤); result invalidation on every edit; ④ retry gated on concrete+ selection; ⑤ add-anyway reachable from a detect-origin inventory outcome.+- Origin-twin tests that exercised the removed optional button are deleted with+ their button (the axis they protected is gone).+- A small `protocolGlyph` test (render marks, assert currentColor sizing+ classes) if a sibling pattern exists; otherwise vitest render smoke is+ optional — do not invent a new test pattern.+- Focused run: `cd ui && npx vitest run src/components/settings/models/` for+ touched suites; `npm run build` before push; i18n keys present in both+ locales in the same change.++## Out of scope++Backend, `modelsApi.ts`, `types.ts` protocol enum, replace mode, frame-06++surfaces, any design.pen edit.++## Ratified scope extensions (orchestrator, 2026-09-03)++The lane's scope-gap report surfaced that the change breaks callers outside+the original file list. Extensions granted in the same lane/PR:++- `ui/e2e/b-add-api-key.spec.ts`, `ui/e2e/g-guards-copy.spec.ts`,+ `ui/e2e/support/hub.ts` — adapt to the two-step flow (Detect is the+ non-persisting observe; the disclosure must be opened before a manual+ protocol segment is clickable). Preserve scenario intent, don't delete.+- `model-hub-ui-spec.md` amendment widened to include the §0.8 register rows+ this dialog owns: retire origin-twin / 拉取型号 rows, add idle / detecting /+ identified states, keep §0.10's completeness-gate mechanics intact.++Untracked-caller lesson for future specs: deleting a locale key (`addKey.test`,+`addKey.submit`) is an API change to every e2e helper and spec that clicks by+label — sweep `ui/e2e/` before the file list is frozen, not after the lane+reports the break.diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 8acf3c42e..128bfa3fd 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -58,12 +58,14 @@ Contract prose points to those authorities and does not add branches.1. Plaintext upstream credentials never appear in config, API payloads, events, logs,or Agent runtime configuration. Hub-held material is referenced by an opaque enginecredential id; native credentials remain in the sanctioned CLI store.-2. Every persisted Source has a protocol proved by a real upstream response before- commit. `POST /api/models/sources/observe` is the non-persisting API-key observation- surface; API-key `POST /api/models/sources` performs the same observation before- its independent committed credential provisioning, while subscription OAuth uses- its vendor-specific observation flow. Vendor names, Base URLs, and manual hints may- order probes but cannot create a saved protocol value.+2. Every persisted Source has a protocol with a named owner before commit: a shipped+ api-key vendor catalog pin, a user declaration on `custom`, or a matching+ protocol-shaped upstream response. `POST /api/models/sources/observe` is the+ non-persisting API-key observation surface; API-key `POST /api/models/sources`+ performs the same observation before its independent committed credential+ provisioning, while subscription OAuth uses its vendor-specific observation flow.+ A typed Base URL never creates a saved protocol value. Catalog pin and declaration+ still require reachability and authentication; they never bypass those failures.3. Every Source/model reference is canonical and referentially valid at write time.Unchanged stale Route hops may be retained or reordered, but new or changed pairsmust validate.@@ -154,7 +156,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac| `backend-model.schema.json` | Backend Agent model identity, editable capability metadata, and server-owned lock/routeability projection. || `agent-chain.schema.json` | Read projection of exact stored hops plus current execution position, runnability, blockers, live connection backoff, retry metadata, and model supply state. || `probe-result.schema.json` | Saved recovery probes and route probes over exact configured hops, including the live connection-backoff reason without persistent network health. |-| `observation-result.schema.json` | Non-persisting Add-time connectivity, authentication, response-backed protocol, and inventory observation. |+| `observation-result.schema.json` | Non-persisting Add-time connectivity, authentication, protocol-establishment, and inventory observation. || `turn-provenance.schema.json` | Exactly attributed turn attempts and terminal outcome; no policy or mapping discriminator. The one versioned object persisted to disk, so it accepts every released version. || `usage-summary.schema.json` | Metered token usage over a trailing local-day window, aggregated from proxied turns. A report only: no consumer may feed it back into resolution, admission, or cooldown. || `resolution-event.schema.json` | Pull-feed Source/resolution records and their closed reason/detail vocabulary. |diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex fa4a2b36a..c9b2cbdc6 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -491,9 +491,14 @@ class EngineAdapter(Protocol):) -> SourceObservation:"""Observe connectivity, authentication, protocol, and inventory.- ``protocol_order`` only orders probes. A returned protocol must be- proven by a real upstream response; it cannot be inferred from vendor- metadata, Base URL, or the first candidate.+ ``protocol_order`` either enumerates Auto-detect probes or names one+ owner-constrained protocol. A returned protocol may be established by+ a protocol-shaped upstream response, by a shipped API-key vendor pin,+ or by a concrete `custom` declaration. The latter two require a+ response from that exact path plus the September 4, 2026 auth ladder:+ 401/403 reject, while 2xx and request-error 400/404/422 accept even+ if the response shape itself stays generic. `custom` Auto detect still+ requires response-backed proof; order alone never proves a protocol."""...diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex 2f89235c7..88f319ec3 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -25,8 +25,8 @@ compatibility path.| Method and path | Request → response | Normative notes || --- | --- | --- || GET `/api/models/sources` | → `{sources: Source[]}` | Unordered asset inventory. Every Source carries server-derived `adopted_by` and any persisted `client_nonce`; array order is never a spend order. |-| POST `/api/models/sources/observe` | `{vendor, base_url?, key, protocol?}` → `{observation: SourceObservation}` | Non-persisting connectivity/authentication/protocol/inventory observation. Omitted `protocol` auto-detects; a supplied value restricts observation to that one interface and still requires matching response proof. No credential reference is returned. |-| POST `/api/models/sources` | `source-create.schema.json` → `{source: Source, added_to: AddedTo[], adopted_by: AdoptedBy[]}` | The server assigns `id` and `created_at`; plaintext keys are transient. Add-time matching and placement are materialized before response. Optional `accept_unavailable_inventory` is the sole explicit consent for a repeated, protocol-proven observation whose inventory discovery fails. An optional `client_nonce` is reserved only in process before work and persisted only on the committed Source for list-based lost-response reconciliation. |+| POST `/api/models/sources/observe` | `{vendor, base_url?, key, protocol?}` → `{observation: SourceObservation}` | Non-persisting connectivity/authentication/protocol/inventory observation. On `custom`, omitted `protocol` auto-detects and still requires matching response proof. A shipped vendor catalog pin collapses omission to that one protocol. A supplied value restricts observation to one interface and is established when authentication succeeds and either `vendor` has a shipped catalog pin, the client declared the protocol on `custom`, or a matching protocol-shaped response proves it. No credential reference is returned. |+| POST `/api/models/sources` | `source-create.schema.json` → `{source: Source, added_to: AddedTo[], adopted_by: AdoptedBy[]}` | The server assigns `id` and `created_at`; plaintext keys are transient. Add-time matching and placement are materialized before response. Optional `accept_unavailable_inventory` is the sole explicit consent for a repeated observation that established a protocol owner but whose inventory discovery fails. An optional `client_nonce` is reserved only in process before work and persisted only on the committed Source for list-based lost-response reconciliation. || PATCH `/api/models/sources/<id>` | `{display_name?, base_url?, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded Source-mutation envelope | Metadata/Base-URL mutation from the authoritative matrix in `model-hub.md` §4.5. A forced retry confirms only an exact echo of the refusal plan. || PUT `/api/models/sources/<id>/credential` | `{key, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded Source-mutation envelope | API-key replacement. Confirmation fields are JSON body fields. Success is exactly `{source, removed_hops, interrupted}`; the OAuth-only repair tail never appears here. || POST `/api/models/sources/<id>/reauth` | `{acknowledge_irreversible?: true}` → `{flow: OAuthFlow}` | Both Hub OAuth and `native_cli` Sources require the acknowledgement before OAuth starts. Missing or false acknowledgement returns `reauth_confirmation_required` before any adapter call. See repair rules. |@@ -82,9 +82,12 @@ create request:````base_url` may be null for an official vendor endpoint. `protocol`, when present,-restricts observation to exactly that interface; omitting it probes the authoritative-three-value order. The selected value is a constraint, not evidence: the endpoint still-requires a matching protocol-shaped upstream response. The protocol probe is deliberately+restricts observation to exactly that interface; omitting it selects the shipped vendor+pin when one exists, otherwise on `custom` it probes the authoritative three-value+order. Auto-detect on `custom` still requires a matching protocol-shaped upstream+response. A supplied protocol is established when authentication succeeds and either+`vendor` has a shipped catalog pin, the client declared that protocol on `custom`, or+a matching protocol-shaped response proves it. The protocol probe is deliberatelyschema-invalid and names no synthetic model, so a relay can authenticate and classify itwithout selecting or invoking an upstream model. A bare-origin Base URL uses thestandard `/v1` endpoint paths, while a URL with a path is treated as the complete API@@ -94,14 +97,15 @@ settling. A revoke failure remains in the existing pending-revocation journal. Tresponse never contains that reference or any persisted Source.For an API-key `POST /api/models/sources`, the server performs the same-response-backed observation internally before its independent committed credential+server-owned observation internally before its independent committed credentialprovisioning. It accepts the create fields and optional protocol constraint, but neveraccepts protocol proof or inventory results from the caller. A null protocol-produces no Source. A proven protocol with failed inventory discovery produces no Source-unless this request explicitly carries `accept_unavailable_inventory: true`; the accepted-Source has `models: []` and the existing uncertain health projection. Subscription OAuth-creation follows its vendor-specific observation flow before commit. Saved Sources use-the stored protocol for every later operation.+produces no Source. A repeated observation that establishes a protocol owner but ends+with failed inventory discovery produces no Source unless this request explicitly carries+`accept_unavailable_inventory: true`; the accepted Source has `models: []` and the+existing uncertain health projection. Subscription OAuth creation follows its+vendor-specific observation flow before commit. Saved Sources use the stored protocol for+every later operation.`source-create.schema.json` is the complete `SourceCreate` request. Its field table isauthoritative; no Source response field may be inferred backwards into the request:@@ -109,12 +113,12 @@ authoritative; no Source response field may be inferred backwards into the reque| Field | Required | Producer → consumer | Rule || --- | --- | --- | --- || `vendor` | yes | Add Source client → observation adapter | Same normalized vendor id as the unsaved observation request. |-| `display_name` | no | Add Source client → Source metadata | Omission uses the server's canonical vendor label; it never carries credential material. |+| `display_name` | no | Add Source client → Source metadata | Omission uses the server's canonical locale-neutral vendor label; it never carries credential material. || `base_url` | no | Add Source client → observation adapter | null or omission selects the official endpoint; a custom URL is validated before provisioning. || `key` | yes | Add Source client → transient and committed credential provisioning | Plaintext is write-only and never appears in a response, Source record, event, or log. |-| `protocol` | no | Add Source client → observation adapter | One supported interface. It restricts the probe to that type; omission auto-detects. Persistence still requires matching response proof. |+| `protocol` | no | Add Source client → observation adapter | One supported interface. It restricts the probe to that type. Omission auto-detects only on `custom`; a shipped vendor catalog pin collapses omission to the pinned protocol. Persistence requires authentication plus a shipped catalog pin, a `custom` declaration, or matching response proof. || `client_nonce` | no | Add Source client → process-local create reservation and persisted Source read projection | Client-generated before send and atomically reserved in the live process before observation or credential work; only the successful commit persists and echoes it unchanged so an ordinary list read can reconcile a lost response. |-| `accept_unavailable_inventory` | no | Add Source state ⑤ client → Source-create commit gate | Boolean; omission is `false`. It consents only to the server's repeated observation returning a proven protocol with `discovery: failed`; it never supplies or overrides observation evidence. |+| `accept_unavailable_inventory` | no | Add Source state ⑤ client → Source-create commit gate | Boolean; omission is `false`. It consents only to the server's repeated observation returning an established protocol owner with `discovery: failed`; it never supplies or overrides observation evidence. |The request has no `id`, `created_at`, `state`, `usage`, protocol evidence, discovered-model,credential-ref, billing, or supply-channel field. The server assigns or observes all of@@ -130,10 +134,10 @@ create precondition:| Repeated server observation | `accept_unavailable_inventory` | Server result || --- | --- | --- |-| Protocol proved; `discovery: succeeded` | omitted, `false`, or `true` | Ordinary create from the newly observed inventory; a legitimately empty result may commit as `models: []`. |-| Protocol proved; `discovery: failed` | omitted or `false` | Existing classified `discovery_failed`; no Source or committed credential is written, and AC-26 cleanup settles before return. |-| Protocol proved; `discovery: failed` | `true` | Commit exactly one Source with the proved protocol, `models: []`, and the existing uncertain health projection; matching has no inventory candidates. |-| Protocol not proved, or an earlier reachability/authentication failure | omitted, `false`, or `true` | Existing classified failure; no Source is committed. The flag cannot authorize this result. |+| Protocol established; `discovery: succeeded` | omitted, `false`, or `true` | Ordinary create from the newly observed inventory; a legitimately empty result may commit as `models: []`. |+| Protocol established; `discovery: failed` | omitted or `false` | Existing classified `discovery_failed`; no Source or committed credential is written, and AC-26 cleanup settles before return. |+| Protocol established; `discovery: failed` | `true` | Commit exactly one Source with the established protocol, `models: []`, and the existing uncertain health projection; matching has no inventory candidates. |+| Protocol not established, or an earlier reachability/authentication failure | omitted, `false`, or `true` | Existing classified failure; no Source is committed. The flag cannot authorize this result. |When `client_nonce` is present, the server atomically reserves it in the live processbefore observation, transient-ref creation, or committed credential provisioning. The@@ -177,8 +181,9 @@ the commit point.The observation result has six terminal outcomes: `observed`, `ambiguous`,`unreachable`, `authentication_failed`, `adapter_error`, and `timeout`. Its-`protocol` is non-null only when a real upstream response shape and positive-authentication evidence prove the transport. Authentication is accepted only by a+`protocol` is non-null only when authentication succeeds and one rung establishes the+transport contract for the attempted path: a shipped vendor catalog pin, an explicit+`custom` declaration, or a matching upstream response shape. Authentication is accepted only by ashaped success or a shaped request-level error that occurs after authentication;shaped authentication errors are rejected. Shaped server and rate-limit errorsprove reachability but not authentication, so they settle as `adapter_error` withdiff --git a/docs/plans/model-hub-contracts/source-create.schema.json b/docs/plans/model-hub-contracts/source-create.schema.jsonindex ffde90d1a..474866bf1 100644--- a/docs/plans/model-hub-contracts/source-create.schema.json+++ b/docs/plans/model-hub-contracts/source-create.schema.json@@ -2,7 +2,7 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/source-create.schema.json","title": "SourceCreate",- "description": "API-key Source creation input. It extends the unsaved observation request with display, reconciliation, and explicit unavailable-inventory consent data; the server still owns Source identity, response proof, discovered inventory, health, usage, custody metadata, and timestamps. Optional protocol restricts observation to one user-selected interface; omission auto-detects across the supported interfaces. Neither branch persists a protocol without matching upstream response proof. When client_nonce is present, the server reserves it atomically in process before observation or credential work; only a successful commit persists Source.client_nonce unchanged. A lost-response client reconciles through the ordinary Source list without a receipt or separate endpoint. Nonce uniqueness covers live-process reservations and live Sources; process restart or Source deletion releases it, and a later same-nonce request after the required list read is a fresh create.",+ "description": "API-key Source creation input. It extends the unsaved observation request with display, reconciliation, and explicit unavailable-inventory consent data; the server still owns Source identity, protocol, discovered inventory, health, usage, custody metadata, and timestamps. Optional protocol restricts observation to one interface; omission selects the shipped vendor pin when one exists, otherwise only custom omission auto-detects across the supported interfaces. A supplied protocol is persisted when observation is authenticated and either vendor has a shipped catalog pin for that protocol, the client declared it on custom, or a matching protocol-shaped upstream response proves it. Auto-detect without a catalog pin still requires matching response proof. When client_nonce is present, the server reserves it atomically in process before observation or credential work; only a successful commit persists Source.client_nonce unchanged. A lost-response client reconciles through the ordinary Source list without a receipt or separate endpoint. Nonce uniqueness covers live-process reservations and live Sources; process restart or Source deletion releases it, and a later same-nonce request after the required list read is a fresh create.","type": "object","required": ["vendor", "key"],"additionalProperties": false,@@ -15,7 +15,7 @@"display_name": {"type": "string","maxLength": 64,- "description": "Optional user-facing name. Omission uses the server's canonical vendor label."+ "description": "Optional user-facing name. Omission uses the server's canonical locale-neutral vendor label."},"base_url": {"type": ["string", "null"],@@ -29,7 +29,7 @@},"protocol": {"enum": ["anthropic", "openai_responses", "openai_chat"],- "description": "Optional user-selected interface. When present, observation probes exactly this protocol and persists it only after matching response proof. Omission auto-detects across the authoritative protocol vocabulary."+ "description": "Optional user-selected interface. When present, observation probes exactly this protocol. Omission selects the shipped vendor pin when one exists; otherwise on vendor custom it auto-detects across the authoritative protocol vocabulary and still requires matching response proof. Persistence requires authentication plus one of: a shipped vendor catalog pin for this protocol, a declaration on vendor custom, or matching protocol-shaped upstream response proof."},"client_nonce": {"type": "string",@@ -39,7 +39,7 @@"accept_unavailable_inventory": {"type": "boolean","default": false,- "description": "Optional explicit consent to commit only when the server's repeated response-backed observation proves a protocol but inventory discovery fails. Omission or false rejects that cell with discovery_failed; true permits a Source with models: []. The flag never supplies observation evidence, has no effect on a successful discovery, and cannot bypass reachability, authentication, or protocol proof."+ "description": "Optional explicit consent to commit only when the server's repeated observation establishes a protocol owner but inventory discovery fails. Omission or false rejects that cell with discovery_failed; true permits a Source with models: []. The flag never supplies observation evidence, has no effect on a successful discovery, and cannot bypass reachability, authentication, or protocol establishment."}},"examples": [diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.mdindex a6b1f7ede..282de1b8d 100644--- a/docs/plans/model-hub-ui-spec.md+++ b/docs/plans/model-hub-ui-spec.md@@ -269,7 +269,7 @@ half named in its Missing cell has an owner.| G-15 | 06 source detail, a source's own name and Base URL — **registered by frame 11** | ~~any affordance that edits them~~ nothing | §1.10 registers the overflow action, edit dialog and guarded `PATCH /api/models/sources/<id>` producer drawn in frame 11. Kept as a registered row so the former absence and its closing frame remain auditable || G-16 | 01 upstream card and 06 source detail — **registered by frame 11** | ~~any affordance that removes a source~~ nothing | §1.10 registers the overflow action and the source-removal guard dialog drawn in frame 11 for `DELETE /api/models/sources/<id>`. The existing 06 model-row 移除 remains a different operation. Kept as a registered row so the former ambiguity and its closing frame remain auditable || G-17 | 04 add-subscription, a flow that expects something pasted back — **registered by the 04 paste-back exhibit** | ~~the field that takes it, and the control that sends it~~ nothing | §1.4 registers `nOgMQ`'s paste-back dialog and its `POST /api/models/oauth/submit` producer. The drawn `paste_code` variant supplies the frame geometry; `presentation.expects` selects the registered code or callback-URL copy without changing that geometry. Kept as a registered row so the former absence and its closing exhibit remain auditable |-| G-18 | 05 add-by-key, 拉取型号 and the observation 添加 runs before it saves — **registered against Source observation** | ~~the route that carries a non-persisting observation of a source that does not exist yet~~ nothing | `POST /api/models/sources/observe` accepts `{vendor, base_url?, key, protocol?}` and returns `SourceObservation` without persisting a Source or returning a credential reference. Omission auto-detects; a value restricts observation to one interface and still requires matching response proof. §1.5 consumes its closed outcome/reachability/authentication/protocol/discovery/models facts. |+| G-18 | 05 add-by-key, 拉取型号 and the observation 添加 runs before it saves — **registered against Source observation** | ~~the route that carries a non-persisting observation of a source that does not exist yet~~ nothing | `POST /api/models/sources/observe` accepts `{vendor, base_url?, key, protocol?}` and returns `SourceObservation` without persisting a Source or returning a credential reference. Omission selects the shipped vendor pin when one exists; otherwise only `custom` omission auto-detects and still requires matching response proof. A supplied value restricts observation to one interface and is established when authentication succeeds and either `vendor` has a shipped catalog pin, the client declared that protocol on `custom`, or a matching protocol-shaped response proves it. §1.5 consumes its closed outcome/reachability/authentication/protocol/discovery/models facts. || G-19 | 05 add-by-key, 取消 pressed while a persisting add is in flight — **registered against the Source-create commit boundary** | ~~what the server is left holding when the cancel lands after the transient phase~~ nothing | Before durable Source commit, AC-26 cleanup completes before cancellation settles. After commit, cancellation ends only the caller's wait: the Source and placements remain committed and the next Source/Agent read owns the outcome. §1.5 registers that boundary instead of promising a post-commit abort. || G-20 | 01 source card and 06 status bar on every Source read — **registered against `Source.adopted_by`** | ~~a *read* that carries `adopted_by`~~ nothing | Every Source returned by `GET /api/models/sources` now carries server-derived, complete, unique `adopted_by` for Hub-mode backends, sorted by backend then menu model. Creation responses echo the same projection at top level. §1.0 owns the grouping/de-duplication rendering and never derives it from chains. || G-21 | 01 upstream card, 添加订阅 → 04 — **registered by frame 13** | ~~the step that picks which vendor the subscription is for~~ nothing | §1.12 registers the vendor menu drawn in frame 13. Claude 订阅 passes `anthropic` and ChatGPT 订阅 passes `openai` into §1.4 before that dialog renders its vendor-specific title, options and `POST /api/models/oauth/start` request. Kept as a registered row so the producer/consumer break and its closing frame remain auditable |@@ -278,7 +278,7 @@ half named in its Missing cell has an owner.| G-24 | 01 run pill, *Unsupported host* — **registered against RuntimeDependency** | ~~a host-platform or installability discriminator in the runtime payload~~ nothing | Every runtime response now carries server-authoritative `host_platform`; an exact match in `manifest.assets[].platform` is the support predicate. §1.0 never substitutes the browser platform. || G-25 | 01 gateway group, the unavailable marker — **registered against AgentSupply model supply; collapse ownership retired 2026-08-23** | ~~a per-model fact that separates a chain with a live hop from one whose hops are all stale~~ nothing | `model_supply[].has_runnable_hop` now carries that server-derived fact under the same runnability axiom as AgentChain. §1.1 uses it only to choose the row marker: a nonempty chain with no runnable hop renders `legend.unavailable`; the forced-false `chain_length: 0` subset branches first to the existing `models.launch.route_unconfigured` treatment instead of borrowing paused-supply copy. The six-row prefix owns collapse independently of this field. || G-26 | 03 order drawer, a reorder — **registered against the same explicit reorder contract as G-13** | ~~a policy value that reads the stored Source order~~ nothing | `POST /api/models/agents/<backend>/chains/reorder` stores the supplied Source-order sequence and applies a stable total sort over every stored Route in the same mutation. A source outside the order remains a later Route hop when it is already configured there. |-| G-27 | 05 add-by-key, the persisting `POST /api/models/sources` — **registered against `source-create.schema.json`** | ~~the request shape that route accepts~~ nothing | The schema is the complete request: required `vendor` and write-only `key`; optional `display_name`, `base_url`, `protocol`, `client_nonce` and `accept_unavailable_inventory` `[contract]`. The client-selected protocol is a one-interface probe constraint, never response proof or discovered inventory. §1.5 sends the consent boolean true only from ⑤, where a repeated observation still has to prove the protocol before a failed inventory may commit. |+| G-27 | 05 add-by-key, the persisting `POST /api/models/sources` — **registered against `source-create.schema.json`** | ~~the request shape that route accepts~~ nothing | The schema is the complete request: required `vendor` and write-only `key`; optional `display_name`, `base_url`, `protocol`, `client_nonce` and `accept_unavailable_inventory` `[contract]`. On `custom` with Auto, `protocol` is omitted and the server still requires matching response proof. A supplied protocol is persisted when observation is authenticated and either the vendor catalog pins it, the client declared it on `custom`, or a matching response proves it. §1.5 sends the consent boolean true only from ⑤, where a repeated observation still has to establish the protocol before a failed inventory may commit. || G-28 | `Qp6FI` guarded-change hop rows — **registered against `RouteHopRef.position`** | ~~the hop's position, on the reference the refusal returns~~ nothing | `guard-refusal.schema.json` carries one-based pre-mutation `position` on every `RouteHopRef`. §1.6 and §1.10 render it directly and issue no per-chain lookup. || G-29 | 05 add-by-key, ⑦'s lost-response reconciliation — **registered against Source-create nonce totality** | ~~anything the client holds *before* the send that the committed Source can afterwards be recognized by~~ nothing | The client generates `SourceCreate.client_nonce` before send. A list read finds exact `Source.client_nonce` after commit; in-flight and committed retries return distinct `409` conflicts, released/list-miss retries are fresh. A committed retry never replays an old response; it returns `source_nonce_conflict` and the client rereads the list to claim the Source. || G-30 | 04 add-subscription, *Start failed* entered by a lost response — **registered against OAuth start nonce totality** | ~~a way to reach a flow whose `flow_id` never arrived~~ nothing | The client generates `client_nonce` before start; the server claims the exact `(client_nonce, vendor, channel)` tuple before provider work. Concurrent retry coalesces to one pending start/result, every resulting flow echoes the nonce, and nonce-bearing cancellation remains bounded by its non-null `expires_at`. §1.4 retries the held tuple without opening a second provider start. |@@ -398,7 +398,7 @@ silently retargets.for a saved-protocol edit route and remains closed by subtraction: changing protocolstill requires a new Source. G-4 asked for a badge conditioned on manual provenance;that marker still does not exist. The new ruling adds an unconditional source identity-label (`provider or host · proved protocol`) and a form-level Auto/manual selector.+label (`provider or host · established protocol`) and a form-level Auto/manual selector.Neither resurrects the retired edit route or invents provenance.### 0.6 Conflicts raised by this pass — all five now ruled@@ -446,9 +446,9 @@ next one should go: the escalation was worth its cost precisely because the answedited and Source still carries no manual/automatic provenance. What changed is thepreflight and read presentation: frame 05 exposes Auto/manual protocol selection beforethe first request, while every Source card and detail header show the endpoint identity-and proved protocol unconditionally. The label never claims who selected it and has no+and established protocol unconditionally. The label never claims who selected it and has noedit action. This separates three facts that the older ruling conflated: choosing a-candidate, proving a protocol, and displaying the proved protocol.+candidate, establishing a protocol owner, and displaying the established protocol.**E-3 is closed, and the design moved again.** It read: *can a source be saved withouta verifying upstream response?* The frames drew 05 state ③ with a 仍要添加 escape, on@@ -493,20 +493,20 @@ produce. The taxonomy and the payload agree once the words are separated, whichusual sign that the split was the real fix and the copy ban was the symptom.**E-5 is closed by drawing the missing state.** It read: *05 has no state for 「protocol-proved, inventory unavailable」.* It was the only one of the five where the contract asked-for **more** surface than the frames drew. AC-27 says 「『Add anyway』 is available only-after the protocol was proved and a different result, such as model inventory, remains-unavailable; that uncertainty is a health fact.」 The rebuilt frame 05 drew neither that-nor E-3's version, because the rebuild removed 仍要添加 from every failure state — its two-failure states were authentication failure (③) and unrecognized interface (④), and both are-protocol-*not*-proved.+established, inventory unavailable」.* It was the only one of the five where the contract+asked for **more** surface than the frames drew. AC-27 now says 「『Add anyway』 is+available only after the protocol was established and a different result, such as model+inventory, remains unavailable; that uncertainty is a health fact.」 The rebuilt frame 05+drew neither that nor E-3's version, because the rebuild removed 仍要添加 from every+failure state — its two failure states were authentication failure (③) and unrecognized+interface (④), and both still lack an established protocol owner.The owner ruled that the two 仍要添加 are different affordances wearing one word, and thatthis one is legitimate. Frame 05 now draws **state ⑤** (`d6bFlX`): the interface wasrecognised, the second fetch came back without an inventory, and the foot offers取消 / 仍要添加 / 重试. §1.5 specifies it and §2's D-27 states the property it protects:-> 已保存的来源恒有一个被观测证明过的协议;凡拿不到证明的路径,产物都是「没有添加成功」。+> 已保存的来源恒有一个已建立且有归属的协议;凡拿不到这个归属的路径,产物都是「没有添加成功」。That single sentence is what separates the two 仍要添加 and is why E-3 stays closed whileE-5 opens a button with the same label. E-3's 仍要添加 would have persisted a source whose@@ -863,14 +863,14 @@ state exit; held intent never bypasses the evidence column.| §1.4 | Engine unavailable | The gateway is not running and gateway-upstream was chosen | F1 | `addSub.error.engineDown`, `addSub.retry` | 重试 re-sends, and that press **is** the recovery observation — nothing here watches for one — so its answer decides: whichever of *Awaiting sign-in* / *Already bound* / *Start failed* the start call then names, or still down → back here; 取消 → dismiss, nothing bound `[derived]` || §1.4 | Already bound | 去登录 was refused by the start call because that backend already holds its one `native_cli` Source — 「the API rejects duplicate creation with the existing Source id」 `[spec §4.1]`. **This is the race the dialog cannot see**: it disables the native row from the sources it read on open, and the singleton can appear after that | F1, in place — nothing was sent to the provider, so there is no flow to cancel | `addSub.error.alreadyBound`, `addSub.retry` | 重试 → Second pass: the dialog re-reads the sources, the native row is now the inert one, and the hub row is what 去登录 sends; 取消 → dismiss, nothing bound `[derived]` || §1.4 | Start failed | `POST /api/models/oauth/start` did not put a flow in this dialog's hands, for any reason that is not the singleton refusal above — a refusal, or no answer at all. The exact generated `(client_nonce, vendor, channel)` tuple remains held `[contract]` | F1, in place — there is no `flow_id` to poll or cancel, so D-36 reconciliation repeats only the held tuple. The server coalesces an in-flight claim, returns its one committed flow, or releases the tuple for one fresh provider start | `addSub.error.startFailed`, `addSub.retry` | 重试 sends the same tuple and classifies the answer as Default does: accepted/coalesced flow → RR-1/RR-2, singleton refusal → Already bound, still no flow → back here. It never opens a second provider start beside the first. 取消 dismisses; a claim released before flow creation has no Source binding `[derived]` |-| §1.5 | ① Default | Dialog opened; Base URL or API key empty | F5 | `addKey.title`, `addKey.subtitle`, `addKey.field.name`, `addKey.field.baseUrl`, `addKey.field.baseUrl.hint`, `addKey.field.apiKey`, `addKey.field.apiKey.reveal`, `addKey.field.apiKey.conceal`, `addKey.field.protocol`, `addKey.protocol.auto`, `addKey.protocol.idleHint`, `addKey.protocol.manual`, `addKey.detect`, `addKey.cancel` | Interface type is a dimmed result area, not a required input. The collapsed disclosure `addKey.protocol.manual` holds Auto plus the three concrete interfaces as a probe constraint, never proof. Auto carries no glyph; a concrete option carries its protocol-family glyph. The collapsed row names whatever 检测 will send: Auto plus `addKey.protocol.idleHint`, or the chosen interface with its glyph and no hint, since only Auto identifies automatically. Expanding the disclosure replaces that row with the selector, which states the same selection as its pressed segment. 检测 is disabled. 取消 → dismiss |-| §1.5 | ① Ready `[derived]` | Base URL and API key filled; no fresh observation | F5 | ①'s keys, undimmed | 检测 → ②. A concrete disclosure selection constrains that observe. 取消 → dismiss |-| §1.5 | ①″ Identified `[derived]` | ② came back `observed`, protocol non-null, `discovery: succeeded` | F5 — the request already succeeded | `addKey.pull.result`, `addKey.pull.empty`, `addKey.protocol.anthropicMessages`, `addKey.protocol.openaiResponses`, `addKey.protocol.openaiChatCompletions`, `addKey.confirm`, `addKey.protocol.manual`, and ①'s still-visible form | Mint strip: protocol-family glyph + proved protocol label + count (or `addKey.pull.empty`). No model names. Editing Base URL, API key, or the protocol selection → ① Ready, the report dropped — §1.5's retirement property, of which this is the plainest case. A rename is not one of those three inputs and keeps the report. 确认添加 → ②″ with the proved protocol and `accept_unavailable_inventory` false / omitted `[contract]`. 取消 → dismiss |+| §1.5 | ① Default | Dialog opened; Base URL or API key empty | F5 | `addKey.title`, `addKey.subtitle`, `addKey.field.vendor`, `addKey.field.vendor.custom`, `addKey.field.vendor.hint`, `addKey.field.name`, `addKey.field.baseUrl`, `addKey.field.baseUrl.hint`, `addKey.field.apiKey`, `addKey.field.apiKey.reveal`, `addKey.field.apiKey.conceal`, `addKey.field.protocol`, `addKey.protocol.auto`, `addKey.protocol.idleHint`, `addKey.protocol.manual`, `addKey.protocol.catalogPinned`, `addKey.detect`, `addKey.cancel` | 服务商 is the first field (自定义 · 兼容端点 by default). A catalog vendor prefills Base URL, locks 接口类型 to the catalog protocol with badge 「内置目录」, and hides the manual disclosure. On 自定义, interface type is a dimmed result area; the collapsed disclosure `addKey.protocol.manual` holds Auto plus the three concrete interfaces as a **declaration**, not a probe constraint. Auto carries no glyph; a concrete option carries its protocol-family glyph. 检测 is disabled until Base URL and API key are filled. 取消 → dismiss |+| §1.5 | ① Ready `[derived]` | Base URL and API key filled; no fresh observation | F5 | ①'s keys, undimmed | 检测 → ②. A catalog vendor sends its pin; a concrete disclosure selection is a declaration on `custom`; Auto auto-detects. 取消 → dismiss |+| §1.5 | ①″ Identified `[derived]` | ② came back `observed`, protocol non-null, `discovery: succeeded` | F5 — the request already succeeded | `addKey.pull.result`, `addKey.pull.empty`, `addKey.protocol.anthropicMessages`, `addKey.protocol.openaiResponses`, `addKey.protocol.openaiChatCompletions`, `addKey.confirm`, `addKey.protocol.manual`, and ①'s still-visible form | Mint strip: protocol-family glyph + established protocol label + count (or `addKey.pull.empty`). No model names. Editing Base URL, API key, or the protocol selection → ① Ready, the report dropped — §1.5's retirement property, of which this is the plainest case. A rename is not one of those three inputs and keeps the report. 确认添加 → ②″ with the established protocol and `accept_unavailable_inventory` false / omitted `[contract]`. 取消 → dismiss || §1.5 | ② Detecting | 检测 pressed, or 重试 pressed from ③ / ④ / ⑤ / ⑥ — `POST /api/models/sources/observe` `[contract]` | → ③ / ④ / ⑤ / ⑥ through O1 | `addKey.protocol.detecting` | O1 classifies the explicit observation. Ready → ①″, persisting nothing. 取消 aborts the in-flight probe and returns to ① Ready with the form intact. A second detect cannot start while one is in flight || §1.5 | ②″ Saving `[derived]` | 确认添加 pressed from ①″, or 仍要添加 pressed from ⑤ — `POST /api/models/sources` with one generated `client_nonce` `[contract]` | → ③ / ④ / ⑤ / ⑦ through O1 | `addKey.saving`, `addKey.saving.detail` | Cancel is blocked. An accepted create closes into 06. A classified create refusal returns to ③ / ④ / ⑤ exactly as the same observation would; only transport/no answer or a create response with no terminal observation classifier → ⑦ || §1.5 | ③ Failure | O1 received one of four closed unsuccessful outcomes from the explicit 检测 observation or Source create's repeated observation: `authentication_failed`, `unreachable`, `timeout` or `adapter_error` `[contract]` | F1 | `addKey.fail.subtitle`; exactly one outcome line: `authentication_failed` → `addKey.fail.auth` + `addKey.fail.auth.detail`, `unreachable` → `addKey.fail.address`, `timeout` → `addKey.fail.network`, `adapter_error` → `addKey.fail.unclassified`; `addKey.retry` | 重试 → ②, whichever producer returned the line — the retry re-runs the explicit observation before any create and does not depend on what the last one concluded. 取消 → dismiss |-| §1.5 | ④ Interface undetermined | O1 received `SourceObservation.outcome: ambiguous` from the explicit 检测 observation or Source create's repeated observation: reachable, protocol null, and authentication authenticated or unknown `[contract]` | F1 | ①'s still-visible form plus `addKey.undetermined.title`, `addKey.undetermined.detail`, the four-segment selector expanded in place (concrete options carry protocol-family glyphs), `addKey.field.protocol.hint`, and `addKey.retry` | Choose one concrete interface + 重试 → ② against exactly that protocol; identified with discovery succeeded → ①″, persisting nothing; identified with discovery failed → ⑤; still ambiguous → back to ④. Retry stays disabled while Auto remains selected. 取消 → dismiss |-| §1.5 | ⑤ Identified, inventory unavailable `[frame]` `d6bFlX` | O1 received `SourceObservation.outcome: observed`, protocol non-null, and `discovery: failed` from the explicit 检测 observation or Source create's repeated observation; the contract carries no request/status/reason evidence `[contract]` | F1 | `addKey.inventory.title`, `addKey.inventory.detail`, `addKey.retry`, `addKey.addAnyway` | 重试 → ② (the entire explicit observation). 仍要添加 is offered whenever this inventory cell carries a proved protocol — it is not origin-scoped. 仍要添加 → ②″ with **`accept_unavailable_inventory: true`** `[contract]`; false / omitted remains the clean path and may not commit this repeated discovery-failed observation. The server still repeats response-backed observation: only the same protocol-proved / discovery-failed cell may commit with `models: []`; every other classified result remains O1's own and the flag supplies no evidence. Only that committed success envelope closes into 06. This state renders no form, so it offers no edit to retire its waived cell; §1.5's retirement property binds it regardless and needs no exception. 取消 → dismiss |+| §1.5 | ④ Interface undetermined | O1 received `SourceObservation.outcome: ambiguous` from the explicit 检测 observation or Source create's repeated observation: reachable, protocol null, and authentication authenticated or unknown `[contract]` — Auto detect on `custom` with no shape proof | F1 | ①'s still-visible form plus `addKey.undetermined.title`, `addKey.undetermined.detail`, the four-segment selector expanded in place (concrete options carry protocol-family glyphs), `addKey.field.protocol.hint`, and `addKey.retry` | Choose one concrete interface + 重试 → ② as a **declaration**: authenticated on that path → ①″ (discovery succeeded) or ⑤ (discovery failed), persisting nothing yet; Auto still selected → 重试 stays disabled; still ambiguous only if Auto is retried. 取消 → dismiss |+| §1.5 | ⑤ Identified, inventory unavailable `[frame]` `d6bFlX` | O1 received `SourceObservation.outcome: observed`, protocol non-null, and `discovery: failed` from the explicit 检测 observation or Source create's repeated observation; the contract carries no request/status/reason evidence `[contract]` | F1 | `addKey.inventory.title`, `addKey.inventory.detail`, `addKey.retry`, `addKey.addAnyway` | 重试 → ② (the entire explicit observation). 仍要添加 is offered whenever this inventory cell carries an established protocol owner — it is not origin-scoped. 仍要添加 → ②″ with **`accept_unavailable_inventory: true`** `[contract]`; false / omitted remains the clean path and may not commit this repeated discovery-failed observation. The server still repeats response-backed observation: only the same protocol-established / discovery-failed cell may commit with `models: []`; every other classified result remains O1's own and the flag supplies no evidence. Only that committed success envelope closes into 06. This state renders no form, so it offers no edit to retire its waived cell; §1.5's retirement property binds it regardless and needs no exception. 取消 → dismiss || §1.5 | ⑥ Engine unavailable `[derived]` | The gateway is not running when 检测 is pressed | F1 | `addKey.fail.engineDown`, `addKey.retry` | F1 in full: the form keeps every value it holds and the primary becomes 重试. Pressing it **is** the recovery observation — nothing here watches for one — and re-attempts 检测 → ②, whose own outcomes then apply; the engine still down → back here; 取消 → dismiss || §1.5 | ⑦ Save unconfirmed `[derived]` | The observation 确认添加 / 仍要添加 owed has already come back with consent — clean in ①″, identified after a hint in ④, or waived in ⑤ — and the complete `SourceCreate` then returned no terminal observation classifier or never answered. Every classified pre-commit observation instead leaves through O1 to ③ / ④ / ⑤. The generated `client_nonce` and every request field remain held `[contract]` | F1 | `addKey.fail.save`; after `source_create_in_progress`, `addKey.fail.inProgress`; `addKey.retry` | Each user press of 重试 first reads `GET /api/models/sources` for the exact nonce. Match → claim the committed Source and enter 06 through the ordinary projection read. Miss → resend the same request/nonce. A response-backed observation enters O1; nonce conflicts follow the exact branches here. `source_create_in_progress` returns to this actionable state with `addKey.fail.inProgress`; there is no timer, automatic list read or automatic mutation retry. A later user press alone repeats the list-read + same-nonce resend algorithm. `source_nonce_conflict` rereads the list and claims the committed Source; a classified pre-commit observation → ③ / ④ / ⑤; a released slot starts one fresh create. Committed never replays the original response, and no branch matches by URL/name or creates a second Source (D-36). 重试 resends the held request rather than the form, so F1 here keeps the form's values while locking every field: the request may not outlive the fields it was built from, and this state resolves that by making them uneditable rather than by retiring on an edit that cannot happen. §1.5's retirement property still binds it. 取消 dismisses; after a committed boundary it ends only the caller's wait and the next Source/Agent read owns the result || §1.6 | Ready | Source detail loaded and the table holds at least one model — discovered, added by hand, or both. When `last_discovered_at` is null the inventory has no age, `{{time}}` is absent by §0.9's rule, and the status line drops that segment `[contract]` | F5 | `sourceDetail.status.inUse`, `sourceDetail.status.listUpdated`, `sourceDetail.summary` | `iGcAi` → 01; a rendered 重新拉取 → Refetching; 添加模型 → Manual draft; a tier area → Tiers editing; a row's overflow → Removing a manual entry. The §1.6 action-capability row decides whether 重新拉取 exists |@@ -3314,25 +3314,49 @@ the interface is undetermined, ⑤ identified but the inventory did not come bacright column is ordered by how far the attempt got before it stopped, which is also theorder in which the product stops refusing: ③ and ④ cannot save at all, ⑤ can.+**2026-09-04 owner ruling — vendor preset + declared protocol** `[derived]`.+This dated block sits on top of detect-then-confirm. Authority:+`docs/plans/model-hub-vendor-preset-protocol.md`. V4 06r already drew the+vendor dropdown; 模型网关 05 is the current-implementation frame and now+carries that field. Do not invent a new dialog.++- Field order is **服务商** → 名称(可选) → Base URL → API Key → 接口类型.+ 服务商 is a select: 自定义 · 兼容端点, then the first-wave catalog+ (`deepseek`, `qwen`, `kimi`, `zhipuai`, `openai`, `anthropic`,+ `openrouter`, `groq`, `mistral`, `xai`, `together`, `fireworks`).+- A catalog vendor pins `vendor`, prefills the official Base URL (still+ editable), and **locks** 接口类型 to the catalog protocol with badge+ 「内置目录」. The manual disclosure is hidden. 检测 authenticates and+ fetches models; it does not have to prove the interface by shape.+- 自定义 keeps detect-then-confirm. Auto detect still requires matching+ response proof. A concrete disclosure choice is a **declaration**:+ authentication on that path is enough to persist. ④ copy says so.+ Retry stays disabled while Auto is selected.+- Identified mint strip carries 「内置目录」 on a catalog pin and+ 「手动指定」 on a declaration. Auto detect has no badge.+- Changing 服务商 resets URL, protocol lock, and any observation.+ Editing Base URL on a preset does not drop the pin.+**2026-09-03 owner ruling — detect-then-confirm** `[derived]`. This dated blocksupersedes the origin-axis / 拉取型号 / one-shot 添加 material later in this section.The dialog is now a single add flow:-- Field order is 名称(可选) → Base URL → API Key → 接口类型. Interface type is a- **detection-result area**, not a required input. Idle is a dimmed row naming+- After 服务商, field order is 名称(可选) → Base URL → API Key → 接口类型. Interface type is a+ **detection-result area**, not a required input, except when a catalog+ vendor has locked it. Idle is a dimmed row namingwhatever 检测 is about to send — 自动探测 with `addKey.protocol.idleHint`, or thechosen interface with its glyph and no hint, because only Auto identifiesautomatically; Ready is the same row undimmed; Detecting is a spinner with- `addKey.protocol.detecting`; Identified is a mint strip naming the proved protocol+ `addKey.protocol.detecting`; Identified is a mint strip naming the established protocol(protocol-family glyph before the label) and the model count — never the modelnames.- Primary is two-step: **检测 / Detect** runs the non-persisting observe; **确认添加 /- Confirm & add** persists with the proved protocol. There is no optional 拉取型号+ Confirm & add** persists with the established protocol. There is no optional 拉取型号button, so the pull/add origin axis has no remaining work and its primed twins are- retired. ⑤'s 仍要添加 stays, gated on an inventory outcome with a proved protocol+ retired. ⑤'s 仍要添加 stays, gated on an inventory outcome with an established protocolrather than on origin.-- Manual override is a collapsed disclosure `addKey.protocol.manual`. A concrete- selection remains a probe constraint, never proof. In ④ the selector is expanded+- On 自定义, manual override is a collapsed disclosure `addKey.protocol.manual`. A concrete+ selection is a declaration, not a probe constraint. In ④ the selector is expandedin place; retry stays disabled while Auto is selected. The collapsed row and theexpanded selector are one selection rendered two ways, so exactly one of them is onscreen: expanding replaces the row, and the pressed segment is then the statement.@@ -3342,9 +3366,11 @@ The dialog is now a single add flow:family's brand glyph (Anthropic mark for `anthropic`; OpenAI mark for both`openai_responses` and `openai_chat`). Auto detect has no glyph. Glyphs live in`protocolGlyph.tsx` and do not touch `vendorMeta.ts`.-- The persisting invariant is unchanged: every persisting exit requires a protocol- proved by an observed response. ③/④ never persist.-- Evidence retires with the inputs it was proved against. Editing Base URL, the API+- The persisting invariant is: every persisting exit requires a protocol+ established on the 2026-09-04 ladder (catalog pin, user declaration, or+ matching response proof). ③ never persists. ④ never persists from Auto;+ a concrete declaration that authenticates leaves ④ through ② into ①″.+- Evidence retires with the inputs it was derived from. Editing Base URL, the APIkey or the protocol selection returns **any** state whose primary would persistwithout observing again to ① Ready — ①″'s report, ⑤'s waived inventory, and theprotocol a refused or unanswered create still holds. That is the property, stated@@ -3365,8 +3391,8 @@ The dialog is now a single add flow:| `f7Ao1U` 名称(可选) | free text | user | yes | — || `cXsiv` Base URL + hint | free text; the hint names an API root, and says a bare host uses the standard `/v1` path | user | yes | — || `mZBBw` API Key | masked value, reveal icon | user | yes | Toggle reveal |-| Interface type | result area last: idle/ready row naming the interface 检测 will send, detecting spinner, identified mint strip, or ④'s gold strip; protocol-family glyphs on every concrete protocol name | observation result; disclosure selection is a probe constraint | disclosure yes; ④ selector yes | Open `addKey.protocol.manual`, which replaces the row with the selector; a concrete choice constrains the next 检测 / ④ 重试 |-| `S0pOY2` 检测 / 确认添加 | 检测 while there is no fresh result; 确认添加 after ①″ | form validity | yes | 检测 → ②; 确认添加 → ②″ with the proved protocol |+| Interface type | result area last: idle/ready row naming the interface 检测 will send, detecting spinner, identified mint strip, catalog-locked row, or ④'s gold strip; protocol-family glyphs on every concrete protocol name | observation result; catalog pin; disclosure selection is a declaration on 自定义 | disclosure yes on 自定义; ④ selector yes | Open `addKey.protocol.manual`, which replaces the row with the selector; a concrete choice declares the next 检测 / ④ 重试 |+| `S0pOY2` 检测 / 确认添加 | 检测 while there is no fresh result; 确认添加 after ①″ | form validity | yes | 检测 → ②; 确认添加 → ②″ with the established protocol || `OT0Xf` state ② | spinner, 识别接口中… | in-flight observe | 取消 only | Abort; return to ① Ready with the form intact || persist strip state ②″ | spinner, 保存中…, 正在保存这个供应商 | in-flight persist | none — cancel blocked | — || `C72yS` state ③ strip | classified outcome copy | observation result | no | — |@@ -3431,8 +3457,8 @@ names, and after it the source exists and its questions belong to 06.of the same probe — 添加 and optional 拉取型号 — and every outcome was primed as anadd/pull twin so that a pull could never persist. Detect is now mandatory and Confirm isthe only persisting primary, so there is no optional pull branch and no remaining work for-those twins. ①′ / ②′ / ③′ / ④′ / ⑤′ / ⑥′ are tombstones. ⑤'s 仍要添加 is gated on a proved-protocol with unavailable inventory, not on origin.+those twins. ①′ / ②′ / ③′ / ④′ / ⑤′ / ⑥′ are tombstones. ⑤'s 仍要添加 is gated on an+established protocol owner with unavailable inventory, not on origin.Cancel is no longer an origin-dependent fork. ②'s 取消 aborts the in-flight observe andreturns to ① Ready with the form intact — a real abort, not a dismissal — and a second@@ -3455,7 +3481,7 @@ copy.**A successful Detect lands in ①″, not back in ① and not in a persist** `[derived]`. ①″ isthe form exactly as ① Ready renders it, plus the mint identified strip: protocol-family-glyph, proved protocol label, and `addKey.pull.result` or `addKey.pull.empty`. It is also+glyph, established protocol label, and `addKey.pull.result` or `addKey.pull.empty`. It is alsowhere ④ lands when the manual selection identifies the interface with discovery succeeded,and where ⑤'s 重试 lands when the repeated observation comes back usable. Nothing waspersisted, so 确认添加 from here still runs Source-create's repeated observation and reuses@@ -3464,21 +3490,20 @@ drops the report, because a count is a fact about the address it was fetched frodismisses with nothing to abort — the in-flight abort belongs to ②, which is where therequest still is.-**The form-level protocol selector is a probe constraint, not response proof**-`[frame]` `[contract]`. The 2026-08-26 owner ruling supersedes the former-ambiguity-only probe-order hint; the 2026-09-03 ruling then moved the selector behind a-collapsed disclosure and made the visible row a detection-result area. Auto detect remains-the default. Auto detect probes the supported interfaces in the adapter's authoritative-order. A concrete choice probes exactly that interface on the next 检测 or ④ 重试.-Persistence still requires a matching protocol-shaped upstream response; the user choice-cannot manufacture proof.+**The form-level protocol selector on 自定义 is a declaration, not a probe constraint**+`[frame]` `[contract]`. The 2026-09-04 owner ruling supersedes the 2026-08-26+shape-only sentence and the 2026-09-03 "probe constraint, never proof" sentence.+Auto detect remains the default on 自定义 and still requires matching response+proof. A concrete choice on the next 检测 or ④ 重试 is persisted after+authentication on that path; shape proof is not required. A catalog vendor+hides this selector and pins protocol from the shipped table.State ④ keeps the same selector visible — expanded in place, not behind the disclosure —and requires a concrete choice before 重试. The primary is still a retry, not a save, andthe strip always describes the latest attempt. A successful retry with discovery succeeded-lands ①″ and still persists nothing. The stored Source records the proved protocol but no-manual/automatic provenance marker: the distinction matters during preflight, not during-later invocation. Saved protocol changes still require a new Source.+lands ①″ and still persists nothing. The stored Source records the established protocol+but no manual/automatic provenance marker: the distinction matters during preflight, not+during later invocation. Saved protocol changes still require a new Source.**State ⑤ is the one place in the product that saves something it could not fullyverify, and the rule that makes it safe is a property, not a permission** `[frame]`@@ -3486,24 +3511,26 @@ verify, and the rule that makes it safe is a property, not a permission** `[fram(`d6bFlX`), and the ruling that closed it states the invariant the whole dialogenforces:-> 已保存的来源恒有一个被观测证明过的协议;凡拿不到证明的路径,产物都是「没有添加成功」。+> 已保存的来源恒有一个已建立且有归属的协议;凡拿不到这个归属的路径,产物都是「没有添加成功」。Read that as a partition of the four ways an add can end, and every button on this-screen falls out of it. ③ and ④ are the paths where the protocol was **not** proved,-so both refuse — that is E-3's gate, and ⑤ does not reopen it, because ⑤ is-downstream of the gate rather than around it. ⑤ is the path where the protocol-*was* proved by a real response and a *different* result — the model inventory —-did not arrive. AC-27 at `ca45aeb6` puts the same thing from the contract's side:-「『Add anyway』 is available only after the protocol was proved and a different-result, such as model inventory, remains unavailable; that uncertainty is a health-fact.」 An unknown inventory is a fact a saved source can carry; an unknown protocol-is not, because every later request depends on it.+screen falls out of it. ③ and ④ are the paths where the protocol owner was **not**+established, so both refuse — that is E-3's gate, and ⑤ does not reopen it, because+⑤ is downstream of the gate rather than around it. ⑤ is the path where the protocol+*was* established by one rung of the ladder — catalog pin, concrete `custom`+declaration, or matching response proof — and a *different* result, the model+inventory, did not arrive. AC-27 at `ca45aeb6` puts the same thing from the+contract's side: 「『Add anyway』 is available only after the protocol was+established and a different result, such as model inventory, remains unavailable;+that uncertainty is a health fact.」 An unknown inventory is a fact a saved source+can carry; an unknown protocol owner is not, because every later request depends on+it.That is why 仍要添加 exists here and nowhere else, and the frame says so in its owncaption: 「全产品唯一一处「仍要添加」」. It is also why the state carries **no field**.④ asks the user for a concrete interface because the product is missing something the user mightknow; ⑤ asks for nothing, because the user cannot supply a model list. The only-question ⑤ puts to a person is whether to keep the connection they just proved.+question ⑤ puts to a person is whether to keep the connection they just established.**The three-button foot is the shape of that question, and the ink partition holdsthrough it** `[frame]`. `x0Gzg` carries 取消 (`SvK44`), 仍要添加 (`wouXZ`) and 重试@@ -3519,23 +3546,24 @@ advisory inks describe the state of the world, and the world's state here is alrsaid once, by the gold strip above.**The property this state produces is an equality, not a pixel**: the set of dialog exits-that persist a source equals the set whose protocol came from an observed response. A+that persist a source equals the set whose protocol has a named established owner. Abuild that lets ③ or ④ save, and a build that refuses ⑤, break the same equality fromopposite sides — which is why it is worth stating as one.**The persisting body is the complete `SourceCreate` schema, including`accept_unavailable_inventory`** `[contract]`. The frozen schemacarries required `vendor` and write-only `key`,-optional `display_name`, normalized `base_url`, the selected `protocol` constraint when+optional `display_name`, normalized `base_url`, the selected `protocol` whenpresent, and the generated `client_nonce`. Itcarries no protocol conclusion or discovered inventory: the server repeats the same-response-backed observation inside the create attempt and owns the stored protocol,-models and health. Thus ④'s pick remains a probe constraint rather than authority, and ⑤'s+observation inside the create attempt and owns the stored protocol,+models and health. Thus ④'s Auto path still cannot save, a concrete ④ declaration+is authority once authenticated, and ⑤'s仍要添加 is the only producer that sets `accept_unavailable_inventory: true`;the clean path sends false or omits it and may not commit when that server-side-observation again proves a protocol while discovery remains unavailable. The flag never-supplies or overrides observation evidence, is inert on successful discovery, and cannot-bypass reachability, authentication or protocol proof. The response is+observation again establishes the protocol owner while discovery remains unavailable. The+flag never supplies or overrides observation evidence, is inert on successful discovery,+and cannot bypass reachability, authentication or protocol establishment. The response is`{source, added_to, adopted_by}`;the plaintext key and nonce reservation never become routing inputs.@@ -3558,7 +3586,7 @@ is revealed; the button carries the verb.| `subtitle` | 先检测连接与接口,确认后添加 | Detect the connection and interface first, then confirm to add || `field.name` | 名称(可选) | Name (optional) || `field.protocol` | 接口类型 | Interface type |-| `field.protocol.hint` | 不确定时用自动探测;已知类型时只验证所选接口 | Use Auto detect when unsure; choose a type to validate only that interface |+| `field.protocol.hint` | 不确定时用自动探测;已知类型时可直接声明所选接口。该路径鉴权成功即可添加;选错了运行时可能失败,而且保存后不可更改 | Use Auto detect when unsure; choose a type to declare that interface. If authentication succeeds it can be added, a wrong choice can fail at runtime, and the saved type cannot be changed || `field.baseUrl` | Base URL | Base URL || `field.baseUrl.hint` | 填写 API 根地址,例如 https://api.example.com/v1;只填域名时使用标准 /v1 路径 | API root, such as https://api.example.com/v1; a bare host uses the standard /v1 path || `field.apiKey` | API Key | API key |@@ -3582,7 +3610,7 @@ is revealed; the button carries the verb.| `fail.inProgress` `[derived]` | 创建仍在进行,可稍后重试 | Creation is still in progress. Try again later. || `retry` | 重试 | Retry || `undetermined.title` | 连上了 —— 但认不出它说哪种接口 | Connected — but we cannot tell which interface it speaks |-| `undetermined.detail` | 返回结构对不上任何一种已知接口,请选择一个明确类型后重试 | The response shape matches no interface we know; choose a concrete interface and retry |+| `undetermined.detail` | 返回结构对不上任何一种已知接口。请选择一个明确类型后重试:只要该路径鉴权成功即可添加;但选错了运行时可能失败,而且保存后不可更改 | The response shape matches no interface we know. Choose a concrete type and retry: if authentication succeeds on that path it can be added, but a wrong choice can fail at runtime and the saved type cannot be changed || `protocol.auto` | 自动探测 | Auto detect || `protocol.anthropicMessages` | Anthropic Messages | Anthropic Messages || `protocol.openaiResponses` | OpenAI Responses | OpenAI Responses |@@ -3638,15 +3666,19 @@ one fact that licenses 仍要添加: the interface is known and only discovery fIt deliberately names no request, status or cause, because `discovery: failed` is a bareenum and cannot support finer evidence. The sentence is static in both locales.-**`undetermined.hint` used to contradict AC-27, and now states it.** The string the-frame drew previously — 「选一种才会保存 · 之后可在来源详情里改」 — promised the choice-was changeable later. At `ca45aeb6`, AC-27 says the opposite: after Save the stored+**`undetermined.hint` used to contradict AC-27, then stated the 2026-08-26+shape-only rule, and now states the 2026-09-04 ladder.** The string the+frame drew originally — 「选一种才会保存 · 之后可在来源详情里改」 — promised the choice+was changeable later. At `ca45aeb6`, AC-27 said the opposite: after Save the storedprotocol is preserved byte-for-byte through retest, discovery, refresh, credential andBase-URL replacement and restart, and 「changing protocol requires a new Source」; FC-12`PATCH /api/models/sources/<source_id>` `[contract]` carries metadata only — frame 11now registers that editor in §1.10 — and has no protocol field at all, so there is no request that could-change one. The rebuilt string-ends 「保存后不可更改」 — the frame moved onto the contract's side. **E-2 is closed, and this string is now its whole surface.** The other+change one. The 2026-09-03 string ended 「保存后不可更改」 and still called the+choice a probe constraint. The 2026-09-04 string keeps immutability after Save+and names the declaration: authentication on the chosen path is enough; a wrong+declaration fails on a later real call. **E-2 remains closed; this string is still+its whole surface.** The otherhalf of that conflict was an instruction to put a protocol-edit entry point on frame06's interface badge; the ruling deleted the badge instead, so there is no longer aplace in the product where a stored protocol is displayed as changeable, and §1.6@@ -3693,13 +3725,13 @@ them do I actually want, and what reasoning tiers does each accept?* Nothing els| Element | Displays | Data source | Interactive | On activate || --- | --- | --- | --- | --- || `iGcAi` back icon | icon only; `sourceDetail.back` is its accessible name in both locales `[derived]` | route | yes | Return to 01 |-| `sugad` source bar | 36×36 identity tile, source name, `provider or endpoint host · proved protocol` identity pill, **state dot + state label** (使用中 in the drawn state) + 型号列表更新于 {{time}}, mono `host · N 个型号` | source state `[spec §4.5]` | capability-gated 重新拉取 / 添加模型 / source overflow `[frame 11]` | Refetch / append an editable row / open 编辑来源 · 移除来源 |+| `sugad` source bar | 36×36 identity tile, source name, `provider or endpoint host · established protocol` identity pill, **state dot + state label** (使用中 in the drawn state) + 型号列表更新于 {{time}}, mono `host · N 个型号` | source state `[spec §4.5]` | capability-gated 重新拉取 / 添加模型 / source overflow `[frame 11]` | Refetch / append an editable row / open 编辑来源 · 移除来源 || 重新拉取 action capability `[derived]` | `sourceDetail.action.refetch` | `Source.supply_channel` | render for `hub`; do not render for `native_cli` | A Hub Source → Refetching. A native Source has no stored credential for this route to validate, so it exposes no activation || `myA8k` header | 型号 ID (250) · 录入 (84) · 推理强度 (470, with info) · fill spacer | static | no | — || `OM5PH` row | model id, entry-kind pill, tier chips, overflow icon | one model | tiers, overflow | Edit tiers / row menu || Retired discovered-row delta `[derived]` | same `OM5PH` chrome, muted ink, existing tag component with `sourceDetail.entry.retired`; never a new row component | `origin: discovered`, `retired: true` `[contract]` | no delete or reactivation action | Remains readable and non-supplying; refetch preserves it || `p2JwTz` tiers | chips, or 未设置档位; `+ 添加档位` is drawn only while a pointer is on the row, in the box it reserves either way, and the row answers that hover with `--model-hub-wash-0a` fill and nothing else — no border, no height, no reflow; a write this row rolled back keeps its 重试 here `[derived]` | `reasoning_efforts[]` `[contract]` FC-03 | the whole cell, by pointer, focus or tap — the cell's box is the row band rather than the chips it happens to hold, so a device with no hover draws no pill and still has the same target | Enter edit mode; retry the rolled-back write |-| `eVavA` tiers (editing) | removable chips + text input + 回车添加 · 任意文本 + ghost suggestion chips derived from the source's proved protocol (the OpenAI protocols offer `low` `medium` `high` `xhigh`; Anthropic Messages names no tier vocabulary and offers none) + one muted line stating that tiers are sent as typed and that a model with none is still routable `[derived]` | local edit → `PATCH /api/models/sources/<source_id>/models/<model_id>` `[contract]`; suggestions are presentation only — never persisted, never pre-filled at discovery, never sent | yes; one row is in this state at a time, and the state ends when focus leaves the editor — Escape (which hands focus back to the row) or focus moving anywhere outside it, including another row's cell — so every control inside it is reachable by keyboard and by pointer alike; a rolled-back write is not held here, it stays with its row `p2JwTz` | Add / remove a tier; a suggestion adds through the same path typing it would take; retry a rolled-back write |+| `eVavA` tiers (editing) | removable chips + text input + 回车添加 · 任意文本 + ghost suggestion chips derived from the source's established protocol (the OpenAI protocols offer `low` `medium` `high` `xhigh`; Anthropic Messages names no tier vocabulary and offers none) + one muted line stating that tiers are sent as typed and that a model with none is still routable `[derived]` | local edit → `PATCH /api/models/sources/<source_id>/models/<model_id>` `[contract]`; suggestions are presentation only — never persisted, never pre-filled at discovery, never sent | yes; one row is in this state at a time, and the state ends when focus leaves the editor — Escape (which hands focus back to the row) or focus moving anywhere outside it, including another row's cell — so every control inside it is reachable by keyboard and by pointer alike; a rolled-back write is not held here, it stays with its row `p2JwTz` | Add / remove a tier; a suggestion adds through the same path typing it would take; retry a rolled-back write || `nN4TZ` manual row | editable id input, 手动添加 pill, tier affordance, 取消 / 添加 | local draft → `POST /api/models/sources/<source_id>/models` `[contract]` | yes | Commit or discard || `Q83BF` add row | 添加模型 + when to use it | — | yes | Append a manual draft row || `tF3Bh` footnote | scope of this page; that tiers are yours to type; that the interface type is confirmed at add time, shown, and not editable here | static | no | — |@@ -4195,7 +4227,7 @@ Five rules:| `edit.title` `[frame]` | 编辑来源 {{source}} | Edit source {{source}} || `edit.name` `[frame]` | 显示名称 | Display name || `edit.baseUrl` `[frame]` | Base URL | Base URL |-| `edit.hint` `[derived]` `[contract]` | 协议已由真实响应证明,不在这里改;改显示名称不会影响型号与路由链。改地址时会先检查供给影响。 | The protocol was proved by a real response and cannot be changed here. Renaming does not affect models or routes; changing the address first checks its supply impact. |+| `edit.hint` `[derived]` `[contract]` | 协议已在添加时建立,不在这里改;改显示名称不会影响型号与路由链。改地址时会先检查供给影响。 | The protocol was established during add and cannot be changed here. Renaming does not affect models or routes; changing the address first checks its supply impact. || `edit.cancel` `[frame]` | 取消 | Cancel || `edit.save` `[frame]` | 保存 | Save || `edit.saving` `[derived]` | 正在保存… | Saving… |@@ -4316,7 +4348,7 @@ act on. A latency figure next to a refetch button would invite exactly the conflthe previous rule forbids.**The source identity label is unconditional and non-editable** `[frame]` `[contract]`.-The card and detail header show `provider or endpoint host · proved protocol`, for+The card and detail header show `provider or endpoint host · established protocol`, forexample `ai-relay.chainbot.io · Anthropic Messages`. It is not the retired「接口由你指定」 badge: Source carries no manual/automatic provenance, so the label neverclaims how the protocol was selected. `PATCH /api/models/sources/<source_id>` still has@@ -4923,7 +4955,7 @@ lifecycle. A `needs_action` card suppresses only a duplicate action already rend| Element | Displays | Data source | Interactive | On activate || --- | --- | --- | --- | --- || Source overflow | 编辑来源; capability-gated 重新授权 or 更换 Key; 移除来源 | selected source + credential capability | yes | Edit / Remove open frame 11; either credential action enters the matching §1.11 producer with the exact source-detail origin held |-| Edit head | `sourceDetail.edit.title` plus kind, credential owner and proved protocol | selected source | close | Dismiss unchanged |+| Edit head | `sourceDetail.edit.title` plus kind, credential owner and established protocol | selected source | close | Dismiss unchanged || 显示名称 | current `display_name` | source | yes | Edit locally || Base URL | current `base_url` | API-key source | yes | Edit locally; clearing a custom value commits `null` and restores the official endpoint || Edit helper | Why protocol is fixed and when a Base-URL edit can affect supply | static | no | — |@@ -5332,7 +5364,8 @@ a category the product cannot adjudicate becomes a label that lies. `[spec §3]`Auto detect plus each supported interface before the first request. Auto is the default;a concrete choice restricts observation to that one protocol.*Why:* compatible relays often expose multiple or misleading routes. The operator may-know the contract while the product still owns the proof required to save it.+know the contract while the product still owns the establishment check required to save+it.**D-3 — Manual selection narrows verification; it never bypasses it.** A concreteselection produces exactly one candidate probe. State ④ keeps the form and selector@@ -5591,13 +5624,16 @@ spends their disk and their minutes on something never named, and the first theyit is a progress bar. Naming it inside the consequence list costs one line and turns adead end into a decision. This was G-6; it is now ruled and the gap is struck.-**D-27 — A saved source always has a protocol that was proved by an observed response;-every path that cannot obtain that proof produces "not added".**-> 已保存的来源恒有一个被观测证明过的协议;凡拿不到证明的路径,产物都是「没有添加成功」。+**D-27 — A saved source always has a protocol with a named owner (catalog pin, user+declaration, or matching response proof); every path that cannot obtain that owner+produces "not added".** (2026-09-04 supersession of the 2026-08-26 response-shape-only+wording.)+> 已保存的来源恒有一个有主的协议;凡拿不到主的路径,产物都是「没有添加成功」。*Why:* this is the property that makes 05's four exits derivable instead of negotiable.-③ and ④ refuse because the protocol is unproved (E-3); ⑤ may save because it *is*-proved and only the inventory is missing (E-5) — and an unknown inventory is a health+③ refuses because nothing established a protocol; ④ refuses from Auto and leaves+through a declaration that authenticates; ⑤ may save because the protocol *is*+established and only the inventory is missing (E-5) — and an unknown inventory is a healthfact a source can carry, while an unknown protocol is a value every later request wouldhave to guess. Stated as a property rather than as a permission, it also decides casesnobody has drawn yet: any future add path inherits the same test.diff --git a/docs/plans/model-hub-vendor-preset-protocol.md b/docs/plans/model-hub-vendor-preset-protocol.mdnew file mode 100644index 000000000..4c4ab3013--- /dev/null+++ b/docs/plans/model-hub-vendor-preset-protocol.md@@ -0,0 +1,186 @@+# Model Hub — Add API key: vendor presets and declared protocol++Status: owner-directed 2026-09-04 (this conversation). This file is the+design authority for the change. `docs/plans/model-hub.md` (protocol+observation ruling), `docs/plans/model-hub-ui-spec.md` §1.5, and+`docs/plans/model-hub-contracts/` receive dated amendments from this plan.++Surface: V4 06r already drew the vendor dropdown; 模型网关 05 is the+current-implementation frame and now carries that field. Do not invent a+new dialog. Detect-then-confirm (#1831) stays. Type-scale fix from closed+#1842 (`f38ee133` on `fix/model-hub-idle-row-type-scale`) is folded in.++## Why this exists++DeepSeek (and Qwen, Kimi, and any gateway that answers `/v1/chat/completions`,+`/v1/responses`, and `/v1/messages` with the same body) cannot be added+today. Observation requires a **protocol-shaped** upstream response+(AC-27, 2026-08-26). Identical answers on all three paths never prove a+protocol. Manual selection is a probe constraint, never proof, so retry+is the same dead end. Live case: `https://api.deepseek.com` + a valid+key → ④ 「认不出它说哪种接口」.++#1731 closed a *shape-table* gap (`param: null`, 400 model-not-found).+It explicitly left vendor presets out of scope and kept AC-27. That+repair cannot save an endpoint whose three paths are indistinguishable.++V4 06r already specified the product intent: a **服务商** dropdown that+prefills the official URL. 05 never wired it; `AddApiKeyDialog` hard-codes+`vendor: 'custom'`.++## Protocol proof ladder (replaces the single AC-27 sentence)++Every stored `protocol` still has a named owner. Inference from a typed+URL string remains forbidden. The owner is one of:++| Rung | When | What observation must still prove | Where `protocol` comes from |+| --- | --- | --- | --- |+| 1. Catalog pin | User picked a first-wave vendor, not 自定义 | Reachable + authenticated | Catalog row's `protocol`. Shape proof is **not** required. |+| 2. Response proof | 自定义 + 自动探测 | Reachable + authenticated + protocol-shaped response (today's AC-27) | The observation evidence table |+| 3. User declaration | 自定义 + a concrete interface selected | Reachable + authenticated **on the constrained protocol's path** | The user-selected `protocol`. Shape proof is **not** required. A wrong declaration fails at runtime on a real call, same philosophy as reasoning-tier v2 evidence isolation. |++「仍要添加」 stays exactly where it is: protocol known, inventory missing.+③ (unreachable / rejected / timeout / adapter_error) and a still-ambiguous+auto-detect ④ still cannot save.++Once saved, `protocol` remains immutable on that Source. Changing it still+means a new Source. No `protocol_source` field in this change (avoids a+contract_version bump). Dialog badges are local form state. After save,+`Source.vendor` is the catalog id (`deepseek`, not `custom`), which is+enough for source-detail identity.++## First-wave catalog++Authoritative table, shipped as `vibe/data/api_key_vendors.json`. Vendor+ids reuse 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 catalog backfill) and is not this picker.++| id | Label | Official Base URL | Pinned protocol |+| --- | --- | --- | --- |+| `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` |+| `zhipuai` | Zhipu AI | `https://open.bigmodel.cn/api/paas/v4` | `openai_chat` |+| `openai` | OpenAI | `https://api.openai.com/v1` | `openai_responses` |+| `anthropic` | Anthropic | `https://api.anthropic.com` | `anthropic` |+| `openrouter` | OpenRouter | `https://openrouter.ai/api/v1` | `openai_chat` |+| `groq` | Groq | `https://api.groq.com/openai/v1` | `openai_chat` |+| `mistral` | Mistral | `https://api.mistral.ai/v1` | `openai_chat` |+| `xai` | xAI | `https://api.x.ai/v1` | `openai_chat` |+| `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. Gemini native is+deferred (not in the three-protocol vocabulary).++Engine `_OFFICIAL_BASE_URLS` today only lists anthropic/openai/codex.+This table is the replacement for api-key observation: look up by+`vendor`, then `base_url` or the official default.++## Dialog (05, aligned with V4 06r)++Field order: **服务商** → 名称(可选) → Base URL → API Key → 接口类型.++服务商 is a select, not a tile grid (06r already drew this; 05b was+deleted as a duplicate). Options: 自定义 · 兼容端点, then the first-wave+rows in the table order above.++### Preset selected (rung 1)++- `vendor` is the catalog id.+- Base URL prefills the official value, remains editable.+- Interface type is a **locked result row**: protocol-family glyph ++ catalog protocol label + badge 「内置目录」 / “Built-in catalog”. The+ manual disclosure is hidden. Hint: detection authenticates and fetches+ models; it does not have to prove the interface by shape.+- 检测 → observe with `vendor` + `protocol` = catalog pin. Success+ (authenticated) → ①″ mint strip with count + the same badge → 确认添加.+- Changing 服务商 resets URL, protocol lock, and any observation.+- Editing Base URL on a preset does **not** drop the pin (vendor stays+ `deepseek`). A relay that is not that vendor is 自定义.++### 自定义 (rung 2 / 3)++- `vendor` is `custom`. Base URL empty. Interface type stays the+ detect-then-confirm result area.+- Auto detect is rung 2 (unchanged evidence table).+- A concrete disclosure choice is now a **declaration** (rung 3), not a+ probe constraint. ④ copy must say so: 鉴权成功即可添加; a wrong+ declaration fails on a later real call. Retry with Auto still selected+ stays disabled.+- ①″ / ④ mint or gold strip: badge 「手动指定」 / “Manually specified”+ when a concrete protocol is selected; no badge on Auto.++### Unchanged++- Two-step primary (检测 → 确认添加).+- ⑤ 仍要添加.+- Replace-key mode.+- No model names in the dialog (count only).+- Glyphs stay on protocol family, in `protocolGlyph.tsx`.+- Type scale: every text node in this dialog declares its own size+ (pending cherry-pick of `f38ee133`).++## Contract amendments (shape unchanged, semantics change)++`contract_version` stays **7**. No new fields. Descriptions and+invariants change.++- `source-create.schema.json` `protocol`: a supplied value is persisted+ when observation is authenticated and either (a) `vendor` has a catalog+ pin for that protocol, or (b) the client declared that protocol on+ `custom`, or (c) a matching protocol-shaped response proves it.+ Omission on `custom` still auto-detects and still requires shape proof;+ shipped catalog vendor omission selects the pin.+- `POST /api/models/sources/observe` in `api.md`: same three-way rule.+ Catalog pin and declaration still require reachability and+ authentication; they never bypass ③.+- Contracts README invariant 2: replace “Vendor names, Base URLs, and+ manual hints may order probes but cannot create a saved protocol+ value” with the ladder above.+- `model-hub.md` protocol-observation ruling: dated 2026-09-04+ supersession of the 2026-08-26 “never infers from vendor name”+ sentence. Catalog pin is not inference from a typed URL; it is an+ explicit vendor choice against a shipped table.+- G-18 / G-27 rows: probe constraint language is now only the Auto+ branch on `custom`.++## Acceptance++- DeepSeek official URL + valid key, vendor `deepseek`, adds as+ `openai_chat` without a shaped proof. Same for a recorded DeepSeek+ `param: null` / identical-three-path fixture.+- 自定义 + declared `openai_chat` + authenticated DeepSeek-shaped+ responses adds. Auto detect on the same fixture still lands ④.+- Official Anthropic / OpenAI presets still add (rung 1 pin; existing+ shape tests stay green).+- ③ still refuses on 401 / unreachable.+- ⑤ still the only 仍要添加.+- Replace-key byte-equivalent.+- `check_model_hub_authorities.py` clean (version stays 7).++## Out of scope++- `protocol_source` on `Source` (follow-up if source detail needs a+ provenance badge).+- Gemini native / a fourth protocol value.+- Expanding #1731's evidence table further (rung 2 stays as shipped).+- OpenCode provider cards (different “服务商” surface).+- Agent “Add models” picker (#1839) — consumes Sources after they exist.++## Lane split++Contracts freeze here. Implementation is two PRs, backend first:++1. **Backend** — `api_key_vendors.json`, official URL lookup, observe and+ create proof ladder, DeepSeek-shaped fixtures, schema/api.md/README+ description edits, `model-hub.md` ruling. No `ui/**` except the+ contract-version literal mirrors if a bump becomes necessary (it+ should not).+2. **UI** — vendor select on `AddApiKeyDialog`, i18n, ④ copy, locked+ protocol row, badges, e2e B1–B4/B11, cherry-pick `f38ee133`, §1.5+ dated amendment. Rebase after backend merges.++Neither lane merges itself.diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex b517ad039..b78ec9789 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -180,7 +180,7 @@ The Source workflow is complete at both entry points:A concrete interface restricts the preflight to one candidate; Auto detect tries thesupported candidates in the adapter's authoritative order. The user-triggered Addaction reuses one connectivity interaction to classify reachability/authentication- and prove the protocol before Save can commit. Its schema-invalid probe settles before+ and establish a protocol owner before Save can commit. Its schema-invalid probe settles beforea relay selects or invokes a model, so observation never depends on a synthetic modelbeing routable. This unsaved operation does not save a Source, consume routing order,or run an Agent turn. For an API key it may provision an engine credential only@@ -190,14 +190,14 @@ The Source workflow is complete at both entry points:reconciliation rather than leaving an unreferenced credential untracked. No testresponse exposes the ref. A reachability or authentication failure is reportedindependently from protocol observation: Save may proceed only when that interaction- still produced response evidence for the protocol, and it provisions the committed+ still established the protocol on the named-owner ladder, and it provisions the committedSource independently.- **CPA ownership after Save.** CPA requires a concrete upstream provider configuration,so it cannot identify an unsaved Source without first being told the interface this- preflight exists to prove. Once the Source is saved, Avibe maps its proven protocol to+ preflight exists to establish. Once the Source is saved, Avibe maps its established protocol toCPA's existing `claude-api-key`, `codex-api-key`, or `openai-compatibility` providersection and every Agent invocation runs through CPA. Avibe owns only the bounded- pre-save evidence step; CPA owns compatible request translation and upstream dispatch.+ pre-save establishment step; CPA owns compatible request translation and upstream dispatch.- **Saved Source refresh and recovery.** Source details exposes the distinct`POST /api/models/sources/<id>/refresh` operation. It is intentionally mutating: ittests the stored protocol, rediscovers inventory, updates Source health, and clears a@@ -254,13 +254,16 @@ The Source workflow is complete at both entry points:discovered-only immutable list would leave the capability permanently undeclarable.**Source-create boundary.** `source-create.schema.json` is the complete API-key create-request: `vendor` and transient `key`, plus optional `display_name`, `base_url`, probe--constraining `protocol`, client-generated `client_nonce`, and boolean+request: `vendor` and transient `key`, plus optional `display_name`, `base_url`,+`protocol`, client-generated `client_nonce`, and boolean`accept_unavailable_inventory`; omission is `false`, and the boolean consents only when-the server's repeated response-backed observation proves a protocol but returns-`discovery: failed`. Omitted `protocol` auto-detects across the supported interfaces;-a supplied value probes exactly that interface but is not evidence and is persisted only-after a matching response. Source identity, protocol+the server's repeated observation has established a protocol (catalog pin, user+declaration, or matching response shape) but returns+`discovery: failed`. Omitted `protocol` selects the shipped vendor pin when one exists;+otherwise only `custom` omission auto-detects across the supported interfaces and still+requires matching response proof. A supplied value is persisted when observation is+authenticated and either the vendor catalog pins that protocol, the client declared it+on `custom`, or a matching protocol-shaped response proves it. Source identity, protocolevidence, discovered inventory, health, usage, custody metadata, and timestamps remainserver-owned. When supplied, `client_nonce` is unique among live Sources and live-processcreate reservations. The server reserves it atomically in process before observation or@@ -340,25 +343,35 @@ nonempty. Create materialization and re-auth failures with no stranded sibling eplain-error row. No later Source read can reconstruct the historical report, so theerror envelope carries it exactly once.-**Protocol observation (owner ruling 2026-08-26, superseding the 2026-08-09-ambiguity-only selector ruling).** Every stored `protocol` is traceable to a real response-from that upstream before Save. Avibe never infers the value from vendor name or Base URL.-The form exposes Auto detect plus the three supported protocols before the first request.-Auto detect tries the authoritative sequence; a concrete selection restricts the attempt-to exactly that protocol. Neither is a save-time conclusion: the selected adapter must-still receive matching upstream response evidence before Save. A failed observation-therefore stores nothing rather than guessing.+**Protocol observation (owner ruling 2026-09-04, superseding the 2026-08-26+response-shape-only ruling, which itself superseded the 2026-08-09 ambiguity-only+selector ruling).** Every stored `protocol` has a named owner before Save. Avibe+never infers the value from a typed Base URL string. The owner is one of three+rungs, documented in `docs/plans/model-hub-vendor-preset-protocol.md`:++1. **Catalog pin.** The user picked a shipped api-key vendor (not `custom`).+ Observation must still prove reachability and authentication. The catalog+ row supplies `protocol`. Shape proof is not required.+2. **Response proof.** `custom` plus Auto detect. Today's evidence table:+ a matching protocol-shaped upstream response is required.+3. **User declaration.** `custom` plus a concrete interface. Observation must+ prove reachability and authentication on that protocol's path. Shape proof+ is not required. A wrong declaration fails on a later real call.++The form exposes a vendor select first (V4 06r / 模型网关 05). Auto detect plus+the three supported protocols remain on `custom`. A failed observation still+stores nothing rather than guessing. Unreachable, rejected, timeout, and+adapter-error paths still cannot save.Once saved, `protocol` is immutable for that Source. Connectivity retest, modeldiscovery, refresh, credential replacement, Base URL replacement, and restart all usethe stored adapter and never rewrite it. Changing protocol means creating a new Source,so a later operation cannot silently reinterpret existing inventory or configured hops.The stored shape carries no manual/automatic provenance marker and no unverified-protocol state: manual and automatic preflight become indistinguishable after the-same response-backed conclusion. “Add anyway” is available only after protocol has been-proved and some other information, such as model inventory, remains unavailable; that+protocol state. “Add anyway” is available only after protocol has been+established on one of the three rungs and some other information, such as model inventory, remains unavailable; thatuncertainty belongs to Source health, not protocol identity. Every saved Source therefore-has a response-proven protocol, and any path without that proof produces no Source.+has a protocol with a named owner, and any path without that owner produces no Source.`openai_chat` is the one Chat Completions-compatible transport; there is no separate`openai_compatible` value because both names drove the same engine section and endpoint.@@ -1677,10 +1690,11 @@ one pinned hop it receives.`model_id`. A user-configured mapping to another model or vendor is legal and isexecuted exactly; that hop may use an API key or a hub-held subscription and requiresno additional warning.-- **No protocol guessing or post-save backfill.** A stored protocol comes from a real- pre-save upstream response, never a vendor/Base-URL string heuristic. Auto detect and- manual selection only choose which adapters to verify; the selected adapter must still- return matching response evidence before anything is saved. No later operation changes+- **No protocol guessing or post-save backfill.** A stored protocol comes from one rung+ of the pre-save ownership ladder, never a vendor/Base-URL string heuristic. Auto detect and+ manual selection choose which adapter path to verify; Auto still requires matching+ response proof, while a shipped catalog pin or a concrete `custom` declaration may+ persist after authenticated generic evidence on that path. No later operation changesthe stored value.- No billing-grade accounting, multi-tenant pools, or operator consoles.- No third source category ("relay" merged into API Key).@@ -1734,8 +1748,9 @@ directions into questions that later lanes must answer before writing mechanicalbackend has at most one native Source.- [ ] §4.1 defines manual connectivity testing, model discovery, manual modeladd/remove, and editable `reasoning_efforts` lists for every inventory entry;- every saved protocol is response-proven before Save and immutable afterward,- with no persistent provenance marker or protocol-level unverified value.+ every saved protocol is established before Save by a named owner (catalog pin,+ `custom` declaration, or matching response proof) and immutable afterward, with+ no persistent provenance marker or protocol-level unverified value.- [ ] §4.1 exposes exactly `anthropic | openai_responses | openai_chat`, retains ChatCompletions, and shows Auto detect plus those three protocol choices beforeobservation; an ambiguous Auto result requires one concrete choice to retry.diff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 3b1a08406..bb25bf646 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -106,6 +106,13 @@ scenarios:layer: scenariobackend: codextest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_codex_oauth_api_key_relay_round_trip_scenario+ - id: AUTH-SETUP-111+ name: Catalog API-key observe and confirm-create repeat the pinned probe, and auth failure persists nothing+ status: covered+ kind: negative_path+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_catalog_api_key_setup_observe_then_create_closed_loop- 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 d0bff0c5a..818e7e3bf 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -40,7 +40,7 @@ from core.show_pages import ShowPageStorefrom modules.agents.codex.agent import CodexAgentfrom tests.scenario_harness.auth_setup import AuthSetupScenarioHarness, FakeProcessfrom tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep-from tests.ui_server_test_helpers import _save_config, remote_session_cookie+from tests.ui_server_test_helpers import _save_config, csrf_headers, remote_session_cookiefrom storage import remote_access_authorization_servicefrom tests.scenario_harness.model_hub_native_oauth import (HubOAuthScenarioHarness,@@ -2525,5 +2525,165 @@ class CodexRelayRoundTripScenarioTests(unittest.IsolatedAsyncioTestCase):await self._run_round_trip(runner, api)+def test_catalog_api_key_setup_observe_then_create_closed_loop(monkeypatch, tmp_path):+ """Scenario: AUTH-SETUP-111"""+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ monkeypatch.setenv("VIBE_MODEL_HUB_ENABLED", "1")+ _save_config(tmp_path)++ from core.handlers.model_hub.adapter import (+ ObservationDiscovery,+ ObservationOutcome,+ SourceObservation,+ )+ from tests.test_model_hub_api import _service++ class _CatalogAPIKeySetupHarness(SimpleNamespace):+ pass++ def make_harness(state_dir: Path) -> _CatalogAPIKeySetupHarness:+ service, store, adapter = _service(state_dir)+ return _CatalogAPIKeySetupHarness(+ service=service,+ store=store,+ adapter=adapter,+ client=app.test_client(),+ base_url="http://127.0.0.1:15131",+ )++ harness = make_harness(tmp_path / "catalog-api-key-flow")+ runner = ScenarioRunner(harness)+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: harness.service)++ def observe_catalog_pin(h) -> None:+ response = h.client.post(+ "/api/models/sources/observe",+ json={+ "vendor": "qwen",+ "key": "sk-test-auth-setup-qwen",+ },+ headers=csrf_headers(h.client, h.base_url),+ base_url=h.base_url,+ )++ assert response.status_code == 200+ observation = response.get_json()["observation"]+ assert observation["outcome"] == "observed"+ assert observation["protocol"] == "openai_chat"+ assert h.store.config.sources == []+ assert h.adapter.observed_protocol_orders == [("openai_chat",)]+ assert h.adapter.revoked == ["cred_test001"]++ def create_catalog_pin(h) -> None:+ response = h.client.post(+ "/api/models/sources",+ json={+ "kind": "api_key",+ "vendor": "qwen",+ "key": "sk-test-auth-setup-qwen",+ },+ headers=csrf_headers(h.client, h.base_url),+ base_url=h.base_url,+ )++ assert response.status_code == 201+ source = response.get_json()["source"]+ assert source["vendor"] == "qwen"+ assert source["display_name"] == "Qwen"+ assert source["protocol"] == "openai_chat"+ assert len(h.store.config.sources) == 1+ assert h.store.config.sources[0].vendor == "qwen"+ assert h.store.config.sources[0].protocol == "openai_chat"+ assert h.store.config.sources[0].credential_ref == "cred_test003"+ assert h.adapter.observed_protocol_orders == [+ ("openai_chat",),+ ("openai_chat",),+ ]+ assert h.adapter.revoked == ["cred_test001", "cred_test002"]++ def observe_auth_failure(h) -> None:+ h.adapter.observation = SourceObservation(+ outcome=ObservationOutcome.AUTHENTICATION_FAILED,+ reachable=True,+ authenticated=False,+ protocol=None,+ discovery=ObservationDiscovery.NOT_ATTEMPTED,+ models=(),+ )+ response = h.client.post(+ "/api/models/sources/observe",+ json={+ "vendor": "qwen",+ "key": "sk-test-auth-setup-qwen-invalid",+ },+ headers=csrf_headers(h.client, h.base_url),+ base_url=h.base_url,+ )++ assert response.status_code == 200+ observation = response.get_json()["observation"]+ assert observation["outcome"] == "authentication_failed"+ assert observation["authenticated"] == "rejected"+ assert len(h.store.config.sources) == 1+ assert h.adapter.observed_protocol_orders == [+ ("openai_chat",),+ ("openai_chat",),+ ("openai_chat",),+ ]+ assert h.store.config.sources[0].credential_ref == "cred_test003"+ assert h.adapter.revoked == ["cred_test001", "cred_test002", "cred_test004"]++ def create_auth_failure(h) -> None:+ response = h.client.post(+ "/api/models/sources",+ json={+ "kind": "api_key",+ "vendor": "qwen",+ "key": "sk-test-auth-setup-qwen-invalid",+ },+ headers=csrf_headers(h.client, h.base_url),+ base_url=h.base_url,+ )++ assert response.status_code == 422+ body = response.get_json()+ assert body["error"] == "discovery_failed"+ assert len(h.store.config.sources) == 1+ assert h.store.config.sources[0].vendor == "qwen"+ assert h.store.config.sources[0].protocol == "openai_chat"+ assert h.store.config.sources[0].credential_ref == "cred_test003"+ assert h.adapter.observed_protocol_orders == [+ ("openai_chat",),+ ("openai_chat",),+ ("openai_chat",),+ ("openai_chat",),+ ]+ assert h.adapter.revoked == [+ "cred_test001",+ "cred_test002",+ "cred_test004",+ "cred_test005",+ ]++ asyncio.run(+ runner.run(+ ScenarioStep("observe_catalog_pin", observe_catalog_pin),+ ScenarioStep("create_catalog_pin", create_catalog_pin),+ ScenarioStep("observe_auth_failure", observe_auth_failure),+ ScenarioStep("create_auth_failure", create_auth_failure),+ )+ )++ ScenarioExpect.step_history(+ runner,+ [+ "observe_catalog_pin",+ "create_catalog_pin",+ "observe_auth_failure",+ "create_auth_failure",+ ],+ )++if __name__ == "__main__":unittest.main()diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex 87f289ca7..354f20a61 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -61,6 +61,7 @@ from core.handlers.model_hub.service import (from tests.ui_server_test_helpers import csrf_headers, remote_peer, save_configfrom vibe import backend_model_catalog, ui_serverfrom vibe.model_hub_client import ModelHubRemoteService, _decode+from vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalogfrom vibe.model_hub_runtime.state import EngineStateError, _validate_source_targetfrom vibe.ui_server import app@@ -84,6 +85,9 @@ API_RESPONSE_ROUTES = API_RESPONSE_CONTRACT["x-model-hub-routes"]API_RESPONSE_EXERCISES = [(route, exercise) for route in API_RESPONSE_ROUTES for exercise in route.get("exercises", [route.get("exercise")])]+CATALOG_API_KEY_SOURCE_CASES = tuple(+ pytest.param(entry.id, entry.label, entry.protocol, id=entry.id) for entry in api_key_vendor_catalog()+)def _assert_valid(name: str, payload: dict) -> None:@@ -4544,6 +4548,185 @@ def test_unsaved_observation_route_restricts_a_manual_protocol_to_one_probe(assert adapter.revoked == ["cred_test001"]+def test_unsaved_observation_route_defaults_a_catalog_vendor_to_its_pinned_protocol(+ monkeypatch,+ tmp_path,+):+ service, store, adapter = _service(tmp_path)+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"++ response = client.post(+ "/api/models/sources/observe",+ json={+ "vendor": "deepseek",+ "key": "sk-test-observation-catalog",+ },+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )++ assert response.status_code == 200+ assert response.get_json()["observation"]["protocol"] == "openai_chat"+ assert adapter.observed_protocol_orders == [("openai_chat",)]+ assert store.config.sources == []+ assert adapter.revoked == ["cred_test001"]+++def test_unsaved_observation_route_rejects_wrong_protocol_for_a_catalog_vendor(+ monkeypatch,+ tmp_path,+):+ service, _, adapter = _service(tmp_path)+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"++ response = client.post(+ "/api/models/sources/observe",+ json={+ "vendor": "deepseek",+ "key": "sk-test-observation-wrong-protocol",+ "protocol": "anthropic",+ },+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )++ assert response.status_code == 400+ assert response.get_json()["error"] == "discovery_failed"+ assert adapter.secret_lengths == []+ assert adapter.observed_protocol_orders == []+ assert adapter.revoked == []+++def test_unsaved_observation_route_rejects_omitted_protocol_for_an_uncataloged_vendor(+ monkeypatch,+ tmp_path,+):+ service, _, adapter = _service(tmp_path)+ monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)+ client = app.test_client()+ base_url = "http://127.0.0.1:15131"++ response = client.post(+ "/api/models/sources/observe",+ json={+ "vendor": "deepsek",+ "base_url": "https://relay.example/v1",+ "key": "sk-test-observation-unknown-vendor",+ },+ headers=csrf_headers(client, base_url),+ base_url=base_url,+ )++ assert response.status_code == 400+ assert response.get_json()["error"] == "discovery_failed"+ assert adapter.secret_lengths == []+ assert adapter.observed_protocol_orders == []+ assert adapter.revoked == []+++def test_create_source_defaults_a_catalog_vendor_to_its_pinned_protocol(tmp_path):+ service, store, adapter = _service(tmp_path)++ created = asyncio.run(+ _create_source(+ service,+ {+ "kind": "api_key",+ "vendor": "deepseek",+ "key": "sk-test-create-catalog",+ },+ )+ )++ assert created["protocol"] == "openai_chat"+ assert created["base_url"] is None+ assert adapter.observed_protocol_orders == [("openai_chat",)]+ assert store.config.sources[0].protocol == "openai_chat"+ assert store.config.sources[0].base_url is None+ assert adapter.revoked == ["cred_test001"]+++ ("vendor", "expected_display_name", "expected_protocol"),+ CATALOG_API_KEY_SOURCE_CASES,+)+def test_create_source_defaults_catalog_display_names_for_all_shipped_api_key_vendors(+ tmp_path,+ vendor: str,+ expected_display_name: str,+ expected_protocol: str,+):+ service, store, adapter = _service(tmp_path)++ created = asyncio.run(+ _create_source(+ service,+ {+ "kind": "api_key",+ "vendor": vendor,+ "key": f"sk-test-create-{vendor}",+ },+ )+ )++ assert created["display_name"] == expected_display_name+ assert created["protocol"] == expected_protocol+ assert created["base_url"] is None+ assert store.config.sources[0].display_name == expected_display_name+ assert store.config.sources[0].protocol == expected_protocol+ assert store.config.sources[0].base_url is None+ assert adapter.observed_protocol_orders == [(expected_protocol,)]+ assert adapter.revoked == ["cred_test001"]+++def test_create_source_rejects_wrong_protocol_for_a_catalog_vendor(tmp_path):+ service, store, adapter = _service(tmp_path)++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "deepseek",+ "key": "sk-test-create-wrong-protocol",+ "protocol": "anthropic",+ }+ )+ )++ assert exc_info.value.code == "discovery_failed"+ assert store.config.sources == []+ assert adapter.secret_lengths == []+ assert adapter.observed_protocol_orders == []+ assert adapter.revoked == []+++def test_create_source_rejects_omitted_protocol_for_an_uncataloged_vendor(tmp_path):+ service, store, adapter = _service(tmp_path)++ with pytest.raises(ModelHubError) as exc_info:+ asyncio.run(+ service.create_source(+ {+ "kind": "api_key",+ "vendor": "deepsek",+ "base_url": "https://relay.example/v1",+ "key": "sk-test-create-unknown-vendor",+ }+ )+ )++ assert exc_info.value.code == "discovery_failed"+ assert store.config.sources == []+ assert adapter.secret_lengths == []+ assert adapter.observed_protocol_orders == []+ assert adapter.revoked == []++@pytest.mark.parametrize(("protocol", "model", "expected_efforts", "expected_source"),(diff --git a/tests/test_model_hub_config.py b/tests/test_model_hub_config.pyindex 8ac726137..b0662b162 100644--- a/tests/test_model_hub_config.py+++ b/tests/test_model_hub_config.py@@ -591,7 +591,9 @@ def test_source_create_unavailable_inventory_consent_is_explicit_and_total():assert "Ordinary create" in succeededassert "legitimately empty" in succeeded- failed_rows = [line for line in result_rows if line.startswith("| Protocol proved; `discovery: failed` |")]+ failed_rows = [+ line for line in result_rows if line.startswith("| Protocol established; `discovery: failed` |")+ ]assert len(failed_rows) == 2rejected = next(line for line in failed_rows if "omitted or `false`" in line)accepted = next(line for line in failed_rows if "| `true` |" in line)@@ -600,9 +602,9 @@ def test_source_create_unavailable_inventory_consent_is_explicit_and_total():assert "AC-26 cleanup" in rejectedassert "Commit exactly one Source" in acceptedassert "`models: []`" in accepted- assert "proved protocol" in accepted+ assert "established protocol" in accepted- unproved = next(line for line in result_rows if line.startswith("| Protocol not proved"))+ unproved = next(line for line in result_rows if line.startswith("| Protocol not established"))assert "omitted, `false`, or `true`" in unprovedassert "no Source is committed" in unprovedassert "cannot authorize" in unproveddiff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 6fe7354ea..3334e767b 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -104,6 +104,7 @@ from vibe.model_hub_runtime.adapter import (_ProtocolObservationShape,_ProtocolProof,)+from vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalogfrom vibe.model_hub_runtime.client import EngineClientError, probe_modelsfrom vibe.model_hub_runtime.state import EngineStateStore@@ -120,6 +121,10 @@ 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)+CATALOG_API_KEY_VENDOR_PROTOCOL_CASES = tuple(+ pytest.param(entry.id, entry.protocol, id=entry.id)+ for entry in api_key_vendor_catalog()+)def _assert_valid(schema_name: str, payload: dict) -> None:@@ -5628,7 +5633,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(state_store = EngineStateStore(tmp_path / "engine-state")credential_ref = state_store.store_api_key("test-observation-key",- vendor="openai",+ vendor="custom",protocol=SOURCE_PROTOCOLS[-1],base_url=base_url,)@@ -5688,11 +5693,11 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof() as inventory_probe,):observed = asyncio.run(- adapter.observe_source(- "openai",- base_url,- credential_ref,- hinted_order,+ adapter.observe_source(+ "custom",+ base_url,+ credential_ref,+ hinted_order,))@@ -5715,11 +5720,11 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof() as inventory_probe,):ambiguous = asyncio.run(- adapter.observe_source(- "openai",- base_url,- credential_ref,- hinted_order,+ adapter.observe_source(+ "custom",+ base_url,+ credential_ref,+ hinted_order,))@@ -5749,11 +5754,11 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof() as inventory_probe,):observed = asyncio.run(- adapter.observe_source(- "openai",- base_url,- credential_ref,- pairwise_order,+ adapter.observe_source(+ "custom",+ base_url,+ credential_ref,+ pairwise_order,))@@ -5781,11 +5786,11 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof() as inventory_probe,):ambiguous = asyncio.run(- adapter.observe_source(- "openai",- base_url,- credential_ref,- SOURCE_PROTOCOLS,+ adapter.observe_source(+ "custom",+ base_url,+ credential_ref,+ SOURCE_PROTOCOLS,))@@ -5813,11 +5818,11 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof() as inventory_probe,):ambiguous = asyncio.run(- adapter.observe_source(- "openai",- base_url,- credential_ref,- SOURCE_PROTOCOLS,+ adapter.observe_source(+ "custom",+ base_url,+ credential_ref,+ SOURCE_PROTOCOLS,))@@ -5847,11 +5852,11 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof() as inventory_probe,):ambiguous = asyncio.run(- adapter.observe_source(- "openai",- base_url,- credential_ref,- SOURCE_PROTOCOLS,+ adapter.observe_source(+ "custom",+ base_url,+ credential_ref,+ SOURCE_PROTOCOLS,))@@ -5883,11 +5888,11 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof() as inventory_probe,):ambiguous = asyncio.run(- adapter.observe_source(- "openai",- base_url,- credential_ref,- SOURCE_PROTOCOLS,+ adapter.observe_source(+ "custom",+ base_url,+ credential_ref,+ SOURCE_PROTOCOLS,))@@ -5917,11 +5922,11 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof() as inventory_probe,):ambiguous = asyncio.run(- adapter.observe_source(- "openai",- base_url,- credential_ref,- SOURCE_PROTOCOLS,+ adapter.observe_source(+ "custom",+ base_url,+ credential_ref,+ SOURCE_PROTOCOLS,))@@ -5957,7 +5962,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():ambiguous = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -5991,7 +5996,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():observed = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -6036,7 +6041,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():ambiguous = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -6070,7 +6075,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():observed = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -6104,7 +6109,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():observed = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -6156,7 +6161,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():rejected = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -6179,20 +6184,20 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),) as inventory_probe,):- ambiguous = asyncio.run(+ observed = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,("anthropic",),))- assert ambiguous.outcome.value == "ambiguous"- assert ambiguous.protocol is None- assert ambiguous.authenticated is True+ assert observed.outcome.value == "observed"+ assert observed.protocol == "anthropic"+ assert observed.authenticated is Trueassert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == ["anthropic"]- inventory_probe.assert_not_awaited()+ assert inventory_probe.await_args.kwargs["protocol"] == "anthropic"async def shaped_server_failure(**kwargs) -> _ProtocolEvidence:if kwargs["protocol"] == "anthropic":@@ -6219,7 +6224,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():upstream_error = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -6265,7 +6270,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():observed = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -6301,7 +6306,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():observed = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -6345,7 +6350,7 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof():rejected = asyncio.run(adapter.observe_source(- "openai",+ "custom",base_url,credential_ref,SOURCE_PROTOCOLS,@@ -6360,161 +6365,829 @@ def test_source_observation_reduces_the_order_at_the_first_authenticated_proof(inventory_probe.assert_not_awaited()-def test_oauth_observation_uses_the_bound_auth_index_and_requires_response_proof(+def test_source_observation_accepts_catalog_pin_and_custom_declaration_without_shape_proof(tmp_path: Path,) -> None:state_store = EngineStateStore(tmp_path / "engine-state")- credential_ref = state_store.bind_oauth_credential(- "src_oauthproof",- "openai",- "codex-test.json",+ catalog_ref = state_store.store_api_key(+ "test-deepseek-key",+ vendor="deepseek",+ protocol="openai_chat",+ base_url=None,+ )+ custom_ref = state_store.store_api_key(+ "test-custom-key",+ vendor="custom",+ protocol="openai_chat",+ base_url="https://api.deepseek.com",)- client = Mock()- api_calls: list[dict] = []-- def management_request(method, path, *, query=None, payload=None):- if path == "/auth-files":- return {- "files": [- {- "id": "codex-test",- "auth_index": "auth-index-test",- "name": "codex-test.json",- "provider": "codex",- "id_token": {"chatgpt_account_id": "account-test"},- }- ]- }- if path == "/api-call":- api_calls.append(payload)- return {- "status_code": 400,- "header": {},- "body": json.dumps(- {- "error": {- "type": "invalid_request_error",- "param": "input",- }- }- ),- }- if path == "/auth-files/models":- assert query == {"name": "codex-test.json"}- return {"models": [{"id": "gpt-5.6"}]}- raise AssertionError((method, path))-- client.management_request.side_effect = management_request- supervisor = Mock()- supervisor.client.return_value = clientadapter = CLIProxyEngineAdapter(- supervisor=supervisor,+ supervisor=Mock(),state_store=state_store,)+ generic_request_accepted = _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ shape=_ProtocolObservationShape.GENERIC_REQUEST_ERROR,+ )- observed = asyncio.run(- adapter.observe_source(- "openai",- None,- credential_ref,- SOURCE_PROTOCOLS,+ async def identical_three_path_shape(**_kwargs) -> _ProtocolEvidence:+ return generic_request_accepted++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(side_effect=identical_three_path_shape),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=(DiscoveredModel(id="deepseek-chat"),)),+ ) as inventory_probe,+ ):+ observed = asyncio.run(+ adapter.observe_source(+ "deepseek",+ None,+ catalog_ref,+ SOURCE_PROTOCOLS,+ ))- )assert observed.outcome.value == "observed"- assert observed.protocol == "openai_responses"- assert observed.model_ids == ("gpt-5.6",)- assert len(api_calls) == 1- assert api_calls[0]["auth_index"] == "auth-index-test"- assert api_calls[0]["header"]["Chatgpt-Account-Id"] == "account-test"- assert api_calls[0]["url"].endswith("/responses")- assert json.loads(api_calls[0]["data"]) == dict(- _PROTOCOL_OBSERVATION_TAXONOMY["openai_responses"].request_body- )-- def ambiguous_management_request(method, path, *, query=None, payload=None):- if path == "/auth-files":- return management_request(method, path, query=query, payload=payload)- if path == "/api-call":- return {"status_code": 200, "header": {}, "body": '{"ok":true}'}- raise AssertionError((method, path))+ assert observed.protocol == "openai_chat"+ assert observed.model_ids == ("deepseek-chat",)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ assert inventory_probe.await_args.kwargs["protocol"] == "openai_chat"- client.management_request.side_effect = ambiguous_management_request- ambiguous = asyncio.run(- adapter.observe_source(- "openai",- None,- credential_ref,- SOURCE_PROTOCOLS,+ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(side_effect=identical_three_path_shape),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),+ ) as inventory_probe,+ ):+ ambiguous = asyncio.run(+ adapter.observe_source(+ "custom",+ "https://api.deepseek.com",+ custom_ref,+ SOURCE_PROTOCOLS,+ ))- )assert ambiguous.outcome.value == "ambiguous"assert ambiguous.protocol is None- assert ambiguous.authenticated is None+ assert ambiguous.authenticated is True+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(SOURCE_PROTOCOLS)+ inventory_probe.assert_not_awaited()+ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(side_effect=identical_three_path_shape),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=(DiscoveredModel(id="deepseek-chat"),)),+ ) as inventory_probe,+ ):+ observed = asyncio.run(+ adapter.observe_source(+ "custom",+ "https://api.deepseek.com",+ custom_ref,+ ("openai_chat",),+ )+ )-DEEPSEEK_AUTHENTICATION_ERROR_PAYLOAD = {- "error": {- "message": "Authentication Fails, Your api key: **** is invalid",- "type": "authentication_error",- "param": None,- "code": "invalid_request_error",- }-}-DEEPSEEK_MODEL_NOT_FOUND_PAYLOAD = {- "error": {- "type": "invalid_request_error",- "param": None,- "code": "model_not_found",- }-}-ANTHROPIC_RELAY_REQUEST_ERROR_PAYLOAD = {- "error": {- "message": "model is required",- "type": "invalid_request_error",- }-}+ assert observed.outcome.value == "observed"+ assert observed.protocol == "openai_chat"+ assert observed.model_ids == ("deepseek-chat",)+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == ["openai_chat"]+ assert inventory_probe.await_args.kwargs["protocol"] == "openai_chat"- ("protocol", "success_body", "request_error_body", "auth_error_body"),- [- (- "anthropic",- {"type": "message"},- {"type": "error", "error": {"type": "invalid_request_error"}},- {"type": "error", "error": {"type": "authentication_error"}},- ),- (- "openai_responses",- {"object": "response"},- {"error": {"type": "invalid_request_error", "param": "input"}},- {- "error": {- "type": "invalid_request_error",- "code": "invalid_api_key",- "param": "input",- }- },- ),- (- "openai_chat",- {"object": "chat.completion"},- {"error": {"type": "invalid_request_error", "param": "messages"}},- {- "error": {- "type": "invalid_request_error",- "code": "invalid_api_key",- "param": "messages",- }- },- ),- ],-)-def test_protocol_evidence_parser_requires_candidate_specific_response_shapes(- protocol: str,- success_body: dict,+def test_qwen_catalog_pin_observation_accepts_wrapperless_authenticated_validation_response(+ tmp_path: Path,+) -> None:+ state_store = EngineStateStore(tmp_path / "engine-state")+ credential_ref = state_store.store_api_key(+ "test-qwen-key",+ vendor="qwen",+ protocol="openai_chat",+ base_url=None,+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=Mock(),+ state_store=state_store,+ )++ async def scenario() -> tuple[list[str], object, dict[str, object]]:+ requests: list[str] = []++ async def capture_probe(request: web.Request) -> web.Response:+ requests.append(request.path)+ if request.path == _PROTOCOL_OBSERVATION_TAXONOMY["openai_chat"].request_path:+ return web.json_response(+ {+ "code": "InvalidParameter",+ "message": "messages is required",+ },+ status=400,+ )+ return web.json_response({}, status=404)++ app = web.Application()+ app.router.add_post("/{tail:.*}", capture_probe)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ assert site._server is not None+ port = site._server.sockets[0].getsockname()[1]+ origin = f"http://127.0.0.1:{port}"+ try:+ with (+ patch.dict(+ "vibe.model_hub_runtime.adapter._OFFICIAL_BASE_URLS",+ {"qwen": origin},+ clear=False,+ ),+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=(DiscoveredModel(id="qwen-plus"),)),+ ) as inventory_probe,+ ):+ observed = await adapter.observe_source(+ "qwen",+ None,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ assert inventory_probe.await_args is not None+ inventory_kwargs = dict(inventory_probe.await_args.kwargs)+ finally:+ await runner.cleanup()+ return requests, observed, inventory_kwargs++ requests, observed, inventory_kwargs = asyncio.run(scenario())++ assert observed.outcome.value == "observed"+ assert observed.protocol == "openai_chat"+ assert observed.authenticated is True+ assert observed.model_ids == ("qwen-plus",)+ assert requests == [+ _PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path+ for protocol in SOURCE_PROTOCOLS+ ]+ assert inventory_kwargs["vendor"] == "qwen"+ assert inventory_kwargs["protocol"] == "openai_chat"+ assert inventory_kwargs["base_url"] is None+++def test_openrouter_catalog_pin_observation_accepts_nested_numeric_authenticated_validation_response(+ tmp_path: Path,+) -> None:+ state_store = EngineStateStore(tmp_path / "engine-state")+ credential_ref = state_store.store_api_key(+ "test-openrouter-key",+ vendor="openrouter",+ protocol="openai_chat",+ base_url=None,+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=Mock(),+ state_store=state_store,+ )++ async def scenario() -> tuple[list[str], object, dict[str, object]]:+ requests: list[str] = []++ async def capture_probe(request: web.Request) -> web.Response:+ requests.append(request.path)+ if request.path == _PROTOCOL_OBSERVATION_TAXONOMY["openai_chat"].request_path:+ return web.json_response(+ {+ "error": {+ "code": 400,+ "message": "messages is required",+ }+ },+ status=400,+ )+ return web.json_response({}, status=404)++ app = web.Application()+ app.router.add_post("/{tail:.*}", capture_probe)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ assert site._server is not None+ port = site._server.sockets[0].getsockname()[1]+ origin = f"http://127.0.0.1:{port}"+ try:+ with (+ patch.dict(+ "vibe.model_hub_runtime.adapter._OFFICIAL_BASE_URLS",+ {"openrouter": origin},+ clear=False,+ ),+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=(DiscoveredModel(id="openrouter/auto"),)),+ ) as inventory_probe,+ ):+ observed = await adapter.observe_source(+ "openrouter",+ None,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ assert inventory_probe.await_args is not None+ inventory_kwargs = dict(inventory_probe.await_args.kwargs)+ finally:+ await runner.cleanup()+ return requests, observed, inventory_kwargs++ requests, observed, inventory_kwargs = asyncio.run(scenario())++ assert observed.outcome.value == "observed"+ assert observed.protocol == "openai_chat"+ assert observed.authenticated is True+ assert observed.model_ids == ("openrouter/auto",)+ assert requests == [+ _PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path+ for protocol in SOURCE_PROTOCOLS+ ]+ assert inventory_kwargs["vendor"] == "openrouter"+ assert inventory_kwargs["protocol"] == "openai_chat"+ assert inventory_kwargs["base_url"] is None+++def _catalog_owner_status_body(vendor: str, status: int) -> dict[str, object]:+ if status == 401 and vendor == "openrouter":+ return {+ "error": {+ "code": 401,+ "message": "Credentials are invalid",+ }+ }+ if status == 400 and vendor == "zhipuai":+ return {+ "error": {+ "code": "1214",+ "message": "messages is required",+ }+ }+ if status == 400 and vendor == "openrouter":+ return {+ "error": {+ "code": 400,+ "message": "invalid API key",+ }+ }+ return {+ "error": {+ "code": f"{vendor}-{status}",+ "message": f"{vendor} response body",+ }+ }+++def _run_catalog_pin_observation(+ tmp_path: Path,+ *,+ vendor: str,+ protocol: str,+ status: int,+ body: dict[str, object],+) -> tuple[list[str], object, dict[str, object] | None]:+ state_store = EngineStateStore(tmp_path / f"engine-state-{vendor}-{status}")+ credential_ref = state_store.store_api_key(+ f"test-{vendor}-{status}",+ vendor=vendor,+ protocol=protocol,+ base_url=None,+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=Mock(),+ state_store=state_store,+ )++ async def scenario() -> tuple[list[str], object, dict[str, object] | None]:+ requests: list[str] = []++ async def capture_probe(request: web.Request) -> web.Response:+ requests.append(request.path)+ return web.json_response(body, status=status)++ app = web.Application()+ app.router.add_post("/{tail:.*}", capture_probe)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ assert site._server is not None+ port = site._server.sockets[0].getsockname()[1]+ origin = f"http://127.0.0.1:{port}"+ try:+ with (+ patch.dict(+ "vibe.model_hub_runtime.adapter._OFFICIAL_BASE_URLS",+ {vendor: origin},+ clear=False,+ ),+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=(DiscoveredModel(id=f"{vendor}/auto"),)),+ ) as inventory_probe,+ ):+ observed = await adapter.observe_source(+ vendor,+ None,+ credential_ref,+ (protocol,),+ )+ inventory_kwargs = (+ dict(inventory_probe.await_args.kwargs)+ if inventory_probe.await_args is not None+ else None+ )+ finally:+ await runner.cleanup()+ return requests, observed, inventory_kwargs++ return asyncio.run(scenario())++[email protected](("vendor", "protocol"), CATALOG_API_KEY_VENDOR_PROTOCOL_CASES)+def test_catalog_pin_observation_accepts_any_nonempty_json_400_response(+ tmp_path: Path,+ vendor: str,+ protocol: str,+) -> None:+ requests, observed, inventory_kwargs = _run_catalog_pin_observation(+ tmp_path,+ vendor=vendor,+ protocol=protocol,+ status=400,+ body=_catalog_owner_status_body(vendor, 400),+ )++ assert observed.outcome.value == "observed"+ assert observed.protocol == protocol+ assert observed.authenticated is True+ assert observed.model_ids == (f"{vendor}/auto",)+ assert requests == [_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path]+ assert inventory_kwargs is not None+ assert inventory_kwargs["vendor"] == vendor+ assert inventory_kwargs["protocol"] == protocol+ assert inventory_kwargs["base_url"] is None++[email protected](("vendor", "protocol"), CATALOG_API_KEY_VENDOR_PROTOCOL_CASES)+def test_catalog_pin_observation_rejects_any_json_401_response(+ tmp_path: Path,+ vendor: str,+ protocol: str,+) -> None:+ requests, observed, inventory_kwargs = _run_catalog_pin_observation(+ tmp_path,+ vendor=vendor,+ protocol=protocol,+ status=401,+ body=_catalog_owner_status_body(vendor, 401),+ )++ assert observed.outcome.value == "authentication_failed"+ assert observed.protocol is None+ assert observed.authenticated is False+ assert observed.model_ids == ()+ assert requests == [_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path]+ assert inventory_kwargs is None+++def test_custom_auto_numeric_auth_failure_message_stays_authentication_failed(+ tmp_path: Path,+) -> None:+ state_store = EngineStateStore(tmp_path / "engine-state-custom-auto")+ adapter = CLIProxyEngineAdapter(+ supervisor=Mock(),+ state_store=state_store,+ )++ async def scenario() -> tuple[list[str], object]:+ requests: list[str] = []++ async def capture_probe(request: web.Request) -> web.Response:+ requests.append(request.path)+ return web.json_response(+ {+ "error": {+ "code": 400,+ "message": "invalid API key",+ }+ },+ status=400,+ )++ app = web.Application()+ app.router.add_post("/{tail:.*}", capture_probe)+ runner = web.AppRunner(app)+ await runner.setup()+ site = web.TCPSite(runner, "127.0.0.1", 0)+ await site.start()+ assert site._server is not None+ port = site._server.sockets[0].getsockname()[1]+ origin = f"http://127.0.0.1:{port}"+ credential_ref = state_store.store_api_key(+ "test-custom-auto-invalid-key",+ vendor="custom",+ protocol="openai_chat",+ base_url=origin,+ )+ try:+ with patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),+ ) as inventory_probe:+ observed = await adapter.observe_source(+ "custom",+ origin,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ inventory_probe.assert_not_awaited()+ finally:+ await runner.cleanup()+ return requests, observed++ requests, observed = asyncio.run(scenario())++ assert observed.outcome.value == "authentication_failed"+ assert observed.protocol is None+ assert observed.authenticated is False+ assert observed.model_ids == ()+ assert requests == [+ _PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path+ for protocol in SOURCE_PROTOCOLS+ ]+++ ("vendor", "base_url", "credential_vendor", "credential_protocol", "protocol_order"),+ [+ ("deepseek", None, "deepseek", "openai_chat", ("openai_chat",)),+ (+ "custom",+ "https://api.deepseek.com",+ "custom",+ "openai_chat",+ ("openai_chat",),+ ),+ ],+ ids=("catalog_pin", "custom_declared"),+)+def test_source_observation_catalog_pin_and_declaration_still_require_authentication(+ tmp_path: Path,+ vendor: str,+ base_url: str | None,+ credential_vendor: str,+ credential_protocol: str,+ protocol_order: tuple[str, ...],+) -> None:+ state_store = EngineStateStore(tmp_path / "engine-state")+ credential_ref = state_store.store_api_key(+ "test-observation-key",+ vendor=credential_vendor,+ protocol=credential_protocol,+ base_url=base_url,+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=Mock(),+ state_store=state_store,+ )+ rejected = _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.REJECTED,+ )++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(return_value=rejected),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),+ ) as inventory_probe,+ ):+ failed = asyncio.run(+ adapter.observe_source(+ vendor,+ base_url,+ credential_ref,+ protocol_order,+ )+ )++ assert failed.outcome.value == "authentication_failed"+ assert failed.protocol is None+ assert failed.authenticated is False+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == list(protocol_order)+ inventory_probe.assert_not_awaited()+++ ("status", "initial_authentication", "expected_outcome", "expected_authenticated"),+ [+ (400, _AuthenticationEvidence.REJECTED, "observed", True),+ (401, _AuthenticationEvidence.ACCEPTED, "authentication_failed", False),+ ],+ ids=("request_error_accepts", "auth_error_rejects"),+)+def test_custom_declared_observation_uses_owner_status_before_parser_verdict(+ tmp_path: Path,+ status: int,+ initial_authentication: _AuthenticationEvidence,+ expected_outcome: str,+ expected_authenticated: bool,+) -> None:+ base_url = "https://relay.example/v1"+ state_store = EngineStateStore(tmp_path / f"engine-state-custom-declared-{status}")+ credential_ref = state_store.store_api_key(+ f"test-custom-declared-{status}",+ vendor="custom",+ protocol="openai_chat",+ base_url=base_url,+ )+ adapter = CLIProxyEngineAdapter(+ supervisor=Mock(),+ state_store=state_store,+ )+ parser_evidence = _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=initial_authentication,+ shape=_ProtocolObservationShape.GENERIC_REQUEST_ERROR,+ status=status,+ )++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_protocol_response",+ new=AsyncMock(return_value=parser_evidence),+ ) as protocol_probe,+ patch(+ "vibe.model_hub_runtime.adapter.probe_models",+ new=AsyncMock(return_value=(DiscoveredModel(id="declared-model"),)),+ ) as inventory_probe,+ ):+ observed = asyncio.run(+ adapter.observe_source(+ "custom",+ base_url,+ credential_ref,+ ("openai_chat",),+ )+ )++ assert observed.outcome.value == expected_outcome+ assert observed.authenticated is expected_authenticated+ assert [call.kwargs["protocol"] for call in protocol_probe.await_args_list] == ["openai_chat"]+ if expected_outcome == "observed":+ assert observed.protocol == "openai_chat"+ assert observed.model_ids == ("declared-model",)+ assert inventory_probe.await_args is not None+ assert inventory_probe.await_args.kwargs["protocol"] == "openai_chat"+ else:+ assert observed.protocol is None+ inventory_probe.assert_not_awaited()+++def test_oauth_observation_uses_the_bound_auth_index_and_requires_response_proof(+ tmp_path: Path,+) -> None:+ state_store = EngineStateStore(tmp_path / "engine-state")+ credential_ref = state_store.bind_oauth_credential(+ "src_oauthproof",+ "openai",+ "codex-test.json",+ )+ client = Mock()+ api_calls: list[dict] = []++ def management_request(method, path, *, query=None, payload=None):+ if path == "/auth-files":+ return {+ "files": [+ {+ "id": "codex-test",+ "auth_index": "auth-index-test",+ "name": "codex-test.json",+ "provider": "codex",+ "id_token": {"chatgpt_account_id": "account-test"},+ }+ ]+ }+ if path == "/api-call":+ api_calls.append(payload)+ return {+ "status_code": 400,+ "header": {},+ "body": json.dumps(+ {+ "error": {+ "type": "invalid_request_error",+ "param": "input",+ }+ }+ ),+ }+ if path == "/auth-files/models":+ assert query == {"name": "codex-test.json"}+ return {"models": [{"id": "gpt-5.6"}]}+ 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,+ )++ observed = asyncio.run(+ adapter.observe_source(+ "openai",+ None,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ assert observed.outcome.value == "observed"+ assert observed.protocol == "openai_responses"+ assert observed.model_ids == ("gpt-5.6",)+ assert len(api_calls) == 1+ assert api_calls[0]["auth_index"] == "auth-index-test"+ assert api_calls[0]["header"]["Chatgpt-Account-Id"] == "account-test"+ assert api_calls[0]["url"].endswith("/responses")+ assert json.loads(api_calls[0]["data"]) == dict(+ _PROTOCOL_OBSERVATION_TAXONOMY["openai_responses"].request_body+ )++ def ambiguous_management_request(method, path, *, query=None, payload=None):+ if path == "/auth-files":+ return management_request(method, path, query=query, payload=payload)+ if path == "/api-call":+ return {"status_code": 200, "header": {}, "body": '{"ok":true}'}+ raise AssertionError((method, path))++ client.management_request.side_effect = ambiguous_management_request+ ambiguous = asyncio.run(+ adapter.observe_source(+ "openai",+ None,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ assert ambiguous.outcome.value == "ambiguous"+ assert ambiguous.protocol is None+ assert ambiguous.authenticated is None+++def test_oauth_observation_does_not_use_api_key_catalog_pins_without_shape_proof(+ tmp_path: Path,+) -> None:+ state_store = EngineStateStore(tmp_path / "engine-state")+ credential_ref = state_store.bind_oauth_credential(+ "src_oauthcatalog",+ "openai",+ "codex-test.json",+ )+ client = Mock()++ def management_request(method, path, *, query=None, payload=None):+ if path == "/auth-files":+ return {+ "files": [+ {+ "id": "codex-test",+ "auth_index": "auth-index-test",+ "name": "codex-test.json",+ "provider": "codex",+ }+ ]+ }+ 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,+ )+ accepted_unproven = _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ shape=_ProtocolObservationShape.GENERIC_REQUEST_ERROR,+ )++ with (+ patch(+ "vibe.model_hub_runtime.adapter._probe_oauth_protocol_response",+ return_value=accepted_unproven,+ ) as oauth_probe,+ patch.object(+ adapter,+ "discover_models",+ new=AsyncMock(return_value=(DiscoveredModel(id="should-not-discover"),)),+ ) as discover_models,+ ):+ ambiguous = asyncio.run(+ adapter.observe_source(+ "openai",+ None,+ credential_ref,+ SOURCE_PROTOCOLS,+ )+ )++ assert ambiguous.outcome.value == "ambiguous"+ assert ambiguous.protocol is None+ assert ambiguous.authenticated is True+ discover_models.assert_not_awaited()+ assert [call.kwargs["protocol"] for call in oauth_probe.call_args_list] == list(SOURCE_PROTOCOLS)+++DEEPSEEK_AUTHENTICATION_ERROR_PAYLOAD = {+ "error": {+ "message": "Authentication Fails, Your api key: **** is invalid",+ "type": "authentication_error",+ "param": None,+ "code": "invalid_request_error",+ }+}+DEEPSEEK_MODEL_NOT_FOUND_PAYLOAD = {+ "error": {+ "type": "invalid_request_error",+ "param": None,+ "code": "model_not_found",+ }+}+ANTHROPIC_RELAY_REQUEST_ERROR_PAYLOAD = {+ "error": {+ "message": "model is required",+ "type": "invalid_request_error",+ }+}+++ ("protocol", "success_body", "request_error_body", "auth_error_body"),+ [+ (+ "anthropic",+ {"type": "message"},+ {"type": "error", "error": {"type": "invalid_request_error"}},+ {"type": "error", "error": {"type": "authentication_error"}},+ ),+ (+ "openai_responses",+ {"object": "response"},+ {"error": {"type": "invalid_request_error", "param": "input"}},+ {+ "error": {+ "type": "invalid_request_error",+ "code": "invalid_api_key",+ "param": "input",+ }+ },+ ),+ (+ "openai_chat",+ {"object": "chat.completion"},+ {"error": {"type": "invalid_request_error", "param": "messages"}},+ {+ "error": {+ "type": "invalid_request_error",+ "code": "invalid_api_key",+ "param": "messages",+ }+ },+ ),+ ],+)+def test_protocol_evidence_parser_requires_candidate_specific_response_shapes(+ protocol: str,+ success_body: dict,request_error_body: dict,auth_error_body: dict,) -> None:@@ -6758,6 +7431,82 @@ def test_openai_request_error_without_family_param_records_accepted_but_unproven)+def test_qwen_wrapperless_invalid_parameter_request_error_counts_as_authenticated_openai_chat() -> None:+ assert _parse_protocol_authenticated_evidence(+ "openai_chat",+ 400,+ json.dumps(+ {+ "code": "InvalidParameter",+ "message": "messages is required",+ }+ ),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ shape=_ProtocolObservationShape.GENERIC_REQUEST_ERROR,+ )++[email protected]("protocol", ("openai_responses", "openai_chat"))+def test_openai_family_nested_numeric_request_error_stays_unknown_before_owner_override(+ protocol: str,+) -> None:+ assert _parse_protocol_authenticated_evidence(+ protocol,+ 400,+ json.dumps(+ {+ "error": {+ "code": 400,+ "message": "missing required parameter",+ }+ }+ ),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )+ assert _parse_protocol_authenticated_evidence(+ protocol,+ 400,+ json.dumps(+ {+ "error": {+ "code": 400,+ "message": "missing required parameter",+ }+ }+ ),+ vendor="openrouter",+ request_root="https://openrouter.ai/api/v1",+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.UNKNOWN,+ )++[email protected]("protocol", ("openai_responses", "openai_chat"))+def test_openai_family_nested_numeric_auth_failure_message_is_rejected(+ protocol: str,+) -> None:+ assert _parse_protocol_authenticated_evidence(+ protocol,+ 400,+ json.dumps(+ {+ "error": {+ "code": 400,+ "message": "invalid API key",+ }+ }+ ),+ ) == _ProtocolEvidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.REJECTED,+ )++@pytest.mark.parametrize("protocol", SOURCE_PROTOCOLS)@pytest.mark.parametrize("status", (400, 422))def test_request_error_with_credential_param_is_rejected(diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 89aa79466..b05cf9661 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -40,6 +40,7 @@ from vibe.model_hub_runtime import adapter as runtime_adapter_modulefrom vibe.model_hub_runtime import client as client_modulefrom vibe.model_hub_runtime import installer as runtime_installer_modulefrom vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter+from vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalogfrom vibe.model_hub_runtime.client import EngineClient, EngineClientError, EngineConnectionfrom vibe.model_hub_runtime.config import write_engine_configfrom vibe.model_hub_runtime.environment import engine_subprocess_environment@@ -76,6 +77,15 @@ RELEASED_INSTALL_CLAIMS = json.loads()["claims"]RUNTIME_INSTALL_GENERATION_A = "a" * 32RUNTIME_INSTALL_GENERATION_B = "b" * 32+API_KEY_VENDOR_RUNTIME_CASES = tuple(+ [+ *[+ pytest.param(entry.id, entry.protocol, entry.official_base_url, id=entry.id)+ for entry in api_key_vendor_catalog()+ ],+ pytest.param("codex", "openai_responses", "https://api.openai.com/v1", id="codex"),+ ]+)def _create_runtime_install_claim(@@ -1388,6 +1398,16 @@ def test_config_generation_is_private_and_never_logs_secrets(vendor="openai",protocol="openai_responses",)+ codex_ref = store.store_api_key(+ "codex-secret-value",+ vendor="codex",+ protocol="openai_responses",+ )+ deepseek_ref = store.store_api_key(+ "deepseek-secret-value",+ vendor="deepseek",+ protocol="openai_chat",+ )store.sync_sources([_binding(credential_ref),@@ -1398,6 +1418,20 @@ def test_config_generation_is_private_and_never_logs_secrets(protocol="openai_responses",base_url=None,),+ _binding(+ codex_ref,+ source_id="src_codexresp1",+ vendor="codex",+ protocol="openai_responses",+ base_url=None,+ ),+ _binding(+ deepseek_ref,+ source_id="src_deepseekcfg",+ vendor="deepseek",+ protocol="openai_chat",+ base_url=None,+ ),])config_path = instance_dir / "config.yaml"@@ -1422,7 +1456,11 @@ def test_config_generation_is_private_and_never_logs_secrets(assert payload["remote-management"]["allow-remote"] is Falseassert payload["remote-management"]["disable-control-panel"] is Trueassert payload["openai-compatibility"][0]["api-key-entries"][0]["api-key"] == ("upstream-secret-value")- assert payload["codex-api-key"][0]["base-url"] == "https://api.openai.com/v1"+ assert {+ entry["base-url"] for entry in payload["openai-compatibility"]+ } == {"https://api.example.test/v1", "https://api.deepseek.com"}+ assert len(payload["codex-api-key"]) == 2+ assert {entry["base-url"] for entry in payload["codex-api-key"]} == {"https://api.openai.com/v1"}assert stat.S_IMODE(config_path.stat().st_mode) == 0o600assert stat.S_IMODE(store.auth_dir.stat().st_mode) == 0o700credential_path = next((store.root / "credentials").iterdir())@@ -1432,6 +1470,8 @@ def test_config_generation_is_private_and_never_logs_secrets(runtime_secrets.gateway_token,"upstream-secret-value","responses-secret-value",+ "codex-secret-value",+ "deepseek-secret-value",):assert secret not in caplog.text@@ -1495,6 +1535,25 @@ def test_state_rejects_unsafe_inputs_and_auth_permissions(tmp_path: Path) -> Non)assert official[0].base_url is None+ official_deepseek_ref = store.store_api_key(+ "secret",+ vendor="deepseek",+ protocol="openai_chat",+ base_url=None,+ )+ official_deepseek = store.sync_sources(+ [+ _binding(+ official_deepseek_ref,+ source_id="src_deepseek01",+ vendor="deepseek",+ protocol="openai_chat",+ base_url=None,+ )+ ]+ )+ assert official_deepseek[0].base_url is None+auth_file = store.auth_dir / "oauth.json"auth_file.write_text("{}", encoding="utf-8")auth_file.chmod(0o644)@@ -1504,6 +1563,76 @@ def test_state_rejects_unsafe_inputs_and_auth_permissions(tmp_path: Path) -> Nonassert stat.S_IMODE(auth_file.stat().st_mode) == 0o600+ ("vendor", "expected_base_url"),+ [+ *[+ pytest.param(entry.id, entry.official_base_url, id=entry.id)+ for entry in api_key_vendor_catalog()+ ],+ pytest.param("codex", "https://api.openai.com/v1", id="codex"),+ ],+)+def test_api_key_vendor_catalog_populates_runtime_official_base_urls(+ vendor: str,+ expected_base_url: str,+) -> None:+ assert client_module._OFFICIAL_BASE_URLS[vendor] == expected_base_url+++ ("vendor", "protocol", "expected_base_url"),+ API_KEY_VENDOR_RUNTIME_CASES,+)+def test_catalog_owned_api_key_sources_without_explicit_base_url_sync_and_write_engine_config(+ tmp_path: Path,+ vendor: str,+ protocol: str,+ expected_base_url: str,+) -> None:+ source_suffix = "".join(character for character in vendor.lower() if character.isalnum())+ source_id = f"src_{(source_suffix + '12345678')[:8]}"+ store = EngineStateStore(tmp_path / "state")+ instance_dir, runtime_secrets = store.prepare_instance("install-1")+ credential_ref = store.store_api_key(+ "secret",+ vendor=vendor,+ protocol=protocol,+ base_url=None,+ )+ store.sync_sources(+ [+ _binding(+ credential_ref,+ source_id=source_id,+ vendor=vendor,+ protocol=protocol,+ base_url=None,+ )+ ]+ )+ config_path = instance_dir / "config.yaml"++ write_engine_config(+ config_path,+ host="127.0.0.1",+ port=18231,+ auth_dir=store.auth_dir,+ runtime_secrets=runtime_secrets,+ sources=store.list_sources(),+ state_store=store,+ )++ payload = yaml.safe_load(config_path.read_text(encoding="utf-8"))+ if protocol == "anthropic":+ assert payload["claude-api-key"][0]["base-url"] == expected_base_url+ return+ if protocol == "openai_responses":+ assert payload["codex-api-key"][0]["base-url"] == expected_base_url+ return+ assert payload["openai-compatibility"][0]["base-url"] == expected_base_url++def test_state_removes_secret_bearing_configs_on_upgrade_and_revocation(tmp_path: Path) -> None:store = EngineStateStore(tmp_path / "state")old_instance, _ = store.prepare_instance("install-old")diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex ea2a8a913..b23923022 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1370,7 +1370,7 @@"field": {"name": "Name (optional)","protocol": "Interface type",- "protocol.hint": "Use Auto detect when unsure; choose a type to validate only that interface",+ "protocol.hint": "Use Auto detect when unsure; choose a type to declare that interface. If authentication succeeds it can be added, a wrong choice can fail at runtime, and the saved type cannot be changed","baseUrl": "Base URL","baseUrl.hint": "API root, such as https://api.example.com/v1; a bare host uses the standard /v1 path","apiKey": "API key",@@ -1403,7 +1403,7 @@"retry": "Retry","undetermined": {"title": "Connected and authenticated — but we cannot tell which interface it speaks",- "detail": "This response shape matches no interface we know; choosing one only narrows the retry probe, and the endpoint still has to prove the interface in its response"+ "detail": "This response shape matches no interface we know. Choose a concrete type and retry: if authentication succeeds on that path it can be added, but a wrong choice can fail at runtime and the saved type cannot be changed"},"protocol": {"auto": "Auto detect",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex e56e9bf22..0caa0bf20 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1370,7 +1370,7 @@"field": {"name": "名称(可选)","protocol": "接口类型",- "protocol.hint": "不确定时用自动探测;已知类型时只验证所选接口",+ "protocol.hint": "不确定时用自动探测;已知类型时可直接声明所选接口。该路径鉴权成功即可添加;选错了运行时可能失败,而且保存后不可更改","baseUrl": "Base URL","baseUrl.hint": "填写 API 根地址,例如 https://api.example.com/v1;只填域名时使用标准 /v1 路径","apiKey": "API Key",@@ -1403,7 +1403,7 @@"retry": "重试","undetermined": {"title": "连上了、也通过了鉴权 —— 但认不出它说哪种接口",- "detail": "这次返回结构对不上任何一种已知接口;手动选择只会缩小重试探测范围,仍要由该地址返回的响应把接口类型证明出来"+ "detail": "这次返回结构对不上任何一种已知接口。请选择一个明确类型后重试:只要该路径鉴权成功即可添加;但选错了运行时可能失败,而且保存后不可更改"},"protocol": {"auto": "自动探测",diff --git a/vibe/data/api_key_vendors.json b/vibe/data/api_key_vendors.jsonnew file mode 100644index 000000000..fda5a836c--- /dev/null+++ b/vibe/data/api_key_vendors.json@@ -0,0 +1,74 @@+[+ {+ "id": "deepseek",+ "label": "DeepSeek",+ "official_base_url": "https://api.deepseek.com",+ "protocol": "openai_chat"+ },+ {+ "id": "qwen",+ "label": "Qwen",+ "official_base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",+ "protocol": "openai_chat"+ },+ {+ "id": "kimi",+ "label": "Kimi",+ "official_base_url": "https://api.moonshot.cn/v1",+ "protocol": "openai_chat"+ },+ {+ "id": "zhipuai",+ "label": "Zhipu AI",+ "official_base_url": "https://open.bigmodel.cn/api/paas/v4",+ "protocol": "openai_chat"+ },+ {+ "id": "openai",+ "label": "OpenAI",+ "official_base_url": "https://api.openai.com/v1",+ "protocol": "openai_responses"+ },+ {+ "id": "anthropic",+ "label": "Anthropic",+ "official_base_url": "https://api.anthropic.com",+ "protocol": "anthropic"+ },+ {+ "id": "openrouter",+ "label": "OpenRouter",+ "official_base_url": "https://openrouter.ai/api/v1",+ "protocol": "openai_chat"+ },+ {+ "id": "groq",+ "label": "Groq",+ "official_base_url": "https://api.groq.com/openai/v1",+ "protocol": "openai_chat"+ },+ {+ "id": "mistral",+ "label": "Mistral",+ "official_base_url": "https://api.mistral.ai/v1",+ "protocol": "openai_chat"+ },+ {+ "id": "xai",+ "label": "xAI",+ "official_base_url": "https://api.x.ai/v1",+ "protocol": "openai_chat"+ },+ {+ "id": "together",+ "label": "Together",+ "official_base_url": "https://api.together.xyz/v1",+ "protocol": "openai_chat"+ },+ {+ "id": "fireworks",+ "label": "Fireworks",+ "official_base_url": "https://api.fireworks.ai/inference/v1",+ "protocol": "openai_chat"+ }+]diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex cffc73f07..4f4490e26 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import reimport secretsimport threadingimport uuid@@ -41,6 +42,7 @@ from vibe.model_hub_runtime.client import (probe_models,upstream_api_url,)+from vibe.model_hub_runtime.api_key_vendors import pinned_api_key_protocolfrom vibe.model_hub_runtime.installer import InstallClaimTransitionfrom vibe.model_hub_runtime.state import EngineStateError, EngineStateStorefrom vibe.model_hub_runtime.supervisor import (@@ -93,6 +95,7 @@ class _ProtocolEvidence:protocol: _ProtocolProofauthentication: _AuthenticationEvidenceshape: _ProtocolObservationShape = _ProtocolObservationShape.NONE+ status: int | None = field(default=None, compare=False)@dataclass(frozen=True)@@ -207,6 +210,17 @@ _CREDENTIAL_ERROR_PARAMS = frozenset("x-token",})+_CREDENTIAL_ERROR_MESSAGE_TOKENS = frozenset(+ {+ "authentication",+ "auth_failed",+ "invalid_api_key",+ "api_key_not_valid",+ "missing_api_key",+ "no_api_key",+ "unauthorized",+ }+)_PAIRWISE_EXCLUSION_SHAPES = frozenset({_ProtocolObservationShape.HTTP_404,@@ -214,6 +228,8 @@ _PAIRWISE_EXCLUSION_SHAPES = frozenset(_ProtocolObservationShape.UNSTRUCTURED,})+_IDENTIFIER_SEPARATOR_RE = re.compile(r"[^0-9A-Za-z]+")+_CAMEL_CASE_BOUNDARY_RE = re.compile(r"(?<=[0-9a-z])(?=[A-Z])")def _openai_evidence_rules(@@ -344,10 +360,21 @@ _PROTOCOL_OBSERVATION_TAXONOMY = {def _error_identifiers(error: Mapping[str, Any]) -> frozenset[str]:+ return _payload_identifiers(error)+++def _normalized_identifier(value: str) -> str:+ normalized = _CAMEL_CASE_BOUNDARY_RE.sub("_", value.strip())+ normalized = _IDENTIFIER_SEPARATOR_RE.sub("_", normalized).strip("_").lower()+ return normalized+++def _payload_identifiers(payload: Mapping[str, Any]) -> frozenset[str]:return frozenset(- value.strip().lower()- for value in (error.get("type"), error.get("code"))+ normalized+ for value in (payload.get("type"), payload.get("code"))if isinstance(value, str)+ if (normalized := _normalized_identifier(value)))@@ -359,6 +386,13 @@ def _error_param_name(error: Mapping[str, Any]) -> str | None:return normalized or None+def _error_message_indicates_credential_rejection(message: object) -> bool:+ if not isinstance(message, str) or not message.strip():+ return False+ normalized = _normalized_identifier(message)+ return any(token in normalized for token in _CREDENTIAL_ERROR_MESSAGE_TOKENS)++def _request_error_rejects_credential(status: int,error: Mapping[str, Any] | None,@@ -366,7 +400,11 @@ def _request_error_rejects_credential(return (status in _REQUEST_ERROR_STATUSESand isinstance(error, dict)- and _error_param_name(error) in _CREDENTIAL_ERROR_PARAMS+ and (+ _error_param_name(error) in _CREDENTIAL_ERROR_PARAMS+ or not _AUTHENTICATION_ERROR_IDENTIFIERS.isdisjoint(_error_identifiers(error))+ or _error_message_indicates_credential_rejection(error.get("message"))+ ))@@ -404,6 +442,28 @@ def _anthropic_wrapperless_error_kind(return None+def _openai_wrapperless_error_kind(+ status: int,+ payload: Mapping[str, Any],+) -> str | None:+ if isinstance(payload.get("error"), dict):+ return None+ identifiers = _payload_identifiers(payload)+ if not identifiers:+ return None+ if status in _REQUEST_ERROR_STATUSES and not (+ _REQUEST_ERROR_IDENTIFIERS | _MODEL_ERROR_IDENTIFIERS+ ).isdisjoint(identifiers):+ return "accepted"+ if status in _AUTHENTICATION_ERROR_STATUSES and not _AUTHENTICATION_ERROR_IDENTIFIERS.isdisjoint(identifiers):+ return "rejected"+ if status in _SERVER_ERROR_STATUSES and not _SERVER_ERROR_IDENTIFIERS.isdisjoint(identifiers):+ return "unknown"+ if status in _RATE_LIMIT_STATUSES and not _RATE_LIMIT_ERROR_IDENTIFIERS.isdisjoint(identifiers):+ return "unknown"+ return None++def _default_unproven_shape(*,status: int,@@ -425,52 +485,58 @@ def _parse_protocol_authenticated_evidence(protocol: str,status: int,body: str | bytes,+ *,+ vendor: str | None = None,+ request_root: str | None = None,) -> _ProtocolEvidence:- """Classify protocol proof and authentication as independent evidence.-- Observation is sequential and stops at the first authenticated proof.- Status, vendor, URL, and probe order never prove a protocol or credential- by themselves; a generic response therefore remains unproven even when its- HTTP status is conventionally associated with authentication or validation.- A structured authentication error may prove credential rejection without- distinguishing the attempted OpenAI protocol. Accepted, rejected, and unknown- are all positive table entries; there is no default authentication result for- a shaped response. The observation result exposes a non-null protocol if and- only if a protocol-specific response shape also proves authentication- acceptance.+ """Classify response-shaped protocol proof and table-driven auth evidence.++ This parser never upgrades a generic response into a protocol owner on its+ own. ``observe_source()`` may later apply the September 4, 2026 owner-based+ ladder for shipped vendor pins and concrete `custom` declarations after the+ constrained path has responded. `custom` Auto detect still relies on this+ parser's response evidence alone."""+ def evidence(+ protocol: _ProtocolProof,+ authentication: _AuthenticationEvidence,+ shape: _ProtocolObservationShape = _ProtocolObservationShape.NONE,+ ) -> _ProtocolEvidence:+ return _ProtocolEvidence(+ protocol=protocol,+ authentication=authentication,+ shape=shape,+ status=status,+ )+try:payload = json.loads(body)except (TypeError, UnicodeDecodeError, ValueError):- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.UNPROVEN,authentication=_AuthenticationEvidence.UNKNOWN,shape=_default_unproven_shape(status=status, non_json=True),)if not isinstance(payload, dict):- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.UNPROVEN,authentication=_AuthenticationEvidence.UNKNOWN,shape=_default_unproven_shape(status=status),)- top_level_identifiers = {- value.strip().lower()- for value in (payload.get("type"), payload.get("code"))- if isinstance(value, str)- }+ top_level_identifiers = _payload_identifiers(payload)if (status in _AUTHENTICATION_ERROR_STATUSESand not _AUTHENTICATION_ERROR_IDENTIFIERS.isdisjoint(top_level_identifiers)):- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.UNPROVEN,authentication=_AuthenticationEvidence.REJECTED,)error = payload.get("error")if _request_error_rejects_credential(status, error):- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.UNPROVEN,authentication=_AuthenticationEvidence.REJECTED,)@@ -478,18 +544,18 @@ def _parse_protocol_authenticated_evidence(if protocol == "anthropic":wrapperless = _anthropic_wrapperless_error_kind(status, payload)if wrapperless == "accepted":- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.UNPROVEN,authentication=_AuthenticationEvidence.ACCEPTED,shape=_ProtocolObservationShape.GENERIC_REQUEST_ERROR,)if wrapperless == "rejected":- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.UNPROVEN,authentication=_AuthenticationEvidence.REJECTED,)if wrapperless == "unknown":- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.UNPROVEN,authentication=_AuthenticationEvidence.UNKNOWN,)@@ -497,12 +563,19 @@ def _parse_protocol_authenticated_evidence(taxonomy = _PROTOCOL_OBSERVATION_TAXONOMY.get(protocol)for rule in taxonomy.evidence_rules if taxonomy is not None else ():if rule.matches(status, payload):- return _ProtocolEvidence(+ return evidence(protocol=rule.protocol,authentication=rule.authentication,shape=rule.shape,)if protocol in _OPENAI_FAMILY_PROTOCOLS and status in _REQUEST_ERROR_STATUSES:+ wrapperless = _openai_wrapperless_error_kind(status, payload)+ if wrapperless == "accepted":+ return evidence(+ protocol=_ProtocolProof.UNPROVEN,+ authentication=_AuthenticationEvidence.ACCEPTED,+ shape=_ProtocolObservationShape.GENERIC_REQUEST_ERROR,+ )if isinstance(error, dict):identifiers = _error_identifiers(error)if (@@ -510,17 +583,17 @@ def _parse_protocol_authenticated_evidence(and _AUTHENTICATION_ERROR_IDENTIFIERS.isdisjoint(identifiers)and _error_param_name(error) not in _OPENAI_FAMILY_PARAMS):- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.UNPROVEN,authentication=_AuthenticationEvidence.ACCEPTED,shape=_ProtocolObservationShape.GENERIC_REQUEST_ERROR,)if _response_shape_proves_protocol(protocol, payload):- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.PROVEN,authentication=_AuthenticationEvidence.UNKNOWN,)- return _ProtocolEvidence(+ return evidence(protocol=_ProtocolProof.UNPROVEN,authentication=_AuthenticationEvidence.UNKNOWN,shape=_default_unproven_shape(status=status, payload=payload),@@ -572,6 +645,8 @@ async def _probe_protocol_response(protocol,response.status,body,+ vendor=vendor,+ request_root=root,)except asyncio.TimeoutError:raise EngineClientError("protocol observation timed out", error_type="timeout") from None@@ -676,6 +751,21 @@ def _pairwise_positive_exclusion(evidence: _ProtocolEvidence) -> bool:)+def _protocol_is_persistable_without_shape_proof(+ *,+ credential_kind: str,+ vendor: str,+ protocol: str,+ protocol_order: Sequence[str],+) -> bool:+ if credential_kind != "api_key":+ return False+ pinned_protocol = pinned_api_key_protocol(vendor)+ if pinned_protocol == protocol:+ return True+ return vendor == "custom" and len(protocol_order) == 1 and protocol_order[0] == protocol++def _anthropic_wrapperless_elimination_proof(responses: Mapping[str, _ProtocolEvidence],*,@@ -766,6 +856,7 @@ def _probe_oauth_protocol_response(protocol,status,body if isinstance(body, str) else "",+ vendor=vendor,)@@ -1428,14 +1519,18 @@ class CLIProxyEngineAdapter:credential_ref: str,protocol_order: Sequence[str],) -> SourceObservation:- """Observe sequentially and stop at the first authenticated proof.+ """Observe sequentially and stop at the first persistable proof.``protocol_order`` orders attempts only. A protocol-specific responsewith accepted authentication proves the current attempt and terminates- observation. A shaped credential rejection is recorded while later- candidates continue. Vendor, URL, and order never create a conclusion;- exhausting the order without any shaped response is the ambiguous- boundary. This is the require-proven reading of AC-27.+ observation. A shipped vendor catalog pin or a concrete `custom`+ declaration also terminates observation once that exact protocol path+ returns an owner-scoped auth status: 401/403 reject, while 2xx and+ request-error 400/404/422 accept even when the response shape stays+ generic. A shaped credential rejection is recorded while later+ candidates continue on Auto detect. Vendor, URL, and order never create+ a conclusion on their own; `custom` Auto still requires response-backed+ proof, and exhausting that path without one remains ambiguous."""metadata = await asyncio.to_thread(@@ -1499,6 +1594,33 @@ class CLIProxyEngineAdapter:except EngineClientError as exc:failures.append(exc)continue+ owner_scoped_protocol = _protocol_is_persistable_without_shape_proof(+ credential_kind=str(credential_kind),+ vendor=normalized_vendor,+ protocol=protocol,+ protocol_order=protocol_order,+ )+ owner_rejected = (+ owner_scoped_protocol+ and evidence.status in _AUTHENTICATION_ERROR_STATUSES+ )+ owner_accepted = (+ owner_scoped_protocol+ and (+ evidence.status in _SUCCESS_STATUSES+ or evidence.status in _REQUEST_ERROR_STATUSES+ )+ )+ if owner_rejected:+ evidence = replace(+ evidence,+ authentication=_AuthenticationEvidence.REJECTED,+ )+ elif owner_accepted:+ evidence = replace(+ evidence,+ authentication=_AuthenticationEvidence.ACCEPTED,+ )if evidence.authentication is _AuthenticationEvidence.REJECTED:received_rejection = Trueruled_out_protocols.add(protocol)@@ -1513,10 +1635,13 @@ class CLIProxyEngineAdapter:received_unproven_response = Trueif evidence.authentication is _AuthenticationEvidence.ACCEPTED:received_accepted_unproven_response = True+ if owner_scoped_protocol:+ proved_protocol = protocolif _pairwise_positive_exclusion(evidence):ruled_out_protocols.add(protocol)response_evidence_by_protocol[protocol] = evidence- continue+ if proved_protocol is None:+ continuetry:if credential_kind == "api_key":models = await probe_models(diff --git a/vibe/model_hub_runtime/api_key_vendors.py b/vibe/model_hub_runtime/api_key_vendors.pynew file mode 100644index 000000000..a2e104ae4--- /dev/null+++ b/vibe/model_hub_runtime/api_key_vendors.py@@ -0,0 +1,102 @@+"""Shared shipped api-key vendor catalog for Model Hub observation."""++from __future__ import annotations++import json+from dataclasses import dataclass+from functools import lru_cache+from pathlib import Path++from config.v2_config import normalize_model_hub_base_url, normalize_model_hub_vendor_id+++_SUPPORTED_PROTOCOLS = {"anthropic", "openai_responses", "openai_chat"}+_LEGACY_OFFICIAL_BASE_URLS = {+ # ``codex`` remains a supported legacy vendor alias outside the shipped+ # api-key vendor preset catalog. Runtime official-URL fallback must keep+ # treating it like OpenAI for persisted Sources that omit ``base_url``.+ "codex": "https://api.openai.com/v1",+}+++@dataclass(frozen=True)+class APIKeyVendorCatalogEntry:+ id: str+ label: str+ official_base_url: str+ protocol: str+++def _catalog_path() -> Path:+ return Path(__file__).resolve().parents[1] / "data" / "api_key_vendors.json"+++@lru_cache(maxsize=1)+def api_key_vendor_catalog() -> tuple[APIKeyVendorCatalogEntry, ...]:+ payload = json.loads(_catalog_path().read_text(encoding="utf-8"))+ if not isinstance(payload, list):+ raise ValueError("api-key vendor catalog is invalid")++ entries: list[APIKeyVendorCatalogEntry] = []+ seen_ids: set[str] = set()+ for item in payload:+ if not isinstance(item, dict):+ raise ValueError("api-key vendor catalog is invalid")+ vendor_id = normalize_model_hub_vendor_id(item.get("id"))+ label = item.get("label")+ protocol = item.get("protocol")+ official_base_url = normalize_model_hub_base_url(item.get("official_base_url"))+ if (+ vendor_id == "custom"+ or vendor_id in seen_ids+ or not isinstance(label, str)+ or not label.strip()+ or not isinstance(protocol, str)+ or protocol not in _SUPPORTED_PROTOCOLS+ or official_base_url is None+ ):+ raise ValueError("api-key vendor catalog is invalid")+ entries.append(+ APIKeyVendorCatalogEntry(+ id=vendor_id,+ label=label.strip(),+ official_base_url=official_base_url,+ protocol=protocol,+ )+ )+ seen_ids.add(vendor_id)+ return tuple(entries)+++@lru_cache(maxsize=1)+def _catalog_by_id() -> dict[str, APIKeyVendorCatalogEntry]:+ return {entry.id: entry for entry in api_key_vendor_catalog()}+++def api_key_vendor_entry(vendor: str) -> APIKeyVendorCatalogEntry | None:+ return _catalog_by_id().get(vendor.strip().lower())+++def pinned_api_key_protocol(vendor: str) -> str | None:+ entry = api_key_vendor_entry(vendor)+ return entry.protocol if entry is not None else None+++def catalog_api_key_vendor_label(vendor: str) -> str | None:+ entry = api_key_vendor_entry(vendor)+ return entry.label if entry is not None else None+++def official_api_key_base_url(vendor: str) -> str | None:+ normalized_vendor = vendor.strip().lower()+ entry = _catalog_by_id().get(normalized_vendor)+ if entry is not None:+ return entry.official_base_url+ return _LEGACY_OFFICIAL_BASE_URLS.get(normalized_vendor)+++def official_api_key_base_urls() -> dict[str, str]:+ return {+ **{entry.id: entry.official_base_url for entry in api_key_vendor_catalog()},+ **_LEGACY_OFFICIAL_BASE_URLS,+ }diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 4c98d0357..f3ef40314 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -40,6 +40,7 @@ from core.handlers.model_hub.stream_wire import (ProtocolUsageReport,observe_buffered_protocol_response,)+from vibe.model_hub_runtime.api_key_vendors import official_api_key_base_urlsfrom vibe.model_hub_runtime.state import SourceRecord@@ -48,11 +49,7 @@ _STREAM_CHUNK_BYTES = 64 * 1024# truncates upstream response bytes._PRELUDE_MEMORY_BYTES = 256 * 1024_ERROR_OBSERVATION_BYTES = 256 * 1024-_OFFICIAL_BASE_URLS = {- "anthropic": "https://api.anthropic.com/v1",- "openai": "https://api.openai.com/v1",- "codex": "https://api.openai.com/v1",-}+_OFFICIAL_BASE_URLS = official_api_key_base_urls()_PROTOCOL_HEADERS = frozenset({"anthropic-beta", "anthropic-version", "openai-beta"})logger = logging.getLogger(__name__)_ProjectedJSON = TypeVar("_ProjectedJSON")diff --git a/vibe/model_hub_runtime/config.py b/vibe/model_hub_runtime/config.pyindex 7917ee1fc..a80e6d48b 100644--- a/vibe/model_hub_runtime/config.py+++ b/vibe/model_hub_runtime/config.py@@ -6,6 +6,7 @@ from typing import Any, Iterableimport yamlfrom config.atomic_io import write_atomic+from vibe.model_hub_runtime.api_key_vendors import official_api_key_base_urlfrom vibe.model_hub_runtime.state import EngineStateError, EngineStateStore, RuntimeSecrets, SourceRecord@@ -71,17 +72,20 @@ def _append_source(payload: dict[str, Any], source: SourceRecord, store: EngineSapi_key = store.read_api_key(source.credential_ref)models = [{"name": model, "alias": model} for model in source.model_ids]if source.protocol == "anthropic":- entry: dict[str, Any] = {"api-key": api_key, "prefix": source.prefix}+ base_url = source.base_url+ if not base_url:+ base_url = official_api_key_base_url(source.vendor)+ if not base_url:+ raise EngineStateError("Anthropic-compatible source requires a base URL")+ entry: dict[str, Any] = {"api-key": api_key, "prefix": source.prefix, "base-url": base_url}if models:entry["models"] = models- if source.base_url:- entry["base-url"] = source.base_urlpayload.setdefault("claude-api-key", []).append(entry)returnif source.protocol == "openai_responses":base_url = source.base_url- if not base_url and source.vendor in {"openai", "codex"}:- base_url = "https://api.openai.com/v1"+ if not base_url:+ base_url = official_api_key_base_url(source.vendor)if not base_url:raise EngineStateError("Responses API source requires a base URL")entry = {"api-key": api_key, "prefix": source.prefix, "base-url": base_url}@@ -91,8 +95,8 @@ def _append_source(payload: dict[str, Any], source: SourceRecord, store: EngineSreturnif source.protocol == "openai_chat":base_url = source.base_url- if not base_url and source.vendor == "openai":- base_url = "https://api.openai.com/v1"+ if not base_url:+ base_url = official_api_key_base_url(source.vendor)if not base_url:raise EngineStateError("OpenAI-compatible source requires a base URL")payload.setdefault("openai-compatibility", []).append(diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex c1eea612a..1969e888f 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -12,6 +12,7 @@ from typing import Any, Sequencefrom config.atomic_io import write_atomicfrom config.v2_config import normalize_model_hub_base_url+from vibe.model_hub_runtime.api_key_vendors import pinned_api_key_protocol_CREDENTIAL_REF_RE = re.compile(r"^cred_[A-Za-z0-9_-]{6,128}$")@@ -499,9 +500,25 @@ def _validated_base_url(value: str | None) -> str | None:def _validate_source_target(vendor: str, protocol: str, base_url: str | None) -> None:- if protocol == "anthropic" and base_url is None and vendor != "anthropic":+ pinned_protocol = pinned_api_key_protocol(vendor)+ if (+ protocol == "anthropic"+ and base_url is None+ and vendor != "anthropic"+ and pinned_protocol != "anthropic"+ ):raise EngineStateError("Anthropic-compatible source requires a base URL")- if protocol == "openai_responses" and base_url is None and vendor not in {"openai", "codex"}:+ if (+ protocol == "openai_responses"+ and base_url is None+ and vendor not in {"openai", "codex"}+ and pinned_protocol != "openai_responses"+ ):raise EngineStateError("Responses API source requires a base URL")- if protocol == "openai_chat" and base_url is None and vendor != "openai":+ if (+ protocol == "openai_chat"+ and base_url is None+ and vendor != "openai"+ and pinned_protocol != "openai_chat"+ ):raise EngineStateError("OpenAI-compatible source requires a base URL")