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
feat(model-hub): hosted tools v2 B1+C1 - passive signal, refusal reason, executor chain, and Vibey re-render (#2644)
Call Whitebf1bda2b0381
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.pyindex b7a0ab90f..309eb56f0 100644--- a/core/agent_core/agent/loop.py+++ b/core/agent_core/agent/loop.py@@ -17,7 +17,7 @@ import timefrom collections import dequefrom contextlib import asynccontextmanager, suppressfrom copy import deepcopy-from dataclasses import asdict, dataclass, replace+from dataclasses import asdict, dataclass, field, replacefrom typing import Any, AsyncIterator, Awaitable, Callable, Iterable, Literal, Mapping, Optional, Sequence, TypeVarfrom core.agent_core.agent.events import (@@ -67,12 +67,13 @@ from core.agent_core.agent.lifecycle import RunAborted as _Aborted, RunScopefrom core.agent_core.agent.models import ModelRouter, ModelSelection, RetryPolicyfrom core.agent_core.agent.outcome import OutcomeOwnerfrom core.agent_core.agent.state import HookStateError, state_representation-from core.agent_core.ai._common import endpoint_origin, native_hosted_tools+from core.agent_core.ai._common import endpoint_origin, native_hosted_tools, portable_endpointfrom core.agent_core.ai.provider import (Done,ModelEndpoint,ModelRequest,ProviderError,+ Refusal,TextDelta,ThinkingDelta,)@@ -187,6 +188,60 @@ async def _silent(*_: Any, **__: Any) -> None:"""A side turn's emit: it shows nothing (C-10 section 7)."""+#: The fresh hops a run resolves to answer refusals before any output (``vibey-hosted-tools.md`` §3.5).+MAX_REFUSAL_RESOLVES = 2+++@dataclass+class _Refusals:+ """A run's refusals before any output, and how the requests after them render (``vibey-hosted-tools.md`` §3.5).++ A refusal is answered by a fresh hop, rendered normally: at most once per (Source, tool, aspect) a narrow hosted+ rule names, and at most ``MAX_REFUSAL_RESOLVES`` times in the run. Past a bound, or when a gateway hand-back's+ fresh hop is the refused one again, the request goes portable instead. A Source identity whose provider refused+ an opaque payload sends none for the rest of the run; that refusal is answered once per identity.+ """++ resolves: int = 0+ rules: set[tuple[Optional[str], str, Optional[str]]] = field(default_factory=set)+ identities: set[Optional[str]] = field(default_factory=set)++ def answer(self, refusal: Refusal) -> Optional[Literal["resolve", "portable"]]:+ """How the next attempt answers ``refusal``, counted; None when the refusal stands as the error."""+ if refusal.kind == "opaque_refused":+ if refusal.source_identity in self.identities:+ return None+ self.identities.add(refusal.source_identity)+ rule = (refusal.source_id, refusal.tool, refusal.aspect) if refusal.tool is not None else None+ if self.resolves >= MAX_REFUSAL_RESOLVES or rule in self.rules:+ return "portable"+ self.resolves += 1+ if rule is not None:+ self.rules.add(rule)+ return "resolve"++ def render(self, selection: ModelSelection, *, portable: bool) -> ModelSelection:+ """``selection`` as the next request goes out: without the refused identities' opaque payloads, and portable+ when the refusal it answers asked for that."""+ endpoint = selection.endpoint+ if self.identities:+ endpoint = replace(endpoint, opaque_refused=frozenset(self.identities))+ if portable:+ endpoint = portable_endpoint(endpoint)+ return selection if endpoint is selection.endpoint else replace(selection, endpoint=endpoint)+++def _same_hop(fresh: ModelEndpoint, refused: ModelEndpoint) -> bool:+ """A fresh hop that would send the refused request again: the same Source, account and model, with the same+ hosted-tool facts (§3.5)."""+ return (fresh.source_id, fresh.source_identity, fresh.model_id, fresh.hosted_tools) == (+ refused.source_id,+ refused.source_identity,+ refused.model_id,+ refused.hosted_tools,+ )++@dataclassclass _Ladder:"""One model request's progress through C-9 sections 3 and 8."""@@ -290,6 +345,7 @@ class Agent:self._turn_inputs: set[int] = set()# The run's attempt ledger (C-9): every model attempt, in order.self._attempts: list[_Attempt] = []+ self._refusals = _Refusals()# When each upstream prompt cache was last used in this Agent: the end of its latest model call, by the provider# and model that served it (``_cache_of``, C-9 section 3).self._last_model_at: dict[tuple[str, str], float] = {}@@ -503,6 +559,7 @@ class Agent:self._unproductive = 0self._turn_inputs = set()self._attempts = []+ self._refusals = _Refusals()loaded = Truesystem = self.systemself._run_tools = dict(self._tools)@@ -712,6 +769,10 @@ class Agent:# A response that dropped after thinking alone is retried once per request (C-2 ``provider.md``): some# prompts drop at the same point every time.thinking_retried = False+ # A refusal before any output is answered by rendering the request again (§3.5, ``_Refusals``): the hop a+ # gateway hand-back refused, and whether the next request goes portable.+ refused: Optional[ModelEndpoint] = None+ portable = Falsewhile True:self._scope.check()if retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:@@ -719,6 +780,7 @@ class Agent:returnif selected is None:selected = await self._scope.call(self.models.resolve)+ portable = portable or (refused is not None and _same_hop(selected.endpoint, refused))# Resolution is the last async stage before request admission.# Expiry wins before route validation, projection, rehydration or# hooks can replace the original error or persist new side effects.@@ -726,8 +788,8 @@ class Agent:yield retry_error, {}returnroute = selected- request, tools = await compose(selected)- selected = None+ request, tools = await compose(self._refusals.render(selected, portable=portable))+ selected, refused, portable = None, None, Falseif retry_error is not None and time.monotonic() - started >= self.retry.max_elapsed_s:yield retry_error, toolsreturn@@ -773,16 +835,24 @@ class Agent:and not streamedand (terminal.partial is None or not terminal.partial.content))+ rerender = (+ self._refusals.answer(terminal.refusal)+ if isinstance(terminal, ProviderError)+ and terminal.refusal is not None+ and not streamed+ and (terminal.partial is None or not terminal.partial.content)+ else None+ )delay = (self.retry.delay(terminal, retries=retries, streamed=streamed, elapsed_s=time.monotonic() - started)- if isinstance(terminal, ProviderError) and not relieve+ if isinstance(terminal, ProviderError) and not relieve and rerender is Noneelse None)if delay is not None and terminal.after_thinking:if thinking_retried:delay = Nonethinking_retried = True- if delay is None and not relieve:+ if delay is None and not relieve and rerender is None:# Admitted here; the caller commits it inside the scope,# BEFORE aclose. Never retry an accepted terminal.admitted = terminal.message if isinstance(terminal, Done) else terminal.partial@@ -799,6 +869,13 @@ class Agent:# ladder step (section 8).await self._settle_attempts(first)terminal = replace(terminal, partial=None)+ if rerender == "portable":+ selected, portable = route, True+ continue+ if rerender == "resolve":+ if terminal.refusal.kind == "pin_unavailable":+ refused = route.endpoint+ continueif relieve:ladder.overflows += 1ladder.refused = Truediff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.pyindex a34703c6a..37635a6b3 100644--- a/core/agent_core/ai/_common.py+++ b/core/agent_core/ai/_common.py@@ -53,6 +53,7 @@ from core.agent_core.ai.provider import (ModelEndpoint,ModelRequest,ProviderError,+ Refusal,TextDelta,ThinkingDelta,ToolCallDelta,@@ -1616,8 +1617,8 @@ PIN_MODEL_HEADER = "x-avibe-pin-model"class HandOff:- """A send that ends without a terminal, because the adapter sends again (§3.5, §4.3). ``drive_sse_stream`` yields- it in place of a terminal and commits nothing."""+ """A send that ends without a terminal, because the adapter decides what follows (§3.5, §4.3).+ ``drive_sse_stream`` yields it in place of a terminal and commits nothing."""def __init__(self, reason: str) -> None:self.reason = reason@@ -1626,36 +1627,66 @@ class HandOff:return f"HandOff({self.reason!r})"-#: The gateway's answer to a pinned request it cannot serve from the pinned Source (§3.5): HTTP 409-#: ``pin_unavailable``, before anything reached a model.-PIN_UNAVAILABLE = HandOff("pin_unavailable")+class PinUnavailable(HandOff):+ """The gateway's answer to a pinned request it cannot serve from the pinned Source (§3.5): HTTP 409+ ``pin_unavailable``, before anything reached a model. ``tool`` and ``aspect`` name the narrow hosted rule that+ fired, when one did (``error.reason``)."""++ def __init__(self, tool: str | None = None, aspect: str | None = None) -> None:+ super().__init__("pin_unavailable")+ self.tool = tool+ self.aspect = aspect++#: A response the provider paused (Anthropic ``pause_turn``, §4.3): the adapter continues it as the same response.PAUSE_TURN = HandOff("pause_turn")#: An HTTP error the adapter answers by sending again (``drive_sse_stream``'s ``refused``).REFUSED = HandOff("refused")-def _pin_unavailable(body: str) -> bool:+def _pin_unavailable(body: str) -> PinUnavailable | None:+ """The gateway's ``pin_unavailable`` answer, matched on ``type`` and ``code`` alone, with its narrow-rule reason+ when it carries one; None for any other body."""try:value = json.loads(body)except (TypeError, ValueError):- return False+ return Noneerror = value.get("error") if isinstance(value, Mapping) else None- return (+ if not (isinstance(error, Mapping)and error.get("type") == "model_hub_pin_unavailable"and error.get("code") == "pin_unavailable"+ ):+ return None+ reason = error.get("reason")+ if isinstance(reason, Mapping) and reason.get("kind") == "hosted_unsupported":+ tool, aspect = reason.get("tool"), reason.get("aspect")+ return PinUnavailable(tool if isinstance(tool, str) else None, aspect if isinstance(aspect, str) else None)+ return PinUnavailable()+++#: xAI's plain-text refusal of a replayed ciphertext it cannot read (§3.2); it does not say which one.+_DECRYPT_REFUSAL = re.compile(r"could not decrypt the provided encrypted_content", re.IGNORECASE)+++def pin_refusal(assembler: StreamAssembler, endpoint: ModelEndpoint, handed_back: PinUnavailable) -> ProviderError:+ """The terminal of a pinned request the gateway handed back, which the loop answers by rendering the request again+ (§3.5). Nothing reached a model, so nothing is lost."""++ error = assembler.error("the gateway handed the pinned request back (pin_unavailable)", kind="server", status=409)+ refusal = Refusal(+ "pin_unavailable", endpoint.source_id, endpoint.source_identity, handed_back.tool, handed_back.aspect)+ return replace(error, retryable=False, refusal=refusal)-def portable_request(request: ModelRequest) -> ModelRequest:- """The same request in portable form (§3.5): never pinned, and every hosted tool as its function, so it carries no- native declaration and replays no native payload. The hop's Source and identity stay for attribution: a response+def portable_endpoint(endpoint: ModelEndpoint) -> ModelEndpoint:+ """``endpoint`` in portable form (§3.5): never pinned, and every hosted tool as its function, so a request carries+ no native declaration and replays no native payload. The hop's Source and identity stay for attribution: a responsethat Source serves is still its own, and its opaque payloads are bound to that identity."""- endpoint = request.endpoint- routes = {name: HostedToolRoute("proxy", route.executor, False) for name, route in endpoint.hosted_tools.items()}- return replace(request, endpoint=replace(endpoint, portable=True, hosted_tools=routes))+ routes = {name: HostedToolRoute("proxy", False) for name in endpoint.hosted_tools}+ return replace(endpoint, portable=True, hosted_tools=routes)@dataclass(frozen=True)@@ -1719,42 +1750,13 @@ def _header_value(value: str) -> bool:return bool(value) and value == value.strip() and all(" " <= char <= "~" for char in value)-def forced_tool(request: ModelRequest) -> tuple[str, HostedToolRoute | None] | None:- """``request.tool_choice`` with its native hosted route (None when it is sent as a function); None when nothing- is forced. The forced tool must be one the request declares."""-- name = request.tool_choice- if name is None:- return None- if not any(tool.name == name for tool in request.tools):- raise ValueError(f"tool_choice names {name!r}, which the request does not declare")- return name, native_hosted_tools(request).get(name)---def required_only_tool(tools: list[Any]) -> str:- """OpenAI's forced choice of a hosted tool: ``required`` over a request that declares only that tool.-- The Responses and Chat named choices name a function, and their hosted-tool choice types have no- ``web_search`` or ``x_search``, so ``required`` is the one form that forces any hosted tool.- """-- if len(tools) != 1:- raise ValueError("forcing a hosted tool on this protocol needs it to be the request's only tool")- return "required"--async def iter_sse_events(response: httpx.Response,cancel: CancelToken,- *,- max_line_size: int | None = None,) -> AsyncIterator[SSEEvent]:- """Yield SSE events while allowing a CancelToken to interrupt a stalled read. ``max_line_size`` overrides the- parser's default line cap; a stream allowed lines that long (a generated image's) is parsed off the controller- loop, because one event can be many MiB."""+ """Yield SSE events while allowing a CancelToken to interrupt a stalled read."""- parser = SSEParser(max_line_size=max_line_size)- offload = max_line_size is not None+ parser = SSEParser()iterator = response.aiter_bytes().__aiter__()while True:if cancel.cancelled:@@ -1769,9 +1771,9 @@ async def iter_sse_events(breakif chunk is None:return- for event in await asyncio.to_thread(parser.feed, chunk) if offload else parser.feed(chunk):+ for event in parser.feed(chunk):yield event- for event in await asyncio.to_thread(parser.finish) if offload else parser.finish():+ for event in parser.finish():yield event@@ -1788,7 +1790,6 @@ async def drive_sse_stream(resolver: ServedHopResolver | None,gateway: bool,translate: WireTranslator,- max_line_size: int | None = None,refused: Callable[[ProviderError], bool] | None = None,) -> AsyncIterator[Any]:"""Own the complete request/stream/terminal/cleanup lifecycle.@@ -1846,10 +1847,15 @@ async def drive_sse_stream(else:if body is None:candidate = assembler.aborted(cancel.reason)- elif gateway and response.status_code == 409 and PIN_SOURCE_HEADER in headers and _pin_unavailable(body):- # The pinned Source cannot serve this content; nothing reached a model. The adapter sends- # the same request once more in portable form (§3.5), so no terminal is committed here.- yield PIN_UNAVAILABLE+ elif (+ gateway+ and response.status_code == 409+ and PIN_SOURCE_HEADER in headers+ and (handed_back := _pin_unavailable(body)) is not None+ ):+ # The pinned Source cannot serve this content; nothing reached a model. The adapter+ # decides what follows (§3.5, §4.3), so no terminal is committed here.+ yield handed_backreturnelse:candidate = assembler.error(@@ -1860,6 +1866,11 @@ async def drive_sse_stream(if refused is not None and refused(candidate):yield REFUSEDreturn+ if response.status_code == 400 and _DECRYPT_REFUSAL.search(body or ""):+ # A replayed ciphertext this account cannot read, refused before any output: the+ # loop renders the request again without that identity's opaque payloads (§3.5).+ refusal = Refusal("opaque_refused", endpoint.source_id, endpoint.source_identity)+ candidate = replace(candidate, retryable=False, refusal=refusal)else:resolved_origin = await resolve_served_origin(endpoint,@@ -1877,7 +1888,7 @@ async def drive_sse_stream(resolved_origin.source_id,resolved_origin.source_identity,)- async for item in translate(iter_sse_events(response, cancel, max_line_size=max_line_size)):+ async for item in translate(iter_sse_events(response, cancel)):if isinstance(item, (Done, ProviderError)):candidate = itembreakdiff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.pyindex 897eed82b..de5fdcb62 100644--- a/core/agent_core/ai/anthropic.py+++ b/core/agent_core/ai/anthropic.py@@ -29,9 +29,9 @@ from core.agent_core.ai._common import (hosted_pin,PAUSE_TURN,PIN_SOURCE_HEADER,- PIN_UNAVAILABLE,+ PinUnavailable,REFUSED,- portable_request,+ pin_refusal,join_endpoint_url,json_object,native_declaration,@@ -853,12 +853,13 @@ class AnthropicAdapter(ProviderAdapter):# The endpoint refused the lifetime before answering: sent again below, with nothing lost.refused=_rejects_ttl if prefix_ttl is not None else None,)- rejected = unavailable = continued = paused = message_started = message_stopped = False+ rejected = continued = paused = message_started = message_stopped = False+ unavailable: PinUnavailable | None = Nonestop_reason = Nonetry:async for event in driver:- if event is PIN_UNAVAILABLE:- unavailable = True+ if isinstance(event, PinUnavailable):+ unavailable = eventbreakif event is PAUSE_TURN:continued = True@@ -869,11 +870,14 @@ class AnthropicAdapter(ProviderAdapter):yield eventfinally:await driver.aclose()- if unavailable and sending is request:- # The pinned Source cannot serve this content: the same request once more, in portable form and- # unpinned, which the gateway fails over as any other (§3.5). Never the generic retry.- sending = portable_request(request)- elif unavailable or (+ if unavailable is not None and continuations == 0:+ # The pinned Source cannot serve this content; nothing reached a model. The loop renders the+ # request again for a fresh hop (§3.5).+ terminal = assembler.terminal(pin_refusal(assembler, request.endpoint, unavailable))+ if terminal is not None:+ yield terminal+ return+ elif unavailable is not None or (continuedand self._gatewayand (PIN_SOURCE_HEADER not in wire.headers or not assembler.verified_origin)@@ -983,10 +987,6 @@ def build_messages_payload(tools[functions[-1]]["cache_control"] = _cache_control(prefix_ttl)if tools:payload["tools"] = tools- if request.tool_choice is not None:- # Current Claude models refuse a forced `tool` or `any` choice, as does extended thinking, so a request that- # forces one would test the refusal instead of the tool. A hosted-tool probe asks in its message instead.- raise ValueError("an Anthropic request never forces a tool")effort = (request.reasoning_effort or "").lower()if effort in {"none", "off", "disabled"}:payload["thinking"] = {"type": "disabled"}diff --git a/core/agent_core/ai/hosted.py b/core/agent_core/ai/hosted.pyindex 300447f13..f8d8cb271 100644--- a/core/agent_core/ai/hosted.py+++ b/core/agent_core/ai/hosted.py@@ -84,8 +84,6 @@ def responses_hosted_tool(item: Mapping[str, Any]) -> Optional[str]:kind = item.get("type")if kind == "web_search_call":return "web_search"- if kind == "image_generation_call":- return "image_generation"if kind == "custom_tool_call" and str(item.get("name") or "").startswith("x_"):return "x_search"return None@@ -97,16 +95,12 @@ def responses_hosted_block(source_id: str,call_id: str,finished: bool = True,- image: HostedImage | None = None,- image_error: tuple[str, str] | None = None,) -> HostedToolBlock:- """One Responses hosted-call item (a ``web_search_call``, an ``image_generation_call``, or xAI's X-search- ``custom_tool_call``) as its block.+ """One Responses hosted-call item (a ``web_search_call``, or xAI's X-search ``custom_tool_call``) as its block.``call_id`` names the block when the item carries no id of its own. An item that has only been added- (``finished`` false) holds the call's place in the output order as a pending call. A generated image is the file- the adapter saved, ``image``: the item's base64 ``result`` is never kept (§7.3), and a finished call that saved no- image failed, for ``image_error``, a reason and its code, when the adapter knows why.+ (``finished`` false) holds the call's place in the output order as a pending call. An ``image_generation_call``+ is no hosted item: Vibey never declares a native image tool (§4.2)."""tool = responses_hosted_tool(item)@@ -123,18 +117,7 @@ def responses_hosted_block(else:record_status = "pending"error, error_code = _item_error(item, record_status) if record_status in ("failed", "incomplete") else (None, None)- images: tuple[HostedImage, ...] | None = None- if tool == "image_generation":- if record_status == "completed" and image is None:- record_status = "failed"- error, error_code = failure(*(image_error or ("the provider returned no image", "provider_no_image")))- images = (image,) if image is not None and record_status == "completed" else ()- action, sources = generate_action(item), ()- # The transcript's copy names the saved file in place of the base64 image.- item = {key: value for key, value in item.items() if key != "result"}- if images:- item["result"] = images[0].path- elif tool == "web_search":+ if tool == "web_search":action, sources = _web_search_action(item)else:action, sources = _x_search_action(item), ()@@ -142,23 +125,22 @@ def responses_hosted_block(id=_text(item.get("id")) or _text(item.get("call_id")) or call_id,tool=tool, # type: ignore[arg-type]action=action,- record=HostedRecord(- status=record_status, error=error, sources=sources, images=images, error_code=error_code # type: ignore[arg-type]- ),+ record=HostedRecord(status=record_status, error=error, sources=sources, error_code=error_code), # type: ignore[arg-type]native=HostedNative(source_id=source_id, payload=_payload(item)),)def generate_action(item: Mapping[str, Any]) -> HostedAction:- """An image generation as it ran: the prompt the provider rendered (its revision of the model's), and the output's- resolved size and quality, which pricing reads (§7.3, item 22). ``item`` is a native ``image_generation_call`` or- a proxy executor's ``generation`` facts, which carry the same names."""+ """An ``image_generate`` call as it ran: the image model, the prompt the endpoint rendered (its revision of the+ model's), and the output's resolved size and quality, which pricing reads (§7.3). ``item`` is the executor's+ ``generation`` facts."""return HostedAction("generate",prompt=_text(item.get("revised_prompt")),size=_text(item.get("size")),quality=_text(item.get("quality")),+ model=_text(item.get("model")),)diff --git a/core/agent_core/ai/openai_chat.py b/core/agent_core/ai/openai_chat.pyindex 8762433c5..90059545b 100644--- a/core/agent_core/ai/openai_chat.py+++ b/core/agent_core/ai/openai_chat.py@@ -20,17 +20,15 @@ from core.agent_core.ai._common import (content_parts,drive_sse_stream,endpoint_origin,- forced_tool,hosted_pin,- PIN_UNAVAILABLE,- portable_request,+ PinUnavailable,+ pin_refusal,join_endpoint_url,json_object,native_declaration,native_hosted_tools,prepare_messages,request_credential_values,- required_only_tool,StreamAssembler,validate_wire_shape,WireField,@@ -639,51 +637,31 @@ class OpenAIChatAdapter(ProviderAdapter):terminal = assembler.terminal(final if isinstance(final, ProviderError) else Done(final))if terminal is not None:yield terminal- sending = request- while True:- driver = drive_sse_stream(- self._client,- method="POST",- url=wire.url,- json_body=wire.body,- headers=wire.headers,- cancel=cancel,- assembler=assembler,- endpoint=sending.endpoint,- resolver=self._served_hop_resolver,- gateway=self._gateway,- translate=translate,- )- unavailable = False- try:- async for event in driver:- if event is PIN_UNAVAILABLE:- unavailable = True- break- yield event- finally:- await driver.aclose()- if not unavailable or sending is not request:- return- # The pinned Source cannot serve this content: the same request once more, in portable form and- # unpinned, which the gateway fails over as any other (§3.5). Never the generic retry.- sending = portable_request(request)- prepared = await prepare_messages(- sending.messages,- target=endpoint_origin(sending.endpoint),- supports_images=sending.supports_images,- protocol=self.protocol,- media_loader=self._media_loader,- cancel=cancel,- endpoint=sending.endpoint,- )- if isinstance(prepared, ProviderError):- terminal = assembler.terminal(prepared)- if terminal is not None:- yield terminal- return- transformed_messages, loaded_images = prepared- wire = wire_request(sending, transformed_messages, gateway=self._gateway, loaded_images=loaded_images)+ driver = drive_sse_stream(+ self._client,+ method="POST",+ url=wire.url,+ json_body=wire.body,+ headers=wire.headers,+ cancel=cancel,+ assembler=assembler,+ endpoint=request.endpoint,+ resolver=self._served_hop_resolver,+ gateway=self._gateway,+ translate=translate,+ )+ try:+ async for event in driver:+ if isinstance(event, PinUnavailable):+ # The pinned Source cannot serve this content; nothing reached a model. The loop renders the+ # request again for a fresh hop (§3.5).+ terminal = assembler.terminal(pin_refusal(assembler, request.endpoint, event))+ if terminal is not None:+ yield terminal+ return+ yield event+ finally:+ await driver.aclose()except Exception as exc:terminal = assembler.terminal(assembler.exception(exc))if terminal is not None:@@ -739,12 +717,6 @@ def build_chat_payload(]if tools:payload["tools"] = tools- forced = forced_tool(request)- if forced is not None:- name, route = forced- payload["tool_choice"] = (- required_only_tool(tools) if route is not None else {"type": "function", "function": {"name": name}}- )effort = sent_effort(request.reasoning_effort or "")if effort is not None:payload["reasoning_effort"] = effortdiff --git a/core/agent_core/ai/openai_responses.py b/core/agent_core/ai/openai_responses.pyindex 4964f0dc4..bdb63a8b6 100644--- a/core/agent_core/ai/openai_responses.py+++ b/core/agent_core/ai/openai_responses.py@@ -9,18 +9,15 @@ Payload and stream rules are ported from tau's ``tau_ai/openai_compatible.py``from __future__ import annotations-import asyncioimport copyimport jsonfrom collections.abc import AsyncIterator, Mapping-from dataclasses import replacefrom typing import Anyimport httpxfrom core.agent_core.ai.hosted import (citation,- image_dimensions,reported_cost,reported_counts,responses_hosted_block,@@ -35,17 +32,15 @@ from core.agent_core.ai._common import (drive_sse_stream,dispatch_wire_event,endpoint_origin,- forced_tool,hosted_pin,- PIN_UNAVAILABLE,- portable_request,+ PinUnavailable,+ pin_refusal,join_endpoint_url,json_object,native_declaration,native_hosted_tools,prepare_messages,request_credential_values,- required_only_tool,StreamAssembler,validate_wire_shape,WireField,@@ -54,19 +49,15 @@ from core.agent_core.ai._common import ()from core.agent_core.ai.provider import (Done,- HostedToolRoute,MediaLoader,- MediaSink,ModelRequest,ProviderAdapter,ProviderError,TextDelta,)from core.agent_core.cancel import CancelToken-from core.agent_core.ai.sse import DEFAULT_MAX_PENDING_EVENT_SIZEfrom core.agent_core.messages import (AssistantMessage,- HostedImage,HostedToolBlock,TextBlock,ThinkingBlock,@@ -75,19 +66,6 @@ from core.agent_core.messages import (UserMessage,)-#: A preview OpenAI streams while an image is drawn (``partial_images``); only the done item's image is kept.-_PARTIAL_IMAGE_EVENT = "response.image_generation_call.partial_image"-#: Every image one response streams, previews and finals, decoded (plan item 25). The terminal response repeats every-#: final image in one event, so the budget is what one event can carry as base64, less a margin for the rest of it.-IMAGE_BYTES_PER_RESPONSE = (DEFAULT_MAX_PENDING_EVENT_SIZE - 1024 * 1024) * 3 // 4-#: Image events beyond the declared previews and the final, per image call (plan item 25).-_IMAGE_EVENT_MARGIN = 2-#: An event longer than this (a generated image's) is parsed off the controller loop.-_INLINE_PARSE_CHARS = 1024 * 1024-#: The line cap of a stream that may carry a generated image: the whole event cap, as one image line can be several-#: MiB of base64 (§7.5). Other streams keep the default line cap.-IMAGE_STREAM_LINE_BYTES = DEFAULT_MAX_PENDING_EVENT_SIZE-_KNOWN_RESPONSE_EVENTS = frozenset({"response.created",@@ -307,7 +285,6 @@ class OpenAIResponsesAdapter(ProviderAdapter):client: httpx.AsyncClient | None = None,*,media_loader: MediaLoader | None = None,- media_sink: MediaSink | None = None,served_hop_resolver: ServedHopResolver | None = None,gateway: bool = False,) -> None:@@ -315,7 +292,6 @@ class OpenAIResponsesAdapter(ProviderAdapter):self._client = client or httpx.AsyncClient(timeout=None, trust_env=not gateway)self._owns_client = client is Noneself._media_loader = media_loader- self._media_sink = media_sinkself._served_hop_resolver = served_hop_resolverself._gateway = gateway@@ -366,7 +342,6 @@ class OpenAIResponsesAdapter(ProviderAdapter):refusal = False# The hosted tools this request declared natively: only their items become hosted calls (§4.2).hosted = frozenset(native_hosted_tools(request))- images = _ImageBudget(native_hosted_tools(request).get("image_generation"))try:wire = wire_request(request, transformed_messages, gateway=self._gateway, loaded_images=loaded_images)@@ -380,24 +355,7 @@ class OpenAIResponsesAdapter(ProviderAdapter):returnif not event.data or event.data == "[DONE]":continue- # A preview of an image still being drawn is never kept: named as one, its base64 is not even- # parsed. Named or known by its JSON type, it counts against the response's image budget.- named_preview = event.event == _PARTIAL_IMAGE_EVENT- if named_preview:- chunk = None- elif len(event.data) > _INLINE_PARSE_CHARS:- # A generated image's event is many MiB: parsed off the controller loop.- chunk = await asyncio.to_thread(json_object, event.data)- else:- chunk = json_object(event.data)- if named_preview or (chunk is not None and chunk.get("type") == _PARTIAL_IMAGE_EVENT):- exceeded = images.charge(len(event.data))- if exceeded is not None:- terminal = assembler.terminal(assembler.error(exceeded, kind="invalid_request"))- if terminal is not None:- yield terminal- return- continue+ chunk = json_object(event.data)if chunk is None:terminal = assembler.terminal(assembler.error(@@ -688,8 +646,6 @@ class OpenAIResponsesAdapter(ProviderAdapter):assembler.ensure_text_slot(output_index)else:# A hosted call takes its place in the output order now; its done item fills it in.- if responses_hosted_tool(item) == "image_generation":- images.started()_add_hosted_call(assembler, item, output_index, hosted, finished=False)elif event_type == "response.reasoning_summary_text.done":continue@@ -980,22 +936,6 @@ class OpenAIResponsesAdapter(ProviderAdapter):end = assembler.block_end(output_index)if end is not None:yield end- elif (- responses_hosted_tool(item) == "image_generation"- and "image_generation" in hosted- and assembler.source_id is not None- ):- encoded = item.get("result")- exceeded = images.charge(len(encoded) if isinstance(encoded, str) else 0)- if exceeded is not None:- terminal = assembler.terminal(assembler.error(exceeded, kind="invalid_request"))- if terminal is not None:- yield terminal- return- image, failure = await _saved_image(self._media_sink, item)- _add_hosted_call(- assembler, item, output_index, hosted, image=image, image_error=failure- )else:_add_hosted_call(assembler, item, output_index, hosted)elif event_type in {"response.completed", "response.incomplete"}:@@ -1345,54 +1285,31 @@ class OpenAIResponsesAdapter(ProviderAdapter):terminal = assembler.terminal(assembler.incomplete())if terminal is not None:yield terminal- sending = request- while True:- driver = drive_sse_stream(- self._client,- method="POST",- url=wire.url,- json_body=wire.body,- headers=wire.headers,- cancel=cancel,- assembler=assembler,- endpoint=sending.endpoint,- resolver=self._served_hop_resolver,- gateway=self._gateway,- translate=translate,- # A generated image arrives as one base64 line of several MiB (§7.5).- max_line_size=IMAGE_STREAM_LINE_BYTES if "image_generation" in hosted else None,- )- unavailable = False- try:- async for event in driver:- if event is PIN_UNAVAILABLE:- unavailable = True- break- yield event- finally:- await driver.aclose()- if not unavailable or sending is not request:- return- # The pinned Source cannot serve this content: the same request once more, in portable form and- # unpinned, which the gateway fails over as any other (§3.5). Never the generic retry.- sending = portable_request(request)- hosted = frozenset()- prepared = await prepare_messages(- sending.messages,- target=endpoint_origin(sending.endpoint),- supports_images=sending.supports_images,- protocol=self.protocol,- media_loader=self._media_loader,- cancel=cancel,- endpoint=sending.endpoint,- )- if isinstance(prepared, ProviderError):- terminal = assembler.terminal(prepared)- if terminal is not None:- yield terminal- return- transformed_messages, loaded_images = prepared- wire = wire_request(sending, transformed_messages, gateway=self._gateway, loaded_images=loaded_images)+ driver = drive_sse_stream(+ self._client,+ method="POST",+ url=wire.url,+ json_body=wire.body,+ headers=wire.headers,+ cancel=cancel,+ assembler=assembler,+ endpoint=request.endpoint,+ resolver=self._served_hop_resolver,+ gateway=self._gateway,+ translate=translate,+ )+ try:+ async for event in driver:+ if isinstance(event, PinUnavailable):+ # The pinned Source cannot serve this content; nothing reached a model. The loop renders the+ # request again for a fresh hop (§3.5).+ terminal = assembler.terminal(pin_refusal(assembler, request.endpoint, event))+ if terminal is not None:+ yield terminal+ return+ yield event+ finally:+ await driver.aclose()except Exception as exc:terminal = assembler.terminal(assembler.exception(exc))if terminal is not None:@@ -1443,10 +1360,6 @@ def build_responses_payload(include.extend(route.include)if include:payload["include"] = list(dict.fromkeys(include))- forced = forced_tool(request)- if forced is not None:- name, route = forced- payload["tool_choice"] = required_only_tool(tools) if route is not None else {"type": "function", "name": name}return payload@@ -1643,15 +1556,11 @@ def _add_hosted_call(*,finished: bool = True,backfill: bool = False,- image: HostedImage | None = None,- image_error: tuple[str, str] | None = None,) -> None:"""An output item of a hosted tool the request declared natively, as its hosted call at its output index (§4.2):pending when only added, filled in when done. A call the terminal response backfills keeps a block it has.A response whose served Source is unknown keeps no hosted call: its native payload could never be replayed.- A generated image is ``image``, the file its done item was saved to. The terminal response repeats that image,- and its copy is never decoded (§7.5), so a call it alone finishes saved none."""tool = responses_hosted_tool(item)@@ -1660,71 +1569,14 @@ def _add_hosted_call(current = assembler.hosted_block_at(output_index)if backfill and current is not None and current.record.status != "pending":return- if backfill and tool == "image_generation":- image_error = ("the image was not streamed before the response ended", "image_not_streamed")assembler.hosted_block(output_index,responses_hosted_block(- item,- source_id=assembler.source_id,- call_id=f"hosted_{output_index}",- finished=finished,- image=image,- image_error=image_error,+ item, source_id=assembler.source_id, call_id=f"hosted_{output_index}", finished=finished),)-class _ImageBudget:- """The image data one response may stream (plan item 25): per image call, the previews its declaration asks for- and the final, plus a small margin; and a cumulative decoded size. Exceeding either ends the stream as an error,- so a misbehaving provider cannot stream images without bound. The terminal response's duplicate is not counted:- it is never decoded."""-- def __init__(self, route: HostedToolRoute | None) -> None:- partials = (route.declaration or {}).get("partial_images") if route is not None else None- self._per_call = (partials if isinstance(partials, int) and partials > 0 else 0) + 1- self._calls = 0- self._events = 0- self._bytes = 0-- def started(self) -> None:- self._calls += 1-- def charge(self, encoded_length: int) -> str | None:- """Count one preview or final of ``encoded_length`` base64 characters; why the stream must end, if it must."""-- self._events += 1- self._bytes += encoded_length * 3 // 4- if self._events > self._per_call * self._calls + _IMAGE_EVENT_MARGIN:- return "the provider streamed more images than the response asked for"- if self._bytes > IMAGE_BYTES_PER_RESPONSE:- return "the provider streamed more image data than one response may carry"- return None---async def _saved_image(- sink: MediaSink | None, item: Mapping[str, Any]-) -> tuple[HostedImage | None, tuple[str, str] | None]:- """The file a done ``image_generation_call`` was saved to, with its output size, or why there is none and its code- (§7.3).-- Only a completed call's image is saved: that is the only record that lists one, so no file is written that no- record names."""-- encoded = item.get("result")- if item.get("status") != "completed" or not isinstance(encoded, str) or not encoded:- return None, None- if sink is None:- return None, ("nothing here can keep a generated image", "image_no_store")- try:- image = await sink.save_image(encoded)- except (ValueError, OSError) as error:- return None, (f"the image could not be saved: {error}", "image_not_saved")- width, height = image_dimensions(item.get("size"))- return replace(image, width=width, height=height), None--def _add_message_citations(assembler: StreamAssembler, index: int, item: Mapping[str, Any]) -> None:"""``url_citation`` annotations on a message's text parts, as citations into the text the parts make together."""diff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.pyindex 7ea2f1aea..7f41641eb 100644--- a/core/agent_core/ai/provider.py+++ b/core/agent_core/ai/provider.py@@ -38,29 +38,17 @@ THINKING_DROP_RETRY_KINDS: frozenset[str] = frozenset()-@dataclass(frozen=True)-class HostedExecutor:- """The proxy executor Model Hub bound for the turn: one verified (Source, model)."""-- source_id: str- model_id: str-- def __post_init__(self) -> None:- if not all(isinstance(value, str) and value for value in (self.source_id, self.model_id)):- raise ValueError("a hosted executor names a Source and a model")--@dataclass(frozen=True)class HostedToolRoute:- """One enabled hosted tool on a hop (C-6 ``HopResolution.hosted_tools``, ``vibey-hosted-tools.md`` §3.5).+ """How a hop sends one enabled search tool, from its C-6 facts (``HopResolution.hosted_tools``,+ ``vibey-hosted-tools.md`` §3.4, §4.1).- ``mode`` is Model Hub's decision for this hop; the agent never decides nativity itself. A ``native`` route has- the wire ``declaration`` and the Responses ``include`` values it needs; a ``proxy`` route has neither.- ``executor`` (None when no executor is verified) and ``replay`` hold in either mode.+ The agent declares the tool natively exactly when Model Hub assumes the hop runs it (``native: assumed``), with+ the wire ``declaration`` and the Responses ``include`` values; otherwise (``proxy``) as the same-named function,+ which the gateway's executor chain runs. ``replay`` is whether a hosted payload may go back verbatim to this hop."""mode: Literal["native", "proxy"]- executor: Optional[HostedExecutor]replay: booldeclaration: Optional[Mapping[str, Any]] = Noneinclude: tuple[str, ...] = ()@@ -68,8 +56,6 @@ class HostedToolRoute:def __post_init__(self) -> None:if self.mode not in ("native", "proxy"):raise ValueError(f"unknown hosted tool mode: {self.mode!r}")- if self.executor is not None and not isinstance(self.executor, HostedExecutor):- raise ValueError("a hosted executor must be a HostedExecutor or None")if not isinstance(self.replay, bool):raise ValueError("hosted replay must be a boolean")if self.mode == "proxy":@@ -83,6 +69,29 @@ class HostedToolRoute:raise ValueError("hosted include must be a tuple of strings")+@dataclass(frozen=True)+class ImageModel:+ """One image model ``image_generate`` may call (C-6 ``HopResolution.hosted_tools.image_generate``, §7.2): its+ Source, its id, one short description line, and the optional arguments it takes."""++ source_id: str+ model_id: str+ description: str+ params: tuple[str, ...]+ size_forms: tuple[str, ...]+++@dataclass(frozen=True)+class ImageModels:+ """The turn's image models, default first, as the ``image_generate`` enum lists them."""++ models: tuple[ImageModel, ...]++ def __post_init__(self) -> None:+ if not self.models or not all(isinstance(model, ImageModel) for model in self.models):+ raise ValueError("image models are a non-empty tuple of ImageModel")++@dataclass(frozen=True)class ModelEndpoint:protocol: ProtocolName@@ -96,11 +105,16 @@ class ModelEndpoint:#: That Source's credential-free identity (``HopResolution.source_identity``): the account a response's opaque#: payloads are bound to (``cross-provider.md``).source_identity: Optional[str] = None- #: A portable request (§3.5, ``portable_request``): never pinned, and no native hosted content. Its Source and+ #: A portable request (§3.5, ``portable_endpoint``): never pinned, and no native hosted content. Its Source and#: identity stay, so a response its own Source serves is still attributed to them.portable: bool = False- #: Each enabled hosted tool's route on this hop, in Model Hub's order; empty when none is enabled.+ #: The Source identities whose opaque payloads go nowhere for the rest of the turn: their provider refused one+ #: (§3.5). A message they served is sent as a different origin's.+ opaque_refused: frozenset[str | None] = frozenset()+ #: Each enabled search tool's route on this hop, in Model Hub's order; empty when none is enabled.hosted_tools: Mapping[str, HostedToolRoute] = field(default_factory=dict)+ #: The models ``image_generate`` may call; None when the tool is off or no model is available.+ image_models: Optional[ImageModels] = None@dataclass(frozen=True)@@ -148,10 +162,6 @@ class ModelRequest:cache: Literal["default", "none"] = "default"supports_images: bool = False"""Resolved by the loop from ``ModelCapabilities``; an unknown capability counts as False."""- tool_choice: Optional[str] = None- """The one tool the response must call, by name (a function's, or a hosted tool's catalog name); ``None``- leaves the choice to the model. Only a hosted-tool probe sets it (``vibey-hosted-tools.md`` §3.2), and never on- Anthropic, whose current models refuse a forced choice."""@dataclass(frozen=True)@@ -200,6 +210,26 @@ class ProviderError:#: The response streamed thinking and nothing else before this error (``THINKING_DROP_RETRY_KINDS``): it is#: ``retryable``, and the loop retries it at most once per request (``provider.md``).after_thinking: bool = False+ #: A refusal before any output, which the loop answers by rendering the request again (``vibey-hosted-tools.md``+ #: §3.5), never by the generic retry.+ refusal: Optional["Refusal"] = None+++@dataclass(frozen=True)+class Refusal:+ """Why a request was refused before any output, so the next attempt renders it differently (§3.5).++ ``pin_unavailable``: the gateway handed a pinned request back; ``tool`` and ``aspect`` name the narrow hosted rule+ that fired, when one did. ``opaque_refused``: the provider refused a replayed ciphertext (xAI's "Could not decrypt+ the provided encrypted_content"), which does not say which one. ``source_id`` and ``source_identity`` are the+ refused request's hop.+ """++ kind: Literal["pin_unavailable", "opaque_refused"]+ source_id: Optional[str] = None+ source_identity: Optional[str] = None+ tool: Optional[str] = None+ aspect: Optional[str] = NoneProviderEvent = Union[TextDelta, ThinkingDelta, ToolCallStart, ToolCallDelta, BlockEnd, Done, ProviderError]diff --git a/core/agent_core/ai/registry.py b/core/agent_core/ai/registry.pyindex 3110625eb..93c22b55d 100644--- a/core/agent_core/ai/registry.py+++ b/core/agent_core/ai/registry.py@@ -2,15 +2,13 @@from __future__ import annotations-from typing import Any, Callable, Optional+from typing import Anyfrom core.agent_core.ai import anthropic, openai_chat, openai_responses-from core.agent_core.ai._common import WireRequest, endpoint_origin, prepare_messagesfrom core.agent_core.ai.anthropic import AnthropicAdapterfrom core.agent_core.ai.openai_chat import OpenAIChatAdapterfrom core.agent_core.ai.openai_responses import OpenAIResponsesAdapter-from core.agent_core.ai.provider import MediaLoader, ModelRequest, ProviderAdapter, ProviderError-from core.agent_core.cancel import CancelToken+from core.agent_core.ai.provider import ProviderAdapterfrom core.agent_core.messages import ProtocolNameADAPTERS: dict[ProtocolName, type[ProviderAdapter]] = {@@ -19,13 +17,6 @@ ADAPTERS: dict[ProtocolName, type[ProviderAdapter]] = {"openai_responses": OpenAIResponsesAdapter,}-_WIRE_REQUESTS: dict[ProtocolName, Callable[..., WireRequest]] = {- "anthropic": anthropic.wire_request,- "openai_chat": openai_chat.wire_request,- "openai_responses": openai_responses.wire_request,-}--def sent_effort(protocol: str, model_id: str, effort: str) -> str | None:"""The effort token a request on ``protocol`` to ``model_id`` carries for ``effort``, exactly as the adapter sendsit: at ``output_config.effort`` (Anthropic), ``reasoning.effort`` (Responses) or ``reasoning_effort`` (Chat; a@@ -55,34 +46,3 @@ def create_adapter(protocol: ProtocolName, **kwargs: Any) -> ProviderAdapter:get_adapter = create_adapter---async def build_wire_request(- request: ModelRequest,- *,- gateway: bool,- media_loader: Optional[MediaLoader] = None,- cancel: Optional[CancelToken] = None,-) -> WireRequest:- """The request ``request.endpoint.protocol``'s adapter would send for ``request``, without sending it.-- The adapter's ``stream`` sends exactly this, so a hosted-tool probe built here is the production request- (``vibey-hosted-tools.md`` §3.2). Raises ``ValueError`` when the request cannot be built.- """-- protocol = request.endpoint.protocol- if protocol not in _WIRE_REQUESTS:- raise ValueError(f"unsupported provider protocol: {protocol}")- prepared = await prepare_messages(- request.messages,- target=endpoint_origin(request.endpoint),- supports_images=request.supports_images,- protocol=protocol,- media_loader=media_loader,- cancel=cancel or CancelToken(),- endpoint=request.endpoint,- )- if isinstance(prepared, ProviderError):- raise ValueError(prepared.message)- messages, loaded_images = prepared- return _WIRE_REQUESTS[protocol](request, messages, gateway=gateway, loaded_images=loaded_images)diff --git a/core/agent_core/ai/transform.py b/core/agent_core/ai/transform.pyindex 1af927df1..145127b03 100644--- a/core/agent_core/ai/transform.py+++ b/core/agent_core/ai/transform.py@@ -126,11 +126,9 @@ def transform_messages(pending_tool_ids.clear()# Opaque payloads are bound to the account that issued them, the Source identity: another account's ciphertext- # is refused (xAI, OpenAI). A message another identity served, or one no known identity did, is sent as a- # different origin's.- same_origin = message.origin == target and (- endpoint is None or message.source_identity == endpoint.source_identity- )+ # is refused (xAI, OpenAI). A message another identity served, one no known identity did, or one whose+ # identity's provider refused an opaque payload this turn is sent as a different origin's.+ same_origin = message.origin == target and _opaque_admitted(message, endpoint)content: list[AssistantContent] = []turn_tool_ids: dict[str, list[str]] = {}in_flight = position == live@@ -255,26 +253,35 @@ def in_flight_position(messages: list[Message] | tuple[Message, ...]) -> int | Nreturn last+def _opaque_admitted(message: AssistantMessage, endpoint: ModelEndpoint | None) -> bool:+ """Whether ``message``'s opaque payloads may go to ``endpoint``: a hop of the Source identity that served it, whose+ provider has not refused one this turn (§3.5)."""++ return endpoint is None or (+ message.source_identity == endpoint.source_identity and message.source_identity not in endpoint.opaque_refused+ )++def native_replay(message: AssistantMessage, *, in_flight: bool, endpoint: ModelEndpoint | None, target: Origin, protocol: str) -> bool:"""Whether a response's hosted calls go back verbatim, their native payloads in place (§4.4, §5).Only to the hop the request goes to, when that hop's Source served them on the same origin: one hop then builds- the request and serves it (§3.5 as implemented; a moved hop gets the in-place form). The hop must still have each- tool they called and a Source, which a portable request has not, over a protocol with native hosted content. A- generated image never goes back verbatim: its stored item no longer holds the image.- * The response its turn continues (``in_flight``) needs no replay evidence: that is the provider's own- continuation contract.- * Any earlier response needs the hop's current ``replay`` evidence for every tool it called, and every one of its- calls finished.+ the request and serves it (§3.5; a moved hop gets the in-place form). The hop must still declare each tool they+ called natively, since a provider refuses its server items without their declaration, over a protocol with native+ hosted content, and the request must not be portable.+ * The response its turn continues (``in_flight``) needs no ``replay``: that is the provider's own continuation+ contract.+ * Any earlier response needs ``replay`` assumed on the hop for every tool it called, and every one of its calls+ finished."""blocks = [block for block in message.content if isinstance(block, HostedToolBlock)]if not blocks or endpoint is None or not endpoint.source_id or endpoint.portable or message.origin != target:return False# A native payload is opaque provider content too: it goes back only to the account that issued it.- if message.source_identity != endpoint.source_identity:+ if not _opaque_admitted(message, endpoint):return Falseif protocol not in ("anthropic", "openai_responses"):return False@@ -282,7 +289,7 @@ def native_replay(return Falsefor block in blocks:route = endpoint.hosted_tools.get(block.tool)- if route is None or block.tool == "image_generation":+ if route is None or route.mode != "native":return Falseif not in_flight and (not route.replay or block.record.status == "pending"):return Falsediff --git a/core/agent_core/messages.py b/core/agent_core/messages.pyindex bbe221cc2..b85ddda3a 100644--- a/core/agent_core/messages.py+++ b/core/agent_core/messages.py@@ -26,13 +26,19 @@ _SOURCE_ID_RE = re.compile(r"^src_[a-z0-9]{8,}$")_COUNTER_NAME_RE = re.compile(r"^[a-z0-9_]{1,64}$")_ERROR_CODE_RE = re.compile(r"^[a-z][a-z0-9_]{0,63}$")-HostedToolName = Literal["web_search", "x_search", "image_generation"]-HOSTED_TOOLS: tuple[str, ...] = ("web_search", "x_search", "image_generation")+#: The tools a provider runs natively, each a ``HostedToolBlock`` in assistant content (``vibey-hosted-tools.md`` §4.2).+HostedToolName = Literal["web_search", "x_search"]+HOSTED_TOOLS: tuple[str, ...] = ("web_search", "x_search")+#: The tools whose ``ToolResultMessage`` carries ``hosted``: a proxied search, and every ``image_generate`` call.+HOSTED_RESULT_TOOLS: tuple[str, ...] = (*HOSTED_TOOLS, "image_generate")+EXECUTION_MODES: tuple[str, ...] = ("proxy", "direct")HostedStatus = Literal["completed", "failed", "incomplete", "pending"]HOSTED_STATUSES: tuple[str, ...] = ("completed", "failed", "incomplete", "pending")HOSTED_ERROR_MAX_CHARS = 400#: The stable code of each hosted failure Avibe words itself (``HostedRecord.error_code``), by which a display localizes#: it; a provider's own reason has none. A record loads with any snake_case code, so one a newer build wrote still reads.+#: ``provider_no_image`` and ``image_not_streamed`` have no producer since native images went (v2); they stay for the+#: records already written.HOSTED_ERROR_CODES: tuple[str, ...] = ("provider_no_reason","provider_no_image",@@ -43,6 +49,8 @@ HOSTED_ERROR_CODES: tuple[str, ...] = ("gateway_unreachable","gateway_refused","gateway_no_result",+ "image_param_unsupported",+ "image_model_unavailable",)COST_BASES: tuple[str, ...] = ("reported", "list", "included")SOURCE_BILLINGS: tuple[str, ...] = ("monthly", "metered")@@ -237,7 +245,7 @@ _HOSTED_ACTIONS: dict[str, tuple[Optional[str], dict[str, type], dict[str, type]"x_search": ("x_search", {"variant": str, "query": str}, {"limit": int, "mode": str}),"x_user_search": ("x_search", {"query": str}, {}),"x_thread_fetch": ("x_search", {"ref": str}, {}),- "generate": ("image_generation", {}, {"prompt": str, "size": str, "quality": str}),+ "generate": ("image_generate", {}, {"prompt": str, "size": str, "quality": str, "model": str}),"other": (None, {"name": str}, {}),}_X_SEARCH_VARIANTS = ("keyword", "semantic")@@ -261,6 +269,8 @@ class HostedAction:size: Optional[str] = Nonequality: Optional[str] = Nonename: Optional[str] = None+ #: ``generate`` only: the image model the call ran on.+ model: Optional[str] = Nonedef __post_init__(self) -> None:_require(self.type, str, "hosted action type")@@ -278,7 +288,7 @@ class HostedAction:raise ValueError("search queries are a non-empty tuple")for query in self.queries:_require_text(query, "search query")- for name in ("url", "pattern", "query", "ref", "prompt", "size", "quality", "name"):+ for name in ("url", "pattern", "query", "ref", "prompt", "size", "quality", "name", "model"):_require_text(getattr(self, name), f"action {name}", optional=True)_require(self.variant, str, "action variant", optional=True)if self.variant is not None and self.variant not in _X_SEARCH_VARIANTS:@@ -297,6 +307,7 @@ class HostedAction:_HOSTED_ACTION_FIELDS: tuple[str, ...] = ("queries", "url", "pattern", "variant", "query", "limit", "mode", "ref", "prompt", "size", "quality", "name",+ "model",)@@ -337,7 +348,7 @@ class HostedImage:@dataclass(frozen=True)class HostedRecord:- """Per-call facts. ``images`` is set exactly for ``image_generation`` (possibly empty).+ """Per-call facts. ``images`` is set exactly for ``image_generate`` (possibly empty).``error`` is model-facing English. ``error_code`` names a reason Avibe wrote (``HOSTED_ERROR_CODES``), only besidean ``error``.@@ -369,8 +380,8 @@ class HostedRecord:raise ValueError("hosted images must be a tuple of HostedImage")def check_tool(self, tool: str) -> None:- if (self.images is not None) != (tool == "image_generation"):- raise ValueError("a hosted record lists images exactly for image_generation")+ if (self.images is not None) != (tool == "image_generate"):+ raise ValueError("a hosted record lists images exactly for image_generate")@dataclass(frozen=True)@@ -411,8 +422,6 @@ class HostedToolBlock:if not self.action.fits(self.tool):raise ValueError(f"a {self.action.type} action does not belong to {self.tool}")self.record.check_tool(self.tool)- if self.action.type == "generate" and self.record.status == "completed" and self.action.prompt is None:- raise ValueError("a completed generate action needs its prompt")@dataclass(frozen=True)@@ -463,20 +472,45 @@ class HostedSummary:_require(self.cost, HostedCost, "hosted cost", optional=True)+@dataclass(frozen=True)+class FailedAttempt:+ """An earlier billable attempt of a proxied search chain, before the one that ran the call (§6)."""++ source_id: str+ billing: str+ cost: Optional[HostedCost] = None++ def __post_init__(self) -> None:+ _require(self.source_id, str, "attempt source id")+ if not _SOURCE_ID_RE.fullmatch(self.source_id):+ raise ValueError(f"invalid source id: {self.source_id!r}")+ _require(self.billing, str, "attempt billing")+ if self.billing not in SOURCE_BILLINGS:+ raise ValueError(f"unknown billing: {self.billing}")+ _require(self.cost, HostedCost, "attempt cost", optional=True)++@dataclass(frozen=True)class ProxyExecution:- """Which executor ran a proxied hosted call; absent when the call never reached one."""+ """What ran a hosted call outside the model: a search executor (``proxy``) or an image endpoint (``direct``);+ absent when the call never reached one. ``cost`` is this attempt's own; ``failed_attempts`` lists the earlier+ billed ones, and ``core/hosted_activity`` totals them for display."""executor_origin: Originexecutor_source_id: strexecutor_billing: strcost: Optional[HostedCost] = None-- @property- def mode(self) -> Literal["proxy"]:- return "proxy"+ mode: Literal["proxy", "direct"] = "proxy"+ failed_attempts: tuple[FailedAttempt, ...] = ()def __post_init__(self) -> None:+ _require(self.mode, str, "execution mode")+ if self.mode not in EXECUTION_MODES:+ raise ValueError(f"unknown execution mode: {self.mode}")+ if not isinstance(self.failed_attempts, tuple) or not all(+ isinstance(attempt, FailedAttempt) for attempt in self.failed_attempts+ ):+ raise ValueError("failed attempts must be a tuple of FailedAttempt")_require(self.executor_origin, Origin, "executor origin")_require(self.executor_source_id, str, "executor source id")if not _SOURCE_ID_RE.fullmatch(self.executor_source_id):@@ -489,9 +523,10 @@ class ProxyExecution:@dataclass(frozen=True)class HostedResult:- """``ToolResultMessage.hosted``: the canonical record of a proxied hosted call. ``action`` is what the executor- reports it did, where that differs from the model's request: for ``image_generation``, the prompt it rendered and- the output's resolved size and quality, as a native call's block carries them."""+ """``ToolResultMessage.hosted``: the canonical record of a proxied search or an ``image_generate`` call.+ ``action`` is what the executor reports it did, where that differs from the model's request: for+ ``image_generate``, the model it ran on, the prompt the endpoint revised it to when it did, and the output's+ resolved size and quality when the endpoint reports them."""record: HostedRecordexecution: Optional[ProxyExecution] = None@@ -615,9 +650,11 @@ class ToolResultMessage:if not self.tool_call_id or not self.tool_name:raise ValueError("a tool result needs its call id and tool name")if self.hosted is not None:- if self.tool_name not in HOSTED_TOOLS:+ if self.tool_name not in HOSTED_RESULT_TOOLS:raise ValueError(f"{self.tool_name} is not a hosted tool")self.hosted.record.check_tool(self.tool_name)+ if self.hosted.action is not None and not self.hosted.action.fits(self.tool_name):+ raise ValueError(f"a {self.hosted.action.type} action does not belong to {self.tool_name}")if self.is_error != (self.hosted.record.status in ("failed", "incomplete")):raise ValueError("a hosted result is an error exactly when its record failed or is incomplete")@@ -634,18 +671,13 @@ def text(value: str) -> TextBlock:def has_reply(message: AssistantMessage) -> bool:- """Whether a response says something to the user: non-blank text, or an image a hosted call generated.+ """Whether a response says something to the user: non-blank text.The one rule for "the model replied", read by the loop's empty-reply test and- by a final row's outcome. A generated image is a reply on its own: a model- asked for a picture may answer with the picture alone.+ by a final row's outcome. A generated image is an ``image_generate`` tool+ result, delivered with the turn, never part of the response itself."""- for block in message.content:- if isinstance(block, TextBlock) and block.text and block.text.strip():- return True- if isinstance(block, HostedToolBlock) and block.record.status == "completed" and block.record.images:- return True- return False+ return any(isinstance(block, TextBlock) and block.text and block.text.strip() for block in message.content)# --- persisted form ---------------------------------------------------------@@ -923,6 +955,15 @@ def message_to_dict(message: Message) -> dict[str, Any]:}if execution.cost is not None:hosted_result["execution"]["cost"] = _cost_to_dict(execution.cost)+ if execution.failed_attempts:+ hosted_result["execution"]["failed_attempts"] = [+ {+ "source_id": attempt.source_id,+ "billing": attempt.billing,+ **({"cost": _cost_to_dict(attempt.cost)} if attempt.cost is not None else {}),+ }+ for attempt in execution.failed_attempts+ ]if message.hosted.action is not None:hosted_result["action"] = _action_to_dict(message.hosted.action)result["hosted"] = hosted_result@@ -980,15 +1021,25 @@ def message_from_dict(data: Mapping[str, Any]) -> Message:"executor_source_id": str,"executor_billing": str,},- {"cost": dict},+ {"cost": dict, "failed_attempts": list},)- if e["mode"] != "proxy":- raise ValueError("proxy execution.mode must be proxy")+ attempts = []+ for attempt in e.get("failed_attempts", ()):+ a = _read(attempt, "failed attempt", {"source_id": str, "billing": str}, {"cost": dict})+ attempts.append(+ FailedAttempt(+ source_id=a["source_id"],+ billing=a["billing"],+ cost=_cost_from_dict(a["cost"]) if "cost" in a else None,+ )+ )execution = ProxyExecution(executor_origin=origin_from_dict(e["executor_origin"]),executor_source_id=e["executor_source_id"],executor_billing=e["executor_billing"],cost=_cost_from_dict(e["cost"]) if "cost" in e else None,+ mode=e["mode"],+ failed_attempts=tuple(attempts),)hosted_result = HostedResult(record=_record_from_dict(h["record"]),diff --git a/core/agent_core/tools/hosted.py b/core/agent_core/tools/hosted.pyindex 3f6ddc23f..676eedba0 100644--- a/core/agent_core/tools/hosted.py+++ b/core/agent_core/tools/hosted.py@@ -38,23 +38,11 @@ _SPECS: dict[str, tuple[str, dict[str, Any]]] = {"additionalProperties": False,},),- "image_generation": (- "Generate an image from a text prompt. The image is saved as a file, and the result names its path.",- {- "type": "object",- "properties": {- "prompt": {"type": "string", "description": "What the image shows."},- "size": {"type": "string", "description": "Width x height in pixels, e.g. 1024x1024."},- },- "required": ["prompt"],- "additionalProperties": False,- },- ),}def hosted_tool_spec(tool: str) -> ToolSpec:- """The canonical spec of the catalog tool ``tool`` (``web_search``, ``x_search`` or ``image_generation``)."""+ """The canonical spec of the search tool ``tool`` (``web_search`` or ``x_search``)."""if tool not in HOSTED_TOOLS:raise ValueError(f"unknown hosted tool: {tool!r}")diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.pyindex 330117856..7a375aefe 100644--- a/core/handlers/model_hub/adapter.py+++ b/core/handlers/model_hub/adapter.py@@ -196,6 +196,9 @@ class RawCallOutcome:os_errno: int | None = None# A 400 before output, as closed tokens for the capability-evidence rules.rejection: UpstreamRejection | None = None+ # The search tools whose own completed item a served response carried, for+ # the positive evidence written at settlement (``vibey-hosted-tools.md`` §3.2).+ hosted_tools: frozenset[str] = frozenset()class ObservationOutcome(str, Enum):diff --git a/core/handlers/model_hub/classification.py b/core/handlers/model_hub/classification.pyindex e0ce5de7d..49f7a08a3 100644--- a/core/handlers/model_hub/classification.py+++ b/core/handlers/model_hub/classification.py@@ -219,6 +219,15 @@ def machine_error_codes(outcome: RawCallOutcome) -> tuple[str, ...]:)+def names_model_refusal(outcome: RawCallOutcome) -> bool:+ """Whether the upstream's machine code says it does not serve the requested model."""++ return bool(_MODEL_SURFACE_PATTERNS.search(_error_text(outcome))) or (+ outcome.http_status == 404+ and any(code in _MODEL_NOT_FOUND_ERROR_CODES for code in machine_error_codes(outcome))+ )++def _classify_unstreamed(outcome: RawCallOutcome,*,@@ -264,11 +273,7 @@ def _classify_unstreamed("fallback",reason="balance_exhausted",)- model_not_found = _MODEL_SURFACE_PATTERNS.search(error_text) or (- outcome.http_status == 404- and any(code in _MODEL_NOT_FOUND_ERROR_CODES for code in machine_error_codes(outcome))- )- if _SURFACE_PATTERNS.search(error_text) or model_not_found:+ if _SURFACE_PATTERNS.search(error_text) or names_model_refusal(outcome):return ResolutionDecision("surface", error_code="upstream_request_invalid")if _QUOTA_PATTERNS.search(error_text):diff --git a/core/handlers/model_hub/hosted_admission.py b/core/handlers/model_hub/hosted_admission.pyindex 097d2820d..bd1c9da12 100644--- a/core/handlers/model_hub/hosted_admission.py+++ b/core/handlers/model_hub/hosted_admission.py@@ -27,6 +27,7 @@ from config.v2_config import ModelHubSourceConfigfrom vibe.backend_model_catalog import HostedToolSpec, bundled_provider_overlayfrom .capability_evidence import HOSTED_TOOL_ASPECTS+from .hosted_items import responses_item_toolfrom .hosted_tools import HostedEvidence, hosted_tool_factsPIN_SOURCE_HEADER: Final = "x-avibe-pin-source"@@ -34,10 +35,6 @@ PIN_SOURCE_HEADER: Final = "x-avibe-pin-source"PIN_MODEL_HEADER: Final = "x-avibe-pin-model"PIN_UNAVAILABLE_CODE: Final = "pin_unavailable"-# Responses items that carry a hosted call's native result, by catalog tool.-_RESPONSES_HOSTED_ITEMS: Final = {"web_search_call": "web_search", "image_generation_call": "image_generation"}-# xAI runs X search as custom tool calls; their names are the provider's.-_X_SEARCH_CALLS: Final = frozenset({"x_keyword_search", "x_semantic_search", "x_user_search", "x_thread_fetch"})# Client items that may follow an in-flight response._RESPONSES_TOOL_OUTPUTS: Final = frozenset({"function_call_output", "custom_tool_call_output"})# Items a Responses model emits. Only these form an in-flight response: anything@@ -116,10 +113,7 @@ def _text(item: Any, key: str) -> str | None:def _responses_hosted_tool(item: Any) -> str | None:- 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 kind is not None else None+ return responses_item_tool(_text(item, "type"), _text(item, "name"))def _responses_output_item(item: Any) -> bool:diff --git a/core/handlers/model_hub/hosted_executor.py b/core/handlers/model_hub/hosted_executor.pyindex ab2d94aa0..0daf598e7 100644--- a/core/handlers/model_hub/hosted_executor.py+++ b/core/handlers/model_hub/hosted_executor.py@@ -1,22 +1,18 @@-"""The gateway's hosted-tool proxy executor (``vibey-hosted-tools.md`` §3.4).--When Vibey's hop runs a hosted tool as a proxy function, Vibey's tool runtime-asks the gateway to run it on the executor bound for the turn. This module owns-what that executor call sends and how its response becomes the canonical-record; the service owns the call itself, and Vibey renders the record and-writes any image into session media.--The executor request depends on the tool: a search tool sends one short native-request that searches and lists results, and ``image_generation`` renders the-supplied prompt at the supplied size. Neither sends a reasoning effort: the-executor is verified for the tool, not for any effort. The declaration is the-overlay's, exactly as a native turn sends it.+"""The gateway's hosted search executor (``vibey-hosted-tools.md`` §6).++When Vibey's hop runs a search tool as a proxy function, Vibey's tool runtime+asks the gateway to run it; the gateway tries the turn's executor chain. This+module owns what one executor request sends and how its response becomes the+canonical record; the service owns the chain and the calls, and Vibey renders+the record.++An executor request is one short native request on the vendor's executor+model that searches and lists results. It sends no reasoning effort, and the+declaration is the overlay's, exactly as a native turn sends it."""from __future__ import annotations-import base64-import binasciiimport jsonimport refrom dataclasses import dataclass, field, replace@@ -25,33 +21,24 @@ from typing import Any, Callable, Final, Mappingfrom config.v2_config import ModelHubSourceConfigfrom core.agent_core.ai.hosted import reported_countsfrom core.agent_core.ai.sse import SSEParser-from vibe.backend_model_catalog import HostedToolSpecfrom .events import bounded_diagnostic_detail+from .hosted_items import responses_item_toolfrom .pricing import usd_from_xai_ticksfrom .request import ModelHubRequest-EXECUTOR_TOOLS: Final = ("web_search", "x_search", "image_generation")+EXECUTOR_TOOLS: Final = ("web_search", "x_search")+# One deadline for a search call's whole executor chain, not one per candidate.SEARCH_TIMEOUT_SECONDS: Final = 180.0-IMAGE_TIMEOUT_SECONDS: Final = 300.0# Responses counts reasoning against this cap, so it leaves room beyond the list itself._RESPONSES_OUTPUT_TOKENS: Final = 4096_ANTHROPIC_OUTPUT_TOKENS: Final = 2048-# An image stream carries a full image per partial and the final image twice.-_IMAGE_LINE_BYTES: Final = 32 * 1024 * 1024-EXECUTOR_RESPONSE_MAX_BYTES: Final = 128 * 1024 * 1024-# One final image, decoded: what a base64 event under the line cap can carry.-_IMAGE_MAX_BYTES: Final = 24 * 1024 * 1024-# Every image a response carries, partials and the final, decoded (vibey-hosted-tools.md §12 item 25).-_IMAGES_TOTAL_MAX_BYTES: Final = 64 * 1024 * 1024-# Image events per response: the requested partials and the final, with a small margin.-_IMAGE_EVENT_MARGIN: Final = 2+# A search answer is a short cited list; this bounds a misbehaving response.+EXECUTOR_RESPONSE_MAX_BYTES: Final = 16 * 1024 * 1024_SNIPPET_CHARS: Final = 500# The url_citation annotations one response's record reads; an executor's answer cites tens._MAX_CITATIONS: Final = 256_X_POST_HOSTS: Final = ("x.com", "twitter.com", "www.x.com", "www.twitter.com", "mobile.twitter.com")-_X_SEARCH_CALLS: Final = frozenset({"x_keyword_search", "x_semantic_search", "x_user_search", "x_thread_fetch"})-_IMAGE_MIME: Final = {"png": "image/png", "jpeg": "image/jpeg", "jpg": "image/jpeg", "webp": "image/webp"}_X_SEARCH_MODES: Final = ("Latest", "Top")_SEARCH_INSTRUCTIONS: Final = {@@ -68,9 +55,6 @@ _SEARCH_INSTRUCTIONS: Final = {"Write nothing else."),}-_IMAGE_INSTRUCTIONS: Final = (- "Generate exactly one image for the user's prompt with the image_generation tool. Write no text."-)class ExecutorResponseRefused(ValueError):@@ -94,68 +78,53 @@ class ExecutorCallRefused(ValueError):class ExecutorCall:tool: strarguments: Mapping[str, Any]- executor: tuple[str, str] | Nonedef parse_call(tool: str, payload: object) -> ExecutorCall:- """Validate one ``POST /vibey/v1/hosted-tools/{tool}`` body against the canonical schema."""+ """Validate one ``POST /vibey/v1/hosted-tools/{tool}`` body, ``{"arguments": ...}``, against the canonical schema."""if tool not in EXECUTOR_TOOLS:raise ExecutorCallRefused("not_found_error", 404)- if not isinstance(payload, dict) or set(payload) != {"arguments", "executor"}:+ if not isinstance(payload, dict) or set(payload) != {"arguments"}:raise ExecutorCallRefused("invalid_request_error", 400)- arguments, executor = payload["arguments"], payload["executor"]+ arguments = payload["arguments"]if not isinstance(arguments, dict):raise ExecutorCallRefused("invalid_request_error", 400)- required = "prompt" if tool == "image_generation" else "query"- optional = {"web_search": set(), "x_search": {"limit", "mode"}, "image_generation": {"size"}}[tool]- text = arguments.get(required)- if set(arguments) - {required} - optional or not isinstance(text, str) or not text.strip():+ optional = {"web_search": set(), "x_search": {"limit", "mode"}}[tool]+ text = arguments.get("query")+ if set(arguments) - {"query"} - optional or not isinstance(text, str) or not text.strip():raise ExecutorCallRefused("invalid_request_error", 400)- limit, mode, size = arguments.get("limit"), arguments.get("mode"), arguments.get("size")+ limit, mode = arguments.get("limit"), arguments.get("mode")if ((limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or limit < 1))or (mode is not None and mode not in _X_SEARCH_MODES)- or (size is not None and (not isinstance(size, str) or not size.strip()))- ):- raise ExecutorCallRefused("invalid_request_error", 400)- if executor is None:- return ExecutorCall(tool, dict(arguments), None)- if (- not isinstance(executor, dict)- or set(executor) != {"source_id", "model_id"}- or not all(isinstance(executor[key], str) and executor[key] for key in ("source_id", "model_id"))):raise ExecutorCallRefused("invalid_request_error", 400)- return ExecutorCall(tool, dict(arguments), (executor["source_id"], executor["model_id"]))+ return ExecutorCall(tool, dict(arguments))def executor_streams(source: ModelHubSourceConfig) -> bool:- """A Responses executor streams, so an image's partials keep the idle bound fed; Anthropic is buffered."""+ """A Responses executor streams, so the idle bound stays fed; Anthropic is buffered."""return source.protocol == "openai_responses"def call_timeout(tool: str) -> float:- return IMAGE_TIMEOUT_SECONDS if tool == "image_generation" else SEARCH_TIMEOUT_SECONDS+ """The deadline of one call's whole executor chain."""+ return SEARCH_TIMEOUT_SECONDS-def executor_request(call: ExecutorCall, source: ModelHubSourceConfig, model_id: str, spec: HostedToolSpec) -> ModelHubRequest:++def executor_request(+ call: ExecutorCall,+ source: ModelHubSourceConfig,+ model_id: str,+ declaration: Mapping[str, Any],+ include: tuple[str, ...],+) -> ModelHubRequest:"""The one native request this call sends, in the executor Source's own protocol."""- declaration = spec.declaration- if call.tool == "image_generation":- if call.arguments.get("size") is not None:- declaration["size"] = call.arguments["size"]- payload: dict[str, Any] = {- "model": model_id,- "instructions": _IMAGE_INSTRUCTIONS,- "input": [{"role": "user", "content": call.arguments["prompt"]}],- "tools": [declaration],- "tool_choice": {"type": "image_generation"},- "store": False,- }- return ModelHubRequest(payload, protocol=source.protocol)+ declaration = dict(declaration)query = call.arguments["query"]if call.tool == "x_search":settings = [f"limit {call.arguments['limit']}" if "limit" in call.arguments else None,@@ -183,8 +152,8 @@ def executor_request(call: ExecutorCall, source: ModelHubSourceConfig, model_id:"store": False,"max_output_tokens": _RESPONSES_OUTPUT_TOKENS,}- if spec.include:- payload["include"] = list(spec.include)+ if include:+ payload["include"] = list(include)return ModelHubRequest(payload, protocol=source.protocol)@@ -209,22 +178,15 @@ class ResponsesReadout:class ResponsesStreamReader:- """Read a Responses event stream into its output items, without keeping image partials.+ """Read a Responses event stream into its output items.- Each line is bounded (32 MiB for an image stream, the same as Vibey's), and- so is the whole stream. Partial images are counted, never kept, and an- image stream may carry only the requested partials and the final image,- with a small margin. Parsing a large event is CPU work: feed it off the- controller loop.+ Each line and event keeps the SSE parser's default bound, and so is the+ whole stream."""- def __init__(self, *, partial_images: int | None) -> None:- limit = _IMAGE_LINE_BYTES if partial_images is not None else None- self._parser = SSEParser(max_line_size=limit, max_event_size=limit)+ def __init__(self) -> None:+ self._parser = SSEParser()self._read = 0- self._image_events = 0- self._image_bytes = 0- self._max_image_events = (partial_images or 0) + 1 + _IMAGE_EVENT_MARGINself.readout = ResponsesReadout()def feed(self, chunk: bytes) -> None:@@ -252,20 +214,15 @@ class ResponsesStreamReader:if not isinstance(kind, str):returnitem = payload.get("item")- if kind == "response.image_generation_call.partial_image":- self._count_image(payload.get("partial_image_b64"))if kind == "response.output_item.done" and isinstance(item, dict):- if item.get("type") == "image_generation_call":- self._count_image(item.get("result"))self.readout.items.append(item)elif kind in {"response.completed", "response.incomplete", "response.failed"} and isinstance(payload.get("response"), dict):response = dict(payload["response"])output = response.pop("output", None)- # The terminal output repeats the streamed items (the image included);- # only the items the stream did not carry are taken from it, and only- # their images count toward the budget.+ # The terminal output repeats the streamed items; only the items the+ # stream did not carry are taken from it.seen = {item.get("id") for item in self.readout.items if isinstance(item.get("id"), str)}streamed = bool(self.readout.items)for adopted in output if isinstance(output, list) else ():@@ -275,35 +232,22 @@ class ResponsesStreamReader:if (ident in seen) if isinstance(ident, str) else streamed:# A repeat, or an item without an id the stream may already hold.continue- if adopted.get("type") == "image_generation_call":- self._count_image(adopted.get("result"))self.readout.items.append(adopted)self.readout.response = response- def _count_image(self, encoded: Any) -> None:- """Bound the response's image events and their decoded bytes, without decoding them."""-- self._image_events += 1- self._image_bytes += len(encoded) * 3 // 4 if isinstance(encoded, str) else 0- if self._image_events > self._max_image_events or self._image_bytes > _IMAGES_TOTAL_MAX_BYTES:- raise ExecutorResponseRefused("modelHub.hostedTools.tooLarge")--# --- results ---------------------------------------------------------------@dataclass(frozen=True)class ExecutorResult:- """The record for the call, plus an image's resolved facts and bytes (base64).+ """The record for the call.``usage`` is the response's own ``usage`` section, as the provider sent it,which the call's cost is read from."""record: dict[str, Any]- generation: dict[str, str] | None = None- images: tuple[dict[str, str], ...] = ()usage: Mapping[str, Any] | None = None@@ -335,8 +279,6 @@ def responses_result(tool: str, readout: ResponsesReadout, say: Say, *, failure:def _responses_record(tool: str, readout: ResponsesReadout, say: Say, failure: str | None) -> ExecutorResult:response = readout.response or {}calls = [item for item in readout.items if _responses_call_tool(item) == tool]- if tool == "image_generation":- return _image_result(calls, readout, say, failure)if not calls:return ExecutorResult(failed_record(failure or _ended_without(tool, response, say)))texts = [@@ -381,14 +323,7 @@ def _text_field(item: Mapping[str, Any], key: str) -> str | None:def _responses_call_tool(item: Mapping[str, Any]) -> str | None:- kind = item.get("type")- if kind == "web_search_call":- return "web_search"- if kind == "image_generation_call":- return "image_generation"- if kind == "custom_tool_call" and _text_field(item, "name") in _X_SEARCH_CALLS:- return "x_search"- return None+ return responses_item_tool(_text_field(item, "type"), _text_field(item, "name"))def _ended_without(tool: str, response: Mapping[str, Any], say: Say) -> str:@@ -525,47 +460,6 @@ def _sentence(text: str, start: int, end: int, line_start: int, line_end: int) -return sentence_start, found.end() if found is not None else line_end-def _image_result(- calls: list[Mapping[str, Any]], readout: ResponsesReadout, say: Say, failure: str | None,-) -> ExecutorResult:- if failure is None and any(call.get("status") == "failed" for call in calls):- # The one failure-precedence rule: a provider-marked failed call fails the call.- return ExecutorResult(failed_record(say("modelHub.hostedTools.callFailed", tool="image_generation")))- done = [call for call in calls if call.get("status") == "completed" and isinstance(call.get("result"), str)]- image = done[-1] if done and done[-1]["result"] else None- status = _text_field(readout.response or {}, "status")- if failure is None and (status == "incomplete" or (image is not None and status != "completed")):- # Success is the allow-list: a response that stopped early, before or after its image, is not completed.- settled = _settled(readout.response or {}, [], say)- return ExecutorResult({**settled, "sources": []})- if failure is not None or image is None:- error = failure or (- say("modelHub.hostedTools.callEnded", tool="image_generation", status=str(calls[-1].get("status")))- if calls else _ended_without("image_generation", readout.response or {}, say)- )- return ExecutorResult(failed_record(error))- output_format = str(image.get("output_format") or "png").lower()- mime = _IMAGE_MIME.get(output_format)- if mime is None:- return ExecutorResult(failed_record(say("modelHub.hostedTools.imageFormat", format=output_format)))- try:- size = len(base64.b64decode(image["result"], validate=True))- except (binascii.Error, ValueError):- return ExecutorResult(failed_record(say("modelHub.hostedTools.imageUnreadable")))- if not size or size > _IMAGE_MAX_BYTES:- return ExecutorResult(failed_record(say("modelHub.hostedTools.imageUnreadable")))- generation = {- name: image[name]- for name in ("revised_prompt", "size", "quality")- if isinstance(image.get(name), str) and image[name]- }- return ExecutorResult(- {"status": "completed", "sources": []},- generation=generation,- images=({"mime": mime, "data": image["result"]},),- )--def anthropic_result(body: bytes | bytearray, say: Say) -> ExecutorResult:"""The canonical record of one buffered Anthropic web search executor call; parse it off the loop."""diff --git a/core/handlers/model_hub/hosted_items.py b/core/handlers/model_hub/hosted_items.pynew file mode 100644index 000000000..1e3bbe627--- /dev/null+++ b/core/handlers/model_hub/hosted_items.py@@ -0,0 +1,35 @@+"""The providers' own hosted-tool items, by catalog tool (``vibey-hosted-tools.md`` §3.2).++One vocabulary for every gateway reader of a provider's hosted items: request+admission, the executor's result reader, and the served-response observer.+"""++from __future__ import annotations++from typing import Final++# xAI runs X search as custom tool calls; their names are the provider's.+X_SEARCH_CALLS: Final = frozenset({"x_keyword_search", "x_semantic_search", "x_user_search", "x_thread_fetch"})+# Responses items that carry a hosted call's native result, by catalog tool.+RESPONSES_HOSTED_ITEMS: Final = {"web_search_call": "web_search", "image_generation_call": "image_generation"}+++def responses_item_tool(kind: str | None, name: str | None) -> str | None:+ """The catalog tool a Responses output item belongs to, or None for any other item."""++ if kind == "custom_tool_call":+ return "x_search" if name in X_SEARCH_CALLS else None+ return RESPONSES_HOSTED_ITEMS.get(kind) if kind is not None else None+++def responses_item_succeeded(kind: str | None, name: str | None, status: str | None) -> str | None:+ """The search tool a completed Responses item proves ran, or None.++ A ``web_search_call`` counts only when it says it completed; an X search+ call is the provider's record of a search it ran. Images are not searches.+ """++ tool = responses_item_tool(kind, name)+ if tool == "web_search":+ return tool if status == "completed" else None+ return tool if tool == "x_search" else Nonediff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.pyindex c4e1bc82d..d8a0d4cd9 100644--- a/core/handlers/model_hub/hosted_tools.py+++ b/core/handlers/model_hub/hosted_tools.py@@ -40,6 +40,7 @@ from vibe.backend_model_catalog import (bundled_provider_vendors,provider_executor_model,provider_image_models,+ provider_overlay_entry,)from .capability_evidence import (@@ -51,6 +52,7 @@ from .capability_evidence import (utc_text,wire_stamp,)+from .hosted_turn import IMAGE_TOOL, ExecutorSlot, TurnHostedToolsSpecLookup = Callable[[str, str, str, str], Optional[HostedToolSpec]]# The engine release when the engine manifest cannot be read. It names no release, so a refusal learned under it@@ -231,6 +233,17 @@ def executor_candidates(return tuple(first + [candidate for source_id, candidate in candidates.items() if source_id not in order])+def executor_vendors(tool: str) -> tuple[str, ...]:+ """The vendors whose Sources can run a proxied search ``tool``: their executor model's family declares it."""++ vendors = []+ for vendor, entry in bundled_provider_vendors().items():+ family = provider_overlay_entry(vendor, entry.executor_model) if entry.executor_model else None+ if family is not None and any(tool in specs for specs in family.hosted_tools.values()):+ vendors.append(vendor)+ return tuple(sorted(vendors))++@dataclass(frozen=True)class ImageChoice:"""One image model ``image_generate`` may name, on the Source that serves it."""@@ -297,44 +310,61 @@ def image_choices(config: ModelHubConfig, *, evidence: HostedEvidence) -> ImageCreturn ImageChoices((default, *rest), default, saved, saved_choice is not None)-def resolve_hosted_tools(- config: ModelHubConfig,- *,+def freeze_turn_tools(config: ModelHubConfig, *, evidence: HostedEvidence, spec_for: SpecLookup) -> TurnHostedTools:+ """What a Vibey turn's first resolution freezes (§3.4). With no image model, ``image_generate`` is not declared."""++ enabled = enabled_tools(config)+ images = image_choices(config, evidence=evidence).models if IMAGE_TOOL in enabled else ()+ tools = frozenset(tool for tool in enabled if tool != IMAGE_TOOL or images)+ executors = {+ tool: tuple(+ ExecutorSlot(candidate.source.id, candidate.model_id, identity_digest(candidate.source))+ for candidate in executor_candidates(config, tool, evidence=evidence, spec_for=spec_for)+ )+ for tool in tools+ if tool != IMAGE_TOOL+ }+ return TurnHostedTools(tools, executors, images)+++def hop_hosted_tools(+ turn: TurnHostedTools,source: ModelHubSourceConfig,model_id: str,+ *,evidence: HostedEvidence,spec_for: SpecLookup,- frozen: Mapping[str, Optional[tuple[str, str]]] | None = None,) -> dict[str, dict[str, Any]]:- """``HopResolution.hosted_tools`` for a Vibey hop, in the C-6 shape the consumer reads today.+ """``HopResolution.hosted_tools`` for one hop of a turn (C-6 item 7).- The facts are v2's: native when assumed, replay when assumed. The executor- is the first candidate of the chain. ``frozen`` is the turn's tool set and- executors from its first resolution. The image tool is not part of this- shape; it arrives with the HopResolution change.+ A search tool's entry is the hop's own facts; the image entry is the+ turn's frozen enum, with ``params`` and ``size_forms`` as sorted lists so+ the tool schema Vibey renders from them is stable across turns."""- resolved: dict[str, dict[str, Any]] = {}- for tool in MODEL_HUB_SEARCH_TOOLS:- if frozen is not None:- if tool not in frozen:- continue- elif not hosted_tool_setting(config, tool).enabled:- continue+ entries: dict[str, dict[str, Any]] = {}+ for tool in sorted(turn.tools - {IMAGE_TOOL}):facts = hosted_tool_facts(source, model_id, tool, evidence=evidence, spec_for=spec_for)- entry: dict[str, Any] = {"mode": "native" if facts.native == "assumed" else "proxy"}+ entry: dict[str, Any] = {"native": facts.native, "replay": facts.replay}if facts.native == "assumed":entry["declaration"] = dict(facts.declaration or {})entry["include"] = list(facts.include)- if frozen is not None:- bound = frozen[tool]- entry["executor"] = {"source_id": bound[0], "model_id": bound[1]} if bound is not None else None- else:- chain = executor_candidates(config, tool, evidence=evidence, spec_for=spec_for)- entry["executor"] = {"source_id": chain[0].source.id, "model_id": chain[0].model_id} if chain else None- entry["replay"] = facts.replay == "assumed"- resolved[tool] = entry- return resolved+ entries[tool] = entry+ if turn.images:+ entries[IMAGE_TOOL] = {+ "models": [+ {+ "source_id": choice.source_id,+ "model_id": choice.model_id,+ "description": choice.description,+ "params": sorted(choice.params),+ "size_forms": sorted(choice.size_forms),+ }+ for choice in turn.images+ ],+ "default": {"source_id": turn.images[0].source_id, "model_id": turn.images[0].model_id},+ }+ return entries# --- The Tools read (§3.3) ---------------------------------------------------------------------------------------diff --git a/core/handlers/model_hub/hosted_turn.py b/core/handlers/model_hub/hosted_turn.pynew file mode 100644index 000000000..4d2b35bf9--- /dev/null+++ b/core/handlers/model_hub/hosted_turn.py@@ -0,0 +1,36 @@+"""What a Vibey turn freezes about its hosted tools (``vibey-hosted-tools.md`` §3.4, §6).++A turn's first resolution fixes which tools the turn declares, each search+tool's executor order, and the ``image_generate`` enum. Later hops of the turn+recompute only their own facts, and the executor endpoint authorizes every+call against the frozen set, so a settings or Source change applies from the+next turn. ``hosted_tools`` computes it; the turn trace holds it.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import TYPE_CHECKING, Final, Mapping++if TYPE_CHECKING:+ from .hosted_tools import ImageChoice++IMAGE_TOOL: Final = "image_generate"+++@dataclass(frozen=True)+class ExecutorSlot:+ """One executor candidate as the chain was built: its Source identity is checked again at call time."""++ source_id: str+ model_id: str+ identity: str+++@dataclass(frozen=True)+class TurnHostedTools:+ tools: frozenset[str]+ # Per search tool, its effective executor order.+ executors: Mapping[str, tuple[ExecutorSlot, ...]]+ # The image_generate enum, default first; empty when the turn has no image tool.+ images: tuple[ImageChoice, ...] = ()diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex cd9f1fc3d..6552f0ff5 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -41,6 +41,7 @@ from .events import (bounded_diagnostic_detail,event_reason_label,)+from .hosted_turn import TurnHostedToolsfrom .resolver import BackendName, ModelHubTurnResolution, parse_model_hub_timestamp, source_eligible_for_backendfrom .state_file import write_state_document@@ -727,9 +728,9 @@ class TurnTrace:# The request whose surfaced attempt set ``terminal_error``, and that exact# value: a handed-back request withdraws only its own terminal.terminal_error_by: Optional[tuple[str, dict]] = None- # 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: the hosted tools the turn's first resolution froze, with each+ # search tool's executor order. Written once; settings apply next turn.+ hosted_tools: Optional[TurnHostedTools] = 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)@@ -779,10 +780,6 @@ class PreparedGatewayRoute:# without it, but a route under another identity is another route, so its# credential carries the launch identity the gateway compares against.primary_identity: str = ""- # Vibey only: the proxy executor bound for each enabled hosted tool, as- # ``HopResolution.hosted_tools`` states it, with the executor Source's- # identity digest at launch: (tool, (source_id, model_id, identity) | None).- hosted_executors: tuple[tuple[str, tuple[str, str, str] | None], ...] = ()@dataclass(frozen=True)@@ -1370,35 +1367,33 @@ class TurnCorrelationRegistry:return Truereturn bound == identity- def turn_hosted_executors(- self, turn_id: Optional[str],- ) -> tuple[tuple[str, tuple[str, str, str] | None], ...] | None:- """The hosted-tool binding a turn's first resolution froze, or None before it has one."""+ def turn_hosted_tools(self, turn_id: Optional[str]) -> TurnHostedTools | None:+ """The hosted tools a turn's first resolution froze, or None before it has them."""normalized = str(turn_id or "").strip()if not normalized:return Nonewith self._lock:trace = self._traces.get(normalized)- return trace.hosted_executors if trace is not None else None+ return trace.hosted_tools if trace is not None else None- def hosted_executor_bindings(+ def live_hosted_turn(self, *, backend: str, token: str, request_metadata: Mapping[str, str] | None,- ) -> tuple[str, dict[str, tuple[str, str, str] | None]] | None:- """The live turn a request belongs to and the proxy executors it bound, per tool; None without one.+ ) -> tuple[str, TurnHostedTools | None] | None:+ """The live turn a request belongs to and the hosted tools it froze; None without a live turn.Only the turn the request names, while it holds the credential's route- and still admits work, has bindings: a request from a finished,- superseded or unnamed turn, or from a turn being stopped or finalized,- cannot start a call.+ and still admits work, is live: a request from a finished, superseded+ or unnamed turn, or from a turn being stopped or finalized, cannot+ start a call."""with self._lock:owner = self._request_turn(backend, token, request_metadata)if owner is None:return None- credential = self._credential(backend, token)- return owner[0], dict(credential.route.hosted_executors)+ trace = self._traces.get(owner[0])+ return owner[0], trace.hosted_tools if trace is not None else Nonedef gateway_primary_origin(self, *, backend: str, token: str) -> HopOrigin | None:"""Read the immutable launch origin, independent of live turn ownership."""@@ -1644,6 +1639,7 @@ class TurnCorrelationRegistry:scope: ProcessScope,turn_id: str,route: PreparedGatewayRoute,+ hosted_tools: TurnHostedTools | None = None,) -> bool:trace = self._traces.setdefault(turn_id,@@ -1676,8 +1672,8 @@ class TurnCorrelationRegistry:trace.gateway_source_id = route.source_idtrace.gateway_request_model_id = route.gateway_request_model_idtrace.gateway_model_id = route.resolved_model_id- if trace.hosted_executors is None:- trace.hosted_executors = route.hosted_executors+ if trace.hosted_tools is None:+ trace.hosted_tools = hosted_toolsreturn Truedef prepare_gateway_turn(@@ -1692,9 +1688,13 @@ class TurnCorrelationRegistry:via_mapping: bool,gateway_request_model_id: str | None = None,primary_origin: HopOrigin | None = None,- hosted_executors: tuple[tuple[str, tuple[str, str, str] | None], ...] = (),+ hosted_tools: TurnHostedTools | None = None,) -> str:- """Register a route and return its legacy credential or explicit handle."""+ """Register a route and return its legacy credential or explicit handle.++ ``hosted_tools`` is what a Vibey turn's first resolution froze; the+ turn keeps the first it is given.+ """with self._lock:credential = self._credential(backend, token)@@ -1713,7 +1713,6 @@ class TurnCorrelationRegistry:gateway_request_model_id=request_model_id,primary_origin=primary_origin,primary_identity=primary_origin.identity if primary_origin is not None else "",- hosted_executors=hosted_executors,)if scope.request_scoped:@@ -1732,6 +1731,7 @@ class TurnCorrelationRegistry:scope=scope,turn_id=normalized_turn_id,route=prepared,+ hosted_tools=hosted_tools,)return launch_token@@ -1780,6 +1780,7 @@ class TurnCorrelationRegistry:scope=scope,turn_id=route_turn_id,route=prepared,+ hosted_tools=hosted_tools,)return launch_tokendiff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex 04c1180e7..cf04dd801 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -103,6 +103,7 @@ from .catalog_admission import (from .classification import (ResolutionDecision,classify_outcome,+ names_model_refusal,source_settlement_allowed,source_settlement_rule,terminal_outcome_category,@@ -127,6 +128,7 @@ from .evidence_rules import wire_effortfrom .hosted_admission import PIN_UNAVAILABLE_CODE, HostedContent, admits, hosted_contentfrom .hosted_executor import (EXECUTOR_RESPONSE_MAX_BYTES,+ ExecutorCall,ExecutorCallRefused,ExecutorResponseRefused,ResponsesStreamReader,@@ -139,16 +141,19 @@ from .hosted_executor import (provider_charges,responses_result,)+from .hosted_turn import ExecutorSlot, TurnHostedToolsfrom .hosted_tools import (+ ExecutorCandidate,HostedEvidence,HostedToolSettingRefused,apply_hosted_tool_put,clear_request,- credential_eligible,engine_stamp,+ executor_candidates,+ executor_vendors,+ freeze_turn_tools,+ hop_hosted_tools,hosted_tools_status,- resolve_hosted_tools,- untranslated,)from .identifiers import (OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL,@@ -789,10 +794,19 @@ def _pinned_hop(request: Any, backend: str) -> tuple[str, str | None] | None:return getattr(request, "pinned_hop", None) if backend == "vibey" else None-def _pin_unavailable() -> ModelHubError:- """The pinned hop cannot serve this request before output (``vibey-hosted-tools.md`` §3.5)."""+def _pin_unavailable(learned: LearnedEvidence | None = None, source_id: str = "") -> ModelHubError:+ """The pinned hop cannot serve this request before output (``vibey-hosted-tools.md`` §3.5).- return ModelHubError(PIN_UNAVAILABLE_CODE, status=409)+ ``learned`` is the hosted feature a narrow rule just refused on that hop;+ only then does the answer carry a ``reason``.+ """++ reason = (+ {"kind": "hosted_unsupported", "tool": learned.feature.name, "aspect": learned.feature.aspect,+ "source_id": source_id}+ if learned is not None else None+ )+ return ModelHubError(PIN_UNAVAILABLE_CODE, status=409, data={"reason": reason} if reason else None)class UserTestCall(NamedTuple):@@ -838,6 +852,41 @@ def _executor_failure(outcome: RawCallOutcome | None, say: Callable[..., str], *return say("modelHub.hostedTools.providerRefused", detail=detail or outcome.kind.value)+def _cost_payload(cost: HostedCost) -> dict[str, Any]:+ return {"basis": cost.basis} if cost.usd is None else {"basis": cost.basis, "usd": cost.usd}+++@dataclass(frozen=True)+class _ExecutorAttempt:+ """One executor candidate a search chain called, as it settled (``vibey-hosted-tools.md`` §6)."""++ source: ModelHubSourceConfig+ model_id: str+ record: dict[str, Any]+ cost: Optional[HostedCost]+ # Whether the provider could have charged for it: it reported tokens or produced a response.+ billable: bool+ # Whether its failure passes the search to the next candidate.+ moves_on: bool++ def execution(self) -> dict[str, Any]:+ execution: dict[str, Any] = {+ "mode": "proxy",+ "executor_origin": {"provider": self.source.vendor, "api": self.source.protocol, "model": self.model_id},+ "executor_source_id": self.source.id,+ "executor_billing": self.source.billing,+ }+ if self.cost is not None:+ execution["cost"] = _cost_payload(self.cost)+ return execution++ def failed_attempt(self) -> dict[str, Any]:+ attempt: dict[str, Any] = {"source_id": self.source.id, "billing": self.source.billing}+ if self.cost is not None:+ attempt["cost"] = _cost_payload(self.cost)+ return attempt++def _sent_effort(backend: str, source: ModelHubSourceConfig, model_id: str, effort: str) -> Optional[str]:"""The effort token ``backend`` sends a hop for the menu value ``effort``: the key its evidence is held under.@@ -889,6 +938,9 @@ class ResolvedInvocation:settlement_generation: Optional[int] = Noneverification_pending: Optional[str] = Noneorigin: HopOrigin | None = None+ # Vibey: the catalog tools the request declared natively, which a served+ # response may prove ran (``vibey-hosted-tools.md`` §3.2).+ hosted_calls: frozenset[str] = frozenset()@dataclass(frozen=True)@@ -6378,48 +6430,48 @@ class ModelHubService:basis, usd = pricedreturn HostedCost(basis=basis, usd=None if usd is None else round(usd, 6))- @staticmethod- def _hosted_executor(config: ModelHubConfig, source_id: str, model_id: str, tool: str, identity: str):- """The bound executor Source if it can still run this tool, else None.-- The binding is the turn's: ordinary Source edits apply from the next- turn. A removed or ineligible Source refuses it, and so does one whose- identity (base URL, credential, ...) changed since launch: the engine- no longer holds the bound credential, and the new one was never- verified. A Claude subscription never runs a hosted tool.+ def _admitted_executor(self, slot: ExecutorSlot, tool: str) -> ExecutorCandidate | None:+ """The chain's candidate as the current snapshot admits it, else None (``vibey-hosted-tools.md`` §6).++ The turn froze the order, not the Sources' runtime: a Source that is+ removed, no longer runs the tool on its executor model, or has refused+ it since is passed over, and so is one whose identity (base URL,+ credential, ...) changed since the chain was built. It reads the config,+ which grows with use: call it off the controller loop."""- source = next((item for item in config.sources if item.id == source_id), None)- if (- source is None- or identity_digest(source) != identity- or source.supply_channel != "hub"- or not source.credential_ref- or not credential_eligible(source)- or not untranslated(source)- ):- return None- spec = hosted_tool_spec(source.vendor, source.protocol, model_id, tool)- return (source, spec) if spec is not None else None+ config = self.store.load()++ return next(+ (+ candidate+ for candidate in executor_candidates(+ config, tool, evidence=self.hosted_evidence(), spec_for=hosted_tool_spec,+ )+ if (candidate.source.id, candidate.model_id) == (slot.source_id, slot.model_id)+ and identity_digest(candidate.source) == slot.identity+ ),+ None,+ )async def run_hosted_tool(self,tool: str,payload: object,*,- bindings: Mapping[str, tuple[str, str, str] | None] | None,+ turn: TurnHostedTools | None,language: str = "en",) -> dict:- """Run one proxied hosted call on the executor bound for its turn (``vibey-hosted-tools.md`` §3.4).-- ``bindings`` are the executors the caller's live turn bound, per tool,- with each executor Source's identity at launch (None without a live- turn). The call must name exactly that binding:- the gateway runs it and no other, with no failover and no Source- switch. A call that reaches no executor answers a failed record without- an execution; one that ran carries its ``ProxyExecution`` and is- metered on the executor Source. It never changes Source health: a- proxy call is a tool call, not the turn's model hop.+ """Run one proxied search on its turn's executor chain (``vibey-hosted-tools.md`` §6).++ ``turn`` is what the caller's live turn froze; a tool outside it is+ refused, unrun. The chain tries the turn's executors in order, each+ admitted on the snapshot it is called on, within one deadline. It moves+ on after a failure normal routing fails over from, a narrow-rule+ refusal, a refusal of the executor model, or a failure mid-response;+ any other outcome ends it. Every candidate called is metered on its own+ Source. A proxy call never changes Source health: it is a tool call,+ not the turn's model hop."""def say(key: str, **params: str) -> str:@@ -6430,26 +6482,57 @@ class ModelHubService:call = await asyncio.to_thread(parse_call, tool, payload)except ExecutorCallRefused as refused:raise ModelHubError(refused.code, status=refused.status) from None- binding = bindings.get(tool, False) if bindings is not None else False- if binding is False or (binding[:2] if binding is not None else None) != call.executor:- raise ModelHubError("executor_not_bound", status=409)- if binding is None:- return {"record": failed_record(say("modelHub.hostedTools.noExecutor", tool=tool))}- source_id, model_id, identity = binding- unavailable = {"record": failed_record(say("modelHub.hostedTools.executorUnavailable", tool=tool))}- bound = self._hosted_executor(self.store.load(), source_id, model_id, tool, identity)- if bound is None:- return unavailable- source, spec = bound- request = executor_request(call, source, model_id, spec)+ if turn is None or tool not in turn.tools:+ raise ModelHubError("tool_not_enabled", status=409)+ loop = asyncio.get_running_loop()+ deadline = loop.time() + call_timeout(tool)+ attempts: list[_ExecutorAttempt] = []+ for slot in turn.executors.get(tool, ()):+ if loop.time() >= deadline:+ break+ attempt = await self._executor_attempt(call, slot, deadline=deadline, say=say)+ if attempt is None:+ continue+ attempts.append(attempt)+ if not attempt.moves_on:+ break+ if not attempts:+ vendors = ", ".join(catalog_api_key_vendor_label(vendor) or vendor for vendor in executor_vendors(tool))+ return {"record": failed_record(say("modelHub.hostedTools.noExecutor", tool=tool, vendors=vendors))}+ # The record is the last attempt's; earlier billable ones are listed, each with its own billing.+ last = attempts[-1]+ record = last.record+ if last.moves_on:+ # Every candidate was tried and failed: say which, so the user sees whether retrying or those Sources is the issue.+ tried = ", ".join(dict.fromkeys(attempt.source.display_name for attempt in attempts))+ record = failed_record(+ f"{record.get('error') or ''} {say('modelHub.hostedTools.triedSources', sources=tried)}".strip(),+ record.get("sources"),+ )+ execution = last.execution()+ failed_attempts = [attempt.failed_attempt() for attempt in attempts[:-1] if attempt.billable]+ if failed_attempts:+ execution["failed_attempts"] = failed_attempts+ return {"record": record, "execution": execution}++ async def _executor_attempt(+ self,+ call: ExecutorCall,+ slot: ExecutorSlot,+ *,+ deadline: float,+ say: Callable[..., str],+ ) -> _ExecutorAttempt | None:+ """Call one executor candidate; None when this snapshot does not admit it, so nothing ran."""++ tool, model_id = call.tool, slot.model_id+ candidate = await asyncio.to_thread(self._admitted_executor, slot, tool)+ if candidate is None:+ return None+ source = candidate.source+ request = executor_request(call, source, model_id, candidate.declaration, candidate.include)stream = executor_streams(source)- declaration = spec.declaration- reader = (- ResponsesStreamReader(- partial_images=declaration.get("partial_images", 0) if tool == "image_generation" else None,- )- if stream else None- )+ reader = ResponsesStreamReader() if stream else Nonebody = bytearray()handle = Nonecancelled_observed: ProtocolSSEState | None = None@@ -6458,7 +6541,7 @@ class ModelHubService:refused: str | None = Noneasync def invoke() -> None:- nonlocal handle, outcome, admitted, refused, cancelled_observed+ nonlocal handle, outcome, admitted, refused, cancelled_observed, sourcewhile True:await self._prepare_engine_for_demand()await self._mutation_lock.acquire()@@ -6476,8 +6559,12 @@ class ModelHubService:release_owner()try:- if self._hosted_executor(self.store.load(), source_id, model_id, tool, identity) is None:+ # Admitted again on the snapshot the call is made on, under the lock. The call and+ # everything it reports (billing, cost, the Source's name) follow that snapshot.+ final = await asyncio.to_thread(self._admitted_executor, slot, tool)+ if final is None:return+ source = final.sourceif not self._engine_synced:continuetry:@@ -6499,7 +6586,6 @@ class ModelHubService:try:async for chunk in handle.stream:if reader is not None:- # An image event is megabytes of JSON: parse it off the controller loop.await asyncio.to_thread(reader.feed, chunk)elif len(body) + len(chunk) > EXECUTOR_RESPONSE_MAX_BYTES:raise ExecutorResponseRefused("modelHub.hostedTools.tooLarge")@@ -6536,9 +6622,11 @@ class ModelHubService:at=ended_at,)+ timed_out = Falsetry:- await asyncio.wait_for(invoke(), timeout=call_timeout(tool))+ await asyncio.wait_for(invoke(), timeout=max(0.0, deadline - asyncio.get_running_loop().time()))except asyncio.TimeoutError:+ timed_out = Trueif admitted:outcome = RawCallOutcome(kind=RawOutcomeKind.TIMEOUT, http_status=None, error_code=None, redacted_message=None,@@ -6547,7 +6635,7 @@ class ModelHubService:except ModelHubError as error:if not admitted:logger.info("Model Hub hosted-tool executor was not reached: %s", error.code)- return unavailable+ return Noneoutcome = RawCallOutcome(kind=RawOutcomeKind.NETWORK_ERROR, http_status=None, error_code=error.code, redacted_message=None,stream_started=False, model_id=model_id, source_id=source.id,@@ -6565,7 +6653,7 @@ class ModelHubService:passraise cancelledif not admitted:- return unavailable+ return Nonefailure = _executor_failure(outcome, say, refused=refused)if reader is not None:result = await asyncio.to_thread(responses_result, tool, reader.readout, say, failure=failure)@@ -6574,49 +6662,71 @@ class ModelHubService:else:# The bytearray itself goes to the worker: no copy of up to the response budget on the loop.result = await asyncio.to_thread(anthropic_result, body, say)- execution: dict[str, Any] = {- "mode": "proxy",- "executor_origin": {"provider": source.vendor, "api": source.protocol, "model": model_id},- "executor_source_id": source.id,- "executor_billing": source.billing,- }+ usage = _call_usage(outcome, handle.observed if handle is not None else cancelled_observed)# The call's cost is the pricing module's, from what the meter saw and what the provider reported.counts, reported_usd = provider_charges(source.protocol, result.usage if result is not None else None)- cost = self.hosted_call_cost(- source, model_id, (tool,),- usage=_call_usage(outcome, handle.observed if handle is not None else cancelled_observed),- counts=counts, reported_usd=reported_usd,- )- if cost is not None:- execution["cost"] = {"basis": cost.basis} if cost.usd is None else {"basis": cost.basis, "usd": cost.usd}- if result is None:- return {"record": failed_record(failure or say("modelHub.hostedTools.unreadable")), "execution": execution}- answer: dict[str, Any] = {"record": result.record, "execution": execution}- if result.generation is not None:- answer["generation"] = result.generation- answer["images"] = list(result.images)- return answer+ cost = self.hosted_call_cost(source, model_id, (tool,), usage=usage, counts=counts, reported_usd=reported_usd)+ if outcome is not None and tool in outcome.hosted_tools and result is not None and result.record["status"] == "completed":+ # A proxy call is a native call on the executor Source: the same positive evidence (§3.2).+ await self.record_hosted_success(source, model_id, tool, "executor")+ # A response that broke a bound reached nothing of Vibey's, so it is a failure before output here (§6+ # step 4): the next candidate is tried. A timeout spent the chain's one deadline.+ moves_on = refused is not None+ if outcome is not None and outcome.kind is not RawOutcomeKind.SUCCESS and refused is None and not timed_out:+ moves_on = await self._executor_moves_on(source, model_id, tool, request, outcome)+ return _ExecutorAttempt(+ source=source,+ model_id=model_id,+ record=(+ result.record if result is not None+ else failed_record(failure or say("modelHub.hostedTools.unreadable"))+ ),+ cost=cost,+ # A call that produced nothing and reported no tokens was not billed.+ billable=usage is not None or (+ outcome is not None and (outcome.stream_started or outcome.kind is RawOutcomeKind.SUCCESS)+ ),+ moves_on=moves_on,+ )- def hosted_tools_for_hop(+ async def _executor_moves_on(self,- config: ModelHubConfig,source: ModelHubSourceConfig,model_id: str,- frozen: Mapping[str, tuple[str, str] | None] | None = None,- ) -> dict:- """``HopResolution.hosted_tools`` for a Vibey launch served by this Source and model.+ tool: str,+ request: ModelHubRequest,+ outcome: RawCallOutcome,+ ) -> bool:+ """Whether a failed executor call passes the search to the next candidate (§6 step 4).- ``frozen`` is the turn's tool set and executors from its first resolution.+ Nothing reaches Vibey until the chain returns, so a failure mid-response+ counts as before output here. A narrow rule's refusal records its+ evidence, as on any hop. A refusal of the executor model records that+ the Source does not run the tool on it, so the Source leaves the chain+ until the refusal is cleared or its wire stamp changes."""- return resolve_hosted_tools(- config,- source=source,- model_id=model_id,- evidence=self.hosted_evidence(),- spec_for=hosted_tool_spec,- frozen=frozen,- )+ learned = await self._learn_capability_evidence(source, model_id, request, outcome)+ if learned is not None and learned.feature.kind == "hosted_tool":+ return True+ if not outcome.stream_started and names_model_refusal(outcome):+ detail = f"{outcome.http_status or 'error'} {outcome.error_code or outcome.error_type or 'model'}"[:64]+ await self.record_hosted_refusals(source, ((model_id, EvidenceFeature.hosted(tool, "call"), detail),))+ return True+ decision = classify_outcome(replace(outcome, stream_started=False))+ return decision.action in {"fallback", "refresh"}++ def freeze_turn_hosted_tools(self, config: ModelHubConfig) -> TurnHostedTools:+ """What a Vibey turn's first resolution freezes: its tools, executor orders and image models (§3.4)."""++ return freeze_turn_tools(config, evidence=self.hosted_evidence(), spec_for=hosted_tool_spec)++ def hosted_tools_for_hop(+ self, source: ModelHubSourceConfig, model_id: str, turn: TurnHostedTools,+ ) -> dict:+ """``HopResolution.hosted_tools`` for a hop of a Vibey turn served by this Source and model."""++ return hop_hosted_tools(turn, source, model_id, evidence=self.hosted_evidence(), spec_for=hosted_tool_spec)async def set_agent_mode(self, backend: str, mode: object) -> dict:if mode not in {"hub", "direct"} or (backend == "vibey" and mode != "hub"):@@ -9427,6 +9537,7 @@ class ModelHubService:await self._verify_successful_source(resolved.source_id, resolved.credential_ref, resolved.verification_pending, outcome,)+ await self._record_native_successes(resolved, outcome)return HandleSettlement(outcome=outcome,decision=decision,@@ -9472,6 +9583,25 @@ class ModelHubService:),)+ async def _record_native_successes(self, resolved: ResolvedInvocation, outcome: RawCallOutcome) -> None:+ """Positive evidence for each natively declared tool the served response proves ran (§3.2).++ Display-only history, written after the response completed. It is+ keyed on the identity the hop was resolved under: a Source changed+ since is not vouched for.+ """++ proven = resolved.hosted_calls & outcome.hosted_tools+ if not proven or resolved.origin is None:+ return+ # The config grows with use: read it off the controller loop.+ config = await asyncio.to_thread(self.store.load)+ source = next((item for item in config.sources if item.id == resolved.source_id), None)+ if source is None or identity_digest(source) != resolved.origin.identity:+ return+ for tool in sorted(proven):+ await self.record_hosted_success(source, resolved.model_id, tool, "native")+def _emit_switch(self,*,@@ -10031,7 +10161,10 @@ class ModelHubService:if source is None or target_model is None:raise AssertionError("runnable hop must have an exact identity")verification_pending = source.verification_pending- origin = HopOrigin(source.vendor, source.protocol, target_model, source.id) if backend == "vibey" else None+ origin = (+ HopOrigin(source.vendor, source.protocol, target_model, source.id, identity_digest(source))+ if backend == "vibey" else None+ )if source.supply_channel == "native_cli":self._emit_switch(agent=event_agent,@@ -10141,6 +10274,7 @@ class ModelHubService:settlement_generation=settlement_generation,verification_pending=verification_pending,origin=origin,+ hosted_calls=frozenset(tool for tool, _type in hosted.calls),)decision = await self._classify_source_outcome(source, outcome)learned = await self._learn_capability_evidence(source, target_model, request, outcome)@@ -10206,6 +10340,7 @@ class ModelHubService:settlement_generation=settlement_generation,verification_pending=verification_pending,origin=origin,+ hosted_calls=frozenset(tool for tool, _type in hosted.calls),)decision = classify_outcome(outcome, refresh_attempted=True)learned = await self._learn_capability_evidence(source, target_model, request, outcome)@@ -10273,7 +10408,7 @@ class ModelHubService:# its evidence: the pinned hop cannot take this content, so the# request goes back to Vibey for its portable form.self.recovery.release(source.id, settlement_generation)- raise _pin_unavailable()+ raise _pin_unavailable(learned, source.id)if decision.action == "surface":self.recovery.release(source.id, settlement_generation)source_transition_persisted: bool | None = Nonediff --git a/core/handlers/model_hub/stream_wire.py b/core/handlers/model_hub/stream_wire.pyindex 089d2f8b4..887636a46 100644--- a/core/handlers/model_hub/stream_wire.py+++ b/core/handlers/model_hub/stream_wire.py@@ -7,6 +7,7 @@ from dataclasses import dataclass, fieldfrom typing import AbstractSet, BinaryIO, Callable, Final, Literal, Mappingfrom .async_owner import run_owned_in_thread+from .hosted_items import responses_item_succeededfrom .json_wire import JSONEvent, JSONPath, JSONScope, SelectiveJSONParser@@ -467,6 +468,24 @@ class ProtocolObservation:recovery_verified: bool = False# Raw upstream text, for bounded redacted display only; never in reprs.error_message: str | None = field(default=None, repr=False)+ # Search tools whose own completed hosted item this response carried (§3.2).+ hosted_tools: frozenset[str] = frozenset()+++@dataclass(frozen=True)+class HostedItemPaths:+ """Where a protocol carries its own hosted-tool items (``vibey-hosted-tools.md`` §3.2).++ A streamed response carries one item per ``event_type`` event, at+ ``event_item``; a buffered one carries them in the ``buffered_items`` array.+ ``leaves`` are the item fields that say which tool ran and whether it+ completed, relative to the item.+ """++ event_type: str+ event_item: JSONPath+ buffered_items: JSONPath+ leaves: tuple[JSONPath, ...]@dataclass(frozen=True)@@ -524,6 +543,7 @@ class ProtocolStreamTaxonomy:buffered_success_selectors: tuple[tuple[JSONPath, tuple[str, ...]], ...] = ()buffered_output_array_path: JSONPath | None = Nonebuffered_terminal_string_paths: tuple[JSONPath, ...] = ()+ hosted_items: HostedItemPaths | None = NonePROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {@@ -596,6 +616,11 @@ PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {buffered_error_envelope_paths=(("error",),),buffered_success_selectors=((("type",), ("message",)),),buffered_output_array_path=("content",),+ # A server tool's result block arrives whole in its start event; its+ # ``content`` is the result list, or the error object on a failed search.+ hosted_items=HostedItemPaths(+ "content_block_start", ("content_block",), ("content",), (("type",), ("content",), ("content", "type")),+ ),terminal_event_name="error",render_terminal_event=_anthropic_terminal_event,usage=ProtocolUsageTaxonomy(@@ -710,12 +735,6 @@ PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {("type",),"response.function_call_arguments.delta",),- ProtocolModelOutputEnvelope(- # https://platform.openai.com/docs/api-reference/responses-streaming/response/image-generation-call/partial-image- "response.image_generation_call.partial_image",- ("type",),- "response.image_generation_call.partial_image",- ),),success_literal=None,sequence_number_path=("sequence_number",),@@ -725,6 +744,9 @@ PROTOCOL_STREAM_TAXONOMY: Final[Mapping[str, ProtocolStreamTaxonomy]] = {(("status",), ("completed", "incomplete")),),buffered_output_array_path=("output",),+ hosted_items=HostedItemPaths(+ "response.output_item.done", ("item",), ("output",), (("type",), ("name",), ("status",)),+ ),terminal_event_name="error",render_terminal_event=_responses_terminal_event,usage=ProtocolUsageTaxonomy(@@ -939,6 +961,30 @@ def _usage_from_scalar_paths(return report+# Container markers for a hosted item's fields; scalars keep their value.+_ARRAY: Final = object()+_MAP: Final = object()+# The buffered response items whose fields are kept; a response carries a few.+_MAX_HOSTED_MEMBERS: Final = 256+++def _hosted_item_tool(protocol: str, fields: Mapping[JSONPath, object]) -> str | None:+ """The search tool one hosted item proves ran to completion, or None (``vibey-hosted-tools.md`` §3.2)."""++ def text(leaf: JSONPath) -> str | None:+ value = fields.get(leaf)+ return value if isinstance(value, str) else None++ if protocol == "openai_responses":+ return responses_item_succeeded(text(("type",)), text(("name",)), text(("status",)))+ if protocol == "anthropic":+ # A failed search arrives under the same block type with an error object as+ # its content; only a result list proves the search ran.+ if text(("type",)) == "web_search_tool_result" and fields.get(("content",)) is _ARRAY:+ return "web_search"+ return None++def _protocol_projection_paths(protocol: str) -> frozenset[JSONPath]:taxonomy = PROTOCOL_STREAM_TAXONOMY[protocol]paths: set[JSONPath] = {()}@@ -959,6 +1005,10 @@ def _protocol_projection_paths(protocol: str) -> frozenset[JSONPath]:)if taxonomy.sequence_number_path is not None:paths.add(taxonomy.sequence_number_path)+ if taxonomy.hosted_items is not None:+ items = taxonomy.hosted_items+ paths.update((*items.event_item, *leaf) for leaf in items.leaves)+ paths.update((*items.buffered_items, "*", *leaf) for leaf in items.leaves)for container_path in taxonomy.usage.container_paths:for leaf_paths in (taxonomy.usage.input_paths,@@ -1021,6 +1071,15 @@ class ProtocolFactProjector:self._scalars: dict[JSONPath, object] = {}self._literal = bytearray()self._literal_too_long = False+ items = self.taxonomy.hosted_items+ # A buffered response's hosted items are array members: their fields are+ # kept per member, a few short values each, for a bounded number of members.+ self._member_leaves: dict[JSONPath, JSONPath] = (+ {(*items.buffered_items, "*", *leaf): leaf for leaf in items.leaves} if items is not None else {}+ )+ self._member_path: JSONPath | None = (*items.buffered_items, "*") if items is not None else None+ self._member_values: dict[JSONScope, dict[JSONPath, object]] = {}+ self._members: list[dict[JSONPath, object]] = []self._parser = SelectiveJSONParser(_protocol_projection_paths(protocol),self._visit,@@ -1062,6 +1121,7 @@ class ProtocolFactProjector:return ProtocolObservation(outcome="served" if not streamed else None)usage = _usage_from_scalar_paths(self.taxonomy.usage, self._scalars)+ hosted_tools = self._hosted_tools(streamed=streamed)model_output_started = any(envelope.event_name == event_name and self._selector_matches(envelope)for envelope in self.taxonomy.model_output_envelopes@@ -1082,6 +1142,7 @@ class ProtocolFactProjector:code_candidates = self._machine_candidates("code", matched_paths)return ProtocolObservation(outcome="failed_terminal" if matched_paths else "served",+ hosted_tools=frozenset() if matched_paths else hosted_tools,error_envelope_paths=matched_paths,error_message=self._error_message(matched_paths),usage=usage,@@ -1139,14 +1200,39 @@ class ProtocolFactProjector:else ()),recovery_verified=model_output_started or envelope.terminal_outcome == "served",+ hosted_tools=hosted_tools,)return ProtocolObservation(model_output_started=model_output_started,sequence_number=sequence_number,usage=usage,recovery_verified=model_output_started,+ hosted_tools=hosted_tools,)+ def _hosted_tools(self, *, streamed: bool) -> frozenset[str]:+ """The search tools whose own completed item this event or buffered response carries."""++ items = self.taxonomy.hosted_items+ if items is None:+ return frozenset()+ if streamed:+ if self._scalars.get(("type",)) != items.event_type:+ return frozenset()+ members = [{leaf: self._field((*items.event_item, *leaf)) for leaf in items.leaves}]+ else:+ members = self._members+ return frozenset(+ tool for fields in members if (tool := _hosted_item_tool(self.protocol, fields)) is not None+ )++ def _field(self, path: JSONPath) -> object:+ if path in self._arrays:+ return _ARRAY+ if path in self._maps:+ return _MAP+ return self._scalars.get(path)+def _visit(self,path: JSONPath,@@ -1154,6 +1240,13 @@ class ProtocolFactProjector:value: object | None,scope: JSONScope,) -> None:+ if scope and path in self._member_leaves and len(self._members) < _MAX_HOSTED_MEMBERS:+ value_of = {"scalar": value, "start_array": _ARRAY, "start_map": _MAP}+ if event in value_of:+ self._member_values.setdefault(scope, {})[self._member_leaves[path]] = value_of[event]+ if event == "scope_end" and path == self._member_path:+ if (member := self._member_values.pop(scope, None)) is not None and len(self._members) < _MAX_HOSTED_MEMBERS:+ self._members.append(member)if event == "replace":self._clear_path(path, scope)elif event == "start_map" and not scope:@@ -1410,6 +1503,7 @@ class ProtocolSSEState:error_type_candidates: tuple[str, ...] = ()error_code_candidates: tuple[str, ...] = ()error_message: str | None = field(default=None, repr=False)+ hosted_tools: frozenset[str] = frozenset()def __post_init__(self) -> None:self.tokenizer = SSEObservationTokenizer(self.protocol)@@ -1464,6 +1558,8 @@ class ProtocolSSEState:returnif observation.model_output_started:self.model_output_started = True+ if observation.hosted_tools:+ self.hosted_tools |= observation.hosted_toolsif observation.usage is not None:self.usage = (observation.usage if self.usage is None else self.usage.merge(observation.usage)@@ -1507,6 +1603,7 @@ class ProtocolSSEState:error_code_candidates=self.error_code_candidates,recovery_verified=self.reached_model,error_message=self.error_message,+ hosted_tools=self.hosted_tools if self.terminal_outcome == "served" else frozenset(),)return Nonediff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex ad147f0de..5d9a764ce 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -11,7 +11,7 @@ import socketimport tempfilefrom collections import dequefrom collections.abc import AsyncIterator, Callable, Mapping-from contextlib import AsyncExitStack, asynccontextmanager, contextmanager, nullcontext, suppress+from contextlib import AsyncExitStack, asynccontextmanager, contextmanager, suppressfrom dataclasses import dataclass, field, replacefrom datetime import datetime, timezonefrom typing import BinaryIO, Final, Optional@@ -46,6 +46,7 @@ from .provenance import (render_turn_outcome_copy,)from .hosted_admission import PIN_MODEL_HEADER, PIN_SOURCE_HEADER, PIN_UNAVAILABLE_CODE+from .hosted_turn import TurnHostedToolsfrom .request import FORWARDED_CALLER_HEADERS, ModelHubRequestfrom .retry import RECOVERY_EXHAUSTED_CODE, RECOVERY_EXHAUSTED_MESSAGEfrom .resolver import parse_model_hub_timestamp@@ -562,7 +563,7 @@ class ModelHubTurnGateway:gateway_request_model_id: Optional[str] = None,request_scoped: bool = False,primary_origin: HopOrigin | None = None,- hosted_executors: tuple[tuple[str, tuple[str, str, str] | None], ...] = (),+ hosted_tools: TurnHostedTools | None = None,) -> tuple[str, str]:if backend not in MODEL_HUB_BACKENDS:raise ModelHubError("mapping_target_unavailable", status=409)@@ -596,7 +597,7 @@ class ModelHubTurnGateway:via_mapping=via_mapping,gateway_request_model_id=gateway_request_model_id,primary_origin=primary_origin,- hosted_executors=hosted_executors,+ hosted_tools=hosted_tools,)except PreparedGatewayRouteConflict:raise ModelHubError("mapping_target_unavailable", status=409) from None@@ -690,11 +691,13 @@ class ModelHubTurnGateway:return Noneasync def _handle_hosted_tool(self, request: web.Request) -> web.StreamResponse:- """Run one proxied hosted call for a Vibey turn (``vibey-hosted-tools.md`` §3.4).+ """Run one hosted call for a live Vibey turn (``vibey-hosted-tools.md`` §6).- Authenticated with the turn's gateway token. Every outcome of a- well-formed call is a 200 carrying its canonical record; only a- malformed call is an error status.+ Authenticated with the turn's gateway token and authorized by what the+ turn froze. Every outcome of a well-formed, authorized call is a 200+ carrying its canonical record; only a malformed call, or one its turn+ cannot make (``turn_not_live``, ``tool_not_enabled``), is an error+ status, and nothing runs."""def refused(status: int, code: str) -> web.Response:@@ -707,6 +710,15 @@ class ModelHubTurnGateway:token = self._authorized_token(request, "vibey")if token is None:return refused(401, "authentication_error")++ def live_turn() -> tuple[str, TurnHostedTools | None] | None:+ return self.correlation.live_hosted_turn(+ backend="vibey", token=token, request_metadata=_request_metadata("vibey", request),+ )++ # A turn that admits no more work is answered first, before its body is read.+ if live_turn() is None:+ return refused(409, "turn_not_live")# Every step proportional to the request or the answer runs off the# controller loop; the call's arguments are small, so the body is bounded.# The bound is on the bytes parsed: an encoded body would be inflated@@ -722,23 +734,22 @@ class ModelHubTurnGateway:payload = await asyncio.to_thread(json.loads, raw)except (ValueError, RecursionError):return refused(400, "invalid_request_error")- # Checked and owned with no await between them: once admitted, the+ # Checked again and owned with no await between them: once admitted, the# call belongs to its turn, and stopping or finalizing the turn ends it.- live = self.correlation.hosted_executor_bindings(- backend="vibey", token=token, request_metadata=_request_metadata("vibey", request),- )+ live = live_turn()+ if live is None:+ return refused(409, "turn_not_live")try:- with self._own_turn_call(live[0]) if live is not None else nullcontext():+ with self._own_turn_call(live[0]):result = await self.service.run_hosted_tool(request.match_info["tool"],payload,- # Only the executor the caller's live turn bound may run.- bindings=live[1] if live is not None else None,+ # Only what the caller's live turn froze may run.+ turn=live[1],language=self._language_provider() or "en",)except ModelHubError as exc:return refused(exc.status, exc.code)- # An image answer carries megabytes of base64: encode it off the loop.body = await asyncio.to_thread(lambda: json.dumps(result).encode("utf-8"))return web.Response(body=body,@@ -1157,8 +1168,12 @@ class ModelHubTurnGateway:# Never shown to the user: Vibey re-renders the request in# portable form and sends it again unpinned in this same turn.terminalizer.hand_back()+ error = {"type": "model_hub_pin_unavailable", "code": PIN_UNAVAILABLE_CODE}+ if "reason" in exc.data:+ # Which hosted feature a narrow rule refused on the pinned hop.+ error["reason"] = exc.data["reason"]return web.json_response(- {"type": "error", "error": {"type": "model_hub_pin_unavailable", "code": PIN_UNAVAILABLE_CODE}},+ {"type": "error", "error": error},status=409,headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},)diff --git a/core/hosted_activity.py b/core/hosted_activity.pyindex 37031cd01..3a472d1a1 100644--- a/core/hosted_activity.py+++ b/core/hosted_activity.py@@ -28,6 +28,7 @@ from core.agent_core.messages import (HostedResult,HostedSource,HostedToolBlock,+ ProxyExecution,ToolCallBlock,)from vibe.i18n import t as i18n_t@@ -50,7 +51,8 @@ class HostedActivity:call_id: strtool: str- mode: Literal["native", "proxy"]+ # How it ran: natively by the model's provider, by a search executor, or by an image endpoint directly.+ mode: Literal["native", "proxy", "direct"]status: str# Model-facing English; ``error_code`` names the reasons Avibe worded itself.error: Optional[str]@@ -228,7 +230,8 @@ def proxy_activity(source_names: SourceNames = _no_names,duration_ms: Optional[int] = None,) -> HostedActivity:- """A proxied hosted call: the model's own call, and the record its executor returned."""+ """A hosted call that ran outside the model: the model's own call, and the record its search executor+ (``proxy``) or image endpoint (``direct``) returned."""arguments = call.arguments if isinstance(call.arguments, dict) else {}subject = next(@@ -237,13 +240,14 @@ def proxy_activity()size = arguments.get("size") if isinstance(arguments.get("size"), str) else Noneexecution = result.execution+ cost, cost_calls = _chain_cost(execution)# What the executor reports it did (an image's rendered prompt and resolved size and quality), read as a native# call's block action is.ran = result.action if result.action is not None and result.action.type == "generate" else Nonereturn HostedActivity(call_id=call.id,tool=call.name,- mode="proxy",+ mode=execution.mode if execution is not None else "proxy",status=result.record.status,error=result.record.error,error_code=result.record.error_code,@@ -259,12 +263,32 @@ def proxy_activity(size=(ran.size if ran is not None and ran.size else size),quality=ran.quality if ran is not None else None,revised_prompt=ran.prompt if ran is not None else None,- cost=execution.cost if execution is not None else None,- cost_calls=1,+ cost=cost,+ cost_calls=cost_calls,duration_ms=duration_ms,)+def _chain_cost(execution: Optional[ProxyExecution]) -> tuple[Optional[HostedCost], int]:+ """What a proxied call cost over every executor attempt it billed, and how many attempts that is (§6).++ ``execution.cost`` is the last attempt's own, and ``failed_attempts`` the earlier billed ones. Every attempt+ included is ``included``; otherwise the known figures are summed, ``reported`` only when each is. An attempt+ without a cost leaves the total unknown rather than understated.+ """++ if execution is None:+ return None, 1+ costs = [*(attempt.cost for attempt in execution.failed_attempts), execution.cost]+ if any(cost is None for cost in costs):+ return None, len(costs)+ if all(cost.basis == "included" for cost in costs):+ return HostedCost(basis="included"), len(costs)+ priced = [cost for cost in costs if cost.basis != "included"]+ basis = "reported" if all(cost.basis == "reported" for cost in priced) else "list"+ return HostedCost(basis=basis, usd=round(sum(cost.usd or 0.0 for cost in priced), 6)), len(costs)++def _vendor_label(provider: Optional[str]) -> Optional[str]:if not provider:return None@@ -286,7 +310,7 @@ def _clip(text: str, limit: int = LINE_SUBJECT_MAX_CHARS) -> str:def _count(activity: HostedActivity, lang: str) -> Optional[str]:- if activity.tool == "image_generation":+ if activity.tool == "image_generate":count, unit = len(activity.images), "image"elif activity.tool == "x_search":count, unit = len(activity.sources), "post"@@ -335,7 +359,7 @@ def hosted_line(activity: HostedActivity, lang: str, *, escape: Callable[[str],subject safe for the destination's markup."""- emoji = "🖼" if activity.tool == "image_generation" else "🔎"+ emoji = "🖼" if activity.tool == "image_generate" else "🔎"parts: list[Optional[str]] = [f"{emoji} {i18n_t(f'hostedTools.tool.{activity.tool}', lang)}"]if activity.subject:parts[0] += " " + i18n_t("hostedTools.quoted", lang, subject=escape(_clip(activity.subject)))diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex 89c3c63f7..4bb0f09ce 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -642,17 +642,18 @@ Responses terminal states:| `incomplete_details.reason=content_filter` or `safety` | `safety` || Failed/cancelled | terminal `ProviderError` (classified `unknown` when no provider error code is present) |-## Hosted tools (planned)--Planned by [`../vibey-hosted-tools.md`](../vibey-hosted-tools.md) (Phase 1: `web_search`, `x_search`,-`image_generation`). These rows describe the wire mapping the `ai` lane implements with that phase. Implemented so-far:--- **Requests.** A hosted tool's canonical spec is sent as the native declaration on a hop whose route is native, with- its Responses `include` values and the pin header on that request.-- **Parsing** for `web_search`, `x_search` and `image_generation`: native results become `HostedToolBlock`s, text- citations become `TextBlock.citations`, and response-level facts go to `hosted_summary`. A generated image is saved- to a file through the adapter's `MediaSink` as its done item is parsed (Images row).+## Hosted tools++Designed by [`../vibey-hosted-tools.md`](../vibey-hosted-tools.md) (v2: the search tools `web_search` and `x_search`+run natively or through the gateway's executor chain; `image_generate` is always a function tool, executed directly).+These rows describe the wire mapping the `ai` lane implements.++- **Requests.** A search tool's canonical spec is sent as the native declaration on a hop whose facts say `native:+ assumed`, with its Responses `include` values and the pin header on that request; otherwise as the same-named+ function. No request declares a hosted image tool.+- **Parsing** for `web_search` and `x_search`: native results become `HostedToolBlock`s, text citations become+ `TextBlock.citations`, and response-level facts go to `hosted_summary`. An `image_generation_call` is no hosted item:+ it is ignored like any undeclared item.- **Portable history.** A finished response's hosted calls become synthetic same-named calls and results, split aroundthe assistant message. There is one call per hosted block, and nothing folds. Each result shows its status linefirst and then every line attached to it. A response its@@ -661,8 +662,8 @@ far:that call from its result.- **Native replay and pins.** A response's hosted calls go back verbatim, their `native.payload` in place, only tothe hop the request goes to, and only when that hop's Source served them on the same origin. The protocol must be- Anthropic or Responses, the hop must still have each tool they called, and `image_generation` never goes back- verbatim. Such a request is pinned to the hop's Source.+ Anthropic or Responses, and the hop must still declare each tool they called natively. Such a request is pinned to+ the hop's Source.- The response a request continues within its turn needs no replay evidence, and its request also names themodel that served it (`x-avibe-pin-model`, when that id is ASCII). That response is the request's last assistantmessage, stopped for tools, with only tool results after it.@@ -671,28 +672,29 @@ far:- Otherwise the calls take the portable form above. A continuation whose fresh hop is another Source thereforegoes in place as text: one hop builds and serves each request.- **`pin_unavailable`.** The gateway's `409` `model_hub_pin_unavailable` / `pin_unavailable` answer to a pinned- request is never shown and never reaches the loop's retry: the adapter renders the same request once more in- portable form (proxy declarations, synthetic history, in-place text) and sends it unpinned. Whatever answers that- request reaches the loop as usual.+ request, matched on `type` and `code`, is never shown and never the generic retry. It ends the send with a refusal+ and no output, and the loop renders the request again for a fresh hop within the bounds in `provider.md`, in+ portable form (proxy declarations, synthetic history, in-place text, unpinned) only as the last resort. xAI's+ decrypt refusal of a replayed ciphertext is answered the same way, without that Source identity's opaque payloads+ for the rest of the run.-- **Proxy.** A hosted tool that a hop does not run natively is its canonical function, and a call to it runs on the- gateway's executor bound for the Turn. The result keeps the record on `ToolResultMessage.hosted`. A proxied image's- base64 comes back beside its record and is saved through the same `MediaSink` as a native one; the record lists the- file.+- **Proxy.** A search tool that a hop does not run natively is its canonical function, and a call to it runs on the+ gateway's executor chain, which the gateway resolves from the live Turn. The result keeps the record on+ `ToolResultMessage.hosted`, with `execution.mode: proxy`. An `image_generate` call is an ordinary tool call and+ result everywhere, with `execution.mode: direct`; its images are files the record lists.An Anthropic citation covers its whole text block, so it carries no range.| Concern | Anthropic Messages | OpenAI Responses (OpenAI, xAI) | OpenAI Chat Completions || --- | --- | --- | --- |-| Native declaration (mode from `HopResolution.hosted_tools`) | `{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}` | `{"type": "web_search"}`; xAI also `{"type": "x_search"}`; OpenAI `{"type": "image_generation", "partial_images": 2, "output_format": "jpeg", "output_compression": 90}`; plus the overlay entry's `include` values (OpenAI web search: `web_search_call.action.sources`) | none. A `google` hop is reached over this Chat form, and the engine translates it to Gemini. |+| Native declaration (mode from `HopResolution.hosted_tools`) | `{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}` | `{"type": "web_search"}`; xAI also `{"type": "x_search"}`; plus the overlay entry's `include` values (OpenAI web search: `web_search_call.action.sources`) | none. A `google` hop is reached over this Chat form, and the engine translates it to Gemini. || Proxy declaration | `{"name": <tool>, "input_schema": <canonical>}` | `{"type": "function", "name": <tool>, "parameters": <canonical>}` | `{"type": "function", "function": {...}}` || Native result → `HostedToolBlock` | every item under a declared hosted tool, one block each, in stream order, mapped to a provider-neutral `action` by the rule in `../vibey-hosted-tools.md` §4.2. `server_tool_use` plus its `web_search_tool_result` → `search`; `encrypted_content` only in `native.payload`. | `web_search_call` `search` (`queries[]`, else `query`) / `open_page` / `find_in_page`; xAI `custom_tool_call` `x_keyword_search` / `x_semantic_search` / `x_user_search` / `x_thread_fetch`. The `tco_…` `reasoning` items stay thinking blocks. Unknown items become `other`, never dropped. | — || Response-level facts → `AssistantMessage.hosted_summary` | `usage.server_tool_use` counts | xAI `cost_in_usd_ticks` (reported once per response), `server_side_tool_usage_details` counts, and the X-search `url_citation`s as `cited_sources` | — || Citations → `TextBlock.citations` | text-block `citations[]` (`web_search_result_location`: `url`, `title`, `cited_text`) | `output_text.annotations[]` of type `url_citation` (`url`, `title`, `start_index`, `end_index`) | — |-| Same-Source replay (target hop is `native.source_id`, same origin, and `hosted_tools[tool].replay` is true now) | `native.payload` blocks verbatim, in place; citations not sent | `native.payload` items verbatim, in place; annotations not sent; never for `image_generation` | — |-| Images | — | `image_generation_call` → a file saved through the `MediaSink` from its `output_item.done`. The record lists it as a `HostedImage`: absolute path, mime type sniffed from its bytes, the item's size as width and height, and the file's byte count. The action is `generate` with the revised prompt and the resolved size and quality. `native.payload` holds the path in place of `result`, so no base64 is ever stored. `partial_image` previews are skipped before parsing. The duplicate `result` in the terminal response is never decoded, and a call that saved no image is `failed`. The model reads the path record, and a file over `read`'s inline limit says so. A stream that declares `image_generation` gets the 32 MiB event cap as its line cap; others keep 8 MiB. | — |+| Same-Source replay (target hop is `native.source_id` under the identity that minted it, same origin, and `hosted_tools[tool].replay` is `assumed` now) | `native.payload` blocks verbatim, in place; citations not sent | `native.payload` items verbatim, in place; annotations not sent | — || Other-origin replay | assistant `tool_use(name=<tool>, input=<per-action arguments>)` + user `tool_result(record as text)`, splitting the assistant message; a `failed`/`incomplete` record sets `is_error: true` | `function_call(name=<tool>, arguments)` + `function_call_output(record as text)`; a failed record's text starts `[<tool> failed: <error>]` | assistant `tool_calls` + `tool` message, failure as in Responses |-| Pinning (any protocol) | a request with a native declaration or a verbatim `native.payload` carries `x-avibe-pin-source: <hop source_id>`. A continuation whose calls go back verbatim also carries `x-avibe-pin-model: <its served model>`, the hop's own model. A `409` `model_hub_pin_unavailable` / `pin_unavailable` answer is not shown: the same request is rendered again in portable form (proxy declarations, synthetic history, in-place text) and sent unpinned, exactly once. A `pause_turn` continuation is the exception (below). | same | — |+| Pinning (any protocol) | a request with a native declaration or a verbatim `native.payload` carries `x-avibe-pin-source: <hop source_id>`. A continuation whose calls go back verbatim also carries `x-avibe-pin-model: <its served model>`, the hop's own model. A `409` `model_hub_pin_unavailable` / `pin_unavailable` answer is not shown: the loop renders the request again for a fresh hop, portable only as the last resort (`provider.md`). A `pause_turn` continuation is the exception (below). | same | — || Citations at delivery | `TextBlock.citations` → `core/citations.py` builder → Markdown links + Web sidecar | same | — || `pause_turn` | not a stop. The adapter sends the request again with the paused content appended as the last assistant message, with no new user message. That continuation goes to the same hop, pinned to the Source and model that served the paused response, and its output streams on as the same response. A continuation block's index follows the paused ones, and a result finalizes its pending call by id. The hosted counters and cost are summed over every response. `usage` is the final request's, whose input already holds every paused part, so the context estimate stays right; billing comes from the gateway's per-call metering. After 5 continuations, a sixth pause ends the response with one `interrupted` error whose partial keeps everything assembled. A continuation is never sent in portable form. One that Source answers `pin_unavailable`, or a pause of a send that carried no pin, ends the response the same way. The merged message is verified only when every response in it was verified and reported the same origin; otherwise it is sanitized as any unverified response. | — | — |-| In-flight replay (same turn, pinned Source) | verbatim when the fresh hop is the Source that served it, else in place as text. On `pin_unavailable`, which the gateway also answers for a narrow rejection of the replayed content (§3.5), each server block pair is replaced in place by one text block; signed thinking is kept on the same origin. | same | — |+| In-flight replay (same turn, pinned Source) | verbatim while the fresh hop is the Source that served it and still declares each tool natively, else in place as text: each server block pair is replaced in place by one text block, and signed thinking is kept on the same origin. After a `pin_unavailable`, the fresh hop's facts decide the same way. | same | — |diff --git a/docs/plans/agent-core-contracts/cross-provider.md b/docs/plans/agent-core-contracts/cross-provider.mdindex d5be59b5c..a4a839c43 100644--- a/docs/plans/agent-core-contracts/cross-provider.md+++ b/docs/plans/agent-core-contracts/cross-provider.md@@ -13,7 +13,7 @@ cross-provider history tests (MIT).| Tool call | kept; `id` and `signature` as stored | kept without `signature`; `id` normalized to the target's rules (below) || Tool result | kept | `tool_call_id` rewritten through the same id map || Image in a user or tool-result message | kept | kept if the target model accepts images, else `[image: <name or mime>]` |-| Hosted tool block (`hosted_tool`) | when the target hop is `native.source_id`, its origin equals the message's `origin`, and its current replay evidence is positive (`HopResolution.hosted_tools[tool].replay`): `native.payload` verbatim, in place; otherwise as a different origin. `image_generation` blocks always take the different-origin form. | a synthetic call to the same-named tool, plus its result, both rendered from the block's `action` and `record` by the one record-to-text function under the per-action rules of `../vibey-hosted-tools.md` §5. A `failed` or `incomplete` record is an error result (`is_error`, or a leading `[<tool> failed: <error>]` where the protocol has no flag). A `pending` record is the interrupted-call result below. The assistant message is split around the pair. |+| Hosted tool block (`hosted_tool`) | when the target hop is `native.source_id`, its origin equals the message's `origin`, and its current replay evidence is positive (`HopResolution.hosted_tools[tool].replay`): `native.payload` verbatim, in place; otherwise as a different origin. | a synthetic call to the same-named tool, plus its result, both rendered from the block's `action` and `record` by the one record-to-text function under the per-action rules of `../vibey-hosted-tools.md` §5. A `failed` or `incomplete` record is an error result (`is_error`, or a leading `[<tool> failed: <error>]` where the protocol has no flag). A `pending` record is the interrupted-call result below. The assistant message is split around the pair. || Text block `citations` | not sent | not sent || Tool result with `hosted` (a proxied hosted call) | kept, as any tool result | kept, as any tool result |@@ -27,8 +27,9 @@ Invariants:takes the "same origin" column only if its origin equals the target's **and** its `source_identity` equals thehop's. A message another identity served (another Source, or the same Source after its key or relay changed), orone no known identity served (after a failover to another Source, or a row written before the field), takes the- "different origin" column at a hop that names an identity. The gateway applies the same binding at failover- (C-6 item 6).+ "different origin" column at a hop that names an identity. So does a message whose identity's provider refused+ an opaque payload earlier in the run (`ModelEndpoint.opaque_refused`): the refusal does not say which one failed.+ The gateway applies the same binding at failover (C-6 item 6).- Tool-call id normalization is deterministic: the stored id when the target accepts it; otherwise`call_` + the first 24 hex characters of SHA-256 of the stored id. Anthropic accepts `^[a-zA-Z0-9_-]{1,64}$`; theother protocols' limits are recorded in the `ai` lane's conversion tables. The map is computed per request; the@@ -44,4 +45,4 @@ Invariants:in-flight turn (`pause_turn`, or a client tool result after server tools in the same message), the request ispinned to the Source that produced the content, and the content goes back verbatim. This transform is the onlyconverter of hosted content. The gateway never rewrites it: a pinned request it cannot serve comes back as- `pin_unavailable`, and the transform renders the request again in portable form.+ `pin_unavailable`, and the loop renders the request again for a fresh hop (`provider.md`).diff --git a/docs/plans/agent-core-contracts/hop-resolution.schema.json b/docs/plans/agent-core-contracts/hop-resolution.schema.jsonindex 9f4887468..ff0037da5 100644--- a/docs/plans/agent-core-contracts/hop-resolution.schema.json+++ b/docs/plans/agent-core-contracts/hop-resolution.schema.json@@ -126,58 +126,168 @@},"hosted_tools": {"type": "object",- "description": "One entry per hosted tool the user enabled (vibey-hosted-tools.md §3.5). `mode` is the primary hop's; `declaration` and `include` are the overlay's wire declaration, present exactly for native; `executor` is the proxy executor bound for this turn, present for every entry because a native request answered pin_unavailable is re-rendered with the proxy in the same turn; `replay` is true only for the primary hop Source's positive replay evidence taken on the current engine and probe shape. A request carrying native content is pinned with x-avibe-pin-source: source_id.",- "propertyNames": {- "enum": [- "web_search",- "x_search",- "image_generation"- ]- },- "additionalProperties": {- "type": "object",- "required": [- "mode",- "executor",- "replay"- ],- "additionalProperties": false,- "properties": {- "mode": {- "enum": [- "native",- "proxy"- ]+ "description": "One entry per hosted tool the turn declares (vibey-hosted-tools.md §3.4). A search tool's entry is the primary hop's facts: `native` is `assumed` when the tool runs on the hop (`runs_on`) and no current negative `call` evidence exists, else `unsupported`; `declaration` and `include` (the overlay's wire declaration and Responses include values) are present exactly when `native` is `assumed`; `replay` is `assumed` when `native` is, the protocol replays natively and no current negative `replay` evidence exists. `image_generate` lists the image models the user's Sources make available, default first, and is absent when the tool is off or no model is available. The turn's first resolution freezes the tool set and the image models; later hops change only `native` and `replay`. A request carrying native content is pinned with x-avibe-pin-source: source_id.",+ "additionalProperties": false,+ "properties": {+ "web_search": {+ "type": "object",+ "required": [+ "native",+ "replay"+ ],+ "additionalProperties": false,+ "properties": {+ "native": {+ "enum": [+ "assumed",+ "unsupported"+ ]+ },+ "declaration": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "include": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ }+ },+ "replay": {+ "enum": [+ "assumed",+ "unsupported"+ ]+ }},- "declaration": {- "type": "object",- "required": [- "type"- ],+ "if": {"properties": {- "type": {+ "native": {+ "const": "assumed"+ }+ }+ },+ "then": {+ "required": [+ "declaration",+ "include"+ ]+ },+ "else": {+ "not": {+ "anyOf": [+ {+ "required": [+ "declaration"+ ]+ },+ {+ "required": [+ "include"+ ]+ }+ ]+ }+ }+ },+ "x_search": {+ "type": "object",+ "required": [+ "native",+ "replay"+ ],+ "additionalProperties": false,+ "properties": {+ "native": {+ "enum": [+ "assumed",+ "unsupported"+ ]+ },+ "declaration": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "include": {+ "type": "array",+ "items": {"type": "string","minLength": 1}+ },+ "replay": {+ "enum": [+ "assumed",+ "unsupported"+ ]}},- "include": {- "type": "array",- "items": {- "type": "string",- "minLength": 1+ "if": {+ "properties": {+ "native": {+ "const": "assumed"+ }}},- "executor": {- "oneOf": [- {- "type": "null"- },- {+ "then": {+ "required": [+ "declaration",+ "include"+ ]+ },+ "else": {+ "not": {+ "anyOf": [+ {+ "required": [+ "declaration"+ ]+ },+ {+ "required": [+ "include"+ ]+ }+ ]+ }+ }+ },+ "image_generate": {+ "type": "object",+ "required": [+ "models",+ "default"+ ],+ "additionalProperties": false,+ "properties": {+ "models": {+ "type": "array",+ "minItems": 1,+ "items": {"type": "object","required": ["source_id",- "model_id"+ "model_id",+ "description",+ "params",+ "size_forms"],"additionalProperties": false,"properties": {@@ -188,149 +298,54 @@"model_id": {"type": "string","minLength": 1- }- }- }- ]- },- "replay": {- "type": "boolean"- }- },- "if": {- "properties": {- "mode": {- "const": "native"- }- }- },- "then": {- "required": [- "declaration",- "include"- ]- },- "else": {- "not": {- "anyOf": [- {- "required": [- "declaration"- ]- },- {- "required": [- "include"- ]- }- ]- }- }- },- "properties": {- "image_generation": {- "allOf": [- {- "type": "object",- "required": [- "mode",- "executor",- "replay"- ],- "additionalProperties": false,- "properties": {- "mode": {- "enum": [- "native",- "proxy"- ]- },- "declaration": {- "type": "object",- "required": [- "type"- ],- "properties": {- "type": {- "type": "string",- "minLength": 1- }- }- },- "include": {- "type": "array",- "items": {+ },+ "description": {"type": "string","minLength": 1- }- },- "executor": {- "oneOf": [- {- "type": "null"- },- {- "type": "object",- "required": [- "source_id",- "model_id"- ],- "additionalProperties": false,- "properties": {- "source_id": {- "type": "string",- "pattern": "^src_[a-z0-9]{8,}$"- },- "model_id": {- "type": "string",- "minLength": 1- }- }- }- ]- },- "replay": {- "type": "boolean"- }- },- "if": {- "properties": {- "mode": {- "const": "native"- }- }- },- "then": {- "required": [- "declaration",- "include"- ]- },- "else": {- "not": {- "anyOf": [- {- "required": [- "declaration"+ },+ "params": {+ "type": "array",+ "uniqueItems": true,+ "items": {+ "enum": [+ "size",+ "images",+ "n"]- },- {- "required": [- "include"+ }+ },+ "size_forms": {+ "type": "array",+ "uniqueItems": true,+ "items": {+ "enum": [+ "pixels",+ "ratio"]}- ]+ }}}},- {+ "default": {+ "type": "object",+ "required": [+ "source_id",+ "model_id"+ ],+ "additionalProperties": false,"properties": {- "replay": {- "const": false+ "source_id": {+ "type": "string",+ "pattern": "^src_[a-z0-9]{8,}$"+ },+ "model_id": {+ "type": "string",+ "minLength": 1}}}- ]+ }}}}@@ -363,12 +378,33 @@},"hosted_tools": {"web_search": {- "mode": "proxy",- "executor": {- "source_id": "src_xai00001",- "model_id": "grok-4.6"+ "native": "assumed",+ "declaration": {+ "type": "web_search_20250305",+ "name": "web_search",+ "max_uses": 5},- "replay": false+ "include": [],+ "replay": "assumed"+ },+ "x_search": {+ "native": "unsupported",+ "replay": "unsupported"+ },+ "image_generate": {+ "models": [+ {+ "source_id": "src_openai0001",+ "model_id": "gpt-image-2",+ "description": "OpenAI's image model; follows long prompts closely",+ "params": ["size", "images", "n"],+ "size_forms": ["pixels"]+ }+ ],+ "default": {+ "source_id": "src_openai0001",+ "model_id": "gpt-image-2"+ }}}}diff --git a/docs/plans/agent-core-contracts/message.schema.json b/docs/plans/agent-core-contracts/message.schema.jsonindex f09d8ce48..8fc02c073 100644--- a/docs/plans/agent-core-contracts/message.schema.json+++ b/docs/plans/agent-core-contracts/message.schema.json@@ -435,7 +435,7 @@"record"],"additionalProperties": false,- "description": "Set only on the result of a proxied hosted call. `execution` is present exactly when an executor ran; without it the record failed. `action` is what the executor reports it did, such as a generated image's rendered prompt and resolved size and quality.",+ "description": "Set only on the result of a proxied search or an `image_generate` call. `execution` is present exactly when an executor or image endpoint ran; without it the record failed. `action` is what the executor reports it did: for `image_generate`, the model it ran on, the prompt it rendered, and the resolved size and quality.","properties": {"record": {"$ref": "#/definitions/HostedRecord"@@ -477,7 +477,7 @@"then": {"properties": {"tool_name": {- "$ref": "#/definitions/HostedToolName"+ "$ref": "#/definitions/HostedResultToolName"}}}@@ -549,7 +549,7 @@],"properties": {"tool_name": {- "const": "image_generation"+ "const": "image_generate"}}},@@ -596,6 +596,43 @@}}}+ },+ {+ "if": {+ "required": [+ "hosted"+ ],+ "properties": {+ "tool_name": {+ "enum": [+ "web_search",+ "x_search"+ ]+ },+ "hosted": {+ "required": [+ "action"+ ]+ }+ }+ },+ "then": {+ "properties": {+ "hosted": {+ "properties": {+ "action": {+ "properties": {+ "type": {+ "not": {+ "const": "generate"+ }+ }+ }+ }+ }+ }+ }+ }}]},@@ -638,10 +675,9 @@"HostedToolName": {"enum": ["web_search",- "x_search",- "image_generation"+ "x_search"],- "description": "Catalog name of a hosted tool (`vibey-hosted-tools.md` §2)."+ "description": "Catalog name of a tool a provider runs natively, a `hosted_tool` block (`vibey-hosted-tools.md` §4.2)."},"HostedAction": {"description": "What a hosted call did, provider-neutral (`vibey-hosted-tools.md` §4.2 mapping rule). An item the mapping does not know is `other`, never dropped.",@@ -786,7 +822,7 @@"type"],"additionalProperties": false,- "description": "An image generation. `prompt` is the provider's revised prompt, required for a completed record; `size` and `quality` are the resolved output settings.",+ "description": "An `image_generate` call. `model` is the image model it ran on; `prompt` is the rendered prompt, required for a completed record; `size` and `quality` are the resolved output settings.","properties": {"type": {"const": "generate"@@ -802,6 +838,10 @@"quality": {"type": "string","minLength": 1+ },+ "model": {+ "type": "string",+ "minLength": 1}}},@@ -889,7 +929,7 @@"sources"],"additionalProperties": false,- "description": "Per-call facts of one hosted call. `images` is present exactly for `image_generation`.",+ "description": "Per-call facts of one hosted call. `images` is present exactly for `image_generate`.","properties": {"status": {"enum": [@@ -1068,63 +1108,6 @@}}}- },- {- "if": {- "properties": {- "tool": {- "const": "image_generation"- }- }- },- "then": {- "properties": {- "action": {- "properties": {- "type": {- "enum": [- "generate",- "other"- ]- }- }- },- "record": {- "required": [- "images"- ]- }- }- }- },- {- "if": {- "properties": {- "action": {- "properties": {- "type": {- "const": "generate"- }- }- },- "record": {- "properties": {- "status": {- "const": "completed"- }- }- }- }- },- "then": {- "properties": {- "action": {- "required": [- "prompt"- ]- }- }- }}]},@@ -1209,10 +1192,13 @@"executor_billing"],"additionalProperties": false,- "description": "Which executor ran a proxied hosted call. `cost` is absent when no price is known.",+ "description": "What ran a hosted call outside the model: a search executor (`proxy`) or an image endpoint (`direct`). `cost` is this attempt's own, absent when no price is known; `failed_attempts` lists the earlier billed attempts, and the display totals them (`core/hosted_activity`).","properties": {"mode": {- "const": "proxy"+ "enum": [+ "proxy",+ "direct"+ ]},"executor_origin": {"$ref": "#/definitions/Origin"@@ -1229,8 +1215,43 @@},"cost": {"$ref": "#/definitions/HostedCost"+ },+ "failed_attempts": {+ "type": "array",+ "description": "The earlier billable attempts of a search chain, in order, before the executor that ran the call.",+ "items": {+ "type": "object",+ "required": [+ "source_id",+ "billing"+ ],+ "additionalProperties": false,+ "properties": {+ "source_id": {+ "type": "string",+ "pattern": "^src_[a-z0-9]{8,}$"+ },+ "billing": {+ "enum": [+ "monthly",+ "metered"+ ]+ },+ "cost": {+ "$ref": "#/definitions/HostedCost"+ }+ }+ }}}+ },+ "HostedResultToolName": {+ "enum": [+ "web_search",+ "x_search",+ "image_generate"+ ],+ "description": "A tool whose result carries `hosted`: a proxied search, or an `image_generate` call (`vibey-hosted-tools.md` §4.2, §7)."}},"examples": [diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.mdindex 2dace5460..72929de1e 100644--- a/docs/plans/agent-core-contracts/model-hub-consumer.md+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md@@ -56,24 +56,29 @@ consumer's requirements, and the Model Hub lane lands the change in both places.converts protocols. Opaque payloads are bound to the account that issued them, the Source identity, as well asthe origin: a provider refuses another account's ciphertext. The serving identity is read on the final admissionsnapshot, so a key rotated mid-turn counts. A pinned request is never rewritten: one pinned to the primary hop- whose identity has changed since the launch answers `pin_unavailable`, and the agent renders it again portably.+ whose identity has changed since the launch answers `pin_unavailable`, and the agent re-resolves and renders it+ for the fresh hop, whose identity drops the old payloads.The identity stays in memory: it is never in the served-hop report or persisted provenance. Known limit:the next request targets the primary origin again, so payloads returned by a fallback origin are not replayed if alater request fails over to that same fallback; a provider that then rejects the call surfaces as a provider error.-7. **Hosted tools** (planned, [`../vibey-hosted-tools.md`](../vibey-hosted-tools.md) §3.5).- - `HopResolution.hosted_tools` names, for each tool the user enabled:- - the primary hop's `mode` (`native` or `proxy`);- - for `native`, the wire declaration, which is required exactly then;- - the executor bound for this turn (`{source_id, model_id}` or `null`), present for every entry whatever the- mode, because a native request that comes back `pin_unavailable` is re-rendered with the proxy function in the- same turn. A config change applies from the next turn;- - `replay`, true only for the primary hop Source's positive replay evidence taken on the current engine and- probe shape.- - `native` requires all of these ([`../model-hub-capability-model.md`](../model-hub-capability-model.md) §3):- - an eligible credential (never a Claude subscription);- - positive `call` evidence for that (Source, model), taken on the current engine and probe shape;- - an untranslated path.+7. **Hosted tools** (v2, [`../vibey-hosted-tools.md`](../vibey-hosted-tools.md) §3.4, §3.5, §6, §7).+ - `HopResolution.hosted_tools` has one entry per hosted tool the turn declares:+ - **a search tool** (`web_search`, `x_search`) gives the primary hop's facts:+ - `native` is `assumed` when the tool runs on the hop (`hosted_tools.runs_on`: a hub Source with an eligible+ credential, never a Claude subscription, and an untranslated path, that serves the model, for which the+ overlay declares the tool) and no current negative `call` evidence exists for it; otherwise `unsupported`.+ Positive evidence never decides it;+ - `declaration` and `include` (the overlay's wire declaration and Responses `include` values), present+ exactly when `native` is `assumed`;+ - `replay` is `assumed` when `native` is, the protocol replays natively (`anthropic`, `openai_responses`),+ and no current negative `replay` evidence exists; otherwise `unsupported`;+ - **`image_generate`** gives `{models: [{source_id, model_id, description, params, size_forms}], default:+ {source_id, model_id}}`: the image models the user's Sources make available, default first. It is absent when+ the tool is off or no image model is available, so `models` is never empty.+ - The turn's first resolution freezes the tool set, each search tool's executor order and the image models on+ the turn trace; later hops of the turn change only `native` and `replay`. A settings change applies from the+ next turn.- **The gateway never rewrites hosted content.** Vibey pins every request that carries a native declaration, anative hosted payload or an in-flight continuation, with `x-avibe-pin-source`.- A pinned request is served only by that Source, with no failover and no recovery wait. The gateway answers HTTP@@ -81,34 +86,33 @@ consumer's requirements, and the Model Hub lane lands the change in both places.cases:- the Source cannot be admitted, checked before invoking anything;- its attempt ends before model output with a failover-class failure;- - its attempt ends before model output with an error that a narrow hosted-content evidence rule names.- - Vibey then renders the same request in portable form and sends it unpinned; it fails over as today.+ - its attempt ends before model output with an error that a narrow hosted-content evidence rule names. Only+ then does the body carry `error.reason: {kind: "hosted_unsupported", tool, aspect, source_id}`, and the rule+ has already written the negative evidence (memory first) when the answer leaves the gateway.+ - Vibey matches the 409 on `type` and `code` and tolerates extra fields. It then resolves a fresh hop and renders+ the request for it: the fresh facts turn exactly the refused tool into the proxy function or synthetic replay,+ and other native content stays native and pinned (bounds in `vibey-hosted-tools.md` §3.5).- **The pin names an exact hop.** It is the pinned Source with the model the content was rendered for:- the model in `x-avibe-pin-model`, which a continuation sets to the served-hop `model` of the response itcontinues;- otherwise the launch's primary hop model, when the pin is the primary Source. The route credential fixesthat 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, on the same snapshot the- call is then made on (after the engine is prepared, for every attempt):+ - **Admission** reads the overlay and the negative evidence 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;- - "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.+ - every hosted declaration in `tools` needs the tool to run on the hop with that declaration `type`, and no+ current negative `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 no current+ negative `replay` evidence. A generated image call is never replayed.- **One identity per turn and Source.** Native content goes to a Source only under one identity (credential,- base URL, protocol, vendor, kind, credential generation) 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`.+ base URL, protocol, vendor, kind, credential generation) 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, 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 thein-flight run. A named call (`function_call`, `custom_tool_call`, `mcp_call`) without one cannot beclassified and ends it too.@@ -119,66 +123,56 @@ consumer's requirements, and the Model Hub lane lands the change in both places.with it or with user messages made only of `tool_result` blocks. On Responses it is the trailing run of modeloutput items (an assistant `message`, `reasoning`, and the known call item types), followed only by`function_call_output` or `custom_tool_call_output` items. Any other item ends the run, so an unknown item- never exempts a hosted call from evidence.+ never exempts a hosted call.- A pinned request is forwarded with nothing changed but `model` and `stream`, so Vibey renders all of it, earlierhistory included, for the pinned Source's origin.- - **Unpinned hosted content is refused.** Vibey pins every request carrying Source-specific hosted content:- native declarations, replayed native items, and in-flight continuations. An unpinned Vibey request carrying- any of it therefore has no correct hop, and the gateway answers 422 `hosted_content_unpinned` before anything- runs.+ - **Unpinned hosted content is refused.** An unpinned Vibey request carrying native declarations, replayed native+ items or an in-flight continuation has no correct hop, and the gateway answers 422 `hosted_content_unpinned`+ before anything runs.- **Native content is never translated.** The pinned hop must speak the request's protocol; otherwise theanswer is `pin_unavailable`.- - A `pin_unavailable` carries no routing state into the resend. Every failover-class failure that is health- evidence settles the Source as normal routing does, so the resend skips it. An unrecognized error frame inside- a 2xx is not health evidence, so the resend may try that Source once more.+ - A `pin_unavailable` carries no routing state into the resend beyond the evidence a narrow rule wrote. Every+ failover-class failure that is health evidence settles the Source as normal routing does.- Item 6 (the opaque thinking strip) is unchanged and applies only to unpinned requests.- - The served-hop report carries `source`, the serving Source id (item 4, Model Hub contract v12), so that a- hosted block's payload is tagged with the exact Source; two Sources can share an origin. The gateway and the- parser in `conversion-tables.md` changed together in that bump. Native hosted mode lands with or after v12.- - **The proxy executor.** `POST {base_url}/hosted-tools/{tool}` with the turn's Bearer token, its- `request_headers` (item 3), and the body- `{"arguments": <canonical arguments>, "executor": HopResolution.hosted_tools[tool].executor}`. The executor- may be `null`.- - The executor must be the one the caller's live turn bound for that tool. The turn's first resolution- binds the enabled tools and their executors, with each executor Source's identity. Later resolutions in the- turn keep that binding and recompute only `mode`, `declaration`, `include` and `replay` for their hop, so a- settings change applies from the next turn.- - Any other executor, a tool not enabled this turn, a credential without a live turn, or a turn that no- longer admits work (stopping or finalizing) gets 409 `executor_not_bound`, and nothing runs.- - The turn owns an admitted call: stopping the turn cancels it, and the call is still metered.- - An executor Source whose identity changed since launch (base URL, credential) is "no longer available".- - The gateway runs that executor and no other: one native request in the executor Source's own protocol, with- the overlay's declaration and no reasoning effort. Search tools ask for a numbered list of results with one- or two cited sentences each. On Responses the tool is forced (`tool_choice: "required"`), as the call probe- that verified it forces it; Anthropic is asked in the message alone. `image_generation` renders the prompt at- the given size and requests partial images.- - Every outcome of a well-formed call is a 200 with `{"record", "execution"?}`, in the- `ToolResultMessage.hosted` encoding. `execution` is present exactly when an executor ran. A call that- reaches none (no verified executor, or the bound Source was removed or is ineligible) has a `failed` record.- Success is an allow-list: a call is `completed` only when the response says it completed (Responses- `status: completed`; Anthropic `end_turn` or `stop_sequence`) and nothing failed. A response that stopped- early (Responses `incomplete`; Anthropic `max_tokens` or `pause_turn`) is `incomplete`. Any reported failure- (a failed call or outcome, an Anthropic search error), or any other or missing ending, is `failed`. Both keep- any partial sources. An unreadable response, including one nested past the decoder's limit or one whose- fields are not of their kind, is `failed`. The record's `error` is in the user's language.+ - **Passive positive evidence.** A served response that carries the provider's own completed item for a tool the+ request declared natively (Responses `web_search_call` with `status: completed`, or a `custom_tool_call` named+ after an X search; Anthropic `server_tool_use` named `web_search` with a `web_search_tool_result` whose+ `content` is a result list) records a success for (serving Source, model, tool) at settlement, off the loop.+ It is display only and never changes routing.+ - **The executor endpoint.** `POST {base_url}/hosted-tools/{tool}` with the turn's Bearer token, its+ `request_headers` (item 3) and the body `{"arguments": <canonical arguments>}`.+ - The call belongs to the live turn the request names (`x-avibe-turn-id`). Without one, or from a turn that no+ longer admits work, it is 409 `turn_not_live`; a tool outside the turn's frozen tool set, or for+ `image_generate` a model outside the turn's frozen models, is 409 `tool_not_enabled`. Nothing runs. Stopping+ the turn cancels an admitted call, which is still metered.+ - **A search call runs on a chain** built from the turn's frozen executor order: each candidate is a Source+ whose vendor offers the tool natively, called with its vendor's `executor_model`, and admitted on the final+ snapshot when the gateway reaches it (`runs_on`, its identity, no current negative `call` evidence). The+ gateway sends one short native request (the overlay's declaration; on Responses `tool_choice: "required"`;+ Anthropic is asked in the message alone; no reasoning effort) and moves to the next candidate on a failure+ normal routing fails over from, a narrow-rule refusal, or a failure mid-stream. A refusal of the executor+ model (`model_not_found`) also writes negative `call` evidence for (Source, `executor_model`, tool). A+ completed response that never ran the tool ends the chain. One deadline covers the whole chain (180 s).+ - **An `image_generate` call** runs directly on the image endpoint of the (Source, model) the turn's frozen+ models name (`vibey-hosted-tools.md` §7.4).+ - Every outcome of a well-formed call is a 200 with `{"record", "execution"?}` in the+ `ToolResultMessage.hosted` encoding. `execution` names the attempt whose response the record came from (the+ last one tried when all failed), with its billing and cost; earlier billable attempts are listed in+ `execution.failed_attempts: [{source_id, billing, cost?}]`. With no candidate, or every candidate failed, the+ record is `failed` and names what to add.+ - Success is an allow-list: a call is `completed` only when the response says it completed (Responses+ `status: completed`; Anthropic `end_turn` or `stop_sequence`) and nothing failed; a response that stopped+ early is `incomplete`; any reported failure, or any other or missing ending, is `failed`. An unreadable+ response is `failed`. The record's `error` is in the user's language.- The record's search `sources` keep the executor's order. A snippet is the answer text its citation belongsto: the list item when that item cites only that source, else its sentence, with the citation markersremoved. An Anthropic result keeps its `cited_text`. X search lists the cited posts. A response's first 256citations are read.- - For `image_generation`, the record has no `images` key. `generation` carries the resolved `revised_prompt`,- `size` and `quality`, and `images` carries `[{mime, data}]` in base64. Vibey saves the bytes through its- session media sink and adds the path records itself. The image must decode, within 24 MiB. The stream may- carry only the requested partials and the final image, plus two, within 64 MiB decoded across all of them.- Anything else is a `failed` record.- - A malformed or unbound call is the only error status: 400 `invalid_request_error` (including a body over- 1 MiB), 401, 404 for an unknown tool, or 409 `executor_not_bound`, as- `{"type": "error", "error": {"type", "code"}}`.- - A search call is bounded at 180 s and an image at 300 s. The call is metered on the executor Source and never- changes Source health.- - `execution.cost` is the pricing module's value of the executor's response (`hosted_call_cost`): `included`- on a monthly Source, the provider's own figure as `reported` (xAI `cost_in_usd_ticks`), else `list` from the- call's metered tokens and the provider's hosted counters (`usage.server_tool_use`,- `usage.server_side_tool_usage_details`). It is absent when the call cannot be valued, never zero.+ - A malformed call is 400 `invalid_request_error` (including a body over the tool's request bound), an+ unauthenticated one 401, an unknown tool 404, as `{"type": "error", "error": {"type", "code"}}`.+ - Each attempt is metered on its own Source and never changes Source health. `cost` is the pricing module's+ value of that attempt: `included` on a monthly Source, the provider's own figure as `reported`, else `list`;+ absent when it cannot be valued, never zero.## 3. Not requireddiff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.mdindex 86b7af516..e6f75786d 100644--- a/docs/plans/agent-core-contracts/provider.md+++ b/docs/plans/agent-core-contracts/provider.md@@ -20,9 +20,14 @@ class ModelEndpoint: # built by the adapter layer from C-6 HopResolutprovider: str # vendor identity of the hop (HopResolution.provider); with protocol and model it# forms the target origin for the cross-provider rulessource_id: str | None # HopResolution.source_id: the pin of a request with native hosted content+ source_identity: str | None # HopResolution.source_identity: the account its opaque payloads are bound to+ portable: bool # never pinned, and no native hosted content (vibey-hosted-tools.md §3.5)+ opaque_refused: frozenset[str | None] # identities whose provider refused an opaque payload in this run; the+ # messages they served are sent as a different origin's (cross-provider.md)hosted_tools: Mapping[str, HostedToolRoute] # HopResolution.hosted_tools, in Model Hub's order: per enabled- # tool its mode, and for native its declaration and Responses include values,- # plus the turn's executor and replay (vibey-hosted-tools.md §3.5)+ # search tool its mode and replay, and for native its declaration and Responses+ # include values (vibey-hosted-tools.md §3.4)+ image_models: ImageModels | None # the models image_generate may call; None when the tool is off@dataclass(frozen=True)@@ -55,7 +60,6 @@ class ModelRequest:cache: Literal["default", "none"] # "default": the protocol's cache breakpoints and their lifetimes# (conversion-tables.md); "none" for the compaction summarizersupports_images: bool # resolved by the loop; unknown capability counts as False- tool_choice: str | None # the one tool the response must call; set only by a hosted-tool probe````tools` is the one owner of what a request declares. A hosted tool is its canonical `ToolSpec`@@ -63,17 +67,28 @@ class ModelRequest:route's `declaration` verbatim in the spec's place, merges a Responses route's `include` values into `include`, andpins the request with `x-avibe-pin-source: <source_id>`; on any other hop the spec is an ordinary function. Vibeylists its hosted tools first, so Anthropic's tools breakpoint, which goes on the last function tool, never moves.-`registry.build_wire_request` returns the URL, headers and body the adapter would send, without sending it; a-hosted-tool probe sends exactly that request (`vibey-hosted-tools.md` §3.2). On Responses and Chat a forced function-is named, and a native hosted tool is forced with `"required"`, which needs it to be the request's only tool. An-Anthropic request is never forced: current Claude models and extended thinking refuse a forced `tool` or `any`-choice.History follows the same Source rule. A response's hosted calls go back verbatim only to the hop the request goes to,when that hop's Source served them on the same origin (`conversion-tables.md`, Hosted tools): within their turn as a-continuation, later with the hop's current `replay`, and pinned to that Source either way. The gateway answers a pinned request it cannot serve from that Source with-`409 pin_unavailable`. That answer is not a `ProviderError`: the adapter sends the same request exactly once more in-portable form and unpinned, so the loop's retry never sees it.+continuation, later with the hop's current `replay`, and pinned to that Source either way.++**Refusals before any output** (`vibey-hosted-tools.md` §3.5). The gateway answers a pinned request it cannot serve+from that Source with `409 pin_unavailable`, matched on its `type` and `code`, and names the narrow hosted rule that+fired in `error.reason` when one did. xAI answers a replayed ciphertext it cannot read with a plain-text 400, `Could+not decrypt the provided encrypted_content`, on any request. The adapter ends either send with a `ProviderError` that+has no output, is not `retryable`, and carries a `refusal`: `pin_unavailable` with the hop's Source and the rule's+tool and aspect, or `opaque_refused` with the hop's Source identity. The loop answers it by rendering the request+again, never by the generic retry:++- by a fresh hop, rendered normally, at most once per (Source, tool, aspect) a narrow rule names and at most twice+ per run, whatever the reason;+- in portable form on the hop it has, past either bound, or at once when a hand-back's fresh hop is the refused one+ again (the same Source, identity, model and hosted-tool facts). A portable request is never pinned, so the gateway+ never hands it back;+- after `opaque_refused`, with that identity in `opaque_refused` for the rest of the run, so none of its opaque+ payloads is sent again. That is answered once per identity: refused again, the error ends the run.++A `pause_turn` continuation's `pin_unavailable` comes after output, so it is no refusal (`conversion-tables.md`).The loop's `ModelRouter` returns the `ModelEndpoint` together with its `ModelCapabilities`. Every capability has adefined effect, including when it is unknown:@@ -86,9 +101,7 @@ defined effect, including when it is unknown:| `supports_images` | images sent | placeholders | placeholders || `supports_reasoning` | `reasoning_effort` sent if it is one of `reasoning_efforts` | `reasoning_effort = None` | `reasoning_effort = None` | Adapters are constructed with a`MediaLoader` and resolve each `ImageBlock`'s bytes at request time; the canonical message never carries bytes. The-token names an immutable snapshot (`message.schema.json`), so the bytes never change for a committed block. The-Responses adapter also takes a `MediaSink`. It saves each image a native `image_generation` call returns as it parses-the call's done item, and the call's record names the file (`vibey-hosted-tools.md` §7.3).+token names an immutable snapshot (`message.schema.json`), so the bytes never change for a committed block.`stream` yields `ProviderEvent`s (`provider-event.schema.json`) and always ends with exactly one `done` or one`error`. `done.message` is the complete canonical `AssistantMessage`; its `origin` comes from the served-hop reportdiff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.pyindex 330117856..7a375aefe 100644--- a/docs/plans/model-hub-contracts/adapter-interface.py+++ b/docs/plans/model-hub-contracts/adapter-interface.py@@ -196,6 +196,9 @@ class RawCallOutcome:os_errno: int | None = None# A 400 before output, as closed tokens for the capability-evidence rules.rejection: UpstreamRejection | None = None+ # The search tools whose own completed item a served response carried, for+ # the positive evidence written at settlement (``vibey-hosted-tools.md`` §3.2).+ hosted_tools: frozenset[str] = frozenset()class ObservationOutcome(str, Enum):diff --git a/docs/plans/model-hub-contracts/hop-resolution.schema.json b/docs/plans/model-hub-contracts/hop-resolution.schema.jsonindex 31eef3506..90e8d44fe 100644--- a/docs/plans/model-hub-contracts/hop-resolution.schema.json+++ b/docs/plans/model-hub-contracts/hop-resolution.schema.json@@ -37,58 +37,168 @@},"hosted_tools": {"type": "object",- "description": "One entry per hosted tool the user enabled (vibey-hosted-tools.md §3.5). `mode` is the primary hop's; `declaration` and `include` are the overlay's wire declaration, present exactly for native; `executor` is the proxy executor bound for this turn, present for every entry because a native request answered pin_unavailable is re-rendered with the proxy in the same turn; `replay` is true only for the primary hop Source's positive replay evidence taken on the current engine and probe shape. A request carrying native content is pinned with x-avibe-pin-source: source_id.",- "propertyNames": {- "enum": [- "web_search",- "x_search",- "image_generation"- ]- },- "additionalProperties": {- "type": "object",- "required": [- "mode",- "executor",- "replay"- ],- "additionalProperties": false,- "properties": {- "mode": {- "enum": [- "native",- "proxy"- ]+ "description": "One entry per hosted tool the turn declares (vibey-hosted-tools.md §3.4). A search tool's entry is the primary hop's facts: `native` is `assumed` when the tool runs on the hop (`runs_on`) and no current negative `call` evidence exists, else `unsupported`; `declaration` and `include` (the overlay's wire declaration and Responses include values) are present exactly when `native` is `assumed`; `replay` is `assumed` when `native` is, the protocol replays natively and no current negative `replay` evidence exists. `image_generate` lists the image models the user's Sources make available, default first, and is absent when the tool is off or no model is available. The turn's first resolution freezes the tool set and the image models; later hops change only `native` and `replay`. A request carrying native content is pinned with x-avibe-pin-source: source_id.",+ "additionalProperties": false,+ "properties": {+ "web_search": {+ "type": "object",+ "required": [+ "native",+ "replay"+ ],+ "additionalProperties": false,+ "properties": {+ "native": {+ "enum": [+ "assumed",+ "unsupported"+ ]+ },+ "declaration": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "include": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ }+ },+ "replay": {+ "enum": [+ "assumed",+ "unsupported"+ ]+ }},- "declaration": {- "type": "object",- "required": [- "type"- ],+ "if": {"properties": {- "type": {+ "native": {+ "const": "assumed"+ }+ }+ },+ "then": {+ "required": [+ "declaration",+ "include"+ ]+ },+ "else": {+ "not": {+ "anyOf": [+ {+ "required": [+ "declaration"+ ]+ },+ {+ "required": [+ "include"+ ]+ }+ ]+ }+ }+ },+ "x_search": {+ "type": "object",+ "required": [+ "native",+ "replay"+ ],+ "additionalProperties": false,+ "properties": {+ "native": {+ "enum": [+ "assumed",+ "unsupported"+ ]+ },+ "declaration": {+ "type": "object",+ "required": [+ "type"+ ],+ "properties": {+ "type": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "include": {+ "type": "array",+ "items": {"type": "string","minLength": 1}+ },+ "replay": {+ "enum": [+ "assumed",+ "unsupported"+ ]}},- "include": {- "type": "array",- "items": {- "type": "string",- "minLength": 1+ "if": {+ "properties": {+ "native": {+ "const": "assumed"+ }}},- "executor": {- "oneOf": [- {- "type": "null"- },- {+ "then": {+ "required": [+ "declaration",+ "include"+ ]+ },+ "else": {+ "not": {+ "anyOf": [+ {+ "required": [+ "declaration"+ ]+ },+ {+ "required": [+ "include"+ ]+ }+ ]+ }+ }+ },+ "image_generate": {+ "type": "object",+ "required": [+ "models",+ "default"+ ],+ "additionalProperties": false,+ "properties": {+ "models": {+ "type": "array",+ "minItems": 1,+ "items": {"type": "object","required": ["source_id",- "model_id"+ "model_id",+ "description",+ "params",+ "size_forms"],"additionalProperties": false,"properties": {@@ -99,149 +209,54 @@"model_id": {"type": "string","minLength": 1- }- }- }- ]- },- "replay": {- "type": "boolean"- }- },- "if": {- "properties": {- "mode": {- "const": "native"- }- }- },- "then": {- "required": [- "declaration",- "include"- ]- },- "else": {- "not": {- "anyOf": [- {- "required": [- "declaration"- ]- },- {- "required": [- "include"- ]- }- ]- }- }- },- "properties": {- "image_generation": {- "allOf": [- {- "type": "object",- "required": [- "mode",- "executor",- "replay"- ],- "additionalProperties": false,- "properties": {- "mode": {- "enum": [- "native",- "proxy"- ]- },- "declaration": {- "type": "object",- "required": [- "type"- ],- "properties": {- "type": {- "type": "string",- "minLength": 1- }- }- },- "include": {- "type": "array",- "items": {+ },+ "description": {"type": "string","minLength": 1- }- },- "executor": {- "oneOf": [- {- "type": "null"- },- {- "type": "object",- "required": [- "source_id",- "model_id"- ],- "additionalProperties": false,- "properties": {- "source_id": {- "type": "string",- "pattern": "^src_[a-z0-9]{8,}$"- },- "model_id": {- "type": "string",- "minLength": 1- }- }- }- ]- },- "replay": {- "type": "boolean"- }- },- "if": {- "properties": {- "mode": {- "const": "native"- }- }- },- "then": {- "required": [- "declaration",- "include"- ]- },- "else": {- "not": {- "anyOf": [- {- "required": [- "declaration"+ },+ "params": {+ "type": "array",+ "uniqueItems": true,+ "items": {+ "enum": [+ "size",+ "images",+ "n"]- },- {- "required": [- "include"+ }+ },+ "size_forms": {+ "type": "array",+ "uniqueItems": true,+ "items": {+ "enum": [+ "pixels",+ "ratio"]}- ]+ }}}},- {+ "default": {+ "type": "object",+ "required": [+ "source_id",+ "model_id"+ ],+ "additionalProperties": false,"properties": {- "replay": {- "const": false+ "source_id": {+ "type": "string",+ "pattern": "^src_[a-z0-9]{8,}$"+ },+ "model_id": {+ "type": "string",+ "minLength": 1}}}- ]+ }}}}diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.mdindex 27c71f0cd..3c0845d5c 100644--- a/docs/plans/vibey-hosted-tools.md+++ b/docs/plans/vibey-hosted-tools.md@@ -113,21 +113,24 @@ The evidence store, its record and its owner are the capability model's §3. v2classifier (`evidence_rules.py`) from a real request, and only for the exact (Source, model, feature) it names.- **Positive (`verified`, display only).** A served response that carries the provider's own completed item for atool the request declared natively: Responses `web_search_call` with `status: completed`, or a `custom_tool_call`- named `x_keyword_search`, `x_semantic_search`, `x_user_search` or `x_thread_fetch`; Anthropic `server_tool_use`- named `web_search` with a `web_search_tool_result` whose `content` is a result list, not the error object- (`web_search_tool_result_error`), which arrives under the same block type. A proxy executor call is itself a native call on the executor Source, so it writes the+ named `x_keyword_search`, `x_semantic_search`, `x_user_search` or `x_thread_fetch`; Anthropic a+ `web_search_tool_result` whose `content` is a result list, not the error object+ (`web_search_tool_result_error`), which arrives under the same block type. The block type is web search's own,+ so the `server_tool_use` that precedes it is not read. A proxy executor call is itself a native call on the executor Source, so it writes thesame record for the executor's (Source, model). A successful `image_generate` writes it for (Source, image model).- **Where the gateway sees it.** The served-stream observer (`ProtocolSSEState` / `ProtocolFactProjector`) keepsonly bounded scalar projections today, and no item types. It gains projection paths: Responses`response.output_item.done` → `item.type`, `item.name`, `item.status`, and the buffered `output[*].type` and- `output[*].name` and `output[*].status`; Anthropic `content_block_start.content_block.type`, `.name` and- `.content.type`. Buffered responses take the same paths through `observe_buffered_protocol_response`.+ `output[*].name` and `output[*].status`; Anthropic `content_block_start.content_block.type`, `.content` (whether it+ is a list) and `.content.type`, and the buffered `content[*]` the same. Buffered responses take the same paths+ through `observe_buffered_protocol_response`, keeping a few short fields for at most 256 members.- **Bounded writes, off the response path.** Each write rewrites the evidence file, so a positive record is writtenat settlement, off the loop, after the response completes, and only when there is no record or the existingpositive record is older than one hour, never on every response. **A positive write never replaces a negativerecord:** a success that settles after a concurrent refusal must not re-enable native routing, so only a clearor a stamp change removes a refusal. It is keyed on- the serving Source's identity from the final admission snapshot.+ the serving Source's identity from the final admission snapshot: a Source re-identified while the response ran is+ not vouched for.- `resolve()` reads a record by its `status`, no longer by its `basis`: today it reads every `observed` record asa refusal.- **A positive record carries the observed `mode`** (`native`, `executor` or `direct`) and is never retired by the@@ -466,7 +469,8 @@ These rules are C-1 rows in `cross-provider.md` and per-protocol rows in `conver`request_headers`, and the body `{"arguments": <canonical arguments>}`. There is no executor in the body: thegateway resolves the chain from the caller's live turn (`x-avibe-turn-id`). A call without a live turn, or from aturn that no longer admits work, is 409 `turn_not_live`; a tool outside the turn's frozen tool set (§3.4) is 409- `tool_not_enabled`. Nothing runs. v1's `executor_not_bound` is retired with the binding.+ `tool_not_enabled`. Nothing runs. The gateway answers `turn_not_live` before it validates the body, and+ `tool_not_enabled` after. v1's `executor_not_bound` is retired with the binding.- **The frozen tool set lives on the turn.** The turn's first resolution writes its tool set, each search tool'seffective executor order, and the `image_generate` enum, once to the turn trace (`hosted_tools`, replacing thewrite-once `hosted_executors`). The endpoint authorizes every call against it, and a settings or Source-order change@@ -491,7 +495,8 @@ These rules are C-1 rows in `cross-provider.md` and per-protocol rows in `converAnthropic is asked in the message alone), a fixed instruction to search and list numbered results with one ortwo cited sentences each, a small output cap, and no reasoning effort.4. On a failure that normal routing fails over from, or a narrow-rule refusal (which also writes negative- evidence), it tries the next candidate. A model refusal (404 `model_not_found`, "model not supported") skips+ evidence), it tries the next candidate. A model refusal (the upstream's machine code naming the model, such as+ `model_not_found`, or a 404 `not_found_error`, as routing's classifier reads it; L1 hands no prose to it) skipsthat Source for this call without settling its health, as `_InvocationUnsupported` does, and, because it namesthe executor model, writes negative `call` evidence for (Source, `executor_model`, tool), so the Source leavesthe chain until the refusal is cleared or its wire stamp changes, and shows and clears like any refusal. A failure mid-stream moves on too: nothing@@ -499,13 +504,15 @@ These rules are C-1 rows in `cross-provider.md` and per-protocol rows in `converreturned, and the partial call is still metered on its Source. A completed response that never ran the tool(the model chose not to; Anthropic is asked in the message alone) ends the chain with a `failed` record: it isa model choice, not a Source failure, and moving on would double the cost. Any other outcome ends the chain.- 5. With no candidate, the call returns a `failed` record naming what to add ("add an xAI Source to use X search").- With candidates that were all tried and failed, it returns the last failure's reason and names the Sources- tried, so the user sees that retrying, or those Sources, is the issue.+ 5. With no admitted candidate, the call returns a `failed` record naming the providers whose Sources can run the+ tool ("add a Source from one of these providers: xAI"). With candidates that were all tried and failed, it+ returns the last failure's reason and names the Sources tried, so the user sees that retrying, or those+ Sources, is the issue.- **One deadline for the whole chain**, the tool's call timeout (180 s for search), not one per candidate.- Each candidate tried is metered on its own Source. The result's `execution` names the Source whose response therecord came from (the last one tried when all failed), with that attempt's `executor_billing` and `cost`; earlier- billable attempts are listed in `execution.failed_attempts: [{source_id, billing, cost?}]`, each with its own+ billable attempts (those that reported tokens or produced a response; a refusal before output that reported+ none is not billed) are listed in `execution.failed_attempts: [{source_id, billing, cost?}]`, each with its ownbilling and cost basis, so a metered failure before a subscription success keeps both. A subscription attemptcarries `cost: {basis: "included"}`, so an absent `cost` always means unpriced.- **The total is computed once**, in `core/hosted_activity`'s projected `cost`, which the Web card and the IM line@@ -513,7 +520,8 @@ These rules are C-1 rows in `cross-provider.md` and per-protocol rows in `converattempt `included` gives `included`; the basis is `reported` only when every summed figure is reported, else`list` (shown with ≈); an attempt without a `cost` makes the total a lower bound, shown as "at least $X" /"至少 $X", never as complete. With `failed_attempts`, the card also names the attempt count ("3 attempts" /- "尝试 3 次").+ "尝试 3 次"). B1 ships the sum, its basis and the attempt count (as the projection's `calls`); until D2 adds the+ lower-bound form, an attempt without a `cost` leaves the total unknown rather than shown as complete.- The executor request is a short model request because no vendor exposes search without a model: Anthropic,OpenAI's public API, xAI and Google all run search inside a model call.- **The result is the canonical record** (v1's rules, unchanged): a `HostedRecord` with `sources[]` in the@@ -809,7 +817,7 @@ under the freeze protocol (`model-hub-contracts/README.md`).| Area | Removed or changed || --- | --- || Model Hub | `core/handlers/model_hub/hosted_probe.py`; `ModelHubService.probe_hosted_tool`, `_record_probe_evidence`, `_probe_estimate`, `_probe_rejection`, `_probe_aspect`; the RPC and UI-server routes for `POST /api/models/hosted-tools/<tool>/probe`; `MODEL_HUB_RPC_TIMEOUT_SECONDS`' probe dependency (it moves back to `vibe/model_hub_client.py`); `HOSTED_PROBE_SHAPE` and every `shape` parameter; the evidence `probe` basis and probe staleness; `engine_stamp()`'s `hosted_wire` branch (#2623); the per-turn executor binding and `_executor`; `UserTestCall`'s probe-only callers |-| Gateway | `stream_wire`'s `response.image_generation_call.partial_image` model-output envelope; the executor's native image path (`ResponsesStreamReader(partial_images=…)`, the 32 MiB image line cap, the image event and byte budget, `_image_result`, the `_IMAGE_*` constants, the 300 s image `call_timeout`), replaced by what the images endpoint needs; the OpenAI `image_generation` overlay declaration (#2580's JPEG q90 becomes the images-endpoint request parameters); `executor` in the proxy body; `executor_request`'s image branch (its `include`/`partial_images` read of the overlay image declaration); the `hosted_executor_bindings` / `turn_hosted_executors` plumbing, replaced by the turn's frozen `hosted_tools` (§6); the `hosted_tools_status` candidates and bound-executor projection. `_own_turn_call` stays. Kept: `disable-image-generation: passthrough`; `hosted_admission`'s "image calls are never replayed" rule until no transcript can carry a native image call; #2616's per-turn identity binding and #2586's turn id. |+| Gateway | `stream_wire`'s `response.image_generation_call.partial_image` model-output envelope; the executor's native image path (`ResponsesStreamReader(partial_images=…)`, the 32 MiB image line cap, the image event and byte budget, `_image_result`, the `_IMAGE_*` constants, the 300 s image `call_timeout`, and the image-sized 128 MiB response budget, now 16 MiB for a search answer), replaced by what the images endpoint needs; the OpenAI `image_generation` overlay declaration (#2580's JPEG q90 becomes the images-endpoint request parameters); `executor` in the proxy body; `executor_request`'s image branch (its `include`/`partial_images` read of the overlay image declaration); the `hosted_executor_bindings` / `turn_hosted_executors` plumbing, replaced by the turn's frozen `hosted_tools` (§6); the `hosted_tools_status` candidates and bound-executor projection. `_own_turn_call` stays. Kept: `disable-image-generation: passthrough`; `hosted_admission`'s "image calls are never replayed" rule until no transcript can carry a native image call; #2616's per-turn identity binding and #2586's turn id. || Vibey | the native `image_generation` declaration, its parsing (`responses_hosted_tool`'s `image_generation_call` mapping, `image=`/`image_error=` in `responses_hosted_block`), `_ImageBudget`, `_saved_image`, `_PARTIAL_IMAGE_EVENT`, `IMAGE_STREAM_LINE_BYTES`, the large-event JSON offload, `drive_sse_stream`'s `max_line_size` and `iter_sse_events`' offload (every stream returns to 8 MiB); `ModelRequest.tool_choice` and `_common.forced_tool`; `registry.build_wire_request` (its tests move to each adapter's `wire_request`); the adapters' probe-only `media_sink` parameter and the `media_sink` argument of `registry_providers(media_loader=…, media_sink=…)`; `HostedTool`'s `executor` field and its `executor` body; the agent's `_with_hosted_images` / `_emit_orphan_images` path for native images (`agent.py`), kept for `image_generate` results. `HostedRecord.images`, `HostedImage`, `generate_action` and the `generate` action stay, on `ToolResultMessage.hosted` only. || UI | `ProbeAnswerNote.tsx` (with `ReplayNote`); in `ToolsTab.tsx` `ProbeCell`, the executor picker and its notes, the `needsCheck`/`needsExecutor` states, the "unchecked" chip and the probe column; in `HostedCapabilityChips.tsx` the recheck action, the recheck-only keyboard path (every chip keeps its keyboard path into the detail), and the reverify, engineUpgraded and unsupportedAged states; `useEstimateLabel.ts`; the `probeHostedTool` wiring in `SettingsModelsPage.tsx` and its Sources re-read after a probe (no clear needs one: §8.2); in `useHostedTools` `probe`, `probing`, `lostProbeOutcome`, `recordedOutcome` and `PROBE_NOT_RECORDED` (the serialized writes, identity fencing and re-read after Source mutations stay); in `hostedTools.ts` `ProbeTarget`, `probeKey`, `probeUnanswered`, `verifiedCandidates`, `sameExecutor` and the `aged`/`engineUpgraded` branches of `evidenceChip`; `modelsApi.probeHostedTool`; the types `HostedToolProbeResult`, `HostedProbeAspect`, `HostedCostEstimate`, `probe_estimate`, `HostedToolCandidate`, `bound`, and `executor` in `HostedToolPut`. Rebuilt on the new read rather than only trimmed: `modelCapabilities` and the Tools-tab rows on `status`; `cost.imageTokens` ("no per-image price yet") by per-image prices; `capability.chip.viaProxy` and `explain.viaProxy` go with the "via proxy" chip. Check-all is removed by the UI lane's pending PR. || i18n (`settings.models`) | `tools.probe.*`; `tools.state.needsCheck` and `needsExecutor`; `tools.executor.*`; `tools.chip.unchecked`, `reverify`, `engineUpgraded`, `unsupportedAged`; `tools.reverify.*`; `capability.recheck`, `recheckCost`; `capability.chip.*` and `capability.explain.*` for reverify, engineUpgraded, viaProxy, viaProxyAged and unsupportedAged; `capability.expiryProbe`; `tools.col.*` and `tools.chip.native`/`unsupported`/`executor` (the candidate table goes). Rewritten: `tools.subtitle` (§8.1), `tools.empty` and `tools.noNative` against the new read; `tools.footnote` keeps its relay and subscription sentences. |diff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex 2e03d65f9..0aba10704 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -29,6 +29,7 @@ from core.handlers.model_hub.events import (EventAgent,EventReason,)+from core.handlers.model_hub.hosted_turn import TurnHostedToolsfrom core.handlers.model_hub.identifiers import (OPENCODE_PROVIDER_BY_NATIVE_PROTOCOL,opencode_menu_model_id,@@ -770,23 +771,6 @@ def overlay_identifier_bytes(content: bytes) -> bytes:return json.dumps(identifiers, ensure_ascii=True, separators=(",", ":")).encode()-def _hosted_executor_bindings(- config: ModelHubConfig, hosted_tools: Mapping[str, Mapping[str, Any]],-) -> tuple[tuple[str, tuple[str, str, str] | None], ...]:- """Each enabled tool's bound executor with its Source identity at launch, for the gateway's route."""-- sources = {source.id: source for source in config.sources}- bindings: list[tuple[str, tuple[str, str, str] | None]] = []- for tool, entry in sorted(hosted_tools.items()):- executor = entry.get("executor")- source = sources.get(executor["source_id"]) if executor else None- bindings.append((- tool,- (source.id, executor["model_id"], identity_digest(source)) if source is not None else None,- ))- return tuple(bindings)--class ModelHubRuntimeRouter:"""Select a supply channel once per turn and build ephemeral injections."""@@ -968,7 +952,7 @@ class ModelHubRuntimeRouter:via_mapping: bool = False,gateway_request_model_id: Optional[str] = None,primary_origin: HopOrigin | None = None,- hosted_executors: tuple[tuple[str, tuple[str, str, str] | None], ...] = (),+ hosted_tools: TurnHostedTools | None = None,) -> tuple[str, str]:if self.turn_gateway is not None:return await self.turn_gateway.endpoint(@@ -982,7 +966,7 @@ class ModelHubRuntimeRouter:gateway_request_model_id=gateway_request_model_id,request_scoped=backend == "codex",**({"primary_origin": primary_origin} if primary_origin is not None else {}),- **({"hosted_executors": hosted_executors} if hosted_executors else {}),+ **({"hosted_tools": hosted_tools} if hosted_tools is not None else {}),)await self.service._ensure_engine_synced()status = await self.service._engine_call(self.service.adapter.start())@@ -1340,22 +1324,20 @@ class ModelHubRuntimeRouter:else target_model)identity = identity_digest(source) if backend == "vibey" else None- # A turn's first resolution binds its hosted tools and executors;- # later attempts of the turn keep that binding (settings apply from- # the next turn) and recompute only what belongs to their hop.+ # A turn's first resolution freezes its hosted tools, executor+ # orders and image models; later attempts of the turn keep them+ # (settings apply from the next turn) and recompute only their+ # hop's own facts.frozen = (- self.turn_gateway.correlation.turn_hosted_executors(turn_id)+ self.turn_gateway.correlation.turn_hosted_tools(turn_id)if backend == "vibey" and self.turn_gateway is not Noneelse None)+ if backend == "vibey" and frozen is None:+ frozen = await asyncio.to_thread(self.service.freeze_turn_hosted_tools, config)hosted_tools = (- # Off the controller loop: the first resolution loads the evidence file.- await asyncio.to_thread(- self.service.hosted_tools_for_hop, config, source, target_model,- {tool: bound[:2] if bound is not None else None for tool, bound in frozen}- if frozen is not None else None,- )- if backend == "vibey"+ await asyncio.to_thread(self.service.hosted_tools_for_hop, source, target_model, frozen)+ if frozen is not Noneelse {})gateway_base_url, gateway_token = await self._gateway_credentials(@@ -1372,11 +1354,8 @@ class ModelHubRuntimeRouter:HopOrigin(source.vendor, source.protocol, target_model, source.id, identity)if identity is not None else None),- # The proxy endpoint runs only the executor this launch bound per- # tool, and only while its Source keeps the identity it had now.- hosted_executors=(- frozen if frozen is not None else _hosted_executor_bindings(config, hosted_tools)- ),+ # The executor endpoint runs only what the turn froze.+ hosted_tools=frozen,)if self.turn_gateway is None:prefix = await self._source_prefix(source.id)diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex b4f0969d3..694a0e86d 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -243,7 +243,7 @@ class VibeyAgent(BaseAgent):environment=self._environment,on_response=self._on_response,)- self._providers = providers or registry_providers(media_loader=self.media, media_sink=self.media)+ self._providers = providers or registry_providers(media_loader=self.media)# The client of the Turn's other gateway calls (the hosted-tool executor); None opens one per call.self._gateway_client = gateway_client# C-9: the Session parts a checkpoint carries (context.md section 9).@@ -631,7 +631,7 @@ class VibeyAgent(BaseAgent):# Job-backed tools receive the loop's tracking wrapper, so Stop kills foreground commands.tools = mark_skill_loads((- *hosted_tools(turn.router.preflight, self._gateway_client, self.media),+ *hosted_tools(turn.router, self._gateway_client, self.media),*suite.create_tools(agent.jobs, self.media.image_sink(session_id)),))diff --git a/modules/agents/vibey/errors.py b/modules/agents/vibey/errors.pyindex cb0a51794..1484a5764 100644--- a/modules/agents/vibey/errors.py+++ b/modules/agents/vibey/errors.py@@ -45,6 +45,8 @@ _KIND_KEYS: dict[str, str] = {# Tool calls under a stop reason that cannot carry them."stop": "providerProtocol","stream_cleanup": "internal",+ # A context row this build cannot read (a shape it no longer accepts): the session cannot continue.+ "TranscriptError": "historyUnreadable",# The loop refuses a route that declares no tool support before any request."UnsupportedModelRoute": "toolsUnsupported",# A provider answer the canonical transcript cannot hold.diff --git a/modules/agents/vibey/models.py b/modules/agents/vibey/models.pyindex cb9fc6895..452b98baf 100644--- a/modules/agents/vibey/models.py+++ b/modules/agents/vibey/models.py@@ -25,8 +25,9 @@ from typing import Any, Awaitable, Callable, Mapping, Optionalfrom core.agent_core.agent.models import ModelSelectionfrom core.agent_core.ai.provider import (- HostedExecutor,HostedToolRoute,+ ImageModel,+ ImageModels,ModelCapabilities,ModelEndpoint,ProviderAdapter,@@ -51,62 +52,86 @@ def _optional(value: Any, kind: type, what: str) -> Any:return value-#: The keys of one ``hosted_tools`` entry per mode, exactly (hop-resolution.schema.json).-_HOSTED_ENTRY_KEYS = {- "native": {"mode", "executor", "replay", "declaration", "include"},- "proxy": {"mode", "executor", "replay"},-}+#: The facts of one search tool's ``hosted_tools`` entry, exactly (hop-resolution.schema.json): the declaration and+#: include values are present exactly when the tool is assumed to run natively.+_FACTS = ("assumed", "unsupported")+_SEARCH_KEYS = {"assumed": {"native", "replay", "declaration", "include"}, "unsupported": {"native", "replay"}}+_IMAGE_KEYS = {"source_id", "model_id", "description", "params", "size_forms"}+_IMAGE_PARAMS = {"size", "images", "n"}+_SIZE_FORMS = {"pixels", "ratio"}_SOURCE_ID = re.compile(r"src_[a-z0-9]{8,}")-def _hosted_routes(raw: Any) -> dict[str, HostedToolRoute]:- """``HopResolution.hosted_tools``: each enabled tool's mode, native declaration, executor and replay."""+def _hosted_routes(raw: Any) -> tuple[dict[str, HostedToolRoute], Optional[ImageModels]]:+ """``HopResolution.hosted_tools``: each enabled search tool's facts as its route, and ``image_generate``'s models."""if not isinstance(raw, Mapping):raise HopResolutionError("hop has no hosted_tools")routes: dict[str, HostedToolRoute] = {}+ images: Optional[ImageModels] = Nonefor tool, entry in raw.items():try:- routes[tool] = _hosted_route(tool, entry)+ if tool == "image_generate":+ images = _image_models(entry)+ else:+ routes[tool] = _hosted_route(tool, entry)except (TypeError, ValueError, KeyError) as error:# Every malformed entry fails here, whatever the parse raised on it.raise HopResolutionError(f"hop hosted tool {tool!r} is invalid: {error}") from None- return routes+ return routes, imagesdef _hosted_route(tool: Any, entry: Any) -> HostedToolRoute:- """One entry, exactly as the hop schema allows it."""+ """One search tool's facts, exactly as the hop schema allows them: declared natively exactly when ``native`` is+ ``assumed`` (§3.4, §4.1)."""if tool not in HOSTED_TOOLS or not isinstance(entry, Mapping):- raise ValueError("not a hosted tool entry")- mode = entry.get("mode")- keys = _HOSTED_ENTRY_KEYS.get(mode) if isinstance(mode, str) else None- if keys is None:- raise ValueError(f"unknown mode {mode!r}")- if set(entry) != keys:- raise ValueError(f"a {mode} entry has exactly {', '.join(sorted(keys))}")- executor = entry["executor"]- if executor is not None:- if (- not isinstance(executor, Mapping)- or set(executor) != {"source_id", "model_id"}- or not isinstance(executor["source_id"], str)- or not _SOURCE_ID.fullmatch(executor["source_id"])- ):- raise ValueError("the executor is a Source id and a model id, or null")- executor = HostedExecutor(executor["source_id"], executor["model_id"])- if tool == "image_generation" and entry["replay"] is not False:- raise ValueError("an image_generation call is never replayed")+ raise ValueError("not a search tool entry")+ native, replay = entry.get("native"), entry.get("replay")+ if native not in _FACTS or replay not in _FACTS:+ raise ValueError("native and replay are each assumed or unsupported")+ if set(entry) != _SEARCH_KEYS[native]:+ raise ValueError(f"a {native} entry has exactly {', '.join(sorted(_SEARCH_KEYS[native]))}")include = entry.get("include", [])if not isinstance(include, list):raise ValueError("include must be a list")return HostedToolRoute(- mode=mode,- executor=executor,- replay=entry["replay"],+ mode="native" if native == "assumed" else "proxy",+ replay=replay == "assumed",declaration=entry.get("declaration"),include=tuple(include),)+def _image_models(entry: Any) -> ImageModels:+ """``image_generate``'s models, default first, exactly as the hop schema allows them (§7.2)."""+ if not isinstance(entry, Mapping) or set(entry) != {"models", "default"}:+ raise ValueError("an image_generate entry has exactly models and default")+ raw_models, default = entry["models"], entry["default"]+ if not isinstance(raw_models, list) or not raw_models:+ raise ValueError("models is a non-empty list")+ models = []+ for item in raw_models:+ if not isinstance(item, Mapping) or set(item) != _IMAGE_KEYS:+ raise ValueError(f"an image model has exactly {', '.join(sorted(_IMAGE_KEYS))}")+ if not isinstance(item["source_id"], str) or not _SOURCE_ID.fullmatch(item["source_id"]):+ raise ValueError("an image model names its Source")+ for name in ("model_id", "description"):+ if not isinstance(item[name], str) or not item[name]:+ raise ValueError(f"an image model has a {name}")+ params, forms = item["params"], item["size_forms"]+ if not isinstance(params, list) or not set(params) <= _IMAGE_PARAMS or len(set(params)) != len(params):+ raise ValueError("params lists distinct size, images and n")+ if not isinstance(forms, list) or not set(forms) <= _SIZE_FORMS or len(set(forms)) != len(forms):+ raise ValueError("size_forms lists distinct pixels and ratio")+ models.append(+ ImageModel(item["source_id"], item["model_id"], item["description"], tuple(params), tuple(forms))+ )+ if not isinstance(default, Mapping) or set(default) != {"source_id", "model_id"}:+ raise ValueError("default is a Source id and a model id")+ if (models[0].source_id, models[0].model_id) != (default["source_id"], default["model_id"]):+ raise ValueError("the default is the first model")+ return ImageModels(tuple(models))++def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[str] = None) -> ModelSelection:"""Build the loop's selection from one ``HopResolution`` (hop-resolution.schema.json).@@ -127,7 +152,7 @@ def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[strisinstance(key, str) and isinstance(value, str) for key, value in headers.items()):raise HopResolutionError("hop request_headers must map strings to strings")- hosted_tools = _hosted_routes(hop.get("hosted_tools"))+ hosted_tools, image_models = _hosted_routes(hop.get("hosted_tools"))raw = hop.get("capabilities")if not isinstance(raw, Mapping):raise HopResolutionError("hop has no capabilities")@@ -158,6 +183,7 @@ def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[strsource_id=hop["source_id"],source_identity=hop["source_identity"],hosted_tools=hosted_tools,+ image_models=image_models,)return ModelSelection(endpoint=endpoint, capabilities=capabilities)@@ -167,7 +193,7 @@ class HubModelRouter:``first`` is the selection the adapter already resolved during preflight; theloop's first attempt reuses it, so a run resolves once and again only after a- retryable error.+ retryable error or a refusal (``vibey-hosted-tools.md`` §3.5)."""def __init__(@@ -182,13 +208,18 @@ class HubModelRouter:self._first = first#: The route preflight resolved; the Turn's tool list is fixed from it.self.preflight = first+ #: The hop the Turn runs on now, its latest resolution. The gateway answers the Turn's requests only on that+ #: hop's credential (C-6 item 3), so the Turn's hosted calls go out on it too.+ self.current = firstself._adapters: dict[str, ProviderAdapter] = {}async def resolve(self) -> ModelSelection:if self._first is not None:selection, self._first = self._first, None- return selection- return await self._resolve()+ else:+ selection = await self._resolve()+ self.current = selection+ return selectiondef provider_for(self, protocol: ProtocolName) -> ProviderAdapter:adapter = self._adapters.get(protocol)@@ -209,24 +240,16 @@ class HubModelRouter:logger.warning("Vibey could not close its %s provider adapter", protocol, exc_info=True)-def registry_providers(*, media_loader: Any, media_sink: Any = None, client: Any = None) -> ProviderFactory:+def registry_providers(*, media_loader: Any, client: Any = None) -> ProviderFactory:"""Provider adapters from the ``ai`` registry, speaking to the Model Hub gateway.In gateway mode each adapter reads the served origin from ``x-avibe-served-hop``- with the engine's own resolver, the one owner of that C-6 rule. ``media_sink``- keeps the images a Responses hop generates natively, the only protocol that does.+ with the engine's own resolver, the one owner of that C-6 rule."""def create(protocol: ProtocolName) -> ProviderAdapter:from core.agent_core.ai.registry import create_adapter- images = {"media_sink": media_sink} if protocol == "openai_responses" else {}- return create_adapter(- protocol,- client=client,- media_loader=media_loader,- gateway=True,- **images,- )+ return create_adapter(protocol, client=client, media_loader=media_loader, gateway=True)return creatediff --git a/modules/agents/vibey/tools.py b/modules/agents/vibey/tools.pyindex 739434994..dd16f1919 100644--- a/modules/agents/vibey/tools.py+++ b/modules/agents/vibey/tools.py@@ -21,11 +21,10 @@ from typing import Any, Awaitable, Callable, Mapping, Optional, Sequenceimport httpx-from core.agent_core.agent.models import ModelSelectionfrom core.agent_core.agent.recovery import RecoveryRendererfrom core.agent_core.ai._common import CONNECT_TIMEOUT_S, auth_headers, join_endpoint_urlfrom core.agent_core.ai.hosted import failure, generate_action, image_dimensions, record_text-from core.agent_core.ai.provider import HostedExecutor, MediaSink, ModelEndpoint+from core.agent_core.ai.provider import MediaSink, ModelEndpointfrom core.agent_core.messages import (HostedImage,HostedRecord,@@ -37,6 +36,7 @@ from core.agent_core.messages import (from core.agent_core.tools.base import CallInstance, JobHost, Tool, ToolContext, ToolResult, ToolSpecfrom core.agent_core.tools.hosted import hosted_tool_specfrom core.agent_core.tools.shell import default_shell+from modules.agents.vibey.models import HubModelRouterImageSink = Callable[[bytes, str, str], Awaitable[str]]#: Whether a job's tool call has a durable ``tool_result`` (the adapter's half of J5).@@ -109,9 +109,8 @@ def local_tool_suite(jobs_dir: Optional[str] = None, *, route: Optional[HandOver)-#: The hosted tools a Turn registers, each serving both modes. A generated image, native or proxied, is saved through-#: the media sink as it arrives, so history holds only its path (§7.3).-PARSED_HOSTED_TOOLS = ("web_search", "x_search", "image_generation")+#: The search tools a Turn registers, each serving both modes (§4.1).+PARSED_HOSTED_TOOLS = ("web_search", "x_search")@dataclass(frozen=True)@@ -119,15 +118,15 @@ class HostedTool:"""One hosted tool of the Turn (``vibey-hosted-tools.md`` §3.4, §4.1), with one name and schema in both modes.On a hop whose route for it is native, the adapter sends the provider's declaration in its spec's place and the- provider runs the call. A call that reaches ``execute`` is proxied: the gateway runs it on the executor Model Hub- bound for the Turn, and nothing else. The gateway writes the record; this tool writes the text the model reads,- with the same function that renders a replayed call.+ provider runs the call. A call that reaches ``execute`` is proxied: the gateway runs it on its executor chain,+ which it resolves from the live Turn the request names (§6). The gateway writes the record; this tool writes the+ text the model reads, with the same function that renders a replayed call."""spec: ToolSpec- executor: Optional[HostedExecutor]- #: The Turn's gateway: where the executor endpoint lives, and the token and headers that authorize the call.- endpoint: ModelEndpoint = field(repr=False)+ #: The hop the Turn runs on now: where the executor endpoint lives, and the token and headers that authorize the+ #: call. A re-resolve can move the Turn to another Source, and the gateway answers only the hop it now holds.+ route: Callable[[], ModelEndpoint] = field(repr=False)client: Optional[httpx.AsyncClient] = field(default=None, repr=False)#: Where a proxied image is saved: the same sink as a native one.media: Optional[MediaSink] = field(default=None, repr=False)@@ -143,13 +142,10 @@ class HostedTool:return ToolResult(content=(TextBlock(text),), is_error=failed, hosted=hosted)async def _run(self, arguments: dict[str, Any]) -> HostedResult:- url = join_endpoint_url(self.endpoint.base_url, f"/hosted-tools/{self.spec.name}")- executor = self.executor- body = {- "arguments": arguments,- "executor": {"source_id": executor.source_id, "model_id": executor.model_id} if executor else None,- }- headers = auth_headers(self.endpoint, provider="openai", gateway=True)+ endpoint = self.route()+ url = join_endpoint_url(endpoint.base_url, f"/hosted-tools/{self.spec.name}")+ body = {"arguments": arguments}+ headers = auth_headers(endpoint, provider="openai", gateway=True)# The gateway bounds the call (180 s for a search); only connecting is bounded here.timeout = httpx.Timeout(None, connect=CONNECT_TIMEOUT_S)try:@@ -171,7 +167,7 @@ class HostedTool:hosted = _hosted_result(self.spec.name, answer)except (TypeError, ValueError):return _failed(self.spec.name, "the gateway answered with no hosted result", "gateway_no_result")- if self.spec.name == "image_generation" and hosted.record.status == "completed":+ if self.spec.name == "image_generate" and hosted.record.status == "completed":hosted = await self._saved(hosted, answer)return hosted@@ -206,7 +202,7 @@ class HostedTool:def _failed_record(tool: str, reason: str, code: str) -> HostedRecord:error, error_code = failure(reason, code)return HostedRecord(- status="failed", error=error, error_code=error_code, images=() if tool == "image_generation" else None+ status="failed", error=error, error_code=error_code, images=() if tool == "image_generate" else None)@@ -231,7 +227,7 @@ def _hosted_result(tool: str, body: Any) -> HostedResult:if not isinstance(body, Mapping) or not isinstance(body.get("record"), Mapping):raise ValueError("no hosted record")hosted = {key: body[key] for key in ("record", "execution") if key in body}- if tool == "image_generation":+ if tool == "image_generate":# The executor answers an image's bytes beside the record (``images``); the record lists what is saved.hosted["record"] = {**hosted["record"], "images": []}message = message_from_dict(@@ -250,19 +246,22 @@ def _hosted_result(tool: str, body: Any) -> HostedResult:def hosted_tools(- selection: Optional[ModelSelection],+ router: HubModelRouter,client: Optional[httpx.AsyncClient] = None,media: Optional[MediaSink] = None,) -> tuple[Tool, ...]:"""The Turn's hosted tools: every tool the user enabled, in Model Hub's order, whatever preflight's hop runs it as.They lead the Turn's tools, so its last tool stays a local one whatever a hop renders them as, and the list stays- the same for the whole Turn."""+ the same for the whole Turn. Each call goes out on the hop the Turn runs on then (``HubModelRouter.current``)."""- if selection is None:+ if router.preflight is None:return ()- endpoint = selection.endpoint++ def route() -> ModelEndpoint:+ return router.current.endpoint+return tuple(- HostedTool(hosted_tool_spec(name), route.executor, endpoint, client, media)- for name, route in endpoint.hosted_tools.items()+ HostedTool(hosted_tool_spec(name), route, client, media)+ for name in router.preflight.endpoint.hosted_toolsif name in PARSED_HOSTED_TOOLS)diff --git a/tests/agent_core/agent/test_context.py b/tests/agent_core/agent/test_context.pyindex 0cd4fd334..461e35d4a 100644--- a/tests/agent_core/agent/test_context.py+++ b/tests/agent_core/agent/test_context.py@@ -323,7 +323,7 @@ def test_the_anchor_holds_while_the_transcript_up_to_its_response_is_unchanged()endpoint=replace(ENDPOINT,source_id="src_hostedtest1",- hosted_tools={"web_search": HostedToolRoute("native", None, False, declaration=declaration)},+ hosted_tools={"web_search": HostedToolRoute("native", False, declaration=declaration)},),)as_spec = len(json.dumps([search.name, search.description, dict(search.input_schema)]).encode())diff --git a/tests/agent_core/agent/test_loop.py b/tests/agent_core/agent/test_loop.pyindex c437a31c1..7db4e0eeb 100644--- a/tests/agent_core/agent/test_loop.py+++ b/tests/agent_core/agent/test_loop.py@@ -1206,27 +1206,18 @@ async def test_reasoning_effort_must_be_declared_by_the_route():@pytest.mark.parametrize("stop_reason", ["stop", "length", "refusal", "safety"])[email protected]("shape", ["empty", "whitespace", "thinking", "visible", "image", "search"])[email protected]("shape", ["empty", "whitespace", "thinking", "visible", "search"])@pytest.mark.parametrize("continuation", ["final", "steer", "follow_up"])async def test_tool_free_final_reply_is_committed_and_empty_success_is_an_error(stop_reason, shape, continuation):# The old refusal/safety-only table missed empty successful finals.# Pending-input responses are non-final and must still be allowed to continue.- # A generated image is a reply on its own; a search with no answer is not.+ # A native search with no answer is no reply.native = HostedNative(source_id="src_testsrc1", payload=({"type": "provider_item"},))content = {"empty": (),"whitespace": (text(" \n"),),"thinking": (ThinkingBlock("private reasoning"),),"visible": (ThinkingBlock("private reasoning"), text("visible reply")),- "image": (- HostedToolBlock(- id="ig_1",- tool="image_generation",- action=HostedAction(type="generate", prompt="a laptop at night"),- record=HostedRecord(status="completed", images=(HostedImage(path="/media/ig_1.png", mime="image/png"),)),- native=native,- ),- ),"search": (HostedToolBlock(id="ws_1",@@ -1237,7 +1228,7 @@ async def test_tool_free_final_reply_is_committed_and_empty_success_is_an_error(),),}[shape]- hosted = shape in ("image", "search")+ hosted = shape == "search"message = replace(assistant(stop_reason=stop_reason), content=content, hosted_summary=HostedSummary() if hosted else None)@@ -1263,7 +1254,7 @@ async def test_tool_free_final_reply_is_committed_and_empty_success_is_an_error(["input"] if continuation == "final" else ["input", "pending"])errors = [event for event in events if isinstance(event, AgentError)]- if continuation != "final" or (shape in ("visible", "image") and stop_reason != "length"):+ if continuation != "final" or (shape == "visible" and stop_reason != "length"):assert errors == []assert events[-1].reason == "completed"else:diff --git a/tests/agent_core/ai/_wire.py b/tests/agent_core/ai/_wire.pynew file mode 100644index 000000000..452e96a75--- /dev/null+++ b/tests/agent_core/ai/_wire.py@@ -0,0 +1,41 @@+"""The request an adapter sends, built without sending it: the transform, then the protocol's ``wire_request``."""++from __future__ import annotations++from typing import Optional++from core.agent_core.ai import anthropic, openai_chat, openai_responses+from core.agent_core.ai._common import WireRequest, endpoint_origin, prepare_messages+from core.agent_core.ai.provider import MediaLoader, ModelRequest, ProviderError+from core.agent_core.cancel import CancelToken++_WIRE_REQUESTS = {+ "anthropic": anthropic.wire_request,+ "openai_chat": openai_chat.wire_request,+ "openai_responses": openai_responses.wire_request,+}+++async def build_wire_request(+ request: ModelRequest,+ *,+ gateway: bool,+ media_loader: Optional[MediaLoader] = None,+) -> WireRequest:+ """Exactly what ``request.endpoint.protocol``'s adapter sends for ``request``. Raises ``ValueError`` when the+ request cannot be built."""++ protocol = request.endpoint.protocol+ prepared = await prepare_messages(+ request.messages,+ target=endpoint_origin(request.endpoint),+ supports_images=request.supports_images,+ protocol=protocol,+ media_loader=media_loader,+ cancel=CancelToken(),+ endpoint=request.endpoint,+ )+ if isinstance(prepared, ProviderError):+ raise ValueError(prepared.message)+ messages, loaded_images = prepared+ return _WIRE_REQUESTS[protocol](request, messages, gateway=gateway, loaded_images=loaded_images)diff --git a/tests/agent_core/ai/test_hosted_images.py b/tests/agent_core/ai/test_hosted_images.pydeleted file mode 100644index 146d78f30..000000000--- a/tests/agent_core/ai/test_hosted_images.py+++ /dev/null@@ -1,257 +0,0 @@-"""Native image generation (``vibey-hosted-tools.md`` §7.3, §7.5). Scenario MH-HOSTED-VIBEY-007.--A generated image is saved to a file as its done item is parsed, and the call's record names that file: no base64-enters the message, the transcript or the model's context. Partial previews are never kept, and the terminal response's-copy of the image is never decoded. A stream that may carry an image gets the whole event cap as its line cap.-"""--from __future__ import annotations--import base64-import json-from pathlib import Path-from typing import Any--import httpx-import pytest--from core.agent_core.ai import openai_responses-from core.agent_core.ai.hosted import in_place_text-from core.agent_core.ai.provider import Done, HostedToolRoute, ModelEndpoint, ModelRequest, ProviderError-from core.agent_core.ai.registry import create_adapter-from core.agent_core.cancel import CancelToken-from core.agent_core.messages import HostedAction, HostedImage, HostedToolBlock, TextBlock, UserMessage, message_to_dict-from core.agent_core.tools.hosted import hosted_tool_spec-from core.agent_core.tools.read import MAX_INLINE_IMAGE_BYTES--SOURCE = "src_served00001"-DECLARATION = {"type": "image_generation", "partial_images": 2, "output_format": "jpeg", "output_compression": 90}-JPEG = b"\xff\xd8\xff\xe0" + b"\x00\x10JFIF" + bytes(range(256)) * 4---class Sink:- """The adapter layer's media store, as a directory: each saved image is one file."""-- def __init__(self, root: Path) -> None:- self.root = root- self.saved: list[Path] = []-- async def save_image(self, encoded: str) -> HostedImage:- data = base64.b64decode(encoded, validate=True)- path = self.root / f"image-{len(self.saved)}.jpg"- path.write_bytes(data)- self.saved.append(path)- return HostedImage(path=str(path), mime="image/jpeg", bytes=len(data))---def _sse(*events: tuple[str | None, Any]) -> str:- """Named SSE events; a string payload goes out as it is, so it need not be JSON."""-- frames = []- for name, payload in events:- data = payload if isinstance(payload, str) else json.dumps(payload)- frames.append((f"event: {name}\n" if name else "") + f"data: {data}\n\n")- return "".join(frames)---def _image_item(result: str | None, *, status: str = "completed") -> dict[str, Any]:- item = {- "id": "ig_1",- "type": "image_generation_call",- "status": status,- "revised_prompt": "A lighthouse at dusk, oil painting",- "size": "1536x1024",- "quality": "high",- "output_format": "jpeg",- }- if result is not None:- item["result"] = result- return item---def _stream(- encoded: str,- *,- done: bool = True,- terminal_copy: str = "!!not base64, never decoded!!",- previews: int = 1,- unnamed_previews: bool = False,- status: str = "completed",-) -> str:- events: list[tuple[str | None, Any]] = [- ("response.created", {"type": "response.created", "response": {"status": "in_progress"}}),- (- "response.output_item.added",- {"type": "response.output_item.added", "output_index": 0, "item": _image_item(None, status="in_progress")},- ),- ]- # A preview: not JSON at all here, so the stream fails if anything parses it. A source that names no SSE event- # sends it as JSON, known only by its type.- preview: tuple[str | None, Any] = (- (None, {"type": "response.image_generation_call.partial_image", "partial_image_b64": "AAAA"})- if unnamed_previews- else ("response.image_generation_call.partial_image", "{partial preview bytes")- )- events += [preview] * previews- if done:- events.append(- (- "response.output_item.done",- {"type": "response.output_item.done", "output_index": 0, "item": _image_item(encoded, status=status)},- )- )- message = {"id": "msg_1", "type": "message", "content": [{"type": "output_text", "text": "Here it is.", "annotations": []}]}- events += [- ("response.output_item.added", {"type": "response.output_item.added", "output_index": 1, "item": {**message, "content": []}}),- ("response.output_text.delta", {"type": "response.output_text.delta", "output_index": 1, "delta": "Here it is."}),- ("response.output_item.done", {"type": "response.output_item.done", "output_index": 1, "item": message}),- (- "response.completed",- {- "type": "response.completed",- "response": {"status": "completed", "output": [_image_item(terminal_copy), message], "usage": {}},- },- ),- ]- return _sse(*events)---async def _generate(body: str, sink: Sink | None, *, declared: bool = True) -> list[Any]:- routes = {"image_generation": HostedToolRoute("native", None, False, declaration=DECLARATION)} if declared else {}- request = ModelRequest(- endpoint=ModelEndpoint(- "openai_responses",- "http://hub.invalid/vibey/v1",- "gpt-6-sol",- "hub-token",- provider="openai",- source_id=SOURCE,- hosted_tools=routes,- ),- system="system",- messages=(UserMessage((TextBlock("paint a lighthouse"),)),),- tools=(hosted_tool_spec("image_generation"),),- max_tokens=256,- cache="none",- )- served = {"provider": "openai", "api": "openai_responses", "model": "gpt-6-sol", "source": SOURCE}- headers = {"content-type": "text/event-stream", "x-avibe-served-hop": json.dumps(served, separators=(",", ":"))}- async with httpx.AsyncClient(- transport=httpx.MockTransport(lambda _: httpx.Response(200, headers=headers, text=body))- ) as client:- adapter = create_adapter("openai_responses", client=client, gateway=True, media_sink=sink)- return [event async for event in adapter.stream(request, CancelToken())]---async def test_a_native_image_is_saved_once_from_its_done_item_and_history_holds_only_its_path(tmp_path):- """MH-HOSTED-VIBEY-007: the record names the file, the action keeps the provider's revised prompt and resolved- size and quality, and no copy of the image, done, partial or terminal, enters the message."""-- sink = Sink(tmp_path)- encoded = base64.b64encode(JPEG).decode()-- events = await _generate(_stream(encoded), sink)-- assert isinstance(events[-1], Done), events[-1]- message = events[-1].message- (call,) = [block for block in message.content if isinstance(block, HostedToolBlock)]- assert [path.read_bytes() for path in sink.saved] == [JPEG]- image = HostedImage(path=str(sink.saved[0]), mime="image/jpeg", width=1536, height=1024, bytes=len(JPEG))- assert call.tool == "image_generation" and call.record.status == "completed" and call.record.images == (image,)- assert call.action == HostedAction(- "generate", prompt="A lighthouse at dusk, oil painting", size="1536x1024", quality="high"- )- assert call.native.payload[0]["result"] == str(sink.saved[0])- stored = json.dumps(message_to_dict(message))- assert encoded not in stored and "never decoded" not in stored- assert in_place_text(call).startswith('[image_generation: "A lighthouse at dusk, oil painting"]\nImage saved: ')--- ("done", "status", "encoded", "stored", "error", "code"),- [- (- False,- "completed",- base64.b64encode(JPEG).decode(),- True,- "the image was not streamed before the response ended",- "image_not_streamed",- ),- (True, "completed", "@@@ not base64 @@@", True, "the image could not be saved: ", "image_not_saved"),- (True, "completed", base64.b64encode(JPEG).decode(), False, "nothing here can keep a generated image", "image_no_store"),- (True, "completed", "", True, "the provider returned no image", "provider_no_image"),- # A call the provider did not complete lists no image, so its bytes are never saved: no file without a record.- (True, "failed", base64.b64encode(JPEG).decode(), True, "the provider ended the call failed", "provider_no_reason"),- ],- ids=["only-in-the-terminal-copy", "unreadable", "no-store", "no-image", "failed-with-bytes"],-)-async def test_an_image_that_was_not_saved_is_a_failed_call_never_a_completed_one(- tmp_path, done, status, encoded, stored, error, code-):- """#2589: each reason Avibe writes carries its code, by which a display localizes it."""-- sink = Sink(tmp_path) if stored else None-- events = await _generate(_stream(encoded, done=done, terminal_copy=encoded, status=status), sink)-- (call,) = [block for block in events[-1].message.content if isinstance(block, HostedToolBlock)]- assert call.record.status == "failed" and call.record.error.startswith(error) and call.record.error_code == code- assert call.record.images == () and "result" not in call.native.payload[0]- assert sink is None or not sink.saved---async def test_a_six_megabyte_image_streams_under_the_image_line_cap_and_its_record_says_read_cannot_show_it(tmp_path):- """§7.3, §7.5: an image of 6 MiB is one base64 line over the default 8 MiB line cap, which a stream that may carry- an image raises to the event cap. Such an image is over ``read``'s inline limit, so its record says so; a stream- that declared no image keeps the default cap."""-- large = JPEG + bytes(6 * 1024 * 1024 - len(JPEG))- encoded = base64.b64encode(large).decode()-- events = await _generate(_stream(encoded), Sink(tmp_path))- undeclared = await _generate(_stream(encoded), Sink(tmp_path), declared=False)-- (call,) = [block for block in events[-1].message.content if isinstance(block, HostedToolBlock)]- assert call.record.images[0].bytes == len(large) > MAX_INLINE_IMAGE_BYTES- assert "inline image limit, so read cannot show it" in in_place_text(call)- assert isinstance(undeclared[-1], ProviderError) and "line" in undeclared[-1].message--- ("previews", "unnamed", "budget", "reason"),- [- # The declaration asks for 2 previews and the final: 3 events per image call, and a margin of 2.- (5, False, None, "more images than the response asked for"),- (5, True, None, "more images than the response asked for"),- (1, False, 1024, "more image data than one response may carry"),- ],- ids=["events", "events-known-by-type", "bytes"],-)-async def test_a_response_that_streams_images_past_its_budget_ends_as_an_error(- tmp_path, monkeypatch, previews, unnamed, budget, reason-):- """Plan item 25: previews are never kept, but each counts, named or known by its type, so a provider cannot- stream images without bound."""-- if budget is not None:- monkeypatch.setattr(openai_responses, "IMAGE_BYTES_PER_RESPONSE", budget)- sink = Sink(tmp_path)-- events = await _generate(- _stream(base64.b64encode(JPEG).decode(), previews=previews, unnamed_previews=unnamed), sink- )-- assert isinstance(events[-1], ProviderError) and reason in events[-1].message- assert not sink.saved---def test_the_images_one_response_may_stream_fit_the_terminal_event_that_repeats_them():- """The terminal response repeats every final image in one SSE event: the response's image budget, as base64 with a- margin for the rest of that event, is never more than one event may carry, so a response within its budget is- never rejected by the event cap after its images were saved."""-- from core.agent_core.ai.sse import DEFAULT_MAX_PENDING_EVENT_SIZE-- as_base64 = -(-openai_responses.IMAGE_BYTES_PER_RESPONSE // 3) * 4- assert as_base64 + 1024 * 1024 <= DEFAULT_MAX_PENDING_EVENT_SIZEdiff --git a/tests/agent_core/ai/test_hosted_parsing.py b/tests/agent_core/ai/test_hosted_parsing.pyindex cd813b8fc..edf578ee0 100644--- a/tests/agent_core/ai/test_hosted_parsing.py+++ b/tests/agent_core/ai/test_hosted_parsing.py@@ -40,8 +40,8 @@ SERVED = "src_served00001"ORIGIN_X = Origin("upstream", "openai_responses", "model-x")WEB, X = hosted_tool_spec("web_search"), hosted_tool_spec("x_search")NATIVE = {- "web_search": HostedToolRoute("native", None, False, declaration={"type": "web_search"}),- "x_search": HostedToolRoute("native", None, False, declaration={"type": "x_search"}),+ "web_search": HostedToolRoute("native", False, declaration={"type": "web_search"}),+ "x_search": HostedToolRoute("native", False, declaration={"type": "x_search"}),}diff --git a/tests/agent_core/ai/test_hosted_pause_turn.py b/tests/agent_core/ai/test_hosted_pause_turn.pyindex cab66e4bd..25f46a313 100644--- a/tests/agent_core/ai/test_hosted_pause_turn.py+++ b/tests/agent_core/ai/test_hosted_pause_turn.py@@ -15,7 +15,7 @@ from typing import Any, Callableimport httpximport pytest-from core.agent_core.ai._common import PIN_MODEL_HEADER, PIN_SOURCE_HEADER+from core.agent_core.ai._common import PIN_MODEL_HEADER, PIN_SOURCE_HEADER, portable_endpointfrom core.agent_core.ai.anthropic import MAX_PAUSE_CONTINUATIONS, PAUSE_LIMIT_MESSAGE, PAUSE_UNSERVED_MESSAGEfrom core.agent_core.ai.provider import Done, HostedToolRoute, ModelEndpoint, ModelRequest, ProviderErrorfrom core.agent_core.ai.registry import create_adapter@@ -36,7 +36,7 @@ _PIN_UNAVAILABLE = {"type": "error", "error": {"type": "model_hub_pin_unavailabldef _request(*, cache: str = "none", base_url: str = "http://hub.invalid/vibey/v1") -> ModelRequest:- route = HostedToolRoute("native", None, False, declaration=DECLARATION)+ route = HostedToolRoute("native", False, declaration=DECLARATION)return ModelRequest(endpoint=ModelEndpoint("anthropic",@@ -204,17 +204,18 @@ async def test_a_response_paused_past_the_bound_ends_interrupted_and_keeps_every@pytest.mark.parametrize(- ("unavailable", "reported", "sends", "kept"),- [(2, True, 2, "part 1"), (1, True, 2, "part 2"), (None, False, 1, "part 1")],+ ("unavailable", "reported", "portable", "sends"),+ [(2, True, False, 2), (None, True, True, 1), (None, False, False, 1)],ids=["continuation-pin-unavailable", "paused-unpinned-send", "paused-unverified-response"],)async def test_a_paused_response_its_source_cannot_continue_ends_interrupted_and_keeps_what_it_has(- unavailable, reported, sends, kept+ unavailable, reported, portable, sends):"""§4.3 as implemented: a continuation goes only to the Source that served the paused response, pinned, so theresponse stays one origin's message. It ends without another send when:- - that Source answers the continuation ``pin_unavailable``;- - the paused send carried no pin (the turn's portable resend);+ - that Source answers the continuation ``pin_unavailable``: the response has output, so the loop never renders it+ again (§3.5);+ - the paused send carried no pin (a portable request);- the paused response named no Source, so its hosted calls could not be kept to send back."""def answer(number: int) -> httpx.Response:@@ -223,12 +224,16 @@ async def test_a_paused_response_its_source_cannot_continue_ends_interrupted_andbody = _response(_text(f"part {number}"), stop_reason="pause_turn", input_tokens=10, output_tokens=1)return httpx.Response(200, headers=_served(reported=reported), text=body)- sent, events = await _stream(answer)+ request = _request()+ if portable:+ request = replace(request, endpoint=portable_endpoint(request.endpoint))+ sent, events = await _stream(answer, request)assert len(sent) == sendserror = events[-1]assert isinstance(error, ProviderError) and error.kind == "interrupted" and error.message == PAUSE_UNSERVED_MESSAGE- assert [block.text for block in error.partial.content if isinstance(block, TextBlock)] == [kept]+ assert error.refusal is None+ assert [block.text for block in error.partial.content if isinstance(block, TextBlock)] == ["part 1"]assert sum(isinstance(event, (Done, ProviderError)) for event in events) == 1diff --git a/tests/agent_core/ai/test_hosted_replay.py b/tests/agent_core/ai/test_hosted_replay.pyindex 20e932bdf..5187bc2ee 100644--- a/tests/agent_core/ai/test_hosted_replay.py+++ b/tests/agent_core/ai/test_hosted_replay.py@@ -2,8 +2,8 @@A hosted call goes back verbatim, its native payload in place, only to the Source that served it, on the same origin,and either within its turn or with the hop's current ``replay`` evidence. Such a request is pinned to that Source; an-in-flight continuation also names the model that served it. When the gateway answers ``pin_unavailable``, the adapter-sends the same request exactly once more, in portable form and unpinned.+in-flight continuation also names the model that served it. A refusal before any output, the gateway's+``pin_unavailable`` or xAI's decrypt refusal, ends the send; the loop renders the request again within its bounds."""from __future__ import annotations@@ -15,9 +15,20 @@ from typing import Anyimport httpximport pytest+from core.agent_core.agent.events import RunEnded+from core.agent_core.agent.loop import Agent+from core.agent_core.agent.models import ModelSelectionfrom core.agent_core.ai._common import PIN_MODEL_HEADER, PIN_SOURCE_HEADER-from core.agent_core.ai.provider import Done, HostedToolRoute, ModelEndpoint, ModelRequest, ProviderError-from core.agent_core.ai.registry import build_wire_request, create_adapter+from core.agent_core.ai.provider import (+ HostedToolRoute,+ ModelCapabilities,+ ModelEndpoint,+ ModelRequest,+ ProviderError,+ Refusal,+)+from core.agent_core.ai.registry import create_adapter+from tests.agent_core.ai._wire import build_wire_requestfrom core.agent_core.cancel import CancelTokenfrom core.agent_core.messages import (AssistantMessage,@@ -34,6 +45,7 @@ from core.agent_core.messages import (UserMessage,)from core.agent_core.tools.hosted import hosted_tool_spec+from tests.agent_core.fakes import FakeJobHost, FakeTool, InMemoryTranscriptStore, input_rowSOURCE = "src_served00001"OTHER = "src_other000001"@@ -63,9 +75,9 @@ def _endpoint(protocol: str, *, replay: bool, native: bool = True, source_id: stprovider, model = MODELS[protocol]declaration = {"type": "web_search_20250305", "name": "web_search"} if protocol == "anthropic" else {"type": "web_search"}route = (- HostedToolRoute("native", None, replay, declaration=declaration)+ HostedToolRoute("native", replay, declaration=declaration)if native- else HostedToolRoute("proxy", None, replay)+ else HostedToolRoute("proxy", replay))return ModelEndpoint(protocol, # type: ignore[arg-type]@@ -137,7 +149,7 @@ async def test_a_hosted_call_goes_back_verbatim_and_pinned_only_to_its_own_sourcprotocol, replay, served_by, identity, verbatim):request = _request(- _endpoint(protocol, replay=replay, native=False),+ _endpoint(protocol, replay=replay),_searched(protocol, served_by=served_by, identity=identity),UserMessage((TextBlock("and then?"),)),)@@ -145,30 +157,33 @@ async def test_a_hosted_call_goes_back_verbatim_and_pinned_only_to_its_own_sourcwire = await build_wire_request(request, gateway=True)assert _verbatim(protocol, wire.body) is verbatim- # The request carries no native declaration here (a proxied route), so only a verbatim payload pins it.- assert (wire.headers.get(PIN_SOURCE_HEADER) == SOURCE) is verbatim+ # A payload goes back verbatim only where the tool is declared natively, so the request is pinned either way.+ assert wire.headers[PIN_SOURCE_HEADER] == SOURCEassert PIN_MODEL_HEADER not in wire.headers@pytest.mark.parametrize("protocol", ["openai_responses", "anthropic"])@pytest.mark.parametrize(- ("hop_source", "after", "continued"),+ ("hop_source", "native", "after", "continued"),[- (SOURCE, (), True),- (OTHER, (), False),- (SOURCE, (UserMessage((TextBlock("a new turn"),)),), False),+ (SOURCE, True, (), True),+ (OTHER, True, (), False),+ # A refusal's fresh hop on the same Source that no longer runs the tool natively (§3.5).+ (SOURCE, False, (), False),+ (SOURCE, True, (UserMessage((TextBlock("a new turn"),)),), False),],- ids=["on-the-hop-that-served-it", "after-the-hop-moved", "after-its-turn-ended"],+ ids=["on-the-hop-that-served-it", "after-the-hop-moved", "after-the-tool-turned-proxy", "after-its-turn-ended"],)-async def test_a_continuation_goes_back_verbatim_only_to_the_hop_that_served_it(protocol, hop_source, after, continued):+async def test_a_continuation_goes_back_verbatim_only_to_the_hop_that_served_it(protocol, hop_source, native, after, continued):"""Within its turn the provider's own continuation contract applies: no replay evidence is needed, and the requestis pinned to its hop's Source and the model that served the response it continues. A fresh hop that is another- Source gets the in-place form instead (§4.4), so one hop builds and serves the request. A turn can end right after- its tool results; a later turn is no continuation, so without replay evidence its calls go back portable."""+ Source, or that no longer declares the tool natively, gets the in-place form instead (§4.4), since a provider+ refuses server items without their declaration. A turn can end right after its tool results; a later turn is no+ continuation, so without replay evidence its calls go back portable."""read = ToolCallBlock(id="toolu_1", name="read", arguments={"path": "a"})request = _request(- _endpoint(protocol, replay=False, source_id=hop_source),+ _endpoint(protocol, replay=False, native=native, source_id=hop_source),_searched(protocol, stop_reason="tool_use", extra=(read,)),ToolResultMessage("toolu_1", "read", (TextBlock("contents"),)),*after,@@ -177,10 +192,10 @@ async def test_a_continuation_goes_back_verbatim_only_to_the_hop_that_served_it(wire = await build_wire_request(request, gateway=True)assert _verbatim(protocol, wire.body) is continued- # The hop's native declaration pins every case to the hop's own Source.- assert wire.headers[PIN_SOURCE_HEADER] == hop_source+ # The hop's native declaration pins the request to the hop's own Source; without one nothing pins it.+ assert wire.headers.get(PIN_SOURCE_HEADER) == (hop_source if native else None)assert (wire.headers.get(PIN_MODEL_HEADER) == MODELS[protocol][1]) is continued- if hop_source == OTHER:+ if not continued and not after:in_place = json.dumps(wire.body)assert '[web_search: \\"avibe release\\"]' in in_place@@ -238,47 +253,246 @@ def _tool_name(tool: dict[str, Any]) -> str:return tool.get("name") or tool["function"]["name"]+def _sse(protocol: str, events: tuple[dict[str, Any], ...]) -> str:+ body = "".join(f"data: {json.dumps(event)}\n\n" for event in events)+ return body + ("data: [DONE]\n\n" if protocol == "openai_chat" else "")+++def _served(protocol: str, source: str = SOURCE) -> dict[str, str]:+ provider, model = MODELS[protocol]+ report = {"provider": provider, "api": protocol, "model": model, "source": source}+ return {"content-type": "text/event-stream", "x-avibe-served-hop": json.dumps(report, separators=(",", ":"))}+++async def _send(request: ModelRequest, answer: Any) -> tuple[list[httpx.Request], list[Any]]:+ sent: list[httpx.Request] = []++ def gateway(wire: httpx.Request) -> httpx.Response:+ sent.append(wire)+ return answer(len(sent))++ protocol = request.endpoint.protocol+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ adapter = create_adapter(protocol, client=client, gateway=True)+ events = [event async for event in adapter.stream(request, CancelToken())]+ return sent, events+++def _hosted_unsupported(tool: str = "web_search", aspect: str = "call", source_id: str = SOURCE) -> dict[str, Any]:+ reason = {"kind": "hosted_unsupported", "tool": tool, "aspect": aspect, "source_id": source_id}+ return {"type": "error", "error": {**_PIN_UNAVAILABLE["error"], "message": "refused", "reason": reason}}++@pytest.mark.parametrize("protocol", ["openai_responses", "anthropic", "openai_chat"])@pytest.mark.parametrize(- ("second", "served_by"),- [("served", OTHER), ("served", SOURCE), ("pin_unavailable", OTHER)],- ids=["served-by-another-source", "served-by-its-source", "pin_unavailable"],+ ("native", "body", "refusal"),+ [+ (True, _PIN_UNAVAILABLE, Refusal("pin_unavailable", SOURCE, IDENTITY)),+ (True, _hosted_unsupported(), Refusal("pin_unavailable", SOURCE, IDENTITY, "web_search", "call")),+ # A 409 to an unpinned request is the gateway's ordinary error: nothing was handed back.+ (False, _PIN_UNAVAILABLE, None),+ ],+ ids=["no-reason", "narrow-rule-reason", "unpinned"],+)+async def test_pin_unavailable_ends_the_pinned_send_as_a_refusal_with_no_output(protocol, native, body, refusal):+ """MH-HOSTED-VIBEY-005: the gateway's hand-back, matched on ``type`` and ``code`` with any other field tolerated,+ ends the pinned send with one error that carries the refusal, the narrow rule when one fired, and no output. The+ adapter sends nothing more and the generic retry never takes it: the loop renders the request again (§3.5)."""++ request = _request(_endpoint(protocol, replay=True, native=native))++ sent, events = await _send(request, lambda _: httpx.Response(409, json=body))++ assert len(sent) == 1 and (PIN_SOURCE_HEADER in sent[0].headers) is native+ (error,) = events+ assert isinstance(error, ProviderError) and error.status == 409 and error.partial is None+ assert error.refusal == refusal+ if refusal is not None:+ assert not error.retryable+++_DECRYPT_REFUSAL = "Could not decrypt the provided encrypted_content"++[email protected]("native", [True, False], ids=["pinned", "unpinned"])+ ("body", "refused"),+ [+ (_DECRYPT_REFUSAL, True),+ # A relay may wrap the provider's text in its own error object.+ (json.dumps({"error": {"message": _DECRYPT_REFUSAL, "type": "invalid_request_error"}}), True),+ ("Invalid request: unknown parameter", False),+ ],+ ids=["plain-text", "wrapped", "another-400"],)-async def test_pin_unavailable_gets_exactly_one_portable_resend_and_never_the_generic_retry(protocol, second, served_by):- """MH-HOSTED-VIBEY-005: the pinned request carries a native declaration and, where the protocol replays one, a- verbatim payload. Its one resend carries neither and no pin; that resend's own answer is what the loop sees. A- resend the hop's own Source serves is still its own: the answer keeps that Source's identity."""-- replayed = protocol in PAYLOADS- history = (_searched(protocol), UserMessage((TextBlock("and then?"),))) if replayed else ()- endpoint = _endpoint(protocol, replay=True)- request = _request(endpoint, *history)- provider, model = MODELS[protocol]- served = json.dumps({"provider": provider, "api": protocol, "model": model, "source": served_by}, separators=(",", ":"))+async def test_a_decrypt_refusal_ends_the_send_as_an_opaque_refusal_of_its_source_identity(native, body, refused):+ """xAI's plain-text 400 for a replayed ciphertext it cannot read says neither which one nor why. The adapter, its+ one classifier, ends the send with an opaque refusal of the request's Source identity, pinned or not (§3.5)."""++ request = _request(_endpoint("openai_responses", replay=True, native=native))++ sent, events = await _send(request, lambda _: httpx.Response(400, text=body))++ (error,) = events+ assert len(sent) == 1 and isinstance(error, ProviderError) and error.status == 400 and not error.retryable+ assert error.refusal == (Refusal("opaque_refused", SOURCE, IDENTITY) if refused else None)+++# The loop answers a refusal (§3.5). These run a turn through the Agent loop and the real adapters against a stub+# gateway; each resolution is the next hop of the run.++THIRD = "src_third000001"+CAPABILITIES = ModelCapabilities(context_window=200_000, max_output_tokens=4096, supports_tools=True)+X_DECLARATION = {"type": "x_search"}+READ = FakeTool("read")+++class _Hops:+ def __init__(self, client: httpx.AsyncClient, hops: tuple[ModelEndpoint, ...]) -> None:+ self.client, self.hops, self.resolved = client, hops, 0++ async def resolve(self) -> ModelSelection:+ hop = self.hops[min(self.resolved, len(self.hops) - 1)]+ self.resolved += 1+ return ModelSelection(hop, CAPABILITIES)++ def provider_for(self, protocol: str) -> Any:+ return create_adapter(protocol, client=self.client, gateway=True) # type: ignore[arg-type]+++def _hosted_tool(name: str) -> FakeTool:+ tool = FakeTool(name)+ tool.spec = hosted_tool_spec(name)+ return tool+++async def _turn(answer: Any, *hops: ModelEndpoint, tools: tuple[Any, ...]) -> tuple[list[httpx.Request], Any, int]:+ """One turn; ``answer(n, body)`` answers the n-th request the gateway receives."""+sent: list[httpx.Request] = []def gateway(wire: httpx.Request) -> httpx.Response:sent.append(wire)- if len(sent) == 1 or second == "pin_unavailable":- return httpx.Response(409, json=_PIN_UNAVAILABLE)- body = "".join(f"data: {json.dumps(event)}\n\n" for event in _ANSWERED[protocol])- body += "data: [DONE]\n\n" if protocol == "openai_chat" else ""- return httpx.Response(200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": served}, text=body)+ return answer(len(sent), json.loads(wire.content))async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:- adapter = create_adapter(protocol, client=client, gateway=True) # type: ignore[arg-type]- events = [event async for event in adapter.stream(request, CancelToken())]+ router = _Hops(client, hops)+ agent = Agent(+ session_id="session",+ models=router,+ tools=tools,+ hooks=(),+ store=InMemoryTranscriptStore(),+ jobs=FakeJobHost(),+ cwd="/test-owned",+ )+ events = [event async for event in agent.run(input_row("input", "search"), turn_id="turn")]+ ended = events[-1]+ assert isinstance(ended, RunEnded)+ return sent, ended, router.resolved+++def _xai(source_id: str = SOURCE, *, web: bool = True, model: str = "grok-4.6") -> ModelEndpoint:+ """An xAI hop: ``x_search`` native, ``web_search`` native while ``web`` holds."""++ web_route = HostedToolRoute("native", True, declaration={"type": "web_search"}) if web else HostedToolRoute("proxy", False)+ return replace(+ _endpoint("openai_responses", replay=True, source_id=source_id),+ model_id=model,+ hosted_tools={"web_search": web_route, "x_search": HostedToolRoute("native", True, declaration=X_DECLARATION)},+ )+++def _answered(number: int, body: dict[str, Any]) -> httpx.Response:+ return httpx.Response(200, headers=_served("openai_responses"), text=_sse("openai_responses", _ANSWERED["openai_responses"]))- assert len(sent) == 2- pinned, portable = (json.loads(wire.content) for wire in sent)- assert sent[0].headers[PIN_SOURCE_HEADER] == SOURCE and PIN_SOURCE_HEADER not in sent[1].headers- assert pinned["tools"] == [dict(endpoint.hosted_tools["web_search"].declaration)]- assert [_tool_name(tool) for tool in portable["tools"]] == ["web_search"] and portable["tools"] != pinned["tools"]- if replayed:- assert _verbatim(protocol, pinned) and not _verbatim(protocol, portable)- if second == "served":- assert isinstance(events[-1], Done)- assert events[-1].message.source_identity == (IDENTITY if served_by == SOURCE else None)++async def test_a_narrow_refusal_is_answered_by_a_fresh_hop_that_runs_only_that_tool_as_its_function():+ """MH-HOSTED-VIBEY-005: the gateway refuses the pinned request because ``web_search`` cannot run natively there and+ writes that evidence; the fresh hop says so. The request is rendered again for it: ``web_search`` as its function,+ ``x_search`` still native and the request still pinned. No output was lost and nothing waited for a retry."""++ def answer(number: int, body: dict[str, Any]) -> httpx.Response:+ return httpx.Response(409, json=_hosted_unsupported()) if number == 1 else _answered(number, body)++ sent, ended, resolved = await _turn(+ answer, _xai(), _xai(web=False), tools=(_hosted_tool("web_search"), _hosted_tool("x_search"))+ )++ assert ended.reason == "completed" and resolved == 2 and len(sent) == 2+ first, second = (json.loads(wire.content)["tools"] for wire in sent)+ assert first == [{"type": "web_search"}, X_DECLARATION]+ assert second[0]["name"] == "web_search" and second[1] == X_DECLARATION+ assert sent[1].headers[PIN_SOURCE_HEADER] == SOURCE+++ ("hops", "refusals", "pins", "resolved"),+ [+ # The fresh hop is the refused one again: the same request would go out, so it goes portable at once.+ ((_xai(), _xai()), (_PIN_UNAVAILABLE,), (SOURCE, None), 2),+ # One fresh hop per (Source, tool, aspect): the same rule refusing again on another model there goes portable.+ ((_xai(), _xai(model="grok-4.6-fast")), (_hosted_unsupported(),) * 2, (SOURCE, SOURCE, None), 2),+ # At most two fresh hops in a turn, whatever the reason: a third refusal goes portable on the hop it has.+ ((_xai(), _xai(OTHER), _xai(THIRD)), (_PIN_UNAVAILABLE,) * 3, (SOURCE, OTHER, THIRD, None), 3),+ ],+ ids=["same-hop", "per-rule", "per-turn"],+)+async def test_refusals_are_answered_within_their_bounds_and_portable_rendering_is_the_last_resort(+ hops, refusals, pins, resolved+):+ """A portable request is never pinned, so the gateway never hands it back: every refusal chain ends."""++ def answer(number: int, body: dict[str, Any]) -> httpx.Response:+ return httpx.Response(409, json=refusals[number - 1]) if number <= len(refusals) else _answered(number, body)++ sent, ended, resolutions = await _turn(answer, *hops, tools=(_hosted_tool("web_search"), _hosted_tool("x_search")))++ assert ended.reason == "completed" and resolutions == resolved+ assert tuple(wire.headers.get(PIN_SOURCE_HEADER) for wire in sent) == pins+ portable = json.loads(sent[-1].content)["tools"]+ assert [_tool_name(tool) for tool in portable] == ["web_search", "x_search"]+++def _reasoned(cipher: str, *, call: str | None) -> str:+ """An xAI response: a reasoning item carrying ``cipher``, then a ``read`` call or a final answer."""++ reasoning = {"id": f"rs_{cipher}", "type": "reasoning", "summary": [], "encrypted_content": cipher}+ if call is None:+ last = {"id": "msg_1", "type": "message", "content": [{"type": "output_text", "text": "ok", "annotations": []}]}+ else:+ last = {"id": f"fc_{call}", "type": "function_call", "call_id": call, "name": "read", "arguments": "{}"}+ events = (+ {"type": "response.output_item.added", "output_index": 0, "item": {**reasoning, "encrypted_content": None}},+ {"type": "response.output_item.done", "output_index": 0, "item": reasoning},+ {"type": "response.output_item.added", "output_index": 1, "item": {**last, "status": "in_progress"}},+ {"type": "response.output_item.done", "output_index": 1, "item": last},+ {"type": "response.completed", "response": {"status": "completed", "output": None, "usage": {"input_tokens": 5, "output_tokens": 1}}},+ )+ return _sse("openai_responses", events)++[email protected]("again", [False, True], ids=["answered", "refused-again"])+async def test_a_decrypt_refusal_drops_every_opaque_payload_of_that_identity_for_the_rest_of_the_turn(again):+ """xAI's encrypted reasoning rides an ordinary, unpinned request. Refused, the request is rendered again without any+ of that identity's ciphertext, and every later request of the turn too, including ciphertext issued after the+ refusal: the refusal does not say which one failed. That is answered once per identity; refused again, the error+ stands."""++ def answer(number: int, body: dict[str, Any]) -> httpx.Response:+ if number == 2 or (number == 3 and again):+ return httpx.Response(400, text=_DECRYPT_REFUSAL)+ reply = {1: _reasoned("cipher-1", call="call_1"), 3: _reasoned("cipher-3", call="call_3")}.get(number)+ return httpx.Response(200, headers=_served("openai_responses"), text=reply or _reasoned("cipher-4", call=None))++ unpinned = replace(_endpoint("openai_responses", replay=False, native=False), hosted_tools={})+ sent, ended, _ = await _turn(answer, unpinned, tools=(READ,))++ bodies = [wire.content.decode() for wire in sent]+ assert all(PIN_SOURCE_HEADER not in wire.headers for wire in sent)+ assert "cipher-1" in bodies[1]+ assert not any(cipher in body for body in bodies[2:] for cipher in ("cipher-1", "cipher-3"))+ if again:+ assert len(sent) == 3 and ended.reason == "error"else:- # A 409 to an unpinned request is an ordinary error: there is no second portable resend.- assert isinstance(events[-1], ProviderError) and events[-1].status == 409+ assert len(sent) == 4 and ended.reason == "completed"diff --git a/tests/agent_core/ai/test_hosted_requests.py b/tests/agent_core/ai/test_hosted_requests.pyindex c28624348..6a927a9bc 100644--- a/tests/agent_core/ai/test_hosted_requests.py+++ b/tests/agent_core/ai/test_hosted_requests.py@@ -1,9 +1,10 @@-"""Hosted-tool request building (``vibey-hosted-tools.md`` §3.2, §3.5, §4.1), read on the wire.+"""Hosted-tool request building (``vibey-hosted-tools.md`` §3.5, §4.1), read on the wire.-``ModelRequest.tools`` is the one owner of what a request declares. A hosted tool's canonical spec is sent as the-overlay's declaration, verbatim and in its place, on a hop whose route for it is native, with the route's Responses+``ModelRequest.tools`` is the one owner of what a request declares. A search tool's canonical spec is sent as the+overlay's declaration, verbatim and in its place, on a hop whose facts assume it runs natively, with its Responses``include`` values, and that request is pinned to the hop's Source; anywhere else the spec is an ordinary function.-``build_wire_request`` is the probe's entry: it must be exactly what the adapter sends. Scenario MH-HOSTED-VIBEY-001.+The tests read requests through ``build_wire_request``, which must be exactly what the adapter sends.+Scenario MH-HOSTED-VIBEY-001."""from __future__ import annotations@@ -17,19 +18,18 @@ import pytestfrom core.agent_core.ai._common import PIN_SOURCE_HEADERfrom core.agent_core.ai.provider import (Done,- HostedExecutor,HostedToolRoute,ModelEndpoint,ModelRequest,)-from core.agent_core.ai.registry import build_wire_request, create_adapter+from core.agent_core.ai.registry import create_adapter+from tests.agent_core.ai._wire import build_wire_requestfrom core.agent_core.cancel import CancelTokenfrom core.agent_core.messages import TextBlock, UserMessagefrom core.agent_core.tools.base import ToolSpecfrom core.agent_core.tools.hosted import hosted_tool_specSOURCE = "src_hostedprobe1"-EXECUTOR = HostedExecutor("src_xaiexecutor1", "grok-4.6")READ = ToolSpec("read", "Read a file.", {"type": "object", "properties": {"path": {"type": "string"}}})BASH = ToolSpec("bash", "Run a command.", {"type": "object", "properties": {"command": {"type": "string"}}})WEB = hosted_tool_spec("web_search")@@ -63,10 +63,10 @@ STREAMS = {def _native(declaration: dict[str, Any], include: tuple[str, ...] = ()) -> HostedToolRoute:- return HostedToolRoute("native", EXECUTOR, False, declaration=declaration, include=include)+ return HostedToolRoute("native", False, declaration=declaration, include=include)-PROXY = HostedToolRoute("proxy", EXECUTOR, False)+PROXY = HostedToolRoute("proxy", False)def _request(@@ -75,7 +75,6 @@ def _request(*,tools: tuple[ToolSpec, ...] = (READ, BASH),effort: str | None = "high",- tool_choice: str | None = None,source_id: str | None = SOURCE,) -> ModelRequest:return ModelRequest(@@ -94,7 +93,6 @@ def _request(tools=tools,max_tokens=256,reasoning_effort=effort,- tool_choice=tool_choice,)@@ -168,20 +166,17 @@ async def test_without_a_declared_native_tool_every_tool_is_a_function_and_the_r@pytest.mark.parametrize(- ("protocol", "hosted", "tools", "tool_choice"),+ ("protocol", "hosted", "tools"),[- ("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, (WEB, READ, BASH), None),- ("openai_responses", {"web_search": _native(OPENAI_SEARCH, (SOURCES_INCLUDE,))}, (WEB, READ, BASH), None),- ("openai_chat", {"web_search": PROXY}, (WEB, READ, BASH), "read"),- # Call probes: the hosted tool alone, forced on Responses and asked for in the message on Anthropic.- ("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, (WEB,), None),- ("openai_responses", {"x_search": _native(X_SEARCH)}, (X,), "x_search"),+ ("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, (WEB, READ, BASH)),+ ("openai_responses", {"web_search": _native(OPENAI_SEARCH, (SOURCES_INCLUDE,))}, (WEB, READ, BASH)),+ ("openai_chat", {"web_search": PROXY}, (WEB, READ, BASH)),],)-async def test_the_probe_entry_builds_exactly_the_request_the_adapter_sends(- protocol: str, hosted: dict[str, HostedToolRoute], tools: tuple[ToolSpec, ...], tool_choice: str | None+async def test_the_wire_builder_the_tests_read_is_exactly_the_request_the_adapter_sends(+ protocol: str, hosted: dict[str, HostedToolRoute], tools: tuple[ToolSpec, ...]) -> None:- request = _request(protocol, hosted, tools=tools, tool_choice=tool_choice)+ request = _request(protocol, hosted, tools=tools)sent: list[httpx.Request] = []def gateway(wire: httpx.Request) -> httpx.Response:@@ -200,47 +195,10 @@ async def test_the_probe_entry_builds_exactly_the_request_the_adapter_sends(assert json.loads(wire.content) == built.body- ("protocol", "hosted", "tools", "tool_choice", "expected"),- [- # OpenAI's hosted choice types have no web_search or x_search: `required` over the tool alone forces it.- ("openai_responses", {"web_search": _native(OPENAI_SEARCH)}, (WEB,), "web_search", "required"),- ("openai_responses", {}, (READ, BASH), "read", {"type": "function", "name": "read"}),- ("openai_chat", {}, (READ, BASH), "bash", {"type": "function", "function": {"name": "bash"}}),- ],-)-async def test_tool_choice_forces_the_named_tool_in_each_protocols_form(- protocol: str, hosted: dict[str, HostedToolRoute], tools: tuple[ToolSpec, ...], tool_choice: str, expected: Any-) -> None:- wire = await build_wire_request(_request(protocol, hosted, tools=tools, tool_choice=tool_choice), gateway=True)-- assert wire.body["tool_choice"] == expected+async def test_a_native_declaration_is_never_sent_unpinned() -> None:+ """Unpinned, the gateway could fail a native declaration over to a hop that does not run the tool."""+ request = _request("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, tools=(WEB, READ), source_id=None)- ("request_", "refusal"),- [- # `required` would let the model pick a function instead of the hosted tool.- (- _request(- "openai_responses", {"web_search": _native(OPENAI_SEARCH)}, tools=(WEB, READ), tool_choice="web_search"- ),- "only tool",- ),- (_request("openai_chat", {}, tool_choice="web_search"), "does not declare"),- # Current Claude models and extended thinking refuse a forced choice: a probe would test that refusal.- (- _request("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, tools=(WEB,), tool_choice="web_search"),- "never",- ),- # A native declaration is never sent unpinned: unpinned, the gateway could fail it over to an unverified hop.- (- _request("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, tools=(WEB, READ), source_id=None),- "pinned",- ),- ],- ids=["forced-hosted-beside-functions", "forced-undeclared", "anthropic-forced", "native-without-source"],-)-async def test_a_request_that_cannot_be_sent_as_specified_is_refused(request_: ModelRequest, refusal: str) -> None:- with pytest.raises(ValueError, match=refusal):- await build_wire_request(request_, gateway=True)+ with pytest.raises(ValueError, match="pinned"):+ await build_wire_request(request, gateway=True)diff --git a/tests/agent_core/ai/test_hosted_transform.py b/tests/agent_core/ai/test_hosted_transform.pyindex 9481bb05e..7883e4ac3 100644--- a/tests/agent_core/ai/test_hosted_transform.py+++ b/tests/agent_core/ai/test_hosted_transform.py@@ -13,7 +13,7 @@ import itertoolsimport pytestfrom core.agent_core.ai.provider import ModelEndpoint, ModelRequest-from core.agent_core.ai.registry import build_wire_request+from tests.agent_core.ai._wire import build_wire_requestfrom core.agent_core.ai.transform import SYNTHETIC_TOOL_RESULT, transform_messagesfrom core.agent_core.messages import (AssistantMessage,diff --git a/tests/agent_core/ai/test_provider_adapters.py b/tests/agent_core/ai/test_provider_adapters.pyindex b2210ba5e..5a13f7751 100644--- a/tests/agent_core/ai/test_provider_adapters.py+++ b/tests/agent_core/ai/test_provider_adapters.py@@ -30,7 +30,8 @@ from core.agent_core.ai.provider import (ToolCallDelta,ToolCallStart,)-from core.agent_core.ai.registry import ADAPTERS, adapter_class, build_wire_request, sent_effort+from core.agent_core.ai.registry import ADAPTERS, adapter_class, sent_effort+from tests.agent_core.ai._wire import build_wire_requestfrom core.agent_core.cancel import CancelTokenfrom core.agent_core.messages import (AssistantMessage,diff --git a/tests/agent_core/test_hosted_messages.py b/tests/agent_core/test_hosted_messages.pyindex 864806eca..59e90c033 100644--- a/tests/agent_core/test_hosted_messages.py+++ b/tests/agent_core/test_hosted_messages.py@@ -19,6 +19,7 @@ from core.agent_core.messages import (HOSTED_ERROR_CODES,AssistantMessage,Citation,+ FailedAttempt,HostedAction,HostedCost,HostedImage,@@ -91,23 +92,6 @@ def _produced() -> list:record=HostedRecord(status="pending"),native=_native({"type": "custom_tool_call", "name": "x_bookmark_lookup"}),),- HostedToolBlock(- id="ig_1",- tool="image_generation",- action=HostedAction(type="generate", prompt="一只猫, watercolor", size="1536x1024", quality="low"),- record=HostedRecord(- status="completed",- images=(HostedImage(path="/tmp/media/image-3f2a.png", mime="image/png", width=1536, height=1024),),- ),- native=_native({"type": "image_generation_call", "result": "[image saved: /tmp/media/image-3f2a.png]"}),- ),- HostedToolBlock(- id="ig_2",- tool="image_generation",- action=HostedAction(type="generate"),- record=HostedRecord(status="failed", error="moderation_blocked", images=()),- native=_native({"type": "image_generation_call", "status": "failed"}),- ),TextBlock(text=answer,citations=(@@ -136,25 +120,48 @@ def _produced() -> list:content=(TextBlock(text="1. Avibe 本地优先 — https://x.com/avibe/status/1"),),hosted=HostedResult(record=HostedRecord(status="completed", sources=(POST,)),+ # The chain's first executor failed after billing, and its cost is in the sum.execution=ProxyExecution(- executor_origin=XAI, executor_source_id=SOURCE, executor_billing="metered", cost=HostedCost(basis="list", usd=0.03)+ executor_origin=XAI,+ executor_source_id=SOURCE,+ executor_billing="metered",+ cost=HostedCost(basis="list", usd=0.03),+ failed_attempts=(FailedAttempt("src_o9p8q7r6s5", "metered", HostedCost(basis="list", usd=0.01)),),),),)included = ToolResultMessage(tool_call_id="call_8",- tool_name="image_generation",+ tool_name="image_generate",content=(TextBlock(text="[image saved: /tmp/media/image-77.png · 1024x1024]"),),hosted=HostedResult(record=HostedRecord(status="completed", images=(HostedImage(path="/tmp/media/image-77.png", mime="image/webp"),)),execution=ProxyExecution(- executor_origin=Origin(provider="openai", api="openai_responses", model="gpt-6-astra"),+ executor_origin=Origin(provider="openai", api="openai_responses", model="gpt-image-2"),executor_source_id="src_o9p8q7r6s5",executor_billing="monthly",cost=HostedCost(basis="included"),+ mode="direct",+ ),+ # What the image endpoint rendered: the model, its revised prompt and the resolved size and quality.+ action=HostedAction(+ type="generate", prompt="A lighthouse at dusk", size="1024x1024", quality="high", model="gpt-image-2"),- # What the executor rendered: its revised prompt and the resolved size and quality.- action=HostedAction(type="generate", prompt="A lighthouse at dusk", size="1024x1024", quality="high"),+ ),+ )+ refused_image = ToolResultMessage(+ tool_call_id="call_10",+ tool_name="image_generate",+ content=(TextBlock(text="[image_generate failed: grok-imagine-image takes no images argument]"),),+ is_error=True,+ hosted=HostedResult(+ record=HostedRecord(+ status="failed",+ error="grok-imagine-image takes no images argument",+ error_code="image_param_unsupported",+ images=(),+ ),+ action=HostedAction(type="generate", model="grok-imagine-image"),),)unexecuted = ToolResultMessage(@@ -170,10 +177,12 @@ def _produced() -> list:)),)- return [native_turn, proxy_call, proxied, included, unexecuted]+ return [native_turn, proxy_call, proxied, included, unexecuted, refused_image][email protected]("message", _produced(), ids=["native", "proxy-call", "proxied", "included", "unexecuted"])+ "message", _produced(), ids=["native", "proxy-call", "proxied", "included", "unexecuted", "refused-image"]+)def test_hosted_messages_the_producer_writes_match_the_schema_and_round_trip(message):payload = message_to_dict(message)VALIDATOR.validate(payload)@@ -183,6 +192,8 @@ def test_hosted_messages_the_producer_writes_match_the_schema_and_round_trip(mesNATIVE = message_to_dict(_produced()[0])PROXIED = message_to_dict(_produced()[2])+IMAGE = message_to_dict(_produced()[3])+REFUSED_IMAGE = message_to_dict(_produced()[5])def _without(payload: dict, path: tuple, field: str) -> dict:@@ -210,9 +221,9 @@ MANDATORY = [(NATIVE, ("content", 0, "record"), "status"),(NATIVE, ("content", 0, "record"), "sources"),(NATIVE, ("content", 0, "record", "sources", 0), "url"),- (NATIVE, ("content", 4, "record", "images", 0), "path"),- (NATIVE, ("content", 4, "record", "images", 0), "mime"),- (NATIVE, ("content", 6, "citations", 0), "url"),+ (IMAGE, ("hosted", "record", "images", 0), "path"),+ (IMAGE, ("hosted", "record", "images", 0), "mime"),+ (NATIVE, ("content", 4, "citations", 0), "url"),(NATIVE, ("hosted_summary",), "counts"),(NATIVE, ("hosted_summary",), "cited_sources"),(NATIVE, ("hosted_summary", "cost"), "basis"),@@ -221,6 +232,8 @@ MANDATORY = [(PROXIED, ("hosted", "execution"), "executor_origin"),(PROXIED, ("hosted", "execution"), "executor_source_id"),(PROXIED, ("hosted", "execution"), "executor_billing"),+ (PROXIED, ("hosted", "execution", "failed_attempts", 0), "source_id"),+ (PROXIED, ("hosted", "execution", "failed_attempts", 0), "billing"),]@@ -243,18 +256,20 @@ def _set(payload: dict, path: tuple, value) -> dict:VIOLATIONS = {"error-on-completed": _set(NATIVE, ("content", 0, "record", "error"), "boom"),- "failed-without-error": _without(NATIVE, ("content", 5, "record"), "error"),+ "failed-without-error": _without(NATIVE, ("content", 1, "record"), "error"),"error-too-long": _set(NATIVE, ("content", 1, "record", "error"), "x" * 401),"error-code-without-error": _set(NATIVE, ("content", 0, "record", "error_code"), "image_not_saved"),- "error-code-not-snake-case": _set(NATIVE, ("content", 5, "record", "error_code"), "Image Not Saved"),- "empty-error-code": _set(NATIVE, ("content", 5, "record", "error_code"), ""),+ "error-code-not-snake-case": _set(NATIVE, ("content", 1, "record", "error_code"), "Image Not Saved"),+ "empty-error-code": _set(NATIVE, ("content", 1, "record", "error_code"), ""),"unknown-status": _set(NATIVE, ("content", 0, "record", "status"), "done"),"images-on-web-search": _set(NATIVE, ("content", 0, "record", "images"), []),- "no-images-on-image-generation": _without(NATIVE, ("content", 4, "record"), "images"),- "image-base64": _set(NATIVE, ("content", 4, "record", "images", 0, "b64_json"), "iVBORw0KGgo="),+ "no-images-on-image-generate": _without(IMAGE, ("hosted", "record"), "images"),+ "image-base64": _set(IMAGE, ("hosted", "record", "images", 0, "b64_json"), "iVBORw0KGgo="),"generate-on-web-search": _set(NATIVE, ("content", 0, "action"), {"type": "generate", "prompt": "p"}),+ "generate-on-proxied-search": _set(PROXIED, ("hosted", "action"), {"type": "generate", "prompt": "p"}),"search-on-x-search": _set(NATIVE, ("content", 2, "action"), {"type": "search", "queries": ["q"]}),- "completed-generate-without-prompt": _without(NATIVE, ("content", 4, "action"), "prompt"),+ # v2 has no native image tool, and an rc-era block is not read (§4.2, §15).+ "native-image-block": _set(NATIVE, ("content", 0, "tool"), "image_generation"),"unknown-action": _set(NATIVE, ("content", 0, "action"), {"type": "browse", "url": "https://a"}),"field-of-another-action": _set(NATIVE, ("content", 0, "action", "url"), "https://a"),"empty-queries": _set(NATIVE, ("content", 0, "action", "queries"), []),@@ -272,11 +287,11 @@ VIOLATIONS = {"negative-usd": _set(NATIVE, ("hosted_summary", "cost", "usd"), -0.01),"negative-count": _set(NATIVE, ("hosted_summary", "counts", "x_posts_fetched"), -1),"counter-name": _set(NATIVE, ("hosted_summary", "counts"), {"Web Search": 1}),- "citation-start-only": _without(NATIVE, ("content", 6, "citations", 0), "end"),+ "citation-start-only": _without(NATIVE, ("content", 4, "citations", 0), "end"),"citations-on-reference-text": _set(- NATIVE, ("content", 6), {"type": "text", "ref": {"ref": "sha256:" + "a" * 64, "bytes": 9}, "citations": [{"url": "https://a"}]}+ NATIVE, ("content", 4), {"type": "text", "ref": {"ref": "sha256:" + "a" * 64, "bytes": 9}, "citations": [{"url": "https://a"}]}),- "empty-citations": _set(NATIVE, ("content", 6, "citations"), []),+ "empty-citations": _set(NATIVE, ("content", 4, "citations"), []),"unexecuted-not-failed": _set(_set(_without(PROXIED, ("hosted",), "execution"), ("hosted", "record"), {"status": "incomplete", "error": "cut", "sources": []}),("is_error",),@@ -287,8 +302,9 @@ VIOLATIONS = {),"completed-result-flagged": _set(PROXIED, ("is_error",), True),"hosted-on-local-tool": _set(PROXIED, ("tool_name",), "bash"),- "proxy-mode": _set(PROXIED, ("hosted", "execution", "mode"), "native"),+ "execution-mode": _set(PROXIED, ("hosted", "execution", "mode"), "native"),"proxy-billing": _set(PROXIED, ("hosted", "execution", "executor_billing"), "free"),+ "failed-attempt-billing": _set(PROXIED, ("hosted", "execution", "failed_attempts", 0, "billing"), "free"),"proxy-images-on-x-search": _set(PROXIED, ("hosted", "record", "images"), []),}@@ -303,17 +319,24 @@ def test_schema_and_reader_refuse_the_same_hosted_violations(payload):def test_a_record_with_an_error_code_this_build_does_not_know_still_loads():"""#2589: a newer build may add codes; an older one reads the record and shows its English error."""- newer = _set(NATIVE, ("content", 5, "record", "error_code"), "executor_overloaded")+ newer = _set(NATIVE, ("content", 1, "record", "error_code"), "executor_overloaded")assert "executor_overloaded" not in HOSTED_ERROR_CODESVALIDATOR.validate(newer)- assert message_from_dict(newer).content[5].record.error_code == "executor_overloaded"+ assert message_from_dict(newer).content[1].record.error_code == "executor_overloaded"++ "payload",+ [_without(IMAGE, ("hosted", "action"), "prompt"), REFUSED_IMAGE],+ ids=["completed-unrevised", "refused-before-the-endpoint"],+)+def test_a_generate_action_names_a_prompt_only_when_the_endpoint_revised_it(payload):+ """The call's own arguments carry the model's prompt. The action's prompt is the endpoint's revision, which most+ image endpoints never send, and an image call refused before the endpoint ran has none."""-def test_a_failed_generate_may_lack_the_revised_prompt():- # Item 28: OpenAI may return a failed image_generation_call with no revised_prompt.- failed = NATIVE["content"][5]- assert "prompt" not in failed["action"] and failed["record"]["status"] == "failed"- VALIDATOR.validate(NATIVE)+ assert "prompt" not in payload["hosted"]["action"]+ VALIDATOR.validate(payload)+ assert message_from_dict(payload).hosted.action.prompt is Nonedef test_a_citation_range_must_lie_within_its_text():@@ -321,4 +344,4 @@ def test_a_citation_range_must_lie_within_its_text():with pytest.raises(ValueError):TextBlock(text="短", citations=(Citation(url="https://a", start=0, end=2),))with pytest.raises(ValueError):- message_from_dict(_set(NATIVE, ("content", 6, "citations", 0, "end"), 99))+ message_from_dict(_set(NATIVE, ("content", 4, "citations", 0, "end"), 99))diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 18abd95bf..cdf7ae555 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -62,7 +62,6 @@ capabilities:- tests/agent_core/ai/test_hosted_parsing.py- tests/agent_core/ai/test_hosted_transform.py- tests/agent_core/ai/test_hosted_replay.py- - tests/agent_core/ai/test_hosted_images.py- tests/agent_core/ai/test_hosted_pause_turn.py- tests/test_vibey_agent.py- tests/test_model_hub_evidence_rules.py@@ -101,6 +100,7 @@ capabilities:- tests/test_model_hub_declared_tools.py- tests/test_model_hub_l3.py- tests/test_model_hub_hosted_executor.py+ - tests/test_model_hub_hosted_evidence.py- tests/test_model_hub_usage.py- tests/test_ui_server_fastapi.py- tests/test_model_hub_quota.pydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 23e9cfc73..4650faa32 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -19,7 +19,6 @@ capability:- tests/agent_core/ai/test_hosted_parsing.py- tests/agent_core/ai/test_hosted_transform.py- tests/agent_core/ai/test_hosted_replay.py- - tests/agent_core/ai/test_hosted_images.py- tests/agent_core/ai/test_hosted_pause_turn.py- tests/test_vibey_agent.py- tests/test_model_hub_evidence_rules.py@@ -45,6 +44,7 @@ capability:- tests/test_model_hub_declared_tools.py- tests/test_model_hub_l3.py- tests/test_model_hub_hosted_executor.py+ - tests/test_model_hub_hosted_evidence.py- tests/test_model_hub_usage.py- tests/test_ui_server_fastapi.py- tests/test_model_hub_quota.py@@ -177,7 +177,7 @@ scenarios:- tests/test_model_hub_hosted_tools_resolution.py::test_a_hops_facts_come_from_priors_and_refusals- tests/test_model_hub_hosted_tools_resolution.py::test_the_executor_chain_follows_the_users_order_then_vibeys- tests/test_model_hub_hosted_tools_resolution.py::test_the_image_enum_is_deterministic_with_the_default_first- - tests/test_model_hub_hosted_tools_resolution.py::test_resolution_states_v2_facts_in_todays_hop_shape+ - tests/test_model_hub_hosted_tools_resolution.py::test_a_turn_freezes_its_tools_executors_and_image_enum_and_each_hop_states_its_own_facts- id: MH-HOSTED-002name: Absent hosted-tools config means every tool is on; an rc-era section keeps each tool's enabled, and a broken section or entry turns only its tools off without the whole-section Model Hub resetstatus: covered@@ -261,30 +261,26 @@ scenarios:related_tests:- tests/test_hosted_activity.py::test_the_im_line_names_a_subscription_and_a_shared_response_cost- id: MH-HOSTED-UI-012- name: A final whose only content is a generated image is a reply, not an empty one, and reaches the user as an attachment- status: covered+ name: A turn whose image_generate call completed reaches the user with the image as an attachment, even when the model says nothing after it (hosted tools v2 C2)+ status: gapkind: contractlayer: contract- test: tests/test_vibey_agent.py::test_an_image_only_final_is_a_reply_and_reaches_the_user- related_tests:- - tests/agent_core/agent/test_loop.py::test_tool_free_final_reply_is_committed_and_empty_success_is_an_error- id: MH-HOSTED-UI-011- name: Vibey delivers a native hosted call as its IM line and Web card, its answer with provider citations as links, and its generated image as an attachment+ name: Vibey delivers a native hosted call as its IM line and Web card, and its answer with provider citations as linksstatus: coveredkind: contractlayer: contract- test: tests/test_vibey_agent.py::test_a_native_hosted_call_reaches_im_as_one_line_with_its_cited_answer_and_image+ test: tests/test_vibey_agent.py::test_a_native_hosted_call_reaches_im_as_one_line_with_its_cited_answerrelated_tests:- tests/test_vibey_agent.py::test_a_native_hosted_call_reaches_the_workbench_as_a_card_and_cited_answer- tests/test_vibey_agent.py::test_a_proxied_hosted_result_shows_once_its_result_is_committed- id: MH-HOSTED-UI-014- name: A hosted call that did not complete shows its status and any known charge, and claims neither how it ran nor what it found, on the IM line, the Web card (collapsed or expanded) and image delivery alike+ name: A hosted call that did not complete shows its status and any known charge, and claims neither how it ran nor what it found, on the IM line and the Web card (collapsed or expanded)status: coveredkind: contractlayer: unittest:- tests/test_hosted_activity.py::test_the_im_line_claims_how_a_call_ran_and_what_it_found_only_once_it_completed- - tests/test_vibey_agent.py::test_an_image_from_a_call_that_did_not_complete_is_not_delivered- ui/src/components/workbench/HostedToolRow.test.tsx::MH-HOSTED-UI-014 (pending)- ui/src/components/workbench/HostedToolRow.test.tsx::MH-HOSTED-UI-014 (failed)- ui/src/components/workbench/HostedToolRow.test.tsx::MH-HOSTED-UI-014 (incomplete)@@ -318,7 +314,7 @@ scenarios:- ui/src/components/workbench/AgentRoutePicker.test.tsx::MH-EFFORT-MENU-003- ui/src/components/workbench/AgentsPage.test.tsx::MH-EFFORT-MENU-003- id: MH-HOSTED-VIBEY-001- name: Vibey declares a hop's native hosted tool verbatim with its include values and pins that request to the hop's Source; the probe builds the same request+ name: Vibey declares a search tool natively, verbatim with its include values, exactly when the hop's facts assume it, and pins that request to the hop's Sourcestatus: coveredkind: contractlayer: contract@@ -326,8 +322,7 @@ scenarios:related_tests:- tests/test_vibey_agent.py::test_a_hop_with_an_invalid_hosted_tool_entry_is_refused- tests/agent_core/ai/test_hosted_requests.py::test_a_hosted_spec_on_a_native_route_is_sent_as_the_declaration_in_its_place_and_pinned- - tests/agent_core/ai/test_hosted_requests.py::test_the_probe_entry_builds_exactly_the_request_the_adapter_sends- - tests/agent_core/ai/test_hosted_requests.py::test_tool_choice_forces_the_named_tool_in_each_protocols_form+ - tests/agent_core/ai/test_hosted_requests.py::test_the_wire_builder_the_tests_read_is_exactly_the_request_the_adapter_sends- id: MH-HOSTED-006name: A real upstream 400 teaches only the feature it names, and a refused effort then skips its hop instead of another provider 400status: covered@@ -377,14 +372,20 @@ scenarios:status: coveredkind: contractlayer: contract- test: tests/test_vibey_agent.py::test_a_proxied_hosted_call_runs_on_the_bound_executor_and_keeps_its_record+ test: tests/test_vibey_agent.py::test_a_proxied_hosted_call_runs_on_the_turns_executor_chain_and_keeps_its_record+ related_tests:+ - tests/test_vibey_agent.py::test_a_proxied_call_after_the_turn_moved_to_another_source_runs_on_the_hop_it_now_holds- id: MH-HOSTED-VIBEY-005- name: A hosted call goes back verbatim and pinned only to the Source that served it, within its turn or with current replay evidence; pin_unavailable gets exactly one portable, unpinned resend+ name: A hosted call goes back verbatim and pinned only to the Source that served it, within its turn while the hop still declares the tool natively or with current replay evidence; a refusal before any output (pin_unavailable, xAI's decrypt refusal) ends the send, and the loop renders the request again for a fresh hop within its bounds, portable only as the last resortstatus: coveredkind: contractlayer: contract- test: tests/agent_core/ai/test_hosted_replay.py::test_pin_unavailable_gets_exactly_one_portable_resend_and_never_the_generic_retry+ test: tests/agent_core/ai/test_hosted_replay.py::test_a_narrow_refusal_is_answered_by_a_fresh_hop_that_runs_only_that_tool_as_its_functionrelated_tests:+ - tests/agent_core/ai/test_hosted_replay.py::test_pin_unavailable_ends_the_pinned_send_as_a_refusal_with_no_output+ - tests/agent_core/ai/test_hosted_replay.py::test_refusals_are_answered_within_their_bounds_and_portable_rendering_is_the_last_resort+ - tests/agent_core/ai/test_hosted_replay.py::test_a_decrypt_refusal_ends_the_send_as_an_opaque_refusal_of_its_source_identity+ - tests/agent_core/ai/test_hosted_replay.py::test_a_decrypt_refusal_drops_every_opaque_payload_of_that_identity_for_the_rest_of_the_turn- tests/agent_core/ai/test_hosted_replay.py::test_a_hosted_call_goes_back_verbatim_and_pinned_only_to_its_own_source_with_replay_evidence- tests/agent_core/ai/test_hosted_replay.py::test_a_continuation_goes_back_verbatim_only_to_the_hop_that_served_it- id: MH-HOSTED-VIBEY-006@@ -398,17 +399,13 @@ scenarios:- tests/agent_core/ai/test_hosted_pause_turn.py::test_a_paused_response_its_source_cannot_continue_ends_interrupted_and_keeps_what_it_has- tests/agent_core/ai/test_hosted_pause_turn.py::test_a_continued_response_is_verified_only_when_every_response_in_it_was_from_one_origin- id: MH-HOSTED-VIBEY-007- name: A native generated image is saved to a file as its done item is parsed and its record names that file; no base64 enters history, partial and terminal copies are never decoded, and an image over read's inline limit says so+ name: A generated image the endpoint returns is saved through the media sink and its record names that file; no base64 enters history, and a call that saved no file is a failed record with its codestatus: coveredkind: contractlayer: contract- test: tests/agent_core/ai/test_hosted_images.py::test_a_native_image_is_saved_once_from_its_done_item_and_history_holds_only_its_path+ test: tests/test_vibey_agent.py::test_an_image_the_endpoint_returns_is_saved_through_the_media_sink_and_its_record_names_the_filerelated_tests:- - tests/agent_core/ai/test_hosted_images.py::test_an_image_that_was_not_saved_is_a_failed_call_never_a_completed_one- - tests/agent_core/ai/test_hosted_images.py::test_a_six_megabyte_image_streams_under_the_image_line_cap_and_its_record_says_read_cannot_show_it- - tests/agent_core/ai/test_hosted_images.py::test_a_response_that_streams_images_past_its_budget_ends_as_an_error- tests/test_vibey_agent.py::test_a_generated_image_is_kept_as_an_immutable_file_its_bytes_name_and_type- - tests/test_vibey_agent.py::test_a_proxied_image_that_was_not_saved_is_a_failed_call_with_its_code- tests/test_agent_transcript.py::test_the_media_sweep_keeps_every_file_a_row_registers_and_takes_only_stale_orphans- id: MH-HOSTED-UI-001name: A Tools-tab control writes only the field it changes, and a tool's controls hold while its write is out@@ -546,7 +543,7 @@ scenarios:- tests/test_vibey_backend_registration.py::test_a_lost_vibey_model_hand_off_heals_on_the_next_start- tests/test_controller_im_ready.py::test_runtime_services_start_when_post_update_notification_fails- id: MH-HOSTED-GATEWAY-002- name: A pinned Vibey request is served only by its Source and unchanged; every refusal or pre-output failure there is pin_unavailable, and unpinned hosted content is refused before anything runs+ name: A pinned Vibey request is served only by its Source and unchanged; every refusal or pre-output failure there is pin_unavailable, which names the refused feature only when a narrow hosted rule fired, and unpinned hosted content is refused before anything runsstatus: coveredkind: contractlayer: contract@@ -554,6 +551,7 @@ scenarios:related_tests:- tests/test_model_hub_hosted_pinning.py::test_the_portable_resend_fails_over_and_the_turn_settles_on_it- tests/test_model_hub_hosted_pinning.py::test_unpinned_hosted_content_is_refused_before_anything_runs+ - tests/test_model_hub_hosted_pinning.py::test_a_refusal_naming_the_pinned_hosted_content_is_handed_back_and_learned- tests/test_model_hub_hosted_pinning.py::test_a_replay_is_admitted_exactly_where_the_hops_facts_assume_it- id: MH-HOSTED-GATEWAY-003name: Hosted declarations are recognized by any vendor's type, and only replayed items outside the in-flight response need replay evidence@@ -2467,7 +2465,7 @@ scenarios:layer: e2e-autotest: tests/e2e/test_model_hub_service_acceptance.py::test_fresh_install_serves_vibey_and_claude_through_the_hub_and_reaps_an_orphaned_engine- id: MH-HOSTED-GATEWAY-004- name: A proxied hosted call runs one native request on its bound executor, without an effort, and answers its canonical record and execution with the pricing module's cost+ name: A proxied search runs one native request on the turn's first admitted executor, without an effort, and answers its canonical record and execution with the pricing module's cost and the same positive evidence a native call writesstatus: coveredkind: contractlayer: contract@@ -2477,15 +2475,27 @@ scenarios:- tests/test_model_hub_hosted_executor.py::test_an_excerpt_is_the_answer_text_its_citation_belongs_to- tests/test_model_hub_hosted_executor.py::test_a_proxied_call_carries_the_pricing_modules_cost- id: MH-HOSTED-GATEWAY-005- name: A proxied hosted call that cannot complete is a failed record, with an execution only when an executor ran; only a malformed call is an error status+ name: A proxied search moves down the turn's frozen executor chain only past a Source failure, within one deadline, listing billed attempts; a call that cannot complete is a failed record, with an execution only when an executor ran; only a malformed call, or one its turn cannot make, is an error statusstatus: coveredkind: boundarylayer: contracttest: tests/test_model_hub_hosted_executor.py::test_a_proxied_call_that_cannot_complete_is_a_failed_recordrelated_tests:+ - tests/test_model_hub_hosted_executor.py::test_the_chain_moves_on_only_past_a_source_failure+ - tests/test_model_hub_hosted_executor.py::test_a_call_runs_only_a_tool_its_live_turn_froze+ - tests/test_model_hub_hosted_executor.py::test_a_turn_keeps_its_tools_and_executor_order_until_the_next_turn- tests/test_model_hub_hosted_executor.py::test_a_malformed_proxy_call_is_refused_before_anything_runs- tests/test_model_hub_hosted_executor.py::test_a_proxy_call_needs_the_turns_gateway_token+ - id: MH-HOSTED-GATEWAY-006+ name: A served response proves only the provider's own completed search item, streamed or buffered, and its positive evidence is written at settlement for a tool the request declared natively+ status: covered+ kind: contract+ layer: contract+ test: tests/test_model_hub_hosted_evidence.py::test_a_served_response_proves_only_its_own_completed_search_item+ related_tests:+ - tests/test_model_hub_hosted_evidence.py::test_a_native_success_is_recorded_at_settlement_for_a_tool_the_request_declarednext_priority:+ - MH-HOSTED-UI-012- MH-PROTOCOL-004- MH-RUNTIME-001- MH-OAUTH-B-001diff --git a/tests/test_agent_transcript.py b/tests/test_agent_transcript.pyindex d638ebc78..df937a415 100644--- a/tests/test_agent_transcript.py+++ b/tests/test_agent_transcript.py@@ -493,23 +493,15 @@ async def test_a_call_instance_is_settled_once_whoever_writes(engine) -> None:async def test_the_media_sweep_keeps_every_file_a_row_registers_and_takes_only_stale_orphans(engine, tmp_path) -> None:"""MH-HOSTED-VIBEY-007, #2588 (``vibey-hosted-tools.md`` §7.3): a generated image is saved before the row that- names it commits, so an interruption in between leaves a file no row names. A committed row registers each image- it names, native or proxied, as an input snapshot is registered; the sweep removes only a file nothing registers- that is older than any Turn holds an uncommitted save, and never a link or a name of someone else's."""+ names it commits, so an interruption in between leaves a file no row names. A committed ``image_generate`` result+ registers each image its record names, as an input snapshot is registered; the sweep removes only a file nothing+ registers that is older than any Turn holds an uncommitted save, and never a link or a name of someone else's."""import base64import osimport timefrom pathlib import Path- from core.agent_core.messages import (- HostedAction,- HostedNative,- HostedRecord,- HostedResult,- HostedSummary,- HostedToolBlock,- ProxyExecution,- )+ from core.agent_core.messages import HostedRecord, HostedResult, ProxyExecutionfrom modules.agents.vibey.media import SWEEP_GRACE_S, MediaSnapshotswith engine.begin() as conn:@@ -525,26 +517,17 @@ async def test_the_media_sweep_keeps_every_file_a_row_registers_and_takes_only_sawait store.consume_input("ses_main", first, _user("paint two lighthouses"))await media.snapshot(b"\x89PNG\r\n\x1a\n" + bytes(64), "image/png", session_id="ses_main")- native, proxied = await media.save_image(jpeg(1)), await media.save_image(jpeg(2))- call = HostedToolBlock(- id="ig_1",- tool="image_generation",- action=HostedAction("generate", prompt="a lighthouse"),- record=HostedRecord(status="completed", images=(native,)),- native=HostedNative(source_id="src_served00001", payload=({"type": "image_generation_call", "result": native.path},)),- )- summary = HostedSummary(counts={}, cited_sources=())- await store.append_response(- "ses_main", AssistantMessage((call,), ORIGIN, "stop", hosted_summary=summary), final=False+ first, second = await media.save_image(jpeg(1)), await media.save_image(jpeg(2))+ execution = ProxyExecution(+ executor_origin=ORIGIN, executor_source_id="src_executor01", executor_billing="metered", mode="direct")- execution = ProxyExecution(executor_origin=ORIGIN, executor_source_id="src_executor01", executor_billing="metered")await store.append_tool_result("ses_main",ToolResultMessage(tool_call_id="call_2",- tool_name="image_generation",+ tool_name="image_generate",content=(text("[image saved]"),),- hosted=HostedResult(record=HostedRecord(status="completed", images=(proxied,)), execution=execution),+ hosted=HostedResult(record=HostedRecord(status="completed", images=(first, second)), execution=execution),),details={},)@@ -569,7 +552,7 @@ async def test_the_media_sweep_keeps_every_file_a_row_registers_and_takes_only_sassert media.sweep() == (2, gone)kept = {entry.name for entry in root.iterdir()}assert Path(stale.path).name not in kept and temporary.name not in kept- assert {Path(image.path).name for image in (native, proxied, fresh, reused)} <= kept+ assert {Path(image.path).name for image in (first, second, fresh, reused)} <= keptassert {foreign.name, link.name} <= kept and secret.read_bytes() == b"key"assert len([name for name in kept if name.endswith(".png")]) == 2 # the input snapshot and the linkdiff --git a/tests/test_hosted_activity.py b/tests/test_hosted_activity.pyindex c921b0878..d4a2d6caf 100644--- a/tests/test_hosted_activity.py+++ b/tests/test_hosted_activity.py@@ -7,6 +7,7 @@ fixture the Web card tests render, so producer and consumer read one shape.from __future__ import annotationsimport json+from dataclasses import replacefrom pathlib import Pathimport pytest@@ -14,6 +15,7 @@ import pytestfrom core.agent_core.messages import (HOSTED_ERROR_CODES,AssistantMessage,+ FailedAttempt,HostedAction,HostedCost,HostedImage,@@ -106,28 +108,26 @@ def proxy_x_search():)-def native_image():- [activity] = native_activities(- _message(- HostedToolBlock(- id="ig_01",- tool="image_generation",- action=HostedAction(type="generate", prompt=PROMPT, size="1536x1024", quality="medium"),- record=HostedRecord(- status="completed",- images=(HostedImage(path="/media/3f2a.png", mime="image/png", width=1536, height=1024, bytes=1993000),),- ),- native=_native("src_relaygpt1"),+def direct_image():+ """An ``image_generate`` call, run directly on the image endpoint (§7.4)."""+ return proxy_activity(+ ToolCallBlock(id="call_ig1", name="image_generate", arguments={"model": "gpt-image-2", "prompt": PROMPT}),+ HostedResult(+ record=HostedRecord(+ status="completed",+ images=(HostedImage(path="/media/3f2a.png", mime="image/png", width=1536, height=1024, bytes=1993000),),),- # Phase 1 knows no image price, so the response carries no cost at all.- summary=HostedSummary(),- provider="openai",- api="openai_responses",- model="gpt-6.1-sol",+ # No image price is known here, so the call carries no cost at all.+ execution=ProxyExecution(+ executor_origin=Origin(provider="openai", api="openai_responses", model="gpt-image-2"),+ executor_source_id="src_relaygpt1",+ executor_billing="metered",+ mode="direct",+ ),+ action=HostedAction(type="generate", prompt=PROMPT, size="1536x1024", quality="medium", model="gpt-image-2"),),source_names=NAMES,)- return activitydef proxy_failed():@@ -142,7 +142,7 @@ def test_a_proxied_image_shows_what_its_executor_rendered_as_a_native_one_does()"""A proxied image's card reads the executor's rendered prompt and resolved size and quality from the result'saction, as a native image's reads its block's action: one reading, no mode branch."""- call = ToolCallBlock(id="call_i1", name="image_generation", arguments={"prompt": "a lighthouse", "size": "auto"})+ call = ToolCallBlock(id="call_i1", name="image_generate", arguments={"prompt": "a lighthouse", "size": "auto"})activity = proxy_activity(call,HostedResult(@@ -171,7 +171,7 @@ def proxy_unreachable():)[email protected]("build", [native_web_search, proxy_x_search, native_image, proxy_failed, proxy_unreachable])[email protected]("build", [native_web_search, proxy_x_search, direct_image, proxy_failed, proxy_unreachable])def test_payloads_match_the_shape_the_web_card_renders(build):"""MH-HOSTED-UI-009: every mode and outcome the card distinguishes, from the canonical records each producer writes.@@ -233,10 +233,10 @@ def test_a_response_scoped_summary_is_shown_once():),(proxy_x_search, "zh", "🔎 X 搜索 “from:OpenAI within_time:7d” · 由 xAI 代理 · 2 条帖子 · $0.11"),(- native_image,+ direct_image,"en","🖼 Image generation “A wide photo of an open laptop on a desk at night, empty da…”"- " · native (OpenAI) · 1 image",+ " · direct (OpenAI) · 1 image",),(proxy_failed, "zh", "🔎 X 搜索 “from:OpenAI” · 失败:no Source is verified for X search"),],@@ -295,6 +295,40 @@ def test_the_im_line_names_a_subscription_and_a_shared_response_cost():assert hosted_line(shared, "en") == "🔎 Web search “b” · native (Anthropic) · 1 source · ≈ $0.02 for 2 calls"+def _attempt(source_id: str, billing: str, cost: HostedCost | None):+ return FailedAttempt(source_id=source_id, billing=billing, cost=cost)+++ ("failed", "last", "cost", "line_cost"),+ [+ # A metered failure before the call that ran: both charges, and how many calls they cover.+ ((("src_relaygpt1", "metered", HostedCost(basis="list", usd=0.02)),), HostedCost(basis="reported", usd=0.11),+ {"basis": "list", "usd": 0.13, "calls": 2}, "≈ $0.13 for 2 calls"),+ ((("src_relaygpt1", "metered", HostedCost(basis="reported", usd=0.02)),), HostedCost(basis="reported", usd=0.11),+ {"basis": "reported", "usd": 0.13, "calls": 2}, "$0.13 for 2 calls"),+ # A subscription attempt adds no money.+ ((("src_chatgpt01", "monthly", HostedCost(basis="included")),), HostedCost(basis="reported", usd=0.11),+ {"basis": "reported", "usd": 0.11, "calls": 2}, "$0.11 for 2 calls"),+ # A billed attempt with no known price: the total is unknown, never shown smaller than it was.+ ((("src_relaygpt1", "metered", None),), HostedCost(basis="reported", usd=0.11), None, None),+ ],+)+def test_a_proxied_calls_cost_counts_every_billed_attempt(failed, last, cost, line_cost):+ """MH-HOSTED-GATEWAY-005: the card and the IM line show what the whole executor chain cost, never less."""++ activity = proxy_activity(+ _x_call("call_x5", "from:OpenAI"),+ HostedResult(+ record=HostedRecord(status="completed", sources=POSTS[:1]),+ execution=replace(XAI, cost=last, failed_attempts=tuple(_attempt(*item) for item in failed)),+ ),+ )+ assert activity.to_payload().get("cost") == cost+ line = hosted_line(activity, "en")+ assert line.endswith(f" · {line_cost}") if line_cost else "$" not in line++def test_the_im_line_escapes_the_quoted_subject_for_its_destination():activity = proxy_activity(_x_call("call_x4", "*bold* claim"),diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.pyindex 22af05bc7..f7a643a14 100644--- a/tests/test_message_mirror.py+++ b/tests/test_message_mirror.py@@ -1631,8 +1631,8 @@ def _hosted_card(image_path: str) -> dict:return {"version": 1,"call_id": "ig_01",- "tool": "image_generation",- "mode": "native",+ "tool": "image_generate",+ "mode": "direct","status": "completed","subject": "a laptop at night","sources": [],@@ -1687,7 +1687,7 @@ def test_a_hosted_card_rides_on_its_toolcall_row_and_its_image_joins_the_answer(card = json.loads(event["content_json"])["hosted"][stored] = card["images"]assert {key: card[key] for key in ("call_id", "tool", "mode", "status", "subject")} == {- "call_id": "ig_01", "tool": "image_generation", "mode": "native", "status": "completed",+ "call_id": "ig_01", "tool": "image_generate", "mode": "direct", "status": "completed","subject": "a laptop at night",}assert stored["path"] == str(image) and stored["bytes"] == image.stat().st_sizediff --git a/tests/test_model_hub_evidence_rules.py b/tests/test_model_hub_evidence_rules.pyindex 378ef3d5d..b7cb1cd11 100644--- a/tests/test_model_hub_evidence_rules.py+++ b/tests/test_model_hub_evidence_rules.py@@ -310,7 +310,7 @@ async def test_no_request_path_reads_a_bundled_file_after_startup(tmp_path, monkconfig = service.store.load()assert service._effort_refused(source, "shared-model", request) is Falseawait service._learn_capability_evidence(source, "shared-model", request, rejected)- service.hosted_tools_for_hop(config, source, "shared-model")+ service.hosted_tools_for_hop(source, "shared-model", service.freeze_turn_hosted_tools(config))service.agent_chain("codex", model)service.list_sources()service.hosted_tools_status()diff --git a/tests/test_model_hub_hosted_evidence.py b/tests/test_model_hub_hosted_evidence.pynew file mode 100644index 000000000..9f39ab034--- /dev/null+++ b/tests/test_model_hub_hosted_evidence.py@@ -0,0 +1,137 @@+"""Passive hosted-tool evidence: what a served response proves ran (vibey-hosted-tools.md §3.2)."""++from __future__ import annotations++import json+from dataclasses import replace++from aiohttp import web+import pytest++from core.handlers.model_hub.adapter import RawOutcomeKind+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from modules.agents.model_hub import ModelHubRuntimeRouter+from tests.test_model_hub_hosted_pinning import SHELL, _native, _post+from tests.test_model_hub_hosted_pinning import _sources as _pinned_sources+from tests.test_model_hub_l3 import LiveInvokeHandle, _outcome+from tests.test_model_hub_retry_advice import _engine, _invoke+from tests.test_model_hub_vibey_consumer import _vibey_service+++def latest_ok(service, tool):+ """The Tools read's latest success for a tool, as (Source, model, mode); None without one."""++ entry = next(item for item in service.hosted_tools_status()["hosted_tools"]["tools"] if item["name"] == tool)+ latest = entry["status"]["latest_ok"]+ return None if latest is None else (latest["source_id"], latest["model_id"], latest["mode"])+++def _responses_stream(item: dict, terminal: str) -> bytes:+ done = {"type": "response.output_item.done", "output_index": 0, "item": item}+ return (+ b"event: response.output_item.done\ndata: " + json.dumps(done).encode() + b"\n\n"+ + {+ "completed": b'event: response.completed\ndata: {"type":"response.completed"}\n\n',+ "failed": b'event: response.failed\ndata: {"type":"response.failed","response":'+ b'{"error":{"type":"server_error"}}}\n\n',+ }[terminal]+ )+++def _anthropic_stream(block: dict, terminal: str) -> bytes:+ start = {"type": "content_block_start", "index": 1, "content_block": block}+ return (+ b"event: content_block_start\ndata: " + json.dumps(start).encode() + b"\n\n"+ + {+ "completed": b'event: message_stop\ndata: {"type":"message_stop"}\n\n',+ "failed": b'event: error\ndata: {"type":"error","error":{"type":"api_error"}}\n\n',+ }[terminal]+ )+++def _responses_body(item: dict, terminal: str) -> bytes:+ if terminal == "failed":+ return json.dumps({"output": [item], "error": {"type": "server_error"}}).encode()+ text = {"type": "message", "content": [{"type": "output_text", "text": "ok"}]}+ return json.dumps({"object": "response", "status": "completed", "output": [item, text]}).encode()+++def _anthropic_body(block: dict, terminal: str) -> bytes:+ if terminal == "failed":+ return json.dumps({"type": "error", "error": {"type": "api_error"}, "content": [block]}).encode()+ call = {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "q"}}+ return json.dumps({"type": "message", "content": [call, block, {"type": "text", "text": "ok"}]}).encode()+++WIRE = {+ "openai_responses": (_responses_stream, _responses_body),+ "anthropic": (_anthropic_stream, _anthropic_body),+}+RESULTS = [{"type": "web_search_result", "url": "https://example.test", "title": "t", "encrypted_content": "e"}]+ITEMS = [+ ("openai_responses", {"type": "web_search_call", "id": "ws_1", "status": "completed"}, "web_search"),+ ("openai_responses", {"type": "web_search_call", "id": "ws_1", "status": "failed"}, None),+ ("openai_responses", {"type": "web_search_call", "id": "ws_1", "status": "in_progress"}, None),+ ("openai_responses", {"type": "custom_tool_call", "name": "x_keyword_search", "input": "{}"}, "x_search"),+ ("openai_responses", {"type": "custom_tool_call", "name": "lookup", "input": "{}"}, None),+ ("openai_responses", {"type": "image_generation_call", "id": "ig_1", "status": "completed"}, None),+ ("anthropic", {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": RESULTS}, "web_search"),+ (+ "anthropic",+ {+ "type": "web_search_tool_result",+ "tool_use_id": "srvtoolu_1",+ "content": {"type": "web_search_tool_result_error", "error_code": "max_uses_exceeded"},+ },+ None,+ ),+ ("anthropic", {"type": "web_fetch_tool_result", "tool_use_id": "srvtoolu_1", "content": RESULTS}, None),+]++[email protected]("stream", [True, False], ids=["streamed", "buffered"])[email protected]("terminal", ["completed", "failed"])[email protected](("protocol", "item", "tool"), ITEMS)+async def test_a_served_response_proves_only_its_own_completed_search_item(+ protocol: str, item: dict, tool: str | None, terminal: str, stream: bool,+) -> None:+ """MH-HOSTED-GATEWAY-006: a failed, unfinished or other item proves nothing, and neither does a failed response."""++ payload = WIRE[protocol][0 if stream else 1](item, terminal)++ async def respond(_request: web.Request) -> web.Response:+ if stream:+ return web.Response(body=payload, content_type="text/event-stream")+ return web.Response(body=payload, content_type="application/json")++ async with _engine(respond) as (client, _requests):+ outcome, _forwarded = await _invoke(client, protocol, stream)++ assert outcome.hosted_tools == (frozenset({tool}) if tool is not None and terminal == "completed" else frozenset())++[email protected](("tools", "proven", "recorded"), [+ # A served response that ran the tool the request declared natively is that tool's success.+ ([{"type": "x_search"}, SHELL], {"x_search"}, True),+ # It proves nothing about a tool the request did not declare natively.+ ([SHELL], {"x_search"}, False),+ ([{"type": "x_search"}, SHELL], set(), False),+])+async def test_a_native_success_is_recorded_at_settlement_for_a_tool_the_request_declared(+ tmp_path, tools, proven, recorded,+):+ """MH-HOSTED-GATEWAY-006: positive evidence is display history, written once the served response settles."""++ primary, fallback = _pinned_sources()+ served = replace(_outcome(RawOutcomeKind.SUCCESS, source_id=primary.id), hosted_tools=frozenset(proven))+ service = _vibey_service(tmp_path, [primary, fallback], handles=[LiveInvokeHandle(served, (b"{}",))])+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:proof", turn_id="turn-proof")+ body = {**_native(hop), "tools": tools}+ native = any(tool.get("type") == "x_search" for tool in tools)+ assert (await _post(hop, body, pin=primary.id if native else None))[0] == 200+ finally:+ await gateway.close()+ assert latest_ok(service, "x_search") == ((primary.id, "grok-4.6", "native") if recorded else None)diff --git a/tests/test_model_hub_hosted_executor.py b/tests/test_model_hub_hosted_executor.pyindex 89797fdc6..a0df24fdc 100644--- a/tests/test_model_hub_hosted_executor.py+++ b/tests/test_model_hub_hosted_executor.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport asyncioimport gzipimport json+import threadingfrom dataclasses import replacefrom datetime import timedelta@@ -21,7 +22,8 @@ import pytestfrom config.v2_config import ModelHubHostedToolConfigfrom core.agent_core.messages import HostedCost, message_from_dictfrom core.handlers.model_hub import service as service_module-from core.handlers.model_hub.adapter import InvokeCancelledError, RawOutcomeKind+from core.handlers.model_hub.adapter import InvokeCancelledError, RawOutcomeKind, UpstreamRejection+from core.handlers.model_hub.capability_evidence import EvidenceFeaturefrom core.handlers.model_hub.hosted_executor import ResponsesReadout, anthropic_result, excerpt, responses_resultfrom core.handlers.model_hub import hosted_tools as hosted_tools_modulefrom core.handlers.model_hub.pricing import PriceTable@@ -39,6 +41,7 @@ from tests.test_model_hub_l3 import (_source,_usage_of,)+from tests.test_model_hub_hosted_evidence import latest_okfrom tests.test_model_hub_vibey_consumer import _vibey_serviceXAI = "src_xaikey0001"@@ -185,22 +188,32 @@ def _hosted_result(tool, answer):async def test_a_proxied_search_runs_one_native_request_and_answers_its_canonical_record(tmp_path, tool, executor, arguments, frames, body_fields, sources,):- """MH-HOSTED-GATEWAY-004: the bound executor only, no effort, the overlay declaration forced, excerpts, metering."""+ """MH-HOSTED-GATEWAY-004: the chain's first executor, no effort, the overlay declaration forced, excerpts,+ metering, and the same positive evidence a native call writes."""usage = ProtocolUsageReport.of(input_tokens=5369, cached_input_tokens=256, output_tokens=307)- service = _vibey_service(tmp_path, _sources(), handles=[- LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=executor[0], usage=usage), frames),- ])+ served = replace(+ _outcome(RawOutcomeKind.SUCCESS, source_id=executor[0], usage=usage), hosted_tools=frozenset({tool}),+ )+ service = _vibey_service(tmp_path, _sources(), handles=[LiveInvokeHandle(served, frames)])_bind(service, tool, executor)- status, answer = await _call(service, tool, {- "arguments": arguments, "executor": {"source_id": executor[0], "model_id": executor[1]},- })+ admitting_threads = []+ admit = service._admitted_executor++ def recorded(*args):+ admitting_threads.append(threading.current_thread())+ return admit(*args)++ service._admitted_executor = recorded+ status, answer = await _call(service, tool, {"arguments": arguments})assert status == 200, answer+ # Admission reads the config, which grows with use: at the chain step and again under the lock, off the loop.+ assert len(admitting_threads) == 2 and threading.main_thread() not in admitting_threadsassert service.adapter.invocations == [(executor[0], executor[1], "vibey")]sent = service.adapter.requests[0]assert sent.protocol == "openai_responses"assert "reasoning" not in sent- # Forced, as the call probe that verified it forces it.+ # Forced: a model answering from memory runs no search.assert sent["tool_choice"] == "required"assert {key: sent[key] for key in body_fields} == body_fieldsassert set(sent) - set(body_fields) == {@@ -223,6 +236,7 @@ async def test_a_proxied_search_runs_one_native_request_and_answers_its_canonicaassert _hosted_result(tool, answer).execution.executor_source_id == executor[0]# Metered on the executor Source, like any gateway call.assert _usage_of(service, executor[0])+ assert latest_ok(service, tool) == (executor[0], executor[1], "executor")@pytest.mark.asyncio@@ -251,7 +265,6 @@ async def test_an_anthropic_executor_is_buffered_and_keeps_the_providers_results_bind(service, "web_search", (ANTHROPIC, "claude-haiku-4-5"))status, answer = await _call(service, "web_search", {"arguments": {"query": "CLIProxyAPI latest release"},- "executor": {"source_id": ANTHROPIC, "model_id": "claude-haiku-4-5"},})assert status == 200sent = service.adapter.requests[0]@@ -318,7 +331,6 @@ async def test_a_proxied_call_carries_the_pricing_modules_cost(tmp_path, tool, e_bind(service, tool, executor)status, answer = await _call(service, tool, {"arguments": {"query": "CLIProxyAPI latest release"},- "executor": {"source_id": executor[0], "model_id": executor[1]},})assert status == 200, answerassert answer["record"]["status"] == "completed"@@ -333,13 +345,15 @@ FAILED_WITH_PARTIAL = {**WEB_CALL, "status": "failed"}@pytest.mark.asyncio@pytest.mark.parametrize(("case", "bound", "handles", "error", "sources", "executed"), [- ("none_verified", None, [], "No Source is verified to run web_search", [], False),- ("source_removed", (XAI, "grok-4.6"), [], "no longer available", [], False),- # A new base URL or credential is a new identity: never verified, so never run.- ("source_identity_changed", (XAI, "grok-4.6"), [], "no longer available", [], False),+ # No Source can run it: the record says which providers' Sources could.+ ("no_candidate", None, [], "No Source can run web_search right now", [], False),+ ("source_removed", (XAI, "grok-4.6"), [], "No Source can run web_search right now", [], False),+ # A new base URL or credential is a new identity, which the turn's chain was not built for.+ ("source_identity_changed", (XAI, "grok-4.6"), [], "No Source can run web_search right now", [], False),+ # The only candidate failed: its failure, and the Sources tried.("provider_refused", (XAI, "grok-4.6"),[InvokeHandle(_outcome(RawOutcomeKind.HTTP_ERROR, status=429, code="rate_limit_error", source_id=XAI))],- "refused the call (HTTP 429 rate_limit_error)", [], True),+ "refused the call (HTTP 429 rate_limit_error). Tried: xAI key.", [], True),("tool_never_ran", (XAI, "grok-4.6"),[LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=XAI), _responses(WEB_ANSWER))],"did not run web_search", [], True),@@ -372,9 +386,8 @@ async def test_a_proxied_call_that_cannot_complete_is_a_failed_record(for item in service.store.config.sources]- executor = {"source_id": bound[0], "model_id": bound[1]} if bound else Nonestatus, answer = await _call(- service, "web_search", {"arguments": {"query": "q"}, "executor": executor}, after_launch=remove_executor,+ service, "web_search", {"arguments": {"query": "q"}}, after_launch=remove_executor,)assert status == 200assert answer["record"]["status"] == "failed"@@ -385,6 +398,104 @@ async def test_a_proxied_call_that_cannot_complete_is_a_failed_record(assert _hosted_result("web_search", answer).record.status == "failed"+def _chain(service, tool, *executors):+ """Turn the tool on with these Sources as its executor chain, in this order, each on its executor model."""++ config = service.store.config+ config.hosted_tools[tool] = ModelHubHostedToolConfig(enabled=True, executor_order=tuple(e[0] for e in executors))+ for source_id, model_id in executors:+ _EXECUTOR_MODELS[next(item for item in config.sources if item.id == source_id).vendor] = model_id+++def _refusal(status, code, source_id, **fields):+ return _outcome(RawOutcomeKind.HTTP_ERROR, status=status, code=code, source_id=source_id, **fields)+++def _served_by_openai():+ return LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), _responses(WEB_CALL, WEB_ANSWER))+++BILLED = ProtocolUsageReport.of(input_tokens=900, cached_input_tokens=0, output_tokens=40)+NARROW = replace(+ _refusal(400, "invalid_request_error", XAI),+ rejection=UpstreamRejection(status=400, code="invalid_request_error", unsupported_tool_type="web_search"),+)++[email protected](("case", "handles", "invoked", "status", "served_by", "failed_attempts"), [+ # A failure normal routing fails over from moves on; a refusal before output that reported no tokens is unbilled.+ ("rate_limited", lambda: [InvokeHandle(_refusal(429, "rate_limit_error", XAI)), _served_by_openai()],+ [XAI, OPENAI], "completed", OPENAI, []),+ # A failure mid-response moves on too, since nothing reached Vibey yet, and it was billed.+ ("failed_mid_response", lambda: [+ LiveInvokeHandle(_refusal(200, "server_error", XAI, stream_started=True, usage=BILLED), _responses(WEB_CALL)[:-1]),+ _served_by_openai(),+ ], [XAI, OPENAI], "completed", OPENAI, [XAI]),+ # A refusal of the executor model, or a narrow rule's: the Source leaves the chain until the refusal is cleared.+ ("executor_model_refused", lambda: [InvokeHandle(_refusal(404, "model_not_found", XAI)), _served_by_openai()],+ [XAI, OPENAI], "completed", OPENAI, []),+ ("narrow_rule_refused", lambda: [InvokeHandle(NARROW), _served_by_openai()], [XAI, OPENAI], "completed", OPENAI, []),+ # The model chose not to search: no Source failed, and moving on would double the cost.+ ("model_chose_not_to_run", lambda: [+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=XAI), _responses(WEB_ANSWER)),+ ], [XAI], "failed", XAI, []),+ # Any other outcome ends the chain.+ ("request_rejected", lambda: [InvokeHandle(_refusal(400, "invalid_request_error", XAI, message="Bad field"))],+ [XAI], "failed", XAI, []),+ ("every_candidate_failed", lambda: [+ InvokeHandle(_refusal(429, "rate_limit_error", XAI)), InvokeHandle(_refusal(503, "server_error", OPENAI)),+ ], [XAI, OPENAI], "failed", OPENAI, []),+])+async def test_the_chain_moves_on_only_past_a_source_failure(+ tmp_path, case, handles, invoked, status, served_by, failed_attempts,+):+ """MH-HOSTED-GATEWAY-005: the executor chain (§6 step 4), each attempt metered and listed with its own billing."""++ service = _vibey_service(tmp_path, _sources(), handles=handles())+ _chain(service, "web_search", (XAI, "grok-4.6"), (OPENAI, "gpt-6-astra"))+ answer_status, answer = await _call(service, "web_search", {"arguments": {"query": "q"}})+ assert answer_status == 200+ assert [entry[0] for entry in service.adapter.invocations] == invoked+ assert answer["record"]["status"] == status+ assert answer["execution"]["executor_source_id"] == served_by+ assert [attempt["source_id"] for attempt in answer["execution"].get("failed_attempts", [])] == failed_attempts+ assert all(attempt["billing"] == "metered" for attempt in answer["execution"].get("failed_attempts", []))+ assert _hosted_result("web_search", answer).record.status == status+ if case == "every_candidate_failed":+ assert answer["record"]["error"].endswith("Tried: xAI key, OpenAI key.")+ xai = next(item for item in service.store.config.sources if item.id == XAI)+ refused = service.hosted_evidence().unsupported(xai, "grok-4.6", EvidenceFeature.hosted("web_search", "call"))+ assert refused is (case in {"executor_model_refused", "narrow_rule_refused"})+ # The next turn's chain leaves a refused Source out.+ chain = service.freeze_turn_hosted_tools(service.store.config).executors["web_search"]+ assert [slot.source_id for slot in chain] == ([OPENAI] if refused else [XAI, OPENAI])+++async def test_a_call_reports_the_source_as_its_final_admission_saw_it(tmp_path):+ """MH-HOSTED-GATEWAY-005: a Source edited while the engine is prepared runs and is billed as it now stands."""++ service = _vibey_service(tmp_path, _sources(), handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=XAI), _responses(WEB_CALL, WEB_ANSWER)),+ ])+ _bind(service, "web_search", (XAI, "grok-4.6"))+ prepare = service._prepare_engine_for_demand++ async def edited_meanwhile(*args, **kwargs):+ # Billing and the name are not the Source's identity, so it is still admitted.+ service.store.config.sources = [+ replace(item, billing="monthly", display_name="xAI team plan") if item.id == XAI else item+ for item in service.store.config.sources+ ]+ await prepare(*args, **kwargs)++ service._prepare_engine_for_demand = edited_meanwhile+ status, answer = await _call(service, "web_search", {"arguments": {"query": "q"}})+ assert status == 200 and answer["record"]["status"] == "completed"+ assert (answer["execution"]["executor_billing"], answer["execution"]["cost"]) == ("monthly", {"basis": "included"})++@pytest.mark.asyncioasync def test_failure_text_is_in_the_users_language(tmp_path):"""MH-HOSTED-GATEWAY-005: the record's error is user-visible on the tool card, so it is localized."""@@ -392,39 +503,25 @@ async def test_failure_text_is_in_the_users_language(tmp_path):service = _vibey_service(tmp_path, _sources())_bind(service, "x_search", None)status, answer = await _call(- service, "x_search", {"arguments": {"query": "q"}, "executor": None}, language="zh",+ service, "x_search", {"arguments": {"query": "q"}}, language="zh",)assert status == 200- assert answer["record"]["error"] == "没有已验证可运行 x_search 的来源。请在「模型」中为某个来源验证它。"+ assert answer["record"]["error"] == "当前没有可运行 x_search 的来源。添加以下任一供应商的来源即可使用:xAI。"@pytest.mark.asyncio[email protected]("case", ["another_executor", "a_claude_subscription", "tool_not_enabled_this_turn"])-async def test_only_the_executor_the_live_turn_bound_may_run(tmp_path, case):- """MH-HOSTED-GATEWAY-005: the token's turn bound one executor per tool; any other is refused, unrun."""-- subscription = replace(- _source("src_claudesub01", "Claude subscription", vendor="anthropic", protocol="anthropic",- model_id="claude-haiku-4-5"),- kind="subscription", billing="monthly",- )- service = _vibey_service(tmp_path, _sources(subscription))- if case != "tool_not_enabled_this_turn":- _bind(service, "web_search", (XAI, "grok-4.6"))- named = {- "another_executor": (OPENAI, "gpt-6-astra"),- "a_claude_subscription": ("src_claudesub01", "claude-haiku-4-5"),- "tool_not_enabled_this_turn": (XAI, "grok-4.6"),- }[case]- status, answer = await _call(service, "web_search", {- "arguments": {"query": "q"}, "executor": {"source_id": named[0], "model_id": named[1]},- })- assert (status, answer) == (409, {"type": "error", "error": {"type": "executor_not_bound", "code": "executor_not_bound"}})- assert service.adapter.invocations == []-+async def test_a_call_runs_only_a_tool_its_live_turn_froze(tmp_path):+ """MH-HOSTED-GATEWAY-005: a tool the turn did not declare is refused, unrun; turning it on mid-turn changes nothing."""+ service = _vibey_service(tmp_path, _sources())+ service.store.config.hosted_tools["web_search"] = ModelHubHostedToolConfig(enabled=False)+ def turned_on(_hop):+ _bind(service, "web_search", (XAI, "grok-4.6"))+ status, answer = await _call(service, "web_search", {"arguments": {"query": "q"}}, after_launch=turned_on)+ assert (status, answer) == (409, {"type": "error", "error": {"type": "tool_not_enabled", "code": "tool_not_enabled"}})+ assert service.adapter.invocations == []@pytest.mark.asyncio@@ -448,7 +545,7 @@ async def test_a_call_is_metered_in_the_slice_it_ended_in(tmp_path):service.usage_writer = UsageWriter(service.usage)_bind(service, "web_search", (XAI, "grok-4.6"))status, _answer = await _call(service, "web_search", {- "arguments": {"query": "q"}, "executor": {"source_id": XAI, "model_id": "grok-4.6"},+ "arguments": {"query": "q"},})assert status == 200rows = json.loads(service.usage.path.read_text(encoding="utf-8"))@@ -501,7 +598,7 @@ async def test_one_failed_anthropic_search_fails_the_call_and_keeps_the_results_])_bind(service, "web_search", (ANTHROPIC, "claude-haiku-4-5"))status, answer = await _call(service, "web_search", {- "arguments": {"query": "q"}, "executor": {"source_id": ANTHROPIC, "model_id": "claude-haiku-4-5"},+ "arguments": {"query": "q"},})assert status == 200assert answer["record"]["status"] == "failed" and "too_many_requests" in answer["record"]["error"]@@ -517,7 +614,7 @@ async def test_a_turn_owns_its_proxied_calls(tmp_path):_bind(service, "web_search", (XAI, "grok-4.6"))gateway = ModelHubTurnGateway(service)router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)- body = json.dumps({"arguments": {"query": "q"}, "executor": {"source_id": XAI, "model_id": "grok-4.6"}})+ body = json.dumps({"arguments": {"query": "q"}})try:hop = await router.resolve_hop("menu-alias", process_scope="vibey:own", turn_id="turn-own")async with aiohttp.ClientSession() as client:@@ -532,13 +629,15 @@ async def test_a_turn_owns_its_proxied_calls(tmp_path):await asyncio.wait_for(completion, timeout=5)assert blocked.cancelled.is_set() and finished == [1]pending.cancel()- # The turn no longer admits work: a new call is refused before anything runs.- async with client.post(- f'{hop["base_url"]}/hosted-tools/web_search',- headers={"Authorization": f'Bearer {hop["token"]}', **hop["request_headers"]}, data=body,- ) as response:- assert response.status == 409- assert (await response.json())["error"]["code"] == "executor_not_bound"+ # The turn no longer admits work: a new call is refused before anything runs, and before its body is+ # read, so even a malformed one is answered as the closed turn it came from.+ for data in (body, b"not json"):+ async with client.post(+ f'{hop["base_url"]}/hosted-tools/web_search',+ headers={"Authorization": f'Bearer {hop["token"]}', **hop["request_headers"]}, data=data,+ ) as response:+ assert response.status == 409+ assert (await response.json())["error"]["code"] == "turn_not_live"finally:await gateway.close()assert len(service.adapter.invocations) == 1@@ -605,7 +704,7 @@ async def test_only_a_response_that_completed_completes_the_call(tmp_path, case,])_bind(service, "web_search", executor)answer_status, answer = await _call(service, "web_search", {- "arguments": {"query": "q"}, "executor": {"source_id": executor[0], "model_id": executor[1]},+ "arguments": {"query": "q"},})assert answer_status == 200assert answer["record"]["status"] == status@@ -615,40 +714,47 @@ async def test_only_a_response_that_completed_completes_the_call(tmp_path, case,@pytest.mark.asyncio-async def test_a_turn_keeps_its_hosted_binding_until_the_next_turn(tmp_path):- """MH-HOSTED-GATEWAY-005: settings apply from the next turn; later attempts of a turn keep its executors."""+async def test_a_turn_keeps_its_tools_and_executor_order_until_the_next_turn(tmp_path):+ """MH-HOSTED-GATEWAY-005: settings apply from the next turn; later hops of a turn keep its tools and chain."""service = _vibey_service(tmp_path, _sources(), handles=[LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=XAI), _responses(WEB_CALL, WEB_ANSWER)),+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), _responses(WEB_CALL, WEB_ANSWER)),])_bind(service, "web_search", (XAI, "grok-4.6"))service.store.config.hosted_tools["x_search"] = ModelHubHostedToolConfig(enabled=False)gateway = ModelHubTurnGateway(service)router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)++ async def search(hop, tool):+ async with aiohttp.ClientSession() as client:+ async with client.post(+ f'{hop["base_url"]}/hosted-tools/{tool}',+ headers={"Authorization": f'Bearer {hop["token"]}', **hop["request_headers"]},+ data=json.dumps({"arguments": {"query": "q"}}),+ ) as response:+ return response.status, await response.json()+try:first = await router.resolve_hop("menu-alias", process_scope="vibey:freeze", turn_id="turn-freeze")- # Mid-turn, the user moves web search to another executor and turns X search on.+ # Mid-turn, the user puts OpenAI first for web search and turns X search on._bind(service, "web_search", (OPENAI, "gpt-6-astra"))_bind(service, "x_search", (XAI, "grok-4.6"))again = await router.resolve_hop("menu-alias", process_scope="vibey:freeze", turn_id="turn-freeze")assert again["hosted_tools"].keys() == first["hosted_tools"].keys() == {"web_search"}- assert again["hosted_tools"]["web_search"]["executor"] == {"source_id": XAI, "model_id": "grok-4.6"}- async with aiohttp.ClientSession() as client:- async with client.post(- f'{again["base_url"]}/hosted-tools/web_search',- headers={"Authorization": f'Bearer {again["token"]}', **again["request_headers"]},- data=json.dumps({"arguments": {"query": "q"}, "executor": again["hosted_tools"]["web_search"]["executor"]}),- ) as response:- assert response.status == 200- assert (await response.json())["execution"]["executor_source_id"] == XAI+ status, answer = await search(again, "web_search")+ assert status == 200 and answer["execution"]["executor_source_id"] == XAI+ assert (await search(again, "x_search"))[0] == 409completion = router.settle_turn("turn-freeze", settled_by=SETTLED_BY_STOPPED, ts=NOW.isoformat())if completion is not None:await completionnxt = await router.resolve_hop("menu-alias", process_scope="vibey:freeze", turn_id="turn-next")- assert nxt["hosted_tools"]["web_search"]["executor"] == {"source_id": OPENAI, "model_id": "gpt-6-astra"}- assert "x_search" in nxt["hosted_tools"]+ assert {"web_search", "x_search"} <= nxt["hosted_tools"].keys()+ status, answer = await search(nxt, "web_search")+ assert status == 200 and answer["execution"]["executor_source_id"] == OPENAIfinally:await gateway.close()+ assert [entry[0] for entry in service.adapter.invocations] == [XAI, OPENAI]@pytest.mark.asyncio@@ -658,7 +764,7 @@ async def test_a_proxy_call_body_is_bounded(tmp_path):service = _vibey_service(tmp_path, _sources())_bind(service, "web_search", None)status, answer = await _call(service, "web_search", json.dumps(- {"arguments": {"query": "q" * (1024 * 1024)}, "executor": None},+ {"arguments": {"query": "q" * (1024 * 1024)}},).encode())assert (status, answer["error"]["code"]) == (400, "invalid_request_error")assert service.adapter.invocations == []@@ -697,11 +803,7 @@ async def test_a_call_cancelled_before_its_handle_is_still_metered(tmp_path, montry:hop = await router.resolve_hop("menu-alias", process_scope="vibey:cancel", turn_id="turn-cancel")call = service.run_hosted_tool(- "web_search",- {"arguments": {"query": "q"}, "executor": {"source_id": XAI, "model_id": "grok-4.6"}},- bindings=gateway.correlation.hosted_executor_bindings(- backend="vibey", token=hop["token"], request_metadata={"avibe_turn_id": "turn-cancel"},- )[1],+ "web_search", {"arguments": {"query": "q"}}, turn=gateway.correlation.turn_hosted_tools("turn-cancel"),)if ended_by == "caller":with pytest.raises(asyncio.CancelledError):@@ -727,8 +829,8 @@ async def test_an_encoded_proxy_call_body_is_refused(tmp_path):async with aiohttp.ClientSession(auto_decompress=False) as client:async with client.post(f'{hop["base_url"]}/hosted-tools/web_search',- headers={"Authorization": f'Bearer {hop["token"]}', "Content-Encoding": "gzip"},- data=gzip.compress(json.dumps({"arguments": {"query": "q"}, "executor": None}).encode()),+ headers={"Authorization": f'Bearer {hop["token"]}', **hop["request_headers"], "Content-Encoding": "gzip"},+ data=gzip.compress(json.dumps({"arguments": {"query": "q"}}).encode()),) as response:assert response.status == 400finally:@@ -753,35 +855,37 @@ class _CountedHandle(LiveInvokeHandle):@pytest.mark.asyncioasync def test_a_buffered_executor_response_is_bounded(tmp_path, monkeypatch):- """MH-HOSTED-GATEWAY-005: an oversized buffered body fails the call instead of growing without bound.+ """MH-HOSTED-GATEWAY-005: an oversized buffered body fails the attempt instead of growing without bound.- Once refused, the response is not read any further, and the call is still metered from its outcome.+ Once refused, the response is not read any further, and the attempt is still metered from its outcome. Nothing+ reached Vibey, so the chain tries its next candidate; the oversized attempt is listed as billed."""monkeypatch.setattr(service_module, "EXECUTOR_RESPONSE_MAX_BYTES", 64)oversized = b"{" + b" " * 128usage = ProtocolUsageReport.of(input_tokens=900, cached_input_tokens=0, output_tokens=40)handle = _CountedHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=ANTHROPIC, usage=usage), (oversized, b"}"))- service = _vibey_service(tmp_path, _sources(), handles=[handle])- _bind(service, "web_search", (ANTHROPIC, "claude-haiku-4-5"))- status, answer = await _call(service, "web_search", {- "arguments": {"query": "q"}, "executor": {"source_id": ANTHROPIC, "model_id": "claude-haiku-4-5"},- })+ service = _vibey_service(tmp_path, _sources(), handles=[handle, _served_by_openai()])+ _chain(service, "web_search", (ANTHROPIC, "claude-haiku-4-5"), (OPENAI, "gpt-6-astra"))+ status, answer = await _call(service, "web_search", {"arguments": {"query": "q"}})assert status == 200- assert answer["record"]["status"] == "failed" and "larger than allowed" in answer["record"]["error"]- assert "execution" in answer+ assert [entry[0] for entry in service.adapter.invocations] == [ANTHROPIC, OPENAI]+ assert answer["record"]["status"] == "completed"+ assert answer["execution"]["executor_source_id"] == OPENAI+ assert [attempt["source_id"] for attempt in answer["execution"]["failed_attempts"]] == [ANTHROPIC]assert handle.read == [oversized]assert _usage_of(service, ANTHROPIC)@pytest.mark.asyncio@pytest.mark.parametrize(("tool", "body", "status", "code"), [- ("web_search", {"arguments": {"query": "q", "count": 3}, "executor": None}, 400, "invalid_request_error"),- ("web_search", {"arguments": {"query": " "}, "executor": None}, 400, "invalid_request_error"),- ("x_search", {"arguments": {"query": "q", "mode": "Oldest"}, "executor": None}, 400, "invalid_request_error"),- ("web_search", {"arguments": {"query": "q"}}, 400, "invalid_request_error"),+ ("web_search", {"arguments": {"query": "q", "count": 3}}, 400, "invalid_request_error"),+ ("web_search", {"arguments": {"query": " "}}, 400, "invalid_request_error"),+ ("x_search", {"arguments": {"query": "q", "mode": "Oldest"}}, 400, "invalid_request_error"),+ # v1's executor field is gone: the turn's chain decides.+ ("web_search", {"arguments": {"query": "q"}, "executor": None}, 400, "invalid_request_error"),("web_search", b"not json", 400, "invalid_request_error"),- ("code_interpreter", {"arguments": {}, "executor": None}, 404, "not_found_error"),+ ("code_interpreter", {"arguments": {}}, 404, "not_found_error"),])async def test_a_malformed_proxy_call_is_refused_before_anything_runs(tmp_path, tool, body, status, code):"""MH-HOSTED-GATEWAY-005: only a malformed call is an error status; nothing is invoked."""@@ -798,7 +902,7 @@ async def test_a_proxy_call_needs_the_turns_gateway_token(tmp_path):service = _vibey_service(tmp_path, _sources())status, answer = await _call(- service, "web_search", {"arguments": {"query": "q"}, "executor": None}, token="not-the-turn-token",+ service, "web_search", {"arguments": {"query": "q"}}, token="not-the-turn-token",)assert (status, answer["error"]["code"]) == (401, "authentication_error")diff --git a/tests/test_model_hub_hosted_pinning.py b/tests/test_model_hub_hosted_pinning.pyindex 95bef8c99..899298bdd 100644--- a/tests/test_model_hub_hosted_pinning.py+++ b/tests/test_model_hub_hosted_pinning.py@@ -39,6 +39,13 @@ from vibe.backend_model_catalog import hosted_tool_specPIN = "x-avibe-pin-source"PIN_MODEL = "x-avibe-pin-model"PIN_UNAVAILABLE = {"type": "error", "error": {"type": "model_hub_pin_unavailable", "code": "pin_unavailable"}}+++def _refused(tool, aspect, source_id):+ """The 409 a narrow hosted rule's handback answers: it names what was refused, and where."""++ reason = {"kind": "hosted_unsupported", "tool": tool, "aspect": aspect, "source_id": source_id}+ return {"type": "error", "error": {**PIN_UNAVAILABLE["error"], "reason": reason}}SHELL = {"type": "function", "name": "shell", "parameters": {"type": "object", "properties": {}}}PORTABLE_X_SEARCH = {"type": "function", "name": "x_search", "parameters": {"type": "object", "properties": {}}}SIGNED_REASONING = {"type": "reasoning", "id": "rs_1", "summary": [], "encrypted_content": "opaque-signed"}@@ -447,7 +454,7 @@ async def test_a_handed_back_refusal_does_not_end_the_turn(tmp_path):turn_id = "turn-withdraw"try:hop = await router.resolve_hop("menu-alias", process_scope="vibey:withdraw", turn_id=turn_id)- assert await _post(hop, _native(hop), pin=primary.id) == (409, PIN_UNAVAILABLE)+ assert await _post(hop, _native(hop), pin=primary.id) == (409, _refused("x_search", "call", primary.id))# The turn ends before any resend (the user stops it): the handed-back# refusal must not stand as the turn's terminal error.completion = router.settle_turn(turn_id, settled_by=SETTLED_BY_STOPPED, ts=NOW.isoformat())@@ -486,7 +493,7 @@ async def test_a_pinned_hop_must_speak_the_requests_protocol(tmp_path):@pytest.mark.asyncioasync def test_a_refusal_naming_the_pinned_hosted_content_is_handed_back_and_learned(tmp_path):- """MH-HOSTED-GATEWAY-002: case 3, a narrow hosted-content rule (#2551) turns the pinned 400 into a handback."""+ """MH-HOSTED-GATEWAY-002: case 3, a narrow hosted-content rule (#2551) turns the pinned 400 into a handback with its reason."""primary, fallback = _sources()refusal = replace(@@ -500,7 +507,8 @@ async def test_a_refusal_naming_the_pinned_hosted_content_is_handed_back_and_learouter = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)try:hop = await router.resolve_hop("menu-alias", process_scope="vibey:learn", turn_id="turn-learn")- assert await _post(hop, _native(hop), pin=primary.id) == (409, PIN_UNAVAILABLE)+ # The 409 names the refused feature; only a narrow rule's handback carries a reason.+ assert await _post(hop, _native(hop), pin=primary.id) == (409, _refused("x_search", "call", primary.id))finally:await gateway.close()assert [entry[0] for entry in service.adapter.invocations] == [primary.id]diff --git a/tests/test_model_hub_hosted_tools_resolution.py b/tests/test_model_hub_hosted_tools_resolution.pyindex 7972c1354..74845321e 100644--- a/tests/test_model_hub_hosted_tools_resolution.py+++ b/tests/test_model_hub_hosted_tools_resolution.py@@ -34,11 +34,13 @@ from core.handlers.model_hub.hosted_tools import (HostedToolSettingRefused,apply_hosted_tool_put,executor_candidates,+ freeze_turn_tools,+ hop_hosted_tools,hosted_tool_facts,hosted_tools_status,image_choices,- resolve_hosted_tools,)+from core.handlers.model_hub.hosted_turn import ExecutorSlotfrom vibe.backend_model_catalog import HostedToolPrice, HostedToolSpec, ImageModelPrice, ImageModelSpecNOW = datetime(2026, 10, 15, 12, 0, tzinfo=timezone.utc)@@ -195,25 +197,42 @@ def test_the_image_enum_is_deterministic_with_the_default_first(tmp_path):assert image_choices(_config(sources=[CLAUDE_SUB, GEMINI]), evidence=evidence).models == ()-def test_resolution_states_v2_facts_in_todays_hop_shape(tmp_path):- """MH-HOSTED-001: every tool is on unless turned off; native when assumed; the first executor binds."""- resolved = resolve_hosted_tools(- _config(), source=XAI, model_id="grok-4.6", evidence=_evidence(tmp_path), spec_for=_spec_for,- )- assert resolved == {+def test_a_turn_freezes_its_tools_executors_and_image_enum_and_each_hop_states_its_own_facts(tmp_path):+ """MH-HOSTED-001: every tool is on unless turned off; the turn freezes the set, each search tool's executor order+ with the identity it was built under, and the image enum; a hop states facts only, the enum's params sorted."""+ evidence = _evidence(tmp_path)+ turn = freeze_turn_tools(_config(), evidence=evidence, spec_for=_spec_for)+ assert turn.tools == {"web_search", "x_search", "image_generate"}+ assert turn.executors == {+ "web_search": (+ ExecutorSlot("src_xai00001", "grok-fast", identity_digest(XAI)),+ ExecutorSlot("src_oai00001", "gpt-mini", identity_digest(OPENAI)),+ ),+ "x_search": (ExecutorSlot("src_xai00001", "grok-fast", identity_digest(XAI)),),+ }+ image = {"description": "Grok Imagine", "params": ["images", "size"], "size_forms": ["pixels"]}+ assert hop_hosted_tools(turn, OPENAI, "gpt-6-astra", evidence=evidence, spec_for=_spec_for) == {"web_search": {- "mode": "native", "declaration": {"type": "web_search"}, "include": [],- "executor": {"source_id": "src_xai00001", "model_id": "grok-fast"}, "replay": True,+ "native": "assumed", "declaration": {"type": "web_search"},+ "include": ["web_search_call.action.sources"], "replay": "assumed",},- "x_search": {- "mode": "native", "declaration": {"type": "x_search"}, "include": [],- "executor": {"source_id": "src_xai00001", "model_id": "grok-fast"}, "replay": True,+ # OpenAI does not run X search: the hop takes the function.+ "x_search": {"native": "unsupported", "replay": "unsupported"},+ "image_generate": {+ "models": [+ {"source_id": "src_xai00001", "model_id": "grok-imagine-image", **image},+ {**{"source_id": "src_oai00001", "model_id": "gpt-image-2", **image}, "description": "OpenAI's image model"},+ ],+ "default": {"source_id": "src_xai00001", "model_id": "grok-imagine-image"},},}- off = _config({"x_search": ModelHubHostedToolConfig(enabled=False)})- assert set(resolve_hosted_tools(- off, source=XAI, model_id="grok-4.6", evidence=_evidence(tmp_path / "o"), spec_for=_spec_for,- )) == {"web_search"}+ # Off, or with no image model available, a tool is not declared at all.+ off = _config({"x_search": ModelHubHostedToolConfig(enabled=False)}, sources=[CLAUDE_SUB, OPENAI, GEMINI])+ turn = freeze_turn_tools(+ off, evidence=_evidence(tmp_path / "o", (OPENAI, "gpt-image-2", "image_generate", "call")), spec_for=_spec_for,+ )+ assert (turn.tools, turn.images) == ({"web_search"}, ())+ assert set(hop_hosted_tools(turn, OPENAI, "gpt-6-astra", evidence=evidence, spec_for=_spec_for)) == {"web_search"}def test_the_tools_read_states_saved_and_effective_values_and_what_real_use_showed(tmp_path):diff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex ca08637d7..56a3b7419 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -322,7 +322,7 @@ def test_route_alias_keeps_its_own_planning_metadata(tmp_path, monkeypatch, backturn_gateway=SimpleNamespace(endpoint=AsyncMock(return_value=("http://127.0.0.1:19000", "fixture-token")),correlation=SimpleNamespace(- gateway_request_metadata=lambda **_kwargs: {}, turn_hosted_executors=lambda _turn_id: None,+ gateway_request_metadata=lambda **_kwargs: {}, turn_hosted_tools=lambda _turn_id: None,),),overlay_path=tmp_path / "overlay.json",diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.pyindex 67ab71199..813df5f2b 100644--- a/tests/test_model_hub_runtime.py+++ b/tests/test_model_hub_runtime.py@@ -8116,9 +8116,9 @@ def test_engine_client_preserves_large_valid_responses(b'{"output":[{"content":"' + large_value + b'"}]}'if not case["stream"]else (- b"event: response.image_generation_call.partial_image\n"- b'data: {"type":"response.image_generation_call.partial_image",'- b'"partial_image_b64":"'+ b"event: response.output_text.delta\n"+ b'data: {"type":"response.output_text.delta",'+ b'"delta":"'+ large_value+ b'"}\n\nevent: response.completed\ndata: {"type":"response.completed"}\n\n')diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex 8dc49c575..c657dbb7f 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -238,13 +238,6 @@ MODEL_OUTPUT_ENVELOPE_FIXTURES = ("response.function_call_arguments.delta",False,),- (- "openai_responses",- "response.image_generation_call.partial_image",- ("type",),- "response.image_generation_call.partial_image",- False,- ),("openai_chat", None, ("choices", "*", "delta", "content"), None, True),("openai_chat", None, ("choices", "*", "delta", "reasoning_content"), None, True),("openai_chat", None, ("choices", "*", "delta", "refusal"), None, True),@@ -710,12 +703,12 @@ def test_usage_metering_has_one_owner_per_call_population() -> None:meter_calls = [node for node in ast.walk(service_tree) if _call_name(node) == "_meter_call"]- # Calls a user asked for (the Source test and hosted-tool probes, both- # through `_user_test_call`) and proxied hosted-tool calls consume their own- # response rather than forwarding a Turn to the gateway. They reuse the same- # metering owner, exactly once.+ # Calls a user asked for (the Source test, through `_user_test_call`) and+ # each executor call of a proxied search consume their own response rather+ # than forwarding a Turn to the gateway. They reuse the same metering owner,+ # exactly once.consumers = (- invoke, _functions(service_tree)["_user_test_call"], _functions(service_tree)["run_hosted_tool"],+ invoke, _functions(service_tree)["_user_test_call"], _functions(service_tree)["_executor_attempt"],)assert len(meter_calls) == len(consumers)assert all(@@ -1760,11 +1753,11 @@ def test_exact_sse_tokenizer_accepts_large_protocol_frames() -> None:assert tokenizer.feed(b"data: " + data + b"\n\n") == (b"data: " + data,)-def test_large_image_event_is_observed_without_retaining_its_base64_body() -> None:+def test_large_output_event_is_observed_without_retaining_its_body() -> None:state = ProtocolSSEState("openai_responses")- event_type = b"response.image_generation_call.partial_image"+ event_type = b"response.output_text.delta"state.observe(- b"event: " + event_type + b'\ndata: {"type":"' + event_type + b'","partial_image_b64":"'+ b"event: " + event_type + b'\ndata: {"type":"' + event_type + b'","delta":"')assert state.model_output_started is Falsediff --git a/tests/test_model_hub_vibey_consumer.py b/tests/test_model_hub_vibey_consumer.pyindex 97f4d8121..e980fd54b 100644--- a/tests/test_model_hub_vibey_consumer.py+++ b/tests/test_model_hub_vibey_consumer.py@@ -104,7 +104,7 @@ def _validate(schema_name, value):# Each enabled hosted tool's promised fields, for a native and a proxied entry.HOSTED_TOOL_MANDATORY_FIELDS = {- ("hosted_tools", "web_search"): ("mode", "executor", "replay", "declaration", "include"),+ ("hosted_tools", "web_search"): ("native", "replay", "declaration", "include"),}@@ -617,7 +617,7 @@ async def test_a_finished_turns_request_is_never_credited_to_the_next_turn_on_it) as response:return response.status, await response.json(content_type=None)- search = {"arguments": {"query": "q"}, "executor": None}+ search = {"arguments": {"query": "q"}}try:async with aiohttp.ClientSession() as client:finished = await router.resolve_hop("menu-alias", process_scope="vibey:session", turn_id="turn-finished")@@ -631,7 +631,7 @@ async def test_a_finished_turns_request_is_never_credited_to_the_next_turn_on_itstale = finished["request_headers"]assert (await post(client, live, stale, "messages", message))[0] == 400status, answer = await post(client, live, stale, "hosted-tools/x_search", search)- assert (status, answer["error"]["code"]) == (409, "executor_not_bound")+ assert (status, answer["error"]["code"]) == (409, "turn_not_live")status, answer = await post(client, live, live["request_headers"], "hosted-tools/x_search", search)assert status == 200 and answer["record"]["status"] == "failed"assert (await post(client, live, live["request_headers"], "messages", message))[0] == 200@@ -1069,8 +1069,8 @@ def test_native_cli_and_direct_are_not_vibey_channels(tmp_path):@pytest.mark.asyncioasync def test_hop_resolution_states_each_enabled_hosted_tool(tmp_path):- """MH-HOSTED-001: a tool the overlay offers is native with no evidence (nothing is probed); every enabled tool- binds the first executor of its chain, the vendor's lightweight model."""+ """MH-HOSTED-001: a tool the overlay offers is assumed native with no evidence (nothing is probed); the hop states+ facts only, never an executor, and a tool the user turned off is absent."""primary = _source("src_primary01", "Primary", protocol="openai_responses", model_id="gpt-6-astra")service = _vibey_service(tmp_path, [primary])service.store.config.hosted_tools = {"x_search": ModelHubHostedToolConfig(enabled=False)}@@ -1091,26 +1091,33 @@ async def test_hop_resolution_states_each_enabled_hosted_tool(tmp_path):_validate("hop-resolution.schema.json", hop)assert hop["hosted_tools"] == {"web_search": {- "mode": "native",+ "native": "assumed","declaration": {"type": "web_search"},"include": ["web_search_call.action.sources"],- "executor": {"source_id": "src_primary01", "model_id": "gpt-6-luna"},- "replay": True,+ "replay": "assumed",},}_assert_mandatory_fields("hop-resolution.schema.json", hop, HOSTED_TOOL_MANDATORY_FIELDS)+ image = {"source_id": "src_primary01", "model_id": "gpt-image-2", "description": "OpenAI images",+ "params": ["images", "n", "size"], "size_forms": ["pixels"]}+ _validate("hop-resolution.schema.json", {**hop, "hosted_tools": {+ "web_search": {"native": "unsupported", "replay": "unsupported"},+ "image_generate": {"models": [image], "default": {"source_id": "src_primary01", "model_id": "gpt-image-2"}},+ }})for broken in (- {"mode": "proxy", "declaration": {"type": "web_search"}, "executor": None, "replay": False},- {"mode": "native", "executor": None, "replay": False, "include": []},- {"mode": "proxy", "executor": {"source_id": "src_primary01"}, "replay": False},+ # Declaration and include belong to an assumed native tool only.+ {"web_search": {"native": "unsupported", "declaration": {"type": "web_search"}, "replay": "unsupported"}},+ {"web_search": {"native": "assumed", "include": [], "replay": "assumed"}},+ # v1's shape is gone: no mode, no executor, no boolean replay.+ {"web_search": {"mode": "proxy", "executor": None, "replay": False}},+ {"web_search": {"native": "assumed", "declaration": {"type": "web_search"}, "include": [], "replay": True}},+ {"image_generation": {"native": "unsupported", "replay": "unsupported"}},+ # image_generate is absent rather than empty, and names only what the enum needs.+ {"image_generate": {"models": [], "default": {"source_id": "src_primary01", "model_id": "gpt-image-2"}}},+ {"image_generate": {"models": [{**image, "endpoint": "images"}], "default": image}},):with pytest.raises(ValidationError):- _validate("hop-resolution.schema.json", {**hop, "hosted_tools": {"web_search": broken}})- with pytest.raises(ValidationError):- _validate(- "hop-resolution.schema.json",- {**hop, "hosted_tools": {"image_generation": {"mode": "proxy", "executor": None, "replay": True}}},- )+ _validate("hop-resolution.schema.json", {**hop, "hosted_tools": broken})finally:await gateway.close()diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex 23c86b87e..d1e578cf1 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -61,7 +61,7 @@ from core.agent_core.messages import (text,message_to_dict,)-from core.agent_core.tools.base import CallInstance, JobStatus, ToolResult+from core.agent_core.tools.base import CallInstance, JobStatus, ToolResult, ToolSpecfrom core.message_dispatcher import ConsolidatedMessageDispatcherfrom core.services.agent_steering import ActiveSteerTarget, SteerOutcome, SteerRequestfrom modules.agents.vibey import VibeyAgent@@ -2218,33 +2218,14 @@ async def test_im_narration_is_live_best_effort_output(engine, session, tmp_pathassert "Third look." not in hidden.controller.im_client.sent- "final, row_type", [("answer", "result"), ("empty", "error"), ("refusal", "error"), ("image", "result")]-)[email protected]("final, row_type", [("answer", "result"), ("empty", "error"), ("refusal", "error")])async def test_a_final_is_stored_with_its_outcome_semantics(engine, session, tmp_path, published, final, row_type) -> None:- image = tmp_path / "image-final.png"- image.write_bytes(b"\x89PNG\r\n\x1a\nimage")message = {"answer": assistant("here it is"),"empty": assistant(""),"refusal": AssistantMessage((), ORIGIN, "refusal"),- # A generated image is a reply by itself (``has_reply``).- "image": AssistantMessage(- (- HostedToolBlock(- id="ig_1",- tool="image_generation",- action=HostedAction(type="generate", prompt="a laptop at night"),- record=HostedRecord(status="completed", images=(HostedImage(path=str(image), mime="image/png"),)),- native=HostedNative(source_id="src_testsrc1", payload=({"type": "image_generation_call"},)),- ),- ),- ORIGIN,- "stop",- hosted_summary=HostedSummary(),- ),}[final]harness = _Harness(engine, tmp_path, "avibe", [[Done(message)]])@@ -2475,9 +2456,10 @@ async def test_a_turn_runs_through_the_real_provider_registry(engine, session, tasync def test_a_hop_resolved_native_hosted_tool_reaches_the_gateway_pinned_to_its_source(engine, session, tmp_path, published, hub_protocol, declaration, include) -> None:- """MH-HOSTED-VIBEY-001 (vibey-hosted-tools.md §3.5, §4.1): Vibey takes each tool's mode from the hop. A tool the- preflight hop runs natively joins the Turn's tools first, and goes out as the provider's declaration, verbatim, with- its include values, on a request pinned to the hop's Source; a proxied tool goes out as its function."""+ """MH-HOSTED-VIBEY-001 (vibey-hosted-tools.md §3.4, §4.1): Vibey declares each search tool from the hop's facts.+ A tool the preflight hop is assumed to run natively joins the Turn's tools first, and goes out as the provider's+ declaration, verbatim, with its include values, on a request pinned to the hop's Source; a tool it does not run+ goes out as its function."""import httpxfrom modules.agents.vibey.models import registry_providers@@ -2495,17 +2477,14 @@ async def test_a_hop_resolved_native_hosted_tool_reaches_the_gateway_pinned_to_i200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": served}, text=body)- executor = {"source_id": "src_executor01", "model_id": "grok-4.6"}async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:harness = _Harness(engine, tmp_path, "telegram", [], providers=registry_providers(media_loader=None, client=client))harness.controller.hub_protocol = hub_protocolharness.controller.hub_hosted_tools = {- "web_search": {- "mode": "native", "declaration": declaration, "include": include, "executor": executor, "replay": True- },- "x_search": {"mode": "proxy", "executor": executor, "replay": False},+ "web_search": {"native": "assumed", "declaration": declaration, "include": include, "replay": "assumed"},+ "x_search": {"native": "unsupported", "replay": "unsupported"},}await harness.agent.handle_message(harness.request("hello"))@@ -2562,7 +2541,7 @@ async def test_a_native_search_is_kept_as_one_hosted_call_and_replayed_next_turnharness.controller.hub_protocol = "openai_responses"harness.controller.hub_hosted_tools = {"web_search": {- "mode": "native", "declaration": {"type": "web_search"}, "include": [], "executor": None, "replay": False+ "native": "assumed", "declaration": {"type": "web_search"}, "include": [], "replay": "unsupported"}}await harness.agent.handle_message(harness.request("search"))@@ -2578,8 +2557,6 @@ async def test_a_native_search_is_kept_as_one_hosted_call_and_replayed_next_turnassert "https://avibe.bot/r" in replayed[1]["output"]-_EXECUTOR = {"source_id": "src_executor01", "model_id": "grok-4.6"}-def _anthropic_reply(*blocks: str, stop_reason: str) -> str:"""An Anthropic stream of whole content blocks, each given as its ``content_block_start`` JSON."""@@ -2630,14 +2607,15 @@ def _anthropic_reply(*blocks: str, stop_reason: str) -> str:],ids=["executed", "no-executor", "refused", "unreachable", "no-result"],)-async def test_a_proxied_hosted_call_runs_on_the_bound_executor_and_keeps_its_record(+async def test_a_proxied_hosted_call_runs_on_the_turns_executor_chain_and_keeps_its_record(engine, session, tmp_path, published, status, answer, is_error, seen, code) -> None:- """MH-HOSTED-VIBEY-004 (vibey-hosted-tools.md §3.4): on a hop that does not run the tool natively, the model calls- the same-named function; Vibey asks the gateway's executor bound for the Turn, keeps the record and execution on- the tool result, and the model reads the record as text. A call that never reached an executor is a failed- record, never an empty success, and the reason Vibey writes for it carries its code (#2589). Every gateway- request, the model's and the executor's, names the Turn (``x-avibe-turn-id``), which binds the executor."""+ """MH-HOSTED-VIBEY-004 (vibey-hosted-tools.md §3.4, §6): on a hop that does not run the tool natively, the model+ calls the same-named function; Vibey asks the gateway, which runs it on the Turn's executor chain, keeps the record+ and execution on the tool result, and the model reads the record as text. A call that never reached an executor+ is a failed record, never an empty success, and the reason Vibey writes for it carries its code (#2589). Every+ gateway request, the model's and the executor's, names the Turn (``x-avibe-turn-id``), from which the gateway+ resolves the chain."""import httpxfrom modules.agents.vibey.models import registry_providers@@ -2676,13 +2654,14 @@ async def test_a_proxied_hosted_call_runs_on_the_bound_executor_and_keeps_its_reproviders=registry_providers(media_loader=None, client=client),gateway_client=client,)- harness.controller.hub_hosted_tools = {"web_search": {"mode": "proxy", "executor": _EXECUTOR, "replay": False}}+ harness.controller.hub_hosted_tools = {"web_search": {"native": "unsupported", "replay": "unsupported"}}message = harness.request("search")await harness.agent.handle_message(message)assert len(named) == 3 and set(named) == {_turn(message.context)}(request,) = executed- assert json.loads(request.content) == {"arguments": {"query": "avibe release"}, "executor": _EXECUTOR}+ # The gateway resolves the executor chain from the live Turn: the body is the arguments alone (C-6 item 7).+ assert json.loads(request.content) == {"arguments": {"query": "avibe release"}}assert request.headers["authorization"] == "Bearer hub-token"# The proxied tool is the canonical function, first among the Turn's tools.assert models[0]["tools"][0]["name"] == "web_search" and "input_schema" in models[0]["tools"][0]@@ -2694,121 +2673,132 @@ async def test_a_proxied_hosted_call_runs_on_the_bound_executor_and_keeps_its_reassert sent["type"] == "tool_result" and seen in json.dumps(sent)-async def test_a_proxied_image_is_saved_through_the_media_sink_and_its_record_names_the_file(- engine, session, tmp_path, published-) -> None:- """MH-HOSTED-VIBEY-007 (vibey-hosted-tools.md §7.3, item 27): the executor answers a proxied image's bytes beside- its record; Vibey saves them through the same sink as a native image, the record lists the file, and no base64- reaches the transcript or the model."""- import httpx-- from modules.agents.vibey.models import registry_providers-- served = json.dumps(- {"provider": "anthropic", "api": "anthropic", "model": "claude-opus-5-5", "source": "src_upstream01"},- separators=(",", ":"),- )- call = '{"type":"tool_use","id":"toolu_1","name":"image_generation","input":{"prompt":"a lighthouse"}}'- replies = [- _anthropic_reply(call, stop_reason="tool_use"),- _anthropic_reply('{"type":"text","text":"here it is"}', stop_reason="end_turn"),- ]- jpeg = b"\xff\xd8\xff\xe0" + bytes(range(256)) * 8- encoded = base64.b64encode(jpeg).decode()- answer = {- "record": {"status": "completed", "sources": []},- "execution": {- "mode": "proxy",- "executor_origin": {"provider": "openai", "api": "openai_responses", "model": "gpt-image"},- "executor_source_id": "src_executor01",- "executor_billing": "metered",- },- "generation": {"revised_prompt": "A lighthouse at dusk", "size": "1536x1024", "quality": "high"},- "images": [{"mime": "image/jpeg", "data": encoded}],- }- models: list[dict] = []-- def gateway(request: httpx.Request) -> httpx.Response:- if request.url.path == "/vibey/v1/hosted-tools/image_generation":- return httpx.Response(200, json=answer)- models.append(json.loads(request.content))- return httpx.Response(- 200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": served}, text=replies.pop(0)- )-- async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:- harness = _Harness(- engine,- tmp_path,- "telegram",- [],- providers=registry_providers(media_loader=None, client=client),- gateway_client=client,- )- harness.controller.hub_hosted_tools = {"image_generation": _PROXY_IMAGE}- await harness.agent.handle_message(harness.request("paint a lighthouse"))-- result = next(row.message for row in await harness.context_rows() if isinstance(row.message, ToolResultMessage))- (image,) = result.hosted.record.images- assert not result.is_error and result.hosted.record.status == "completed"- assert Path(image.path).read_bytes() == jpeg- assert (image.mime, image.width, image.height, image.bytes) == ("image/jpeg", 1536, 1024, len(jpeg))- assert f"Image saved: {image.path}" in result.content[0].text- assert encoded not in json.dumps(models) and encoded not in json.dumps(message_to_dict(result))- # The executor's rendered prompt and resolved size and quality, kept as a native call's block keeps them.- assert result.hosted.action == HostedAction(- "generate", prompt="A lighthouse at dusk", size="1536x1024", quality="high"- )- assert result.content[0].text.startswith('[image_generation: "A lighthouse at dusk"]')+_IMAGE_SPEC = ToolSpec(+ "image_generate",+ "Generate an image.",+ {"type": "object", "properties": {"model": {"type": "string"}, "prompt": {"type": "string"}}},+)+_JPEG = b"\xff\xd8\xff\xe0" + bytes(range(256)) * 8+_DIRECT = {+ "mode": "direct",+ "executor_origin": {"provider": "openai", "api": "openai_responses", "model": "gpt-image-2"},+ "executor_source_id": "src_executor01",+ "executor_billing": "metered",+}@pytest.mark.parametrize(("images", "stored", "error", "code"),[+ ([{"mime": "image/jpeg", "data": base64.b64encode(_JPEG).decode()}], True, None, None),([], True, "the executor returned no image", "executor_no_image"),([{"mime": "image/jpeg", "data": "@@@ not base64 @@@"}], True, "the image could not be saved: ", "image_not_saved"),([{"mime": "image/jpeg", "data": "/9j/4AAQ"}], False, "nothing here can keep a generated image", "image_no_store"),],- ids=["no-image", "unreadable", "no-store"],+ ids=["saved", "no-image", "unreadable", "no-store"],)-async def test_a_proxied_image_that_was_not_saved_is_a_failed_call_with_its_code(tmp_path, images, stored, error, code):- """§7.3, #2589: an executor's completed image call that saved no file is a failed record, never a completed one- listing nothing, and the reason Vibey writes for it carries its code, by which a display localizes it."""+async def test_an_image_the_endpoint_returns_is_saved_through_the_media_sink_and_its_record_names_the_file(+ tmp_path, images, stored, error, code+):+ """MH-HOSTED-VIBEY-007 (vibey-hosted-tools.md §7.3): the gateway answers an ``image_generate`` call's bytes beside+ its record; Vibey saves them through the session media sink, the record lists the file, the result keeps the+ model and what the endpoint rendered, and no base64 reaches the transcript. A completed call that saved no file is+ a failed record whose reason carries its code (#2589), never a completed one listing nothing."""import httpx- from core.agent_core.ai.provider import HostedExecutor, ModelEndpoint- from core.agent_core.tools.hosted import hosted_tool_spec+ from core.agent_core.ai.provider import ModelEndpointfrom modules.agents.vibey.tools import HostedToolanswer = {"record": {"status": "completed", "sources": []},- "execution": {- "mode": "proxy",- "executor_origin": {"provider": "openai", "api": "openai_responses", "model": "gpt-image"},- "executor_source_id": "src_executor01",- "executor_billing": "metered",- },+ "execution": _DIRECT,+ "generation": {"model": "gpt-image-2", "revised_prompt": "A lighthouse at dusk", "size": "1536x1024", "quality": "high"},"images": images,}endpoint = ModelEndpoint("anthropic", "http://hub.invalid/vibey/v1", "claude-opus-5-5", "hub-token")async with httpx.AsyncClient(transport=httpx.MockTransport(lambda _: httpx.Response(200, json=answer))) as client:tool = HostedTool(- hosted_tool_spec("image_generation"),- HostedExecutor("src_executor01", "gpt-image"),- endpoint,+ _IMAGE_SPEC,+ lambda: endpoint,client,media=MediaSnapshots(None, tmp_path / "media") if stored else None, # type: ignore[arg-type])- result = await tool.execute({"prompt": "a lighthouse"}, None) # type: ignore[arg-type]+ result = await tool.execute({"model": "gpt-image-2", "prompt": "a lighthouse"}, None) # type: ignore[arg-type]record = result.hosted.record- assert result.is_error and record.status == "failed" and record.images == ()- assert record.error.startswith(error) and record.error_code == code- assert not (tmp_path / "media").exists() or not any((tmp_path / "media").iterdir())+ if error is None:+ (image,) = record.images+ assert not result.is_error and record.status == "completed"+ assert Path(image.path).read_bytes() == _JPEG+ assert (image.mime, image.width, image.height, image.bytes) == ("image/jpeg", 1536, 1024, len(_JPEG))+ assert result.hosted.execution.mode == "direct"+ assert result.hosted.action == HostedAction(+ "generate", prompt="A lighthouse at dusk", size="1536x1024", quality="high", model="gpt-image-2"+ )+ assert result.content[0].text.startswith('[image_generate: "A lighthouse at dusk"]')+ assert f"Image saved: {image.path}" in result.content[0].text+ assert images[0]["data"] not in json.dumps(message_to_dict(+ ToolResultMessage("call_1", "image_generate", result.content, hosted=result.hosted)+ ))+ else:+ assert result.is_error and record.status == "failed" and record.images == ()+ assert record.error.startswith(error) and record.error_code == code+ assert not (tmp_path / "media").exists() or not any((tmp_path / "media").iterdir())-_NATIVE_SEARCH = {"mode": "native", "declaration": {"type": "web_search"}, "include": [], "executor": None, "replay": False}-_PROXY_IMAGE = {"mode": "proxy", "executor": {"source_id": "src_executor01", "model_id": "gpt-image"}, "replay": False}+async def test_a_proxied_call_after_the_turn_moved_to_another_source_runs_on_the_hop_it_now_holds(+ tmp_path, monkeypatch+):+ """MH-HOSTED-VIBEY-004, closed loop: the gateway answers a Vibey request only while its credential's route is the+ one the turn now holds (C-6 item 3). After a re-resolve moved the turn to another Source, a proxied call goes out+ on that hop, never on the one the turn's tools were built from, which the gateway answers ``turn_not_live``."""+ import httpx++ from config.v2_config import ModelHubHostedToolConfig, ModelHubRouteConfig, ModelHubRouteHopConfig+ from core.handlers.model_hub import hosted_tools as hosted_tools_module+ from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+ from modules.agents.model_hub import ModelHubRuntimeRouter+ from modules.agents.vibey.models import HubModelRouter, selection_from_hop+ from modules.agents.vibey.tools import hosted_tools+ from tests.test_model_hub_hosted_executor import OPENAI, XAI, _served_by_openai, _sources+ from tests.test_model_hub_vibey_consumer import _vibey_service++ monkeypatch.setattr(hosted_tools_module, "provider_executor_model", {"openai": "gpt-6-astra"}.get)+ service = _vibey_service(tmp_path, _sources(), handles=[_served_by_openai()])+ config = service.store.config+ config.hosted_tools["web_search"] = ModelHubHostedToolConfig(enabled=True, executor_order=(OPENAI,))+ gateway = ModelHubTurnGateway(service)+ hub = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)++ async def resolve():+ hop = await hub.resolve_hop("menu-alias", process_scope="vibey:moved", turn_id="turn-moved")+ return selection_from_hop(hop)++ try:+ router = HubModelRouter(resolve, lambda protocol: None, first=await resolve())+ async with httpx.AsyncClient(trust_env=False) as client:+ (search,) = [tool for tool in hosted_tools(router, client) if tool.spec.name == "web_search"]+ assert (await router.resolve()).endpoint.source_id == XAI+ # The turn's next hop is another Source (here its route changed; a pin refusal or a failover moves it too).+ config.agents["vibey"].routes["menu-alias"] = ModelHubRouteConfig((ModelHubRouteHopConfig(OPENAI, "gpt-6-astra"),))+ assert (await router.resolve()).endpoint.source_id == OPENAI+ result = await search.execute({"query": "q"}, None) # type: ignore[arg-type]+ finally:+ await gateway.close()++ assert not result.is_error, result.content[0].text+ assert result.hosted.execution.executor_source_id == OPENAI+++_NATIVE_SEARCH = {"native": "assumed", "declaration": {"type": "web_search"}, "include": [], "replay": "assumed"}+_PROXY_SEARCH = {"native": "unsupported", "replay": "unsupported"}+_IMAGES = {+ "models": [+ {"source_id": "src_executor01", "model_id": "gpt-image-2", "description": "OpenAI", "params": ["size"],+ "size_forms": ["pixels"]},+ ],+ "default": {"source_id": "src_executor01", "model_id": "gpt-image-2"},+}def _without(entry: dict, key: str) -> dict:@@ -2819,20 +2809,24 @@ def _without(entry: dict, key: str) -> dict:"hosted_tools",[None,- {"web_fetch": _PROXY_IMAGE},+ {"web_fetch": _PROXY_SEARCH},{"web_search": _without(_NATIVE_SEARCH, "declaration")},- {"web_search": {**_without(_NATIVE_SEARCH, "declaration"), "mode": "proxy"}},+ {"web_search": {**_PROXY_SEARCH, "include": []}},{"web_search": {**_NATIVE_SEARCH, "note": "extra"}},{"web_search": _without(_NATIVE_SEARCH, "replay")},- {"image_generation": {**_PROXY_IMAGE, "executor": {"source_id": "src_executor01"}}},- {"image_generation": {**_PROXY_IMAGE, "executor": {"source_id": "openai-main", "model_id": "gpt-image"}}},- {"image_generation": {**_PROXY_IMAGE, "replay": True}},- {"web_search": {**_NATIVE_SEARCH, "mode": []}},+ {"web_search": {**_NATIVE_SEARCH, "native": "native"}},+ {"web_search": {**_NATIVE_SEARCH, "native": []}},{"web_search": {**_NATIVE_SEARCH, "include": "web_search_call.action.sources"}},+ {"web_search": {**_PROXY_SEARCH, "executor": None}},+ {"image_generate": {**_IMAGES, "models": []}},+ {"image_generate": {**_IMAGES, "default": {"source_id": "src_executor01", "model_id": "grok-imagine"}}},+ {"image_generate": {**_IMAGES, "models": [{**_IMAGES["models"][0], "params": ["quality"]}]}},+ {"image_generate": {**_IMAGES, "models": [{**_IMAGES["models"][0], "source_id": "openai-main"}]}},],ids=[- "absent", "unknown-tool", "native-without-declaration", "proxy-with-include", "extra-field", "no-replay",- "half-executor", "executor-not-a-source-id", "image-replay", "unhashable-mode", "include-not-a-list",+ "absent", "unknown-tool", "assumed-without-declaration", "unsupported-with-include", "extra-field",+ "no-replay", "unknown-fact", "unhashable-fact", "include-not-a-list", "v1-executor", "no-image-models",+ "default-not-first", "unknown-image-param", "image-source-not-a-source-id",],)def test_a_hop_with_an_invalid_hosted_tool_entry_is_refused(hosted_tools) -> None:@@ -3633,8 +3627,8 @@ async def test_a_running_service_prunes_settled_jobs_after_its_runs(engine, sessCHANGELOG = "https://platform.openai.com/docs/changelog"-def _cited_search_turn(image: Optional[Path] = None) -> list:- """One response with a native web search, an answer that cites it, and optionally a generated image."""+def _cited_search_turn() -> list:+ """One response with a native web search and an answer that cites it."""blocks: list = [HostedToolBlock(id="srvtoolu_1",@@ -3644,16 +3638,6 @@ def _cited_search_turn(image: Optional[Path] = None) -> list:native=HostedNative(source_id="src_testsrc1", payload=({"type": "server_tool_use"},)),)]- if image is not None:- blocks.append(- HostedToolBlock(- id="ig_1",- tool="image_generation",- action=HostedAction(type="generate", prompt="a laptop at night", size="1536x1024"),- record=HostedRecord(status="completed", images=(HostedImage(path=str(image), mime="image/png"),)),- native=HostedNative(source_id="src_testsrc1", payload=({"type": "image_generation_call"},)),- )- )answer = "Domain filters shipped."blocks.append(TextBlock(text=answer, citations=(Citation(url=CHANGELOG, title="Changelog", start=0, end=len(answer)),)))message = AssistantMessage(@@ -3662,18 +3646,15 @@ def _cited_search_turn(image: Optional[Path] = None) -> list:return [[Done(message)]]-async def test_a_native_hosted_call_reaches_im_as_one_line_with_its_cited_answer_and_image(+async def test_a_native_hosted_call_reaches_im_as_one_line_with_its_cited_answer(engine, session, tmp_path, published) -> None:- """MH-HOSTED-UI-011: the line, the cited answer and the generated image, as an IM channel gets them."""- image = tmp_path / "image-3f2a.png"- image.write_bytes(b"\x89PNG\r\n\x1a\nimage")- harness = _Harness(engine, tmp_path, "telegram", _cited_search_turn(image))+ """MH-HOSTED-UI-011: the line and the cited answer, as an IM channel gets them."""+ harness = _Harness(engine, tmp_path, "telegram", _cited_search_turn())await harness.agent.handle_message(harness.request("what shipped?"))- search = "🔎 Web search “responses api \\*domain\\* filters” · native (test-provider) · 1 source"- image_line = "🖼 Image generation “a laptop at night” · native (test-provider) · 1 image · ≈ $0.01 for 2 calls"+ search = "🔎 Web search “responses api \\*domain\\* filters” · native (test-provider) · 1 source · ≈ $0.01"with engine.connect() as conn:lines = [row["content_text"]@@ -3685,14 +3666,12 @@ async def test_a_native_hosted_call_reaches_im_as_one_line_with_its_cited_answer]# One line per hosted call, escaped for the destination; the response's cost is# shown once, on its last call. The process log opens with the first of them.- assert lines == [search, image_line]+ assert lines == [search]sent = harness.controller.im_client.sentassert sent[0] == search[answer] = [item for item in sent if item.startswith("Domain filters shipped.")]- # The citation is a Markdown link where its span ends; the image is an upload, not a link.+ # The citation is a Markdown link where its span ends.assert f"]({CHANGELOG})" in answer- assert "file://" not in answer- assert harness.controller.im_client.uploads == [str(image.resolve())]async def test_a_native_hosted_call_reaches_the_workbench_as_a_card_and_cited_answer(@@ -3748,38 +3727,6 @@ async def test_a_proxied_hosted_result_shows_once_its_result_is_committed(engineassert harness.controller.im_client.sent[-1:] == ["🔎 X search “from:OpenAI” · via xAI proxy · 1 post · $0.11"]-async def test_generated_images_reach_the_user_when_no_final_reply_follows(engine, session, tmp_path, published) -> None:- """A paid image is delivered even when the run fails before a final reply could carry it."""- from core.agent_core.ai.provider import ProviderError-- image = tmp_path / "image-orphan.png"- image.write_bytes(b"\x89PNG\r\n\x1a\nimage")- generated = AssistantMessage(- (- HostedToolBlock(- id="ig_1",- tool="image_generation",- action=HostedAction(type="generate", prompt="a laptop at night"),- record=HostedRecord(status="completed", images=(HostedImage(path=str(image), mime="image/png"),)),- native=HostedNative(source_id="src_testsrc1", payload=({"type": "image_generation_call"},)),- ),- ToolCallBlock(id="call_1", name="echo", arguments={}),- ),- ORIGIN,- "tool_use",- hosted_summary=HostedSummary(),- )- harness = _Harness(- engine, tmp_path, "telegram",- [[Done(generated)], [ProviderError("invalid_request", "the served response broke its protocol", False)]],- )-- await harness.agent.handle_message(harness.request("draw it, then summarize"))-- assert harness.controller.im_client.uploads == [str(image.resolve())]- assert harness.controller.terminals[-1]["is_error"] is True--def test_an_image_is_attached_unless_the_reply_already_links_it(tmp_path) -> None:"""A prose mention of the path is not a delivered file; a relative path names no file to send."""from modules.agents.vibey.agent import _Run, VibeyAgent@@ -3827,65 +3774,3 @@ async def test_a_final_whose_cited_text_is_all_silent_stays_silent(engine, sessiassert not any(CHANGELOG in item for item in harness.controller.im_client.sent)assert not any(CHANGELOG in (row["content_text"] or "") for row in harness.rows("result") + harness.rows("assistant"))---async def test_an_image_only_final_is_a_reply_and_reaches_the_user(engine, session, tmp_path, published) -> None:- """MH-HOSTED-UI-012: a model asked for a picture may answer with the picture alone; that is not an empty reply."""- image = tmp_path / "image-only.png"- image.write_bytes(b"\x89PNG\r\n\x1a\nimage")- final = AssistantMessage(- (- HostedToolBlock(- id="ig_1",- tool="image_generation",- action=HostedAction(type="generate", prompt="a laptop at night"),- record=HostedRecord(status="completed", images=(HostedImage(path=str(image), mime="image/png"),)),- native=HostedNative(source_id="src_testsrc1", payload=({"type": "image_generation_call"},)),- ),- ),- ORIGIN,- "stop",- hosted_summary=HostedSummary(),- )- harness = _Harness(engine, tmp_path, "telegram", [[Done(final)]])-- await harness.agent.handle_message(harness.request("draw a laptop at night"))-- assert harness.controller.terminals[-1]["is_error"] is False- assert harness.controller.im_client.uploads == [str(image.resolve())]- # The reply is the image under its heading, never the empty-reply error.- [result] = harness.rows("result")- assert result["content_text"].startswith(i18n_t("info.generatedImagesFallback", "en"))- assert not any(i18n_t("vibeyAgent.error.emptyResponse", "en") in item for item in harness.controller.im_client.sent)---async def test_an_image_from_a_call_that_did_not_complete_is_not_delivered(engine, session, tmp_path, published) -> None:- """MH-HOSTED-UI-014: delivery follows the card and ``has_reply``: a call that did not complete shows no image."""- image = tmp_path / "partial.png"- image.write_bytes(b"\x89PNG\r\n\x1a\npartial")- final = AssistantMessage(- (- HostedToolBlock(- id="ig_2",- tool="image_generation",- action=HostedAction(type="generate", prompt="a laptop at night"),- record=HostedRecord(- status="incomplete",- error="the provider stopped the image",- images=(HostedImage(path=str(image), mime="image/png"),),- ),- native=HostedNative(source_id="src_testsrc1", payload=({"type": "image_generation_call"},)),- ),- TextBlock(text="The image could not be finished."),- ),- ORIGIN,- "stop",- hosted_summary=HostedSummary(),- )- harness = _Harness(engine, tmp_path, "telegram", [[Done(final)]])-- await harness.agent.handle_message(harness.request("draw a laptop at night"))-- assert harness.controller.terminals[-1]["is_error"] is False- assert harness.controller.im_client.uploads == []-diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 17708ea6a..c671c256c 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4953,7 +4953,9 @@"executor_no_image": "The proxy executor returned no image.","gateway_unreachable": "Couldn't reach the model gateway.","gateway_refused": "The model gateway refused the call.",- "gateway_no_result": "The model gateway returned no result."+ "gateway_no_result": "The model gateway returned no result.",+ "image_param_unsupported": "The chosen image model doesn't take one of the arguments.",+ "image_model_unavailable": "The chosen image model isn't available."},"mode": {"native": "Native · {{provider}}",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 378761eed..a3fc07d5d 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4953,7 +4953,9 @@"executor_no_image": "代理执行者没有返回图片。","gateway_unreachable": "无法连接模型网关。","gateway_refused": "模型网关拒绝了这次调用。",- "gateway_no_result": "模型网关没有返回结果。"+ "gateway_no_result": "模型网关没有返回结果。",+ "image_param_unsupported": "所选图片模型不支持其中一个参数。",+ "image_model_unavailable": "所选图片模型当前不可用。"},"mode": {"native": "原生 · {{provider}}",diff --git a/ui/src/lib/hostedActivity.fixture.json b/ui/src/lib/hostedActivity.fixture.jsonindex c0067b216..9ca4be885 100644--- a/ui/src/lib/hostedActivity.fixture.json+++ b/ui/src/lib/hostedActivity.fixture.json@@ -83,5 +83,22 @@"subject": "from:xai","sources": [],"images": []+ },+ "direct_image": {+ "version": 1,+ "call_id": "call_ig1",+ "tool": "image_generate",+ "mode": "direct",+ "status": "completed",+ "sources": [],+ "images": [{ "path": "/media/3f2a.png", "mime": "image/png", "width": 1536, "height": 1024, "bytes": 1993000 }],+ "subject": "A wide photo of an open laptop on a desk at night, empty dark space in the upper right",+ "provider": "openai",+ "source_id": "src_relaygpt1",+ "source_name": "relay-gpt",+ "model": "gpt-image-2",+ "size": "1536x1024",+ "quality": "medium",+ "revised_prompt": "A wide photo of an open laptop on a desk at night, empty dark space in the upper right"}}diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 594fb9152..705d717d9 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1140,8 +1140,7 @@"upstream_error": "The upstream service returned an error."},"hostedTools": {- "noExecutor": "No Source is verified to run {tool}. Verify it on a Source in Models.",- "executorUnavailable": "The Source bound to run {tool} for this turn is no longer available.",+ "noExecutor": "No Source can run {tool} right now. Add a Source from one of these providers to use it: {vendors}.","providerRefused": "The executor's provider refused the call ({detail}).","timedOut": "The executor call timed out.","unreachable": "The executor could not be reached.",@@ -1150,9 +1149,7 @@"didNotRun": "The executor did not run {tool}.","responseEnded": "The executor's response ended as {status}.","callFailed": "The provider's {tool} call failed.",- "callEnded": "The provider's {tool} call ended as {status}.",- "imageFormat": "The provider returned an unsupported image format: {format}.",- "imageUnreadable": "The provider returned an image that could not be used."+ "triedSources": "Tried: {sources}."},"events": {"sourceFallback": "source",@@ -1761,6 +1758,7 @@"unclassified": "The request to the model failed with an error {backend} could not classify. Try again, or choose another model.","outputLimit": "The model reached its output limit before producing a usable answer or tool call. Ask for smaller steps, or choose a model with a larger output limit.","internal": "{backend} stopped because of an internal error. Try again; if it happens again, the service log names the cause.",+ "historyUnreadable": "This session's history can't be loaded, so {backend} can't continue it. Start a new session with /new.","generic": "{backend}'s run failed."}},@@ -1782,17 +1780,20 @@"executor_no_image": "the proxy executor returned no image","gateway_unreachable": "couldn't reach the model gateway","gateway_refused": "the model gateway refused the call",- "gateway_no_result": "the model gateway returned no result"+ "gateway_no_result": "the model gateway returned no result",+ "image_param_unsupported": "the chosen image model doesn't take one of the arguments",+ "image_model_unavailable": "the chosen image model isn't available"},"tool": {"web_search": "Web search","x_search": "X search",- "image_generation": "Image generation"+ "image_generate": "Image generation"},"quoted": "“{subject}”","mode": {"native": "native ({provider})",- "proxy": "via {provider} proxy"+ "proxy": "via {provider} proxy",+ "direct": "direct ({provider})"},"count": {"sourceOne": "1 source",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex e1388a7a2..77cf45ee6 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1140,8 +1140,7 @@"upstream_error": "供应商返回错误。"},"hostedTools": {- "noExecutor": "没有已验证可运行 {tool} 的来源。请在「模型」中为某个来源验证它。",- "executorUnavailable": "本轮绑定运行 {tool} 的来源已不可用。",+ "noExecutor": "当前没有可运行 {tool} 的来源。添加以下任一供应商的来源即可使用:{vendors}。","providerRefused": "执行方的供应商拒绝了此次调用({detail})。","timedOut": "执行方调用超时。","unreachable": "无法连接执行方。",@@ -1150,9 +1149,7 @@"didNotRun": "执行方没有运行 {tool}。","responseEnded": "执行方的响应以 {status} 结束。","callFailed": "供应商的 {tool} 调用失败。",- "callEnded": "供应商的 {tool} 调用以 {status} 结束。",- "imageFormat": "供应商返回了不支持的图片格式:{format}。",- "imageUnreadable": "供应商返回的图片无法使用。"+ "triedSources": "已尝试:{sources}。"},"events": {"sourceFallback": "供应商",@@ -1761,6 +1758,7 @@"unclassified": "请求模型时出现了 {backend} 无法归类的错误。可以重试,或换一个模型。","outputLimit": "模型在生成可用的答案或工具调用前达到了输出上限。请让它分成更小的步骤,或换用输出上限更大的模型。","internal": "{backend} 因内部错误而停止。可以重试;如果再次出现,服务日志里记录了原因。",+ "historyUnreadable": "这个会话的历史记录无法加载,{backend} 无法继续它。请发送 /new 开始一个新会话。","generic": "{backend} 运行失败。"}},@@ -1782,17 +1780,20 @@"executor_no_image": "代理执行者没有返回图片","gateway_unreachable": "无法连接模型网关","gateway_refused": "模型网关拒绝了这次调用",- "gateway_no_result": "模型网关没有返回结果"+ "gateway_no_result": "模型网关没有返回结果",+ "image_param_unsupported": "所选图片模型不支持其中一个参数",+ "image_model_unavailable": "所选图片模型当前不可用"},"tool": {"web_search": "网页搜索","x_search": "X 搜索",- "image_generation": "图片生成"+ "image_generate": "图片生成"},"quoted": "“{subject}”","mode": {"native": "原生({provider})",- "proxy": "由 {provider} 代理"+ "proxy": "由 {provider} 代理",+ "direct": "{provider} 直连"},"count": {"sourceOne": "1 个来源",diff --git a/vibe/model_hub_runtime/client.py b/vibe/model_hub_runtime/client.pyindex 78052acb1..c826e20ab 100644--- a/vibe/model_hub_runtime/client.py+++ b/vibe/model_hub_runtime/client.py@@ -1719,6 +1719,7 @@ def _reduce_protocol_observation(stream_started=stream_started,usage=observation.usage,recovery_verified=observation.recovery_verified,+ hosted_tools=observation.hosted_tools,)if observation.outcome == "failed_terminal":projected_types = tuple(@@ -1891,6 +1892,7 @@ def _outcome(upstream_detail: str | None = None,os_errno: int | None = None,rejection: UpstreamRejection | None = None,+ hosted_tools: frozenset[str] = frozenset(),) -> RawCallOutcome:return RawCallOutcome(kind=kind,@@ -1907,6 +1909,7 @@ def _outcome(upstream_detail=upstream_detail,os_errno=os_errno,rejection=rejection,+ hosted_tools=hosted_tools,)