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): run proxied hosted tools on the turn's bound executor (#2560)
Call White0b93286826f9
diff --git a/core/handlers/model_hub/hosted_executor.py b/core/handlers/model_hub/hosted_executor.pynew file mode 100644index 000000000..22bbeab72--- /dev/null+++ b/core/handlers/model_hub/hosted_executor.py@@ -0,0 +1,587 @@+"""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.+"""++from __future__ import annotations++import base64+import binascii+import json+import re+from dataclasses import dataclass, field+from typing import Any, Callable, Final, Mapping++from config.v2_config import ModelHubSourceConfig+from core.agent_core.ai.sse import SSEParser+from vibe.backend_model_catalog import HostedToolSpec++from .events import bounded_diagnostic_detail+from .request import ModelHubRequest++EXECUTOR_TOOLS: Final = ("web_search", "x_search", "image_generation")+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+_SNIPPET_CHARS: Final = 500+_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 = {+ "web_search": (+ "You are a search executor. Search the web once for the user's query with the web_search tool. "+ "Then list what you found as a numbered list, most relevant first. For each result, write one or two "+ "sentences stating what the page says about the query, and cite the result in each sentence. "+ "Write nothing else."+ ),+ "x_search": (+ "You are a search executor. Search X once for the user's query with the x_search tool. "+ "Then list the posts you found as a numbered list, in the order the search returned them. For each post, "+ "write one or two sentences stating what the post says, and cite the post in each sentence. "+ "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):+ """The executor's response broke a bound; ``key`` names the failure to show."""++ def __init__(self, key: str):+ super().__init__(key)+ self.key = key+++class ExecutorCallRefused(ValueError):+ """A malformed proxy call: its machine code and HTTP status."""++ def __init__(self, code: str, status: int):+ super().__init__(code)+ self.code = code+ self.status = status+++@dataclass(frozen=True)+class ExecutorCall:+ tool: str+ arguments: Mapping[str, Any]+ executor: tuple[str, str] | None+++def parse_call(tool: str, payload: object) -> ExecutorCall:+ """Validate one ``POST /vibey/v1/hosted-tools/{tool}`` body 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"}:+ raise ExecutorCallRefused("invalid_request_error", 400)+ arguments, executor = payload["arguments"], payload["executor"]+ 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():+ raise ExecutorCallRefused("invalid_request_error", 400)+ limit, mode, size = arguments.get("limit"), arguments.get("mode"), arguments.get("size")+ 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"]))+++def executor_streams(source: ModelHubSourceConfig) -> bool:+ """A Responses executor streams, so an image's partials keep the idle bound 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+++def executor_request(call: ExecutorCall, source: ModelHubSourceConfig, model_id: str, spec: HostedToolSpec) -> 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)+ query = call.arguments["query"]+ if call.tool == "x_search":+ settings = [f"limit {call.arguments['limit']}" if "limit" in call.arguments else None,+ f"mode {call.arguments['mode']}" if "mode" in call.arguments else None]+ chosen = ", ".join(item for item in settings if item)+ if chosen:+ query = f"{query}\n\n(Search with {chosen}.)"+ instructions = _SEARCH_INSTRUCTIONS[call.tool]+ if source.protocol == "anthropic":+ payload = {+ "model": model_id,+ "max_tokens": _ANTHROPIC_OUTPUT_TOKENS,+ "system": instructions,+ "messages": [{"role": "user", "content": query}],+ "tools": [declaration],+ }+ else:+ payload = {+ "model": model_id,+ "instructions": instructions,+ "input": [{"role": "user", "content": query}],+ "tools": [declaration],+ "store": False,+ "max_output_tokens": _RESPONSES_OUTPUT_TOKENS,+ }+ if spec.include:+ payload["include"] = list(spec.include)+ return ModelHubRequest(payload, protocol=source.protocol)+++# Renders one of this module's failure keys (``modelHub.hostedTools.*``) in the user's language.+Say = Callable[..., str]+++def failed_record(error: str, sources: list[dict[str, Any]] | None = None) -> dict[str, Any]:+ return {"status": "failed", "error": bounded_diagnostic_detail(error) or error[:400], "sources": sources or []}+++@dataclass+class ResponsesReadout:+ """What a streamed Responses executor call reported: its output items and its final response.++ Error envelopes are not read here: the engine client's one extractor owns+ upstream error codes, and the call's outcome carries them.+ """++ items: list[dict[str, Any]] = field(default_factory=list)+ response: dict[str, Any] | None = None+++class ResponsesStreamReader:+ """Read a Responses event stream into its output items, without keeping image partials.++ 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.+ """++ 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)+ self._read = 0+ self._image_events = 0+ self._image_bytes = 0+ self._max_image_events = (partial_images or 0) + 1 + _IMAGE_EVENT_MARGIN+ self.readout = ResponsesReadout()++ def feed(self, chunk: bytes) -> None:+ self._read += len(chunk)+ if self._read > EXECUTOR_RESPONSE_MAX_BYTES:+ raise ExecutorResponseRefused("modelHub.hostedTools.tooLarge")+ try:+ events = self._parser.feed(chunk)+ except ValueError:+ # A line or event over its cap.+ raise ExecutorResponseRefused("modelHub.hostedTools.tooLarge") from None+ for event in events:+ self._event(event.data)++ def _event(self, data: str) -> None:+ if not data or data == "[DONE]":+ return+ try:+ payload = json.loads(data)+ except ValueError:+ return+ except RecursionError:+ raise ExecutorResponseRefused("modelHub.hostedTools.unreadable") from None+ if not isinstance(payload, dict):+ return+ kind = payload.get("type")+ item = 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.+ 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 ():+ if not isinstance(adopted, dict):+ continue+ ident = adopted.get("id")+ 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)."""++ record: dict[str, Any]+ generation: dict[str, str] | None = None+ images: tuple[dict[str, str], ...] = ()+++def responses_result(tool: str, readout: ResponsesReadout, say: Say, *, failure: str | None = None) -> ExecutorResult:+ """The canonical record of one streamed Responses executor call.++ ``failure`` is how the call failed, from its outcome, when it did; it takes+ precedence over anything the stream emitted, whose sources a failed record+ keeps. A call the provider marked failed is failed too.+ """++ 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 = [+ part+ for item in readout.items+ if item.get("type") == "message"+ for part in (item.get("content") if isinstance(item.get("content"), list) else ())+ if isinstance(part, dict) and part.get("type") == "output_text" and isinstance(part.get("text"), str)+ ]+ cited = _cited_sources(texts, x_posts_only=tool == "x_search")+ sources = _merge_sources(cited, [] if tool == "x_search" else _call_sources(calls))+ if failure is not None:+ return ExecutorResult(failed_record(failure, sources))+ if any(call.get("status") == "failed" for call in calls):+ return ExecutorResult(failed_record(say("modelHub.hostedTools.callFailed", tool=tool), sources))+ return ExecutorResult(_settled(response, sources, say))+++def _settled(response: Mapping[str, Any], sources: list[dict[str, Any]], say: Say) -> dict[str, Any]:+ """Success is an allow-list: only a response that says it completed completes the call.++ One that stopped early (output cap) is incomplete, and keeps what it found;+ any other or missing ending is a failure.+ """++ status = response.get("status")+ if status == "completed":+ return {"status": "completed", "sources": sources}+ ended = _ended_without("", response, say) if status in {"failed", "incomplete"} else say(+ "modelHub.hostedTools.responseEnded", status=str(status or "unknown"),+ )+ if status == "incomplete":+ return {"status": "incomplete", "error": failed_record(ended)["error"], "sources": sources}+ return failed_record(ended, sources)+++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 item.get("name") in _X_SEARCH_CALLS:+ return "x_search"+ return None+++def _ended_without(tool: str, response: Mapping[str, Any], say: Say) -> str:+ status = response.get("status")+ if status in {"failed", "incomplete"}:+ details = response.get("incomplete_details")+ reason = details.get("reason") if isinstance(details, dict) else None+ text = say("modelHub.hostedTools.responseEnded", status=status)+ return f"{text} ({reason})" if isinstance(reason, str) and reason else text+ return say("modelHub.hostedTools.didNotRun", tool=tool)+++def _call_sources(calls: list[Mapping[str, Any]]) -> list[dict[str, Any]]:+ sources = []+ for call in calls:+ action = call.get("action")+ for source in action.get("sources", ()) if isinstance(action, dict) else ():+ if isinstance(source, dict) and isinstance(source.get("url"), str) and source["url"]:+ sources.append({"url": source["url"]})+ return sources+++def _cited_sources(parts: list[Mapping[str, Any]], *, x_posts_only: bool) -> list[dict[str, Any]]:+ """Each cited URL once, in citation order, with the sentence its span sits in as the snippet."""++ sources: list[dict[str, Any]] = []+ for part in parts:+ text = part["text"]+ citations = [+ note+ for note in (part.get("annotations") if isinstance(part.get("annotations"), list) else ())+ if isinstance(note, dict) and note.get("type") == "url_citation"+ and isinstance(note.get("url"), str) and note["url"]+ ]+ spans = [+ (note["start_index"], note["end_index"], note["url"])+ for note in citations+ if _valid_span(note.get("start_index"), note.get("end_index"), len(text))+ ]+ for note in citations:+ url = note["url"]+ if x_posts_only and not _is_x_post(url):+ continue+ source: dict[str, Any] = {"url": url}+ title = note.get("title")+ # xAI numbers its citations ("1", "2"); a number is not a title.+ if isinstance(title, str) and title.strip() and not title.strip().isdigit():+ source["title"] = title.strip()+ start, end = note.get("start_index"), note.get("end_index")+ if _valid_span(start, end, len(text)):+ snippet = excerpt(text, start, end, url, spans)+ if snippet:+ source["snippet"] = snippet+ sources.append(source)+ return sources+++def _valid_span(start: Any, end: Any, length: int) -> bool:+ return (+ isinstance(start, int) and isinstance(end, int)+ and not isinstance(start, bool) and not isinstance(end, bool)+ and 0 <= start < end <= length+ )+++def _is_x_post(url: str) -> bool:+ match = re.match(r"https?://([^/]+)/", url)+ return match is not None and match.group(1).lower() in _X_POST_HOSTS+++def _merge_sources(*groups: list[dict[str, Any]]) -> list[dict[str, Any]]:+ merged: dict[str, dict[str, Any]] = {}+ for group in groups:+ for source in group:+ known = merged.setdefault(source["url"], {"url": source["url"]})+ for key, value in source.items():+ known.setdefault(key, value)+ return list(merged.values())+++_SENTENCE_END = re.compile(r"[.!?。!?](?=\s|$)")+_LIST_MARKER = re.compile(r"^\s*(?:[-*•]|\d+[.)])\s*")+++def excerpt(text: str, start: int, end: int, url: str, spans: list[tuple[int, int, str]]) -> str | None:+ """The answer text a citation span belongs to, without citation markers (``vibey-hosted-tools.md`` §12 item 24).++ The executor asks for one list item per result, each ending in its+ citation, so a span on a line that cites only its own URL takes that whole+ line. On a line that cites several sources, it takes its sentence: the one+ it sits in, or the one it follows (``It rose 5%. ([site](url))``). Every+ citation span, a leading list marker and bold markers are removed.+ """++ line_start = text.rfind("\n", 0, start) + 1+ line_end = text.find("\n", end)+ line_end = len(text) if line_end == -1 else line_end+ on_line = [span for span in spans if span[0] >= line_start and span[1] <= line_end]+ if all(span[2] == url for span in on_line):+ region_start, region_end = line_start, line_end+ else:+ region_start, region_end = _sentence(text, start, end, line_start, line_end)+ pieces, cursor = [], region_start+ for span_start, span_end, _url in sorted(spans):+ if span_end <= region_start or span_start >= region_end:+ continue+ pieces.append(text[cursor:max(cursor, span_start)])+ cursor = max(cursor, span_end)+ if cursor < region_end:+ pieces.append(text[cursor:region_end])+ snippet = " ".join(_LIST_MARKER.sub("", "".join(pieces), count=1).replace("**", "").split())+ snippet = re.sub(r"\s+([.,;:!?])", r"\1", snippet)+ if len(snippet) > _SNIPPET_CHARS:+ snippet = snippet[: _SNIPPET_CHARS - 1].rstrip() + "…"+ return snippet or None+++def _sentence(text: str, start: int, end: int, line_start: int, line_end: int) -> tuple[int, int]:+ """The sentence of a line a citation span belongs to: the one it sits in, or the one it follows."""++ before = text[line_start:start].rstrip()+ trailing = bool(before) and not _LIST_MARKER.fullmatch(before) and before[-1] in ".!?。!?"+ anchor = line_start + len(before) - 1 if trailing else start+ sentence_start = line_start+ for match in _SENTENCE_END.finditer(text, line_start, anchor):+ sentence_start = match.end()+ if trailing:+ return sentence_start, line_start + len(before)+ found = _SENTENCE_END.search(text, end, line_end)+ 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)]+ if done and done[-1]["result"] and failure is None and (readout.response or {}).get("status") != "completed":+ settled = _settled(readout.response or {}, [], say)+ return ExecutorResult({**settled, "sources": []})+ if failure is not None or not done or not done[-1]["result"]:+ 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))+ image = done[-1]+ 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."""++ try:+ message = json.loads(body)+ except (ValueError, RecursionError):+ return ExecutorResult(failed_record(say("modelHub.hostedTools.unreadable")))+ content = message.get("content") if isinstance(message, dict) else None+ blocks = [block for block in content if isinstance(block, dict)] if isinstance(content, list) else []+ if not any(block.get("type") == "server_tool_use" and block.get("name") == "web_search" for block in blocks):+ return ExecutorResult(failed_record(say("modelHub.hostedTools.didNotRun", tool="web_search")))+ results: list[dict[str, Any]] = []+ errors: list[str] = []+ for block in blocks:+ if block.get("type") != "web_search_tool_result":+ continue+ found = block.get("content")+ if isinstance(found, dict):+ errors.append(str(found.get("error_code") or "unknown"))+ continue+ for result in found if isinstance(found, list) else ():+ if isinstance(result, dict) and isinstance(result.get("url"), str) and result["url"]:+ source = {"url": result["url"]}+ for key in ("title", "page_age"):+ if isinstance(result.get(key), str) and result[key]:+ source[key] = result[key]+ results.append(source)+ cited = [+ {"url": citation["url"], "snippet": " ".join(citation["cited_text"].split())}+ for block in blocks+ if block.get("type") == "text"+ for citation in (block.get("citations") if isinstance(block.get("citations"), list) else ())+ if isinstance(citation, dict)+ and isinstance(citation.get("url"), str)+ and citation["url"]+ and isinstance(citation.get("cited_text"), str)+ and citation["cited_text"].strip()+ ]+ # Results keep the provider's order; a cited result gains the text it was cited for.+ sources = _merge_sources(results, cited)+ if errors:+ # Any search the provider marked failed fails the call, as on Responses;+ # the results that did arrive stay as partial sources.+ text = say("modelHub.hostedTools.callFailed", tool="web_search")+ return ExecutorResult(failed_record(f"{text} ({', '.join(errors)})", sources))+ # Success is an allow-list here too: an early stop is incomplete, anything else unknown fails.+ stop = message.get("stop_reason")+ if stop in {"end_turn", "stop_sequence"}:+ uses = {+ block.get("id") for block in blocks+ if block.get("type") == "server_tool_use" and block.get("name") == "web_search"+ }+ answered = {block.get("tool_use_id") for block in blocks if block.get("type") == "web_search_tool_result"}+ if not uses <= answered:+ # A finished response must carry every search's result block, even an empty one.+ return ExecutorResult(failed_record(say("modelHub.hostedTools.unreadable"), sources))+ return ExecutorResult({"status": "completed", "sources": sources})+ ended = say("modelHub.hostedTools.responseEnded", status=str(stop or "unknown"))+ if stop in {"max_tokens", "pause_turn"}:+ return ExecutorResult({"status": "incomplete", "error": failed_record(ended)["error"], "sources": sources})+ return ExecutorResult(failed_record(ended, sources))diff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.pyindex 546900bed..aa598cd2e 100644--- a/core/handlers/model_hub/hosted_tools.py+++ b/core/handlers/model_hub/hosted_tools.py@@ -134,22 +134,39 @@ def resolve_hosted_tools(engine: str,now: datetime,shape: int = HOSTED_PROBE_SHAPE,+ frozen: Mapping[str, Optional[tuple[str, str]]] | None = None,) -> dict[str, dict[str, Any]]:- """``HopResolution.hosted_tools`` for a Vibey hop served by ``source``/``model_id``."""+ """``HopResolution.hosted_tools`` for a Vibey hop served by ``source``/``model_id``.++ ``frozen`` is the turn's binding from its first resolution: which tools are+ on and the executor bound to each. A later resolution in the same turn+ keeps it, since settings apply from the next turn, and recomputes only what+ belongs to the hop (mode, declaration, include, replay).+ """context = _Context(evidence, spec_for, engine, shape, now)resolved: dict[str, dict[str, Any]] = {}for tool in MODEL_HUB_HOSTED_TOOLS:toggle = config.hosted_tools.get(tool)- if toggle is None or not toggle.enabled:+ if frozen is not None:+ if tool not in frozen:+ continue+ elif toggle is None or not toggle.enabled:continuespec = _runnable_spec(context, source, model_id, tool)entry: dict[str, Any] = {"mode": "native" if spec is not None else "proxy"}if spec is not None:entry["declaration"] = spec.declarationentry["include"] = list(spec.include)- chosen = (toggle.executor.source_id, toggle.executor.model_id) if toggle.executor is not None else None- entry["executor"] = _executor(context, config, tool, chosen)+ 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:+ chosen = (+ (toggle.executor.source_id, toggle.executor.model_id)+ if toggle is not None and toggle.executor is not None else None+ )+ entry["executor"] = _executor(context, config, tool, chosen)entry["replay"] = ("replay" in HOSTED_TOOL_ASPECTS[tool]and credential_eligible(source)diff --git a/core/handlers/model_hub/provenance.py b/core/handlers/model_hub/provenance.pyindex 06ac6e28b..5a11bab51 100644--- a/core/handlers/model_hub/provenance.py+++ b/core/handlers/model_hub/provenance.py@@ -722,6 +722,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@propertydef pending_attempt(self) -> Optional[AttemptIdentity]:@@ -764,6 +767,10 @@ class PreparedGatewayRoute:source_id: strgateway_request_model_id: strprimary_origin: HopOrigin | None = None+ # 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)@@ -1328,6 +1335,42 @@ class TurnCorrelationRegistry:)return token+ 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."""++ normalized = str(turn_id or "").strip()+ if not normalized:+ return None+ with self._lock:+ trace = self._traces.get(normalized)+ return trace.hosted_executors if trace is not None else None++ def hosted_executor_bindings(+ self, *, backend: str, token: str,+ ) -> tuple[str, dict[str, tuple[str, str, str] | None]] | None:+ """The live turn a credential belongs to and the proxy executors it bound, per tool; None without one.++ Only a credential whose route is the current route of an active turn+ that still admits work has bindings: a superseded or turnless+ credential, or a turn being stopped or finalized, cannot start a call.+ """++ with self._lock:+ credential = self._credential(backend, token)+ scope = self._scopes.get(credential.scope_key) if credential is not None else None+ if scope is None or credential.route is None:+ return None+ for turn_id in scope.active_turns:+ trace = self._traces.get(turn_id)+ if (+ scope.prepared_routes.get(turn_id) == credential.route+ and (trace is None or not trace.admission_closed)+ ):+ return turn_id, dict(credential.route.hosted_executors)+ return None+def gateway_primary_origin(self, *, backend: str, token: str) -> HopOrigin | None:"""Read the immutable launch origin, independent of live turn ownership."""@@ -1557,6 +1600,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_executorsreturn Truedef prepare_gateway_turn(@@ -1571,6 +1616,7 @@ 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], ...] = (),) -> str:"""Register a route and return its legacy credential or explicit handle."""@@ -1590,6 +1636,7 @@ class TurnCorrelationRegistry:source_id=source_id,gateway_request_model_id=request_model_id,primary_origin=primary_origin,+ hosted_executors=hosted_executors,)if scope.request_scoped:diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex c9c92e935..22e814dd0 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -56,12 +56,14 @@ from vibe.backend_model_catalog import (bundled_provider_overlay,hosted_tool_spec,)+from vibe.i18n import t as i18n_tfrom vibe.model_hub_runtime.api_key_vendors import (catalog_api_key_vendor_label,pinned_api_key_protocol,)from .adapter import (+ ENGINE_TRANSPORT_TIMEOUT_SECONDS,DiscoveredModel,EngineAdapter,EngineEnsureResult,@@ -113,9 +115,24 @@ from .evidence_rules import LearnedEvidencefrom .evidence_rules import learn as learn_from_rejectionfrom .evidence_rules import wire_effortfrom .hosted_admission import PIN_UNAVAILABLE_CODE, HostedContent, admits, hosted_content+from .hosted_executor import (+ EXECUTOR_RESPONSE_MAX_BYTES,+ ExecutorCallRefused,+ ExecutorResponseRefused,+ ResponsesStreamReader,+ anthropic_result,+ call_timeout,+ executor_request,+ executor_streams,+ failed_record,+ parse_call,+ responses_result,+)from .hosted_tools import (HOSTED_PROBE_SHAPE,HostedToolSettingRefused,+ credential_eligible,+ untranslated,engine_stamp,hosted_tools_status,parse_hosted_tool_setting,@@ -699,6 +716,34 @@ def _pin_unavailable() -> ModelHubError:return ModelHubError(PIN_UNAVAILABLE_CODE, status=409)+def _executor_failure(outcome: RawCallOutcome | None, say: Callable[..., str], *, refused: str | None) -> str | None:+ """How a proxied hosted call failed, in the user's language; None when it succeeded.++ ``refused`` names a bound the response itself broke (size, nesting).+ """++ if refused is not None:+ return say(refused)+ if outcome is None or outcome.kind is RawOutcomeKind.SUCCESS:+ return None+ if outcome.kind is RawOutcomeKind.TIMEOUT:+ return say("modelHub.hostedTools.timedOut")+ if outcome.kind is RawOutcomeKind.NETWORK_ERROR:+ return say("modelHub.hostedTools.unreachable")+ if outcome.kind is RawOutcomeKind.PROTOCOL_ERROR:+ return say("modelHub.hostedTools.unreadable")+ # The provider's own machine code and its redacted, bounded detail stay verbatim.+ detail = " ".join(+ part for part in (+ f"HTTP {outcome.http_status}" if outcome.http_status is not None else None,+ outcome.error_code,+ ) if part+ )+ if outcome.upstream_detail:+ detail = f"{detail}: {outcome.upstream_detail}" if detail else outcome.upstream_detail+ return say("modelHub.hostedTools.providerRefused", detail=detail or outcome.kind.value)++def _google_admission_skip_reason(frontend_protocol: str | None,source_protocol: str,@@ -5951,8 +5996,217 @@ class ModelHubService:basis, usd = pricedreturn HostedCost(basis=basis, usd=None if usd is None else round(usd, 6))- def hosted_tools_for_hop(self, config: ModelHubConfig, source: ModelHubSourceConfig, model_id: str) -> dict:- """``HopResolution.hosted_tools`` for a Vibey launch served by this Source and model."""+ @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.+ """++ 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++ async def run_hosted_tool(+ self,+ tool: str,+ payload: object,+ *,+ bindings: Mapping[str, tuple[str, str, str] | None] | 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.+ """++ def say(key: str, **params: str) -> str:+ return i18n_t(key, language, **params)++ try:+ # Validation is proportional to the request: off the controller loop.+ 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)+ 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+ )+ body = bytearray()+ handle = None+ cancelled_observed: ProtocolSSEState | None = None+ outcome: RawCallOutcome | None = None+ admitted = False+ refused: str | None = None++ async def invoke() -> None:+ nonlocal handle, outcome, admitted, refused, cancelled_observed+ while True:+ await self._prepare_engine_for_demand()+ await self._mutation_lock.acquire()+ held = True++ def release_owner() -> None:+ nonlocal held+ if held:+ held = False+ self._mutation_lock.release()++ def on_admitted() -> None:+ nonlocal admitted+ admitted = True+ release_owner()++ try:+ if self._hosted_executor(self.store.load(), source_id, model_id, tool, identity) is None:+ return+ if not self._engine_synced:+ continue+ try:+ handle = await self._engine_call(self.adapter.invoke(+ source.id, model_id, request, stream, "vibey", on_admitted=on_admitted,+ ))+ except InvokeCancelledError as cancelled_early:+ # Cancelled after admission, before a handle: the wire+ # facts already observed are still billed, so still metered.+ cancelled_observed = cancelled_early.observed+ raise+ break+ finally:+ release_owner()+ if handle.stream is not None:+ async for chunk in handle.stream:+ if refused is not None:+ continue+ try:+ 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")+ else:+ body.extend(chunk)+ except ExecutorResponseRefused as broken:+ # The response broke a bound: the call failed. Its usage is still metered.+ refused = broken.key+ outcome = await self._engine_call(handle.outcome())++ async def settle() -> None:+ try:+ if handle is not None:+ # Bounded like the gateway's own teardown: a stuck close must+ # not hold the call past its deadline or the gateway's shutdown.+ await asyncio.wait_for(handle.close_stream(), timeout=ENGINE_TRANSPORT_TIMEOUT_SECONDS)+ except (asyncio.TimeoutError, Exception):+ logger.warning("Model Hub hosted-tool executor stream did not close cleanly", exc_info=True)+ finally:+ if handle is not None or cancelled_observed is not None:+ await self._meter_call(+ source_id=source.id,+ model_id=model_id,+ outcome=outcome,+ observed=handle.observed if handle is not None else cancelled_observed,+ )++ try:+ await asyncio.wait_for(invoke(), timeout=call_timeout(tool))+ except asyncio.TimeoutError:+ if admitted:+ outcome = RawCallOutcome(+ kind=RawOutcomeKind.TIMEOUT, http_status=None, error_code=None, redacted_message=None,+ stream_started=False, model_id=model_id, source_id=source.id,+ )+ except ModelHubError as error:+ if not admitted:+ logger.info("Model Hub hosted-tool executor was not reached: %s", error.code)+ return unavailable+ outcome = 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,+ )+ finally:+ # A known outcome belongs to the call even if its caller leaves:+ # drain the bounded settlement before propagating cancellation.+ settlement = asyncio.create_task(settle())+ try:+ await asyncio.shield(settlement)+ except asyncio.CancelledError as cancelled:+ try:+ await await_owned_task(settlement)+ except BaseException:+ pass+ raise cancelled+ if not admitted:+ return unavailable+ execution = {+ "mode": "proxy",+ "executor_origin": {"provider": source.vendor, "api": source.protocol, "model": model_id},+ "executor_source_id": source.id,+ "executor_billing": source.billing,+ }+ failure = _executor_failure(outcome, say, refused=refused)+ if reader is not None:+ result = await asyncio.to_thread(responses_result, tool, reader.readout, say, failure=failure)+ elif failure is not None:+ result = None+ 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)+ 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++ def hosted_tools_for_hop(+ 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.++ ``frozen`` is the turn's tool set and executors from its first resolution.+ """return resolve_hosted_tools(config,@@ -5962,6 +6216,7 @@ class ModelHubService:spec_for=hosted_tool_spec,engine=self.engine_stamp,now=self.now(),+ frozen=frozen,)async def set_agent_mode(self, backend: str, mode: object) -> dict:diff --git a/core/handlers/model_hub/turn_gateway.py b/core/handlers/model_hub/turn_gateway.pyindex 72099b571..8c50313d5 100644--- a/core/handlers/model_hub/turn_gateway.py+++ b/core/handlers/model_hub/turn_gateway.py@@ -10,7 +10,7 @@ import socketimport tempfilefrom collections import dequefrom collections.abc import AsyncIterator, Callable, Mapping-from contextlib import AsyncExitStack, asynccontextmanager, contextmanager, suppress+from contextlib import AsyncExitStack, asynccontextmanager, contextmanager, nullcontext, suppressfrom dataclasses import dataclass, field, replacefrom datetime import datetime, timezonefrom typing import BinaryIO, Final, Optional@@ -97,6 +97,8 @@ _SSE_RESPONSE_HEADERS: Final = {# The ending a local error response carries, so a stream whose headers already# left can still deliver it as the protocol's terminal event._LOCAL_ENDING: Final = "model_hub_local_ending"+# A proxied hosted-tool call carries a few canonical arguments, never content.+_HOSTED_TOOL_REQUEST_MAX_BYTES: Final = 1024 * 1024_SUPPORTED_PATHS: Final = frozenset({"messages",@@ -331,8 +333,10 @@ class _DownstreamDisconnected(ConnectionError):@dataclass(eq=False)class _OwnedGatewayRequest:task: asyncio.Task- terminalizer: GatewayTurnTerminalizer- execution: _TurnExecution+ # None for a proxied hosted-tool call: a tool call, not the turn's model+ # hop, so it owns no provenance and no settlement.+ terminalizer: GatewayTurnTerminalizer | None+ execution: _TurnExecution | Nonedone: asyncio.Future[None]@@ -405,6 +409,19 @@ class ModelHubTurnGateway:terminalizer.on_attribution_released = Noneself._release_turn_request(turn_id, owned)+ @contextmanager+ def _own_turn_call(self, turn_id: str):+ """Own a proxied hosted-tool call by its turn, so stopping or finalizing the turn ends it too."""++ task = asyncio.current_task()+ assert task is not None+ owned = _OwnedGatewayRequest(task, None, None, asyncio.get_running_loop().create_future())+ self._turn_requests.setdefault(turn_id, set()).add(owned)+ try:+ yield+ finally:+ self._release_turn_request(turn_id, owned)+def _release_turn_request(self, turn_id: str, owned: _OwnedGatewayRequest) -> None:requests = self._turn_requests.get(turn_id)if requests is not None:@@ -471,6 +488,11 @@ class ModelHubTurnGateway:for owned in requests:if owned.done not in pending or owned.done.done():continue+ if owned.terminalizer is None or owned.execution is None:+ # A hosted-tool call has no turn facts to settle; it was cancelled above.+ logger.error("Abandoned a Model Hub hosted-tool call after the engine transport deadline")+ self._release_turn_request(turn_id, owned)+ continueself._abandon_owned_task(owned.task, phase="request", terminalizer=owned.terminalizer, execution=owned.execution)@@ -522,6 +544,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], ...] = (),) -> tuple[str, str]:if backend not in MODEL_HUB_BACKENDS:raise ModelHubError("mapping_target_unavailable", status=409)@@ -531,7 +554,8 @@ class ModelHubTurnGateway:# work; the registry still refuses any remaining overlap.finishing = [owned.done for owned in self._turn_requests.get(turn_id, ())- if owned.execution.settlement_recorded or owned.execution.terminal_fact_committed+ if owned.execution is not None+ and (owned.execution.settlement_recorded or owned.execution.terminal_fact_committed)]if finishing:await asyncio.wait(finishing, timeout=self._transport_timeout)@@ -554,6 +578,7 @@ class ModelHubTurnGateway:via_mapping=via_mapping,gateway_request_model_id=gateway_request_model_id,primary_origin=primary_origin,+ hosted_executors=hosted_executors,)except PreparedGatewayRouteConflict:raise ModelHubError("mapping_target_unavailable", status=409) from None@@ -602,6 +627,8 @@ class ModelHubTurnGateway:client_max_size += 1app = web.Application(client_max_size=client_max_size)app.router.add_get("/{backend}/v1/models", self._handle_models)+ # Before the catch-all model route, which would otherwise take it.+ app.router.add_post("/vibey/v1/hosted-tools/{tool}", self._handle_hosted_tool)app.router.add_post("/{backend}/v1/{endpoint:.*}", self._handle_request)app.router.add_post("/{backend}/v1beta/models/{google_action:.*}", self._handle_google_request)runner = web.AppRunner(@@ -644,6 +671,61 @@ class ModelHubTurnGateway:return candidatereturn None+ async 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).++ 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.+ """++ def refused(status: int, code: str) -> web.Response:+ return web.json_response(+ {"type": "error", "error": {"type": code, "code": code}},+ status=status,+ headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},+ )++ token = self._authorized_token(request, "vibey")+ if token is None:+ return refused(401, "authentication_error")+ # 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+ # past it, and on the loop, before the check could see it.+ if (+ request.headers.get("Content-Encoding", "identity").strip().lower() not in {"", "identity"}+ or request.content_length is None+ or request.content_length > _HOSTED_TOOL_REQUEST_MAX_BYTES+ ):+ return refused(400, "invalid_request_error")+ raw = await request.read()+ try:+ 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+ # call belongs to its turn, and stopping or finalizing the turn ends it.+ live = self.correlation.hosted_executor_bindings(backend="vibey", token=token)+ try:+ with self._own_turn_call(live[0]) if live is not None else nullcontext():+ 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,+ 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,+ content_type="application/json",+ headers={"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff"},+ )+async def _handle_models(self, request: web.Request) -> web.StreamResponse:backend = request.match_info["backend"]if self._authorized_token(request, backend) is None:diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.mdindex b2eacb5f3..69b02bd7a 100644--- a/docs/plans/agent-core-contracts/model-hub-consumer.md+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md@@ -98,6 +98,43 @@ consumer's requirements, and the Model Hub lane lands the change in both places.- The served-hop report carries `source`, the serving Source id (item 4, Model Hub contract v12), so that ahosted block's payload is tagged with the exact Source; two Sources can share an origin. The gateway and theparser 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 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. `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, 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 belongs+ to: the list item when that item cites only that source, else its sentence, with the citation markers+ removed. An Anthropic result keeps its `cited_text`. X search lists the cited posts.+ - 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 absent until the pricing module values it.## 3. Not requireddiff --git a/modules/agents/model_hub.py b/modules/agents/model_hub.pyindex d8db96d6d..f06555aa9 100644--- a/modules/agents/model_hub.py+++ b/modules/agents/model_hub.py@@ -23,6 +23,7 @@ from urllib.parse import urlsplitfrom config import pathsfrom config.atomic_io import write_atomicfrom config.v2_config import MODEL_HUB_BACKENDS, ModelHubConfig, ModelHubSourceConfig+from core.handlers.model_hub.capability_evidence import identity_digestfrom core.handlers.model_hub.classification import ResolutionDecisionfrom core.handlers.model_hub.events import (EventAgent,@@ -766,6 +767,23 @@ 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."""@@ -947,6 +965,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], ...] = (),) -> tuple[str, str]:if self.turn_gateway is not None:return await self.turn_gateway.endpoint(@@ -960,6 +979,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 {}),)await self.service._ensure_engine_synced()status = await self.service._engine_call(self.service.adapter.start())@@ -1316,6 +1336,24 @@ class ModelHubRuntimeRouter:if self.turn_gateway is not None and backend == "codex"else target_model)+ # 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.+ frozen = (+ self.turn_gateway.correlation.turn_hosted_executors(turn_id)+ if backend == "vibey" and self.turn_gateway is not None+ else None+ )+ 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"+ else {}+ )gateway_base_url, gateway_token = await self._gateway_credentials(backend,process_scope=str(process_scope or "").strip() or f"{backend}:untracked",@@ -1329,6 +1367,11 @@ class ModelHubRuntimeRouter:HopOrigin(source.vendor, source.protocol, target_model, source.id)if backend == "vibey" 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)+ ),)if self.turn_gateway is None:prefix = await self._source_prefix(source.id)@@ -1367,12 +1410,7 @@ class ModelHubRuntimeRouter:if backend_model is not None and backend_model.input_modalitieselse None),- 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)- if backend == "vibey"- else {}- ),+ hosted_tools=hosted_tools,)self._emit_transition(launch, config)return launchdiff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 3a4e35969..96c0fbc7a 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -92,6 +92,7 @@ capabilities:- tests/test_model_hub_request_body_budget.py- tests/test_model_hub_codex_image_tool.py- tests/test_model_hub_l3.py+ - tests/test_model_hub_hosted_executor.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 40d957ee8..572ca9cb2 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -36,6 +36,7 @@ capability:- tests/test_model_hub_request_body_budget.py- tests/test_model_hub_codex_image_tool.py- tests/test_model_hub_l3.py+ - tests/test_model_hub_hosted_executor.py- tests/test_model_hub_usage.py- tests/test_ui_server_fastapi.py- tests/test_model_hub_quota.py@@ -2165,6 +2166,25 @@ scenarios:kind: runtime_lifecyclelayer: 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+ status: covered+ kind: contract+ layer: contract+ test: tests/test_model_hub_hosted_executor.py::test_a_proxied_search_runs_one_native_request_and_answers_its_canonical_record+ related_tests:+ - tests/test_model_hub_hosted_executor.py::test_an_anthropic_executor_is_buffered_and_keeps_the_providers_results_and_cited_text+ - tests/test_model_hub_hosted_executor.py::test_a_proxied_image_returns_its_bytes_once_for_vibey_to_save+ - tests/test_model_hub_hosted_executor.py::test_an_excerpt_is_the_answer_text_its_citation_belongs_to+ - 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+ status: covered+ kind: boundary+ layer: contract+ test: tests/test_model_hub_hosted_executor.py::test_a_proxied_call_that_cannot_complete_is_a_failed_record+ related_tests:+ - 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_tokennext_priority:- MH-PROTOCOL-004- MH-RUNTIME-001diff --git a/tests/test_model_hub_hosted_executor.py b/tests/test_model_hub_hosted_executor.pynew file mode 100644index 000000000..58044f33a--- /dev/null+++ b/tests/test_model_hub_hosted_executor.py@@ -0,0 +1,761 @@+"""MH-HOSTED-GATEWAY-004/005: the gateway's proxy executor for hosted tools (``vibey-hosted-tools.md`` §3.4).++Each case posts a proxied call to the real gateway endpoint for a Vibey turn,+with a recording engine adapter playing the executor provider's own response+(shapes from the 2026-10-13 spike and a live check of these requests). The+answer must be the canonical record and execution, in the C-1 encoding of+``ToolResultMessage.hosted``.+"""++from __future__ import annotations++import asyncio+import base64+import gzip+import json+import threading+from dataclasses import replace++import aiohttp+import pytest++from config.v2_config import ModelHubHostedToolConfig, ModelHubRouteHopConfig+from core.agent_core.messages import message_from_dict+from core.handlers.model_hub import hosted_executor as executor_module+from core.handlers.model_hub import service as service_module+from core.handlers.model_hub.adapter import InvokeCancelledError, RawOutcomeKind+from core.handlers.model_hub.capability_evidence import EvidenceFeature, EvidenceRecord, identity_digest+from core.handlers.model_hub.hosted_executor import excerpt+from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE, engine_stamp+from core.handlers.model_hub.stream_wire import ProtocolSSEState, ProtocolUsageReport+from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway+from modules.agents.model_hub import ModelHubRuntimeRouter+from core.run_settlement import SETTLED_BY_STOPPED+from tests.test_model_hub_l3 import (+ NOW,+ BlockingLiveInvokeHandle,+ InvokeHandle,+ LiveInvokeHandle,+ _outcome,+ _source,+ _usage_of,+)+from tests.test_model_hub_vibey_consumer import _vibey_service++XAI = "src_xaikey0001"+OPENAI = "src_openai0001"+ANTHROPIC = "src_anthkey0001"+POST_1 = "https://x.com/OpenAI/status/2107909792945832070"+POST_2 = "https://x.com/OpenAI/status/2107895006350791071"+PAGE_A = "https://github.com/router-for-me/CLIProxyAPI/releases"+PAGE_B = "https://newreleases.io/project/github/router-for-me/CLIProxyAPI/release/v8.0.27"+++def _event(payload: dict) -> bytes:+ return f"event: {payload['type']}\ndata: {json.dumps(payload)}\n\n".encode()+++def _cited(lines: list[tuple[str, str, int]]) -> dict:+ """An output_text whose lines each end in an xAI-style ``[[n]](url)`` citation."""++ text, notes = "", []+ for number, (sentence, url, _) in enumerate(lines, start=1):+ marker = f"[[{number}]]({url})"+ text += ("\n" if text else "") + f"{number}. {sentence}"+ notes.append({"type": "url_citation", "url": url, "start_index": len(text),+ "end_index": len(text) + len(marker), "title": str(number)})+ text += marker+ return {"type": "output_text", "text": text, "annotations": notes}+++def _responses(*items: dict, usage: dict | None = None) -> tuple[bytes, ...]:+ frames = [_event({"type": "response.created", "response": {"id": "resp_1", "status": "in_progress"}})]+ frames += [_event({"type": "response.output_item.done", "item": item}) for item in items]+ frames.append(_event({"type": "response.completed", "response": {+ "id": "resp_1", "status": "completed", "output": list(items), "usage": usage or {"input_tokens": 9},+ }}))+ return tuple(frames)+++WEB_CALL = {"type": "web_search_call", "id": "ws_1", "status": "completed",+ "action": {"type": "search", "query": "CLIProxyAPI latest release",+ "sources": [{"type": "url", "url": PAGE_A}, {"type": "url", "url": PAGE_B}]}}+WEB_ANSWER = {"type": "message", "role": "assistant", "content": [_cited([+ ("v8.0.27 is the latest release. It adds a streaming keepalive.", PAGE_B, 0),+])]}+# A citation without a URL is not a source.+WEB_ANSWER["content"][0]["annotations"].append(+ {"type": "url_citation", "url": "", "start_index": 0, "end_index": 2, "title": "0"},+)+X_CALL = {"type": "custom_tool_call", "name": "x_keyword_search", "call_id": "xs_1", "id": "ctc_1",+ "input": json.dumps({"query": "from:OpenAI", "limit": 5, "mode": "Latest"})}+X_ANSWER = {"type": "message", "role": "assistant", "content": [_cited([+ ("OpenAI shared progress on ChatGPT for Teens. They will keep building.", POST_1, 0),+ ("A page about the release.", PAGE_A, 0),+ ("GPT-6 with Intelligent UI rolls out globally.", POST_2, 0),+])]}+++def _sources(*extra):+ xai = _source(XAI, "xAI key", vendor="xai", model_id="grok-4.6")+ openai = _source(OPENAI, "OpenAI key", vendor="openai", model_id="gpt-6-astra")+ anthropic = _source(ANTHROPIC, "Anthropic key", vendor="anthropic", protocol="anthropic",+ model_id="claude-haiku-4-5")+ return [xai, openai, anthropic, *extra]+++def _bind(service, tool, executor):+ """Turn the tool on with this executor verified, so the turn's resolution binds it."""++ config = service.store.config+ config.hosted_tools[tool] = ModelHubHostedToolConfig(+ enabled=True, executor=ModelHubRouteHopConfig(*executor) if executor else None,+ )+ if executor is None:+ return+ source = next(item for item in config.sources if item.id == executor[0])+ service.capability_evidence.write(+ EvidenceRecord(+ source_id=source.id, model_id=executor[1], feature=EvidenceFeature.hosted(tool, "call"),+ status="verified", basis="probe", observed_at=service.now(), engine=engine_stamp(),+ shape=HOSTED_PROBE_SHAPE, source_identity=identity_digest(source),+ ),+ live=config.sources,+ )+++async def _call(service, tool, body, *, token=None, after_launch=None, language="en"):+ gateway = ModelHubTurnGateway(service, language_provider=lambda: language)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:proxy", turn_id="turn-proxy")+ if after_launch is not None:+ after_launch(hop)+ async with aiohttp.ClientSession() as client:+ async with client.post(+ f'{hop["base_url"]}/hosted-tools/{tool}',+ headers={"Authorization": f'Bearer {token or hop["token"]}', **hop["request_headers"]},+ data=body if isinstance(body, bytes) else json.dumps(body),+ ) as response:+ return response.status, await response.json(content_type=None)+ finally:+ await gateway.close()+++def _hosted_result(tool, answer):+ """The answer is exactly what Vibey stores as ``ToolResultMessage.hosted``."""++ hosted = {key: answer[key] for key in ("record", "execution") if key in answer}+ record = hosted["record"]+ if tool == "image_generation":+ hosted["record"] = {**record, "images": []}+ message = message_from_dict({+ "role": "tool_result", "tool_call_id": "call_1", "tool_name": tool,+ "content": [{"type": "text", "text": "rendered by Vibey"}],+ "is_error": record["status"] != "completed", "hosted": hosted,+ })+ return message.hosted++[email protected](("tool", "executor", "arguments", "frames", "body_fields", "sources"), [+ (+ "web_search", (XAI, "grok-4.6"), {"query": "CLIProxyAPI latest release"},+ _responses({"type": "reasoning", "id": "rs_1", "summary": []}, WEB_CALL, WEB_ANSWER),+ {"tools": [{"type": "web_search"}]},+ [{"url": PAGE_B, "snippet": "v8.0.27 is the latest release. It adds a streaming keepalive."}, {"url": PAGE_A}],+ ),+ (+ "web_search", (OPENAI, "gpt-6-astra"), {"query": "CLIProxyAPI latest release"},+ _responses(WEB_CALL, WEB_ANSWER),+ {"tools": [{"type": "web_search"}], "include": ["web_search_call.action.sources"]},+ [{"url": PAGE_B, "snippet": "v8.0.27 is the latest release. It adds a streaming keepalive."}, {"url": PAGE_A}],+ ),+ (+ # X search has no per-call results: the record lists the cited posts, and only posts.+ "x_search", (XAI, "grok-4.6"), {"query": "from:OpenAI within_time:7d", "limit": 5, "mode": "Latest"},+ _responses(X_CALL, {"type": "reasoning", "id": "tco_1", "encrypted_content": "opaque"}, X_ANSWER),+ {"tools": [{"type": "x_search"}]},+ [{"url": POST_1, "snippet": "OpenAI shared progress on ChatGPT for Teens. They will keep building."},+ {"url": POST_2, "snippet": "GPT-6 with Intelligent UI rolls out globally."}],+ ),+])+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, excerpts, metering."""++ 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),+ ])+ _bind(service, tool, executor)+ status, answer = await _call(service, tool, {+ "arguments": arguments, "executor": {"source_id": executor[0], "model_id": executor[1]},+ })+ assert status == 200, answer+ assert service.adapter.invocations == [(executor[0], executor[1], "vibey")]+ sent = service.adapter.requests[0]+ assert sent.protocol == "openai_responses"+ assert "reasoning" not in sent and "tool_choice" not in sent+ assert {key: sent[key] for key in body_fields} == body_fields+ assert set(sent) - set(body_fields) == {"model", "instructions", "input", "store", "max_output_tokens"}+ query = sent["input"][0]["content"]+ assert query.startswith(arguments["query"])+ if tool == "x_search":+ assert "limit 5" in query and "mode Latest" in query+ assert answer == {+ "record": {"status": "completed", "sources": sources},+ "execution": {+ "mode": "proxy",+ "executor_origin": {"provider": "xai" if executor[0] == XAI else "openai",+ "api": "openai_responses", "model": executor[1]},+ "executor_source_id": executor[0],+ "executor_billing": "metered",+ },+ }+ assert _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])+++async def test_an_anthropic_executor_is_buffered_and_keeps_the_providers_results_and_cited_text(tmp_path):+ """MH-HOSTED-GATEWAY-004: Anthropic results keep their order and ages; a cited one gains its cited_text."""++ body = json.dumps({+ "type": "message", "role": "assistant", "stop_reason": "end_turn",+ "content": [+ {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "q"}},+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": [+ {"type": "web_search_result", "url": PAGE_A, "title": "Releases", "page_age": "0 days ago",+ "encrypted_content": "opaque"},+ {"type": "web_search_result", "url": PAGE_B, "title": "v8.0.27", "encrypted_content": "opaque"},+ ]},+ {"type": "text", "text": "The latest is v8.0.27.", "citations": [+ {"type": "web_search_result_location", "url": PAGE_B, "title": "v8.0.27",+ "cited_text": "v8.0.27 released 2026-10-12", "encrypted_index": "opaque"},+ ]},+ ],+ "usage": {"input_tokens": 2671, "output_tokens": 242, "server_tool_use": {"web_search_requests": 1}},+ }).encode()+ service = _vibey_service(tmp_path, _sources(), handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=ANTHROPIC), (body,)),+ ])+ _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 == 200+ sent = service.adapter.requests[0]+ assert sent.protocol == "anthropic"+ assert set(sent) == {"model", "max_tokens", "system", "messages", "tools"}+ assert sent["tools"] == [{"type": "web_search_20250305", "name": "web_search", "max_uses": 5}]+ assert answer["record"] == {"status": "completed", "sources": [+ {"url": PAGE_A, "title": "Releases", "page_age": "0 days ago"},+ {"url": PAGE_B, "title": "v8.0.27", "snippet": "v8.0.27 released 2026-10-12"},+ ]}+ assert answer["execution"]["executor_origin"] == {+ "provider": "anthropic", "api": "anthropic", "model": "claude-haiku-4-5",+ }+++async def test_a_proxied_image_returns_its_bytes_once_for_vibey_to_save(tmp_path, monkeypatch):+ """MH-HOSTED-GATEWAY-004: the image comes back once, with the resolved prompt, size and quality.++ The final image is over Vibey's default 8 MiB SSE line, so the image stream's+ 32 MiB line cap is what accepts it. Partials are previews and are dropped;+ the duplicate in ``response.completed`` is not returned.+ """++ image = b"\x89PNG\r\n\x1a\n" + bytes(range(256)) * (7 * 1024 * 4)+ encoded = base64.b64encode(image).decode()+ assert len(encoded) > 9 * 1024 * 1024+ call = {"type": "image_generation_call", "id": "ig_1", "status": "completed", "output_format": "png",+ "quality": "low", "size": "1536x1024", "revised_prompt": "A small red paper boat", "result": encoded}+ partial = _event({"type": "response.image_generation_call.partial_image", "partial_image_index": 0,+ "partial_image_b64": base64.b64encode(b"preview").decode()})+ frames = _responses(call)+ service = _vibey_service(tmp_path, _sources(), handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), (frames[0], partial, *frames[1:])),+ ])+ _bind(service, "image_generation", (OPENAI, "gpt-6-astra"))+ encoding_threads = []+ dumps = json.dumps++ def recorded(value, *args, **kwargs):+ if isinstance(value, dict) and "images" in value:+ encoding_threads.append(threading.current_thread())+ return dumps(value, *args, **kwargs)++ monkeypatch.setattr(json, "dumps", recorded)+ status, answer = await _call(service, "image_generation", {+ "arguments": {"prompt": "a small red paper boat", "size": "1024x1024"},+ "executor": {"source_id": OPENAI, "model_id": "gpt-6-astra"},+ })+ assert status == 200+ # Megabytes of base64 are never encoded on the controller loop.+ assert encoding_threads and threading.main_thread() not in encoding_threads+ sent = service.adapter.requests[0]+ assert sent["tools"] == [{"type": "image_generation", "partial_images": 2, "size": "1024x1024"}]+ assert sent["tool_choice"] == {"type": "image_generation"}+ assert "reasoning" not in sent+ assert answer["record"] == {"status": "completed", "sources": []}+ assert answer["generation"] == {"revised_prompt": "A small red paper boat", "size": "1536x1024", "quality": "low"}+ assert [(item["mime"], base64.b64decode(item["data"])) for item in answer["images"]] == [("image/png", image)]+ _hosted_result("image_generation", answer)+++FAILED_WITH_PARTIAL = {**WEB_CALL, "status": "failed"}++[email protected](("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),+ ("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),+ ("tool_never_ran", (XAI, "grok-4.6"),+ [LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=XAI), _responses(WEB_ANSWER))],+ "did not run web_search", [], True),+ # A failed call keeps the partial results it returned, but stays failed.+ ("call_failed_with_partial_results", (XAI, "grok-4.6"),+ [LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=XAI), _responses(FAILED_WITH_PARTIAL))],+ "web_search call failed", [{"url": PAGE_A}, {"url": PAGE_B}], True),+ # The call's outcome failed after its items arrived: the outcome wins.+ ("stream_failed_after_items", (XAI, "grok-4.6"),+ [LiveInvokeHandle(_outcome(RawOutcomeKind.HTTP_ERROR, status=200, code="server_error", source_id=XAI,+ stream_started=True), _responses(WEB_CALL, WEB_ANSWER)[:-1])],+ "refused the call (HTTP 200 server_error)",+ [{"url": PAGE_B, "snippet": "v8.0.27 is the latest release. It adds a streaming keepalive."}, {"url": PAGE_A}],+ True),+])+async def test_a_proxied_call_that_cannot_complete_is_a_failed_record(+ tmp_path, case, bound, handles, error, sources, executed,+):+ """MH-HOSTED-GATEWAY-005: never a silent or partial success; an execution only when an executor ran."""++ service = _vibey_service(tmp_path, _sources(), handles=handles)+ _bind(service, "web_search", bound)++ def remove_executor(_hop):+ if case == "source_removed":+ service.store.config.sources = [item for item in service.store.config.sources if item.id != XAI]+ if case == "source_identity_changed":+ service.store.config.sources = [+ replace(item, base_url="https://relay.example/v1") if item.id == XAI else item+ for item in service.store.config.sources+ ]++ executor = {"source_id": bound[0], "model_id": bound[1]} if bound else None+ status, answer = await _call(+ service, "web_search", {"arguments": {"query": "q"}, "executor": executor}, after_launch=remove_executor,+ )+ assert status == 200+ assert answer["record"]["status"] == "failed"+ assert error in answer["record"]["error"]+ assert answer["record"]["sources"] == sources+ assert ("execution" in answer) is executed+ assert len(service.adapter.invocations) == int(executed)+ assert _hosted_result("web_search", answer).record.status == "failed"+++async 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."""++ 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",+ )+ assert status == 200+ assert answer["record"]["error"] == "没有已验证可运行 x_search 的来源。请在「模型」中为某个来源验证它。"++[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 == []++[email protected](("case", "call", "error"), [+ ("unreadable_base64", {"result": "not base64!"}, "could not be used"),+ ("one_of_two_calls_failed", None, "image_generation call failed"),+ ("too_many_images", None, "larger than allowed"),+ ("partials_over_the_byte_budget", None, "larger than allowed"),+])+async def test_an_image_the_executor_cannot_vouch_for_is_a_failed_record(tmp_path, monkeypatch, case, call, error):+ """MH-HOSTED-GATEWAY-005: an undecodable image, more image events, or more image bytes than allowed fail.++ Partials count toward the decoded-byte budget though they are never returned.+ """++ if case == "partials_over_the_byte_budget":+ monkeypatch.setattr(executor_module, "_IMAGES_TOTAL_MAX_BYTES", 64)++ final = {"type": "image_generation_call", "id": "ig_1", "status": "completed", "output_format": "png",+ "result": base64.b64encode(b"\x89PNG fixture").decode(), **(call or {})}+ partial = _event({"type": "response.image_generation_call.partial_image", "partial_image_index": 0,+ "partial_image_b64": base64.b64encode(b"preview" * 8).decode()})+ frames = _responses(final) if case != "one_of_two_calls_failed" else _responses(+ {"type": "image_generation_call", "id": "ig_0", "status": "failed"}, final,+ )+ # Two partials were asked for; six are more than the final and the margin allow.+ stream = (frames[0], *([partial] * (6 if case == "too_many_images" else 1)), *frames[1:])+ service = _vibey_service(tmp_path, _sources(), handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), stream),+ ])+ _bind(service, "image_generation", (OPENAI, "gpt-6-astra"))+ status, answer = await _call(service, "image_generation", {+ "arguments": {"prompt": "a boat"}, "executor": {"source_id": OPENAI, "model_id": "gpt-6-astra"},+ })+ assert status == 200+ assert answer["record"]["status"] == "failed" and error in answer["record"]["error"]+ assert "images" not in answer and "execution" in answer+++async def test_one_failed_anthropic_search_fails_the_call_and_keeps_the_results_that_arrived(tmp_path):+ """MH-HOSTED-GATEWAY-005: failure precedence is the same on both protocols."""++ body = json.dumps({+ "type": "message", "role": "assistant", "stop_reason": "end_turn",+ "content": [+ {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "q"}},+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": [+ {"type": "web_search_result", "url": PAGE_A, "title": "Releases", "encrypted_content": "opaque"},+ ]},+ {"type": "server_tool_use", "id": "srvtoolu_2", "name": "web_search", "input": {"query": "q2"}},+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_2",+ "content": {"type": "web_search_tool_result_error", "error_code": "too_many_requests"}},+ ],+ }).encode()+ service = _vibey_service(tmp_path, _sources(), handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=ANTHROPIC), (body,)),+ ])+ _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"},+ })+ assert status == 200+ assert answer["record"]["status"] == "failed" and "too_many_requests" in answer["record"]["error"]+ assert answer["record"]["sources"] == [{"url": PAGE_A, "title": "Releases"}]+++async def test_a_turn_owns_its_proxied_calls(tmp_path):+ """MH-HOSTED-GATEWAY-005: no call starts once the turn stops admitting work, and stopping it ends one in flight."""++ blocked = BlockingLiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=XAI))+ service = _vibey_service(tmp_path, _sources(), handles=[blocked])+ _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"}})+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:own", turn_id="turn-own")+ async with aiohttp.ClientSession() as client:+ pending = asyncio.create_task(client.post(+ f'{hop["base_url"]}/hosted-tools/web_search',+ headers={"Authorization": f'Bearer {hop["token"]}'}, data=body,+ ))+ await asyncio.wait_for(blocked.started.wait(), timeout=5)+ finished = []+ completion = gateway.finalize_turn("turn-own", settled_by=SETTLED_BY_STOPPED, finish=lambda: finished.append(1))+ assert completion is not None+ 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"]}'}, data=body,+ ) as response:+ assert response.status == 409+ assert (await response.json())["error"]["code"] == "executor_not_bound"+ finally:+ await gateway.close()+ assert len(service.adapter.invocations) == 1+++INCOMPLETE = (+ _event({"type": "response.output_item.done", "item": WEB_CALL}),+ _event({"type": "response.incomplete", "response": {+ "id": "resp_1", "status": "incomplete", "incomplete_details": {"reason": "max_output_tokens"},+ }}),+)+DEEP = "[" * 100_000 + "]" * 100_000++[email protected](("case", "executor", "chunks", "status", "error", "sources"), [+ # Success is an allow-list: a response that stopped early is incomplete and keeps what it found.+ ("responses_incomplete", (XAI, "grok-4.6"), INCOMPLETE, "incomplete", "max_output_tokens",+ [{"url": PAGE_A}, {"url": PAGE_B}]),+ ("anthropic_max_tokens", (ANTHROPIC, "claude-haiku-4-5"), (json.dumps({+ "type": "message", "stop_reason": "max_tokens", "content": [+ {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "q"}},+ {"type": "web_search_tool_result", "tool_use_id": "srvtoolu_1", "content": [+ {"type": "web_search_result", "url": PAGE_A, "title": "Releases"}]},+ ]}).encode(),), "incomplete", "max_tokens", [{"url": PAGE_A, "title": "Releases"}]),+ # A finished Anthropic response must carry each search's result block.+ ("anthropic_search_without_its_result", (ANTHROPIC, "claude-haiku-4-5"), (json.dumps({+ "type": "message", "stop_reason": "end_turn", "content": [+ {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {"query": "q"}},+ {"type": "text", "text": "Nothing found."},+ ]}).encode(),), "failed", "could not be read", []),+ ("responses_without_an_ending", (XAI, "grok-4.6"), INCOMPLETE[:1], "failed", "unknown",+ [{"url": PAGE_A}, {"url": PAGE_B}]),+ # Nesting past the decoder's recursion limit is an unreadable response, not a 500.+ ("responses_nested_too_deep", (XAI, "grok-4.6"), (f"data: {DEEP}\n\n".encode(),), "failed",+ "could not be read", []),+ ("anthropic_nested_too_deep", (ANTHROPIC, "claude-haiku-4-5"), (DEEP.encode(),), "failed",+ "could not be read", []),+])+async def test_only_a_response_that_completed_completes_the_call(tmp_path, case, executor, chunks, status, error, sources):+ """MH-HOSTED-GATEWAY-005: completion is an allow-list on both protocols; anything unreadable fails cleanly."""++ service = _vibey_service(tmp_path, _sources(), handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=executor[0]), chunks),+ ])+ _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]},+ })+ assert answer_status == 200+ assert answer["record"]["status"] == status+ assert error in answer["record"]["error"]+ assert answer["record"]["sources"] == sources+ assert _hosted_result("web_search", answer).record.status == status+++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."""++ 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"))+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ 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.+ _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"]}'},+ 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+ completion = router.settle_turn("turn-freeze", settled_by=SETTLED_BY_STOPPED, ts=NOW.isoformat())+ if completion is not None:+ await completion+ nxt = 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"]+ finally:+ await gateway.close()+++async def test_a_proxy_call_body_is_bounded(tmp_path):+ """MH-HOSTED-GATEWAY-005: a call carries a few arguments; an oversized body is refused before it is parsed."""++ 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},+ ).encode())+ assert (status, answer["error"]["code"]) == (400, "invalid_request_error")+ assert service.adapter.invocations == []+++async def test_items_only_the_terminal_response_carries_are_kept(tmp_path):+ """MH-HOSTED-GATEWAY-004: a relay that streams some items but not others still yields the terminal list's."""++ reasoning = {"type": "reasoning", "id": "rs_1", "summary": []}+ image = {"type": "image_generation_call", "id": "ig_1", "status": "completed", "output_format": "png",+ "result": base64.b64encode(b"\x89PNG fixture").decode(), "revised_prompt": "a boat"}+ frames = (+ _event({"type": "response.output_item.done", "item": reasoning}),+ _event({"type": "response.completed", "response": {+ "id": "resp_1", "status": "completed", "output": [reasoning, image]}}),+ )+ service = _vibey_service(tmp_path, _sources(), handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=OPENAI), frames),+ ])+ _bind(service, "image_generation", (OPENAI, "gpt-6-astra"))+ status, answer = await _call(service, "image_generation", {+ "arguments": {"prompt": "a boat"}, "executor": {"source_id": OPENAI, "model_id": "gpt-6-astra"},+ })+ assert status == 200+ assert answer["record"]["status"] == "completed"+ assert [base64.b64decode(item["data"]) for item in answer["images"]] == [b"\x89PNG fixture"]+++async def test_a_call_cancelled_before_its_handle_is_still_metered(tmp_path):+ """MH-HOSTED-GATEWAY-005: wire facts observed after admission are billed, so they reach the usage ledger."""++ service = _vibey_service(tmp_path, _sources())+ _bind(service, "web_search", (XAI, "grok-4.6"))+ observed = ProtocolSSEState("openai_responses")+ observed.observe(_responses(usage={"input_tokens": 1200, "output_tokens": 3})[-1])++ async def cancelled_after_admission(source_id, model_id, request, stream, origin, *, on_admitted=None):+ on_admitted()+ raise InvokeCancelledError(observed)++ service.adapter.invoke = cancelled_after_admission+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:cancel", turn_id="turn-cancel")+ with pytest.raises(asyncio.CancelledError):+ await 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"])[1],+ )+ finally:+ await gateway.close()+ assert _usage_of(service, XAI)+++async def test_an_encoded_proxy_call_body_is_refused(tmp_path):+ """MH-HOSTED-GATEWAY-005: the 1 MiB bound is on what is parsed, so an encoded body is refused before inflating."""++ service = _vibey_service(tmp_path, _sources())+ _bind(service, "web_search", None)+ gateway = ModelHubTurnGateway(service)+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)+ try:+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:gzip", turn_id="turn-gzip")+ 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()),+ ) as response:+ assert response.status == 400+ finally:+ await gateway.close()+ assert service.adapter.invocations == []+++async 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."""++ monkeypatch.setattr(service_module, "EXECUTOR_RESPONSE_MAX_BYTES", 64)+ service = _vibey_service(tmp_path, _sources(), handles=[+ LiveInvokeHandle(_outcome(RawOutcomeKind.SUCCESS, source_id=ANTHROPIC), (b"{" + b" " * 128 + b"}",)),+ ])+ _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"},+ })+ assert status == 200+ assert answer["record"]["status"] == "failed" and "larger than allowed" in answer["record"]["error"]+ assert "execution" in answer++[email protected](("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", b"not json", 400, "invalid_request_error"),+ ("code_interpreter", {"arguments": {}, "executor": None}, 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."""++ service = _vibey_service(tmp_path, _sources())+ answer_status, answer = await _call(service, tool, body)+ assert (answer_status, answer) == (status, {"type": "error", "error": {"type": code, "code": code}})+ assert service.adapter.invocations == []+++async def test_a_proxy_call_needs_the_turns_gateway_token(tmp_path):+ """MH-HOSTED-GATEWAY-005: the endpoint authenticates like every Vibey request."""++ service = _vibey_service(tmp_path, _sources())+ status, answer = await _call(+ service, "web_search", {"arguments": {"query": "q"}, "executor": None}, token="not-the-turn-token",+ )+ assert (status, answer["error"]["code"]) == (401, "authentication_error")+++RECORDED_XAI_LIST = (+ "1. OpenAI is sharing progress on ChatGPT for Teens. They will keep building these tools."+ "[[1]](https://x.com/a)\n2. [[2]](https://x.com/b)GPT-6 rolls out today. It applies to Chat."+)+RECORDED_XAI_PROSE = (+ "The latest release is **v8.0.27**. It was released on October 12, 2026 (at 16:37 UTC)."+ "[[1]](https://a.example)[[2]](https://b.example)"+)+RECORDED_OPENAI_PROSE = (+ "Prices rose 5% in May. ([reuters.com](https://r.example)) Rates held steady ([ft.com](https://f.example)), "+ "analysts said."+)+++def _spans(text: str, markers: list[tuple[str, str]]) -> list[tuple[int, int, str]]:+ return [(text.index(marker), text.index(marker) + len(marker), url) for marker, url in markers]++[email protected](("text", "markers", "snippets"), [+ (RECORDED_XAI_LIST, [("[[1]](https://x.com/a)", "https://x.com/a"), ("[[2]](https://x.com/b)", "https://x.com/b")],+ ["OpenAI is sharing progress on ChatGPT for Teens. They will keep building these tools.",+ "GPT-6 rolls out today. It applies to Chat."]),+ (RECORDED_XAI_PROSE, [("[[1]](https://a.example)", "https://a.example"),+ ("[[2]](https://b.example)", "https://b.example")],+ ["It was released on October 12, 2026 (at 16:37 UTC).", "It was released on October 12, 2026 (at 16:37 UTC)."]),+ (RECORDED_OPENAI_PROSE, [("([reuters.com](https://r.example))", "https://r.example"),+ ("([ft.com](https://f.example))", "https://f.example")],+ ["Prices rose 5% in May.", "Rates held steady, analysts said."]),+])+def test_an_excerpt_is_the_answer_text_its_citation_belongs_to(text, markers, snippets):+ """MH-HOSTED-GATEWAY-004: a list item citing one source, else its sentence; markers removed (§12 item 24)."""++ spans = _spans(text, markers)+ assert [excerpt(text, start, end, url, spans) for start, end, url in spans] == snippetsdiff --git a/tests/test_model_hub_injection.py b/tests/test_model_hub_injection.pyindex 4ceaf21f3..ca08637d7 100644--- a/tests/test_model_hub_injection.py+++ b/tests/test_model_hub_injection.py@@ -321,7 +321,9 @@ def test_route_alias_keeps_its_own_planning_metadata(tmp_path, monkeypatch, backservice=service_for(tmp_path, store, ModelHubScenarioAdapter()),turn_gateway=SimpleNamespace(endpoint=AsyncMock(return_value=("http://127.0.0.1:19000", "fixture-token")),- correlation=SimpleNamespace(gateway_request_metadata=lambda **_kwargs: {}),+ correlation=SimpleNamespace(+ gateway_request_metadata=lambda **_kwargs: {}, turn_hosted_executors=lambda _turn_id: None,+ ),),overlay_path=tmp_path / "overlay.json",)diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.pyindex a425767d2..9b8b1ae0c 100644--- a/tests/test_model_hub_structure_guards.py+++ b/tests/test_model_hub_structure_guards.py@@ -710,9 +710,10 @@ 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"]- # Explicit Source tests 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)["probe_source"])+ # Explicit Source tests 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.+ consumers = (invoke, _functions(service_tree)["probe_source"], _functions(service_tree)["run_hosted_tool"])assert len(meter_calls) == len(consumers)assert all(sum(call in set(ast.walk(consumer)) for call in meter_calls) == 1@@ -1244,9 +1245,11 @@ def test_machine_error_field_access_has_one_extractor() -> None:if (history := functions.get(name)) is not Nonefor node in ast.walk(history)}- if path.name == "hosted_admission.py":- # Hosted admission discriminates request tools and history items,- # never an error envelope; its type reads are exempt too.+ if path.name in {"hosted_admission.py", "hosted_executor.py"}:+ # Hosted admission discriminates request tools and history items, and+ # the proxy executor response items and stream events, never an error+ # envelope (executor error codes come from the call's outcome). Their+ # type reads are exempt too.history_nodes = set(ast.walk(tree))for node in ast.walk(tree):if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex ecd3cfd11..a80b0a457 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1103,6 +1103,21 @@"upstream_unauthorized": "The upstream service rejected authorization after refresh.","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.",+ "providerRefused": "The executor's provider refused the call ({detail}).",+ "timedOut": "The executor call timed out.",+ "unreachable": "The executor could not be reached.",+ "unreadable": "The executor's response could not be read.",+ "tooLarge": "The executor's response was larger than allowed.",+ "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."+ },"events": {"sourceFallback": "source","switch": "{from_source}: {reason} -> switched to {to_source}",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex d6f32a5ad..86b86b032 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1103,6 +1103,21 @@"upstream_unauthorized": "刷新后供应商仍拒绝授权。","upstream_error": "供应商返回错误。"},+ "hostedTools": {+ "noExecutor": "没有已验证可运行 {tool} 的来源。请在「模型」中为某个来源验证它。",+ "executorUnavailable": "本轮绑定运行 {tool} 的来源已不可用。",+ "providerRefused": "执行方的供应商拒绝了此次调用({detail})。",+ "timedOut": "执行方调用超时。",+ "unreachable": "无法连接执行方。",+ "unreadable": "无法读取执行方的响应。",+ "tooLarge": "执行方的响应超出了大小上限。",+ "didNotRun": "执行方没有运行 {tool}。",+ "responseEnded": "执行方的响应以 {status} 结束。",+ "callFailed": "供应商的 {tool} 调用失败。",+ "callEnded": "供应商的 {tool} 调用以 {status} 结束。",+ "imageFormat": "供应商返回了不支持的图片格式:{format}。",+ "imageUnreadable": "供应商返回的图片无法使用。"+ },"events": {"sourceFallback": "供应商","switch": "{from_source}:{reason},已自动切换到 {to_source}",