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(vibey): declare native hosted tools from the hop and pin those requests (#2552)
Call White95980ab3c83e
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.pyindex 74fb852b2..a8c3025a6 100644--- a/core/agent_core/agent/loop.py+++ b/core/agent_core/agent/loop.py@@ -67,7 +67,7 @@ from core.agent_core.agent.lifecycle import RunAborted as _Aborted, RunScopefrom core.agent_core.agent.models import ModelRouter, ModelSelection, RetryPolicyfrom core.agent_core.agent.outcome import OutcomeOwnerfrom core.agent_core.agent.state import HookStateError, state_representation-from core.agent_core.ai._common import endpoint_origin+from core.agent_core.ai._common import endpoint_origin, native_hosted_toolsfrom core.agent_core.ai.provider import (Done,ModelEndpoint,@@ -1503,7 +1503,7 @@ class Agent:last_tokens = unit_tokens(last) if last is not None else 0parts = [ContextPart("system", text_tokens(request.system)),- ContextPart("tools", request_tokens("", request.tools, ())),+ ContextPart("tools", request_tokens("", request.tools, (), native_hosted_tools(request))),ContextPart("history", max(0, messages_tokens(request.messages) - last_tokens)),]if last is not None:@@ -1878,7 +1878,9 @@ class Agent:candidate = ContextEntry(self.session_id, seq, "compaction", "uncommitted-compaction", payload=payload)after = context_view([*self._rows, candidate])# What the next request would carry; it is budgeted for real when it is built.- payload["tokens_after_estimate"] = request_tokens(request.system, request.tools, self._carried(after))+ payload["tokens_after_estimate"] = request_tokens(+ request.system, request.tools, self._carried(after), native_hosted_tools(request)+ )return payload, afterasync def _hosted(self, view: ContextView, cut: int) -> tuple[tuple[str, ...], Optional[str]]:diff --git a/core/agent_core/ai/_common.py b/core/agent_core/ai/_common.pyindex 924d77ccd..521473ea3 100644--- a/core/agent_core/ai/_common.py+++ b/core/agent_core/ai/_common.py@@ -4,12 +4,13 @@ from __future__ import annotationsimport asyncioimport base64+import copyimport ioimport inspectimport jsonimport refrom collections.abc import AsyncIterator, Awaitable, Callable, Hashable, Mapping-from dataclasses import dataclass, replace+from dataclasses import dataclass, field, replacefrom typing import Any, TypeVarfrom urllib.parse import parse_qsl, unquote, unquote_to_bytes, urlencode, urlsplit, urlunsplit@@ -40,8 +41,10 @@ from core.agent_core.ai.provider import (THINKING_DROP_RETRY_KINDS,BlockEnd,Done,+ HostedToolRoute,MediaLoader,ModelEndpoint,+ ModelRequest,ProviderError,TextDelta,ThinkingDelta,@@ -1412,6 +1415,71 @@ def request_credential_values(endpoint: ModelEndpoint) -> tuple[str, ...]:return tuple(dict.fromkeys(values))+#: Pins a request that carries Source-specific hosted content to one Source (``vibey-hosted-tools.md`` §3.5): the+#: gateway serves it from that Source only, and answers ``pin_unavailable`` where it would otherwise fail over.+PIN_SOURCE_HEADER = "x-avibe-pin-source"+++@dataclass(frozen=True)+class WireRequest:+ """One model request exactly as its adapter sends it. A hosted-tool probe sends this request (§3.2)."""++ url: str+ headers: dict[str, str] = field(repr=False)+ body: dict[str, Any]+++def native_hosted_tools(request: ModelRequest) -> dict[str, HostedToolRoute]:+ """The request's tools that this hop runs natively: a declared tool whose hosted route here is ``native``."""++ routes = request.endpoint.hosted_tools+ return {+ spec.name: routes[spec.name]+ for spec in request.tools+ if spec.name in routes and routes[spec.name].mode == "native"+ }+++def native_declaration(route: HostedToolRoute) -> dict[str, Any]:+ """A native route's wire declaration, verbatim (§4.1), as a fresh object the payload may own."""++ return copy.deepcopy(dict(route.declaration or {}))+++def hosted_pin(request: ModelRequest) -> dict[str, str]:+ """The pin header of a request that sends a native hosted declaration, else nothing."""++ if not native_hosted_tools(request):+ return {}+ if not request.endpoint.source_id:+ raise ValueError("a native hosted declaration needs the Source the request is pinned to")+ return {PIN_SOURCE_HEADER: request.endpoint.source_id}+++def forced_tool(request: ModelRequest) -> tuple[str, HostedToolRoute | None] | None:+ """``request.tool_choice`` with its native hosted route (None when it is sent as a function); None when nothing+ is forced. The forced tool must be one the request declares."""++ name = request.tool_choice+ if name is None:+ return None+ if not any(tool.name == name for tool in request.tools):+ raise ValueError(f"tool_choice names {name!r}, which the request does not declare")+ return name, native_hosted_tools(request).get(name)+++def required_only_tool(tools: list[Any]) -> str:+ """OpenAI's forced choice of a hosted tool: ``required`` over a request that declares only that tool.++ The Responses and Chat named choices name a function, and their hosted-tool choice types have no+ ``web_search`` or ``x_search``, so ``required`` is the one form that forces any hosted tool.+ """++ if len(tools) != 1:+ raise ValueError("forcing a hosted tool on this protocol needs it to be the request's only tool")+ return "required"++async def iter_sse_events(response: httpx.Response,cancel: CancelToken,diff --git a/core/agent_core/ai/anthropic.py b/core/agent_core/ai/anthropic.pyindex b2c1bb394..cbc667af8 100644--- a/core/agent_core/ai/anthropic.py+++ b/core/agent_core/ai/anthropic.py@@ -17,13 +17,17 @@ import httpxfrom core.agent_core.ai._common import (ServedHopResolver,+ WireRequest,auth_headers,content_parts,drive_sse_stream,dispatch_wire_event,endpoint_origin,+ hosted_pin,join_endpoint_url,json_object,+ native_declaration,+ native_hosted_tools,prepare_messages,request_credential_values,StreamAssembler,@@ -242,11 +246,7 @@ class AnthropicAdapter(ProviderAdapter):stop_reason: str | None = Nonemessage_started = Falsemessage_stopped = False- prefix_ttl = _prefix_ttl(request)try:- headers = auth_headers(request.endpoint, provider="anthropic", gateway=self._gateway)- headers.update({"anthropic-version": ANTHROPIC_VERSION, "content-type": "application/json"})- url = join_endpoint_url(request.endpoint.base_url, "/messages")async def translate(events: AsyncIterator[Any]) -> AsyncIterator[Any]:nonlocal message_started, message_stopped, stop_reasonasync for event in events:@@ -740,15 +740,15 @@ class AnthropicAdapter(ProviderAdapter):if terminal is not None:yield terminalwhile True:- payload = build_messages_payload(- request, transformed_messages, loaded_images=loaded_images, prefix_ttl=prefix_ttl- )+ # The lifetime ``wire_request`` gives the prefix: the default once this route has rejected the field.+ prefix_ttl = _prefix_ttl(request)+ wire = wire_request(request, transformed_messages, gateway=self._gateway, loaded_images=loaded_images)driver = drive_sse_stream(self._client,method="POST",- url=url,- json_body=payload,- headers=headers,+ url=wire.url,+ json_body=wire.body,+ headers=wire.headers,cancel=cancel,assembler=assembler,endpoint=request.endpoint,@@ -770,7 +770,6 @@ class AnthropicAdapter(ProviderAdapter):# The endpoint refused the request before answering, so the consumer saw nothing: send it once more# with the default lifetime, which this route keeps from now on._remember_ttl_rejection(request.endpoint)- prefix_ttl = Noneassembler = new_assembler()except Exception as exc:terminal = assembler.terminal(assembler.exception(exc))@@ -811,20 +810,24 @@ def build_messages_payload("system": system,"messages": payload_messages,}- if request.tools:- payload["tools"] = [- {- "name": tool.name,- "description": tool.description,- "input_schema": dict(tool.input_schema),- **(- {"cache_control": _cache_control(prefix_ttl)}- if request.cache == "default" and index == len(request.tools) - 1- else {}- ),- }- for index, tool in enumerate(request.tools)- ]+ # A hosted tool this hop runs natively is sent as the provider's declaration in its spec's place (§4.1). The tools+ # breakpoint goes on the last function tool, never on a server tool.+ native = native_hosted_tools(request)+ tools: list[dict[str, Any]] = [+ native_declaration(native[tool.name])+ if tool.name in native+ else {"name": tool.name, "description": tool.description, "input_schema": dict(tool.input_schema)}+ for tool in request.tools+ ]+ functions = [index for index, tool in enumerate(request.tools) if tool.name not in native]+ if request.cache == "default" and functions:+ tools[functions[-1]]["cache_control"] = _cache_control(prefix_ttl)+ if tools:+ payload["tools"] = tools+ if request.tool_choice is not None:+ # Current Claude models refuse a forced `tool` or `any` choice, as does extended thinking, so a request that+ # forces one would test the refusal instead of the tool. A hosted-tool probe asks in its message instead.+ raise ValueError("an Anthropic request never forces a tool")effort = (request.reasoning_effort or "").lower()if effort in {"none", "off", "disabled"}:payload["thinking"] = {"type": "disabled"}@@ -846,6 +849,22 @@ def build_messages_payload(return payload+def wire_request(+ request: ModelRequest,+ messages: tuple[Any, ...],+ *,+ gateway: bool,+ loaded_images: Mapping[str, tuple[str, str]] | None = None,+) -> WireRequest:+ """The Messages request for already prepared ``messages``, as the adapter sends it."""++ payload = build_messages_payload(request, messages, loaded_images=loaded_images, prefix_ttl=_prefix_ttl(request))+ headers = auth_headers(request.endpoint, provider="anthropic", gateway=gateway)+ headers.update({"anthropic-version": ANTHROPIC_VERSION, "content-type": "application/json"})+ headers.update(hosted_pin(request))+ return WireRequest(join_endpoint_url(request.endpoint.base_url, "/messages"), headers, payload)++def _message_to_anthropic(message: Any,supports_images: bool,diff --git a/core/agent_core/ai/openai_chat.py b/core/agent_core/ai/openai_chat.pyindex bba1c4dc1..79013fc45 100644--- a/core/agent_core/ai/openai_chat.py+++ b/core/agent_core/ai/openai_chat.py@@ -15,14 +15,20 @@ import httpxfrom core.agent_core.ai._common import (ServedHopResolver,+ WireRequest,auth_headers,content_parts,drive_sse_stream,endpoint_origin,+ forced_tool,+ hosted_pin,join_endpoint_url,json_object,+ native_declaration,+ native_hosted_tools,prepare_messages,request_credential_values,+ required_only_tool,StreamAssembler,validate_wire_shape,WireField,@@ -209,10 +215,7 @@ class OpenAIChatAdapter(ProviderAdapter):refusal_seen = Falseprotocol_terminal = Falsetry:- payload = build_chat_payload(request, transformed_messages, loaded_images=loaded_images)- headers = auth_headers(request.endpoint, provider="openai", gateway=self._gateway)- headers.setdefault("content-type", "application/json")- url = join_endpoint_url(request.endpoint.base_url, "/chat/completions")+ wire = wire_request(request, transformed_messages, gateway=self._gateway, loaded_images=loaded_images)async def translate(events: AsyncIterator[Any]) -> AsyncIterator[Any]:nonlocal finish_reason, native_finish_reason, refusal_seen, protocol_terminalasync for event in events:@@ -636,9 +639,9 @@ class OpenAIChatAdapter(ProviderAdapter):driver = drive_sse_stream(self._client,method="POST",- url=url,- json_body=payload,- headers=headers,+ url=wire.url,+ json_body=wire.body,+ headers=wire.headers,cancel=cancel,assembler=assembler,endpoint=request.endpoint,@@ -689,23 +692,50 @@ def build_chat_payload(payload["max_completion_tokens"] = request.max_tokenselse:payload["max_tokens"] = request.max_tokens- if request.tools:- payload["tools"] = [- {- "type": "function",- "function": {- "name": tool.name,- "description": tool.description,- "parameters": dict(tool.input_schema),- },- }- for tool in request.tools- ]+ # A hosted tool this hop runs natively is sent as the provider's declaration in its spec's place (§4.1).+ native = native_hosted_tools(request)+ tools = [+ native_declaration(native[tool.name])+ if tool.name in native+ else {+ "type": "function",+ "function": {+ "name": tool.name,+ "description": tool.description,+ "parameters": dict(tool.input_schema),+ },+ }+ for tool in request.tools+ ]+ if tools:+ payload["tools"] = tools+ forced = forced_tool(request)+ if forced is not None:+ name, route = forced+ payload["tool_choice"] = (+ required_only_tool(tools) if route is not None else {"type": "function", "function": {"name": name}}+ )if request.reasoning_effort and request.reasoning_effort.lower() not in {"off", "disabled"}:payload["reasoning_effort"] = _openai_effort(request.reasoning_effort)return payload+def wire_request(+ request: ModelRequest,+ messages: tuple[Any, ...],+ *,+ gateway: bool,+ loaded_images: Mapping[str, tuple[str, str]] | None = None,+) -> WireRequest:+ """The Chat Completions request for already prepared ``messages``, as the adapter sends it."""++ payload = build_chat_payload(request, messages, loaded_images=loaded_images)+ headers = auth_headers(request.endpoint, provider="openai", gateway=gateway)+ headers.setdefault("content-type", "application/json")+ headers.update(hosted_pin(request))+ return WireRequest(join_endpoint_url(request.endpoint.base_url, "/chat/completions"), headers, payload)++def _message_to_chat(message: Any,supports_images: bool,diff --git a/core/agent_core/ai/openai_responses.py b/core/agent_core/ai/openai_responses.pyindex 473d722da..afe7b2d19 100644--- a/core/agent_core/ai/openai_responses.py+++ b/core/agent_core/ai/openai_responses.py@@ -17,15 +17,21 @@ import httpxfrom core.agent_core.ai._common import (ServedHopResolver,+ WireRequest,auth_headers,content_parts,drive_sse_stream,dispatch_wire_event,endpoint_origin,+ forced_tool,+ hosted_pin,join_endpoint_url,json_object,+ native_declaration,+ native_hosted_tools,prepare_messages,request_credential_values,+ required_only_tool,StreamAssembler,validate_wire_shape,WireField,@@ -325,10 +331,7 @@ class OpenAIResponsesAdapter(ProviderAdapter):refusal = Falsetry:- payload = build_responses_payload(request, transformed_messages, loaded_images=loaded_images)- headers = auth_headers(request.endpoint, provider="openai", gateway=self._gateway)- headers.setdefault("content-type", "application/json")- url = join_endpoint_url(request.endpoint.base_url, "/responses")+ wire = wire_request(request, transformed_messages, gateway=self._gateway, loaded_images=loaded_images)async def translate(events: AsyncIterator[Any]) -> AsyncIterator[Any]:nonlocal status, incomplete_reason, refusalasync for event in events:@@ -1272,9 +1275,9 @@ class OpenAIResponsesAdapter(ProviderAdapter):driver = drive_sse_stream(self._client,method="POST",- url=url,- json_body=payload,- headers=headers,+ url=wire.url,+ json_body=wire.body,+ headers=wire.headers,cancel=cancel,assembler=assembler,endpoint=request.endpoint,@@ -1311,23 +1314,54 @@ def build_responses_payload("stream": True,"store": False,}- if request.tools:- payload["tools"] = [- {- "type": "function",- "name": tool.name,- "description": tool.description,- "parameters": dict(tool.input_schema),- }- for tool in request.tools- ]+ # A hosted tool this hop runs natively is sent as the provider's declaration in its spec's place (§4.1).+ native = native_hosted_tools(request)+ tools = [+ native_declaration(native[tool.name])+ if tool.name in native+ else {+ "type": "function",+ "name": tool.name,+ "description": tool.description,+ "parameters": dict(tool.input_schema),+ }+ for tool in request.tools+ ]+ if tools:+ payload["tools"] = tools+ include: list[str] = []if request.reasoning_effort and request.reasoning_effort.lower() not in {"off", "disabled"}:payload["reasoning"] = {"effort": _openai_effort(request.reasoning_effort), "summary": "auto"}if request.reasoning_effort.lower() != "none":- payload["include"] = ["reasoning.encrypted_content"]+ include.append("reasoning.encrypted_content")+ # A native hosted tool's own include values, e.g. OpenAI's web_search_call.action.sources (§4.1).+ for route in native.values():+ include.extend(route.include)+ if include:+ payload["include"] = list(dict.fromkeys(include))+ forced = forced_tool(request)+ if forced is not None:+ name, route = forced+ payload["tool_choice"] = required_only_tool(tools) if route is not None else {"type": "function", "name": name}return payload+def wire_request(+ request: ModelRequest,+ messages: tuple[Any, ...],+ *,+ gateway: bool,+ loaded_images: Mapping[str, tuple[str, str]] | None = None,+) -> WireRequest:+ """The Responses request for already prepared ``messages``, as the adapter sends it."""++ payload = build_responses_payload(request, messages, loaded_images=loaded_images)+ headers = auth_headers(request.endpoint, provider="openai", gateway=gateway)+ headers.setdefault("content-type", "application/json")+ headers.update(hosted_pin(request))+ return WireRequest(join_endpoint_url(request.endpoint.base_url, "/responses"), headers, payload)++def _message_to_response(message: Any,supports_images: bool,diff --git a/core/agent_core/ai/provider.py b/core/agent_core/ai/provider.pyindex bd823437d..80c053aef 100644--- a/core/agent_core/ai/provider.py+++ b/core/agent_core/ai/provider.py@@ -8,7 +8,7 @@ given, converts canonical messages with the cross-provider rules, and yieldsfrom __future__ import annotationsfrom dataclasses import dataclass, field-from typing import AsyncIterator, Literal, Mapping, Optional, Protocol, Union+from typing import Any, AsyncIterator, Literal, Mapping, Optional, Protocol, Unionfrom core.agent_core.cancel import CancelTokenfrom core.agent_core.messages import AssistantMessage, Message, ProtocolName@@ -38,6 +38,51 @@ THINKING_DROP_RETRY_KINDS: frozenset[str] = frozenset()+@dataclass(frozen=True)+class HostedExecutor:+ """The proxy executor Model Hub bound for the turn: one verified (Source, model)."""++ source_id: str+ model_id: str++ def __post_init__(self) -> None:+ if not all(isinstance(value, str) and value for value in (self.source_id, self.model_id)):+ raise ValueError("a hosted executor names a Source and a model")+++@dataclass(frozen=True)+class HostedToolRoute:+ """One enabled hosted tool on a hop (C-6 ``HopResolution.hosted_tools``, ``vibey-hosted-tools.md`` §3.5).++ ``mode`` is Model Hub's decision for this hop; the agent never decides nativity itself. A ``native`` route has+ the wire ``declaration`` and the Responses ``include`` values it needs; a ``proxy`` route has neither.+ ``executor`` (None when no executor is verified) and ``replay`` hold in either mode.+ """++ mode: Literal["native", "proxy"]+ executor: Optional[HostedExecutor]+ replay: bool+ declaration: Optional[Mapping[str, Any]] = None+ include: tuple[str, ...] = ()++ def __post_init__(self) -> None:+ if self.mode not in ("native", "proxy"):+ raise ValueError(f"unknown hosted tool mode: {self.mode!r}")+ if self.executor is not None and not isinstance(self.executor, HostedExecutor):+ raise ValueError("a hosted executor must be a HostedExecutor or None")+ if not isinstance(self.replay, bool):+ raise ValueError("hosted replay must be a boolean")+ if self.mode == "proxy":+ if self.declaration is not None or self.include:+ raise ValueError("a proxy hosted tool has no native declaration or include")+ return+ declaration = self.declaration+ if not isinstance(declaration, Mapping) or not isinstance(declaration.get("type"), str) or not declaration["type"]:+ raise ValueError("a native hosted tool needs a declaration with a type")+ if not isinstance(self.include, tuple) or not all(isinstance(item, str) and item for item in self.include):+ raise ValueError("hosted include must be a tuple of strings")++@dataclass(frozen=True)class ModelEndpoint:protocol: ProtocolName@@ -46,6 +91,10 @@ class ModelEndpoint:token: str = field(repr=False)request_headers: Mapping[str, str] = field(default_factory=dict)provider: str = ""+ #: The hop's Source (``HopResolution.source_id``): the pin of a request that carries native hosted content.+ source_id: Optional[str] = None+ #: Each enabled hosted tool's route on this hop, in Model Hub's order; empty when none is enabled.+ hosted_tools: Mapping[str, HostedToolRoute] = field(default_factory=dict)@dataclass(frozen=True)@@ -80,6 +129,10 @@ class ModelRequest:cache: Literal["default", "none"] = "default"supports_images: bool = False"""Resolved by the loop from ``ModelCapabilities``; an unknown capability counts as False."""+ tool_choice: Optional[str] = None+ """The one tool the response must call, by name (a function's, or a hosted tool's catalog name); ``None``+ leaves the choice to the model. Only a hosted-tool probe sets it (``vibey-hosted-tools.md`` §3.2), and never on+ Anthropic, whose current models refuse a forced choice."""@dataclass(frozen=True)diff --git a/core/agent_core/ai/registry.py b/core/agent_core/ai/registry.pyindex 77008a91b..5c5322e46 100644--- a/core/agent_core/ai/registry.py+++ b/core/agent_core/ai/registry.py@@ -2,12 +2,15 @@from __future__ import annotations-from typing import Any+from typing import Any, Callable, Optional+from core.agent_core.ai import anthropic, openai_chat, openai_responses+from core.agent_core.ai._common import WireRequest, endpoint_origin, prepare_messagesfrom core.agent_core.ai.anthropic import AnthropicAdapterfrom core.agent_core.ai.openai_chat import OpenAIChatAdapterfrom core.agent_core.ai.openai_responses import OpenAIResponsesAdapter-from core.agent_core.ai.provider import ProviderAdapter+from core.agent_core.ai.provider import MediaLoader, ModelRequest, ProviderAdapter, ProviderError+from core.agent_core.cancel import CancelTokenfrom core.agent_core.messages import ProtocolNameADAPTERS: dict[ProtocolName, type[ProviderAdapter]] = {@@ -16,6 +19,12 @@ ADAPTERS: dict[ProtocolName, type[ProviderAdapter]] = {"openai_responses": OpenAIResponsesAdapter,}+_WIRE_REQUESTS: dict[ProtocolName, Callable[..., WireRequest]] = {+ "anthropic": anthropic.wire_request,+ "openai_chat": openai_chat.wire_request,+ "openai_responses": openai_responses.wire_request,+}+def adapter_class(protocol: ProtocolName) -> type[ProviderAdapter]:try:@@ -31,3 +40,33 @@ def create_adapter(protocol: ProtocolName, **kwargs: Any) -> ProviderAdapter:get_adapter = create_adapter+++async def build_wire_request(+ request: ModelRequest,+ *,+ gateway: bool,+ media_loader: Optional[MediaLoader] = None,+ cancel: Optional[CancelToken] = None,+) -> WireRequest:+ """The request ``request.endpoint.protocol``'s adapter would send for ``request``, without sending it.++ The adapter's ``stream`` sends exactly this, so a hosted-tool probe built here is the production request+ (``vibey-hosted-tools.md`` §3.2). Raises ``ValueError`` when the request cannot be built.+ """++ protocol = request.endpoint.protocol+ if protocol not in _WIRE_REQUESTS:+ raise ValueError(f"unsupported provider protocol: {protocol}")+ prepared = await prepare_messages(+ request.messages,+ target=endpoint_origin(request.endpoint),+ supports_images=request.supports_images,+ protocol=protocol,+ media_loader=media_loader,+ cancel=cancel or CancelToken(),+ )+ if isinstance(prepared, ProviderError):+ raise ValueError(prepared.message)+ messages, loaded_images = prepared+ return _WIRE_REQUESTS[protocol](request, messages, gateway=gateway, loaded_images=loaded_images)diff --git a/core/agent_core/harness/context.py b/core/agent_core/harness/context.pyindex 63bdc77e0..55ebad1bb 100644--- a/core/agent_core/harness/context.py+++ b/core/agent_core/harness/context.py@@ -22,8 +22,8 @@ from itertools import accumulatefrom dataclasses import dataclass, fieldfrom typing import Any, Callable, Collection, Mapping, Optional, Protocol, Sequence-from core.agent_core.ai._common import endpoint_origin-from core.agent_core.ai.provider import ModelCapabilities, ModelEndpoint, ModelRequest+from core.agent_core.ai._common import endpoint_origin, native_hosted_tools+from core.agent_core.ai.provider import HostedToolRoute, ModelCapabilities, ModelEndpoint, ModelRequestfrom core.agent_core.harness.projection import ContextView, Unit, context_viewfrom core.agent_core.harness.store import ContextEntryfrom core.agent_core.messages import (@@ -279,10 +279,27 @@ def messages_tokens(messages: Sequence[Message]) -> int:return sum(message_tokens(message) for message in messages)-def request_tokens(system: str, tools: Sequence[ToolSpec], messages: Sequence[Message]) -> int:- """The whole request: system prompt, tool definitions, and messages."""+def request_tokens(+ system: str,+ tools: Sequence[ToolSpec],+ messages: Sequence[Message],+ native: Optional[Mapping[str, HostedToolRoute]] = None,+) -> int:+ """The whole request: system prompt, tool definitions, and messages.++ ``native`` holds the request's hosted tools that its hop runs natively (``native_hosted_tools``): such a tool is+ sent as the provider's declaration in its spec's place, so that is what it counts as.+ """+ native = native or {}definitions = sum(- _utf8(json.dumps([spec.name, spec.description, dict(spec.input_schema)], ensure_ascii=False))+ _utf8(+ json.dumps(+ dict(native[spec.name].declaration or {})+ if spec.name in native+ else [spec.name, spec.description, dict(spec.input_schema)],+ ensure_ascii=False,+ )+ )for spec in tools)return math.ceil((_utf8(system) + definitions) / 4) + messages_tokens(messages)@@ -340,7 +357,7 @@ def _valid_usage(message: Optional[Message]) -> bool:def sent_tokens(request: ModelRequest) -> int:"""``tokens()`` of a whole request (section 2): system prompt, tool definitions, and messages."""- return request_tokens(request.system, request.tools, request.messages)+ return request_tokens(request.system, request.tools, request.messages, native_hosted_tools(request))def request_facts(request: ModelRequest) -> dict[str, int]:diff --git a/core/agent_core/tools/hosted.py b/core/agent_core/tools/hosted.pynew file mode 100644index 000000000..3f6ddc23f--- /dev/null+++ b/core/agent_core/tools/hosted.py@@ -0,0 +1,62 @@+"""The canonical hosted tools (``vibey-hosted-tools.md`` §2).++One user-facing tool per capability, with one name and schema in either execution mode. The schema is the+providers' trained interface: what their models call the hosted tool with. A request carries these specs like any+other tool; on a hop that runs the tool natively, the adapter sends the provider's declaration in the spec's place+(``ModelEndpoint.hosted_tools``), so ``ModelRequest.tools`` stays the one owner of what a request declares.+"""++from __future__ import annotations++import copy+from typing import Any++from core.agent_core.messages import HOSTED_TOOLS+from core.agent_core.tools.base import ToolSpec++_SPECS: dict[str, tuple[str, dict[str, Any]]] = {+ "web_search": (+ "Search the web. Returns numbered results with their titles, links and short excerpts.",+ {+ "type": "object",+ "properties": {"query": {"type": "string", "description": "What to search for."}},+ "required": ["query"],+ "additionalProperties": False,+ },+ ),+ "x_search": (+ "Search posts on X. The query accepts X's search operators, such as from:user and within_time:7d. "+ "Returns numbered posts with their links and excerpts.",+ {+ "type": "object",+ "properties": {+ "query": {"type": "string", "description": "What to search for."},+ "limit": {"type": "integer", "minimum": 1, "description": "The most posts to return."},+ "mode": {"type": "string", "enum": ["Latest", "Top"], "description": "Newest or top posts first."},+ },+ "required": ["query"],+ "additionalProperties": False,+ },+ ),+ "image_generation": (+ "Generate an image from a text prompt. The image is saved as a file, and the result names its path.",+ {+ "type": "object",+ "properties": {+ "prompt": {"type": "string", "description": "What the image shows."},+ "size": {"type": "string", "description": "Width x height in pixels, e.g. 1024x1024."},+ },+ "required": ["prompt"],+ "additionalProperties": False,+ },+ ),+}+++def hosted_tool_spec(tool: str) -> ToolSpec:+ """The canonical spec of the catalog tool ``tool`` (``web_search``, ``x_search`` or ``image_generation``)."""++ if tool not in HOSTED_TOOLS:+ raise ValueError(f"unknown hosted tool: {tool!r}")+ description, schema = _SPECS[tool]+ return ToolSpec(tool, description, copy.deepcopy(schema))diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.mdindex 40a650a26..9bafec1e7 100644--- a/docs/plans/agent-core-contracts/conversion-tables.md+++ b/docs/plans/agent-core-contracts/conversion-tables.md@@ -643,9 +643,11 @@ Responses terminal states:## Hosted tools (planned)-Planned by [`../vibey-hosted-tools.md`](../vibey-hosted-tools.md) (Phase 1: `web_search`, `x_search`). These rows-describe the wire mapping the `ai` lane implements with that phase. Until then the adapters ignore hosted items, as-the sections above record, and the Anthropic stop table above still maps `pause_turn` to `stop`.+Planned by [`../vibey-hosted-tools.md`](../vibey-hosted-tools.md) (Phase 1: `web_search`, `x_search`,+`image_generation`). These rows describe the wire mapping the `ai` lane implements with that phase. Implemented so+far: a hosted tool's canonical spec is sent as the native declaration on a hop whose route is native, with its+Responses `include` values and the pin header on that request. Until the rest lands the adapters ignore hosted items, as the sections above record, and the Anthropic stop+table above still maps `pause_turn` to `stop`.| Concern | Anthropic Messages | OpenAI Responses (OpenAI, xAI) | OpenAI Chat Completions || --- | --- | --- | --- |diff --git a/docs/plans/agent-core-contracts/fork.md b/docs/plans/agent-core-contracts/fork.mdindex 89c923cca..57585ffed 100644--- a/docs/plans/agent-core-contracts/fork.md+++ b/docs/plans/agent-core-contracts/fork.md@@ -188,6 +188,9 @@ because they are rendered into the prompt (C-9 §6).byte for byte.- It narrows capability when a call executes, never in the tool list. Removing a denied tool from the request wouldshift every byte after it.+- That includes a native hosted tool's declaration (`../vibey-hosted-tools.md` §4.1). The provider runs such a call+ upstream, so the policy cannot deny it at execution: a side turn may make one, billed like any other. A side turn's+ prompt asks for its reply, and a warm prefix on every checkpoint is worth more than that rare call.**A fork Session is cache-cold today.**diff --git a/docs/plans/agent-core-contracts/provider.md b/docs/plans/agent-core-contracts/provider.mdindex 31e7d8073..2d1520f1d 100644--- a/docs/plans/agent-core-contracts/provider.md+++ b/docs/plans/agent-core-contracts/provider.md@@ -19,6 +19,10 @@ class ModelEndpoint: # built by the adapter layer from C-6 HopResolutrequest_headers: Mapping[str, str]provider: str # vendor identity of the hop (HopResolution.provider); with protocol and model it# forms the target origin for the cross-provider rules+ source_id: str | None # HopResolution.source_id: the pin of a request with native hosted content+ hosted_tools: Mapping[str, HostedToolRoute] # HopResolution.hosted_tools, in Model Hub's order: per enabled+ # tool its mode, and for native its declaration and Responses include values,+ # plus the turn's executor and replay (vibey-hosted-tools.md §3.5)@dataclass(frozen=True)@@ -47,8 +51,20 @@ class ModelRequest:cache: Literal["default", "none"] # "default": the protocol's cache breakpoints and their lifetimes# (conversion-tables.md); "none" for the compaction summarizersupports_images: bool # resolved by the loop; unknown capability counts as False+ tool_choice: str | None # the one tool the response must call; set only by a hosted-tool probe```+`tools` is the one owner of what a request declares. A hosted tool is its canonical `ToolSpec`+(`core/agent_core/tools/hosted.py`, `hosted_tool_spec`). On a hop whose route for it is native, the adapter sends the+route's `declaration` verbatim in the spec's place, merges a Responses route's `include` values into `include`, and+pins the request with `x-avibe-pin-source: <source_id>`; on any other hop the spec is an ordinary function. Vibey+lists its hosted tools first, so Anthropic's tools breakpoint, which goes on the last function tool, never moves.+`registry.build_wire_request` returns the URL, headers and body the adapter would send, without sending it; a+hosted-tool probe sends exactly that request (`vibey-hosted-tools.md` §3.2). On Responses and Chat a forced function+is named, and a native hosted tool is forced with `"required"`, which needs it to be the request's only tool. An+Anthropic request is never forced: current Claude models and extended thinking refuse a forced `tool` or `any`+choice.+The loop's `ModelRouter` returns the `ModelEndpoint` together with its `ModelCapabilities`. Every capability has adefined effect, including when it is unknown:diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.pyindex e89116f19..92188a75d 100644--- a/modules/agents/vibey/agent.py+++ b/modules/agents/vibey/agent.py@@ -90,7 +90,7 @@ from modules.agents.vibey.media import MediaSnapshotsfrom modules.agents.vibey.models import HubModelRouter, ProviderFactory, registry_providers, selection_from_hopfrom modules.agents.vibey.prompt import EnvironmentValue, current_environment, system_promptfrom modules.agents.vibey.store import AdapterTranscriptStore-from modules.agents.vibey.tools import ToolSuite, local_tool_suite+from modules.agents.vibey.tools import ToolSuite, local_tool_suite, native_hosted_toolsfrom modules.agents.base import AGENT_RUNTIME_TURN_KEY, AgentRequest, BaseAgentfrom modules.agents.catalog import display_name_for_backendfrom modules.im.base import FileAttachment@@ -597,7 +597,12 @@ class VibeyAgent(BaseAgent):context=ContextConfig(host=self.context_host, scratch_dir=str(self._state_dir / "scratch" / session_id)),)# Job-backed tools receive the loop's tracking wrapper, so Stop kills foreground commands.- tools = mark_skill_loads(tuple(suite.create_tools(agent.jobs, self.media.image_sink(session_id))))+ tools = mark_skill_loads(+ (+ *native_hosted_tools(turn.router.preflight),+ *suite.create_tools(agent.jobs, self.media.image_sink(session_id)),+ )+ )agent.set_tools(tools)finds_rg = shutil.which("rg", path=environment.get("PATH", "")) is not Noneagent.system = system_prompt(diff --git a/modules/agents/vibey/models.py b/modules/agents/vibey/models.pyindex 2294533a1..6a8ad5906 100644--- a/modules/agents/vibey/models.py+++ b/modules/agents/vibey/models.py@@ -10,16 +10,28 @@ A ``google`` hop is called over Chat Completions at the same gateway: Model Hubserves every source on its OpenAI-compatible ``/v1`` surface and converts, sothe agent needs no Gemini transport. The served origin still comes from``x-avibe-served-hop``.++Each enabled hosted tool's route rides on the endpoint as Model Hub resolved it+(``hosted_tools``): an adapter declares a tool natively exactly where its mode+is ``native``, and pins that request to the hop's Source+(``vibey-hosted-tools.md`` §3.5, §4.1). The agent never decides nativity."""from __future__ import annotationsimport logging+import refrom typing import Any, Awaitable, Callable, Mapping, Optionalfrom core.agent_core.agent.models import ModelSelection-from core.agent_core.ai.provider import ModelCapabilities, ModelEndpoint, ProviderAdapter-from core.agent_core.messages import PROTOCOLS, ProtocolName+from core.agent_core.ai.provider import (+ HostedExecutor,+ HostedToolRoute,+ ModelCapabilities,+ ModelEndpoint,+ ProviderAdapter,+)+from core.agent_core.messages import HOSTED_TOOLS, PROTOCOLS, ProtocolNamelogger = logging.getLogger(__name__)@@ -39,6 +51,62 @@ def _optional(value: Any, kind: type, what: str) -> Any:return value+#: The keys of one ``hosted_tools`` entry per mode, exactly (hop-resolution.schema.json).+_HOSTED_ENTRY_KEYS = {+ "native": {"mode", "executor", "replay", "declaration", "include"},+ "proxy": {"mode", "executor", "replay"},+}+_SOURCE_ID = re.compile(r"src_[a-z0-9]{8,}")+++def _hosted_routes(raw: Any) -> dict[str, HostedToolRoute]:+ """``HopResolution.hosted_tools``: each enabled tool's mode, native declaration, executor and replay."""+ if not isinstance(raw, Mapping):+ raise HopResolutionError("hop has no hosted_tools")+ routes: dict[str, HostedToolRoute] = {}+ for tool, entry in raw.items():+ try:+ routes[tool] = _hosted_route(tool, entry)+ except (TypeError, ValueError, KeyError) as error:+ # Every malformed entry fails here, whatever the parse raised on it.+ raise HopResolutionError(f"hop hosted tool {tool!r} is invalid: {error}") from None+ return routes+++def _hosted_route(tool: Any, entry: Any) -> HostedToolRoute:+ """One entry, exactly as the hop schema allows it."""+ if tool not in HOSTED_TOOLS or not isinstance(entry, Mapping):+ raise ValueError("not a hosted tool entry")+ mode = entry.get("mode")+ keys = _HOSTED_ENTRY_KEYS.get(mode) if isinstance(mode, str) else None+ if keys is None:+ raise ValueError(f"unknown mode {mode!r}")+ if set(entry) != keys:+ raise ValueError(f"a {mode} entry has exactly {', '.join(sorted(keys))}")+ executor = entry["executor"]+ if executor is not None:+ if (+ not isinstance(executor, Mapping)+ or set(executor) != {"source_id", "model_id"}+ or not isinstance(executor["source_id"], str)+ or not _SOURCE_ID.fullmatch(executor["source_id"])+ ):+ raise ValueError("the executor is a Source id and a model id, or null")+ executor = HostedExecutor(executor["source_id"], executor["model_id"])+ if tool == "image_generation" and entry["replay"] is not False:+ raise ValueError("an image_generation call is never replayed")+ include = entry.get("include", [])+ if not isinstance(include, list):+ raise ValueError("include must be a list")+ return HostedToolRoute(+ mode=mode,+ executor=executor,+ replay=entry["replay"],+ declaration=entry.get("declaration"),+ include=tuple(include),+ )++def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[str] = None) -> ModelSelection:"""Build the loop's selection from one ``HopResolution`` (hop-resolution.schema.json).@@ -51,7 +119,7 @@ def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[strprotocol = hop.get("protocol")if protocol not in PROTOCOLS:raise HopResolutionError(f"hop protocol {protocol!r} is not supported")- for name in ("base_url", "token", "runtime_model", "provider"):+ for name in ("base_url", "token", "runtime_model", "provider", "source_id"):if not isinstance(hop.get(name), str) or not hop[name]:raise HopResolutionError(f"hop has no {name}")headers = hop.get("request_headers")@@ -59,6 +127,7 @@ def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[strisinstance(key, str) and isinstance(value, str) for key, value in headers.items()):raise HopResolutionError("hop request_headers must map strings to strings")+ hosted_tools = _hosted_routes(hop.get("hosted_tools"))raw = hop.get("capabilities")if not isinstance(raw, Mapping):raise HopResolutionError("hop has no capabilities")@@ -86,6 +155,8 @@ def selection_from_hop(hop: Mapping[str, Any], *, gateway_base_url: Optional[strtoken=hop["token"],request_headers=dict(headers),provider=hop["provider"],+ source_id=hop["source_id"],+ hosted_tools=hosted_tools,)return ModelSelection(endpoint=endpoint, capabilities=capabilities)@@ -108,6 +179,8 @@ class HubModelRouter:self._resolve = resolveself._providers = providersself._first = first+ #: The route preflight resolved; the Turn's tool list is fixed from it.+ self.preflight = firstself._adapters: dict[str, ProviderAdapter] = {}async def resolve(self) -> ModelSelection:diff --git a/modules/agents/vibey/tools.py b/modules/agents/vibey/tools.pyindex f9231ffde..312badba6 100644--- a/modules/agents/vibey/tools.py+++ b/modules/agents/vibey/tools.py@@ -19,8 +19,11 @@ import asynciofrom dataclasses import dataclass, fieldfrom typing import Any, Awaitable, Callable, Mapping, Optional, Sequence+from core.agent_core.agent.models import ModelSelectionfrom core.agent_core.agent.recovery import RecoveryRenderer-from core.agent_core.tools.base import CallInstance, JobHost, Tool+from core.agent_core.messages import TextBlock+from core.agent_core.tools.base import CallInstance, JobHost, Tool, ToolContext, ToolResult, ToolSpec+from core.agent_core.tools.hosted import hosted_tool_specfrom core.agent_core.tools.shell import default_shellImageSink = Callable[[bytes, str, str], Awaitable[str]]@@ -92,3 +95,29 @@ def local_tool_suite(jobs_dir: Optional[str] = None, *, route: Optional[HandOverprune=prune,shell=host.shell.describe(),)+++@dataclass(frozen=True)+class NativeHostedTool:+ """A hosted tool the Turn's preflight hop runs natively (``vibey-hosted-tools.md`` §4.1).++ Its spec is the canonical one; on a hop whose route is native the adapter sends the provider's declaration in+ its place, and the provider runs the call. A call reaches ``execute`` only when a later hop of the Turn resolved+ the tool as proxied, and no proxy executor is wired yet.+ """++ spec: ToolSpec++ async def execute(self, arguments: Mapping[str, Any], ctx: ToolContext) -> ToolResult:+ del arguments, ctx+ return ToolResult(content=(TextBlock(f"{self.spec.name} is not available on this route."),), is_error=True)+++def native_hosted_tools(selection: Optional[ModelSelection]) -> tuple[Tool, ...]:+ """The hosted tools preflight's hop runs natively, in Model Hub's order. They lead the Turn's tools, so its last+ tool stays a local one whatever a hop renders them as."""++ if selection is None:+ return ()+ routes = selection.endpoint.hosted_tools+ return tuple(NativeHostedTool(hosted_tool_spec(name)) for name, route in routes.items() if route.mode == "native")diff --git a/tests/agent_core/agent/test_context.py b/tests/agent_core/agent/test_context.pyindex 62ec98475..13d7f6d9a 100644--- a/tests/agent_core/agent/test_context.py+++ b/tests/agent_core/agent/test_context.py@@ -18,7 +18,7 @@ from pathlib import Pathimport pytest-from core.agent_core.ai.provider import ModelCapabilities, ModelEndpoint, ModelRequest+from core.agent_core.ai.provider import HostedToolRoute, ModelCapabilities, ModelEndpoint, ModelRequestfrom core.agent_core.harness.context import (KEPT_INPUTS_WIN,CLEARED_PLACEHOLDER,@@ -54,6 +54,7 @@ from core.agent_core.harness.context import (from core.agent_core.harness.projection import context_view, projectfrom core.agent_core.harness.store import ContextEntryfrom core.agent_core.tools.base import ToolSpec+from core.agent_core.tools.hosted import hosted_tool_specfrom core.agent_core.messages import (AssistantMessage,ImageBlock,@@ -279,6 +280,22 @@ def test_the_anchor_holds_while_the_transcript_up_to_its_response_is_unchanged()tool = ToolSpec("t", "d" * 400, {})tool_delta = request_tokens("system", (tool,), ()) - request_tokens("system", (), ())assert _est(rows, make_request(messages, tools=(tool,))) == 5_000 + after + tool_delta+ # A hosted tool counts as what its hop sends: the provider's declaration where its route is native, its spec+ # elsewhere, so a route that turns proxied grows the estimate though the request's tools are the same.+ search = hosted_tool_spec("web_search")+ declaration = {"type": "web_search_20250305", "name": "web_search", "max_uses": 5}+ proxied = make_request(messages, tools=(search,))+ native = replace(+ proxied,+ endpoint=replace(+ ENDPOINT,+ source_id="src_hostedtest1",+ hosted_tools={"web_search": HostedToolRoute("native", None, False, declaration=declaration)},+ ),+ )+ as_spec = len(json.dumps([search.name, search.description, dict(search.input_schema)]).encode())+ as_declaration = len(json.dumps(declaration).encode())+ assert _est(rows, proxied) - _est(rows, native) == math.ceil((6 + as_spec) / 4) - math.ceil((6 + as_declaration) / 4)rehydrated = user("state " * 50)assert _est(rows, make_request((rehydrated, *messages))) == 5_000 + after + message_tokens(rehydrated)# An edit after the anchored response is counted by its bytes.diff --git a/tests/agent_core/ai/test_hosted_requests.py b/tests/agent_core/ai/test_hosted_requests.pynew file mode 100644index 000000000..c28624348--- /dev/null+++ b/tests/agent_core/ai/test_hosted_requests.py@@ -0,0 +1,246 @@+"""Hosted-tool request building (``vibey-hosted-tools.md`` §3.2, §3.5, §4.1), read on the wire.++``ModelRequest.tools`` is the one owner of what a request declares. A hosted tool's canonical spec is sent as the+overlay's declaration, verbatim and in its place, on a hop whose route for it is native, with the route's Responses+``include`` values, and that request is pinned to the hop's Source; anywhere else the spec is an ordinary function.+``build_wire_request`` is the probe's entry: it must be exactly what the adapter sends. Scenario MH-HOSTED-VIBEY-001.+"""++from __future__ import annotations++import json+from typing import Any++import httpx+import pytest++from core.agent_core.ai._common import PIN_SOURCE_HEADER+from core.agent_core.ai.provider import (+ Done,+ HostedExecutor,+ HostedToolRoute,+ ModelEndpoint,+ ModelRequest,+)+from core.agent_core.ai.registry import build_wire_request, create_adapter+from core.agent_core.cancel import CancelToken+from core.agent_core.messages import TextBlock, UserMessage+from core.agent_core.tools.base import ToolSpec+from core.agent_core.tools.hosted import hosted_tool_spec++SOURCE = "src_hostedprobe1"+EXECUTOR = HostedExecutor("src_xaiexecutor1", "grok-4.6")+READ = ToolSpec("read", "Read a file.", {"type": "object", "properties": {"path": {"type": "string"}}})+BASH = ToolSpec("bash", "Run a command.", {"type": "object", "properties": {"command": {"type": "string"}}})+WEB = hosted_tool_spec("web_search")+X = hosted_tool_spec("x_search")+# The §4.1 declarations, as HopResolution carries them from the overlay.+ANTHROPIC_SEARCH = {"type": "web_search_20250305", "name": "web_search", "max_uses": 5}+OPENAI_SEARCH = {"type": "web_search"}+X_SEARCH = {"type": "x_search"}+SOURCES_INCLUDE = "web_search_call.action.sources"+PROVIDER = {"anthropic": "anthropic", "openai_responses": "openai", "openai_chat": "openai"}+STREAMS = {+ "anthropic": (+ 'data: {"type":"message_start","message":{"usage":{}}}\n\n'+ 'data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}\n\n'+ 'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}\n\n'+ 'data: {"type":"content_block_stop","index":0}\n\n'+ 'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"}}\n\n'+ 'data: {"type":"message_stop"}\n\n'+ ),+ "openai_responses": (+ 'data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"msg_1"}}\n\n'+ 'data: {"type":"response.output_text.delta","output_index":0,"delta":"ok"}\n\n'+ 'data: {"type":"response.completed","response":{"status":"completed","output":null}}\n\n'+ ),+ "openai_chat": (+ 'data: {"choices":[{"delta":{"content":"ok"}}]}\n\n'+ 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}\n\n'+ "data: [DONE]\n\n"+ ),+}+++def _native(declaration: dict[str, Any], include: tuple[str, ...] = ()) -> HostedToolRoute:+ return HostedToolRoute("native", EXECUTOR, False, declaration=declaration, include=include)+++PROXY = HostedToolRoute("proxy", EXECUTOR, False)+++def _request(+ protocol: str,+ hosted: dict[str, HostedToolRoute],+ *,+ tools: tuple[ToolSpec, ...] = (READ, BASH),+ effort: str | None = "high",+ tool_choice: str | None = None,+ source_id: str | None = SOURCE,+) -> ModelRequest:+ return ModelRequest(+ endpoint=ModelEndpoint(+ protocol, # type: ignore[arg-type]+ "http://hub.invalid/vibey/v1",+ "claude-opus-5-5" if protocol == "anthropic" else "grok-4.6",+ "hub-token",+ request_headers={"x-avibe-turn": "turn-1"},+ provider=PROVIDER[protocol],+ source_id=source_id,+ hosted_tools=hosted,+ ),+ system="You are a coding agent.",+ messages=(UserMessage((TextBlock("search for 'Avibe local-first agent OS'"),)),),+ tools=tools,+ max_tokens=256,+ reasoning_effort=effort,+ tool_choice=tool_choice,+ )+++def _function_names(protocol: str, entries: list[dict[str, Any]]) -> list[str]:+ if protocol == "openai_chat":+ return [entry["function"]["name"] for entry in entries]+ return [entry["name"] for entry in entries]+++ ("protocol", "hosted", "tools", "declared", "include"),+ [+ ("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, (WEB, READ, BASH), [ANTHROPIC_SEARCH], None),+ (+ "openai_responses",+ {"web_search": _native(OPENAI_SEARCH, (SOURCES_INCLUDE,))},+ (WEB, READ, BASH),+ [OPENAI_SEARCH],+ ["reasoning.encrypted_content", SOURCES_INCLUDE],+ ),+ # xAI: both search tools native, neither needing an include.+ (+ "openai_responses",+ {"web_search": _native(OPENAI_SEARCH), "x_search": _native(X_SEARCH)},+ (WEB, X, READ, BASH),+ [OPENAI_SEARCH, X_SEARCH],+ ["reasoning.encrypted_content"],+ ),+ ],+)+async def test_a_hosted_spec_on_a_native_route_is_sent_as_the_declaration_in_its_place_and_pinned(+ protocol: str,+ hosted: dict[str, HostedToolRoute],+ tools: tuple[ToolSpec, ...],+ declared: list[dict[str, Any]],+ include: list[str] | None,+) -> None:+ wire = await build_wire_request(_request(protocol, hosted, tools=tools), gateway=True)++ sent = wire.body["tools"]+ assert sent[: len(declared)] == declared+ assert _function_names(protocol, sent[len(declared) :]) == ["read", "bash"]+ assert wire.body.get("include") == include+ assert wire.headers[PIN_SOURCE_HEADER] == SOURCE+ if protocol == "anthropic":+ # The tools breakpoint stays on the last function tool; a server tool never carries it.+ assert [index for index, tool in enumerate(sent) if "cache_control" in tool] == [len(sent) - 1]++[email protected]("protocol", ["anthropic", "openai_responses", "openai_chat"])+ ("hosted", "tools", "functions"),+ [+ ({}, (READ, BASH), ["read", "bash"]),+ # A proxied hosted tool is its canonical function.+ ({"web_search": PROXY}, (WEB, READ, BASH), ["web_search", "read", "bash"]),+ # The endpoint alone declares nothing: a native route for a tool the request does not carry sends nothing.+ ({"web_search": _native(OPENAI_SEARCH, (SOURCES_INCLUDE,))}, (READ, BASH), ["read", "bash"]),+ ],+ ids=["no-route", "proxy-route", "native-route-undeclared"],+)+async def test_without_a_declared_native_tool_every_tool_is_a_function_and_the_request_unpinned(+ protocol: str, hosted: dict[str, HostedToolRoute], tools: tuple[ToolSpec, ...], functions: list[str]+) -> None:+ wire = await build_wire_request(_request(protocol, hosted, tools=tools), gateway=True)++ assert _function_names(protocol, wire.body["tools"]) == functions+ assert PIN_SOURCE_HEADER not in wire.headers+ if protocol == "openai_responses":+ assert wire.body["include"] == ["reasoning.encrypted_content"]+++ ("protocol", "hosted", "tools", "tool_choice"),+ [+ ("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, (WEB, READ, BASH), None),+ ("openai_responses", {"web_search": _native(OPENAI_SEARCH, (SOURCES_INCLUDE,))}, (WEB, READ, BASH), None),+ ("openai_chat", {"web_search": PROXY}, (WEB, READ, BASH), "read"),+ # Call probes: the hosted tool alone, forced on Responses and asked for in the message on Anthropic.+ ("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, (WEB,), None),+ ("openai_responses", {"x_search": _native(X_SEARCH)}, (X,), "x_search"),+ ],+)+async def test_the_probe_entry_builds_exactly_the_request_the_adapter_sends(+ protocol: str, hosted: dict[str, HostedToolRoute], tools: tuple[ToolSpec, ...], tool_choice: str | None+) -> None:+ request = _request(protocol, hosted, tools=tools, tool_choice=tool_choice)+ sent: list[httpx.Request] = []++ def gateway(wire: httpx.Request) -> httpx.Response:+ sent.append(wire)+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, text=STREAMS[protocol])++ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ adapter = create_adapter(protocol, client=client, gateway=True) # type: ignore[arg-type]+ events = [event async for event in adapter.stream(request, CancelToken())]+ built = await build_wire_request(request, gateway=True)++ assert isinstance(events[-1], Done)+ (wire,) = sent+ assert str(wire.url) == built.url+ assert {key: wire.headers[key] for key in built.headers} == built.headers+ assert json.loads(wire.content) == built.body+++ ("protocol", "hosted", "tools", "tool_choice", "expected"),+ [+ # OpenAI's hosted choice types have no web_search or x_search: `required` over the tool alone forces it.+ ("openai_responses", {"web_search": _native(OPENAI_SEARCH)}, (WEB,), "web_search", "required"),+ ("openai_responses", {}, (READ, BASH), "read", {"type": "function", "name": "read"}),+ ("openai_chat", {}, (READ, BASH), "bash", {"type": "function", "function": {"name": "bash"}}),+ ],+)+async def test_tool_choice_forces_the_named_tool_in_each_protocols_form(+ protocol: str, hosted: dict[str, HostedToolRoute], tools: tuple[ToolSpec, ...], tool_choice: str, expected: Any+) -> None:+ wire = await build_wire_request(_request(protocol, hosted, tools=tools, tool_choice=tool_choice), gateway=True)++ assert wire.body["tool_choice"] == expected+++ ("request_", "refusal"),+ [+ # `required` would let the model pick a function instead of the hosted tool.+ (+ _request(+ "openai_responses", {"web_search": _native(OPENAI_SEARCH)}, tools=(WEB, READ), tool_choice="web_search"+ ),+ "only tool",+ ),+ (_request("openai_chat", {}, tool_choice="web_search"), "does not declare"),+ # Current Claude models and extended thinking refuse a forced choice: a probe would test that refusal.+ (+ _request("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, tools=(WEB,), tool_choice="web_search"),+ "never",+ ),+ # A native declaration is never sent unpinned: unpinned, the gateway could fail it over to an unverified hop.+ (+ _request("anthropic", {"web_search": _native(ANTHROPIC_SEARCH)}, tools=(WEB, READ), source_id=None),+ "pinned",+ ),+ ],+ ids=["forced-hosted-beside-functions", "forced-undeclared", "anthropic-forced", "native-without-source"],+)+async def test_a_request_that_cannot_be_sent_as_specified_is_refused(request_: ModelRequest, refusal: str) -> None:+ with pytest.raises(ValueError, match=refusal):+ await build_wire_request(request_, gateway=True)diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 1064e356e..2d3d531b9 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -53,6 +53,8 @@ capabilities:- tests/test_model_hub_hosted_tools_config.py- tests/test_model_hub_capability_evidence.py- tests/test_provider_overlay.py+ - tests/agent_core/ai/test_hosted_requests.py+ - tests/test_vibey_agent.py- tests/test_model_hub_admission.py- tests/test_model_hub_vibey_consumer.py- tests/test_model_hub_config.pydiff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yamlindex 34406495e..e03e966ef 100644--- a/tests/scenarios/model_hub/catalog.yaml+++ b/tests/scenarios/model_hub/catalog.yaml@@ -9,6 +9,8 @@ capability:- tests/test_model_hub_hosted_tools_config.py- tests/test_model_hub_capability_evidence.py- tests/test_provider_overlay.py+ - tests/agent_core/ai/test_hosted_requests.py+ - tests/test_vibey_agent.py- tests/test_model_hub_config.py- tests/test_model_hub_legacy_opencode_migration.py- tests/test_member_management_parity.py@@ -189,6 +191,17 @@ scenarios:related_tests:- tests/test_provider_overlay.py::test_bundled_providers_section_satisfies_its_schema- tests/test_provider_overlay.py::test_an_invalid_vendor_entry_disables_only_that_vendor+ - id: MH-HOSTED-VIBEY-001+ name: Vibey declares a hop's native hosted tool verbatim with its include values and pins that request to the hop's Source; the probe builds the same request+ status: covered+ kind: contract+ layer: contract+ test: tests/test_vibey_agent.py::test_a_hop_resolved_native_hosted_tool_reaches_the_gateway_pinned_to_its_source+ related_tests:+ - tests/test_vibey_agent.py::test_a_hop_with_an_invalid_hosted_tool_entry_is_refused+ - tests/agent_core/ai/test_hosted_requests.py::test_a_hosted_spec_on_a_native_route_is_sent_as_the_declaration_in_its_place_and_pinned+ - tests/agent_core/ai/test_hosted_requests.py::test_the_probe_entry_builds_exactly_the_request_the_adapter_sends+ - tests/agent_core/ai/test_hosted_requests.py::test_tool_choice_forces_the_named_tool_in_each_protocols_form- id: MH-VIBEY-007name: Vibey starts once with the user's Sources and built-in Agent models, seeded when its first Source existsstatus: covereddiff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.pyindex d5a1266cf..5b5248269 100644--- a/tests/test_vibey_agent.py+++ b/tests/test_vibey_agent.py@@ -191,6 +191,8 @@ class _Controller:self.hub_protocol = "anthropic"# The Model Hub model definition's limits (C-9 takes W, L_in, and O from them).self.hub_limits = {"context_window": 32000, "max_output_tokens": 4096}+ # HopResolution.hosted_tools as Model Hub resolves it for the hop.+ self.hub_hosted_tools: dict = {}self.agent: Optional[VibeyAgent] = Noneself.agent_service = SimpleNamespace(mark_runtime_turn_started=self._native_start,@@ -244,6 +246,7 @@ class _Controller:protocol=self.hub_protocol,provider="test-provider",supports_images=True,+ hosted_tools=self.hub_hosted_tools,)def _native_start(self, context, *, activation_identity=None) -> None:@@ -2378,6 +2381,103 @@ async def test_a_turn_runs_through_the_real_provider_registry(engine, session, tassert harness.controller.im_client.sent == ["hi"]+ ("hub_protocol", "declaration", "include"),+ [+ ("anthropic", {"type": "web_search_20250305", "name": "web_search", "max_uses": 5}, []),+ ("openai_responses", {"type": "web_search"}, ["web_search_call.action.sources"]),+ ],+)+async def test_a_hop_resolved_native_hosted_tool_reaches_the_gateway_pinned_to_its_source(+ engine, session, tmp_path, published, hub_protocol, declaration, include+) -> None:+ """MH-HOSTED-VIBEY-001 (vibey-hosted-tools.md §3.5, §4.1): Vibey takes each tool's mode from the hop. A tool the+ preflight hop runs natively joins the Turn's tools first, and goes out as the provider's declaration, verbatim, with+ its include values, on a request pinned to the hop's Source. A proxied tool is not offered yet."""+ import httpx++ from modules.agents.vibey.models import registry_providers++ path, body = _TEXT_STREAMS[hub_protocol]+ served = json.dumps(+ {"provider": "upstream", "api": hub_protocol, "model": "served-model", "source": "src_upstream01"},+ separators=(",", ":"),+ )+ seen: list[httpx.Request] = []++ def gateway(request: httpx.Request) -> httpx.Response:+ seen.append(request)+ return httpx.Response(+ 200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": served}, text=body+ )++ executor = {"source_id": "src_executor01", "model_id": "grok-4.6"}+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:+ harness = _Harness(+ engine, tmp_path, "telegram", [], providers=registry_providers(media_loader=None, client=client)+ )+ harness.controller.hub_protocol = hub_protocol+ harness.controller.hub_hosted_tools = {+ "web_search": {+ "mode": "native", "declaration": declaration, "include": include, "executor": executor, "replay": True+ },+ "x_search": {"mode": "proxy", "executor": executor, "replay": False},+ }+ await harness.agent.handle_message(harness.request("hello"))++ (request,) = seen+ sent = json.loads(request.content)+ assert request.url.path == path+ assert request.headers["x-avibe-pin-source"] == "src_test"+ # The native tool leads the Turn's tools; the proxied one is not offered until its executor exists.+ assert sent["tools"][0] == declaration+ assert all(tool.get("name") != "x_search" and tool.get("type") != "x_search" for tool in sent["tools"])+ assert set(include) <= set(sent.get("include", []))+ assert harness.controller.im_client.sent == ["hi"]+++_NATIVE_SEARCH = {"mode": "native", "declaration": {"type": "web_search"}, "include": [], "executor": None, "replay": False}+_PROXY_IMAGE = {"mode": "proxy", "executor": {"source_id": "src_executor01", "model_id": "gpt-image"}, "replay": False}+++def _without(entry: dict, key: str) -> dict:+ return {name: value for name, value in entry.items() if name != key}+++ "hosted_tools",+ [+ None,+ {"web_fetch": _PROXY_IMAGE},+ {"web_search": _without(_NATIVE_SEARCH, "declaration")},+ {"web_search": {**_without(_NATIVE_SEARCH, "declaration"), "mode": "proxy"}},+ {"web_search": {**_NATIVE_SEARCH, "note": "extra"}},+ {"web_search": _without(_NATIVE_SEARCH, "replay")},+ {"image_generation": {**_PROXY_IMAGE, "executor": {"source_id": "src_executor01"}}},+ {"image_generation": {**_PROXY_IMAGE, "executor": {"source_id": "openai-main", "model_id": "gpt-image"}}},+ {"image_generation": {**_PROXY_IMAGE, "replay": True}},+ {"web_search": {**_NATIVE_SEARCH, "mode": []}},+ {"web_search": {**_NATIVE_SEARCH, "include": "web_search_call.action.sources"}},+ ],+ ids=[+ "absent", "unknown-tool", "native-without-declaration", "proxy-with-include", "extra-field", "no-replay",+ "half-executor", "executor-not-a-source-id", "image-replay", "unhashable-mode", "include-not-a-list",+ ],+)+def test_a_hop_with_an_invalid_hosted_tool_entry_is_refused(hosted_tools) -> None:+ from modules.agents.vibey.models import HopResolutionError, selection_from_hop++ hop = ModelHubLaunch(+ backend="vibey", channel="hub", requested_model="m", target_model="m", runtime_model="m",+ source_id="src_test", gateway_base_url="http://hub.invalid/vibey", gateway_token="hub-token",+ protocol="openai_responses", provider="openai",+ ).to_hop_resolution()+ hop["hosted_tools"] = hosted_tools++ with pytest.raises(HopResolutionError, match="hosted"):+ selection_from_hop(hop)++# How a stream breaks off: the connection simply ends, or CLIProxyAPI (Model Hub's engine) reports the upstream# closing before its terminal in its own frame, byte for byte, which Model Hub forwards as it is._THINKING_DROPS = {