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
fix(model-hub): verify pinned and declared api keys from their model listing (#1936)
Max5db73f70e0cb
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 7ed75a067..5c8fceee5 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -2884,7 +2884,15 @@ class ModelHubService:detail="modelHub.errors.inventory_unavailable",data={"observation": self._observation_payload(observation)},)- self._mark_source_unverified(source)+ if observation is None:+ # The marker records that nothing upstream has accepted this+ # credential yet, so the first successful call can retire it.+ # An observation reaching here is authenticated -- the terminal+ # product admits no other `observed` -- and that acceptance is+ # what the marker was waiting for; keeping it on a Source the+ # user just watched verify would make it mean something else.+ # Only the explicit unverified save arrives with none.+ self._mark_source_unverified(source)if observation is not None:source.protocol = cast(Literal["anthropic", "openai_responses", "openai_chat"],diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.mdindex 96d8d3619..ff3e2da3b 100644--- a/docs/plans/model-hub-contracts/README.md+++ b/docs/plans/model-hub-contracts/README.md@@ -72,13 +72,16 @@ No underlying engine expansion or OAuth alias substitution is part of this changnormally repeats observation before committed credential provisioning. Explicit`save_unverified: true` permits a catalog pin or declaration without observation;custom Auto still cannot be guessed. Completed Hub OAuth consent can retain its- bound credential under the fixed vendor protocol. Every newly stored Hub- credential, including observed creates and native-config imports, carries an- opaque `verification_pending` identity until an actual matching-credential- model call succeeds. Its clearing is a fresh cross-process field mutation;- model discovery never clears it. A typed Base URL never+ bound credential under the fixed vendor protocol. A newly stored Hub credential+ that no add-time observation authenticated — an explicit unverified save, a+ native-config import, Hub OAuth admission, any credential or endpoint replacement —+ carries an opaque `verification_pending` identity until an actual+ matching-credential model call succeeds. Its clearing is a fresh cross-process+ field mutation; model discovery never clears it. A typed Base URL neversupplies protocol ownership. Model-free validation, altered-credential controls- and public model lists do not prove authentication. See the 2026-09-07 ruling+ and publicly readable model lists do not prove authentication; on a protocol that+ already has an owner, a model listing that answers the credential while refusing+ the identical uncredentialed request does. See the 2026-09-07 rulingsin `docs/plans/model-hub.md` and the create/Source schemas for the complete policy.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 pairsdiff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex d6f1a84e9..9d91f3074 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -25,7 +25,7 @@ remain readable; ephemeral envelopes use only the terminal version.| 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. 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/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. On a catalog pin or a `custom` declaration, an `api_key` whose probe left authentication unknown is settled by that protocol's model listing: authenticated when the listing answers the credential and refuses the identical uncredentialed request, in which case the same response is the reported inventory; rejected on `401`/`403`; otherwise unchanged. Auto is never offered the listing. 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. Default placement is committed before effective adoption is projected; manual overrides are unchanged. 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. |@@ -121,8 +121,9 @@ is rejected before credential provisioning. Manual models remain manual; no inveis invented. The Source carries an opaque `verification_pending` marker, independently of itsrouting health, and may be configured and invoked. List/detail surfaces label itunverified, not healthy/in use. Successful inventory discovery never clears this flag.-Every newly stored Hub credential starts pending, including observed creates and-native-config imports. A call captures the persisted marker before invocation; any+A newly stored Hub credential starts pending unless an add-time observation+authenticated it, so an explicit unverified save and a native-config import always+start pending while an observed api-key create does not. A call captures the persisted marker before invocation; anysuccessful call using the same current credential and marker clears it through afresh cross-process config transaction. Newer same-credential attempts do not negatesuccess. Credential/endpoint replacement generates a new marker, including same-handle@@ -211,9 +212,12 @@ The observation result has six terminal outcomes: `observed`, `ambiguous`,`protocol` is non-null only when authentication succeeds and one rung establishes thetransport 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 a-shaped success or a shaped request-level error that occurs after authentication;-shaped authentication errors are rejected. Shaped server and rate-limit errors-prove reachability but not authentication, so they settle as `adapter_error` with+shaped success, a shaped request-level error that occurs after authentication, or —+where a pin or declaration already owns the protocol — a model listing that answers+the credential and refuses the identical uncredentialed request;+shaped authentication errors are rejected, as is that listing answering `401`/`403`.+Shaped server and rate-limit errors+prove reachability but not authentication, so absent an accepting listing they settle as `adapter_error` with`reachable: true`, `authenticated: unknown`, and `protocol: null`. A local adapterfailure may use the same outcome with `reachable: null`. A bare HTTP status provesreachability, but proves neither protocol nor authentication. Consequently,diff --git a/docs/plans/model-hub-contracts/observation-result.schema.json b/docs/plans/model-hub-contracts/observation-result.schema.jsonindex b64e1d9b3..4fe8225c0 100644--- a/docs/plans/model-hub-contracts/observation-result.schema.json+++ b/docs/plans/model-hub-contracts/observation-result.schema.json@@ -2,7 +2,7 @@"$schema": "http://json-schema.org/draft-07/schema#","$id": "model-hub/observation-result.schema.json","title": "SourceObservation",- "description": "Response-backed result of the unsaved Source observation. It never contains a credential reference or persisted Source state. Any upstream response proves reachability, but a bare HTTP status proves neither protocol nor authentication. A shaped success can establish authentication; schema errors cannot, because they can precede authentication. No synthetic credential control or public model inventory upgrades that evidence. Shaped authentication errors reject their candidate; unknown sibling candidates in Auto remain unknown. Shaped request, server and rate-limit errors leave authentication unknown and settle as adapter_error rather than observed. Explicit unverified Source creation is separate from this result and never changes its evidence.",+ "description": "Response-backed result of the unsaved Source observation. It never contains a credential reference or persisted Source state. Any upstream response proves reachability, but a bare HTTP status proves neither protocol nor authentication. A shaped success can establish authentication; schema errors cannot, because they can precede authentication. No synthetic credential control and no publicly readable model inventory upgrades that evidence. Where the protocol already has an owner, an api_key candidate the probe left unknown is settled by that protocol's model listing: a listing that answers the credential while refusing the identical uncredentialed request authenticates it and supplies the discovered inventory, 401/403 there rejects it, and every other answer leaves the probe's result unchanged. Shaped authentication errors reject their candidate; unknown sibling candidates in Auto remain unknown, and Auto is never offered the listing because a listing names no protocol. Shaped request, server and rate-limit errors leave authentication unknown and settle as adapter_error rather than observed unless that listing accepts the credential. Explicit unverified Source creation is separate from this result and never changes its evidence.","type": "object","required": ["contract_version",diff --git a/docs/plans/model-hub-contracts/source-create.schema.json b/docs/plans/model-hub-contracts/source-create.schema.jsonindex 50e406c50..d3087432d 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. The default path requires authenticated observation and a protocol established by a shipped catalog pin, a declaration on custom, or matching response proof. Explicit save_unverified consent instead persists configuration with verification pending, without observation, attempts best-effort inventory discovery, and requires a catalog pin or a concrete custom declaration. The server owns Source identity, discovered inventory, health, usage, custody metadata and timestamps. Both paths use canonical validation and the same custody, rollback and reconciliation lifecycle. 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. The default path requires authenticated observation and a protocol established by a shipped catalog pin, a declaration on custom, or matching response proof; on the first two, authentication may instead come from that protocol's credential-gated model listing, which then supplies the inventory in the same request. A default-path create that authenticated is not pending verification. Explicit save_unverified consent instead persists configuration with verification pending, without observation, attempts best-effort inventory discovery, and requires a catalog pin or a concrete custom declaration. The server owns Source identity, discovered inventory, health, usage, custody metadata and timestamps. Both paths use canonical validation and the same custody, rollback and reconciliation lifecycle. 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,diff --git a/docs/plans/model-hub-contracts/source.schema.json b/docs/plans/model-hub-contracts/source.schema.jsonindex 13c9e781d..87b4f74aa 100644--- a/docs/plans/model-hub-contracts/source.schema.json+++ b/docs/plans/model-hub-contracts/source.schema.json@@ -22,7 +22,7 @@"verification_pending": {"type": ["string", "null"],"pattern": "^vp_[0-9a-f]{32}$",- "description": "Opaque, non-secret pending-verification identity, replaced whenever Hub credential material or endpoint is stored, including observed creates and same-handle OAuth reauthentication. Presence means not yet model-call verified, independently of routing health. An invocation captures this marker before admission; any successful call with the same current credential and marker may clear it through a fresh cross-process config mutation. Later same-credential calls do not invalidate proof. Inventory never clears it. Null or omission retains legacy behavior without a retrospective verification claim."+ "description": "Opaque, non-secret pending-verification identity, replaced whenever Hub credential material or endpoint is stored without an add-time observation that authenticated it, same-handle OAuth reauthentication included. Presence means nothing upstream has accepted this credential yet, independently of routing health. An invocation captures this marker before admission; any successful call with the same current credential and marker may clear it through a fresh cross-process config mutation. Later same-credential calls do not invalidate proof. Inventory never clears it. Null or omission retains legacy behavior without a retrospective verification claim."},"id": {"type": "string",diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.mdindex 4e59c780f..e87147eb5 100644--- a/docs/plans/model-hub-ui-spec.md+++ b/docs/plans/model-hub-ui-spec.md@@ -3266,13 +3266,31 @@ outline footer action with the Save icon; enter the existing persisting phase wiUnknown-write reconciliation retains this consent and the nonce. Draft edits retireheld evidence as before. The footer wraps on narrow screens. This supersedes theobservation prerequisite in the earlier state tables, not cancellation, settlement-or focus ownership. No upstream observation or inventory request occurs on this exit.+or focus ownership. No upstream observation gates this exit; the bounded inventory+request it attempts fills the model list and can never admit the Source.Source list/detail show `sourceDetail.status.unverified` in existing advisory ink;error/cooldown states retain visual precedence. Adoption and model discovery cannotreplace this label with healthy/in-use copy. Only an actual successful model callretires verification as defined by the Source contract. Ambiguity copy must notclaim authentication success.+**2026-09-07 owner ruling, later the same day — ①″ is reachable again under a pin or+a declaration.** The model-independent probe the ruling above introduced cannot+succeed by construction, so a pinned or declared draft could only land in ③/④/⑤ or+leave through 未验证保存, a valid key and a healthy relay included. 检测 now reads the+established interface's own model list whenever the probe leaves the credential+unknown: a list that answers this key while refusing the identical request carrying+no key authenticates it, and that same response is the inventory ①″ reports — one+request, both facts. A list that refuses this key lands ③ on `addKey.fail.auth`.+Anything else — no list, an unreadable body, a list open to anyone — lands exactly+where it landed before, 未验证保存 included. This adds no state, no string and no+footer action: `addKey.protocol.catalogPinned.hint` still says the pin is not+credential proof, `addKey.pull.result` counts the models that list returned, and the+unverified exit becomes the fallback rather than the only way out. A Source that left+through ①″ has nothing pending, so list/detail do not label it+`sourceDetail.status.unverified`; that label keeps its meaning — nothing upstream has+accepted this credential yet.+**Element inventory**| Element | Displays | Data source | Interactive | On activate |diff --git a/docs/plans/model-hub-vendor-preset-protocol.md b/docs/plans/model-hub-vendor-preset-protocol.mdindex 0c79aa904..4cb906c0f 100644--- a/docs/plans/model-hub-vendor-preset-protocol.md+++ b/docs/plans/model-hub-vendor-preset-protocol.md@@ -169,7 +169,9 @@ request taxonomy applies to API-key and OAuth observation alike.The owner's 2026-09-07 ruling separates configuration from verification. Theprotocol owners remain catalog pins, custom declarations and response evidence;explicit `save_unverified: true` may save either of the first two without an-upstream request. Custom Auto cannot invent an owner. Canonical input validation,+upstream request as its gate; the bounded inventory discovery it then attempts+fills the Source and answers no credential question. Custom Auto cannot invent+an owner. Canonical input validation,credential custody, nonce reconciliation and rollback remain unchanged.Schema errors never authenticate: they can precede key lookup. Synthetic controls@@ -200,14 +202,79 @@ or fabricated OAuth control is needed. Native CLI OAuth is unchanged.`AUTH-SETUP-112` covers every catalog pin and concrete custom protocol againstisolated HTTP middleware with both authentication/schema orders, public/protectedinventory and alphanumeric/punctuation-only credentials. Unknown validation cannot-authenticate, while explicit saving performs no additional upstream requests.+authenticate, while explicit saving makes no request that could admit a Source.`AUTH-SETUP-113` covers completed Hub OAuth admission, fixed protocol ownership,pending verification and idempotent polling across credential shapes and upstreamoutcomes. `AUTH-SETUP-114` covers Auto policy responses that must remain unknownand cannot permit unverified saving without a concrete protocol declaration.+## Authentication witness on an owned interface (2026-09-07, amends the section above)++The model-independent ruling above left catalog pins and concrete `custom`+declarations with no way to verify anything at add time. Its probes deliberately+carry no `model`, so a strict interface answers them with a request-level schema+error, which that ruling classifies as authentication-unknown — correctly, since a+schema error can precede key lookup. Because the probe can therefore never succeed,+every API-key add funnelled into the explicit unverified save, valid credential and+healthy relay included.++The owner's ruling closes that gap without restoring status-based acceptance: where+the interface already has an owner, authentication is read from that owner's model+listing.++- The model-less probe still runs first and still owns reachability, protocol shape+ and immediate rejection. Its evidence table is unchanged.+- Only a probe that left authentication unknown asks further, and only for rung 1+ and rung 3 with an API-key credential. Custom Auto never asks: a listing names no+ protocol, so it cannot supply the owner Auto is missing.+- A listing accepts the credential only once the identical request carrying no+ credential is refused. An absent credential is not an altered one — no grammar to+ guess wrong, no other valid key to collide with — so the synthetic-control+ objection does not reach it, and what it answers is unambiguous: a listing that+ serves an uncredentialed request belongs to anyone who asks and attests to no+ credential. A public model list still repairs no proof.+- What that establishes is bounded, and no further evidence lifts the bound: the+ interface admits this credential and refuses admission without one. It is not+ proof that the interface read the value. Observation may make two requests —+ one carrying the credential and one carrying none — and a gate on the value+ and a gate on presence alone answer that pair identically, the second+ admitting a key it never validated because its probe answers out of a schema+ check that precedes the lookup it never performs. Separating them requires a+ third request carrying a different value, and an altered credential attests to+ nothing in either direction, so this ladder declines it. A credential an+ interface never validated therefore adds as verified and is caught by the+ first real call through the existing needs-action path, where a credential+ revoked after its add is already caught. Withholding verification for that+ case withholds it for every case, which is the state this ruling ends.+- `401`/`403` on that listing rejects the candidate. The shaped-evidence requirement+ exists so that a status cannot establish a *protocol*; this rung holds its protocol+ from its owner already, so the listing's refusal speaks about the credential alone.+- Every other answer — no listing, a non-JSON body, a timeout, a listing open to+ anyone — leaves the observation exactly where the model-independent ruling put it,+ explicit unverified-save exit included. The witness can only add verified adds; it+ can never remove one.+- An accepting listing is also the inventory this rung would fetch next, so the one+ request both verifies the Source and fills it.++`verification_pending` marks a Source that nothing upstream has accepted yet. An+add-time observation that authenticated the credential is that acceptance, so an+API-key create through the observed path stores no marker; for that path this+supersedes the "including observed creates" rule above. Explicit unverified saves,+Hub OAuth admission, native-config imports and every credential or endpoint+replacement still mark, and the first-successful-call clearing, its identity matching+and its shared transaction are unchanged. Inventory still never clears it, and+discovery on a replacement path is still not a witness: it asks no uncredentialed+control and answers no ownership question.++`AUTH-SETUP-112` covers both branches for every shipped catalog vendor and every+concrete custom protocol: a credential-gated listing verifies, populates and leaves+no marker, while a public listing keeps the credential unproven and leaves the+explicit unverified save as the only exit.+## Acceptance+- A relay that answers the model-less probe with a canonical `400` schema error and+ gates `GET /v1/models` on the key adds as verified — the owner's reported case.- 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.diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.mdindex 6a42b18ae..60f40e32c 100644--- a/docs/plans/model-hub.md+++ b/docs/plans/model-hub.md@@ -369,8 +369,11 @@ The three owners above still determine the interface, but explicit API-key`save_unverified: true` no longer requires a successful observation. It saves onlya catalog-pinned or user-declared protocol, with canonical validation, credentialcustody, nonce reconciliation and rollback unchanged. Custom Auto without a-declaration is refused before credential work. No upstream probe or model discovery-is performed by this explicit save path; supplied manual models remain manual.+declaration is refused before credential work. No upstream probe gates this explicit+save path. It attempts one bounded inventory discovery with the provisioned+credential, which fills the Source without answering the credential question and+never blocks the save or replaces manual entries; supplied manual models remain+manual.Schema errors may precede authentication and never authenticate a key. There is nosynthetic credential control: unknown grammar/checksums and other valid credentials@@ -378,6 +381,28 @@ make both rejection and acceptance of an altered token inconclusive. Bare 401/40statuses likewise do not prove credential rejection. The ordinary non-persistingobservation still reports response-backed evidence without inventing certainty.+**Owner ruling 2026-09-07, later the same day, superseding the paragraph above+wherever the two conflict: an owned interface's model listing is the authentication+witness.** A model-less probe cannot succeed by construction, so the ruling above+left rungs 1 and 3 with no add-time verification at all and funnelled every API-key+add into the explicit unverified save. When a probe leaves authentication unknown on+an API-key candidate whose protocol already has an owner — a catalog pin or a+concrete `custom` declaration — observation reads that protocol's `GET /v1/models`.+A listing that answers the credential and refuses the identical request carrying no+credential authenticates it, and is reused as the discovered inventory rather than+fetched twice. `401`/`403` there rejects the candidate: the shaped-evidence rule+guards protocol claims, and this rung's protocol comes from its owner, so the refusal+speaks only about the credential. Every other answer — no listing, a non-JSON body, a+timeout, a listing open to anyone — leaves the outcome the paragraph above would have+produced, unverified-save exit included. There is still no synthetic credential+control: the control request carries no credential at all, and a public list still+repairs no proof. What the witness establishes is bounded there — the interface+admits this credential and refuses admission without one, not that it read the+value, since a gate on presence alone answers those two requests identically and+the third request that would separate them is the altered credential this ladder+declines. A credential no interface validated is caught by the first real call,+like one revoked after its add. Custom Auto is never asked, because a listing names no protocol.+Completed Hub OAuth consent may retain its bound credential as an unverified Sourceunder the fixed vendor protocol. The engine retains OAuth token custody; optionalmodel-free observation uses the existing allowlisted auth-index transport and token@@ -385,8 +410,11 @@ substitution, not private-token reads. Explicit upstream credential rejection rethe existing needs-action state. Native CLI OAuth is unchanged.`Source.verification_pending` is one optional persisted opaque identity, independent-of health and routing eligibility. Every newly stored Hub credential gets a marker,-including observed creates and native-config imports. Source list/detail use the+of health and routing eligibility. It marks a credential nothing upstream has+accepted yet, so an API-key create whose add-time observation authenticated the+credential stores none — superseding, for that path only, the earlier rule that every+observed create is marked. Native-config imports, Hub OAuth admission and every+credential or endpoint replacement still get one. Source list/detail use theexisting advisory treatment instead of healthy/in-use copy. Inventory never clears it.A call captures the marker before invocation; any successful same-credential callwith that marker, including the existing backend probe, clears it in a fresh shareddiff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 49fff84b4..1dd099e7a 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -114,7 +114,7 @@ scenarios:backend: sharedtest: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_catalog_api_key_setup_observe_then_create_closed_loop- id: AUTH-SETUP-112- name: API-key setup saves unverified with best-effort inventory and never schedules a model+ name: API-key setup verifies from a credential-gated model list, or saves unverified with best-effort inventory, and never schedules a modelstatus: coveredkind: happy_pathlayer: scenariodiff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex b24d1cc85..6701d7629 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -2975,9 +2975,14 @@ def test_api_key_setup_does_not_schedule_a_model(request.headers.get("x-api-key")if protocol == "anthropic"else request.headers.get("Authorization", "").removeprefix("Bearer ")- )+ ) or ""observed_credentials.add(supplied_key)- if not re.fullmatch(key_syntax, supplied_key):+ if not supplied_key:+ # An absent credential is not a malformed one: a public+ # inventory answers it and every protected surface refuses it.+ if not (request.method == "GET" and public_inventory):+ return web.json_response({"code": "INVALID_API_KEY"}, status=401)+ elif not re.fullmatch(key_syntax, supplied_key):return web.json_response({"code": "INVALID_API_KEY"}, status=401)if request.method == "POST" and not auth_before_validation and "model" not in body:return web.json_response(@@ -3014,26 +3019,47 @@ def test_api_key_setup_does_not_schedule_a_model(}harness = SimpleNamespace()runner = ScenarioRunner(harness)+ # The interface has an owner either way, so the only open question is+ # the credential -- and the model-less probe never answers it. The+ # listing does, but only while it is gated by that credential: a public+ # inventory answers whoever asks and so names no key.+ gated_inventory = not public_inventory+async def observe(h):result = await service.observe_source(draft)observation = result["observation"]- assert observation["outcome"] != "observed"- assert observation["authenticated"] == "unknown"+ if gated_inventory:+ assert observation["outcome"] == "observed"+ assert observation["authenticated"] == "authenticated"+ assert observation["protocol"] == protocol+ assert observation["models"] == ["relay-model"]+ else:+ assert observation["outcome"] != "observed"+ assert observation["authenticated"] == "unknown"assert not store.config.sourcesasync def confirm(h):- with pytest.raises(ModelHubError):- await service.create_source({- "kind": "api_key", **draft, "accept_unavailable_inventory": True,- })- before = len(requests)- await service.create_source({"kind": "api_key", **draft, "save_unverified": True})- assert requests[before:] == [("GET", "/v1/models", None)]+ if gated_inventory:+ created = (await service.create_source({"kind": "api_key", **draft}))["source"]+ assert "verification_pending" not in created+ else:+ with pytest.raises(ModelHubError):+ await service.create_source({+ "kind": "api_key", **draft, "accept_unavailable_inventory": True,+ })+ before = len(requests)+ await service.create_source({"kind": "api_key", **draft, "save_unverified": True})+ # The explicit save observes nothing. Its one request is the+ # best-effort inventory, which fills the Source without+ # answering the credential question the listing left open.+ assert requests[before:] == [("GET", "/v1/models", None)]assert len(store.config.sources) == 1h.source = store.config.sources[0].to_payload()assert h.source["protocol"] == protocol+ # Both paths end up holding the listing's inventory; only the one+ # the listing authenticated ends up without the pending marker.assert [model["id"] for model in h.source["models"]] == ["relay-model"]- assert h.source["verification_pending"]+ assert bool(h.source.get("verification_pending")) is not gated_inventoryassert state_store.read_api_key(h.source["credential_ref"]) == valid_keyasync def reject_invalid_key(h):@@ -3055,7 +3081,11 @@ def test_api_key_setup_does_not_schedule_a_model()ScenarioExpect.step_history(runner, ["observe", "confirm", "reject_invalid_key"])assert observed_credentials == {- valid_key, "invalid-test-key" if valid_key[0].isalpha() else "!!??",+ valid_key,+ "invalid-test-key" if valid_key[0].isalpha() else "!!??",+ # Reading the listing as a witness also asks it with nothing at+ # all, which is what tells a gated inventory from a public one.+ "",}assert all(path == (paths[protocol] if method == "POST" else "/v1/models")diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.pyindex 6cf4d15de..6ef6d83ab 100644--- a/tests/test_model_hub_l3.py+++ b/tests/test_model_hub_l3.py@@ -6741,8 +6741,13 @@ def test_qwen_catalog_pin_validation_remains_unverified(clear=False,),patch(+ # This interface publishes no model listing, so nothing on+ # it can speak for the credential the wrapperless+ # validation error left unknown."vibe.model_hub_runtime.adapter.probe_models",- new=AsyncMock(return_value=(DiscoveredModel(id="qwen-plus"),)),+ new=AsyncMock(+ side_effect=EngineClientError("no listing", status_code=404)+ ),) as inventory_probe,):observed = await adapter.observe_source(@@ -6751,8 +6756,7 @@ def test_qwen_catalog_pin_validation_remains_unverified(credential_ref,SOURCE_PROTOCOLS,)- inventory_probe.assert_not_awaited()- inventory_kwargs = {}+ inventory_kwargs = dict(inventory_probe.await_args.kwargs)finally:await runner.cleanup()return requests, observed, inventory_kwargs@@ -6767,7 +6771,7 @@ def test_qwen_catalog_pin_validation_remains_unverified(_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_pathfor protocol in SOURCE_PROTOCOLS]- assert inventory_kwargs == {}+ assert inventory_kwargs["protocol"] == "openai_chat"def test_openrouter_catalog_pin_numeric_validation_remains_unverified(@@ -6821,8 +6825,13 @@ def test_openrouter_catalog_pin_numeric_validation_remains_unverified(clear=False,),patch(+ # This interface publishes no model listing, so nothing on+ # it can speak for the credential the numeric validation+ # error left unknown."vibe.model_hub_runtime.adapter.probe_models",- new=AsyncMock(return_value=(DiscoveredModel(id="openrouter/auto"),)),+ new=AsyncMock(+ side_effect=EngineClientError("no listing", status_code=404)+ ),) as inventory_probe,):observed = await adapter.observe_source(@@ -6831,8 +6840,7 @@ def test_openrouter_catalog_pin_numeric_validation_remains_unverified(credential_ref,SOURCE_PROTOCOLS,)- inventory_probe.assert_not_awaited()- inventory_kwargs = {}+ inventory_kwargs = dict(inventory_probe.await_args.kwargs)finally:await runner.cleanup()return requests, observed, inventory_kwargs@@ -6847,7 +6855,7 @@ def test_openrouter_catalog_pin_numeric_validation_remains_unverified(_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_pathfor protocol in SOURCE_PROTOCOLS]- assert inventory_kwargs == {}+ assert inventory_kwargs["protocol"] == "openai_chat"def _catalog_owner_status_body(vendor: str, status: int) -> dict[str, object]:@@ -6887,10 +6895,27 @@ def _run_catalog_pin_observation(protocol: str,status: int,body: dict[str, object],-) -> tuple[list[str], object, dict[str, object] | None]:+ listing: str,+ interface_key: str | None = None,+) -> tuple[list[tuple[str, str]], object]:+ """Observe a pinned vendor whose probe answers `status` and whose model+ listing behaves as `listing`.++ ``listing`` names what the interface does with ``GET /v1/models``:+ ``gated`` answers the stored credential and refuses an uncredentialed+ caller, ``open`` answers anybody, ``rejects`` refuses every caller,+ ``absent`` publishes no listing at all, and ``presence`` requires a+ credential without ever reading its value.++ ``interface_key`` is the credential this interface would actually accept,+ which the stored one matches unless a caller says otherwise.+ """++ key = f"test-{vendor}-{status}"+ accepted_key = key if interface_key is None else interface_keystate_store = EngineStateStore(tmp_path / f"engine-state-{vendor}-{status}")credential_ref = state_store.store_api_key(- f"test-{vendor}-{status}",+ key,vendor=vendor,protocol=protocol,base_url=None,@@ -6900,17 +6925,39 @@ def _run_catalog_pin_observation(state_store=state_store,)- async def scenario() -> tuple[list[str], object, dict[str, object] | None]:- requests: list[str] = []+ def supplied_credential(request: web.Request) -> str:+ return request.headers.get("x-api-key") or request.headers.get(+ "Authorization", ""+ ).removeprefix("Bearer ")++ async def scenario() -> tuple[list[tuple[str, str]], object]:+ requests: list[tuple[str, str]] = []async def capture_probe(request: web.Request) -> web.Response:- requests.append(request.path)- supplied = request.headers.get("x-api-key") or request.headers.get("Authorization", "").removeprefix("Bearer ")- if supplied != f"test-{vendor}-{status}":+ requests.append((request.method, request.path))+ # An interface that never reads the credential's value answers the+ # model-less probe out of its schema check, which precedes any key+ # lookup, so the probe leaves a key it never validated unknown.+ if listing != "presence" and supplied_credential(request) != accepted_key:return web.json_response({"code": "INVALID_API_KEY"}, status=401)return web.json_response(body, status=status)+ async def capture_listing(request: web.Request) -> web.Response:+ requests.append((request.method, request.path))+ if listing == "absent":+ return web.json_response({"error": "unknown route"}, status=404)+ if listing == "presence":+ refused = not supplied_credential(request)+ else:+ refused = listing == "rejects" or (+ listing == "gated" and supplied_credential(request) != accepted_key+ )+ if refused:+ return web.json_response({"code": "INVALID_API_KEY"}, status=401)+ return web.json_response({"data": [{"id": f"{vendor}/listed"}]})+app = web.Application()+ app.router.add_get("/v1/models", capture_listing)app.router.add_post("/{tail:.*}", capture_probe)runner = web.AppRunner(app)await runner.setup()@@ -6920,16 +6967,10 @@ def _run_catalog_pin_observation(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,+ with patch.dict(+ "vibe.model_hub_runtime.adapter._OFFICIAL_BASE_URLS",+ {vendor: origin},+ clear=False,):observed = await adapter.observe_source(vendor,@@ -6937,60 +6978,116 @@ def _run_catalog_pin_observation(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 requests, observedreturn asyncio.run(scenario())[email protected]("listing", ["gated", "open", "rejects", "absent"])[email protected]("status", [400, 401])@pytest.mark.parametrize(("vendor", "protocol"), CATALOG_API_KEY_VENDOR_PROTOCOL_CASES)-def test_catalog_pin_json_400_does_not_prove_authentication(+def test_catalog_pin_authentication_comes_from_a_credential_gated_listing(tmp_path: Path,vendor: str,protocol: str,+ status: int,+ listing: str,) -> None:- requests, observed, inventory_kwargs = _run_catalog_pin_observation(+ """A pin's authentication is whatever its model listing attests.++ The model-less probe cannot speak for the credential: neither its request+ error nor a bare authentication status without a shaped identifier decides+ anything, for any vendor. So the listing on the pinned interface answers+ instead, and only a listing that is gated by the credential attests to it --+ an open catalogue answers whoever asks and therefore names no key.+ """++ requests, observed = _run_catalog_pin_observation(tmp_path,vendor=vendor,protocol=protocol,- status=400,- body=_catalog_owner_status_body(vendor, 400),+ status=status,+ body=_catalog_owner_status_body(vendor, status),+ listing=listing,)- assert observed.outcome.value == "ambiguous"- assert observed.protocol is None- assert observed.authenticated is None- assert observed.model_ids == ()- assert requests == [_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path]- assert inventory_kwargs is None+ if listing == "gated":+ assert observed.outcome.value == "observed"+ assert observed.protocol == protocol+ assert observed.authenticated is True+ assert observed.model_ids == (f"{vendor}/listed",)+ elif listing == "rejects":+ assert observed.outcome.value == "authentication_failed"+ assert observed.protocol is None+ assert observed.authenticated is False+ assert observed.model_ids == ()+ else:+ assert observed.outcome.value == "ambiguous"+ assert observed.protocol is None+ assert observed.authenticated is None+ assert observed.model_ids == ()+ assert requests[0] == ("POST", _PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path)+ assert set(requests[1:]) <= {("GET", "/v1/models")}@pytest.mark.parametrize(("vendor", "protocol"), CATALOG_API_KEY_VENDOR_PROTOCOL_CASES)-def test_catalog_pin_unknown_json_401_is_not_credential_rejection(+def test_a_listing_gate_on_presence_answers_exactly_like_one_on_the_key(tmp_path: Path,vendor: str,protocol: str,) -> None:- requests, observed, inventory_kwargs = _run_catalog_pin_observation(- tmp_path,+ """Add-time verification cannot see which of the two an interface is doing.++ Observation may make exactly two requests: one carrying the stored+ credential and one carrying none. An interface that reads the value answers+ a credential it accepts with its catalogue and an uncredentialed caller+ with a refusal. An interface that only requires the header to be there+ answers *any* credential with the same catalogue and that same refusal --+ including one it would never have accepted, since its probe answers out of+ a schema check that precedes the key lookup it never performs. Both worlds+ hand back an identical pair of responses, so no reading of that pair+ separates them; only a third request carrying a different value could, and+ an altered credential attests to nothing in either direction, which is why+ this ladder has no synthetic credential control.++ So the witness admits both, and a credential an interface never validated+ is left to the first real call and the existing needs-action path -- the+ same place a credential revoked after it was added is caught.+ """++ validated = _run_catalog_pin_observation(+ tmp_path / "validated",+ vendor=vendor,+ protocol=protocol,+ status=400,+ body=_catalog_owner_status_body(vendor, 400),+ listing="gated",+ )+ unread = _run_catalog_pin_observation(+ tmp_path / "unread",vendor=vendor,protocol=protocol,- status=401,- body=_catalog_owner_status_body(vendor, 401),+ status=400,+ body=_catalog_owner_status_body(vendor, 400),+ listing="presence",+ interface_key="a-credential-this-source-does-not-carry",)- assert observed.outcome.value == "ambiguous"- assert observed.protocol is None- assert observed.authenticated is None- assert observed.model_ids == ()- assert requests == [_PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path]- assert inventory_kwargs is None+ def observation(result: tuple[list[tuple[str, str]], object]) -> tuple[object, ...]:+ requests, observed = result+ return (+ requests,+ observed.outcome,+ observed.protocol,+ observed.authenticated,+ observed.model_ids,+ )++ assert observation(validated) == observation(unread)+ assert unread[1].outcome.value == "observed"+ assert unread[1].authenticated is Truedef test_custom_auto_numeric_auth_failure_message_stays_authentication_failed(@@ -7166,6 +7263,8 @@ def test_custom_declared_observation_preserves_transport_authentication_verdict(new=AsyncMock(return_value=parser_evidence),) as protocol_probe,patch(+ # This listing answers with or without a credential, so it attests+ # to nobody and cannot repair an unknown verdict."vibe.model_hub_runtime.adapter.probe_models",new=AsyncMock(return_value=(DiscoveredModel(id="declared-model"),)),) as inventory_probe,@@ -7189,7 +7288,127 @@ def test_custom_declared_observation_preserves_transport_authentication_verdict(assert inventory_probe.await_args.kwargs["protocol"] == "openai_chat"else:assert observed.protocol is None- inventory_probe.assert_not_awaited()+ # An unknown verdict is the only one the listing may still answer: a+ # rejection is already decided, so nothing further is asked.+ asked_listing = initial_authentication is _AuthenticationEvidence.UNKNOWN+ assert (inventory_probe.await_count > 0) is asked_listing++[email protected]("stored_key", ["relay-live-key", "relay-wrong-key"])+def test_declared_custom_anthropic_relay_verifies_from_its_models_listing(+ tmp_path: Path,+ stored_key: str,+) -> None:+ """The reported relay, recorded from a live one: a declared `anthropic`+ endpoint that answers the model-less probe with Anthropic's own 400+ envelope -- which proves the interface and says nothing about the key --+ and gates `GET /v1/models` on that key.++ The listing is therefore what separates the working credential from the+ wrong one, on an interface whose probe can only ever be a request error.+ """++ live_key = "relay-live-key"+ state_store = EngineStateStore(tmp_path / f"engine-state-relay-{stored_key}")+ adapter = CLIProxyEngineAdapter(supervisor=Mock(), state_store=state_store)++ async def scenario() -> tuple[list[tuple[str, str, str]], list[dict], object]:+ requests: list[tuple[str, str, str]] = []+ probe_bodies: list[dict] = []++ def supplied(request: web.Request) -> str:+ return request.headers.get("x-api-key", "")++ async def relay_messages(request: web.Request) -> web.Response:+ requests.append((request.method, request.path, supplied(request)))+ probe_bodies.append(await request.json())+ if supplied(request) != live_key:+ return web.json_response(+ {+ "type": "error",+ "error": {+ "type": "authentication_error",+ "message": "invalid x-api-key",+ },+ },+ status=401,+ )+ return web.json_response(+ {+ "type": "error",+ "error": {+ "type": "invalid_request_error",+ "message": "model: Field required",+ },+ },+ status=400,+ )++ async def relay_models(request: web.Request) -> web.Response:+ requests.append((request.method, request.path, supplied(request)))+ if supplied(request) != live_key:+ return web.json_response(+ {+ "type": "error",+ "error": {+ "type": "authentication_error",+ "message": "invalid x-api-key",+ },+ },+ status=401,+ )+ return web.json_response(+ {"data": [{"id": "claude-sonnet-4-5"}, {"id": "claude-opus-4-6"}]}+ )++ app = web.Application()+ app.router.add_get("/v1/models", relay_models)+ app.router.add_post("/{tail:.*}", relay_messages)+ 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+ origin = f"http://127.0.0.1:{site._server.sockets[0].getsockname()[1]}"+ credential_ref = state_store.store_api_key(+ stored_key,+ vendor="custom",+ protocol="anthropic",+ base_url=origin,+ )+ try:+ observed = await adapter.observe_source(+ "custom",+ origin,+ credential_ref,+ ("anthropic",),+ )+ finally:+ await runner.cleanup()+ return requests, probe_bodies, observed++ requests, probe_bodies, observed = asyncio.run(scenario())++ probe_path = _PROTOCOL_OBSERVATION_TAXONOMY["anthropic"].request_path+ assert all("model" not in body for body in probe_bodies)+ if stored_key == live_key:+ assert observed.outcome.value == "observed"+ assert observed.protocol == "anthropic"+ assert observed.authenticated is True+ assert observed.model_ids == ("claude-sonnet-4-5", "claude-opus-4-6")+ assert requests == [+ ("POST", probe_path, live_key),+ ("GET", "/v1/models", live_key),+ # The control carries no credential at all, which is how an+ # answered listing is told apart from a published one.+ ("GET", "/v1/models", ""),+ ]+ else:+ assert observed.outcome.value == "authentication_failed"+ assert observed.authenticated is False+ assert observed.protocol is None+ assert observed.model_ids == ()+ assert requests == [("POST", probe_path, stored_key)]def test_auth_setup_executable_scenarios_are_registered() -> None:diff --git a/tests/test_model_hub_unverified.py b/tests/test_model_hub_unverified.pyindex ea88b6bac..0f90dda4d 100644--- a/tests/test_model_hub_unverified.py+++ b/tests/test_model_hub_unverified.py@@ -11,7 +11,14 @@ from unittest.mock import AsyncMockimport pytestfrom config.v2_config import ModelHubSourceConfig, V2Config, config_write_transaction-from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind, SOURCE_PROTOCOLS+from core.handlers.model_hub.adapter import (+ ObservationDiscovery,+ ObservationOutcome,+ RawCallOutcome,+ RawOutcomeKind,+ SOURCE_PROTOCOLS,+ SourceObservation,+)from core.handlers.model_hub.service import ModelHubError, V2ModelHubConfigStorefrom tests.test_model_hub_api import _assert_valid, _servicefrom vibe.model_hub_runtime.api_key_vendors import api_key_vendor_catalog@@ -169,12 +176,34 @@ def test_model_call_consumers_retire_pending_verification(tmp_path, path):asyncio.run(scenario())[email protected]("unverified", [False, True])-def test_new_api_key_credentials_always_start_pending(tmp_path, unverified):- service, _store, _adapter = _service(tmp_path)- created = asyncio.run(service.create_source(_draft(save_unverified=unverified)))["source"]+ "add", ["save_unverified", "observed_with_inventory", "observed_without_inventory"]+)+def test_pending_verification_marks_only_what_no_observation_accepted(tmp_path, add):+ """The marker records that nothing has accepted this credential yet.++ An add-time observation that authenticated it is that acceptance, whatever+ the observation went on to discover, so re-asking would make the marker mean+ something else. An explicit unverified save asks nothing upstream and+ therefore always carries it.+ """+ service, store, adapter = _service(tmp_path)+ draft = _draft(save_unverified=add == "save_unverified")+ if add == "observed_without_inventory":+ adapter.observation = SourceObservation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol=draft["protocol"],+ discovery=ObservationDiscovery.FAILED,+ models=(),+ )+ draft["accept_unavailable_inventory"] = True+ created = asyncio.run(service.create_source(draft))["source"]_assert_valid("source.schema.json", created)- assert created["verification_pending"]+ unaccepted = add == "save_unverified"+ assert ("verification_pending" in created) is unaccepted+ assert (store.config.sources[0].verification_pending is None) is not unaccepteddef _settle_in_controller(config_home, captured, attempted, done):diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex c6420cc8f..ca296e30f 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -852,6 +852,87 @@ def _protocol_is_persistable_without_shape_proof(return vendor == "custom" and len(protocol_order) == 1 and protocol_order[0] == protocol+class _ModelsWitness(Enum):+ """What an owned interface's model listing established about a credential."""++ ACCEPTED = "accepted"+ REJECTED = "rejected"+ INCONCLUSIVE = "inconclusive"+++@dataclass(frozen=True)+class _ModelsWitnessResult:+ credential: _ModelsWitness+ models: tuple[DiscoveredModel, ...] = ()+++async def _authenticate_with_models_witness(+ *,+ vendor: str,+ protocol: str,+ base_url: str | None,+ secret: str,+) -> _ModelsWitnessResult:+ """Read the owned interface's model listing as the authentication witness.++ The protocol probe deliberately carries no ``model`` so observation never+ enters a relay's scheduler, which is exactly why a conforming interface+ answers it with a request error and leaves authentication unknown. The+ listing this rung already fetches for inventory is the one call on that same+ interface that a correct credential answers and a wrong one refuses, so it+ carries the authentication the probe cannot: an authentication status+ rejects the credential, and no listing route, an unparseable body, or a+ transport failure proves nothing and leaves the observation exactly where+ the probe left it.++ A listing only accepts the credential once the same request without one is+ refused. Some interfaces publish their catalogue to anybody, and there a+ listing attests to whoever asked rather than to this key. Asking with no+ credential settles which kind this is: unlike an altered or fabricated key,+ an absent one cannot be wrong about a grammar nobody published or collide+ with another valid key, so the answer is unambiguous. An open catalogue+ therefore stays inconclusive and the source saves the way it does today.++ Acceptance is bounded accordingly: the interface admits this credential and+ refuses admission without one, which is not proof that it read the value.+ An interface that requires a credential without reading it answers those two+ requests identically, so it is admitted as well, and the third request that+ would separate the two carries an altered credential and attests to nothing+ in either direction. The first real call catches a credential nothing+ validated, exactly where it catches one revoked after its add.++ Only a catalog pin or a concrete declaration asks, because the answer names+ no protocol; that owner supplies it. The accepted result carries the+ listing, so one call both authenticates the source and populates it.+ """++ try:+ models = await probe_models(+ vendor=vendor,+ protocol=protocol,+ base_url=base_url,+ secret=secret,+ )+ except EngineClientError as exc:+ if exc.status_code in _AUTHENTICATION_ERROR_STATUSES:+ return _ModelsWitnessResult(credential=_ModelsWitness.REJECTED)+ return _ModelsWitnessResult(credential=_ModelsWitness.INCONCLUSIVE)+ try:+ await probe_models(+ vendor=vendor,+ protocol=protocol,+ base_url=base_url,+ secret=None,+ )+ except EngineClientError as refusal:+ if refusal.status_code in _AUTHENTICATION_ERROR_STATUSES:+ return _ModelsWitnessResult(+ credential=_ModelsWitness.ACCEPTED,+ models=tuple(models),+ )+ return _ModelsWitnessResult(credential=_ModelsWitness.INCONCLUSIVE)++def _anthropic_wrapperless_elimination_proof(responses: Mapping[str, _ProtocolEvidence],*,@@ -1680,8 +1761,11 @@ class CLIProxyEngineAdapter:could be served. A protocol-specific responsewith accepted authentication proves the current attempt and terminatesobservation. A shipped vendor catalog pin or a concrete `custom`- declaration also terminates observation after a shaped success.- Schema errors remain unverified; explicit unverified saving belongs to+ declaration also terminates observation after a shaped success, and,+ because that interface's owner is already named, may take its+ authentication from the model listing when the model-less probe leaves+ it unknown. Schema errors that no listing answers remain unverified;+ explicit unverified saving belongs toSource creation, not this observation. A shaped rejection isrecorded while later candidates continue on Auto detect. Vendor, URL,and order never create a conclusion on their own; `custom` Auto still requires response-backed@@ -1777,6 +1861,36 @@ class CLIProxyEngineAdapter:received_rejection = Trueruled_out_protocols.add(protocol)continue+ if (+ credential_kind == "api_key"+ and owner_scoped_protocol+ and evidence.authentication is _AuthenticationEvidence.UNKNOWN+ ):+ # This interface already has an owner, so the only thing left to+ # establish is whether it accepts the credential -- and the+ # model-less probe just declined to say. Its model listing+ # answers that, and is the inventory this rung would fetch next+ # anyway, so a listing that turns out to be credential-gated+ # both verifies the source and fills it in one pass.+ witness = await _authenticate_with_models_witness(+ vendor=normalized_vendor,+ protocol=protocol,+ base_url=base_url,+ secret=secret or "",+ )+ if witness.credential is _ModelsWitness.REJECTED:+ received_rejection = True+ ruled_out_protocols.add(protocol)+ continue+ if witness.credential is _ModelsWitness.ACCEPTED:+ return make_source_observation(+ outcome=ObservationOutcome.OBSERVED,+ reachable=True,+ authenticated=True,+ protocol=protocol,+ discovery=ObservationDiscovery.SUCCEEDED,+ models=witness.models,+ )proved_protocol: str | None = Noneif evidence.protocol is _ProtocolProof.PROVEN:if evidence.authentication is _AuthenticationEvidence.UNKNOWN:diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 95e01f845..272f85731 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -743,10 +743,16 @@ async def probe_models(vendor: str,protocol: str,base_url: str | None,- secret: str,+ secret: str | None,timeout: float = 15.0,) -> tuple[DiscoveredModel, ...]:- """Probe the one allowlisted models path without redirecting credentials."""+ """Probe the one allowlisted models path without redirecting credentials.++ ``secret=None`` sends no credential at all. It is not an altered or+ fabricated one -- there is no token to guess wrong and no other valid key to+ collide with -- so what it answers is unambiguous: a listing that still+ arrives belongs to anyone who asks and therefore attests to no credential.+ """normalized_vendor = vendor.strip().lower()root = base_url or _OFFICIAL_BASE_URLS.get(normalized_vendor)if not root:@@ -756,13 +762,16 @@ async def probe_models(except (TypeError, ValueError):raise EngineClientError("source base URL is invalid")assert url is not None- headers = {"Authorization": f"Bearer {secret}", "Accept": "application/json"}+ headers = {"Accept": "application/json"}if protocol == "anthropic":- headers = {- "x-api-key": secret,- "anthropic-version": "2023-06-01",- "Accept": "application/json",- }+ # The version header is part of the interface, not the credential, so it+ # stays on the uncredentialed request: it must differ in exactly one way.+ headers["anthropic-version"] = "2023-06-01"+ if secret is not None:+ if protocol == "anthropic":+ headers["x-api-key"] = secret+ else:+ headers["Authorization"] = f"Bearer {secret}"deadline = time.monotonic() + timeoutclient_timeout = aiohttp.ClientTimeout(total=timeout)try: