Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): describe provider candidates from models.dev (#2202)
Call White293546bdd550
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex b86fabdd6..ddab41e11 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -42,7 +42,10 @@ from core.agent_auth_service import BackendLoginInProgressErrorfrom core.services.settings import default_configfrom storage.db import get_cached_sqlite_enginefrom storage.models import agent_sessions, messages-from vibe.backend_model_catalog import bundled_catalog_reasoning_efforts_by_model+from vibe.backend_model_catalog import (+ PROTOCOL_REASONING_EFFORT_DEFAULTS,+ bundled_catalog_reasoning_efforts_by_model,+)from vibe.model_hub_runtime.api_key_vendors import (catalog_api_key_vendor_label,pinned_api_key_protocol,@@ -191,6 +194,23 @@ def _storable_backend_model_metadata(return proposed_display_name, proposed_efforts+def _cached_models_dev_catalog() -> Mapping[str, Any]:+ from vibe.models_dev_catalog import load_models_dev_catalog_with_date++ return load_models_dev_catalog_with_date()[0]+++_MODELS_DEV_CANDIDATE_FIELDS = (+ "models_dev_id",+ "context_window",+ "max_output_tokens",+ "input_modalities",+ "output_modalities",+ "supports_tools",+ "supports_reasoning",+)++AGENT_CHAIN_CONTRACT_VERSION = 10PROBE_RESULT_CONTRACT_VERSION = 10_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15@@ -901,6 +921,7 @@ class ModelHubService:now: Callable[[], datetime] = _utc_now,recovery: RecoveryPolicy | None = None,price_table: Callable[[], PriceTable] | None = None,+ models_dev_catalog: Callable[[], Mapping[str, Any]] | None = None,):self.store = storeself.adapter = adapter@@ -967,6 +988,10 @@ class ModelHubService:self.price_table: Callable[[], PriceTable] = price_table or (lambda: load_price_table(paths.get_state_dir()))+ # A cached copy only: the picker read must not wait on the network.+ self.models_dev_catalog: Callable[[], Mapping[str, Any]] = models_dev_catalog or (+ lambda: _cached_models_dev_catalog()+ )@staticmethod@asynccontextmanager@@ -4479,6 +4504,23 @@ class ModelHubService:reasoning_efforts.append(effort)return suppliers, display_name, reasoning_efforts+ def _models_dev_descriptions(self, model_ids: list[str]) -> dict[str, dict]:+ """Exact models.dev matches for provider candidates; empty when unknown.++ The description is optional: an unreadable catalog leaves every+ candidate as its suppliers describe it rather than failing the picker.+ """++ if not model_ids:+ return {}+ from vibe.models_dev_catalog import exact_models_dev_matches++ try:+ return exact_models_dev_matches(model_ids, dict(self.models_dev_catalog()))+ except Exception as exc: # noqa: BLE001 - optional metadata never fails a read+ logger.info("Model Hub candidates have no models.dev metadata: %s", type(exc).__name__)+ return {}+def agent_model_candidates(self, backend: str) -> dict:agent_backend = cast(BackendName, backend)config = self.store.load()@@ -4557,12 +4599,34 @@ class ModelHubService:provider_ids.append(candidate_id)providers = []+ described = self._models_dev_descriptions(provider_ids)for model_id in provider_ids:suppliers, display_name, reasoning_efforts = self._candidate_suppliers(config,agent_backend,model_id,)+ # Suppliers speak first, models.dev fills what they left unsaid, and+ # an unstated ladder falls back to the tiers the backend's request+ # protocol accepts, unless models.dev says the model cannot reason.+ match = described.get(model_id)+ enrichment = (+ {field: match[field] for field in _MODELS_DEV_CANDIDATE_FIELDS}+ if match is not None+ else {}+ )+ if reasoning_efforts and enrichment.get("supports_reasoning") is False:+ # A supplier's ladder outranks the catalog's flag, and a false+ # flag would suppress that ladder at launch.+ enrichment["supports_reasoning"] = None+ display_name = display_name or (match or {}).get("display_name")+ if not reasoning_efforts and match is not None:+ reasoning_efforts = list(match["reasoning_efforts"])+ if not reasoning_efforts and enrichment.get("supports_reasoning") is not False:+ request_protocol = _FIXED_BACKEND_PROTOCOLS.get(+ agent_backend+ ) or native_protocol_for_model_id(model_id)+ reasoning_efforts = list(PROTOCOL_REASONING_EFFORT_DEFAULTS[request_protocol])admitted = admissible_backend_model(agent_backend,model_id,@@ -4570,6 +4634,7 @@ class ModelHubService:"origin": "provider","display_name": display_name,"reasoning_efforts": reasoning_efforts,+ **enrichment,**protocol_payload(model_id),},claude_builtin_ids=_builtin_model_ids("claude"),@@ -4583,6 +4648,10 @@ class ModelHubService:"reasoning_efforts": admitted.reasoning_efforts,"suppliers": suppliers,"origin": "provider",+ **{+ field: getattr(admitted, field)+ for field in enrichment+ },**protocol_payload(admitted.id),})diff --git a/docs/plans/backend-model-catalogs.md b/docs/plans/backend-model-catalogs.mdindex d72424f88..2b4228c54 100644--- a/docs/plans/backend-model-catalogs.md+++ b/docs/plans/backend-model-catalogs.md@@ -259,7 +259,17 @@ the contract guard as the test. Nothing here introduces a second vocabulary for- **C2 — Proposed values travel in the candidates read; the save is literal.** The serverproposes `display_name` and `reasoning_efforts` for every candidate (C4): for a built-infrom the built-in snapshot, for a provider model from its suppliers (display name from the- first ordered supplier that has one; efforts = union in Source order). The picker copies+ first ordered supplier that has one; efforts = union in Source order). A provider model whose+ id names a models.dev entry exactly — full `provider/model`, else the id or its last path+ segment, spelled identically; no case, punctuation, or alias folding and never a substring — also+ proposes that entry's `models_dev_id`, limits, modalities and capabilities, and its display+ name and efforts fill only what suppliers left empty. When no side states efforts and+ models.dev does not say `supports_reasoning: false`, the proposal is the+ `PROTOCOL_REASONING_EFFORT_DEFAULTS` ladder of the backend's request protocol (Claude+ `anthropic`, Codex `openai_responses`, OpenCode the id's derived `native_protocol`). A+ models.dev `supports_reasoning: false` is proposed as `null` when suppliers state efforts,+ so the catalog flag cannot suppress a supplier's ladder. The match reads the cached catalog only and+ an unreadable catalog proposes no enrichment. The picker copiesthose proposals into the editable catalog draft; the custom editor copies the chosenmodels.dev suggestion. A proposal contains only values the catalog can store — an effortvalue that violates `backend-model.schema.json` is left out of the proposal, never copied. `PUT` stores the request literally — an empty field in the requestdiff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.jsonindex 7ec2bee52..9710fdfad 100644--- a/docs/plans/model-hub-contracts/api-response.schema.json+++ b/docs/plans/model-hub-contracts/api-response.schema.json@@ -362,8 +362,24 @@"reasoning_efforts": {"type": "array", "items": {"type": "string", "minLength": 1, "maxLength": 64}, "uniqueItems": true},"suppliers": {"type": "array", "items": {"$ref": "#/definitions/CandidateSupplier"}, "uniqueItems": true},"origin": {"enum": ["builtin", "provider", "models_dev", "manual"]},+ "models_dev_id": {"type": "string", "minLength": 3},+ "context_window": {"type": ["integer", "null"], "minimum": 1},+ "max_output_tokens": {"type": ["integer", "null"], "minimum": 1},+ "input_modalities": {"type": "array", "items": {"enum": ["text", "image", "audio", "video", "pdf"]}, "uniqueItems": true},+ "output_modalities": {"type": "array", "items": {"enum": ["text", "image", "audio", "video"]}, "uniqueItems": true},+ "supports_tools": {"type": ["boolean", "null"]},+ "supports_reasoning": {"type": ["boolean", "null"]},"native_protocol": {"enum": ["openai_responses", "anthropic"]},"group_if_removed": {"anyOf": [{"enum": ["builtin", "providers"]}, {"type": "null"}]}+ },+ "dependencies": {+ "models_dev_id": ["context_window", "max_output_tokens", "input_modalities", "output_modalities", "supports_tools", "supports_reasoning"],+ "context_window": ["models_dev_id"],+ "max_output_tokens": ["models_dev_id"],+ "input_modalities": ["models_dev_id"],+ "output_modalities": ["models_dev_id"],+ "supports_tools": ["models_dev_id"],+ "supports_reasoning": ["models_dev_id"]}},"AddableModelCandidate": {diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.mdindex e0bde1203..cec6a0a3f 100644--- a/docs/plans/model-hub-contracts/api.md+++ b/docs/plans/model-hub-contracts/api.md@@ -50,7 +50,7 @@ remain readable; ephemeral envelopes use only the terminal version.| POST `/api/models/agents/<backend>/chains/reorder` | `{order?: string[], force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409` or `{agent: AgentSupply}` | Compatibility default-order entry point with the same guards as Sources PUT. Never reorders manual arrays. Without order, returns the current projection. New UI uses Sources PUT. || PATCH `/api/models/agents/<backend>/mode` | `{mode}` → `{agent: AgentSupply}` | Explicit `hub` / `direct` switch. Direct-to-Hub rechecks native absence under the shared migration guard and returns `mode_switch_blocked` if credentials require consent. It does not auto-create or adopt a native Source; native custody takeover is the grouped migration transaction. Hub-to-Direct remains mode-only. || GET `/api/models/agents/<backend>/models` | → `{agent: {backend, mode, catalog_models}}` | Picker-safe catalog read. It exposes no Source order, Route, or credential-bearing supplier data. Every OpenCode row carries required `native_protocol`; Claude and Codex rows omit it. |-| GET `/api/models/agents/<backend>/models/candidates` | → `{candidates: {builtin: Candidate[], providers: Candidate[], in_list: Candidate[]}}` | Server-owned picker projection. It returns addable built-ins, deduplicated ordered-provider inventory, and every current menu row with the same exact supplier projection; it is independent of backend mode and contains no credentials. Every OpenCode Candidate carries server-derived `native_protocol`; other backends omit it. Only `in_list` candidates may carry optional `group_if_removed: "builtin" | "providers" | null`, naming the group where that id would be offered after removal. |+| GET `/api/models/agents/<backend>/models/candidates` | → `{candidates: {builtin: Candidate[], providers: Candidate[], in_list: Candidate[]}}` | Server-owned picker projection. It returns addable built-ins, deduplicated ordered-provider inventory, and every current menu row with the same exact supplier projection; it is independent of backend mode and contains no credentials. Every OpenCode Candidate carries server-derived `native_protocol`; other backends omit it. Only `in_list` candidates may carry optional `group_if_removed: "builtin" | "providers" | null`, naming the group where that id would be offered after removal. A `providers` candidate whose id names a cached models.dev model exactly also carries that match's `models_dev_id`, `context_window`, `max_output_tokens`, `input_modalities`, `output_modalities`, `supports_tools`, and `supports_reasoning` together; those seven are absent otherwise. || PUT `/api/models/agents/<backend>/models` | `{baseline: BackendModel[], models: BackendModel[], expected_suppliers?: {<id>: [{source_id, model_id}]}, force?: boolean, would_remove_hops?: RouteHopRef[], would_interrupt?: SupplyGap[]}` → guarded `409`, stale-candidate `409`, `{agent: AgentSupply}`, or `{agent: AgentSupply, removed_hops: RouteHopRef[], interrupted: SupplyGap[]}` | Applies one full-list backend catalog edit with optimistic merge. OpenCode rows require a literal `native_protocol: openai_responses | anthropic`; rows for other backends forbid it. Each caller addition still absent from the latest list starts automatic without a route key. A listed supplier-projection mismatch refuses atomically with the separate exact shape `{ok: false, contract_version, error: "candidate_suppliers_changed", detail, changed}`; a concurrently added row keeps its existing Route. A routeful removal uses the exact echoed-plan guard and then atomically removes its Route; empty-route removal is ordinary success. Supplier inventory remains unchanged. || GET `/api/models/catalog/models-dev?query=<text>` | → `{matches: ModelsDevMatch[]}` | Read-only metadata lookup through the server-owned conditional cache. Results keep the shipped provider fields, deduplicate aggregator copies by model id, rank first-party matches first, add `first_party`, derive `native_protocol` from the model id's last path segment through the vendor map, cap results at 8, and never persist automatically. || GET `/api/models/agents/<backend>/chains` | → `{chains: AgentChain[]}` | Hub only. Returns the complete Overview model set in menu order, followed by a selected model or configured Route not already present. All members share one config snapshot and observation time. Direct returns the documented `direct_mode` error. |diff --git a/tests/test_model_hub_api.py b/tests/test_model_hub_api.pyindex d605d3fa5..98030aef5 100644--- a/tests/test_model_hub_api.py+++ b/tests/test_model_hub_api.py@@ -413,6 +413,10 @@ _PRICE_TABLE = PriceTable()+# Hermetic: the default reads the machine's cached models.dev copy.+_MODELS_DEV_CATALOG: dict = {}++def _service(tmp_path, adapter=None):store = MemoryStore()adapter = adapter or FakeAdapter()@@ -435,6 +439,7 @@ def _service(tmp_path, adapter=None):requested_model_override=lambda backend: store.requested_model(backend),migration_home=tmp_path / "native-home",price_table=lambda: _PRICE_TABLE,+ models_dev_catalog=lambda: _MODELS_DEV_CATALOG,)return service, store, adapter@@ -2596,6 +2601,137 @@ def test_candidate_protocol_projection_is_total_only_for_opencode(tmp_path):)+def test_provider_candidates_carry_exact_models_dev_description(tmp_path):+ service, store, _adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_enrich001",+ kind="api_key",+ vendor="custom",+ display_name="Relay",+ protocol="openai_chat",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[+ # Bare `/v1/models` discovery: nothing but the id.+ ModelHubModelConfig(id="gpt-described", provenance="discovered"),+ ModelHubModelConfig(+ id="gpt-supplier-says",+ provenance="discovered",+ display_name="Relay label",+ reasoning_efforts=["high"],+ ),+ ModelHubModelConfig(id="gpt-unknown", provenance="discovered"),+ ModelHubModelConfig(id="gpt-no-reasoning", provenance="discovered"),+ # A near neighbour of a catalog id, which must not borrow its row.+ ModelHubModelConfig(id="gpt-described-mini", provenance="discovered"),+ ModelHubModelConfig(id="claude-unknown", provenance="discovered"),+ ModelHubModelConfig(+ id="gpt-relay-reasons",+ provenance="discovered",+ reasoning_efforts=["low", "high"],+ ),+ ],+ credential_ref="cred_enrich001",+ )+ store.config.sources = [source]+ for agent in store.config.agents.values():+ agent.sources.order = [source.id]+ service.models_dev_catalog = lambda: {+ "openai": {+ "name": "OpenAI",+ "models": {+ "gpt-described": {+ "name": "GPT Described",+ "reasoning": True,+ "reasoning_options": [{"type": "effort", "values": ["low", "high"]}],+ "tool_call": True,+ "modalities": {"input": ["text", "image"], "output": ["text"]},+ "limit": {"context": 400_000, "output": 128_000},+ },+ "gpt-supplier-says": {+ "name": "Catalog label",+ "reasoning": True,+ "reasoning_options": [{"type": "effort", "values": ["low"]}],+ },+ "gpt-no-reasoning": {"name": "GPT No Reasoning", "reasoning": False},+ "gpt-relay-reasons": {"name": "GPT Relay Reasons", "reasoning": False},+ },+ }+ }++ rows = {row["id"]: row for row in service.agent_model_candidates("codex")["providers"]}++ assert rows["gpt-described"] == {+ "id": "gpt-described",+ "display_name": "GPT Described",+ "reasoning_efforts": ["low", "high"],+ "suppliers": rows["gpt-described"]["suppliers"],+ "origin": "provider",+ "models_dev_id": "openai/gpt-described",+ "context_window": 400_000,+ "max_output_tokens": 128_000,+ "input_modalities": ["text", "image"],+ "output_modalities": ["text"],+ "supports_tools": True,+ "supports_reasoning": True,+ }+ # What the suppliers state wins; models.dev only fills what they left unsaid.+ assert rows["gpt-supplier-says"]["display_name"] == "Relay label"+ assert rows["gpt-supplier-says"]["reasoning_efforts"] == ["high"]+ assert rows["gpt-supplier-says"]["models_dev_id"] == "openai/gpt-supplier-says"+ # Nobody states a ladder: the tiers the backend's request protocol accepts —+ # fixed for Codex and Claude, the model family's for OpenCode — and no+ # description.+ openai = ["minimal", "low", "medium", "high", "xhigh"]+ anthropic = ["low", "medium", "high", "xhigh", "max"]+ for model_id in ("gpt-unknown", "gpt-described-mini", "claude-unknown"):+ assert rows[model_id]["reasoning_efforts"] == openai+ assert "models_dev_id" not in rows["gpt-unknown"]+ assert "models_dev_id" not in rows["gpt-described-mini"]+ elsewhere = {+ backend: {row["id"]: row for row in service.agent_model_candidates(backend)["providers"]}+ for backend in ("claude", "opencode")+ }+ assert elsewhere["claude"]["gpt-unknown"]["reasoning_efforts"] == anthropic+ assert elsewhere["opencode"]["gpt-unknown"]["reasoning_efforts"] == openai+ assert elsewhere["opencode"]["claude-unknown"]["reasoning_efforts"] == anthropic+ # A supplier's ladder is not switched off by the catalog's reasoning flag.+ assert rows["gpt-relay-reasons"]["reasoning_efforts"] == ["low", "high"]+ assert rows["gpt-relay-reasons"]["supports_reasoning"] is None+ # A model stated not to reason gets no invented ladder.+ assert rows["gpt-no-reasoning"]["reasoning_efforts"] == []+ assert rows["gpt-no-reasoning"]["supports_reasoning"] is False+++def test_provider_candidates_survive_an_unreadable_models_dev_catalog(tmp_path):+ service, store, _adapter = _service(tmp_path)+ source = ModelHubSourceConfig(+ id="src_enrich002",+ kind="api_key",+ vendor="custom",+ display_name="Relay",+ protocol="openai_chat",+ supply_channel="hub",+ billing="metered",+ state=ModelHubSourceStateConfig(status="standby"),+ models=[ModelHubModelConfig(id="gpt-described", provenance="discovered")],+ credential_ref="cred_enrich002",+ )+ store.config.sources = [source]+ store.config.agents["codex"].sources.order = [source.id]++ def unreadable():+ raise RuntimeError("cache is corrupt")++ service.models_dev_catalog = unreadable++ [row] = service.agent_model_candidates("codex")["providers"]++ assert row["id"] == "gpt-described"+ assert "models_dev_id" not in row++def test_candidates_exclude_only_noncanonical_ids(monkeypatch, tmp_path):service, store, _adapter = _service(tmp_path)invalid_claude_id = "not-a-claude-family"diff --git a/tests/test_models_dev_catalog.py b/tests/test_models_dev_catalog.pyindex f1c4dc70d..d4028a8c6 100644--- a/tests/test_models_dev_catalog.py+++ b/tests/test_models_dev_catalog.py@@ -333,3 +333,43 @@ def test_models_dev_caps_matches_at_eight(monkeypatch):assert len(matches) == models_dev_catalog.MODELS_DEV_MAX_MATCHES == 8assert [item["model_id"] for item in matches] == sorted(item["model_id"] for item in matches)+++def test_exact_models_dev_matches_never_borrow_a_neighbour():+ catalog = {+ "openrouter": {+ "name": "OpenRouter",+ "models": {+ "gpt-target": {"name": "Proxy"},+ "claude-3-5-target": {"name": "Claude 3.5 proxy"},+ },+ },+ "openai": {+ "name": "OpenAI",+ "models": {+ "gpt-target": {"name": "GPT target"},+ "gpt-target-mini": {"name": "GPT target mini"},+ "foo": {"name": "Foo"},+ "Case-Target": {"name": "Case target"},+ },+ },+ }++ matches = models_dev_catalog.exact_models_dev_matches(+ [+ "gpt-target", "openrouter/gpt-target", "relay/gpt-target-mini",+ "open_router/gpt.target", "claude-3.5-target", "gpt", "gpt-target-max",+ "avibe-foo", "case-target",+ ],+ catalog,+ )++ # A bare id prefers the first-party copy; a full identity names its own.+ assert matches["gpt-target"]["models_dev_id"] == "openai/gpt-target"+ assert matches["openrouter/gpt-target"]["models_dev_id"] == "openrouter/gpt-target"+ # A relay prefix falls back to the last segment.+ assert matches["relay/gpt-target-mini"]["models_dev_id"] == "openai/gpt-target-mini"+ # Only identical spellings match: no punctuation, case, or alias folding and+ # no substrings.+ assert set(matches) == {"gpt-target", "openrouter/gpt-target", "relay/gpt-target-mini"}+ assert models_dev_catalog.exact_models_dev_matches(["gpt-target"], {}) == {}diff --git a/ui/src/components/settings/models/backendCatalog.test.ts b/ui/src/components/settings/models/backendCatalog.test.tsindex 296efdb2a..7adc1ce7a 100644--- a/ui/src/components/settings/models/backendCatalog.test.ts+++ b/ui/src/components/settings/models/backendCatalog.test.ts@@ -363,6 +363,32 @@ describe('candidateBackendModel', () => {expect(Object.keys(drafted)).not.toContain('suppliers');});+ it('copies an exact models.dev description whole when the server states one', () => {+ const described: ModelCandidate = {+ ...candidate,+ models_dev_id: 'zhipuai/glm-5.2',+ context_window: 128_000,+ max_output_tokens: null,+ input_modalities: ['text', 'image'],+ output_modalities: ['text'],+ supports_tools: true,+ supports_reasoning: true,+ };++ // Stated by the server, so a pick carries it into the draft rather than+ // leaving the user to look it up in the editor.+ expect(candidateBackendModel(described)).toMatchObject({+ models_dev_id: 'zhipuai/glm-5.2',+ context_window: 128_000,+ max_output_tokens: null,+ input_modalities: ['text', 'image'],+ output_modalities: ['text'],+ supports_tools: true,+ supports_reasoning: true,+ origin: 'provider',+ });+ });+it('copies the proposed efforts instead of aliasing them', () => {candidateBackendModel(candidate).reasoning_efforts.push('mutated');diff --git a/ui/src/components/settings/models/backendCatalog.ts b/ui/src/components/settings/models/backendCatalog.tsindex 36f621fe8..6786fb3d3 100644--- a/ui/src/components/settings/models/backendCatalog.ts+++ b/ui/src/components/settings/models/backendCatalog.ts@@ -126,12 +126,13 @@ export const blankBackendModel = (): BackendModel => ({/*** A picked candidate, poured into a draft row.*- * Copies exactly the three values the server proposed (C2) and leaves every- * other field unstated. That asymmetry is the contract: the proposal covers what- * the product already knows about the model — its label and the efforts its- * suppliers accept — and the rest stays empty until the user fills it, because- * `PUT` stores the request literally and an invented context window would- * persist as if the user had stated it.+ * Copies exactly the values the server proposed (C2) and leaves every other+ * field unstated. That asymmetry is the contract: the proposal covers what the+ * product already knows about the model — its label, the efforts its suppliers+ * accept, and the exact models.dev description when one names this id — and the+ * rest stays empty until the user fills it, because `PUT` stores the request+ * literally and an invented context window would persist as if the user had+ * stated it.** Unstated, NOT the blank floor. The blank floor's `text`/`text`/tools-on/* reasoning-off belong to a row the editor is about to show, where they are on@@ -153,6 +154,17 @@ export const candidateBackendModel = (candidate: ModelCandidate): BackendModel =origin: candidate.origin,reasoning_efforts: [...candidate.reasoning_efforts],...(candidate.native_protocol ? { native_protocol: candidate.native_protocol } : {}),+ ...(candidate.models_dev_id+ ? {+ models_dev_id: candidate.models_dev_id,+ context_window: candidate.context_window ?? null,+ max_output_tokens: candidate.max_output_tokens ?? null,+ input_modalities: [...(candidate.input_modalities ?? [])],+ output_modalities: [...(candidate.output_modalities ?? [])],+ supports_tools: candidate.supports_tools ?? null,+ supports_reasoning: candidate.supports_reasoning ?? null,+ }+ : {}),});/**diff --git a/ui/src/components/settings/models/backendModelContract.test.ts b/ui/src/components/settings/models/backendModelContract.test.tsindex 0d7afc160..7bf4c475b 100644--- a/ui/src/components/settings/models/backendModelContract.test.ts+++ b/ui/src/components/settings/models/backendModelContract.test.ts@@ -88,8 +88,21 @@ const CANDIDATE: Required<ModelCandidate> = {origin: 'provider',group_if_removed: 'providers',native_protocol: 'openai_responses',+ models_dev_id: 'zhipuai/glm-5.2',+ context_window: 128_000,+ max_output_tokens: null,+ input_modalities: ['text', 'image'],+ output_modalities: ['text'],+ supports_tools: true,+ supports_reasoning: null,};+/** The fields an exact models.dev match adds to a provider candidate. */+const MODELS_DEV_FIELDS = [+ 'models_dev_id', 'context_window', 'max_output_tokens', 'input_modalities',+ 'output_modalities', 'supports_tools', 'supports_reasoning',+];+const MATCH: ModelsDevMatch = {provider_id: 'zhipuai',provider_name: 'Zhipu AI',@@ -173,7 +186,7 @@ describe('backend model catalog contract', () => {// `required`, rather than a second opinion about the same field.expect(new Set(candidate.required)).toEqual(new Set(Object.keys(CANDIDATE).filter(- (field) => !['group_if_removed', 'native_protocol'].includes(field),+ (field) => !['group_if_removed', 'native_protocol', ...MODELS_DEV_FIELDS].includes(field),)));// The re-entry vocabulary, and the reason it is a separate field: the schemadiff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.tsindex c483e1175..7065c3643 100644--- a/ui/src/components/settings/models/modelsApi.ts+++ b/ui/src/components/settings/models/modelsApi.ts@@ -25,6 +25,7 @@ import type {MigrationApplyResult,MigrationScan,ModelCandidate,+ ModelCandidateModelsDev,ModelCandidateSupplier,ModelsDevMatch,NativeProtocol,@@ -45,7 +46,7 @@ import type {UsageWindowKey,QuotaSummary,} from './types';-import { USAGE_DEFAULT_WINDOW } from './types';+import { BACKEND_MODEL_INPUT_MODALITIES, BACKEND_MODEL_OUTPUT_MODALITIES, USAGE_DEFAULT_WINDOW } from './types';/** Add-time Route placement returned by both source-creation paths. */export type Adoption = { added_to: AddedTo[]; adopted_by: AdoptedBy[] };@@ -323,6 +324,27 @@ const reentryGroup = (raw: Record<string, unknown>): Pick<ModelCandidate, 'group: {};};+const positiveInt = (value: unknown): number | null =>+ typeof value === 'number' && Number.isInteger(value) && value > 0 ? value : null;+const flag = (value: unknown): boolean | null => (typeof value === 'boolean' ? value : null);+const members = <T extends string>(value: unknown, allowed: readonly T[]): T[] =>+ Array.isArray(value) ? value.filter((item): item is T => allowed.includes(item as T)) : [];++/** A candidate's models.dev description, kept whole or not at all: the server+ * states the seven fields together, keyed by `models_dev_id`. */+const candidateModelsDev = (row: Record<string, unknown>): ModelCandidateModelsDev | Record<string, never> =>+ typeof row.models_dev_id === 'string' && row.models_dev_id+ ? {+ models_dev_id: row.models_dev_id,+ context_window: positiveInt(row.context_window),+ max_output_tokens: positiveInt(row.max_output_tokens),+ input_modalities: members(row.input_modalities, BACKEND_MODEL_INPUT_MODALITIES),+ output_modalities: members(row.output_modalities, BACKEND_MODEL_OUTPUT_MODALITIES),+ supports_tools: flag(row.supports_tools),+ supports_reasoning: flag(row.supports_reasoning),+ }+ : {};+/*** One candidate group, read defensively.*@@ -350,6 +372,7 @@ const modelCandidates = (raw: unknown, fallbackOrigin: CandidateOrigin): ModelCa? { native_protocol: row.native_protocol as NativeProtocol }: {}),...reentryGroup(row),+ ...candidateModelsDev(row),}];}): [];diff --git a/ui/src/components/settings/models/types.ts b/ui/src/components/settings/models/types.tsindex e6990c37c..662277d81 100644--- a/ui/src/components/settings/models/types.ts+++ b/ui/src/components/settings/models/types.ts@@ -272,6 +272,19 @@ export type ModelCandidate = {* nowhere, reachable through `Add custom model…`. Never inferred from* anything else on the row. */group_if_removed?: 'builtin' | 'providers' | null;+} & Partial<ModelCandidateModelsDev>;++/** What an exact models.dev match states about a provider candidate (C2).+ * All or none: the server sends these together, keyed by `models_dev_id`, and+ * only when the id names one models.dev model exactly. */+export type ModelCandidateModelsDev = {+ models_dev_id: string;+ context_window: number | null;+ max_output_tokens: number | null;+ input_modalities: BackendModelInputModality[];+ output_modalities: BackendModelOutputModality[];+ supports_tools: boolean | null;+ supports_reasoning: boolean | null;};/** The picker's one read. Groups are rendered in this order and a candidate iddiff --git a/vibe/models_dev_catalog.py b/vibe/models_dev_catalog.pyindex 9ea942428..79b9e3aa1 100644--- a/vibe/models_dev_catalog.py+++ b/vibe/models_dev_catalog.py@@ -11,7 +11,7 @@ import timeimport urllib.errorimport urllib.requestfrom pathlib import Path-from typing import Any+from typing import Any, Iterablefrom config import pathsfrom config.atomic_io import write_atomic@@ -332,12 +332,18 @@ def _modalities(model: dict[str, Any], direction: str) -> list[str]:)-def search_models_dev(query: str) -> list[dict[str, Any]]:- tokens = _search_tokens(query)- catalog = load_models_dev_catalog()- vendor_map = load_model_vendor_map()- aggregators = vendor_map["aggregators"]- candidates: dict[str, list[tuple[int, str, dict[str, Any]]]] = {}+def _catalog_rows(+ catalog: dict[str, Any],+ vendor_map: dict[str, Any],+ admit: Any,+) -> dict[str, list[tuple[Any, str, dict[str, Any]]]]:+ """Every admissible catalog copy, grouped by admitted model id.++ ``admit(provider_id, model_id, display_name)`` returns a sort key for a copy+ worth keeping, or ``None`` to skip it before any normalization work.+ """++ candidates: dict[str, list[tuple[Any, str, dict[str, Any]]]] = {}for provider_key, provider in catalog.items():if not isinstance(provider_key, str) or not isinstance(provider, dict):continue@@ -374,7 +380,7 @@ def search_models_dev(query: str) -> list[dict[str, Any]]:reasoning_efforts = _reasoning_efforts(model)if display_name is None or reasoning_efforts is None:continue- score = _match_score(tokens, provider_id, model_id, display_name)+ score = admit(provider_id, model_id, display_name)if score is None:continuelimit = model.get("limit")@@ -452,23 +458,44 @@ def search_models_dev(query: str) -> list[dict[str, Any]]:})candidates.setdefault(admitted.id, []).append((score, provider_id, row))+ return candidates+++def _preferred_copy(+ model_id: str,+ copies: list[tuple[Any, str, dict[str, Any]]],+ vendor_map: dict[str, Any],+) -> dict[str, Any]:+ first_party_vendor = _first_party_vendor(model_id, vendor_map)+ _score, _vendor_id, row = min(+ copies,+ key=lambda item: _vendor_rank(+ item[1],+ first_party_vendor=first_party_vendor,+ aggregators=vendor_map["aggregators"],+ ),+ )+ return {**row, "first_party": row["provider_id"] == first_party_vendor}+++def search_models_dev(query: str) -> list[dict[str, Any]]:+ tokens = _search_tokens(query)+ catalog = load_models_dev_catalog()+ vendor_map = load_model_vendor_map()+ candidates = _catalog_rows(+ catalog,+ vendor_map,+ lambda provider_id, model_id, display_name: _match_score(+ tokens, provider_id, model_id, display_name+ ),+ )matches: list[tuple[bool, int, str, str, dict[str, Any]]] = []for model_id, copies in candidates.items():- first_party_vendor = _first_party_vendor(model_id, vendor_map)- _score, _vendor_id, row = min(- copies,- key=lambda item: _vendor_rank(- item[1],- first_party_vendor=first_party_vendor,- aggregators=aggregators,- ),- )- first_party = row["provider_id"] == first_party_vendor- row["first_party"] = first_party+ row = _preferred_copy(model_id, copies, vendor_map)matches.append((- not first_party,+ not row["first_party"],min(item[0] for item in copies),row["display_name"].lower(),model_id,@@ -477,3 +504,49 @@ def search_models_dev(query: str) -> list[dict[str, Any]]:)matches.sort(key=lambda item: item[:-1])return [row for *_, row in matches[:MODELS_DEV_MAX_MATCHES]]+++def exact_models_dev_matches(+ model_ids: Iterable[str],+ catalog: dict[str, Any],+) -> dict[str, dict[str, Any]]:+ """The preferred models.dev copy for each id that names one exactly.++ Exact means the full ``provider/model`` identity or, failing that, the bare+ model id — the id as given or a relay's last path segment — spelled+ identically. No case, punctuation, or alias folding and no substring hits:+ this answer is applied without the user choosing it, so any looser rule+ lets a near neighbour silently describe a different model.+ """++ wanted: dict[str, list[str]] = {}+ for model_id in dict.fromkeys(model_ids):+ for key in dict.fromkeys((model_id, model_id.rsplit("/", 1)[-1])):+ wanted.setdefault(key, []).append(model_id)+ if not wanted or not catalog:+ return {}+ vendor_map = load_model_vendor_map()+ by_request: dict[str, list[tuple[int, str, dict[str, Any]]]] = {}++ def admit(provider_id: str, model_id: str, _display_name: str):+ hits = [(0, requested) for requested in wanted.get(f"{provider_id}/{model_id}", ())]+ hits += [(1, requested) for requested in wanted.get(model_id, ())]+ return hits or None++ for copies in _catalog_rows(catalog, vendor_map, admit).values():+ for hits, provider_id, row in copies:+ for requested in dict.fromkeys(requested for _rank, requested in hits):+ rank = min(rank for rank, other in hits if other == requested)+ by_request.setdefault(requested, []).append((rank, provider_id, row))+ matches: dict[str, dict[str, Any]] = {}+ for requested, copies in by_request.items():+ best = min(rank for rank, _provider, _row in copies)+ closest = [copy for copy in copies if copy[0] == best]+ # Every closest copy names one catalog model id, so the family that+ # decides first-party ownership is read off the catalog row.+ matches[requested] = _preferred_copy(+ closest[0][2]["model_id"],+ closest,+ vendor_map,+ )+ return matches