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): remove an address only where its owner is known

cyh71d14e485db0
diff --git a/config/v2_config.py b/config/v2_config.py
index 4f350c475..e143d07d8 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -800,8 +800,153 @@ def _migrate_opencode_active_turn_timeout_on_load(payload: dict) -> dict:
return migrated
+def _migrate_model_hub_credential_addresses(payload: dict) -> dict:
+ """Drop credential addresses from model names an earlier release stored.
+
+ The engine addresses a credential through the model field of one outbound
+ request, so a call spells its target ``<source prefix>/<model>``. Releases
+ before this one persisted what the engine's management API answered with,
+ which is already addressed, so a stored inventory id could carry the address
+ of the credential that served it. Composition then addressed it a second
+ time and the engine refused the call, and resolution — which compares a
+ menu id against an inventory id literally — matched nothing either.
+
+ A bounded repair rather than a rule in the admission path. Discovery now
+ removes the address of the credential it is discovering, at the boundary
+ where the address enters, so no newly written file carries one; what remains
+ is files already written, and this is the compatibility boundary that reads
+ them. Nothing here is claimed about a name a caller sends afterwards.
+
+ Only rows discovery produced are touched. Those are the only rows an address
+ could have reached, and it means a model a person added by hand is never
+ renamed, however it is spelled. A config file records no prefix to compare
+ against — that lives with the credential — so the address is recognised by
+ its minted shape, which is safe exactly because of that provenance limit.
+
+ Unwrapping can land a discovered row on a name a manual row already holds,
+ which is the shape left behind when someone added the bare name by hand to
+ work around this bug. The manual row wins: it carries a display name,
+ reasoning efforts, and a provenance a person chose, and the discovered row
+ duplicates an identity rather than adding one. Next discovery re-attaches
+ upstream metadata to the surviving row.
+
+ Any shape this cannot read is returned untouched, so the strict parse that
+ follows still reports it rather than having it quietly repaired here.
+ """
+
+ model_hub = payload.get("model_hub")
+ if not isinstance(model_hub, dict):
+ return payload
+ raw_sources = model_hub.get("sources")
+ if not isinstance(raw_sources, list):
+ return payload
+
+ from core.handlers.model_hub.identifiers import model_id_without_credential_address
+
+ healed_sources: list[dict] = []
+ # Per Source, the addressed spellings this repair renamed and what each
+ # became. A route hop is rewritten only if it names one of these, so a hop
+ # is never redirected to a model this file does not show it already meant.
+ renamed: dict[str, dict[str, str]] = {}
+ changed = False
+ for source in raw_sources:
+ if not isinstance(source, dict):
+ return payload
+ models = source.get("models")
+ source_id = source.get("id")
+ if not isinstance(models, list) or not isinstance(source_id, str):
+ healed_sources.append(source)
+ continue
+ # Which rows this repair moves, and which names it is not moving. Read
+ # before anything is rewritten, because a name a row already holds
+ # outranks one this repair would move onto it however the file orders
+ # the two — a manual row a person added by hand to work around this
+ # bug most of all.
+ settled: dict[str, str] = {}
+ held: set[str] = set()
+ for model in models:
+ if not isinstance(model, dict):
+ return payload
+ model_id = model.get("id")
+ if not isinstance(model_id, str) or not model_id:
+ continue
+ identity = (
+ model_id_without_credential_address(model_id)
+ if model.get("origin") == "discovered"
+ else model_id
+ )
+ if identity == model_id:
+ held.add(model_id)
+ else:
+ settled[model_id] = identity
+
+ healed_models: list[dict] = []
+ moved: set[str] = set()
+ for model in models:
+ model_id = model.get("id")
+ identity = settled.get(model_id) if isinstance(model_id, str) else None
+ if identity is None:
+ # Untouched, including a row this file lists twice: a duplicate
+ # this repair did not create is still the strict parse's to report.
+ healed_models.append(model)
+ continue
+ changed = True
+ if identity in held or identity in moved:
+ continue
+ moved.add(identity)
+ healed_models.append({**model, "id": identity})
+ if settled:
+ renamed[source_id] = settled
+ healed_sources.append({**source, "models": healed_models})
+
+ if not changed:
+ return payload
+
+ healed_hub = {**model_hub, "sources": healed_sources}
+ agents = model_hub.get("agents")
+ if isinstance(agents, dict):
+ healed_agents: dict[str, object] = {}
+ for backend, agent in agents.items():
+ routes = agent.get("routes") if isinstance(agent, dict) else None
+ if not isinstance(routes, dict):
+ healed_agents[backend] = agent
+ continue
+ healed_routes: dict[str, object] = {}
+ for requested, route in routes.items():
+ hops = route.get("hops") if isinstance(route, dict) else None
+ if not isinstance(hops, list):
+ healed_routes[requested] = route
+ continue
+ healed_hops: list[object] = []
+ # Which hop already holds each pair, and whether this repair is
+ # what put it there. A hop is dropped only where renaming is
+ # what made the two identical; a route that already listed one
+ # hop twice still reaches the strict parse that refuses it.
+ settled_hops: dict[tuple[str, str], bool] = {}
+ for hop in hops:
+ if isinstance(hop, dict):
+ source_id = hop.get("source_id")
+ model_id = hop.get("model_id")
+ if isinstance(source_id, str) and isinstance(model_id, str):
+ identity = renamed.get(source_id, {}).get(model_id)
+ if identity is not None:
+ hop = {**hop, "model_id": identity}
+ model_id = identity
+ earlier = settled_hops.get((source_id, model_id))
+ if earlier is not None and (identity is not None or earlier):
+ continue
+ settled_hops[(source_id, model_id)] = identity is not None
+ healed_hops.append(hop)
+ healed_routes[requested] = {**route, "hops": healed_hops}
+ healed_agents[backend] = {**agent, "routes": healed_routes}
+ healed_hub["agents"] = healed_agents
+
+ return {**payload, "model_hub": healed_hub}
+
+
def _migrate_config_payload_on_load(payload: dict) -> tuple[dict, bool, tuple[str, ...]]:
migrated, changed, warnings = _migrate_legacy_model_hub_payload(payload)
+ migrated = _migrate_model_hub_credential_addresses(migrated)
migrated, catalog_changed, catalog_warnings = _migrate_legacy_opencode_catalog(migrated)
model_hub_changed = changed or catalog_changed or migrated.get("model_hub") != payload.get("model_hub")
migrated = _migrate_opencode_active_turn_timeout_on_load(migrated)
@@ -2729,16 +2874,10 @@ 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.
- # 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,
- )
+ from core.handlers.model_hub.identifiers import normalized_model_id
return cls(
- id=model_id_without_credential_address(normalized_model_id(model_id)),
+ id=normalized_model_id(model_id),
provenance=origin,
reasoning_efforts=list(reasoning_efforts),
reasoning_efforts_source=reasoning_efforts_source,
@@ -3077,15 +3216,9 @@ 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 (
- model_id_without_credential_address,
- normalized_model_id,
- )
+ from core.handlers.model_hub.identifiers import normalized_model_id
- return cls(
- source_id=source_id,
- model_id=model_id_without_credential_address(normalized_model_id(model_id)),
- )
+ return cls(source_id=source_id, model_id=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.py
index fc4ebefec..37767dc72 100644
--- a/core/handlers/model_hub/identifiers.py
+++ b/core/handlers/model_hub/identifiers.py
@@ -17,31 +17,45 @@ 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:
+# The shape a Source prefix is minted in: ``avibe-`` plus twelve random bytes.
+# Only ever used to recognise an address in a record that does not say which one
+# it carries; wherever the owning prefix is known, it is compared literally.
+_CREDENTIAL_ADDRESS_SHAPE = re.compile(r"avibe-[0-9a-f]{24}")
+
+
+def model_id_without_credential_address(value: str, prefix: str | None = None) -> 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.
+ 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.
+
+ ``prefix`` is the address of the credential this identity belongs to. Given
+ one, only that exact address is removed, so nothing is claimed about any
+ other name: reserving the whole ``avibe-<hex>/`` namespace would rewrite an
+ upstream identity that happened to be spelled that way, and an identity is
+ not ours to rename. Callers that hold the owning Source or credential always
+ pass it.
+
+ Without one, the address is recognised by its minted shape. That is for a
+ record which stores no prefix of its own to compare against — a config file
+ an earlier release wrote — and it is why that path is confined to rows
+ discovery produced, which are the only rows an address can have reached.
+
+ Unwrapping repeatedly rather than once makes the result total: whatever this
+ returns carries no address, so a caller never has to ask how many one
+ identity accumulated across releases.
"""
identity = value
while True:
address, separator, remainder = identity.partition("/")
- if not separator or not remainder or not _CREDENTIAL_ADDRESS.fullmatch(address):
+ if not separator or not remainder:
+ return identity
+ if prefix is not None:
+ if address != prefix:
+ return identity
+ elif not _CREDENTIAL_ADDRESS_SHAPE.fullmatch(address):
return identity
identity = remainder
diff --git a/tests/test_model_hub_credential_address.py b/tests/test_model_hub_credential_address.py
index bbe074ee2..67c760e70 100644
--- a/tests/test_model_hub_credential_address.py
+++ b/tests/test_model_hub_credential_address.py
@@ -6,20 +6,35 @@ request and through no other field, so a call spells its target
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.
+
+The address is removed where its owner is known, so what gets removed is a
+credential's own address and never a name that merely looks like one. Discovery
+knows the credential it is discovering, an engine record names the prefix it is
+addressed by, and a config file — which records no prefix at all — is repaired
+once on load, for the rows discovery produced, by the minted spelling.
"""
+import copy
+import json
+
import pytest
-from config.v2_config import ModelHubModelConfig, ModelHubRouteConfig, ModelHubSourceConfig
+from config.v2_config import V2Config
from core.handlers.model_hub.identifiers import (
model_id_without_credential_address,
normalized_model_id,
usage_ledger_key,
)
+from core.services.settings import default_config
+from vibe import api
from vibe.model_hub_runtime.adapter import _discovered_models
from vibe.model_hub_runtime.state import EngineStateError, SourceRecord
ADDRESS = "avibe-dc0395516c77a0ee4e62e01e"
+# Minted the same way, for some other credential. Nothing here may treat the two
+# as interchangeable: removing one credential's address from another's model
+# would leave a name no source can serve.
+OTHER_ADDRESS = "avibe-4f21ab90c3de5871ba0c6d17"
@pytest.mark.parametrize(
@@ -32,6 +47,7 @@ ADDRESS = "avibe-dc0395516c77a0ee4e62e01e"
("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"),
+ ("x-ai/grok-4.6-latest", "x-ai/grok-4.6-latest"),
# 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"),
@@ -42,9 +58,30 @@ ADDRESS = "avibe-dc0395516c77a0ee4e62e01e"
],
)
def test_only_the_minted_address_is_unwrapped(stored: str, identity: str) -> None:
+ """Without an owner to compare against, the minted spelling is the whole rule."""
+
assert model_id_without_credential_address(stored) == identity
+ ("prefix", "stored", "identity"),
+ [
+ (ADDRESS, f"{ADDRESS}/gpt-5.5", "gpt-5.5"),
+ (ADDRESS, f"{ADDRESS}/{ADDRESS}/gpt-5.5", "gpt-5.5"),
+ # Minted, but minted for someone else. A name this credential cannot be
+ # proven to have addressed is left as whoever named it spelled it.
+ (ADDRESS, f"{OTHER_ADDRESS}/gpt-5.5", f"{OTHER_ADDRESS}/gpt-5.5"),
+ (ADDRESS, "anthropic/claude-sonnet-4", "anthropic/claude-sonnet-4"),
+ (ADDRESS, "gpt-5.5", "gpt-5.5"),
+ # Provenance authorizes the removal, not the spelling: a credential
+ # addressed by something the mint would not produce today still owns it.
+ ("legacy-prefix", "legacy-prefix/gpt-5.5", "gpt-5.5"),
+ ],
+)
+def test_only_the_owning_address_is_unwrapped(prefix: str, stored: str, identity: str) -> None:
+ assert model_id_without_credential_address(stored, prefix) == identity
+
+
def test_usage_ledger_spelling_is_left_alone() -> None:
"""Unwrapping is not folded into the spelling a ledger key is derived from.
@@ -58,52 +95,44 @@ def test_usage_ledger_spelling_is_left_alone() -> None:
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_discovery_drops_the_address_the_engine_answers_with() -> None:
+ """The management API answers with the name it addresses the credential by.
+ This is the boundary the address enters through, so it is where the address
+ leaves. Discovery holds the credential, so it removes that credential's own
+ address and nothing else.
+ """
-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,
+ models = _discovered_models(
+ {
+ "models": [
+ {"id": f"{ADDRESS}/gpt-5.5", "supported_parameters": ["reasoning"]},
+ {"id": f"{ADDRESS}/gpt-6-astra"},
+ {"id": "gpt-5.5"},
+ ]
+ },
+ ADDRESS,
)
- assert [hop.model_id for hop in route.hops] == ["gpt-5.5"]
+ assert [model.id for model in models] == ["gpt-5.5", "gpt-6-astra"]
+ assert models[0].supported_parameters == ("reasoning",)
-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_discovery_keeps_a_name_it_cannot_prove_is_an_address() -> None:
+ models = _discovered_models(
+ {"models": [{"id": f"{OTHER_ADDRESS}/gpt-5.5"}, {"id": "x-ai/grok-4.6-latest"}]},
+ ADDRESS,
+ )
-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."""
+ assert [model.id for model in models] == [f"{OTHER_ADDRESS}/gpt-5.5", "x-ai/grok-4.6-latest"]
- 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_discovery_without_a_known_address_falls_back_to_the_minted_shape() -> None:
+ """A credential whose metadata carries no prefix still yields bare names."""
+
+ models = _discovered_models({"models": [{"id": f"{ADDRESS}/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"]))
+ assert [model.id for model in models] == ["gpt-5.5"]
def _record_payload(**overrides: object) -> dict:
@@ -156,6 +185,22 @@ def test_engine_record_collapses_an_addressed_duplicate() -> None:
assert record.model_reasoning_efforts == (("gpt-5.5", ("high",)),)
+def test_engine_record_keeps_a_name_addressed_to_another_credential() -> None:
+ """A record removes the address it is reached by, not every minted spelling."""
+
+ record = SourceRecord.from_payload(
+ _record_payload(
+ model_ids=[f"{OTHER_ADDRESS}/gpt-5.5"],
+ route_model_ids=[f"{OTHER_ADDRESS}/gpt-5.5"],
+ model_reasoning_efforts=[[f"{OTHER_ADDRESS}/gpt-5.5", ["high"]]],
+ )
+ )
+
+ assert record.model_ids == (f"{OTHER_ADDRESS}/gpt-5.5",)
+ assert record.route_model_ids == (f"{OTHER_ADDRESS}/gpt-5.5",)
+ assert record.model_reasoning_efforts == ((f"{OTHER_ADDRESS}/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."""
@@ -165,18 +210,199 @@ def test_engine_record_still_refuses_an_unreadable_reasoning_map() -> None:
)
-def test_discovery_drops_the_address_the_engine_answers_with() -> None:
- """The management API answers with the name it addresses the credential by."""
+SOURCE_ID = "src_fixture123"
- models = _discovered_models(
+
+def _model_payload(model_id: str, origin: str = "discovered", **overrides: object) -> dict:
+ payload = {
+ "id": model_id,
+ "display_name": None,
+ "origin": origin,
+ "reasoning_efforts": [],
+ }
+ if origin == "discovered":
+ payload["discovered_at"] = "2026-07-23T03:00:00Z"
+ payload.update(overrides)
+ return payload
+
+
+def _config_payload(models: list[dict], hops: list[dict] | None = None) -> dict:
+ payload = api.config_to_payload(default_config(), include_secrets=True, include_internal=True)
+ payload["model_hub"]["sources"] = [
{
- "models": [
- {"id": f"{ADDRESS}/gpt-5.5", "supported_parameters": ["reasoning"]},
- {"id": f"{ADDRESS}/gpt-6-astra"},
- {"id": "gpt-5.5"},
- ]
+ "id": SOURCE_ID,
+ "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": copy.deepcopy(models),
}
+ ]
+ if hops is not None:
+ route = payload["model_hub"]["agents"]["claude"]["routes"].setdefault(
+ "claude-opus-4-6", {"hops": []}
+ )
+ route["hops"] = copy.deepcopy(hops)
+ return payload
+
+
+def _load(tmp_path, payload: dict) -> V2Config:
+ config_path = tmp_path / "config.json"
+ config_path.write_text(json.dumps(payload, ensure_ascii=False), encoding="utf-8")
+ return V2Config.load(config_path=config_path)
+
+
+def test_a_file_an_earlier_release_addressed_loads_without_the_address(tmp_path) -> None:
+ """One repair on load, for a file written before discovery stopped storing one."""
+
+ loaded = _load(
+ tmp_path,
+ _config_payload(
+ [_model_payload(f"{ADDRESS}/gpt-5.5"), _model_payload(f"{ADDRESS}/gpt-6-astra")],
+ [{"source_id": SOURCE_ID, "model_id": f"{ADDRESS}/gpt-5.5"}],
+ ),
)
- assert [model.id for model in models] == ["gpt-5.5", "gpt-6-astra"]
- assert models[0].supported_parameters == ("reasoning",)
+ assert loaded.load_warnings == ()
+ assert [model.id for model in loaded.model_hub.sources[0].models] == ["gpt-5.5", "gpt-6-astra"]
+ hops = loaded.model_hub.agents["claude"].routes["claude-opus-4-6"].hops
+ assert [hop.model_id for hop in hops] == ["gpt-5.5"]
+
+
+def test_a_model_a_person_added_keeps_the_name_they_gave_it(tmp_path) -> None:
+ """Only discovery could have stored an address, so only its rows are repaired.
+
+ A hand-added model spelled like an address is a name someone chose. Renaming
+ it would point the row at a model the source may not serve at all.
+ """
+
+ loaded = _load(tmp_path, _config_payload([_model_payload(f"{ADDRESS}/gpt-5.5", "manual")]))
+
+ assert [model.id for model in loaded.model_hub.sources[0].models] == [f"{ADDRESS}/gpt-5.5"]
+
+
+def test_a_repaired_row_yields_to_the_manual_row_already_holding_its_name(tmp_path) -> None:
+ """The shape left behind by working around this bug by hand.
+
+ Both rows name one model once the address is gone. The manual row is the one
+ a person made — it carries their display name and their provenance — and the
+ discovered row adds no identity the surviving row does not already have.
+ """
+
+ loaded = _load(
+ tmp_path,
+ _config_payload(
+ [
+ _model_payload(f"{ADDRESS}/gpt-5.5"),
+ _model_payload("gpt-5.5", "manual", display_name="Added by hand"),
+ ]
+ ),
+ )
+
+ assert loaded.load_warnings == ()
+ models = loaded.model_hub.sources[0].models
+ assert [(model.id, model.provenance, model.display_name) for model in models] == [
+ ("gpt-5.5", "manual", "Added by hand")
+ ]
+
+
+def test_two_spellings_of_one_hop_collapse_onto_the_model_they_now_name(tmp_path) -> None:
+ loaded = _load(
+ tmp_path,
+ _config_payload(
+ [_model_payload(f"{ADDRESS}/gpt-5.5"), _model_payload("gpt-5.5")],
+ [
+ {"source_id": SOURCE_ID, "model_id": f"{ADDRESS}/gpt-5.5"},
+ {"source_id": SOURCE_ID, "model_id": "gpt-5.5"},
+ ],
+ ),
+ )
+
+ assert loaded.load_warnings == ()
+ assert [model.id for model in loaded.model_hub.sources[0].models] == ["gpt-5.5"]
+ hops = loaded.model_hub.agents["claude"].routes["claude-opus-4-6"].hops
+ assert [(hop.source_id, hop.model_id) for hop in hops] == [(SOURCE_ID, "gpt-5.5")]
+
+
+def test_a_hop_this_repair_did_not_rename_is_left_where_it_points(tmp_path) -> None:
+ """A hop follows its source's rows; it is never redirected on its own.
+
+ Nothing in the file shows this hop meant ``gpt-5.5``: the source holds no row
+ that was renamed to it. Rewriting the hop anyway would move a route to a
+ model on a guess, so the hop stays and the ordinary unavailable-target path
+ reports it.
+ """
+
+ loaded = _load(
+ tmp_path,
+ _config_payload(
+ [_model_payload(f"{ADDRESS}/gpt-6-astra")],
+ [{"source_id": SOURCE_ID, "model_id": f"{ADDRESS}/gpt-5.5"}],
+ ),
+ )
+
+ assert [model.id for model in loaded.model_hub.sources[0].models] == ["gpt-6-astra"]
+ hops = loaded.model_hub.agents["claude"].routes["claude-opus-4-6"].hops
+ assert [(hop.source_id, hop.model_id) for hop in hops] == [(SOURCE_ID, f"{ADDRESS}/gpt-5.5")]
+
+
+def test_a_file_carrying_no_address_is_not_rewritten(tmp_path) -> None:
+ """The repair is a repair: a file with nothing to fix is left byte for byte."""
+
+ config_path = tmp_path / "config.json"
+ config_path.write_text(
+ json.dumps(
+ _config_payload(
+ [_model_payload("gpt-5.5"), _model_payload("x-ai/grok-4.6-latest")],
+ [{"source_id": SOURCE_ID, "model_id": "x-ai/grok-4.6-latest"}],
+ ),
+ ensure_ascii=False,
+ ),
+ encoding="utf-8",
+ )
+ original = config_path.read_bytes()
+
+ loaded = V2Config.load(config_path=config_path)
+
+ assert config_path.read_bytes() == original
+ assert [model.id for model in loaded.model_hub.sources[0].models] == [
+ "gpt-5.5",
+ "x-ai/grok-4.6-latest",
+ ]
+
+
+def test_a_repaired_config_serializes_to_one_this_product_loads_again(tmp_path) -> None:
+ """The terminal property: repairing may not produce a file that will not load.
+
+ Collapsing two spellings into one identity is where that could break — write
+ the surviving name twice and the next load refuses the file it just wrote.
+ """
+
+ loaded = _load(
+ tmp_path,
+ _config_payload(
+ [_model_payload(f"{ADDRESS}/gpt-5.5"), _model_payload("gpt-5.5")],
+ [
+ {"source_id": SOURCE_ID, "model_id": f"{ADDRESS}/gpt-5.5"},
+ {"source_id": SOURCE_ID, "model_id": "gpt-5.5"},
+ ],
+ ),
+ )
+ rewritten = tmp_path / "rewritten.json"
+ rewritten.write_text(
+ json.dumps(
+ api.config_to_payload(loaded, include_secrets=True, include_internal=True),
+ ensure_ascii=False,
+ ),
+ encoding="utf-8",
+ )
+
+ reloaded = V2Config.load(config_path=rewritten)
+
+ assert reloaded.load_warnings == ()
+ assert reloaded.model_hub.to_payload() == loaded.model_hub.to_payload()
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index cc69a8d99..3588404c4 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -2100,7 +2100,11 @@ class CLIProxyEngineAdapter:
"/auth-files/models",
query={"name": str(metadata["auth_name"])},
)
- return _discovered_models(payload)
+ prefix = metadata.get("prefix")
+ return _discovered_models(
+ payload,
+ str(prefix) if isinstance(prefix, str) and prefix else None,
+ )
normalized_base_url = await asyncio.to_thread(
self.state_store.validate_api_key_target,
credential_ref,
@@ -2904,7 +2908,10 @@ def _auth_inventory(client: EngineClient) -> dict[str, _AuthRecord]:
return inventory
-def _discovered_models(payload: Mapping[str, Any]) -> tuple[DiscoveredModel, ...]:
+def _discovered_models(
+ payload: Mapping[str, Any],
+ prefix: str | None = None,
+) -> tuple[DiscoveredModel, ...]:
models = payload.get("models")
if not isinstance(models, list):
return ()
@@ -2914,11 +2921,12 @@ def _discovered_models(payload: Mapping[str, Any]) -> tuple[DiscoveredModel, ...
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:
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)
+ # This is the one place an address enters the product: the engine answers
+ # with the name it addresses this credential by. It is removed here, at
+ # that boundary, rather than by every later reader of the inventory — and
+ # only the address of the credential being discovered, so a model whose
+ # own name is spelled like one is left as upstream named it.
+ value = model_id_without_credential_address(value, prefix)
if not value or value in seen:
continue
seen.add(value)
diff --git a/vibe/model_hub_runtime/state.py b/vibe/model_hub_runtime/state.py
index ab1477820..b9b4296e8 100644
--- a/vibe/model_hub_runtime/state.py
+++ b/vibe/model_hub_runtime/state.py
@@ -50,6 +50,10 @@ def _without_credential_addresses(payload: dict[str, Any]) -> dict[str, Any]:
one-shot script keeps one spelling in memory no matter which release wrote
the file, and the next ordinary write persists it.
+ A record names the prefix it is addressed by, so only that exact address is
+ removed. Nothing is claimed about any other name: a model whose own identity
+ happens to be spelled like an address belongs to whoever named 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
@@ -58,12 +62,17 @@ def _without_credential_addresses(payload: dict[str, Any]) -> dict[str, Any]:
so the parse still reports it.
"""
+ prefix = payload.get("prefix")
+ if not isinstance(prefix, str) or not prefix:
+ return payload
+
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
+ model_id_without_credential_address(str(model), prefix)
+ for model in model_ids
)
)
route_model_ids = payload.get("route_model_ids")
@@ -72,7 +81,8 @@ def _without_credential_addresses(payload: dict[str, Any]) -> dict[str, Any]:
):
healed["route_model_ids"] = list(
dict.fromkeys(
- model_id_without_credential_address(model) for model in route_model_ids
+ model_id_without_credential_address(model, prefix)
+ for model in route_model_ids
)
)
reasoning_efforts = payload.get("model_reasoning_efforts")
@@ -83,7 +93,7 @@ def _without_credential_addresses(payload: dict[str, Any]) -> dict[str, Any]:
healed_efforts: dict[str, Any] = {}
for model_id, efforts in reasoning_efforts:
healed_efforts.setdefault(
- model_id_without_credential_address(model_id), efforts
+ model_id_without_credential_address(model_id, prefix), efforts
)
healed["model_reasoning_efforts"] = [
[model_id, efforts] for model_id, efforts in healed_efforts.items()
@@ -584,9 +594,19 @@ 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)
+ # Settle the address this Source is reached by before reading any
+ # model name, so a name carrying it is unwrapped against the one
+ # prefix that owns it rather than against the shape of a prefix.
+ prefix = (
+ str(credential["prefix"])
+ if credential.get("prefix")
+ else previous.prefix
+ if previous
+ else f"avibe-{secrets.token_hex(12)}"
+ )
model_ids = tuple(
dict.fromkeys(
- model_id_without_credential_address(str(model).strip())
+ model_id_without_credential_address(str(model).strip(), prefix)
for model in binding.model_ids
)
)
@@ -597,7 +617,9 @@ 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 = model_id_without_credential_address(str(model_id).strip())
+ normalized_model_id = model_id_without_credential_address(
+ str(model_id).strip(), prefix
+ )
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:
@@ -620,18 +642,12 @@ class EngineStateStore:
route_model_ids=tuple(
sorted(
{
- model_id_without_credential_address(model)
+ model_id_without_credential_address(model, prefix)
for model in route_model_ids
}
)
),
- prefix=(
- str(credential["prefix"])
- if credential.get("prefix")
- else previous.prefix
- if previous
- else f"avibe-{secrets.token_hex(12)}"
- ),
+ prefix=prefix,
model_reasoning_efforts=tuple(reasoning_by_model.items()),
)
)
@@ -651,7 +667,9 @@ class EngineStateStore:
raise EngineStateError("source is not registered")
models = tuple(
dict.fromkeys(
- model_id_without_credential_address(str(model).strip())
+ model_id_without_credential_address(
+ str(model).strip(), current.prefix
+ )
for model in model_ids
)
)