Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

fix(model-hub): support upstream interface selection (#1704)

Call White9ae24a413b7a
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index a9059bbe4..59daa972e 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -1100,19 +1100,13 @@ class ModelHubService:
)
@staticmethod
- def _observation_protocol_order(payload: Mapping[str, Any]) -> tuple[str, ...]:
- requested = payload.get("protocol_order")
- if requested is None:
+ def _observation_protocols(payload: Mapping[str, Any]) -> tuple[str, ...]:
+ if "protocol" not in payload:
return SOURCE_PROTOCOLS
- if (
- not isinstance(requested, list)
- or not all(isinstance(item, str) for item in requested)
- ):
- raise ModelHubError("discovery_failed")
- requested_order = tuple(requested)
- if len(set(requested_order)) != len(SOURCE_PROTOCOLS) or set(requested_order) != set(SOURCE_PROTOCOLS):
+ requested = payload.get("protocol")
+ if not isinstance(requested, str) or requested not in SOURCE_PROTOCOLS:
raise ModelHubError("discovery_failed")
- return requested_order
+ return (requested,)
@staticmethod
def _observation_payload(observation: SourceObservation) -> dict:
@@ -1178,7 +1172,14 @@ class ModelHubService:
discovery=ObservationDiscovery.NOT_ATTEMPTED,
model_ids=(),
)
- return self._validate_observation(observation)
+ validated = self._validate_observation(observation)
+ if (
+ len(protocol_order) == 1
+ and validated.protocol is not None
+ and validated.protocol != protocol_order[0]
+ ):
+ raise ModelHubError("discovery_failed", status=502)
+ return validated
async def _require_proven_observation(
self,
@@ -1230,7 +1231,7 @@ class ModelHubService:
*,
require_proven: bool = False,
) -> SourceObservation:
- if set(payload) - {"vendor", "base_url", "key", "protocol_order"}:
+ if set(payload) - {"vendor", "base_url", "key", "protocol"}:
raise ModelHubError("discovery_failed")
vendor = payload.get("vendor")
try:
@@ -1241,7 +1242,7 @@ class ModelHubService:
key = payload.get("key")
if not isinstance(key, str) or not key.strip():
raise ModelHubError("discovery_failed")
- protocol_order = self._observation_protocol_order(payload)
+ protocol_order = self._observation_protocols(payload)
transient_ref = await _provision_transient_credential_with_cancellation_ownership(
self,
vendor,
@@ -2324,8 +2325,9 @@ class ModelHubService:
"models",
"key",
"oauth_flow_ref",
- "protocol_order",
+ "protocol",
"client_nonce",
+ "accept_unavailable_inventory",
}:
raise ModelHubError("discovery_failed")
forbidden = {
@@ -2338,7 +2340,7 @@ class ModelHubService:
"created_at",
"last_discovered_at",
} & set(payload)
- if forbidden or "protocol" in payload:
+ if forbidden:
raise ModelHubError("discovery_failed")
kind = payload.get("kind")
vendor = payload.get("vendor")
@@ -2410,9 +2412,21 @@ class ModelHubService:
raise ModelHubError("discovery_failed")
if kind != "api_key" and client_nonce is not None:
raise ModelHubError("discovery_failed")
+ accept_unavailable_inventory = payload.get("accept_unavailable_inventory", False)
+ if (
+ not isinstance(accept_unavailable_inventory, bool)
+ or (
+ kind != "api_key"
+ and (
+ "protocol" in payload
+ or "accept_unavailable_inventory" in payload
+ )
+ )
+ ):
+ raise ModelHubError("discovery_failed")
protocol_order: tuple[str, ...] | None = None
if kind == "api_key":
- protocol_order = self._observation_protocol_order(payload)
+ protocol_order = self._observation_protocols(payload)
if oauth_ref:
return self._source_creation_result(
@@ -2467,14 +2481,24 @@ class ModelHubService:
nonce_claimed = True
if self.revocations.list():
await self._ensure_engine_synced()
- observation = await self._require_proven_source_payload(
- {
- "vendor": vendor,
- "base_url": base_url,
- "key": credential_value,
- "protocol_order": payload.get("protocol_order"),
- }
- )
+ observation_payload: dict[str, Any] = {
+ "vendor": vendor,
+ "base_url": base_url,
+ "key": credential_value,
+ }
+ if "protocol" in payload:
+ observation_payload["protocol"] = payload["protocol"]
+ observation = await self._require_proven_source_payload(observation_payload)
+ if (
+ observation.discovery is ObservationDiscovery.FAILED
+ and not accept_unavailable_inventory
+ ):
+ raise ModelHubError(
+ "discovery_failed",
+ status=422,
+ detail="modelHub.errors.inventory_unavailable",
+ data={"observation": self._observation_payload(observation)},
+ )
source.protocol = cast(
Literal["anthropic", "openai_responses", "openai_chat"],
observation.protocol,
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 9529704e3..9c0d5af19 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -143,7 +143,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| File | Authority and consumer role |
| --- | --- |
| `source.schema.json` | Source identity, channel, three protocols, state, usage, inventory, credential reference, and audit metadata. |
-| `source-create.schema.json` | API-key Source creation request, transient credential boundary, probe-order hint, and lost-response correlation. |
+| `source-create.schema.json` | API-key Source creation request, transient credential boundary, optional single-protocol constraint, and lost-response correlation. |
| `agent-supply.schema.json` | Backend mode, explicit policy-free Source order, configuration eligibility, model-supply and backend-health projections. |
| `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. |
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 940ffe6cd..0f2566d12 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -6,8 +6,8 @@
"type": "object",
"x-model-hub-routes": [
{"method": "GET", "path": "/api/models/sources", "response_schema": "SourceListResponse", "exercise": {"path": "/api/models/sources", "status": 200}},
- {"method": "POST", "path": "/api/models/sources/observe", "response_schema": "ObservationResponse", "exercise": {"path": "/api/models/sources/observe", "status": 200, "json": {"vendor": "anthropic", "key": "sk-contract-test", "protocol_order": ["anthropic", "openai_responses", "openai_chat"]}}},
- {"method": "POST", "path": "/api/models/sources", "response_schema": "SourceCreateResponse", "exercise": {"path": "/api/models/sources", "status": 201, "json": {"kind": "api_key", "vendor": "anthropic", "display_name": "Contract source", "key": "sk-contract-test", "protocol_order": ["anthropic", "openai_responses", "openai_chat"]}}},
+ {"method": "POST", "path": "/api/models/sources/observe", "response_schema": "ObservationResponse", "exercise": {"path": "/api/models/sources/observe", "status": 200, "json": {"vendor": "anthropic", "key": "sk-contract-test", "protocol": "anthropic"}}},
+ {"method": "POST", "path": "/api/models/sources", "response_schema": "SourceCreateResponse", "exercise": {"path": "/api/models/sources", "status": 201, "json": {"kind": "api_key", "vendor": "anthropic", "display_name": "Contract source", "key": "sk-contract-test", "protocol": "anthropic"}}},
{"method": "PATCH", "path": "/api/models/sources/<id>", "response_schema": "SourceMutationResponse", "exercise": {"path": "/api/models/sources/src_conform001", "status": 200, "json": {"display_name": "Renamed contract source"}}},
{"method": "PUT", "path": "/api/models/sources/<id>/credential", "response_schema": "SourceMutationResponse", "exercise": {"path": "/api/models/sources/src_conform001/credential", "status": 200, "json": {"key": "sk-replacement-contract-test"}}},
{"method": "POST", "path": "/api/models/sources/<id>/reauth", "response_schema": "OAuthFlowResponse", "exercise": {"path": "/api/models/sources/src_subscribe01/reauth", "status": 200, "json": {"acknowledge_irreversible": true}}},
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 3fd4cabac..cd6192910 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -25,7 +25,7 @@ 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_order?}` → `{observation: SourceObservation}` | Non-persisting connectivity/authentication/protocol/inventory observation. `protocol_order` only orders the three probes; it never supplies a conclusion. No credential reference is returned. |
+| 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. |
| 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. |
@@ -73,22 +73,26 @@ create request:
"vendor": "custom",
"base_url": "https://relay.example/v1",
"key": "<transient plaintext key>",
- "protocol_order": ["openai_chat", "openai_responses", "anthropic"]
+ "protocol": "openai_chat"
}
```
-`base_url` may be null for an official vendor endpoint. `protocol_order`, when
-present, contains each protocol exactly once and is only probe ordering; omitting it
-uses the authoritative three-value order. The endpoint provisions an unbound engine
-credential only for this operation, returns `observation-result.schema.json`, then
-revokes the transient reference before settling. A revoke failure remains in the
-existing pending-revocation journal. The response never contains that reference or
-any persisted Source.
+`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
+schema-invalid and names no synthetic model, so a relay can authenticate and classify it
+without selecting or invoking an upstream model. A bare-origin Base URL uses the
+standard `/v1` endpoint paths, while a URL with a path is treated as the complete API
+root. The endpoint provisions an unbound engine credential only for this operation,
+returns `observation-result.schema.json`, then revokes the transient reference before
+settling. A revoke failure remains in the existing pending-revocation journal. The
+response 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
-provisioning. It accepts the create fields and optional `protocol_order`, but never
-accepts a protocol conclusion or inventory result from the caller. A null protocol
+provisioning. It accepts the create fields and optional protocol constraint, but never
+accepts 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
@@ -104,11 +108,11 @@ authoritative; no Source response field may be inferred backwards into the reque
| `display_name` | no | Add Source client → Source metadata | Omission uses the server's canonical 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_order` | no | Add Source client → observation adapter | Contains all three protocols exactly once and only orders probes. |
+| `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. |
| `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. |
-The request has no `id`, `created_at`, `state`, `usage`, `protocol`, discovered-model,
+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
them. A successfully observed empty inventory is represented by the returned
`source.models: []`; the client never submits a discovered inventory as authority.
@@ -179,8 +183,8 @@ failure may use the same outcome with `reachable: null`. A bare HTTP status prov
reachability, but proves neither protocol nor authentication. Consequently,
`ambiguous` always has `reachable: true` and `protocol: null`.
`authentication_failed` also has `protocol: null`, because a rejected credential
-does not establish a persistable protocol. `ambiguous` is the sole outcome that asks
-for the one-time probe-order hint. Only `observed` attempts inventory discovery and
+does not establish a persistable protocol. After ambiguous Auto detection, the client
+must select one concrete protocol before retrying. Only `observed` attempts inventory discovery and
therefore reports `succeeded` or `failed`; every other terminal reports
`not_attempted` with an empty model list.
diff --git a/docs/plans/model-hub-contracts/mirror-registry.json b/docs/plans/model-hub-contracts/mirror-registry.json
index e73ea2895..d9aafb207 100644
--- a/docs/plans/model-hub-contracts/mirror-registry.json
+++ b/docs/plans/model-hub-contracts/mirror-registry.json
@@ -423,7 +423,7 @@
{
"kind": "schema_vocabulary",
"schema": "source-create.schema.json",
- "paths": ["/properties/protocol_order/items"]
+ "paths": ["/properties/protocol"]
}
]
},
diff --git a/docs/plans/model-hub-contracts/source-create.schema.json b/docs/plans/model-hub-contracts/source-create.schema.json
index 546816ee4..ffde90d1a 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, protocol evidence, discovered inventory, health, usage, custody metadata, and timestamps. 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, 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.",
"type": "object",
"required": ["vendor", "key"],
"additionalProperties": false,
@@ -27,15 +27,9 @@
"writeOnly": true,
"description": "Transient plaintext credential. It is never returned or persisted in Source state."
},
- "protocol_order": {
- "type": "array",
- "items": {
- "enum": ["anthropic", "openai_responses", "openai_chat"]
- },
- "minItems": 3,
- "maxItems": 3,
- "uniqueItems": true,
- "description": "Optional one-time probe order containing every protocol exactly once. It orders observation and never supplies a protocol conclusion."
+ "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."
},
"client_nonce": {
"type": "string",
@@ -54,14 +48,14 @@
"display_name": "relay.example",
"base_url": "https://relay.example/v1",
"key": "<transient plaintext key>",
- "protocol_order": ["openai_chat", "openai_responses", "anthropic"],
+ "protocol": "openai_chat",
"client_nonce": "scn_01j5w8z7p4n6q2rt"
},
{
"vendor": "custom",
"base_url": "https://relay.example/v1",
"key": "<transient plaintext key>",
- "protocol_order": ["openai_chat", "openai_responses", "anthropic"],
+ "protocol": "openai_chat",
"accept_unavailable_inventory": true
}
]
diff --git a/docs/plans/model-hub-ui-spec.md b/docs/plans/model-hub-ui-spec.md
index a228f233e..97dc0e615 100644
--- a/docs/plans/model-hub-ui-spec.md
+++ b/docs/plans/model-hub-ui-spec.md
@@ -267,7 +267,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_order?}` and returns `SourceObservation` without persisting a Source or returning a credential reference. §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 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-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`, 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 |
@@ -276,7 +276,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` consumes the current Source-order sequence with a stable total sort over every stored Route. The order PUT remains chain-byte-identical; invocation is explicit and separate. |
-| 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_order`, `client_nonce` and `accept_unavailable_inventory` `[contract]`. The client submits no protocol conclusion or discovered inventory; the server observes both. §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]`. 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-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. |
@@ -392,16 +392,12 @@ single-select and one 去登录 produces exactly one effect, so there is no part
define. Both are struck rather than renumbered: a `G-n` that moves is a citation that
silently retargets.
-**G-2 and G-4 stopped being gaps when the basis moved to `176b41b7`, and both became
-conflicts.** A gap is silence; a conflict is a sentence pointing the other way, and
-the two need opposite handling — a gap is closed by adding, a conflict by somebody
-retracting. G-2 was 06's protocol-edit entry having no route: at `176b41b7` the UI
-landing checklist says the protocol selector exists *only* after a failed observation,
-as a probe-order hint, so the contract now **forbids** the control rather than merely
-omitting its route. G-4 was the quiet badge having no field to read: AC-27 now states
-「the stored shape has **no** manual/automatic provenance marker」, which is not an
-absence to be filled but a decision that the badge cannot be rendered. Both fold into
-E-2 in §0.6, and their numbers are struck rather than reused.
+**G-2 and G-4 remain retired, with E-2 superseded in part on 2026-08-26.** G-2 asked
+for a saved-protocol edit route and remains closed by subtraction: changing protocol
+still 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.
+Neither resurrects the retired edit route or invents provenance.
### 0.6 Conflicts raised by this pass — all five now ruled
@@ -443,24 +439,13 @@ recorded here rather than deleted because a resolved conflict is evidence about
next one should go: the escalation was worth its cost precisely because the answer was
*not* the side this lane had drawn.
-**E-2 is closed, and it was the design that moved.** It read: *can a stored protocol be
-changed, and can the surface tell that a human chose it?* One half had already
-narrowed — 05's `undetermined.hint` used to say the value was editable later, and the
-rebuilt frame says 「保存后不可更改」. What remained was the standing instruction to put a
-protocol-edit entry point at frame 06's quiet badge, plus the badge tooltip written to
-match it, and at `ca45aeb6` the contract still rules against the control twice over: the UI
-landing checklist allows a protocol selector 「**only after failed observation**」 as a
-probe-order hint, which excludes one on a saved source's detail page; and AC-27 states
-「the stored shape has **no** manual/automatic provenance marker」, so a badge drawn only
-for human-supplied interfaces has nothing to render *from*.
-
-The owner ruled for the behaviour spec. **The badge is gone from frame 06 and the edit
-entry point with it**, and 05 state ④'s hint carries the whole rule instead —
-「提示只改探测顺序 · 仍要真的连上才会保存;保存后不可更改」. §1.6 no longer specifies a
-badge, an `interfaceBadge` copy row or a tooltip, and no `UI-n` quantifies over one.
-The second contract bullet is why the ruling was inevitable in hindsight: it killed the
-badge whichever way the *edit* question went, because a conditional control whose
-condition is an absent field cannot be drawn at all.
+**E-2 was amended by the 2026-08-26 owner ruling.** A stored protocol still cannot be
+edited and Source still carries no manual/automatic provenance. What changed is the
+preflight and read presentation: frame 05 exposes Auto/manual protocol selection before
+the 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
+edit action. This separates three facts that the older ruling conflated: choosing a
+candidate, proving a protocol, and displaying the proved protocol.
**E-3 is closed, and the design moved again.** It read: *can a source be saved without
a verifying upstream response?* The frames drew 05 state ③ with a 仍要添加 escape, on
@@ -872,14 +857,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 | F5 | `addKey.title` … `addKey.submit` | 添加 → ②; 拉取型号 → ②′; 取消 → dismiss |
+| §1.5 | ① Default | Dialog opened | F5 | `addKey.title` … `addKey.submit`; `addKey.field.protocol`, `addKey.field.protocol.hint`, and all four `addKey.protocol.*` options | Auto detect is selected initially. Choosing a concrete interface constrains both 拉取型号 and 添加 to exactly that protocol. 添加 → ②; 拉取型号 → ②′; 取消 → dismiss |
| §1.5 | ①′ Pull result, **Pull origin** `[derived]` | ②′ came back with an inventory — including after a hint in ④′, and after 重试 reran the entire observation from ⑤′ | F5 — the request already succeeded | `addKey.pull.result`, `addKey.pull.empty`, and ①'s own keys, which all still render | Editing Base URL or API Key → ①, the report dropped; 拉取型号 again → ②′; 添加 → ②, which runs its own observation and reuses nothing from here; 取消 → dismiss |
| §1.5 | ② Adding | 添加 pressed — `POST /api/models/sources/observe` runs first, and `POST /api/models/sources` with one generated `client_nonce` goes out only on the outcome that has consent `[contract]` | → ③ / ④ / ⑤ / ⑦ through O1 | `addKey.adding`, `addKey.adding.detail` | O1 classifies both producers. An accepted explicit observation sends the complete `SourceCreate` with `accept_unavailable_inventory` false / omitted `[contract]`; its committed success envelope 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 | ②′ Pulling, **Pull origin** `[derived]` | 拉取型号 pressed, or 重试 pressed from ③′ / ④′ / ⑤′ | → ③′ / ④′ / ⑤′ | `addKey.adding`, `addKey.adding.detail` | Success → ①′, persisting nothing |
| §1.5 | ③ Failure, **Add origin** | 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 |
| §1.5 | ③′ Failure, **Pull origin** `[derived]` | A probe run by 拉取型号 classified the failure | F1 | as ③ | 重试 → **another 拉取型号, not ②** |
-| §1.5 | ④ Interface undetermined, **Add origin** | 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 | `addKey.undetermined.title`, `addKey.undetermined.detail`, `addKey.undetermined.label`, `addKey.undetermined.hint`, `addKey.protocol.anthropicMessages`, `addKey.protocol.openaiResponses`, `addKey.protocol.openaiChatCompletions`, `addKey.retry` | Pick a hint + 重试 → run the entire explicit observation with that `protocol_order`; identified with discovery succeeded → send the complete `SourceCreate` with `accept_unavailable_inventory` false / omitted `[contract]`, whose result re-enters O1; identified with discovery failed → ⑤; still ambiguous → back to ④ |
-| §1.5 | ④′ Interface undetermined, **Pull origin** `[derived]` | The same outcome, from 拉取型号 | F1 | as ④ | Pick a hint + 重试, still as a pull → identified: → ①′, persisting nothing; still undetermined: back to ④′ |
+| §1.5 | ④ Interface undetermined, **Add origin** | 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 and selector plus `addKey.undetermined.title`, `addKey.undetermined.detail`, and `addKey.retry` | Choose one concrete interface + 重试 → run the entire explicit observation against exactly that protocol; identified with discovery succeeded → send the complete `SourceCreate` with the same `protocol` constraint and `accept_unavailable_inventory` false / omitted `[contract]`, whose result re-enters O1; identified with discovery failed → ⑤; still ambiguous → back to ④ |
+| §1.5 | ④′ Interface undetermined, **Pull origin** `[derived]` | The same outcome, from 拉取型号 | F1 | as ④ | Choose one concrete interface + 重试, still as a pull → identified: → ①′, persisting nothing; still undetermined: back to ④′ |
| §1.5 | ⑤ Identified, inventory unavailable, **Add origin** `[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` | 重试 → run **the entire explicit observation** again. 仍要添加 → send `SourceCreate` 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 |
| §1.5 | ⑤′ Identified, inventory unavailable, **Pull origin** `[derived]` | The same outcome, from 拉取型号 | F1 | as ⑤ without `addKey.addAnyway` | 重试 → run the entire observation again as a pull |
| §1.5 | ⑥ Engine unavailable, **Add origin** `[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 |
@@ -3305,7 +3290,8 @@ refusing: ③ and ④ cannot save at all, ⑤ can.
| --- | --- | --- | --- | --- |
| head sub-line | that Add performs one real connection | static | no | — |
| `f7Ao1U` 名称(可选) | free text | user | yes | — |
-| `cXsiv` Base URL + hint | free text; the hint says any relay/aggregator/self-hosted address works | user | yes | — |
+| Interface type | Auto detect plus Anthropic Messages, OpenAI Responses and OpenAI Chat Completions; Auto detect is selected by default | user | yes | Select the exact probe constraint used by both actions |
+| `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 |
| `zVU7c` / `V6CtoF` 拉取型号 + hint | an optional early pull, which Add performs anyway | — | yes | Enter ②′; render its result in place |
| `S0pOY2` 添加 | — | form validity | yes | Run the add action (connect + identify + fetch) |
@@ -3313,8 +3299,8 @@ refusing: ③ and ④ cannot save at all, ⑤ can.
| `C72yS` state ③ strip | classified outcome copy | observation result | no | — |
| `EJrDH` ③ foot | 取消 / 重试 | — | yes | Dismiss / re-run whatever failed |
| `vKiIo` state ④ strip | connected, interface undetermined | observation result | no | — |
-| `WZyA8` selector | the three interface types, as a **hint to the prober** | static | yes, **nothing pre-selected** | Select one; enables 重试 |
-| `Nak7y` ④ foot | 取消 / 重试 (dimmed until a hint is picked) | selection | yes | — |
+| `WZyA8` selector | the same four interface choices from the form | selection | yes, Auto detect remains selected until changed | Select one concrete interface; enables 重试 |
+| `Nak7y` ④ foot | 取消 / 重试 (dimmed until a concrete interface is picked) | selection | yes | — |
| `d6bFlX` state ⑤ strip | the interface *was* identified, and the model list did not come back | observation result | no | — |
| `x0Gzg` ⑤ foot | 取消 / 仍要添加 / 重试 — **three** buttons, the only foot in the product with three | — | yes | Dismiss / save the source without an inventory / rerun the entire observation |
| `sqZa9` success note | that the dialog closes straight into 06 | static | no | — |
@@ -3325,27 +3311,23 @@ sets no fixed height, so a build that pins one is deviating, not matching. Head
`radius 8` fill `#FFFFFF08`; field hint 10.5 JetBrains Mono `#9BA3B8B3`. 拉取型号
`padding [8,14]` `gap 6`, neutral. Result strip 520 wide `padding [11,13]` `gap 10`
`radius 9`: red `#FF6B6B14`/`#FF6B6B40` for ③, gold `#FFC85714`/`#FFC85759` for ④
-**and for ⑤** (`AFl3g`), mint `#5BFFA014`/`#5BFFA040` for the success note. State ④
-selector `padding 3` `gap 3` on `#FFFFFF0A`/`$--border`, **all three segments fill
-`#00000000`**. Foot `padding [14,20]` `gap 8` on `#FFFFFF05`, top border; buttons
+**and for ⑤** (`AFl3g`), mint `#5BFFA014`/`#5BFFA040` for the success note. The
+form-level selector uses `padding 3` `gap 3` on `#FFFFFF0A`/`$--border`; unselected
+segments fill `#00000000`, while the selected Auto or concrete segment uses the mint
+success fill and ink. Foot `padding [14,20]` `gap 8` on `#FFFFFF05`, top border; buttons
`padding [8,14]` `gap 6`. State ⑤ (`d6bFlX`, 560×148) is the same dialog shell with
one strip (`uKZuq` 560×87 → `AFl3g` 520×59 → `EbcxN` `triangle-alert` + `LePtp`
title/detail) and a three-button foot (`x0Gzg` 560×61 → `SvK44` 取消, `wouXZ`
仍要添加, `o8K7m` 重试); it carries no field, because ⑤ asks the user for nothing.
-**Three of those fills are the design carrying a product rule, not styling.** Every
-segment in ④'s selector is transparent — nothing is pre-selected — and ④'s primary
-`LrUsk` 重试 is `#5BFFA059`, the same dimmed mint that ② uses for its in-flight
-primary and that ⑤'s `o8K7m` 重试 uses. ③'s primary, by contrast, is full `$--mint`.
-The rule underneath all four is one sentence: **full mint means the user has already
-supplied the new information; dimmed mint means pressing it repeats a request the
-user has not changed.** ③ qualifies because fixing the credential field *is* the new
-information. ② is mid-flight, ④ without a hint would re-run the identical probe
-order, and ⑤'s whole observation would re-hit the same endpoint with the same key — in
-⑤ the new information is elapsed time, which the user supplies by waiting rather than
-by editing. A build that pre-selects a segment, or that enables ④'s 重试 before a pick,
-or that promotes ⑤'s whole-observation retry to full mint, is not deviating cosmetically; it has
-implemented the opposite decision.
+**Three of those fills carry state policy, not styling.** Auto detect is selected on the
+initial form. In ④, 重试 stays dimmed and disabled only while the selector remains Auto;
+a concrete interface selected before or after the ambiguous attempt is shown as selected
+and enables the full-mint retry. State ②'s in-flight primary and ⑤'s whole-observation
+retry retain their drawn dimmed mint, while ③'s retry is full `$--mint`. A build that
+defaults the initial form to a concrete interface, enables ④ while it still reads Auto,
+or hides a concrete selection that produced the latest attempt has implemented a
+different decision rather than a cosmetic variation.
**States** — §0.8, rows marked §1.5. Two of them are absences worth stating: this
dialog has no Loading state, because nothing is fetched before it opens, and no Empty
@@ -3360,11 +3342,11 @@ details.
**添加 observes before it persists, and that ordering is what makes ③, ④ and ⑤ offers
rather than notifications** `[contract]`. Each of them asks the user for a
-decision — retry, pick a protocol, add anyway — and a decision offered after the row is
+decision — retry, pick a concrete protocol, add anyway — and a decision offered after the row is
already stored is not a decision; ⑤ is the clearest case, because 仍要添加 is only an
offer if nothing was added when the inventory came back unusable. So 添加 runs the same
non-persisting observation 拉取型号 runs, and `POST /api/models/sources` goes out on one
-of three paths, all of them past a consent: a clean observation, ④'s retry once a hint
+of three paths, all of them past a consent: a clean observation, ④'s retry once a concrete selection
identified the protocol, and ⑤'s 仍要添加. An earlier version had the creation call go
first and the diagnosis come back from it, which needed the persisting route to answer
non-terminally — a response no contract gives it — and left every 重试 in this dialog
@@ -3409,7 +3391,7 @@ happened to ②, whose row said 取消 returned to ① while the axis said an ad
earlier version primed ③ alone, which left ④ and ⑤ silently shared between the two
origins —
and both of their success paths persist a source and close the dialog. A user who
-pressed the optional button, picked a hint, and pressed 重试 would then have created a
+pressed the optional button, picked a concrete interface, and pressed 重试 would then have created a
source they never asked for, or lost the form to 取消; the same hole existed twice
because the fix had been written as a row rather than as a rule. 拉取型号 is labelled
可选 (D-4), and the promise that word makes is *nothing you do here commits anything* —
@@ -3458,7 +3440,7 @@ describes as 「Dialog opened」. ①′ is that state written down: the form ex
renders it, plus `addKey.pull.result` reporting what came back, or `addKey.pull.empty`
when the source answered and listed nothing — the reachable zero this key has, and the
reason it takes a string rather than 「拉到 0 个型号」. It is also where ④′ lands when
- the hint identifies the interface, and where ⑤′'s 重试 lands when the repeated observation
+ the manual selection identifies the interface, and where ⑤′'s 重试 lands when the repeated observation
comes back usable: the same result by a longer road, which is the point of naming it once. Three
properties hold here because it is a Pull-origin state and for no other reason. Nothing
was persisted, so 添加 from here still runs its own observation and reuses none of
@@ -3468,33 +3450,19 @@ abort belongs to ②′, which is where the request still is. A build without th
decide all three from what is on screen, which is the reconstruction the paragraph above
names as the only way to get the origin wrong.
-**④'s selector is a hint to the prober, not a declaration of the answer** `[frame]`
-`[contract]`. The drawn hint is explicit — 「提示只改探测顺序 · 仍要真的连上才会保存;
-保存后不可更改」 — and it settles three things at once that earlier revisions of this
-file got wrong in three different ways:
-
-- **The pick does not persist by itself.** It reorders the probe sequence for the next
- attempt. Identification still has to come from a real upstream response, which is
- AC-27's requirement, reached here by agreement rather than by exception.
-- **The primary is 重试, not a save.** A build that persists the picked protocol
- directly has removed the verification the same screen promises.
-- **Repeated failures must not accumulate silently**: the strip shows the latest
- attempt's evidence, for the order that was tried `[derived]`.
-
-`[derived]` for ④'s entry gate: until a segment is chosen, 重试 stays in the dimmed
-treatment. Retrying with no hint would re-run the identical probe order that just
-failed, and a button that is guaranteed to reproduce the current screen is worse than
-no button. (D-3.)
-
-**This is the one screen in the product where the user supplies a fact the product
-normally derives, and the frame goes out of its way to bound it** — one hint, affecting
-one attempt, not stored as an answer. 「全产品唯一一处让你提示接口类型的地方」 is the
-frame's own caption. At `ca45aeb6` the ledger
-uses the frame's own word for it: AC-27 calls the control 「a one-time three-value
-**probe-order hint**」 and FC-07 contracts it as 「a manual three-value probe-order hint」
-that 「cannot save a protocol without response proof」. The frame and the contract now
-say the same sentence, which is the ideal end state for a `[frame]` `[contract]` pair —
-neither is quoting the other, and they agree anyway.
+**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 selector is visible before the first request, with
+Auto detect selected by default. Auto detect probes the supported interfaces in the
+adapter's authoritative order. A concrete choice probes exactly that interface for both
+拉取型号 and 添加. In either branch, persistence still requires a matching
+protocol-shaped upstream response; the user choice cannot manufacture proof.
+
+State ④ keeps the same selector visible and requires a concrete choice before 重试. The
+primary is still a retry, not a save, and the strip always describes the latest attempt.
+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.
**State ⑤ is the one place in the product that saves something it could not fully
verify, and the rule that makes it safe is a property, not a permission** `[frame]`
@@ -3517,7 +3485,7 @@ is not, because every later request depends on it.
That is why 仍要添加 exists here and nowhere else, and the frame says so in its own
caption: 「全产品唯一一处「仍要添加」」. It is also why the state carries **no field**.
-④ asks the user for a hint because the product is missing something the user might
+④ asks the user for a concrete interface because the product is missing something the user might
know; ⑤ 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.
@@ -3542,11 +3510,11 @@ opposite 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 schema
carries required `vendor` and write-only `key`,
-optional `display_name`, normalized `base_url`, the one-time `protocol_order` hint when
+optional `display_name`, normalized `base_url`, the selected `protocol` constraint when
present, and the generated `client_nonce`. It
carries 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 ordering rather than authority, and ⑤'s
+models and health. Thus ④'s pick remains a probe constraint rather than authority, 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
@@ -3573,8 +3541,10 @@ is revealed; the button carries the verb.
| `title` | 添加 API Key | Add API key |
| `subtitle` | 「添加」时自动连一次:认出接口 + 拉取型号列表 | Add connects once: it identifies the interface and fetches the model list |
| `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.baseUrl` | Base URL | Base URL |
-| `field.baseUrl.hint` | 粘贴任何中转 / 聚合 / 自建服务的地址即可,Avibe 会自己认出接口 | Paste any relay, aggregator or self-hosted address — Avibe identifies the interface itself |
+| `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 |
| `field.apiKey.reveal` | 显示 API Key | Show API key |
| `field.apiKey.conceal` | 隐藏 API Key | Hide API key |
@@ -3585,10 +3555,10 @@ is revealed; the button carries the verb.
| `pull.empty` | 连上了,但这个来源没有可用型号 | Connected, but this source lists no models |
| `submit` | 添加 | Add |
| `adding` | 连接中… | Connecting… |
-| `adding.detail` | 连上 + 认出接口 + 首次拉取型号列表 · 通常 1–3 秒 | Connect, identify the interface, fetch the model list · usually 1–3s |
+| `adding.detail` | 连上 + 验证接口 + 首次拉取型号列表 · 通常 1–3 秒 | Connect, validate the interface, fetch the model list · usually 1–3s |
| `fail.subtitle` | 认出接口是「添加」的前置条件 · 先按下面这条修,再重试 | Identifying the interface is a precondition of Add · fix what the line below names, then retry |
-| `fail.auth` | 鉴权失败 | Authentication failed |
-| `fail.auth.detail` | 检查 API Key 是否有效 | Check whether the API key is valid |
+| `fail.auth` | 上游拒绝了这个凭据 | The upstream rejected this credential |
+| `fail.auth.detail` | 检查 API Key、接口类型和 Base URL 的 API 根路径 | Check the API key, interface type, and the Base URL's API root path |
| `fail.address` `[derived]` | 无法连接这个地址 | Could not reach this address |
| `fail.network` `[derived]` | 连接超时 | The connection timed out |
| `fail.unclassified` `[derived]` | 响应无法归类 | The response could not be classified |
@@ -3597,9 +3567,8 @@ 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 |
-| `undetermined.label` | 接口类型 · 这一次由你提示 | Interface type · you hint it this once |
-| `undetermined.hint` | 提示只改探测顺序 · 仍要真的连上才会保存;保存后不可更改 | The hint only reorders the probe · it still has to really connect before anything is saved, and it cannot be changed afterwards |
+| `undetermined.detail` | 返回结构对不上任何一种已知接口,请选择一个明确类型后重试 | The response shape matches no interface we know; choose a concrete interface and retry |
+| `protocol.auto` | 自动探测 | Auto detect |
| `protocol.anthropicMessages` | Anthropic Messages | Anthropic Messages |
| `protocol.openaiResponses` | OpenAI Responses | OpenAI Responses |
| `protocol.openaiChatCompletions` | OpenAI Chat Completions | OpenAI Chat Completions |
@@ -3706,7 +3675,7 @@ 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, **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 · 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 编辑来源 · 移除来源 |
| 重新拉取 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 |
@@ -3715,7 +3684,7 @@ them do I actually want, and what reasoning tiers does each accept?* Nothing els
| `eVavA` tiers (editing) | removable chips + text input + 回车添加 · 任意文本 | local edit → `PATCH /api/models/sources/<source_id>/models/<model_id>` `[contract]` | yes | Add / remove a tier |
| `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 identified at add time, fixed, and neither shown nor editable here | static | no | — |
+| `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 | — |
**The back icon is named rather than inferred** `[derived]`. `iGcAi` is this page's only
route back to 01 and draws no text, so `sourceDetail.back` carries its accessible name in
@@ -4240,7 +4209,7 @@ Five rules:
| `addRow.hint` | 拉取不到、或只想接入其中一个时用 | Use this when a model is not discoverable, or when you only want one of them |
| `empty` `[derived]` | 这个来源没有返回型号。可以手动添加,或重新拉取。 | This source returned no models. Add one by hand, or refetch. |
| `emptyNeverFetched` `[derived]` | 还没有成功拉取过这个来源的型号列表。可以按上面状态里写的那条先处理,再拉一次,或者手动添加一个型号。 | This source's model list has never come back. Deal with whatever the status above reports, fetch again, or add a model by hand. |
-| `footnote` | 这里只管「这个来源有哪些型号」。型号走哪条路由链,在网关模块里改。档位自己填,两种录入方式都一样。接口类型在添加时认出并固定,页面上不显示、也不能改。 | This page answers only "which models does this source have". Which routing chain a model takes is set in the gateway module. Tiers are yours to type, the same for both entry kinds. The interface type is identified when the source is added and fixed there — it is neither shown on this page nor editable. |
+| `footnote` | 这里只管「这个来源有哪些型号」。型号走哪条路由链,在网关模块里改。档位自己填,两种录入方式都一样。接口类型在添加时确认并固定,页面会显示、但不能修改。 | This page answers only "which models does this source have". Which routing chain a model takes is set in the gateway module. Tiers are yours to type, the same for both entry kinds. The interface type is confirmed when the source is added, shown here, and not editable. |
**The four discovery results are rendered at two different grains, and one of them has
no row to land on** `[derived]` `[spec §4.2]`. `model-hub.md` requires discovery to render
@@ -4328,29 +4297,14 @@ probe. A freshness stamp next to a refetch button is a closed loop the user can
act on. A latency figure next to a refetch button would invite exactly the conflation
the previous rule forbids.
-**This page shows no protocol at all, and that is the resolution of E-2** `[frame]`.
-Earlier revisions of this section specified a quiet badge next to the source name —
-「接口由你指定」 — with a tooltip naming the stored protocol and a 「改为…」 action
-behind it. Both are gone, and the frame no longer draws either. The ruling took the
-subtractive branch of the conflict: the stored shape at `ca45aeb6` carries no
-manual/automatic provenance marker (AC-27), so a badge conditioned on 「由你指定」 has
-nothing to render *from*; and 「changing protocol requires a new Source」, so an edit
-affordance would advertise an operation the API cannot perform: `PATCH
-/api/models/sources/<source_id>` `[contract]` has no protocol field to send it in.
-
-What replaced both is one clause in the footnote: 「接口类型在添加时认出并固定,页面上
-不显示、也不能改。」 That is a better outcome than either half of the original design,
-and the reason generalizes past this frame. A badge that renders on *some* sources
-teaches every user that protocols are a thing they may have to think about, in exchange
-for a fact that changes nothing they can do — which is the mechanism D-8 spends its
-whole argument hiding. Stating the rule once, in the place where a user might go
-looking for the control, costs one sentence and leaves nothing conditional to
-implement. The 「type is fixed」 half of the rule is also stated at the only moment it
-can still be acted on, in 05 state ④'s hint (§1.5).
-
-Consequently no `interfaceBadge*` copy key exists, no `UI-n` quantifies over a badge,
-and D-8's 「the user does not perceive the supply mechanism」 now holds on frame 06
-without an exception clause.
+**The source identity label is unconditional and non-editable** `[frame]` `[contract]`.
+The card and detail header show `provider or endpoint host · proved protocol`, for
+example `ai-relay.chainbot.io · Anthropic Messages`. It is not the retired
+「接口由你指定」 badge: Source carries no manual/automatic provenance, so the label never
+claims how the protocol was selected. `PATCH /api/models/sources/<source_id>` still has
+no protocol field; changing it requires a new Source.
+Consequently no `interfaceBadge.manual` or protocol-edit copy exists. The ordinary
+identity pill is always present and reads only persisted endpoint/protocol facts.
**Extreme data** `[derived]`: the table does not collapse — the whole point of the
page is the full inventory, so it scrolls (the frame's 13 rows are an instance, not
@@ -4871,8 +4825,8 @@ stroke `#FF6B6B40`, a `circle-x` in `#FF8A8A`, title Inter 12 / 600 in `#FF8A8A`
machine detail under it in JetBrains Mono 10.5 `#9BA3B8B3`. Nothing else in the dialog
changes — the bullets stay, 取消 stays, and 切换到网关 stays in its full mint treatment.
That last point is the one place this differs from §1.5's dimmed-重试 rule, and the
-difference is real rather than an exception: there, a retry with no new hint re-runs an
-identical probe and is guaranteed to reproduce the screen; here the input was never the
+difference is real rather than an exception: there, an ambiguous Auto result cannot
+progress until the user supplies a concrete interface; here the input was never the
thing that failed, so a second press is not a guaranteed repeat. Stating it this way
keeps one rule — *a control is dimmed when pressing it cannot change the outcome* —
rather than two rules that happen to disagree.
@@ -5356,20 +5310,18 @@ self-hosted endpoint are all *an API key with a custom base URL*.
*Why:* the official/unofficial split is unanswerable for compatible endpoints, and
a category the product cannot adjudicate becomes a label that lies. `[spec §3]`
-**D-2 — The user never picks the interface protocol.** The add action performs one
-real upstream request and identifies it.
-*Why:* it is derivable from evidence the product can obtain in one round trip. A
-field the product can answer itself is a field the user can only get wrong.
-
-**D-3 — When identification fails, ask for a hint instead of guessing.** State ④ is
-the single protocol selector in the product; nothing is pre-selected, the pick reorders
-the probe rather than answering for it, and 重试 stays dimmed until a hint exists.
-*Why:* **guessing stores an unverifiable value that fails later, at request time,
-far from the moment the user could have fixed it in one click.** One question now
-is cheaper than a wrong value forever. This is also why the *picture* enforces it:
-an unselected control and a dimmed button cannot silently default. Asking for a hint
-rather than an answer is what keeps this compatible with D-4 — the user narrows the
-search, the upstream still supplies the fact.
+**D-2 — Protocol selection is explicit but never self-proving.** The add form offers
+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.
+
+**D-3 — Manual selection narrows verification; it never bypasses it.** A concrete
+selection produces exactly one candidate probe. State ④ keeps the form and selector
+visible, and Retry stays dimmed while Auto remains selected after auto-detection was
+ambiguous.
+*Why:* one visible owner for the candidate removes probe-order uncertainty without
+turning a user claim into a stored fact. A matching upstream response remains the gate.
**D-4 — Identification is a gate; the model pull is not.** Nothing persists until an
upstream response identifies the interface — state ③ offers only 取消 / 重试 — while
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index 500190445..8ab24f31e 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -173,12 +173,15 @@ card data, not persisted Source state, and clients never reconstruct it from liv
The Source workflow is complete at both entry points:
-- **Connectivity and protocol observation.** The normal Add Source form asks only for
- optional name, Base URL, and API key. Its user-triggered Add action reuses one
- connectivity interaction to classify reachability/authentication and observe the
- protocol before Save can commit; it adds no separate step and presents no protocol
- selector. 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
+- **Connectivity and protocol observation.** The normal Add Source form asks for an
+ optional name, an interface selection (Auto detect by default), Base URL, and API key.
+ A concrete interface restricts the preflight to one candidate; Auto detect tries the
+ supported candidates in the adapter's authoritative order. The user-triggered Add
+ action reuses one connectivity interaction to classify reachability/authentication
+ and prove the protocol before Save can commit. Its schema-invalid probe settles before
+ a relay selects or invokes a model, so observation never depends on a synthetic model
+ being 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
transiently:
every success, failure, timeout, and cancellation path revokes that ref before the
operation settles. A revoke failure enters the existing durable pending-revocation
@@ -187,6 +190,12 @@ The Source workflow is complete at both entry points:
independently from protocol observation: Save may proceed only when that interaction
still produced response evidence for the protocol, and it provisions the committed
Source 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
+ CPA's existing `claude-api-key`, `codex-api-key`, or `openai-compatibility` provider
+ section and every Agent invocation runs through CPA. Avibe owns only the bounded
+ pre-save evidence 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: it
tests the stored protocol, rediscovers inventory, updates Source health, and clears a
@@ -244,10 +253,12 @@ The Source workflow is complete at both entry points:
**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-
-only `protocol_order`, client-generated `client_nonce`, and boolean
+constraining `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`. Source identity, protocol
+`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
evidence, discovered inventory, health, usage, custody metadata, and timestamps remain
server-owned. When supplied, `client_nonce` is unique among live Sources and live-process
create reservations. The server reserves it atomically in process before observation or
@@ -327,21 +338,21 @@ nonempty. Create materialization and re-auth failures with no stranded sibling e
plain-error row. No later Source read can reconstruct the historical report, so the
error envelope carries it exactly once.
-**Protocol observation (owner ruling 2026-08-09, superseding AC-27's 2026-08-07
-manual-choice 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;
-known-vendor metadata may order the three probes but cannot produce a conclusion or a
-save-time default. When observation cannot distinguish a protocol, the failure state
-honestly asks the user for a one-time manual hint among the same three values. The hint
-changes probe order only: its selected adapter must still receive a successful upstream
-response before Save. A failed observation therefore stores nothing rather than guessing.
+**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.
Once saved, `protocol` is immutable for that Source. Connectivity retest, model
discovery, refresh, credential replacement, Base URL replacement, and restart all use
the 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 probe ordering become indistinguishable after the
+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
uncertainty belongs to Source health, not protocol identity. Every saved Source therefore
@@ -477,7 +488,8 @@ The `matching-v1` decision is normative and exhaustive:
```text
for each configuration-eligible Source added in this transaction:
- observed = response_backed_observation(Source, protocol_order)
+ candidates = [request.protocol] if selected else SOURCE_PROTOCOLS
+ observed = response_backed_observation(Source, candidates)
if observed.protocol is null:
persist no Source and no Route hop
return the classified observation failure
@@ -1443,7 +1455,7 @@ Required interaction rules:
a consent flow. When a backend already has its singleton native Source, its native
choice is disabled rather than creating an alias for the same CLI login.
- Add Source exposes §4.1's combined connectivity/protocol observation and compatible
- model discovery without a normal protocol control. Source details exposes only the
+ model discovery with Auto detect plus a manual three-protocol selector. Source details exposes only the
separately named mutating “Refresh models” / 「重新拉取」 action against the stored
protocol; it has no “Test connectivity” button or second discovery mutation. Results
stay in the current flow and use compact status plus an
@@ -1451,8 +1463,8 @@ Required interaction rules:
paragraphs. Every inventory model exposes an editable per-model `reasoning_efforts`
list beside the exact id. The list has no default item or selected state; the control
form follows the owner-approved `design.pen` baseline and is not prescribed here. A
- protocol selector appears only inside an observation-failure state and its hint still
- requires a successful response before Save. Source freshness may say only “Model list
+ selection constrains the first observation and every retry but still requires a
+ successful response before Save. Source freshness may say only “Model list
updated at …” / 「型号列表更新于…」 from `last_discovered_at`; latency and “last
checked” copy are absent.
- Compatibility detail for converted or cross-vendor supply stays behind a compact
@@ -1605,10 +1617,10 @@ one pinned hop it receives.
executed exactly; that hop may use an API key or a hub-held subscription and requires
no 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. If observation
- fails, the product may ask once for a manual probe-order hint, but the hinted adapter
- must still return a successful response before anything is saved. No later operation
- changes the stored value.
+ 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
+ the stored value.
- No billing-grade accounting, multi-tenant pools, or operator consoles.
- No third source category ("relay" merged into API Key).
- No v3 Configure Agents module (§5), runtime plugin UI, or GA scope beyond the
@@ -1664,7 +1676,8 @@ directions into questions that later lanes must answer before writing mechanical
every saved protocol is response-proven before Save and immutable afterward,
with no persistent provenance marker or protocol-level unverified value.
- [ ] §4.1 exposes exactly `anthropic | openai_responses | openai_chat`, retains Chat
- Completions, and shows protocol choices only after observation cannot decide.
+ Completions, and shows Auto detect plus those three protocol choices before
+ observation; an ambiguous Auto result requires one concrete choice to retry.
- [ ] §4.2 alone owns Add Source placement: every accepted match is persisted at one
deterministic policy-chosen position that is visible and adjustable; no later
path reruns placement, and no UI test infers newness from position.
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 4e48ab39a..70a6220a7 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -101,6 +101,12 @@ scenarios:
kind: contract
layer: scenario
test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_protocol_002_contract_exposes_only_the_three_authoritative_transports
+ - id: MH-PROTOCOL-003
+ name: Manual protocol selection constrains observation and persists only matching response proof
+ status: covered
+ kind: observation
+ layer: scenario
+ test: tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py::test_mh_protocol_003_manual_selection_requires_matching_response_proof
- id: MH-AC29-001
name: A persisted import-shaped Source survives canonical serialization and reload
status: covered
diff --git a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
index 59823db40..4aa1affca 100644
--- a/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
+++ b/tests/scenarios/model_hub/test_model_hub_configured_route_scenarios.py
@@ -398,11 +398,6 @@ def test_mh_protocol_001_saved_protocol_is_response_observed_and_transient_state
"vendor": "custom",
"base_url": "https://upstream.example/v1",
"key": "sk-scenario-observe-key",
- "protocol_order": [
- "openai_chat",
- "openai_responses",
- "anthropic",
- ],
}
)
)
@@ -457,6 +452,75 @@ def test_mh_protocol_002_contract_exposes_only_the_three_authoritative_transport
assert len(schema_protocols) == len(set(schema_protocols))
+def test_mh_protocol_003_manual_selection_requires_matching_response_proof(
+ tmp_path: Path,
+) -> None:
+ """MH-PROTOCOL-003: manual selection probes one type and never overrides evidence."""
+
+ store = MemoryModelHubStore(config_with_sources([]))
+ adapter = ModelHubScenarioAdapter(
+ observation=SourceObservation(
+ outcome=ObservationOutcome.OBSERVED,
+ reachable=True,
+ authenticated=True,
+ protocol="openai_responses",
+ discovery=ObservationDiscovery.SUCCEEDED,
+ model_ids=("selected-model",),
+ )
+ )
+ service = service_for(tmp_path, store, adapter)
+
+ created = asyncio.run(
+ service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "custom",
+ "base_url": "https://relay.example/v1",
+ "key": "sk-scenario-manual-protocol",
+ "protocol": "openai_responses",
+ }
+ )
+ )
+
+ assert created["source"]["protocol"] == "openai_responses"
+ assert adapter.observation_calls == [
+ ("custom", "https://relay.example/v1", ("openai_responses",))
+ ]
+ assert adapter.revoked == adapter.provisioned_transient
+
+ mismatch_store = MemoryModelHubStore(config_with_sources([]))
+ mismatch_adapter = ModelHubScenarioAdapter(
+ observation=SourceObservation(
+ outcome=ObservationOutcome.OBSERVED,
+ reachable=True,
+ authenticated=True,
+ protocol="openai_chat",
+ discovery=ObservationDiscovery.SUCCEEDED,
+ model_ids=("wrong-protocol-model",),
+ )
+ )
+ mismatch_service = service_for(
+ tmp_path / "mismatch",
+ mismatch_store,
+ mismatch_adapter,
+ )
+ with pytest.raises(ModelHubError) as mismatch:
+ asyncio.run(
+ mismatch_service.create_source(
+ {
+ "kind": "api_key",
+ "vendor": "custom",
+ "base_url": "https://relay.example/v1",
+ "key": "sk-scenario-mismatched-protocol",
+ "protocol": "openai_responses",
+ }
+ )
+ )
+ assert mismatch.value.status == 502
+ assert mismatch_store.load().sources == []
+ assert mismatch_adapter.revoked == mismatch_adapter.provisioned_transient
+
+
def test_mh_ac29_001_persisted_source_payload_round_trips_through_the_canonical_validator(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.py
index 51c1f47c4..e09f5bdb8 100644
--- a/tests/test_model_hub_api.py
+++ b/tests/test_model_hub_api.py
@@ -1500,7 +1500,13 @@ def test_source_create_nonce_covers_in_flight_committed_and_deleted_states(tmp_p
@pytest.mark.parametrize(
"malformed_fields",
[
- pytest.param({"protocol_order": ["anthropic"]}, id="protocol-order"),
+ pytest.param({"protocol_order": ["anthropic"]}, id="retired-protocol-order"),
+ pytest.param({"protocol": None}, id="null-protocol"),
+ pytest.param({"protocol": "unknown"}, id="unknown-protocol"),
+ pytest.param(
+ {"accept_unavailable_inventory": "yes"},
+ id="non-boolean-unavailable-inventory-consent",
+ ),
pytest.param({"billing": "credits"}, id="billing"),
pytest.param(
{
@@ -2507,6 +2513,87 @@ def test_unsaved_observation_route_returns_valid_result_and_revokes_transient_re
assert "credential_ref" not in json.dumps(body)
+def test_unsaved_observation_route_restricts_a_manual_protocol_to_one_probe(
+ 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": "custom",
+ "base_url": "https://relay.example/v1",
+ "key": "sk-test-observation-manual",
+ "protocol": "openai_responses",
+ },
+ headers=csrf_headers(client, base_url),
+ base_url=base_url,
+ )
+
+ assert response.status_code == 200
+ assert response.get_json()["observation"]["protocol"] == "openai_responses"
+ assert adapter.observed_protocol_orders == [("openai_responses",)]
+ assert store.config.sources == []
+ assert adapter.revoked == ["cred_test001"]
+
+
+def test_source_create_requires_explicit_consent_for_proven_inventory_failure(
+ tmp_path,
+):
+ store = MemoryStore()
+ adapter = FakeAdapter()
+ adapter.observation = SourceObservation(
+ outcome=ObservationOutcome.OBSERVED,
+ reachable=True,
+ authenticated=True,
+ protocol="anthropic",
+ discovery=ObservationDiscovery.FAILED,
+ model_ids=(),
+ )
+ service = ModelHubService(
+ store=store,
+ adapter=adapter,
+ events=BoundedEventLog(tmp_path / "events.json"),
+ oauth_flows=OAuthFlowRegistry(tmp_path / "oauth_flows.json"),
+ revocations=CredentialRevocationJournal(tmp_path / "revocations.json"),
+ )
+ payload = {
+ "kind": "api_key",
+ "vendor": "custom",
+ "base_url": "https://relay.example/v1",
+ "key": "sk-test-inventory-consent",
+ "protocol": "anthropic",
+ }
+
+ with pytest.raises(ModelHubError) as rejected:
+ asyncio.run(service.create_source(payload))
+
+ assert rejected.value.status == 422
+ assert rejected.value.data["observation"]["discovery"] == "failed"
+ assert store.config.sources == []
+ assert adapter.revoked == ["cred_test001"]
+
+ created = asyncio.run(
+ service.create_source(
+ {**payload, "accept_unavailable_inventory": True}
+ )
+ )["source"]
+
+ assert created["protocol"] == "anthropic"
+ assert created["models"] == []
+ assert created["state"] == {
+ "status": "error",
+ "retry_at": None,
+ "detail_key": "models.source.error.unclassified",
+ }
+ assert len(store.config.sources) == 1
+ assert adapter.revoked == ["cred_test001", "cred_test002"]
+
+
def test_source_order_route_rejects_retired_policy_payload(monkeypatch, tmp_path):
service, _, _ = _service(tmp_path)
monkeypatch.setattr(ui_server, "_model_hub_service", lambda: service)
diff --git a/tests/test_model_hub_l3.py b/tests/test_model_hub_l3.py
index f9cc3965b..47641662e 100644
--- a/tests/test_model_hub_l3.py
+++ b/tests/test_model_hub_l3.py
@@ -4865,11 +4865,29 @@ def test_shared_openai_authentication_rejection_does_not_prove_a_protocol() -> N
)
+def test_top_level_authentication_rejection_is_classified_without_forging_protocol() -> None:
+ body = json.dumps({"code": "INVALID_API_KEY", "message": "Invalid API key"})
+
+ for protocol in SOURCE_PROTOCOLS:
+ assert _parse_protocol_authenticated_evidence(
+ protocol,
+ 401,
+ body,
+ ) == _ProtocolEvidence(
+ protocol=_ProtocolProof.UNPROVEN,
+ authentication=_AuthenticationEvidence.REJECTED,
+ )
+
+
def test_protocol_observation_consumers_cannot_classify_from_status_codes() -> None:
module_path = Path(__file__).parents[1] / "vibe/model_hub_runtime/adapter.py"
module_source = module_path.read_text(encoding="utf-8")
tree = ast.parse(module_source)
assert _PROTOCOL_OBSERVATION_TAXONOMY.keys() == set(SOURCE_PROTOCOLS)
+ assert _PROTOCOL_OBSERVATION_TAXONOMY["anthropic"].request_body == {
+ "max_tokens": 0,
+ "messages": [],
+ }
assert _PROTOCOL_OBSERVATION_TAXONOMY["openai_responses"].request_path != _PROTOCOL_OBSERVATION_TAXONOMY[
"openai_chat"
].request_path
@@ -4970,6 +4988,40 @@ def test_protocol_observation_preserves_query_on_each_distinct_upstream_path() -
]
+def test_protocol_observation_adds_standard_v1_paths_to_a_bare_origin() -> None:
+ async def scenario() -> list[str]:
+ requests: list[str] = []
+
+ async def capture_probe(request: web.Request) -> web.Response:
+ requests.append(request.path)
+ return web.json_response({"error": {"type": "invalid_request"}}, 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]
+ try:
+ for protocol in SOURCE_PROTOCOLS:
+ await _probe_protocol_response(
+ vendor="custom",
+ protocol=protocol,
+ base_url=f"http://127.0.0.1:{port}",
+ secret="test-observation-key",
+ )
+ finally:
+ await runner.cleanup()
+ return requests
+
+ assert asyncio.run(scenario()) == [
+ _PROTOCOL_OBSERVATION_TAXONOMY[protocol].request_path
+ for protocol in SOURCE_PROTOCOLS
+ ]
+
+
def test_openai_probe_requests_are_mutually_distinguishable() -> None:
responses = _PROTOCOL_OBSERVATION_TAXONOMY["openai_responses"]
chat = _PROTOCOL_OBSERVATION_TAXONOMY["openai_chat"]
@@ -5033,6 +5085,37 @@ def test_model_discovery_preserves_query_when_appending_models_path() -> None:
assert models == ("upstream-model",)
+def test_model_discovery_adds_standard_v1_path_to_a_bare_origin() -> None:
+ async def scenario() -> str:
+ request_path = ""
+
+ async def list_models(request: web.Request) -> web.Response:
+ nonlocal request_path
+ request_path = request.path
+ return web.json_response({"data": [{"id": "upstream-model"}]})
+
+ app = web.Application()
+ app.router.add_get("/{tail:.*}", list_models)
+ 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]
+ try:
+ await probe_models(
+ vendor="custom",
+ protocol="anthropic",
+ base_url=f"http://127.0.0.1:{port}",
+ secret="test-observation-key",
+ )
+ finally:
+ await runner.cleanup()
+ return request_path
+
+ assert asyncio.run(scenario()) == "/v1/models"
+
+
def test_blocked_exact_hop_emits_one_supply_interruption(tmp_path: Path) -> None:
source = _source("src_blocked01", "Blocked")
service = _service(tmp_path, sources=[source])
diff --git a/tests/test_model_hub_resolution.py b/tests/test_model_hub_resolution.py
index a9d629378..ee35336be 100644
--- a/tests/test_model_hub_resolution.py
+++ b/tests/test_model_hub_resolution.py
@@ -1475,18 +1475,12 @@ def test_create_source_persists_only_the_response_proven_protocol(tmp_path):
"vendor": "openai",
"display_name": "Observed key",
"key": "sk-test-response-proof",
- "protocol_order": [
- "openai_responses",
- "anthropic",
- "openai_chat",
- ],
+ "protocol": "openai_responses",
}
)
)
- assert adapter.observed_protocol_orders == [
- ("openai_responses", "anthropic", "openai_chat")
- ]
+ assert adapter.observed_protocol_orders == [("openai_responses",)]
assert result["source"]["protocol"] == "openai_responses"
assert store.load().sources[0].protocol == "openai_responses"
assert adapter.revoked == ["cred_00000001"]
@@ -1509,11 +1503,7 @@ def test_create_source_normalizes_vendor_before_matching_v1_placement(tmp_path):
"vendor": "OpenAI",
"display_name": "Observed key",
"key": "sk-test-vendor-normalization",
- "protocol_order": [
- "openai_responses",
- "openai_chat",
- "anthropic",
- ],
+ "protocol": "openai_responses",
}
)
)
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
index 564f8cbb5..6a31e8021 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.test.tsx
@@ -17,7 +17,6 @@ import type {
import {
CONTRACT_VERSION,
SOURCE_DISPLAY_NAME_MAX_LENGTH,
- SOURCE_PROTOCOLS,
type RouteHopRef,
type Source,
type SourceObservation,
@@ -162,7 +161,27 @@ describe('AddApiKeyDialog', () => {
expect(screen.queryByText(/Fetched 2 models|拉到 2 个型号/i)).toBeNull();
});
- it('uses the interface choice only as the next complete probe order', async () => {
+ it('sends one manually selected interface on the first observation and create', async () => {
+ const observe = vi.spyOn(modelsApi, 'observeApiKeySource')
+ .mockResolvedValueOnce(observed({ protocol: 'openai_responses' }));
+ const create = vi.spyOn(modelsApi, 'createApiKeySource').mockResolvedValueOnce({
+ source,
+ added_to: [],
+ adopted_by: [],
+ });
+ renderDialog();
+ const user = await fillCredentials();
+
+ expect(screen.getByRole('button', { name: /Auto detect|自动探测/i }).getAttribute('aria-pressed')).toBe('true');
+ await user.click(screen.getByRole('button', { name: 'OpenAI Responses' }));
+ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));
+
+ await waitFor(() => expect(create).toHaveBeenCalledOnce());
+ expect(observe.mock.calls[0][0].protocol).toBe('openai_responses');
+ expect(create.mock.calls[0][0].protocol).toBe('openai_responses');
+ });
+
+ it('turns an ambiguous auto-detection into one exact manual retry', async () => {
const observe = vi.spyOn(modelsApi, 'observeApiKeySource')
.mockResolvedValueOnce(observed({
outcome: 'ambiguous',
@@ -188,10 +207,8 @@ describe('AddApiKeyDialog', () => {
await waitFor(() => expect(create).toHaveBeenCalledOnce());
const secondObservation = observe.mock.calls[1][0];
- expect(secondObservation.protocol_order?.[0]).toBe('openai_responses');
- expect(new Set(secondObservation.protocol_order)).toEqual(new Set(SOURCE_PROTOCOLS));
- expect(create.mock.calls[0][0]).not.toHaveProperty('protocol');
- expect(create.mock.calls[0][0].protocol_order?.[0]).toBe('openai_responses');
+ expect(secondObservation.protocol).toBe('openai_responses');
+ expect(create.mock.calls[0][0].protocol).toBe('openai_responses');
expect(onAdded).toHaveBeenCalledWith({ source, added_to: [], adopted_by: [] });
});
@@ -215,8 +232,8 @@ describe('AddApiKeyDialog', () => {
await user.click(await screen.findByRole('button', { name: /Add anyway|仍要添加/i }));
await waitFor(() => expect(create).toHaveBeenCalledOnce());
- expect(create.mock.calls[0][0]).not.toHaveProperty('protocol');
- expect(create.mock.calls[0][0].protocol_order?.[0]).toBe('openai_chat');
+ expect(create.mock.calls[0][0].protocol).toBe('openai_chat');
+ expect(create.mock.calls[0][0].accept_unavailable_inventory).toBe(true);
});
it('adopts the new observation result when inventory retry moves to interface undetermined', async () => {
@@ -243,6 +260,29 @@ describe('AddApiKeyDialog', () => {
expect(screen.queryByRole('button', { name: /Add anyway|仍要添加/i })).toBeNull();
});
+ it('preserves unavailable-inventory consent across lost-response reconciliation', async () => {
+ vi.spyOn(modelsApi, 'observeApiKeySource').mockResolvedValueOnce(
+ observed({ discovery: 'failed', models: [] }),
+ );
+ const create = vi.spyOn(modelsApi, 'createApiKeySource')
+ .mockRejectedValueOnce(new TypeError('response lost'))
+ .mockResolvedValueOnce({ source, added_to: [], adopted_by: [] });
+ vi.spyOn(modelsApi, 'listSources').mockResolvedValueOnce([]);
+ renderDialog();
+ const user = await fillCredentials();
+
+ await user.click(screen.getByRole('button', { name: /^Add$|^添加$/i }));
+ await user.click(await screen.findByRole('button', { name: /Add anyway|仍要添加/i }));
+ await user.click(await screen.findByRole('button', { name: /^Retry$|^重试$/i }));
+
+ await waitFor(() => expect(create).toHaveBeenCalledTimes(2));
+ expect(create.mock.calls.map(([draft]) => draft.accept_unavailable_inventory)).toEqual([
+ true,
+ true,
+ ]);
+ expect(create.mock.calls[1][0].client_nonce).toBe(create.mock.calls[0][0].client_nonce);
+ });
+
it('aborts an in-flight pull and returns to the form without dismissing', async () => {
let wasAborted = false;
vi.spyOn(modelsApi, 'observeApiKeySource').mockImplementation((_draft, signal) => new Promise((_resolve, reject) => {
diff --git a/ui/src/components/settings/models/AddApiKeyDialog.tsx b/ui/src/components/settings/models/AddApiKeyDialog.tsx
index 79d7d1124..e4407353d 100644
--- a/ui/src/components/settings/models/AddApiKeyDialog.tsx
+++ b/ui/src/components/settings/models/AddApiKeyDialog.tsx
@@ -22,7 +22,6 @@ import {
classifyObservation,
isAbortError,
PROTOCOL_COPY_KEYS,
- protocolOrderWithHint,
type AddApiKeyFailure,
type AddApiKeyOrigin,
} from './addApiKeyState';
@@ -56,12 +55,22 @@ type Phase =
| { kind: 'form'; report: SourceObservation | null }
| { kind: 'working'; origin: AddApiKeyOrigin; stage: 'observe' | 'persist' }
| { kind: 'failure'; origin: AddApiKeyOrigin; cause: AddApiKeyFailure }
- | { kind: 'undetermined'; origin: AddApiKeyOrigin; observation: SourceObservation; hint: SourceProtocol | null }
+ | { kind: 'undetermined'; origin: AddApiKeyOrigin; observation: SourceObservation }
| { kind: 'inventory'; origin: AddApiKeyOrigin; observation: SourceObservation }
- | { kind: 'persist_failure'; messageKey: string | null; protocolOrder: SourceProtocol[] | undefined }
- | { kind: 'save_unconfirmed'; protocolOrder: SourceProtocol[] | undefined };
+ | {
+ kind: 'persist_failure';
+ messageKey: string | null;
+ protocol: SourceProtocol | undefined;
+ acceptUnavailableInventory: boolean;
+ }
+ | {
+ kind: 'save_unconfirmed';
+ protocol: SourceProtocol | undefined;
+ acceptUnavailableInventory: boolean;
+ };
const INITIAL_PHASE: Phase = { kind: 'form', report: null };
+type ProtocolSelection = 'auto' | SourceProtocol;
type ReplaceOutcome =
| { kind: 'repaired' }
@@ -196,6 +205,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
const [displayName, setDisplayName] = React.useState('');
const [baseUrl, setBaseUrl] = React.useState('');
const [apiKey, setApiKey] = React.useState('');
+ const [protocolSelection, setProtocolSelection] = React.useState<ProtocolSelection>('auto');
const [revealed, setRevealed] = React.useState(false);
const [phase, setPhase] = React.useState<Phase>(INITIAL_PHASE);
const [replacePhase, setReplacePhase] = React.useState<ReplacePhase>({ kind: 'edit' });
@@ -221,6 +231,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
setDisplayName('');
setBaseUrl('');
setApiKey('');
+ setProtocolSelection('auto');
setRevealed(false);
setPhase(INITIAL_PHASE);
setReplacePhase({ kind: 'edit' });
@@ -259,20 +270,28 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
if (settle) void settle().catch(() => undefined);
}, [continuation]);
- const draft = React.useCallback((protocolOrder?: SourceProtocol[]): ApiKeySourceCreate => ({
+ const draft = React.useCallback((
+ protocol?: SourceProtocol,
+ acceptUnavailableInventory = false,
+ ): ApiKeySourceCreate => ({
kind: 'api_key',
vendor: 'custom',
...(displayName.trim() ? { display_name: displayName.trim() } : {}),
base_url: baseUrl.trim(),
key: apiKey.trim(),
client_nonce: clientNonce.current,
- ...(protocolOrder ? { protocol_order: protocolOrder } : {}),
+ ...(protocol ? { protocol } : {}),
+ ...(acceptUnavailableInventory ? { accept_unavailable_inventory: true } : {}),
}), [apiKey, baseUrl, displayName]);
- const persist = React.useCallback(async (seq: ContinuationTicket, protocolOrder?: SourceProtocol[]) => {
+ const persist = React.useCallback(async (
+ seq: ContinuationTicket,
+ protocol?: SourceProtocol,
+ acceptUnavailableInventory = false,
+ ) => {
if (continuation.settle(seq, () => setPhase({ kind: 'working', origin: 'add', stage: 'persist' })) === 'stale') return;
try {
- const created = await modelsApi.createApiKeySource(draft(protocolOrder));
+ const created = await modelsApi.createApiKeySource(draft(protocol, acceptUnavailableInventory));
createdDelivery.settle(continuation, seq, created);
} catch (error) {
const failure = apiFailure(error);
@@ -285,7 +304,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
continuation.settle(seq, () => {
if (definitiveClientFailure && verdict && verdict.kind !== 'ready') {
if (verdict.kind === 'undetermined') {
- setPhase({ kind: 'undetermined', origin: 'add', observation: verdict.observation, hint: null });
+ setPhase({ kind: 'undetermined', origin: 'add', observation: verdict.observation });
} else if (verdict.kind === 'inventory') {
setPhase({ kind: 'inventory', origin: 'add', observation: verdict.observation });
} else {
@@ -294,15 +313,20 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
return;
}
setPhase(definitiveClientFailure
- ? { kind: 'persist_failure', messageKey: failureMessageKey(failure), protocolOrder }
- : { kind: 'save_unconfirmed', protocolOrder });
+ ? {
+ kind: 'persist_failure',
+ messageKey: failureMessageKey(failure),
+ protocol,
+ acceptUnavailableInventory,
+ }
+ : { kind: 'save_unconfirmed', protocol, acceptUnavailableInventory });
});
}
}, [continuation, createdDelivery, draft]);
const observe = React.useCallback(async (
origin: AddApiKeyOrigin,
- protocolOrder?: SourceProtocol[],
+ protocol?: SourceProtocol,
) => {
const seq = continuation.begin();
observationAbort.current?.abort();
@@ -314,7 +338,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
vendor: 'custom',
base_url: baseUrl.trim(),
key: apiKey.trim(),
- ...(protocolOrder ? { protocol_order: protocolOrder } : {}),
+ ...(protocol ? { protocol } : {}),
}, controller.signal);
const verdict = classifyObservation(observation);
let persistNext = false;
@@ -324,14 +348,14 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
if (origin === 'pull') setPhase({ kind: 'form', report: observation });
else persistNext = true;
} else if (verdict.kind === 'undetermined') {
- setPhase({ kind: 'undetermined', origin, observation, hint: null });
+ setPhase({ kind: 'undetermined', origin, observation });
} else if (verdict.kind === 'inventory') {
setPhase({ kind: 'inventory', origin, observation });
} else {
setPhase({ kind: 'failure', origin, cause: verdict.cause });
}
});
- if (landed === 'landed' && persistNext) await persist(seq, protocolOrder);
+ if (landed === 'landed' && persistNext) await persist(seq, protocol);
} catch (error) {
if (isAbortError(error)) return;
continuation.settle(seq, () => {
@@ -446,17 +470,14 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
const retry = async () => {
if (phase.kind === 'undetermined') {
- if (!phase.hint) return;
- await observe(phase.origin, protocolOrderWithHint(phase.hint));
+ if (protocolSelection === 'auto') return;
+ await observe(phase.origin, protocolSelection);
return;
}
if (phase.kind === 'inventory') {
- const order = phase.observation.protocol
- ? protocolOrderWithHint(phase.observation.protocol)
- : undefined;
// 2026-08-11 ruling: retry repeats the complete observation. There is no
// inventory-only credential lifetime or server capability.
- await observe(phase.origin, order);
+ await observe(phase.origin, phase.observation.protocol ?? undefined);
return;
}
if (phase.kind === 'save_unconfirmed') {
@@ -475,21 +496,30 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
return;
}
if (reconciliation.kind === 'absent') {
- await persist(seq, phase.protocolOrder);
+ await persist(seq, phase.protocol, phase.acceptUnavailableInventory);
}
return;
}
if (phase.kind === 'persist_failure') {
- await persist(continuation.begin(), phase.protocolOrder);
+ await persist(
+ continuation.begin(),
+ phase.protocol,
+ phase.acceptUnavailableInventory,
+ );
return;
}
- if (phase.kind === 'failure') await observe(phase.origin);
+ if (phase.kind === 'failure') {
+ await observe(
+ phase.origin,
+ protocolSelection === 'auto' ? undefined : protocolSelection,
+ );
+ }
};
const addAnyway = async () => {
if (phase.kind !== 'inventory' || phase.origin !== 'add' || !phase.observation.protocol) return;
const seq = continuation.begin();
- await persist(seq, protocolOrderWithHint(phase.observation.protocol));
+ await persist(seq, phase.observation.protocol, true);
};
const editEndpoint = (value: string) => {
@@ -505,6 +535,10 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
setDisplayName(value);
if (phase.kind === 'persist_failure') setPhase(INITIAL_PHASE);
};
+ const editProtocol = (value: ProtocolSelection) => {
+ setProtocolSelection(value);
+ if (phase.kind === 'form' && phase.report) setPhase(INITIAL_PHASE);
+ };
const isWorking = phase.kind === 'working';
const formLocked = isWorking || phase.kind === 'save_unconfirmed';
@@ -514,7 +548,8 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
const displayNameValid = optionalTrimmedTextWithin(displayName, SOURCE_DISPLAY_NAME_MAX_LENGTH);
const canObserve = Boolean(baseUrl.trim() && apiKey.trim()) && !formLocked;
const canSubmit = canObserve && displayNameValid;
- const showForm = phase.kind !== 'undetermined' && phase.kind !== 'inventory';
+ const selectedProtocol = protocolSelection === 'auto' ? undefined : protocolSelection;
+ const showForm = phase.kind !== 'inventory';
const replaceTerminalFailure = replacePhase.kind === 'failure'
&& replacePhase.failureClass === 'authoritative-terminal';
const replaceFieldLocked = replacePhase.kind === 'submitting'
@@ -620,6 +655,40 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
<Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" label={t('settings.models.addKey.field.name')}>
{(id) => <Input id={id} value={displayName} disabled={formLocked} aria-invalid={!displayNameValid} onChange={(event) => editDisplayName(event.target.value)} className="model-hub-add-key-input" />}
</Field>
+ <Field
+ className="model-hub-add-key-field"
+ labelClassName="model-hub-add-key-label"
+ hintClassName="model-hub-add-key-hint"
+ label={t('settings.models.addKey.field.protocol')}
+ hint={t('settings.models.addKey.field.protocol.hint')}
+ >
+ {(id) => (
+ <div
+ id={id}
+ role="group"
+ aria-label={t('settings.models.addKey.field.protocol')}
+ className="model-hub-add-key-segments flex max-w-full flex-wrap"
+ >
+ {(['auto', ...SOURCE_PROTOCOLS] as const).map((selection) => (
+ <button
+ key={selection}
+ type="button"
+ disabled={formLocked}
+ aria-pressed={protocolSelection === selection}
+ className={cn(
+ 'model-hub-add-key-segment',
+ protocolSelection === selection && 'is-selected',
+ )}
+ onClick={() => editProtocol(selection)}
+ >
+ {t(selection === 'auto'
+ ? 'settings.models.addKey.protocol.auto'
+ : PROTOCOL_COPY_KEYS[selection])}
+ </button>
+ ))}
+ </div>
+ )}
+ </Field>
<Field className="model-hub-add-key-field" labelClassName="model-hub-add-key-label" hintClassName="model-hub-add-key-hint" label={t('settings.models.addKey.field.baseUrl')} hint={t('settings.models.addKey.field.baseUrl.hint')}>
{(id) => <Input id={id} value={baseUrl} disabled={formLocked} autoComplete="url" spellCheck={false} onChange={(event) => editEndpoint(event.target.value)} className="model-hub-add-key-input font-mono" />}
</Field>
@@ -632,6 +701,16 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
onToggleReveal={() => setRevealed((value) => !value)}
/>
+ {phase.kind === 'undetermined' && (
+ <div className="model-hub-add-key-strip model-hub-add-key-strip--advisory">
+ <Info className="model-hub-ink-gold size-3.5 shrink-0" />
+ <div className="flex min-w-0 flex-col gap-[3px]">
+ <span className="model-hub-add-key-strip-title model-hub-ink-gold">{t('settings.models.addKey.undetermined.title')}</span>
+ <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.undetermined.detail')}</span>
+ </div>
+ </div>
+ )}
+
{!isWorking && (
<div className="model-hub-add-key-test-row flex items-center justify-between gap-4">
<Button
@@ -639,7 +718,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
variant="outline"
className="model-hub-add-key-secondary"
disabled={!canObserve}
- onClick={() => void observe('pull')}
+ onClick={() => void observe('pull', selectedProtocol)}
>
<PlugZap className="size-3" />
{t('settings.models.addKey.test')}
@@ -693,40 +772,6 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
</div>
)}
- {!replaceMode && phase.kind === 'undetermined' && (
- <div className="model-hub-add-key-outcome flex flex-col">
- <div className="model-hub-add-key-outcome-wrap">
- <div className="model-hub-add-key-strip model-hub-add-key-strip--advisory">
- <Info className="model-hub-ink-gold size-3.5 shrink-0" />
- <div className="flex min-w-0 flex-col gap-[3px]">
- <span className="model-hub-add-key-strip-title model-hub-ink-gold">{t('settings.models.addKey.undetermined.title')}</span>
- <span className="model-hub-add-key-strip-detail">{t('settings.models.addKey.undetermined.detail')}</span>
- </div>
- </div>
- </div>
- <div className="model-hub-add-key-protocol-field flex flex-col">
- <div className="flex items-center gap-1.5">
- <span className="model-hub-add-key-label">{t('settings.models.addKey.undetermined.label')}</span>
- <Info className="model-hub-ink-59 size-[13px]" aria-hidden />
- </div>
- <div className="model-hub-add-key-segments flex max-w-full flex-wrap">
- {SOURCE_PROTOCOLS.map((protocol) => (
- <button
- key={protocol}
- type="button"
- aria-pressed={phase.hint === protocol}
- className={cn('model-hub-add-key-segment', phase.hint === protocol && 'is-selected')}
- onClick={() => setPhase({ ...phase, hint: protocol })}
- >
- {t(PROTOCOL_COPY_KEYS[protocol])}
- </button>
- ))}
- </div>
- <span className="model-hub-add-key-hint">{t('settings.models.addKey.undetermined.hint')}</span>
- </div>
- </div>
- )}
-
{!replaceMode && phase.kind === 'inventory' && (
<div className="model-hub-add-key-outcome-wrap">
<div className="model-hub-add-key-strip model-hub-add-key-strip--advisory model-hub-add-key-strip--inventory">
@@ -793,7 +838,7 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
variant="brand"
className="model-hub-add-key-action"
disabled={!canSubmit}
- onClick={() => void observe('add')}
+ onClick={() => void observe('add', selectedProtocol)}
>
{t('settings.models.addKey.submit')}
</Button>
@@ -810,10 +855,10 @@ export const AddApiKeyDialog: React.FC<AddApiKeyDialogProps> = (props) => {
variant="brand"
className={cn(
'model-hub-add-key-action',
- (phase.kind === 'inventory' || phase.kind === 'save_unconfirmed' || (phase.kind === 'undetermined' && !phase.hint))
+ (phase.kind === 'inventory' || phase.kind === 'save_unconfirmed' || (phase.kind === 'undetermined' && protocolSelection === 'auto'))
&& 'model-hub-add-key-action--dim',
)}
- disabled={phase.kind === 'undetermined' && !phase.hint}
+ disabled={phase.kind === 'undetermined' && protocolSelection === 'auto'}
onClick={() => void retry()}
>
{t('settings.models.addKey.retry')}
diff --git a/ui/src/components/settings/models/SourceDetailPanel.test.tsx b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
index 5f7f9f026..b520cdea3 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.test.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.test.tsx
@@ -231,7 +231,7 @@ describe('SourceDetailPanel', () => {
expect(screen.queryByText(/latency|延迟|enrollment|protocol|协议/i)).toBeNull();
expect(screen.queryByText(/^Standby$|^待命$/i)).toBeNull();
expect(screen.getByText('model-a')).toBeTruthy();
- expect(screen.getByText(/relay\.example/)).toBeTruthy();
+ expect(screen.getByTitle('relay.example · Anthropic Messages')).toBeTruthy();
});
it('shows in-use only when the response carries adoption for this source', () => {
@@ -325,7 +325,7 @@ describe('SourceDetailPanel', () => {
await userEvent.click(screen.getByRole('button', { name: /Manage Production key|管理 Production key/i }));
await userEvent.click(screen.getByRole('menuitem', { name: /^Edit source$|^编辑来源$/i }));
- expect(screen.getByText(/OpenAI Chat Completions/i)).toBeTruthy();
+ expect(screen.getByTitle('relay.example · OpenAI Chat Completions')).toBeTruthy();
expect(screen.queryByText('openai_chat')).toBeNull();
});
@@ -620,7 +620,7 @@ describe('SourceDetailPanel', () => {
await waitFor(() => expect(inventory).toHaveBeenCalledOnce());
expect(patch).toHaveBeenCalledWith(source.id, { base_url: requestedBaseUrl });
if (committed) {
- expect(await screen.findByText(/requested\.example/)).toBeTruthy();
+ expect(await screen.findByTitle('requested.example · Anthropic Messages')).toBeTruthy();
expect(document.querySelector('[data-manage-failure="edit"]')).toBeNull();
} else {
const failure = await waitFor(() => {
diff --git a/ui/src/components/settings/models/SourceDetailPanel.tsx b/ui/src/components/settings/models/SourceDetailPanel.tsx
index 1cdb590dc..f6210254d 100644
--- a/ui/src/components/settings/models/SourceDetailPanel.tsx
+++ b/ui/src/components/settings/models/SourceDetailPanel.tsx
@@ -31,6 +31,10 @@ import type {
SourceEditDraft,
} from './manage';
import { apiFailure, modelsApi, type GuardConfirmation } from './modelsApi';
+import {
+ SOURCE_PROVIDER_COPY_KEYS,
+ sourceProviderIdentity,
+} from './sourcePresentation';
import {
sourceMutationReadScope,
type PresentSourceMutationCommit,
@@ -753,6 +757,10 @@ export const SourceDetailPanel: React.FC<{
&& manageStage.retryRead;
const managePlan = 'plan' in manageStage ? manageStage.plan : null;
const manageCopyKind = manageStage.kind.includes('edit') ? 'editSource' : 'deleteSource';
+ const providerIdentity = sourceProviderIdentity(source);
+ const providerCopyKey = SOURCE_PROVIDER_COPY_KEYS[providerIdentity];
+ const providerLabel = providerCopyKey ? t(providerCopyKey) : providerIdentity;
+ const interfaceLabel = `${providerLabel} · ${t(PROTOCOL_COPY_KEYS[source.protocol])}`;
return (
<div className="model-hub-source-detail">
@@ -766,6 +774,9 @@ export const SourceDetailPanel: React.FC<{
<div className="model-hub-source-copy flex min-w-0 flex-1 flex-col">
<div className={cn('model-hub-source-line flex min-w-0 flex-wrap items-center gap-x-[7px]', state.textClass)}>
<h2 ref={headingRef} tabIndex={-1} className="model-hub-source-title truncate font-bold text-foreground">{source.display_name}</h2>
+ <span className="model-hub-pill model-hub-source-interface-pill border" title={interfaceLabel}>
+ <span className="truncate">{interfaceLabel}</span>
+ </span>
{state.key && <span className="model-hub-source-state flex items-center gap-1.5"><span className={cn('size-[5px] shrink-0 rounded-full', state.dotClass)} />{t(state.key, state.values)}</span>}
{source.last_discovered_at && <span className="model-hub-source-age text-muted">{t('settings.models.sourceDetail.status.listUpdated', { time: formatRelativeTime(source.last_discovered_at, t) })}</span>}
</div>
diff --git a/ui/src/components/settings/models/SourceRow.test.tsx b/ui/src/components/settings/models/SourceRow.test.tsx
index a79ace6c9..caeb18599 100644
--- a/ui/src/components/settings/models/SourceRow.test.tsx
+++ b/ui/src/components/settings/models/SourceRow.test.tsx
@@ -26,6 +26,19 @@ describe('SourceRow', () => {
await userEvent.click(screen.getByRole('button', { name: /Production/ }));
expect(onOpen).toHaveBeenCalledWith(source);
expect(screen.queryByText(/latency/i)).toBeNull();
+ expect(screen.getByText('Anthropic · Anthropic Messages')).toBeTruthy();
+ });
+
+ it('labels a custom upstream by host and protocol', () => {
+ render(
+ <I18nextProvider i18n={i18n}>
+ <SourceRow
+ source={{ ...source, vendor: 'custom', base_url: 'https://relay.example/v1' }}
+ onOpen={vi.fn()}
+ />
+ </I18nextProvider>,
+ );
+ expect(screen.getByText('relay.example · Anthropic Messages')).toBeTruthy();
});
it('uses the authoritative Source adoption to name an active supplying source', () => {
diff --git a/ui/src/components/settings/models/SourceRow.tsx b/ui/src/components/settings/models/SourceRow.tsx
index c0e20e1d7..c0e41e536 100644
--- a/ui/src/components/settings/models/SourceRow.tsx
+++ b/ui/src/components/settings/models/SourceRow.tsx
@@ -3,7 +3,12 @@ import { ChevronRight } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
-import { sourceDetail } from './sourcePresentation';
+import { PROTOCOL_COPY_KEYS } from './addApiKeyState';
+import {
+ SOURCE_PROVIDER_COPY_KEYS,
+ sourceDetail,
+ sourceProviderIdentity,
+} from './sourcePresentation';
import { sourceStatePresentation } from './sourceStatePresentation';
import { useDeadlineClock } from './useDeadlineClock';
import { ACCENT_ICON, ACCENT_PILL, ACCENT_TILE, sourceVisual } from './vendorMeta';
@@ -14,6 +19,10 @@ export const SourceRow: React.FC<{ source: Source; onOpen: (source: Source) => v
const now = useDeadlineClock(source.state.status === 'cooldown' ? source.state.retry_at : null);
const { Icon, accent } = sourceVisual(source);
const detail = sourceDetail(source);
+ const providerIdentity = sourceProviderIdentity(source);
+ const providerCopyKey = SOURCE_PROVIDER_COPY_KEYS[providerIdentity];
+ const providerLabel = providerCopyKey ? t(providerCopyKey) : providerIdentity;
+ const interfaceLabel = `${providerLabel} · ${t(PROTOCOL_COPY_KEYS[source.protocol])}`;
const adoptedBackends = [...new Set((source.adopted_by ?? []).map(({ backend }) => t(`settings.models.backends.${backend}`, { defaultValue: backend }) as string))];
const state = sourceStatePresentation(source.state, 'card', i18n.language, now, {
known: source.adopted_by !== undefined,
@@ -44,6 +53,12 @@ export const SourceRow: React.FC<{ source: Source; onOpen: (source: Source) => v
<span className="min-w-0 flex-1">
<span className="flex min-w-0 items-center gap-1.5">
<span className="truncate text-[12.5px] font-bold leading-[18px] text-foreground" title={source.display_name}>{source.display_name}</span>
+ <span
+ className="model-hub-pill model-hub-source-interface-pill border"
+ title={interfaceLabel}
+ >
+ <span className="truncate">{interfaceLabel}</span>
+ </span>
<span className={cn('model-hub-pill border', ACCENT_PILL[accent])}>
{t(`settings.models.upstream.kind.${kindKey}`)}
</span>
diff --git a/ui/src/components/settings/models/addApiKeyState.test.ts b/ui/src/components/settings/models/addApiKeyState.test.ts
index 831317b24..918535e6d 100644
--- a/ui/src/components/settings/models/addApiKeyState.test.ts
+++ b/ui/src/components/settings/models/addApiKeyState.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from 'vitest';
-import { classifyObservation, protocolOrderWithHint } from './addApiKeyState';
-import { CONTRACT_VERSION, SOURCE_PROTOCOLS, type SourceObservation } from './types';
+import { classifyObservation } from './addApiKeyState';
+import { CONTRACT_VERSION, type SourceObservation } from './types';
const observation = (patch: Partial<SourceObservation>): SourceObservation => ({
contract_version: CONTRACT_VERSION,
@@ -15,13 +15,6 @@ const observation = (patch: Partial<SourceObservation>): SourceObservation => ({
});
describe('Add API key observation state', () => {
- it('turns a one-time hint into a complete probe order without duplicating the protocol table', () => {
- const order = protocolOrderWithHint('openai_responses');
- expect(order?.[0]).toBe('openai_responses');
- expect(new Set(order)).toEqual(new Set(SOURCE_PROTOCOLS));
- expect(order).toHaveLength(SOURCE_PROTOCOLS.length);
- });
-
it('separates proven inventory failure from unknown protocol and connectivity failures', () => {
const inventory = observation({ discovery: 'failed', models: [] });
expect(classifyObservation(inventory)).toEqual({ kind: 'inventory', observation: inventory });
diff --git a/ui/src/components/settings/models/addApiKeyState.ts b/ui/src/components/settings/models/addApiKeyState.ts
index d7a83d3a8..af48fe70f 100644
--- a/ui/src/components/settings/models/addApiKeyState.ts
+++ b/ui/src/components/settings/models/addApiKeyState.ts
@@ -1,8 +1,4 @@
-import {
- SOURCE_PROTOCOLS,
- type SourceObservation,
- type SourceProtocol,
-} from './types';
+import type { SourceObservation, SourceProtocol } from './types';
export type AddApiKeyOrigin = 'add' | 'pull';
export type AddApiKeyFailure = 'auth' | 'network' | 'interface' | 'unclassified' | 'engineDown';
@@ -19,11 +15,6 @@ export const PROTOCOL_COPY_KEYS: Record<SourceProtocol, string> = {
openai_chat: 'settings.models.addKey.protocol.openaiChatCompletions',
};
-export function protocolOrderWithHint(hint: SourceProtocol | null): SourceProtocol[] | undefined {
- if (!hint) return undefined;
- return [hint, ...SOURCE_PROTOCOLS.filter((protocol) => protocol !== hint)];
-}
-
export function classifyObservation(observation: SourceObservation): ObservationVerdict {
switch (observation.outcome) {
case 'observed':
diff --git a/ui/src/components/settings/models/modelHubSurface.css b/ui/src/components/settings/models/modelHubSurface.css
index e36a397f5..f34090f07 100644
--- a/ui/src/components/settings/models/modelHubSurface.css
+++ b/ui/src/components/settings/models/modelHubSurface.css
@@ -158,6 +158,15 @@
white-space: nowrap;
}
+.model-hub-source-interface-pill {
+ min-width: 0;
+ max-width: 52%;
+ flex: 0 1 auto;
+ border-color: var(--model-hub-cyan-4d);
+ background: var(--model-hub-cyan-1a);
+ color: var(--cyan-ink);
+}
+
.model-hub-ink-mint { color: var(--mint-ink); }
.model-hub-ink-gold { color: var(--gold-ink); }
.model-hub-ink-violet { color: var(--violet-ink); }
@@ -664,10 +673,6 @@
.model-hub-add-key-outcome-wrap {
padding: var(--model-hub-add-key-outcome-padding-y) var(--model-hub-add-key-outcome-padding-x);
}
-.model-hub-add-key-protocol-field {
- gap: var(--model-hub-add-key-field-gap);
- padding: 4px var(--model-hub-add-key-outcome-padding-x) 16px;
-}
.model-hub-add-key-segments {
width: fit-content;
gap: 3px;
diff --git a/ui/src/components/settings/models/sourcePresentation.ts b/ui/src/components/settings/models/sourcePresentation.ts
index cb26bfd52..34fd5c912 100644
--- a/ui/src/components/settings/models/sourcePresentation.ts
+++ b/ui/src/components/settings/models/sourcePresentation.ts
@@ -1,4 +1,22 @@
import type { Source } from './types';
+import { officialVendorForEndpoint } from './vendorMeta';
+
+export const SOURCE_PROVIDER_COPY_KEYS: Partial<Record<string, string>> = {
+ anthropic: 'settings.models.upstream.vendor.anthropic',
+ openai: 'settings.models.upstream.vendor.openai',
+};
+
+export const sourceProviderIdentity = (source: Pick<Source, 'vendor' | 'base_url'>): string => {
+ if (!source.base_url) return source.vendor;
+ const officialVendor = officialVendorForEndpoint(source.base_url);
+ if (officialVendor) return officialVendor;
+ try {
+ const host = new URL(source.base_url).host;
+ return host;
+ } catch {
+ return source.vendor;
+ }
+};
export const sourceDetail = (source: Source): string | null => {
const parts: string[] = [];
diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.ts
index 62d372a10..a0e071b71 100644
--- a/ui/src/components/settings/models/types.ts
+++ b/ui/src/components/settings/models/types.ts
@@ -636,8 +636,8 @@ export type ApiKeySourceObservation = {
vendor: string;
base_url?: string | null;
key: string;
- /** Probe order only. Every member occurs exactly once. */
- protocol_order?: SourceProtocol[];
+ /** Omission auto-detects; a value restricts observation to this protocol. */
+ protocol?: SourceProtocol;
};
/** POST /api/models/sources — api_key create observes again before persisting. */
@@ -649,8 +649,10 @@ export type ApiKeySourceCreate = {
key: string;
/** Stable across a create retry; persisted only when the Source commits. */
client_nonce?: string;
- /** Probe order only; the client never sends a protocol conclusion. */
- protocol_order?: SourceProtocol[];
+ /** Omission auto-detects; a value is persisted only after response proof. */
+ protocol?: SourceProtocol;
+ /** Explicit consent for a repeated, protocol-proven inventory failure. */
+ accept_unavailable_inventory?: boolean;
};
/**
diff --git a/ui/src/components/settings/models/vendorMeta.ts b/ui/src/components/settings/models/vendorMeta.ts
index 378ec3f4a..1e9dc5c71 100644
--- a/ui/src/components/settings/models/vendorMeta.ts
+++ b/ui/src/components/settings/models/vendorMeta.ts
@@ -97,7 +97,7 @@ export function backendVisual(backend: AgentBackend): BackendVisual {
return BACKEND_VISUAL[backend] ?? { Icon: Bot, accent: 'muted' };
}
-// Official endpoints are used only to classify an existing Source as custom.
+// Official endpoints classify existing Sources and provide their display identity.
// Add API key accepts a Base URL directly and intentionally has no vendor picker.
const OFFICIAL_BASE_URLS: Record<string, string> = {
anthropic: 'https://api.anthropic.com/v1',
@@ -107,6 +107,17 @@ const OFFICIAL_BASE_URLS: Record<string, string> = {
xai: 'https://api.x.ai/v1',
};
+export function officialVendorForEndpoint(baseUrl: string): string | null {
+ try {
+ const hostname = new URL(baseUrl).hostname;
+ return Object.entries(OFFICIAL_BASE_URLS).find(([, official]) => (
+ new URL(official).hostname === hostname
+ ))?.[0] ?? null;
+ } catch {
+ return null;
+ }
+}
+
// An api_key points at a custom endpoint when its base URL is set and differs
// from the vendor's official one — covers both vendor='custom' (official = null)
// and an official vendor whose prefilled Base URL was edited to a relay. Shared
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 3e86ab182..b24b95b25 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -913,6 +913,10 @@
"subscription": "Subscription",
"apiKey": "API key"
},
+ "vendor": {
+ "anthropic": "Anthropic",
+ "openai": "OpenAI"
+ },
"empty": "No sources yet. Add a subscription or an API key first.",
"unread": "Could not read the source list · the gateway itself is fine",
"retry": "Retry",
@@ -1171,8 +1175,10 @@
"subtitle": "Add connects once: it identifies the interface and fetches the model list",
"field": {
"name": "Name (optional)",
+ "protocol": "Interface type",
+ "protocol.hint": "Use Auto detect when unsure; choose a type to validate only that interface",
"baseUrl": "Base URL",
- "baseUrl.hint": "Paste any relay, aggregator or self-hosted address — Avibe identifies the interface itself",
+ "baseUrl.hint": "API root, such as https://api.example.com/v1; a bare host uses the standard /v1 path",
"apiKey": "API key",
"apiKey.reveal": "Show API key",
"apiKey.conceal": "Hide API key"
@@ -1186,11 +1192,11 @@
},
"submit": "Add",
"adding": "Connecting…",
- "adding.detail": "Connect, identify the interface, fetch the model list · usually 1–3s",
+ "adding.detail": "Connect, validate the interface, fetch the model list · usually 1–3s",
"fail": {
"subtitle": "Identifying the interface is a precondition of Add · fix what the line below names, then retry",
- "auth": "Authentication failed: 401 Unauthorized",
- "auth.detail": "Check whether the API key is valid",
+ "auth": "The upstream rejected this credential",
+ "auth.detail": "Check the API key, interface type, and the Base URL's API root path",
"address": "Wrong address: 404 Not Found",
"network": "Could not connect to this address (unreachable or timed out)",
"undetermined": "Connected, but we could not identify the model interface",
@@ -1202,11 +1208,10 @@
"retry": "Retry",
"undetermined": {
"title": "Connected and authenticated — but we cannot tell which interface it speaks",
- "detail": "The response shape matches no interface we know",
- "label": "Interface type · you hint it this once",
- "hint": "The hint only reorders the probe · it still has to really connect before anything is saved, and it cannot be changed afterwards"
+ "detail": "The response shape matches no interface we know; choose a concrete interface and retry"
},
"protocol": {
+ "auto": "Auto detect",
"anthropicMessages": "Anthropic Messages",
"openaiResponses": "OpenAI Responses",
"openaiChatCompletions": "OpenAI Chat Completions"
@@ -1479,7 +1484,7 @@
},
"empty": "This source returned no models. Add one by hand, or refetch.",
"emptyNeverFetched": "This source's model list has never come back. Deal with the status above, fetch again, or add a model by hand.",
- "footnote": "This page answers only \"which models does this source have\". Which routing chain a model takes is set in the gateway module. Tiers are yours to type, the same for both entry kinds. The interface type is identified when the source is added and fixed there — it is neither shown on this page nor editable."
+ "footnote": "This page answers only \"which models does this source have\". Which routing chain a model takes is set in the gateway module. Tiers are yours to type, the same for both entry kinds. The interface type is confirmed when the source is added, shown here, and not editable."
},
"guard": {
"label": "Hops that will be removed",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 6ba028d71..95efe939d 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -913,6 +913,10 @@
"subscription": "订阅",
"apiKey": "API Key"
},
+ "vendor": {
+ "anthropic": "Anthropic",
+ "openai": "OpenAI"
+ },
"empty": "还没有来源。先添加一个订阅或 API Key。",
"unread": "来源列表没读到 · 网关本身正常",
"retry": "重试",
@@ -1171,8 +1175,10 @@
"subtitle": "「添加」时自动连一次:认出接口 + 拉取型号列表",
"field": {
"name": "名称(可选)",
+ "protocol": "接口类型",
+ "protocol.hint": "不确定时用自动探测;已知类型时只验证所选接口",
"baseUrl": "Base URL",
- "baseUrl.hint": "粘贴任何中转 / 聚合 / 自建服务的地址即可,Avibe 会自己认出接口",
+ "baseUrl.hint": "填写 API 根地址,例如 https://api.example.com/v1;只填域名时使用标准 /v1 路径",
"apiKey": "API Key",
"apiKey.reveal": "显示 API Key",
"apiKey.conceal": "隐藏 API Key"
@@ -1186,11 +1192,11 @@
},
"submit": "添加",
"adding": "连接中…",
- "adding.detail": "连上 + 认出接口 + 首次拉取型号列表 · 通常 1–3 秒",
+ "adding.detail": "连上 + 验证接口 + 首次拉取型号列表 · 通常 1–3 秒",
"fail": {
"subtitle": "认出接口是「添加」的前置条件 · 先按下面这条修,再重试",
- "auth": "鉴权失败:401 Unauthorized",
- "auth.detail": "检查 API Key 是否有效",
+ "auth": "上游拒绝了这个凭据",
+ "auth.detail": "检查 API Key、接口类型和 Base URL 的 API 根路径",
"address": "地址不对:404 Not Found",
"network": "无法连接到该地址(不可达或超时)",
"undetermined": "已连接,但无法确认这是哪种模型接口",
@@ -1202,11 +1208,10 @@
"retry": "重试",
"undetermined": {
"title": "连上了、也通过了鉴权 —— 但认不出它说哪种接口",
- "detail": "返回结构对不上任何一种已知接口",
- "label": "接口类型 · 这一次由你提示",
- "hint": "提示只改探测顺序 · 仍要真的连上才会保存;保存后不可更改"
+ "detail": "返回结构对不上任何一种已知接口,请选择一个明确类型后重试"
},
"protocol": {
+ "auto": "自动探测",
"anthropicMessages": "Anthropic Messages",
"openaiResponses": "OpenAI Responses",
"openaiChatCompletions": "OpenAI Chat Completions"
@@ -1479,7 +1484,7 @@
},
"empty": "这个来源没有返回型号。可以手动添加,或重新拉取。",
"emptyNeverFetched": "还没有成功拉取过这个来源的型号列表。先处理上面的状态,再拉一次,或者手动添加一个型号。",
- "footnote": "这里只管「这个来源有哪些型号」。型号走哪条路由链,在网关模块里改。档位自己填,两种录入方式都一样。接口类型在添加时认出并固定,页面上不显示、也不能改。"
+ "footnote": "这里只管「这个来源有哪些型号」。型号走哪条路由链,在网关模块里改。档位自己填,两种录入方式都一样。接口类型在添加时确认并固定,页面会显示、但不能修改。"
},
"guard": {
"label": "会被移除的跳",
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index f6e5d3c9b..c4b8f0ff5 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -882,6 +882,7 @@
"flow_expired": "Authorization flow expired.",
"discovery_failed": "Could not validate or discover this source.",
"ambiguous_source": "Connected, but we could not identify the model interface.",
+ "inventory_unavailable": "The interface was confirmed, but its model list is unavailable.",
"source_unreachable": "Could not reach this address. Check the address and retry.",
"authentication_failed": "Authentication failed. Check whether the API key is valid.",
"observation_failed": "Connected, but the response did not prove a valid model interface.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 0d5382cb8..d77938f0f 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -882,6 +882,7 @@
"flow_expired": "授权流程已过期。",
"discovery_failed": "无法验证或发现此来源。",
"ambiguous_source": "已连接,但无法确认这是哪种模型接口。",
+ "inventory_unavailable": "接口已确认,但暂时无法获取型号清单。",
"source_unreachable": "无法连接到这个地址,请检查地址后重试。",
"authentication_failed": "鉴权失败,请检查 API Key 是否有效。",
"observation_failed": "已连接,但无法确认服务返回的是有效模型接口。",
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 323a67129..3270e7d35 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -38,6 +38,7 @@ from vibe.model_hub_runtime.client import (
EngineInvokeHandle,
completed_handle,
probe_models,
+ upstream_api_url,
)
from vibe.model_hub_runtime.installer import InstallClaimTransition
from vibe.model_hub_runtime.state import EngineStateError, EngineStateStore
@@ -231,9 +232,11 @@ _PROTOCOL_OBSERVATION_TAXONOMY = {
"anthropic": _ProtocolObservationTaxonomy(
request_path="/v1/messages",
request_body={
- "model": "__avibe_model_hub_probe__",
- "max_tokens": 1,
- "messages": [{"role": "user", "content": "ping"}],
+ # Fail schema validation before a relay selects a model. A synthetic
+ # model can otherwise surface as an availability failure even when
+ # the credential and interface are valid.
+ "max_tokens": 0,
+ "messages": [],
},
oauth_path="/v1/messages?beta=true",
evidence_rules=(
@@ -331,6 +334,20 @@ def _parse_protocol_authenticated_evidence(
authentication=_AuthenticationEvidence.UNKNOWN,
)
+ top_level_identifiers = {
+ value.strip().lower()
+ for value in (payload.get("type"), payload.get("code"))
+ if isinstance(value, str)
+ }
+ if (
+ status in _AUTHENTICATION_ERROR_STATUSES
+ and not _AUTHENTICATION_ERROR_IDENTIFIERS.isdisjoint(top_level_identifiers)
+ ):
+ return _ProtocolEvidence(
+ protocol=_ProtocolProof.UNPROVEN,
+ authentication=_AuthenticationEvidence.REJECTED,
+ )
+
taxonomy = _PROTOCOL_OBSERVATION_TAXONOMY.get(protocol)
for rule in taxonomy.evidence_rules if taxonomy is not None else ():
if rule.matches(status, payload):
@@ -362,9 +379,8 @@ async def _probe_protocol_response(
taxonomy = _PROTOCOL_OBSERVATION_TAXONOMY.get(protocol)
if taxonomy is None:
raise EngineClientError("unsupported source protocol")
- endpoint = taxonomy.request_path.removeprefix("/v1")
try:
- url = normalize_model_hub_base_url(root, append_path=endpoint)
+ url = upstream_api_url(root, taxonomy.request_path)
except (TypeError, ValueError):
raise EngineClientError("source base URL is invalid")
assert url is not None
diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.py
index df192e190..651454dd2 100644
--- a/vibe/model_hub_runtime/client.py
+++ b/vibe/model_hub_runtime/client.py
@@ -47,6 +47,18 @@ _PROTOCOL_HEADERS = frozenset({"anthropic-beta", "anthropic-version", "openai-be
logger = logging.getLogger(__name__)
+def upstream_api_url(root: str, path: str) -> str:
+ """Resolve a standard v1 endpoint from either an origin or an API root."""
+
+ normalized = normalize_model_hub_base_url(root)
+ assert normalized is not None
+ root_path = urllib.parse.urlsplit(normalized).path.rstrip("/")
+ append_path = path if not root_path else path.removeprefix("/v1")
+ resolved = normalize_model_hub_base_url(normalized, append_path=append_path)
+ assert resolved is not None
+ return resolved
+
+
class EngineClientError(RuntimeError):
def __init__(
self,
@@ -567,7 +579,7 @@ async def probe_models(
if not root:
raise EngineClientError("source requires a base URL for model discovery")
try:
- url = normalize_model_hub_base_url(root, append_path="/models")
+ url = upstream_api_url(root, "/v1/models")
except (TypeError, ValueError):
raise EngineClientError("source base URL is invalid")
assert url is not None