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): route a turn's own mid-thread model change (#2098)
Call White05e520326b72
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 176a69cb7..b6f715d00 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -1472,8 +1472,6 @@ class TurnCorrelationRegistry:and trace is not Noneand not trace.ambiguousand request_id in trace.pending_attempts- and gateway_model_id- in {trace.gateway_request_model_id, trace.gateway_model_id}):# Admission may close after this request opened. Its# ownership remains valid through the bounded drain.@@ -1549,11 +1547,33 @@ class TurnCorrelationRegistry:if explicit is None:return None, False_key, _scope, route, _route_id = explicit- if gateway_model_id not in {- route.gateway_request_model_id,- route.resolved_model_id,- }:- return None, False+ # An explicit handle proves which process holds it and which turn+ # it was minted for. It deliberately does not fix the model. A+ # dispatched turn names another of Avibe's own models as a matter+ # of course, and Codex always does at a model change: it+ # re-serialises the thread under the OUTGOING model before the+ # first turn on the new one, so that hop arrives on the new turn's+ # handle carrying the old id. Refusing it here strands the thread+ # for good — the re-serialisation never lands, so every later turn+ # repeats it and fails the same way. Whether Avibe configured the+ # named model is resolution's question, not routing's: the caller+ # model below reaches `effective_model_route`, which serves only+ # ids already in this agent's menu and returns an empty route for+ # anything else. Answering it a second time here would duplicate+ # that authority and report an unconfigured model as an+ # incompatible request.+ if gateway_model_id == route.gateway_request_model_id:+ # The one id that proves a request is on its own route: what+ # Avibe told this launch to send. The route's upstream target+ # proves nothing, because menu ids and upstream ids are+ # separate namespaces that may be spelled the same — reading+ # that spelling as this route's would send the outgoing+ # model's re-serialisation down the new route, to another+ # source under another model. Where no distinct id was minted+ # the two coincide, and this one comparison covers both.+ caller_model_id = route.requested_model_id+ else:+ caller_model_id = gateway_model_ididentity = self._request_identity(request_metadata)assert identity is not None_route_id, turn_id = identity@@ -1564,11 +1584,11 @@ class TurnCorrelationRegistry:route=route,):return None, False- return route.requested_model_id, True+ return caller_model_id, True# Completed turn IDs are intentionally not retained. A valid# process-owned route handle can route a late continuation, but it# cannot claim a newer active turn.- return route.requested_model_id, False+ return caller_model_id, Falseroute = credential.routeif route is None:# No route was known when this credential was minted: the shareddiff --git a/tests/e2e/test_codex_request_metadata.py b/tests/e2e/test_codex_request_metadata.pyindex 83d809cba..527121cda 100644--- a/tests/e2e/test_codex_request_metadata.py+++ b/tests/e2e/test_codex_request_metadata.py@@ -11,14 +11,32 @@ from pathlib import Pathimport pytest-from config.v2_config import ModelHubBackendModelConfig+from config.v2_config import (+ ModelHubBackendModelConfig,+ ModelHubRouteConfig,+ ModelHubRouteHopConfig,+)+from core.handlers.model_hub.adapter import RawOutcomeKind+from core.handlers.model_hub.turn_gateway import ModelHubTurnGatewayfrom modules.agents.codex.transport import CodexTransport-from modules.agents.model_hub import ModelHubLaunch, build_codex_hub_launch+from modules.agents.model_hub import (+ ModelHubLaunch,+ ModelHubRuntimeRouter,+ build_codex_hub_launch,+)from tests.e2e.drivers import mock_llm_upstream as upstreamfrom tests.e2e.test_model_hub_catalog_consumer import (codex_catalog_runtime, # noqa: F401 -- fixture dependencyrejected_external_proxy, # noqa: F401 -- fixture dependency)+from tests.scenario_harness.model_hub import (+ MemoryModelHubStore,+ ModelHubScenarioAdapter,+ ScenarioCallResult,+ config_with_sources,+ service_for,+ source,+)from vibe.backend_model_catalog import _codex_hub_catalog_bytes@@ -361,3 +379,140 @@ def test_codex_transport_retry_keeps_metadata(metadata_runtime, monkeypatch, faifor request in requests:_assert_identity(request, identity)assert len({json.loads(request["headers"][METADATA_HEADER])["turn_id"] for request in requests}) == 1+++# A model change re-serialises the thread under the OUTGOING model, so that hop+# reaches the gateway on the NEW turn's handle naming the OLD model. Two real+# catalog slugs from different comp_hash groups are required to provoke it.+SWITCH_OLD, SWITCH_NEW = "gpt-5.5", "gpt-6-astra"+SWITCH_TARGET = "relay-upstream"+++def switch_runtime(codex_catalog_runtime):+ binary, runtime, raw_catalog = codex_catalog_runtime+ Path(runtime.env["CODEX_HOME"], "config.toml").write_text(+ 'cli_auth_credentials_store = "file"\n',+ )+ catalog_path = runtime.home / "switch-models.json"+ # Native rows carry the comp_hash this test depends on; reuse them by id.+ catalog_path.write_bytes(_codex_hub_catalog_bytes(+ raw_catalog,+ [ModelHubBackendModelConfig(id=model).to_payload()+ for model in (SWITCH_OLD, SWITCH_NEW)],+ ))+ return binary, runtime, catalog_path+++def test_codex_mid_thread_model_switch_routes_its_compaction(switch_runtime, tmp_path):+ """MH-PROTOCOL-004: the pre-turn re-serialisation is routed and attributed.++ Rejecting it stranded the thread permanently: the re-serialisation never+ landed, so the thread kept its old format and every later turn repeated it+ and failed the same way. Driven through the real gateway because the defect+ was in route admission, which the wire-only fixtures never reach.+ """+ binary, runtime, catalog_path = switch_runtime+ src = source("src_switch", [SWITCH_TARGET], vendor="custom", protocol="openai_responses")+ config = config_with_sources(+ [src], backend="codex", menu_model=SWITCH_OLD, hops=((src.id, SWITCH_TARGET),),+ )+ agent = config.agents["codex"]+ agent.sources.order = [src.id]+ agent.models = [+ ModelHubBackendModelConfig(+ id=model, origin="manual", native_protocol="openai_responses",+ )+ for model in (SWITCH_OLD, SWITCH_NEW)+ ]+ agent.routes[SWITCH_NEW] = ModelHubRouteConfig(+ hops=(ModelHubRouteHopConfig(src.id, SWITCH_TARGET),),+ )+ adapter = ModelHubScenarioAdapter(invoke_results=(+ ScenarioCallResult(+ RawOutcomeKind.SUCCESS, status=200,+ body=b"".join(upstream._responses_stream_frames(SWITCH_TARGET)),+ stream_started=True,+ )+ for _ in range(8)+ ))+ service = service_for(tmp_path, MemoryModelHubStore(config), adapter)+ hub_gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=hub_gateway)++ async def spawn(launch):+ args, env = build_codex_hub_launch(+ [], runtime.env, launch, model_catalog_path=catalog_path,+ )+ transport = CodexTransport(+ binary=binary, cwd=str(runtime.home), runtime_args=args, runtime_env=env,+ )+ queue = asyncio.Queue()++ async def notify(method, params):+ if method == "turn/completed":+ await queue.put(params)++ transport.on_notification(notify)+ await transport.start()+ return transport, queue++ async def exercise():+ outcomes = []+ launch = await router.resolve(+ "codex", SWITCH_OLD, process_scope=str(runtime.home), turn_id="turn-old",+ )+ transport, queue = await spawn(launch)+ try:+ started = await transport.send_request("thread/start", {+ "model": SWITCH_OLD, "cwd": str(runtime.home), "approvalPolicy": "never",+ })+ thread_id = started["thread"]["id"]+ await transport.send_request("turn/start", {+ "threadId": thread_id, "model": SWITCH_OLD,+ "input": [{"type": "text", "text": "第一轮,保留中文与 café。"}],+ "responsesapiClientMetadata": dict(launch.gateway_request_metadata),+ })+ outcomes.append(await _completed(queue))+ finally:+ await transport.stop()+ hub_gateway.correlation.settle("turn-old", settled_by="test")++ # The owner's shape: a new app-server resumes the thread, then the first+ # turn on the new model. comp_hash lives in the rollout, so the change is+ # detected here even though this process never ran the old model.+ switched = await router.resolve(+ "codex", SWITCH_NEW, process_scope=str(runtime.home), turn_id="turn-new",+ )+ transport, queue = await spawn(switched)+ try:+ await transport.send_request(+ "thread/resume", {"threadId": thread_id, "excludeTurns": True},+ )+ await transport.send_request("turn/start", {+ "threadId": thread_id, "model": SWITCH_NEW, "approvalPolicy": "never",+ "input": [{"type": "text", "text": "第二轮"}],+ "responsesapiClientMetadata": dict(switched.gateway_request_metadata),+ })+ outcomes.append(await _completed(queue))+ finally:+ await transport.stop()+ hub_gateway.correlation.settle("turn-new", settled_by="test")+ await hub_gateway.close()+ return outcomes++ asyncio.run(exercise())+ wire_models = [request.get("model") for request in adapter.requests]+ assert wire_models[0] == SWITCH_OLD, wire_models+ # The switch is only exercised if the new turn really re-serialised first.+ assert wire_models[1:].count(SWITCH_OLD) >= 1, wire_models+ assert wire_models[-1] == SWITCH_NEW, wire_models++ rows = json.loads((tmp_path / "model-hub-state" / "provenance.json").read_text())+ entries = rows if isinstance(rows, list) else rows.get("entries", [])+ by_turn = {row.get("turn_id"): row for row in entries}+ assert {"turn-old", "turn-new"} <= set(by_turn), entries+ # The re-serialisation rode the new turn's handle without renaming the turn+ # or stranding it: both requests settle under the model the user switched to.+ assert by_turn["turn-new"]["requested_model_id"] == SWITCH_NEW, by_turn+ assert by_turn["turn-new"]["outcome"] == "served", by_turndiff --git a/tests/test_codex_request_provenance.py b/tests/test_codex_request_provenance.pyindex 93be60923..9cd4d9109 100644--- a/tests/test_codex_request_provenance.py+++ b/tests/test_codex_request_provenance.py@@ -35,6 +35,7 @@ def _launch(requested_model_id: str,resolved_model_id: str = "shared-upstream",source_id: str = "source",+ gateway_request_model_id: str | None = None,) -> tuple[str, str, dict[str, str]]:token = registry.credentials("codex",@@ -49,6 +50,7 @@ def _launch(requested_model_id=requested_model_id,resolved_model_id=resolved_model_id,source_id=source_id,+ gateway_request_model_id=gateway_request_model_id,via_mapping=True,)metadata = registry.gateway_request_metadata(@@ -271,6 +273,18 @@ def test_late_request_on_same_route_never_claims_newer_turn(tmp_path):assert late.turn_id is Nonelate.mark_downstream_canceled()+ # Off its own route it routes by the model the request names, and claims a+ # turn no more and no less than on it: what a settled turn cannot do is own+ # a request, which has nothing to do with the model the request names.+ with registry.gateway_terminalizer(+ backend="codex",+ token=token,+ request_metadata=metadata_old,+ ) as stale_switch:+ assert stale_switch.resolution_model("other-alias") == "other-alias"+ assert stale_switch.turn_id is None+ stale_switch.mark_downstream_canceled()+with registry.gateway_terminalizer(backend="codex",token=token,@@ -300,7 +314,6 @@ def test_invalid_identity_and_live_route_mismatch_fail_closed_without_poisoning({"avibe_route_id": route_a},{"avibe_route_id": "foreign-route", "avibe_turn_id": "turn-a"},{"avibe_route_id": "路由-非ASCII", "avibe_turn_id": "turn-a"},- {"avibe_route_id": route_a, "avibe_turn_id": "turn-a"},]for request_metadata in cases:with registry.gateway_terminalizer(@@ -329,6 +342,151 @@ def test_invalid_identity_and_live_route_mismatch_fail_closed_without_poisoning(assert not registry._traces["turn-b"].ambiguous+def test_live_handle_routes_another_model_and_keeps_its_turn(tmp_path):+ """A verified handle authenticates a process and a turn, never a model.++ Codex re-serialises a thread under the OUTGOING model before the first turn+ on a new one, so that hop arrives on the new turn's handle naming the old+ model. Refusing it here stranded the thread for good. Whether Avibe+ configured the named model is resolution's question; routing only has to+ hand the request on and keep it attributed to the turn that made it.+ """++ registry = _registry(tmp_path)+ token, _route, metadata = _launch(+ registry,+ turn_id="turn-new",+ requested_model_id="alias-new",+ gateway_request_model_id="alias-new",+ )++ with registry.gateway_terminalizer(+ backend="codex",+ token=token,+ request_metadata=metadata,+ ) as compaction:+ assert compaction.resolution_model("alias-old") == "alias-old"+ assert compaction.turn_id == "turn-new"+ compaction.begin_attempt(+ source_id="source",+ resolved_model_id="shared-upstream",+ channel="hub",+ via_mapping=True,+ )+ compaction.finish_attempt(+ outcome=_success(),+ decision=classify_outcome(_success()),+ )++ with registry.gateway_terminalizer(+ backend="codex",+ token=token,+ request_metadata=metadata,+ ) as turn:+ assert turn.resolution_model("alias-new") == "alias-new"+ assert turn.turn_id == "turn-new"+ turn.begin_attempt(+ source_id="source",+ resolved_model_id="shared-upstream",+ channel="hub",+ via_mapping=True,+ )+ turn.finish_attempt(+ outcome=_success(),+ decision=classify_outcome(_success()),+ )++ trace = registry._traces["turn-new"]+ assert not trace.ambiguous+ assert "turn-new" not in registry._scopes[("codex", "codex-process")].ambiguous_turns+++def test_handle_routes_every_model_its_process_names_in_any_order(tmp_path):+ """A handle authorizes no model, so no order of them can starve one.++ Bounding what a live turn may name brings back the bug the bound was meant+ to contain. Counted, the first other model a process names spends the+ allowance and the outgoing model's re-serialisation is refused behind it;+ ordered, a turn that names its own model first refuses the hop that had to+ precede it. Both stranded the thread again from the other side. Whether a+ named model is configured at all is resolution's question, and it answers+ it from this agent's menu.+ """++ registry = _registry(tmp_path)+ token, _route, metadata = _launch(+ registry,+ turn_id="turn-many",+ requested_model_id="alias",+ gateway_request_model_id="alias",+ )++ def route(gateway_model_id: str) -> tuple[str | None, str | None]:+ with registry.gateway_terminalizer(+ backend="codex",+ token=token,+ request_metadata=metadata,+ ) as terminalizer:+ model = terminalizer.resolution_model(gateway_model_id)+ terminalizer.mark_downstream_canceled()+ return model, terminalizer.turn_id++ # Some other configured model first, then the outgoing one the thread is+ # re-serialised under, then the turn's own route.+ assert route("alias-other") == ("alias-other", "turn-many")+ assert route("alias-old") == ("alias-old", "turn-many")+ assert route("alias") == ("alias", "turn-many")+ # The route's upstream target is a name in another namespace, so it routes+ # as itself like any other id the handle did not mint.+ assert route("shared-upstream") == ("shared-upstream", "turn-many")+ # A turn's own request closes the handle to nothing: a retry of the+ # migration hop behind it is the same request on the same handle.+ assert route("alias-old") == ("alias-old", "turn-many")+ trace = registry._traces["turn-many"]+ assert not trace.ambiguous+ assert "turn-many" not in registry._scopes[("codex", "codex-process")].ambiguous_turns+++def test_outgoing_model_survives_an_upstream_name_collision(tmp_path):+ """Menu ids and upstream target ids are separate namespaces that collide.++ A route proves one spelling of itself: the id Avibe told the launch to+ send. An outgoing menu model spelled like the new route's upstream target+ is not that, and reading it as this route's would send the outgoing+ model's re-serialisation down the new route — another source, another+ model — which is the aliasing a per-route handle exists to prevent.+ """++ registry = _registry(tmp_path)+ token, _route, metadata = _launch(+ registry,+ turn_id="turn-new",+ requested_model_id="alias-new",+ # The new route relays through a source whose upstream model happens to+ # be spelled like the menu model the thread is migrating away from.+ resolved_model_id="gpt-5.5",+ gateway_request_model_id="alias-new",+ )++ with registry.gateway_terminalizer(+ backend="codex",+ token=token,+ request_metadata=metadata,+ ) as migration:+ assert migration.resolution_model("gpt-5.5") == "gpt-5.5"+ assert migration.turn_id == "turn-new"+ migration.mark_downstream_canceled()++ with registry.gateway_terminalizer(+ backend="codex",+ token=token,+ request_metadata=metadata,+ ) as turn:+ assert turn.resolution_model("alias-new") == "alias-new"+ assert turn.turn_id == "turn-new"+ turn.mark_downstream_canceled()++def test_retirement_revokes_explicit_auth_and_preserves_exact_closed_fact(tmp_path):registry = _registry(tmp_path)token, _route, metadata = _launch(