Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(model_hub): keep credential addresses out of stored model names
cyheb9947678fca
diff --git a/config/v2_config.py b/config/v2_config.pyindex 5a50548a1..4f350c475 100644--- a/config/v2_config.py+++ b/config/v2_config.py@@ -2729,10 +2729,16 @@ class ModelHubModelConfig:# config, so no admission path can invent a second spelling for one# model and split its usage across two ledger rows. New-admission checks# stay with callers: this constructor also reads older persisted files.- from core.handlers.model_hub.identifiers import normalized_model_id+ # A credential address is unwrapped as part of that settling, and not+ # inside `normalized_model_id`, because that spelling is also what a+ # usage ledger key is derived from and its historical encoding is fixed.+ from core.handlers.model_hub.identifiers import (+ model_id_without_credential_address,+ normalized_model_id,+ )return cls(- id=normalized_model_id(model_id),+ id=model_id_without_credential_address(normalized_model_id(model_id)),provenance=origin,reasoning_efforts=list(reasoning_efforts),reasoning_efforts_source=reasoning_efforts_source,@@ -3071,9 +3077,15 @@ class ModelHubRouteHopConfig:):raise ValueError("Config 'model_hub.agents.routes.hops.model_id' is invalid")# Keep saved targets in the same canonical namespace as inventory evidence.- from core.handlers.model_hub.identifiers import normalized_model_id+ from core.handlers.model_hub.identifiers import (+ model_id_without_credential_address,+ normalized_model_id,+ )- return cls(source_id=source_id, model_id=normalized_model_id(model_id))+ return cls(+ source_id=source_id,+ model_id=model_id_without_credential_address(normalized_model_id(model_id)),+ )def to_payload(self) -> dict:return {"source_id": self.source_id, "model_id": self.model_id}diff --git a/core/handlers/model_hub/identifiers.py b/core/handlers/model_hub/identifiers.pyindex afb650baf..fc4ebefec 100644--- a/core/handlers/model_hub/identifiers.py+++ b/core/handlers/model_hub/identifiers.py@@ -3,6 +3,7 @@from __future__ import annotationsimport hashlib+import re# Usage rows shipped with a 200-character readable head. Keep that threshold# stable even when a later API admits longer model identifiers, or one upgrade@@ -16,6 +17,35 @@ USAGE_LEDGER_KEY_MAX_LENGTH = (USAGE_LEDGER_VERBATIM_MAX_LENGTH + 1 + 2 * hashlib.sha256().digest_size)+# The engine addresses a credential through the model name and no other field,+# so an outbound call spells one as ``<source prefix>/<model>``. That prefix is+# the address of a credential, never part of a model's identity, and it is+# minted per Source as ``avibe-`` plus twelve random bytes. Match that minted+# spelling exactly rather than any leading segment: an upstream identity may+# legitimately carry a slash of its own — OpenRouter's ``anthropic/claude-x``,+# Together's ``meta-llama/Llama-3-70b`` — and stripping one of those would+# rename the model instead of unwrapping an address.+_CREDENTIAL_ADDRESS = re.compile(r"avibe-[0-9a-f]{24}")+++def model_id_without_credential_address(value: str) -> str:+ """Return the identity ``value`` names, with no credential address around it.++ The engine's management API answers with names it has already addressed, so+ a discovered identity arrives wrapped and a persisted one may have been+ stored wrapped by an earlier release. Unwrapping repeatedly rather than once+ makes the result total: whatever this returns carries no address, so a+ caller never has to ask how many an identity accumulated.+ """++ identity = value+ while True:+ address, separator, remainder = identity.partition("/")+ if not separator or not remainder or not _CREDENTIAL_ADDRESS.fullmatch(address):+ return identity+ identity = remainder++OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL = {"openai_responses": "avibe-openai","anthropic": "avibe-anthropic",diff --git a/tests/test_model_hub_credential_address.py b/tests/test_model_hub_credential_address.pynew file mode 100644index 000000000..bbe074ee2--- /dev/null+++ b/tests/test_model_hub_credential_address.py@@ -0,0 +1,182 @@+"""A credential's address never survives into stored or displayed model names.++The engine reaches one credential through the model field of one outbound+request and through no other field, so a call spells its target+``<source prefix>/<model>``. That prefix addresses a credential; it is not part+of what the model is called. These tests hold the boundary in both directions:+nothing the product stores, shows, or matches against carries an address, and a+file an earlier release wrote with one still loads.+"""++import pytest++from config.v2_config import ModelHubModelConfig, ModelHubRouteConfig, ModelHubSourceConfig+from core.handlers.model_hub.identifiers import (+ model_id_without_credential_address,+ normalized_model_id,+ usage_ledger_key,+)+from vibe.model_hub_runtime.adapter import _discovered_models+from vibe.model_hub_runtime.state import EngineStateError, SourceRecord++ADDRESS = "avibe-dc0395516c77a0ee4e62e01e"+++ ("stored", "identity"),+ [+ (f"{ADDRESS}/gpt-5.5", "gpt-5.5"),+ (f"{ADDRESS}/{ADDRESS}/gpt-5.5", "gpt-5.5"),+ # An upstream identity may carry a slash of its own. Unwrapping by+ # leading segment rather than by the minted spelling would rename these.+ ("anthropic/claude-sonnet-4", "anthropic/claude-sonnet-4"),+ ("meta-llama/Llama-3-70b-instruct", "meta-llama/Llama-3-70b-instruct"),+ ("accounts/fireworks/models/mixtral", "accounts/fireworks/models/mixtral"),+ # Neither is the minted spelling: twelve random bytes, lowercase hex.+ ("avibe-short/gpt-5.5", "avibe-short/gpt-5.5"),+ (f"{ADDRESS.upper()}/gpt-5.5", f"{ADDRESS.upper()}/gpt-5.5"),+ ("avibe-openai/gpt-5.5", "avibe-openai/gpt-5.5"),+ # An address with nothing behind it names no model to recover.+ (f"{ADDRESS}/", f"{ADDRESS}/"),+ (ADDRESS, ADDRESS),+ ],+)+def test_only_the_minted_address_is_unwrapped(stored: str, identity: str) -> None:+ assert model_id_without_credential_address(stored) == identity+++def test_usage_ledger_spelling_is_left_alone() -> None:+ """Unwrapping is not folded into the spelling a ledger key is derived from.++ ``usage_ledger_key`` hashes the canonical identity and its historical+ encoding is fixed, so a row written before this change must keep deriving+ the key it was written under.+ """++ addressed = f"{ADDRESS}/gpt-5.5"+ assert normalized_model_id(addressed) == addressed+ assert usage_ledger_key(addressed) == addressed+++def test_persisted_source_model_loads_without_its_address() -> None:+ model = ModelHubModelConfig.from_payload(+ {"id": f"{ADDRESS}/gpt-5.5", "origin": "discovered", "reasoning_efforts": []}+ )+ assert model.id == "gpt-5.5"+++def test_persisted_route_hop_loads_without_its_address() -> None:+ route = ModelHubRouteConfig.from_payload(+ {"hops": [{"source_id": "src_fixture123", "model_id": f"{ADDRESS}/gpt-5.5"}]},+ repairing=True,+ )+ assert [hop.model_id for hop in route.hops] == ["gpt-5.5"]+++def _source_payload(model_ids: list[str]) -> dict:+ return {+ "id": "src_fixture123",+ "kind": "api_key",+ "vendor": "openai",+ "display_name": "Fixture",+ "protocol": "openai_responses",+ "base_url": None,+ "supply_channel": "hub",+ "billing": "metered",+ "state": {"status": "standby"},+ "credential_ref": "cred_fixture123",+ "models": [+ {"id": model_id, "origin": "discovered", "reasoning_efforts": []}+ for model_id in model_ids+ ],+ }+++def test_addressed_and_bare_rows_collapse_when_repairing_a_file() -> None:+ """Both spellings name one model, and a file that loads must keep loading."""++ source = ModelHubSourceConfig.from_payload(+ _source_payload([f"{ADDRESS}/gpt-5.5", "gpt-5.5"]), repairing=True+ )+ assert [model.id for model in source.models] == ["gpt-5.5"]+++def test_addressed_and_bare_rows_are_refused_from_a_caller() -> None:+ with pytest.raises(ValueError, match="duplicate ids"):+ ModelHubSourceConfig.from_payload(_source_payload([f"{ADDRESS}/gpt-5.5", "gpt-5.5"]))+++def _record_payload(**overrides: object) -> dict:+ payload = {+ "source_id": "src_fixture123",+ "vendor": "openai",+ "protocol": "openai_responses",+ "base_url": None,+ "credential_ref": "cred_fixture123",+ "allowed_origins": ["main"],+ "model_ids": [f"{ADDRESS}/gpt-5.5"],+ "route_model_ids": [f"{ADDRESS}/gpt-5.5"],+ "prefix": ADDRESS,+ "model_reasoning_efforts": [[f"{ADDRESS}/gpt-5.5", ["low", "high"]]],+ }+ payload.update(overrides)+ return payload+++def test_engine_record_rekeys_reasoning_efforts_with_its_model_ids() -> None:+ """The reasoning map is keyed by model id, so unwrapping must move the key.++ Unwrapping the ids alone would leave every effort list addressed to a model+ no longer in the inventory, and each model would silently fall back to its+ default effort.+ """++ record = SourceRecord.from_payload(_record_payload())++ assert record.model_ids == ("gpt-5.5",)+ assert record.route_model_ids == ("gpt-5.5",)+ assert record.model_reasoning_efforts == (("gpt-5.5", ("low", "high")),)+ assert record.prefix == ADDRESS+++def test_engine_record_collapses_an_addressed_duplicate() -> None:+ record = SourceRecord.from_payload(+ _record_payload(+ model_ids=[f"{ADDRESS}/gpt-5.5", "gpt-5.5"],+ route_model_ids=[f"{ADDRESS}/gpt-5.5", "gpt-5.5"],+ model_reasoning_efforts=[+ [f"{ADDRESS}/gpt-5.5", ["high"]],+ ["gpt-5.5", ["low"]],+ ],+ )+ )++ assert record.model_ids == ("gpt-5.5",)+ assert record.route_model_ids == ("gpt-5.5",)+ assert record.model_reasoning_efforts == (("gpt-5.5", ("high",)),)+++def test_engine_record_still_refuses_an_unreadable_reasoning_map() -> None:+ """Healing reads what it recognizes; the strict parse still reports the rest."""++ with pytest.raises(EngineStateError, match="invalid engine source reasoning state"):+ SourceRecord.from_payload(+ _record_payload(model_reasoning_efforts=[["unregistered-model", ["high"]]])+ )+++def test_discovery_drops_the_address_the_engine_answers_with() -> None:+ """The management API answers with the name it addresses the credential by."""++ models = _discovered_models(+ {+ "models": [+ {"id": f"{ADDRESS}/gpt-5.5", "supported_parameters": ["reasoning"]},+ {"id": f"{ADDRESS}/gpt-6-astra"},+ {"id": "gpt-5.5"},+ ]+ }+ )++ assert [model.id for model in models] == ["gpt-5.5", "gpt-6-astra"]+ assert models[0].supported_parameters == ("reasoning",)diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex ddba51763..cc69a8d99 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -34,6 +34,7 @@ from core.handlers.model_hub.adapter import (make_source_observation,)from core.handlers.model_hub.errors import ModelDiscoveryError+from core.handlers.model_hub.identifiers import model_id_without_credential_addressfrom core.handlers.model_hub.async_owner import run_owned_in_threadfrom vibe.model_hub_runtime.client import (_OFFICIAL_BASE_URLS,@@ -2911,7 +2912,14 @@ def _discovered_models(payload: Mapping[str, Any]) -> tuple[DiscoveredModel, ...seen: set[str] = set()for item in models:value = item.get("id") or item.get("alias") or item.get("name") if isinstance(item, dict) else item- if not isinstance(value, str) or not value or value in seen:+ if not isinstance(value, str) or not value:+ continue+ # The engine answers with the name it addresses this credential by. The+ # address is how one call reaches one credential, never part of what the+ # model is called, so it is unwrapped here — at the boundary it enters+ # the product — rather than by every later reader of the inventory.+ value = model_id_without_credential_address(value)+ if not value or value in seen:continueseen.add(value)supported_parameters = Nonediff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.pyindex 5aa96f478..ab1477820 100644--- a/vibe/model_hub_runtime/state.py+++ b/vibe/model_hub_runtime/state.py@@ -16,6 +16,7 @@ from typing import Any, Callable, Sequencefrom config.atomic_io import write_atomicfrom config.v2_config import normalize_model_hub_base_url+from core.handlers.model_hub.identifiers import model_id_without_credential_addressfrom vibe.model_hub_runtime.api_key_vendors import (official_api_key_base_url,validate_api_key_auth_scheme,@@ -40,6 +41,56 @@ class RuntimeSecrets:gateway_token: str+def _without_credential_addresses(payload: dict[str, Any]) -> dict[str, Any]:+ """Read a record an earlier release stored with addressed model names.++ The address belongs to the outbound call, not to the file, but releases+ before this one persisted whatever the engine's management API answered+ with — which is already addressed. Healing on load rather than in a+ one-shot script keeps one spelling in memory no matter which release wrote+ the file, and the next ordinary write persists it.++ Unwrapping can collapse two stored names onto one identity. The strict+ parse below refuses a repeated reasoning key and a repeated route target,+ so this keeps the first of each instead: a file that loads today must keep+ loading, and a healed duplicate is the same model named twice, not a+ conflict to report. Any shape this cannot read is left exactly as it was,+ so the parse still reports it.+ """++ healed = dict(payload)+ model_ids = payload.get("model_ids")+ if isinstance(model_ids, list):+ healed["model_ids"] = list(+ dict.fromkeys(+ model_id_without_credential_address(str(model)) for model in model_ids+ )+ )+ route_model_ids = payload.get("route_model_ids")+ if isinstance(route_model_ids, list) and all(+ isinstance(model, str) for model in route_model_ids+ ):+ healed["route_model_ids"] = list(+ dict.fromkeys(+ model_id_without_credential_address(model) for model in route_model_ids+ )+ )+ reasoning_efforts = payload.get("model_reasoning_efforts")+ if isinstance(reasoning_efforts, list) and all(+ isinstance(item, list) and len(item) == 2 and isinstance(item[0], str)+ for item in reasoning_efforts+ ):+ healed_efforts: dict[str, Any] = {}+ for model_id, efforts in reasoning_efforts:+ healed_efforts.setdefault(+ model_id_without_credential_address(model_id), efforts+ )+ healed["model_reasoning_efforts"] = [+ [model_id, efforts] for model_id, efforts in healed_efforts.items()+ ]+ return healed++@dataclass(frozen=True)class SourceRecord:source_id: str@@ -55,6 +106,7 @@ class SourceRecord:@classmethoddef from_payload(cls, payload: dict[str, Any]) -> SourceRecord:+ payload = _without_credential_addresses(payload)try:raw_reasoning_efforts = payload["model_reasoning_efforts"]except KeyError as exc:@@ -532,7 +584,12 @@ class EngineStateStore:if credential["kind"] == "oauth" and not allowed_origins:raise EngineStateError("OAuth source requires at least one allowed origin")previous = existing.get(source_id)- model_ids = tuple(dict.fromkeys(str(model).strip() for model in binding.model_ids))+ model_ids = tuple(+ dict.fromkeys(+ model_id_without_credential_address(str(model).strip())+ for model in binding.model_ids+ )+ )if any(not model for model in model_ids):raise EngineStateError("model id cannot be empty")route_model_ids = tuple(binding.route_model_ids)@@ -540,7 +597,7 @@ class EngineStateStore:raise EngineStateError("invalid route model id")reasoning_by_model: dict[str, tuple[str, ...]] = {}for model_id, efforts in binding.model_reasoning_efforts:- normalized_model_id = str(model_id).strip()+ normalized_model_id = model_id_without_credential_address(str(model_id).strip())if not normalized_model_id or normalized_model_id not in model_ids:raise EngineStateError("reasoning model id is not registered")if normalized_model_id in reasoning_by_model:@@ -560,7 +617,14 @@ class EngineStateStore:credential_ref=credential_ref,allowed_origins=allowed_origins,model_ids=model_ids,- route_model_ids=tuple(sorted(set(route_model_ids))),+ route_model_ids=tuple(+ sorted(+ {+ model_id_without_credential_address(model)+ for model in route_model_ids+ }+ )+ ),prefix=(str(credential["prefix"])if credential.get("prefix")@@ -585,7 +649,12 @@ class EngineStateStore:current = next((source for source in sources if source.source_id == source_id), None)if current is None:raise EngineStateError("source is not registered")- models = tuple(dict.fromkeys(str(model).strip() for model in model_ids))+ models = tuple(+ dict.fromkeys(+ model_id_without_credential_address(str(model).strip())+ for model in model_ids+ )+ )if not models:raise EngineStateError("source requires at least one model id")if any(not model for model in models):