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): keep a turn's native content on the Source identity it was first served under (#2616)

Call White341745c5d7a2
diff --git a/core/handlers/model_hub/hosted_admission.py b/core/handlers/model_hub/hosted_admission.py
index efc75e417..34c94dd39 100644
--- a/core/handlers/model_hub/hosted_admission.py
+++ b/core/handlers/model_hub/hosted_admission.py
@@ -12,7 +12,9 @@ way it cannot be served there before output becomes ``pin_unavailable``, after
which Vibey re-renders it in portable form. A pinned request's in-flight
response (a ``pause_turn`` continuation, or client tool results after server
tools in the same response) is the provider's own continuation contract, so
-its hosted items need no replay evidence.
+its hosted items need no replay evidence, only the identity that response was
+served under: a turn's native content on a Source never crosses an identity
+change (the turn's pin identity claim, made atomically at final admission).
"""
from __future__ import annotations
@@ -59,14 +61,16 @@ class HostedContent:
"""What a request's hosted content needs from a hop.
``calls`` holds each declared (catalog tool, declaration ``type``);
- ``replays`` the catalog tools whose native items it replays.
+ ``replays`` the catalog tools whose native items it replays; ``in_flight``
+ those whose native items it carries in the in-flight response.
"""
calls: frozenset[tuple[str, str]] = frozenset()
replays: frozenset[str] = frozenset()
+ in_flight: frozenset[str] = frozenset()
def __bool__(self) -> bool:
- return bool(self.calls or self.replays)
+ return bool(self.calls or self.replays or self.in_flight)
@lru_cache(maxsize=1)
@@ -97,12 +101,12 @@ def hosted_content(request: Mapping[str, Any], protocol: str, *, pinned: bool) -
if isinstance(tool, Mapping) and isinstance(tool.get("type"), str) and tool["type"] in declared
)
if protocol == "openai_responses":
- replays = _responses_replays(request.get("input"), pinned=pinned)
+ replays, in_flight = _responses_replays(request.get("input"), pinned=pinned)
elif protocol == "anthropic":
- replays = _anthropic_replays(request.get("messages"), pinned=pinned)
+ replays, in_flight = _anthropic_replays(request.get("messages"), pinned=pinned)
else:
- replays = frozenset()
- return HostedContent(calls, replays)
+ replays, in_flight = frozenset(), frozenset()
+ return HostedContent(calls, replays, in_flight)
def _text(item: Any, key: str) -> str | None:
@@ -131,9 +135,11 @@ def _responses_output_item(item: Any) -> bool:
return kind in _RESPONSES_MODEL_OUTPUTS
-def _responses_replays(items: Any, *, pinned: bool) -> frozenset[str]:
+def _responses_replays(items: Any, *, pinned: bool) -> tuple[frozenset[str], frozenset[str]]:
+ """The tools of hosted items to replay, and of those in the in-flight response."""
+
if not isinstance(items, list):
- return frozenset()
+ return frozenset(), frozenset()
end = len(items)
if pinned:
# The in-flight response is the trailing run of output items, followed
@@ -145,10 +151,11 @@ def _responses_replays(items: Any, *, pinned: bool) -> frozenset[str]:
tools = {tool for item in items[:end] if (tool := _responses_hosted_tool(item)) is not None}
# An image call is never replayed verbatim, in flight or not: Vibey has
# replaced its result with the path record, so no hop may receive it.
- tools.update(
- "image_generation" for item in items[end:] if _responses_hosted_tool(item) == "image_generation"
- )
- return frozenset(tools)
+ in_flight = {tool for item in items[end:] if (tool := _responses_hosted_tool(item)) is not None}
+ if "image_generation" in in_flight:
+ in_flight.discard("image_generation")
+ tools.add("image_generation")
+ return frozenset(tools), frozenset(in_flight)
def _anthropic_hosted_tool(block: Any) -> str | None:
@@ -171,9 +178,11 @@ def _only_tool_results(message: Any) -> bool:
)
-def _anthropic_replays(messages: Any, *, pinned: bool) -> frozenset[str]:
+def _anthropic_replays(messages: Any, *, pinned: bool) -> tuple[frozenset[str], frozenset[str]]:
+ """The tools of hosted blocks to replay, and of those in the in-flight response."""
+
if not isinstance(messages, list):
- return frozenset()
+ return frozenset(), frozenset()
in_flight: int | None = None
if pinned:
# The in-flight response is the last assistant message, when only the
@@ -184,14 +193,15 @@ def _anthropic_replays(messages: Any, *, pinned: bool) -> frozenset[str]:
if index and isinstance(messages[index - 1], Mapping) and messages[index - 1].get("role") == "assistant":
in_flight = index - 1
tools: set[str] = set()
+ carried: set[str] = set()
for index, message in enumerate(messages):
- if index == in_flight or not isinstance(message, Mapping) or message.get("role") != "assistant":
+ if not isinstance(message, Mapping) or message.get("role") != "assistant":
continue
content = message.get("content")
for block in content if isinstance(content, list) else ():
if (tool := _anthropic_hosted_tool(block)) is not None:
- tools.add(tool)
- return frozenset(tools)
+ (carried if index == in_flight else tools).add(tool)
+ return frozenset(tools), frozenset(carried)
def admits(
diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.py
index 50383f884..66d66aa25 100644
--- a/core/handlers/model_hub/provenance.py
+++ b/core/handlers/model_hub/provenance.py
@@ -725,6 +725,9 @@ class TurnTrace:
# Vibey: the hosted-tool executors the turn's first resolution bound, with
# each executor Source's identity. Written once; settings apply next turn.
hosted_executors: Optional[tuple[tuple[str, tuple[str, str, str] | None], ...]] = None
+ # Vibey: per Source, the identity digest the turn's native content is bound
+ # to, claimed by its first admitted pinned request. Each entry is written once.
+ pinned_identities: dict[str, str] = field(default_factory=dict)
@property
def pending_attempt(self) -> Optional[AttemptIdentity]:
@@ -1335,6 +1338,29 @@ class TurnCorrelationRegistry:
)
return token
+ def claim_pinned_identity(
+ self, turn_id: Optional[str], source_id: str, identity: str, continuation: bool,
+ ) -> bool:
+ """Whether a turn's native content may go to this Source under ``identity``; binds the first claim.
+
+ The turn's first claim for a Source binds its identity, and later ones
+ must match it. A continuation carries the native items of a response
+ already served, so it needs an identity already bound. A request without
+ a live turn has none to bind to.
+ """
+
+ with self._lock:
+ trace = self._traces.get(str(turn_id or "").strip())
+ if trace is None:
+ return False
+ bound = trace.pinned_identities.get(source_id)
+ if bound is None:
+ if continuation:
+ return False
+ trace.pinned_identities[source_id] = identity
+ return True
+ return bound == identity
+
def turn_hosted_executors(
self, turn_id: Optional[str],
) -> tuple[tuple[str, tuple[str, str, str] | None], ...] | None:
diff --git a/core/handlers/model_hub/request.py b/core/handlers/model_hub/request.py
index 73b88c30a..1898c1f29 100644
--- a/core/handlers/model_hub/request.py
+++ b/core/handlers/model_hub/request.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from typing import TYPE_CHECKING, Any, Final, Mapping
+from typing import TYPE_CHECKING, Any, Callable, Final, Mapping
if TYPE_CHECKING:
from .provenance import HopOrigin
@@ -34,6 +34,7 @@ class ModelHubRequest(dict[str, Any]):
headers: Mapping[str, str] | None = None,
primary_origin: HopOrigin | None = None,
pinned_hop: tuple[str, str | None] | None = None,
+ pin_identity_claim: Callable[[str, bool], bool] | None = None,
) -> None:
super().__init__(payload)
self.protocol = protocol
@@ -45,6 +46,11 @@ class ModelHubRequest(dict[str, Any]):
# content may be served by: no failover, no recovery wait, no rewrite.
# A model of None matches no hop.
self.pinned_hop = pinned_hop
+ # Claims the pinned Source's identity digest for the request's turn at
+ # final admission: ``(identity, continuation)`` -> whether native
+ # content may go there under it. A turn's first claim binds the
+ # identity; a continuation needs one already bound.
+ self.pin_identity_claim = pin_identity_claim
_OPAQUE_FIELDS = frozenset({"signature", "thoughtSignature", "thought_signature", "encrypted_content"})
@@ -110,6 +116,7 @@ def without_opaque_history(request: Mapping[str, Any]) -> Mapping[str, Any]:
return ModelHubRequest(
payload, protocol=request.protocol, headers=request.headers,
primary_origin=request.primary_origin, pinned_hop=request.pinned_hop,
+ pin_identity_claim=request.pin_identity_claim,
)
return payload
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index b88d5094f..ac2d24b39 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -9607,6 +9607,12 @@ class ModelHubService:
# or a Source that changed while the engine was prepared counts.
if hosted and not self._admits_hosted(hosted, source, model_id):
raise _pin_unavailable()
+ # Native content stays on one identity of the Source per turn. The
+ # claim is made here, under the exclusion this call is admitted in,
+ # so no concurrent request or config change slips between them.
+ claim = getattr(request, "pin_identity_claim", None)
+ if hosted and (claim is None or not claim(identity_digest(source), bool(hosted.in_flight))):
+ raise _pin_unavailable()
if self._engine_synced:
if recovery_request is not None and recovery_request.expired:
raise _RecoveryWindowClosed
diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.py
index 3a81ec758..ad147f0de 100644
--- a/core/handlers/model_hub/turn_gateway.py
+++ b/core/handlers/model_hub/turn_gateway.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
+import functools
import json
import logging
import math
@@ -1133,6 +1134,12 @@ class ModelHubTurnGateway:
pinned_hop=(
terminalizer.pinned_hop(pin_source_id, pin_model_id) if pin_source_id else None
),
+ pin_identity_claim=(
+ functools.partial(
+ self.correlation.claim_pinned_identity, terminalizer.turn_id, pin_source_id,
+ )
+ if pin_source_id else None
+ ),
),
stream=stream,
supply_channel="hub",
diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.md
index ecfb8643f..8187a81e0 100644
--- a/docs/plans/agent-core-contracts/model-hub-consumer.md
+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md
@@ -86,6 +86,13 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
protocol, for any vendor; a function never is one;
- every replayed hosted item outside the in-flight response needs its tool to run on the hop, and `replay`
evidence. A generated image never has it.
+ - **One identity per turn and Source.** Native content goes to a Source only under one identity (credential,
+ base URL, protocol, vendor, kind, verification) per turn. The turn's first pinned request admitted to the
+ Source binds it, atomically with that request's final admission, and every later one must match it. After a
+ mid-turn change, such as a rotated key or an edited relay URL, every pinned request to that Source is
+ `pin_unavailable` for the rest of the turn, even with evidence taken anew, including one overlapping the
+ binding request. An in-flight response carrying hosted items needs an identity already bound, so it is
+ `pin_unavailable` when none is. A request without a live turn binds nothing and is `pin_unavailable`.
- A `type` or `name` that is not non-blank text is absent, so its item is no hosted item and ends the
in-flight run. A named call (`function_call`, `custom_tool_call`, `mcp_call`) without one cannot be
classified and ends it too.
diff --git a/tests/test_model_hub_hosted_pinning.py b/tests/test_model_hub_hosted_pinning.py
index 7f782e7f2..2aeb1e244 100644
--- a/tests/test_model_hub_hosted_pinning.py
+++ b/tests/test_model_hub_hosted_pinning.py
@@ -11,6 +11,7 @@ received which body.
from __future__ import annotations
+import asyncio
import copy
import threading
from dataclasses import replace
@@ -237,6 +238,94 @@ async def test_a_pin_names_the_exact_hop_it_was_rendered_for(tmp_path, case):
assert service.adapter.requests[2] == continuation
[email protected](("case", "statuses"), [
+ ("same_identity", [200, 200]),
+ ("credential_rotated_and_reverified", [200, 409]),
+ ("no_pinned_response_this_turn", [409]),
+])
+async def test_a_continuation_stays_on_the_identity_its_response_was_served_under(tmp_path, case, statuses):
+ """MH-HOSTED-GATEWAY-002: native content never crosses a Source's identity change within a turn.
+
+ The turn's first admitted pinned request binds the Source's identity, and
+ the in-flight response is exempt from replay evidence only on that bound
+ identity. Evidence taken anew at a rotated credential does not carry the
+ earlier response's payload across.
+ """
+
+ primary, fallback = _sources()
+ service = _vibey_service(tmp_path, [primary, fallback], handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)) for _ in statuses
+ ])
+ _verify(service, primary, "grok-4.6", "x_search", "call")
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ answers = []
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:identity", turn_id="turn-identity")
+ if case != "no_pinned_response_this_turn":
+ answers.append(await _post(hop, _native(hop), pin=primary.id))
+ if case == "credential_rotated_and_reverified":
+ live = service.store.config.sources[0]
+ live.credential_ref = "cred_rotated0001"
+ _verify(service, live, "grok-4.6", "x_search", "call")
+ # Client tool results after the model's X search: the in-flight response carries its native item.
+ continuation = {
+ "model": hop["runtime_model"], "stream": False,
+ "input": [{"role": "user", "content": "posts from OpenAI this week"}, X_CALL, LOCAL_CALL, LOCAL_OUTPUT],
+ "tools": [{"type": "x_search"}, SHELL],
+ }
+ answers.append(await _post(hop, continuation, pin=primary.id))
+ finally:
+ await gateway.close()
+ assert [status for status, _answer in answers] == statuses
+ if statuses[-1] == 409:
+ assert answers[-1][1] == PIN_UNAVAILABLE
+ assert len(service.adapter.invocations) == statuses.count(200)
+
+
+async def test_overlapping_first_pinned_requests_bind_one_identity(tmp_path):
+ """MH-HOSTED-GATEWAY-002: the identity is bound at final admission, so a concurrent first request cannot use another.
+
+ The first request is admitted and still opening its call when the key is
+ rotated and re-verified; the second, admitted on the new identity, is handed back.
+ """
+
+ primary, fallback = _sources()
+ service = _vibey_service(tmp_path, [primary, fallback], handles=[
+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), (b"{}",)) for _ in range(2)
+ ])
+ _verify(service, primary, "grok-4.6", "x_search", "call")
+ admitted, release = asyncio.Event(), asyncio.Event()
+ invoke = service.adapter.invoke
+
+ async def held_first(*args, **kwargs):
+ handle = await invoke(*args, **kwargs)
+ if not admitted.is_set():
+ admitted.set()
+ await release.wait()
+ return handle
+
+ service.adapter.invoke = held_first
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:overlap", turn_id="turn-overlap")
+ first = asyncio.create_task(_post(hop, _native(hop), pin=primary.id))
+ await asyncio.wait_for(admitted.wait(), timeout=5)
+ live = service.store.config.sources[0]
+ live.credential_ref = "cred_rotated0001"
+ _verify(service, live, "grok-4.6", "x_search", "call")
+ assert await _post(hop, _native(hop), pin=primary.id) == (409, PIN_UNAVAILABLE)
+ release.set()
+ assert (await asyncio.wait_for(first, timeout=5))[0] == 200
+ finally:
+ release.set()
+ await gateway.close()
+ assert len(service.adapter.invocations) == 1
+
+
@pytest.mark.asyncio
async def test_the_portable_resend_fails_over_and_the_turn_settles_on_it(tmp_path):
"""MH-HOSTED-GATEWAY-002: the handed-back request leaves only its failed attempt in the turn."""