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): admit hosted content by runs_on, on the final invocation snapshot (#2608)

Call White4a00005f0f6d
diff --git a/core/handlers/model_hub/hosted_admission.py b/core/handlers/model_hub/hosted_admission.py
index 27d4c2d65..efc75e417 100644
--- a/core/handlers/model_hub/hosted_admission.py
+++ b/core/handlers/model_hub/hosted_admission.py
@@ -26,7 +26,7 @@ from config.v2_config import ModelHubSourceConfig
from vibe.backend_model_catalog import HostedToolSpec, bundled_provider_overlay
from .capability_evidence import HOSTED_TOOL_ASPECTS, CapabilityEvidenceStore, EvidenceFeature
-from .hosted_tools import credential_eligible, untranslated
+from .hosted_tools import runs_on
PIN_SOURCE_HEADER: Final = "x-avibe-pin-source"
# The served-hop model a continuation was rendered for; without it a pin is the launch's primary hop.
@@ -46,6 +46,8 @@ _RESPONSES_MODEL_OUTPUTS: Final = frozenset({
"file_search_call", "computer_call", "code_interpreter_call", "local_shell_call", "mcp_call",
"mcp_list_tools", "mcp_approval_request",
})
+# Output items identified by the tool they name; one without a textual name is malformed.
+_RESPONSES_NAMED_CALLS: Final = frozenset({"function_call", "custom_tool_call", "mcp_call"})
_ANTHROPIC_SERVER_RESULTS: Final = {"web_search_tool_result": "web_search"}
@@ -103,21 +105,29 @@ def hosted_content(request: Mapping[str, Any], protocol: str, *, pinned: bool) -
return HostedContent(calls, replays)
+def _text(item: Any, key: str) -> str | None:
+ """A request field read as text with content; anything else, blank text, or a non-object item is absent."""
+
+ value = item.get(key) if isinstance(item, Mapping) else None
+ return value if isinstance(value, str) and value.strip() else None
+
+
def _responses_hosted_tool(item: Any) -> str | None:
- if not isinstance(item, Mapping):
- return None
- kind = item.get("type")
- if kind == "custom_tool_call" and item.get("name") in _X_SEARCH_CALLS:
+ kind = _text(item, "type")
+ if kind == "custom_tool_call" and _text(item, "name") in _X_SEARCH_CALLS:
return "x_search"
- return _RESPONSES_HOSTED_ITEMS.get(kind) if isinstance(kind, str) else None
+ return _RESPONSES_HOSTED_ITEMS.get(kind) if kind is not None else None
def _responses_output_item(item: Any) -> bool:
if not isinstance(item, Mapping):
return False
- kind = item.get("type")
- if kind is None or kind == "message":
+ if item.get("type") in (None, "message"):
return item.get("role") == "assistant"
+ kind = _text(item, "type")
+ if kind in _RESPONSES_NAMED_CALLS and _text(item, "name") is None:
+ # A named call without a textual name cannot be classified, so it ends the run like any unknown item.
+ return False
return kind in _RESPONSES_MODEL_OUTPUTS
@@ -128,7 +138,7 @@ def _responses_replays(items: Any, *, pinned: bool) -> frozenset[str]:
if pinned:
# The in-flight response is the trailing run of output items, followed
# only by the client's tool outputs.
- while end and isinstance(items[end - 1], Mapping) and items[end - 1].get("type") in _RESPONSES_TOOL_OUTPUTS:
+ while end and _text(items[end - 1], "type") in _RESPONSES_TOOL_OUTPUTS:
end -= 1
while end and _responses_output_item(items[end - 1]):
end -= 1
@@ -142,13 +152,11 @@ def _responses_replays(items: Any, *, pinned: bool) -> frozenset[str]:
def _anthropic_hosted_tool(block: Any) -> str | None:
- if not isinstance(block, Mapping):
- return None
- kind = block.get("type")
+ kind = _text(block, "type")
if kind == "server_tool_use":
- name = block.get("name")
+ name = _text(block, "name")
return name if name in HOSTED_TOOL_ASPECTS else None
- return _ANTHROPIC_SERVER_RESULTS.get(kind) if isinstance(kind, str) else None
+ return _ANTHROPIC_SERVER_RESULTS.get(kind) if kind is not None else None
def _only_tool_results(message: Any) -> bool:
@@ -197,20 +205,18 @@ def admits(
shape: int,
now: datetime,
) -> bool:
- """Whether this hop offers every piece of hosted content and has current positive evidence for it.
+ """Whether this hop runs every piece of hosted content and has current positive evidence for it.
- The overlay must still offer the tool on this hop, with the declaration
- type the request carries, as native resolution requires. The first lookup
- may load the evidence file, so call this off the event loop.
+ Where a tool may run is ``runs_on``, the rule hop resolution uses for
+ native mode, so the two agree by construction; a declaration must also
+ carry the type the overlay declares there. Evidence is read from memory.
"""
if not content:
return True
- if not credential_eligible(source) or not untranslated(source):
- return False
def offered(tool: str) -> HostedToolSpec | None:
- return spec_for(source.vendor, source.protocol, model_id, tool)
+ return runs_on(source, model_id, tool, spec_for=spec_for)
def verified(tool: str, aspect: str) -> bool:
if aspect not in HOSTED_TOOL_ASPECTS.get(tool, ()):
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index a3db52d57..f7f5951d6 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -6103,7 +6103,7 @@ class ModelHubService:
return learned
def _admits_hosted(self, content: HostedContent, source: ModelHubSourceConfig, model_id: str) -> bool:
- """Whether this hop has current positive evidence for a request's hosted content; off the loop."""
+ """Whether this hop runs a request's hosted content with current positive evidence; memory only."""
return admits(
content,
@@ -9471,6 +9471,7 @@ class ModelHubService:
exact_retry: bool = False,
on_admitted: Callable[[int], None] | None = None,
recovery_request: RecoveryRequest | None = None,
+ hosted: HostedContent = HostedContent(),
) -> InvokeHandle:
while True:
await self._mutation_lock.acquire()
@@ -9533,6 +9534,10 @@ class ModelHubService:
# never rewritten; only an unpinned one is stripped here.
if pinned_hop is None and getattr(request, "primary_origin", None) != origin:
attempt_request = without_opaque_history(request)
+ # Hosted content is admitted on this final snapshot, so evidence
+ # 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()
if self._engine_synced:
if recovery_request is not None and recovery_request.expired:
raise _RecoveryWindowClosed
@@ -9573,6 +9578,7 @@ class ModelHubService:
exact_retry: bool = False,
on_admitted: Callable[[int], None] | None = None,
recovery_request: RecoveryRequest | None = None,
+ hosted: HostedContent = HostedContent(),
) -> tuple[InvokeHandle, Optional[RawCallOutcome], asyncio.CancelledError | None]:
acquired_handle: InvokeHandle | None = None
generation: int | None = None
@@ -9619,6 +9625,7 @@ class ModelHubService:
exact_retry=exact_retry,
on_admitted=admitted,
recovery_request=recovery_request,
+ hosted=hosted,
)
except InvokeCancelledError as cancelled:
await meter_observed(cancelled.observed, None)
@@ -9986,9 +9993,6 @@ class ModelHubService:
if pinned_hop is not None and getattr(request, "protocol", None) != source.protocol:
# Native content is never translated: the pinned hop must speak the request's protocol.
raise _pin_unavailable()
- if hosted and not await asyncio.to_thread(self._admits_hosted, hosted, source, target_model):
- # The pinned hop has no current positive evidence for this content.
- raise _pin_unavailable()
await self._prepare_engine_for_demand(already_synced=engine_prepared)
engine_prepared = True
handle, outcome, cancelled = await self._invoke(
@@ -10003,6 +10007,7 @@ class ModelHubService:
supply_channel=supply_channel,
on_admitted=admitted,
recovery_request=recovery_request,
+ hosted=hosted,
)
except _InvocationUnsupported as skipped:
if pinned_hop is not None:
@@ -10076,6 +10081,7 @@ class ModelHubService:
exact_retry=True,
on_admitted=admitted,
recovery_request=recovery_request,
+ hosted=hosted,
)
except _InvocationPlanChanged:
if attempt_observer is not None:
diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.md
index 7d3364af2..ecfb8643f 100644
--- a/docs/plans/agent-core-contracts/model-hub-consumer.md
+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md
@@ -74,13 +74,21 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
that model.
- A pin that is neither matches no hop.
- Nothing turn-wide is read, because a turn may have concurrent requests.
- - **Admission** reads the overlay and the evidence at the current engine and probe shape:
+ - **Admission** reads the overlay and the evidence at the current engine and probe shape, on the same snapshot the
+ call is then made on (after the engine is prepared, for every attempt):
- the pinned hop must be a runnable hop of the route;
- - every hosted declaration in `tools` needs the overlay to still offer that tool on the hop with that
- declaration `type`, and `call` evidence. A declaration is a tool whose `type` the overlay declares for a
- catalog tool on this protocol, for any vendor; a function never is one;
- - every replayed hosted item outside the in-flight response needs the overlay to still offer its tool on the
- hop, and `replay` evidence. A generated image never has it.
+ - "the tool runs on the hop" is the one rule hop resolution uses for native mode (`hosted_tools.runs_on`): a hub
+ Source with an eligible credential and an untranslated path that serves the model (an API-key Source any
+ model it does not list as retired; a subscription only its listed models), for which the overlay declares the
+ tool;
+ - every hosted declaration in `tools` needs the tool to run on the hop with that declaration `type`, and
+ `call` evidence. A declaration is a tool whose `type` the overlay declares for a catalog tool on this
+ 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.
+ - 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.
- The hosted items are Responses `web_search_call`, `image_generation_call`, and `custom_tool_call` named
`x_keyword_search`, `x_semantic_search`, `x_user_search` or `x_thread_fetch`; and Anthropic `server_tool_use`
named after a catalog tool, and `web_search_tool_result`.
diff --git a/tests/test_model_hub_hosted_pinning.py b/tests/test_model_hub_hosted_pinning.py
index 8dc03f351..7f782e7f2 100644
--- a/tests/test_model_hub_hosted_pinning.py
+++ b/tests/test_model_hub_hosted_pinning.py
@@ -22,14 +22,17 @@ import pytest
from config.v2_config import ModelHubModelConfig, ModelHubRouteConfig, ModelHubRouteHopConfig
from core.handlers.model_hub import service as service_module
from core.handlers.model_hub.adapter import RawOutcomeKind, UpstreamRejection
-from core.handlers.model_hub.capability_evidence import EvidenceFeature, EvidenceRecord, identity_digest
-from core.handlers.model_hub.hosted_admission import hosted_content
+from core.handlers.model_hub.capability_evidence import (
+ CapabilityEvidenceStore, EvidenceFeature, EvidenceRecord, identity_digest,
+)
+from core.handlers.model_hub.hosted_admission import admits, hosted_content
from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE, engine_stamp
from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
from core.run_settlement import SETTLED_BY_STOPPED, SETTLED_BY_TERMINAL_RESULT
from modules.agents.model_hub import ModelHubRuntimeRouter
from tests.test_model_hub_l3 import NOW, InvokeHandle, LiveInvokeHandle, _outcome, _source
from tests.test_model_hub_vibey_consumer import _validate, _vibey_service
+from vibe.backend_model_catalog import hosted_tool_spec
PIN = "x-avibe-pin-source"
PIN_MODEL = "x-avibe-pin-model"
@@ -88,6 +91,8 @@ def _native(hop, *, history=()):
("evidence_from_another_engine", 409, []),
("source_cooling_down", 409, []),
("source_not_on_route", 409, []),
+ # Admission reads the snapshot the call is made on, after the engine is prepared.
+ ("evidence_demoted_while_the_engine_is_prepared", 409, []),
])
async def test_a_pinned_request_is_served_only_by_its_source_or_handed_back(
tmp_path, monkeypatch, case, status, invoked,
@@ -116,6 +121,22 @@ async def test_a_pinned_request_is_served_only_by_its_source_or_handed_back(
elif case != "no_call_evidence":
engine = "model-hub-engine-previous" if case == "evidence_from_another_engine" else None
_verify(service, primary, primary_model, "x_search", "call", engine=engine)
+ if case == "evidence_demoted_while_the_engine_is_prepared":
+ prepare = service._prepare_engine_for_demand
+
+ async def demoting(*args, **kwargs):
+ await prepare(*args, **kwargs)
+ service.capability_evidence.write(
+ EvidenceRecord(
+ source_id=primary.id, model_id=primary_model, feature=EvidenceFeature.hosted("x_search", "call"),
+ status="unsupported", basis="observed", observed_at=service.now(), engine=engine_stamp(),
+ shape=HOSTED_PROBE_SHAPE, source_identity=identity_digest(primary),
+ detail="400 invalid_request_error",
+ ),
+ live=service.store.config.sources,
+ )
+
+ service._prepare_engine_for_demand = demoting
scanning_threads = []
scan = service_module.hosted_content
@@ -440,6 +461,22 @@ IN_FLIGHT_CASES = [
[USER, {"role": "assistant", "content": [SERVER_USE, SERVER_RESULT]}, "not a message"], True, {"web_search"}),
("anthropic_unpinned", "anthropic",
[USER, {"role": "assistant", "content": [SERVER_USE, SERVER_RESULT]}], False, {"web_search"}),
+ # A field that is not text is absent: an item with one is no hosted item and ends the in-flight run.
+ # A named call without a textual name is malformed, so it ends the in-flight run.
+ ("responses_custom_call_name_not_text", "openai_responses",
+ [USER, WEB_CALL, {**X_CALL, "name": {"x": 1}}, LOCAL_CALL, LOCAL_OUTPUT], True, {"web_search"}),
+ ("responses_custom_call_without_name", "openai_responses",
+ [USER, WEB_CALL, {key: value for key, value in X_CALL.items() if key != "name"}, LOCAL_CALL, LOCAL_OUTPUT],
+ True, {"web_search"}),
+ ("responses_custom_call_blank_name", "openai_responses",
+ [USER, WEB_CALL, {**X_CALL, "name": " "}, LOCAL_CALL, LOCAL_OUTPUT], True, {"web_search"}),
+ ("responses_function_call_without_name", "openai_responses",
+ [USER, WEB_CALL, {key: value for key, value in LOCAL_CALL.items() if key != "name"}, LOCAL_OUTPUT], True,
+ {"web_search"}),
+ ("responses_item_type_not_text", "openai_responses",
+ [USER, WEB_CALL, LOCAL_CALL, {"type": ["function_call_output"], "call_id": "fc_1"}], True, {"web_search"}),
+ ("anthropic_server_tool_name_not_text", "anthropic",
+ [USER, {"role": "assistant", "content": [{**SERVER_USE, "name": ["web_search"]}]}, USER], True, set()),
]
@@ -454,6 +491,38 @@ def test_only_items_outside_the_in_flight_response_need_replay_evidence(protocol
assert content.calls == frozenset()
[email protected](("case", "kind", "channel", "listed", "admitted"), [
+ ("api_key_listed", "api_key", "hub", "listed", True),
+ ("api_key_unlisted", "api_key", "hub", "unlisted", True),
+ ("api_key_retired_tombstone", "api_key", "hub", "retired", False),
+ ("subscription_unlisted", "subscription", "hub", "unlisted", False),
+ ("native_channel", "api_key", "native_cli", "listed", False),
+])
+def test_admission_runs_a_tool_only_where_hop_resolution_would(tmp_path, case, kind, channel, listed, admitted):
+ """MH-HOSTED-GATEWAY-002: admission uses ``runs_on``, so old evidence never admits a hop the tool cannot run on."""
+
+ model_id = "gpt-6-astra"
+ source = replace(_source("src_openai0001", "OpenAI", vendor="openai", model_id=model_id), kind=kind,
+ supply_channel=channel)
+ if listed != "listed":
+ source.models = [ModelHubModelConfig(id=model_id if listed == "retired" else "gpt-6-other",
+ provenance="discovered", retired=listed == "retired" or None)]
+ evidence = CapabilityEvidenceStore(tmp_path / "evidence.json")
+ evidence.write(
+ EvidenceRecord(
+ source_id=source.id, model_id=model_id, feature=EvidenceFeature.hosted("web_search", "call"),
+ status="verified", basis="probe", observed_at=NOW, engine=engine_stamp(), shape=HOSTED_PROBE_SHAPE,
+ source_identity=identity_digest(source),
+ ),
+ live=[source],
+ )
+ content = hosted_content({"tools": [{"type": "web_search"}]}, "openai_responses", pinned=True)
+ assert admits(
+ content, source=source, model_id=model_id, spec_for=hosted_tool_spec, evidence=evidence,
+ engine=engine_stamp(), shape=HOSTED_PROBE_SHAPE, now=NOW,
+ ) is admitted
+
+
def test_declarations_are_recognized_by_every_vendors_type():
"""MH-HOSTED-GATEWAY-003: a declaration counts whichever vendor offers it, never a function."""