Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(vibey): run proxied hosted tools on the gateway's bound executor (#2574)

Call White4a47b4d87029
diff --git a/core/agent_core/agent/loop.py b/core/agent_core/agent/loop.py
index 6c9b06c2b..923b4b9ab 100644
--- a/core/agent_core/agent/loop.py
+++ b/core/agent_core/agent/loop.py
@@ -1118,7 +1118,7 @@ class Agent:
async def _commit_result(
self, call: ToolCallBlock, result: ToolResult, emit: Callable[..., Awaitable[None]]
) -> None:
- message = ToolResultMessage(call.id, call.name, result.content, result.is_error)
+ message = ToolResultMessage(call.id, call.name, result.content, result.is_error, hosted=result.hosted)
validate_message_append(self._rows, session_id=self.session_id, kind="tool_result", message=message)
await self._save_state()
row = await self._scope.call(
@@ -1808,7 +1808,9 @@ class Agent:
# A side turn's call has no committed response, so no instance: it starts no job (F4).
result = await self._execute(tool, call, None, _silent)
# Every other result that enters the turn is bounded to the room the window leaves (C-9 section 6).
- return ToolResultMessage(call.id, call.name, fit_result(result.content, limit), result.is_error)
+ return ToolResultMessage(
+ call.id, call.name, fit_result(result.content, limit), result.is_error, hosted=result.hosted
+ )
async def _drop(
self,
diff --git a/core/agent_core/tools/base.py b/core/agent_core/tools/base.py
index b51413778..b113fb81e 100644
--- a/core/agent_core/tools/base.py
+++ b/core/agent_core/tools/base.py
@@ -11,7 +11,7 @@ from dataclasses import dataclass, field
from typing import Any, Callable, Literal, Mapping, Optional, Protocol
from core.agent_core.cancel import CancelToken
-from core.agent_core.messages import UserContent
+from core.agent_core.messages import HostedResult, UserContent
MAX_LINES = 2000
MAX_BYTES = 50 * 1024
@@ -63,6 +63,8 @@ class ToolResult:
is_error: bool = False
details: Mapping[str, Any] = field(default_factory=dict)
terminate: bool = False
+ #: A proxied hosted tool's canonical record and execution, kept on its ``ToolResultMessage``.
+ hosted: Optional[HostedResult] = None
class Tool(Protocol):
diff --git a/docs/plans/agent-core-contracts/conversion-tables.md b/docs/plans/agent-core-contracts/conversion-tables.md
index bf5c7ab22..012676104 100644
--- a/docs/plans/agent-core-contracts/conversion-tables.md
+++ b/docs/plans/agent-core-contracts/conversion-tables.md
@@ -658,7 +658,10 @@ far:
So does a hosted call that follows a client tool call of the same response, because a split there would separate
that call from its result.
-Still to come: native verbatim replay, the `pin_unavailable` re-render, `pause_turn`, the proxy executor and images.
+- **Proxy.** A hosted tool that a hop does not run natively is its canonical function, and a call to it runs on the
+ gateway's executor bound for the Turn. The result keeps the record on `ToolResultMessage.hosted`.
+
+Still to come: native verbatim replay, the `pin_unavailable` re-render, `pause_turn` and images.
Until `pause_turn` lands, the Anthropic stop table above still maps it to `stop`. An Anthropic citation covers its
whole text block, so it carries no range.
diff --git a/docs/plans/agent-core-contracts/tools.md b/docs/plans/agent-core-contracts/tools.md
index 7babcfe8c..d2437be73 100644
--- a/docs/plans/agent-core-contracts/tools.md
+++ b/docs/plans/agent-core-contracts/tools.md
@@ -13,6 +13,12 @@ the same response (C-3 [`loop-control.md`](loop-control.md) §2). When it is abs
is exclusive. `read` and `bash` are concurrent; `write` and `edit` are exclusive. Pi instead runs a response's calls at
the same time unless a tool opts out, and serializes `write` and `edit` only per file path, which `bash` bypasses.
+**Hosted tools** (Avibe, [`../vibey-hosted-tools.md`](../vibey-hosted-tools.md)) are not coding tools. Each enabled
+one (`web_search`, `x_search`) has its canonical spec in `core/agent_core/tools/hosted.py` and leads the Turn's tools.
+On a hop that runs it natively the provider runs the call. Anywhere else the model calls the same-named function, and
+its `execute` asks the gateway's executor bound for the Turn. The result's text is the record as `record_text` renders
+it, and `ToolResult.hosted` carries the record and execution onto `ToolResultMessage.hosted`.
+
## 1. Constants
| Name | Value |
diff --git a/modules/agents/vibey/agent.py b/modules/agents/vibey/agent.py
index 83591b60f..5f817edb2 100644
--- a/modules/agents/vibey/agent.py
+++ b/modules/agents/vibey/agent.py
@@ -36,6 +36,7 @@ from pathlib import Path
from types import SimpleNamespace
from typing import Any, AsyncIterator, Callable, Mapping, Optional, Sequence
+import httpx
from sqlalchemy import and_, select
from sqlalchemy.engine import Engine
@@ -99,7 +100,7 @@ from modules.agents.vibey.media import MediaSnapshots
from modules.agents.vibey.models import HubModelRouter, ProviderFactory, registry_providers, selection_from_hop
from modules.agents.vibey.prompt import EnvironmentValue, current_environment, system_prompt
from modules.agents.vibey.store import AdapterTranscriptStore
-from modules.agents.vibey.tools import ToolSuite, local_tool_suite, native_hosted_tools
+from modules.agents.vibey.tools import ToolSuite, hosted_tools, local_tool_suite
from modules.agents.base import AGENT_RUNTIME_TURN_KEY, AgentRequest, BaseAgent
from modules.agents.catalog import display_name_for_backend
from modules.im.base import FileAttachment
@@ -229,6 +230,7 @@ class VibeyAgent(BaseAgent):
providers: Optional[ProviderFactory] = None,
tool_suite: Optional[ToolSuite] = None,
state_dir: Optional[Path] = None,
+ gateway_client: Optional[httpx.AsyncClient] = None,
) -> None:
super().__init__(controller)
self._engine = engine or get_cached_sqlite_engine()
@@ -242,6 +244,8 @@ class VibeyAgent(BaseAgent):
on_response=self._on_response,
)
self._providers = providers or registry_providers(media_loader=self.media)
+ # The client of the Turn's other gateway calls (the hosted-tool executor); None opens one per call.
+ self._gateway_client = gateway_client
# C-9: the Session parts a checkpoint carries (context.md section 9).
self.context_host = VibeyContextHost(self._engine, environment=self._environment)
self._tool_suite = tool_suite
@@ -613,7 +617,7 @@ class VibeyAgent(BaseAgent):
# Job-backed tools receive the loop's tracking wrapper, so Stop kills foreground commands.
tools = mark_skill_loads(
(
- *native_hosted_tools(turn.router.preflight),
+ *hosted_tools(turn.router.preflight, self._gateway_client),
*suite.create_tools(agent.jobs, self.media.image_sink(session_id)),
)
)
diff --git a/modules/agents/vibey/tools.py b/modules/agents/vibey/tools.py
index b8f9c9fa6..8e419e569 100644
--- a/modules/agents/vibey/tools.py
+++ b/modules/agents/vibey/tools.py
@@ -19,9 +19,14 @@ import asyncio
from dataclasses import dataclass, field
from typing import Any, Awaitable, Callable, Mapping, Optional, Sequence
+import httpx
+
from core.agent_core.agent.models import ModelSelection
from core.agent_core.agent.recovery import RecoveryRenderer
-from core.agent_core.messages import TextBlock
+from core.agent_core.ai._common import CONNECT_TIMEOUT_S, auth_headers, join_endpoint_url
+from core.agent_core.ai.hosted import bounded_error, record_text
+from core.agent_core.ai.provider import HostedExecutor, ModelEndpoint
+from core.agent_core.messages import HostedRecord, HostedResult, TextBlock, ToolResultMessage, message_from_dict
from core.agent_core.tools.base import CallInstance, JobHost, Tool, ToolContext, ToolResult, ToolSpec
from core.agent_core.tools.hosted import hosted_tool_spec
from core.agent_core.tools.shell import default_shell
@@ -97,36 +102,108 @@ def local_tool_suite(jobs_dir: Optional[str] = None, *, route: Optional[HandOver
)
+#: The hosted tools whose native results the adapters parse. A generated image arrives as base64 that history must
+#: never hold (§7.3), so ``image_generation`` joins with its media handling.
+PARSED_HOSTED_TOOLS = ("web_search", "x_search")
+
+
@dataclass(frozen=True)
-class NativeHostedTool:
- """A hosted tool the Turn's preflight hop runs natively (``vibey-hosted-tools.md`` §4.1).
+class HostedTool:
+ """One hosted tool of the Turn (``vibey-hosted-tools.md`` §3.4, §4.1), with one name and schema in both modes.
- 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.
+ On a hop whose route for it is native, the adapter sends the provider's declaration in its spec's place and the
+ provider runs the call. A call that reaches ``execute`` is proxied: the gateway runs it on the executor Model Hub
+ bound for the Turn, and nothing else. The gateway writes the record; this tool writes the text the model reads,
+ with the same function that renders a replayed call.
"""
spec: ToolSpec
+ executor: Optional[HostedExecutor]
+ #: The Turn's gateway: where the executor endpoint lives, and the token and headers that authorize the call.
+ endpoint: ModelEndpoint = field(repr=False)
+ client: Optional[httpx.AsyncClient] = field(default=None, repr=False)
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)
+ del ctx
+ hosted = await self._run(dict(arguments))
+ query = arguments.get("query")
+ text = record_text(self.spec.name, hosted.record, query=query if isinstance(query, str) else None)
+ failed = hosted.record.status in ("failed", "incomplete")
+ return ToolResult(content=(TextBlock(text),), is_error=failed, hosted=hosted)
+
+ async def _run(self, arguments: dict[str, Any]) -> HostedResult:
+ url = join_endpoint_url(self.endpoint.base_url, f"/hosted-tools/{self.spec.name}")
+ executor = self.executor
+ body = {
+ "arguments": arguments,
+ "executor": {"source_id": executor.source_id, "model_id": executor.model_id} if executor else None,
+ }
+ headers = auth_headers(self.endpoint, provider="openai", gateway=True)
+ # The gateway bounds the call (180 s for a search); only connecting is bounded here.
+ timeout = httpx.Timeout(None, connect=CONNECT_TIMEOUT_S)
+ try:
+ if self.client is not None:
+ response = await self.client.post(url, json=body, headers=headers, timeout=timeout)
+ else:
+ # The Model Hub gateway is loopback: an environment or system proxy must never carry it.
+ async with httpx.AsyncClient(timeout=timeout, trust_env=False) as client:
+ response = await client.post(url, json=body, headers=headers)
+ except httpx.HTTPError as error:
+ return _failed(f"the gateway could not run the call ({type(error).__name__})")
+ if response.status_code != 200:
+ return _failed(f"the gateway refused the call (HTTP {response.status_code} {_error_code(response)})")
+ try:
+ return _hosted_result(self.spec.name, response.json())
+ except (TypeError, ValueError):
+ return _failed("the gateway answered with no hosted result")
-#: The hosted tools whose native results the adapters parse. A generated image arrives as base64 that history must
-#: never hold (§7.3), so ``image_generation`` joins with its media handling.
-PARSED_HOSTED_TOOLS = ("web_search", "x_search")
+def _failed(reason: str) -> HostedResult:
+ """A call that never reached an executor: a failed record, and no execution (§4.2)."""
+
+ return HostedResult(record=HostedRecord(status="failed", error=bounded_error(reason)))
+
+
+def _error_code(response: httpx.Response) -> str:
+ try:
+ error = response.json().get("error")
+ except (TypeError, ValueError, AttributeError):
+ return ""
+ code = error.get("code") or error.get("type") if isinstance(error, Mapping) else None
+ return code if isinstance(code, str) else ""
+
+
+def _hosted_result(tool: str, body: Any) -> HostedResult:
+ """The executor's answer, read with the transcript's own reader for ``ToolResultMessage.hosted``."""
+
+ if not isinstance(body, Mapping) or not isinstance(body.get("record"), Mapping):
+ raise ValueError("no hosted record")
+ hosted = {key: body[key] for key in ("record", "execution") if key in body}
+ message = message_from_dict(
+ {
+ "role": "tool_result",
+ "tool_call_id": "proxied",
+ "tool_name": tool,
+ "content": [],
+ "is_error": body["record"].get("status") in ("failed", "incomplete"),
+ "hosted": hosted,
+ }
+ )
+ if not isinstance(message, ToolResultMessage) or message.hosted is None:
+ raise ValueError("no hosted result")
+ return message.hosted
-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."""
+def hosted_tools(selection: Optional[ModelSelection], client: Optional[httpx.AsyncClient] = None) -> tuple[Tool, ...]:
+ """The Turn's hosted tools: every tool the user enabled, in Model Hub's order, whatever preflight's hop runs it as.
+ They lead the Turn's tools, so its last tool stays a local one whatever a hop renders them as, and the list stays
+ the same for the whole Turn."""
if selection is None:
return ()
- routes = selection.endpoint.hosted_tools
+ endpoint = selection.endpoint
return tuple(
- NativeHostedTool(hosted_tool_spec(name))
- for name, route in routes.items()
- if route.mode == "native" and name in PARSED_HOSTED_TOOLS
+ HostedTool(hosted_tool_spec(name), route.executor, endpoint, client)
+ for name, route in endpoint.hosted_tools.items()
+ if name in PARSED_HOSTED_TOOLS
)
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 599e820dd..984c9edf7 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -291,6 +291,12 @@ scenarios:
- tests/agent_core/ai/test_hosted_transform.py::test_every_hosted_call_is_one_result_that_shows_its_own_status
- tests/agent_core/ai/test_hosted_transform.py::test_the_posts_an_answer_cites_show_on_a_call_kept_in_place
- tests/agent_core/agent/test_context.py::test_a_hosted_call_counts_as_the_call_and_result_it_is_replayed_as_never_as_its_opaque_payload
+ - id: MH-HOSTED-VIBEY-004
+ name: A proxied hosted call runs on the executor bound for the Turn; its record and execution stay on the tool result and the model reads the record as text, a call that reached no executor as a failure
+ status: covered
+ kind: contract
+ layer: contract
+ test: tests/test_vibey_agent.py::test_a_proxied_hosted_call_runs_on_the_bound_executor_and_keeps_its_record
- id: MH-VIBEY-007
name: Vibey starts once with the user's Sources and built-in Agent models, seeded when its first Source exists
status: covered
diff --git a/tests/test_vibey_agent.py b/tests/test_vibey_agent.py
index 8bd714067..919df3c48 100644
--- a/tests/test_vibey_agent.py
+++ b/tests/test_vibey_agent.py
@@ -311,7 +311,7 @@ async def _unused_renderer(*_args) -> ToolResult:
class _Harness:
def __init__(
self, engine, tmp_path: Path, platform: str, scripts, *, tools=None, suite=None, language="en", session_id=SESSION,
- providers=None,
+ providers=None, gateway_client=None,
):
self.session_id = session_id
self.engine = engine
@@ -320,6 +320,7 @@ class _Harness:
self.controller = _Controller(engine, platform, language=language)
self.provider = ScriptedProvider(scripts)
self.providers = providers or (lambda protocol: self.provider)
+ self.gateway_client = gateway_client
self.jobs = FakeJobHost()
self.tools = list(tools or [FakeTool("echo")])
self.suite = suite or ToolSuite(
@@ -339,6 +340,7 @@ class _Harness:
providers=self.providers,
tool_suite=self.suite,
state_dir=self.tmp_path / "agent_core",
+ gateway_client=self.gateway_client,
)
self.controller.agent = agent
self.agent = agent
@@ -2427,7 +2429,7 @@ async def test_a_hop_resolved_native_hosted_tool_reaches_the_gateway_pinned_to_i
) -> 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."""
+ its include values, on a request pinned to the hop's Source; a proxied tool goes out as its function."""
import httpx
from modules.agents.vibey.models import registry_providers
@@ -2463,9 +2465,10 @@ async def test_a_hop_resolved_native_hosted_tool_reaches_the_gateway_pinned_to_i
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.
+ # The hosted tools lead the Turn's tools: the native one as the provider's declaration, the proxied one as its
+ # canonical function.
assert sent["tools"][0] == declaration
- assert all(tool.get("name") != "x_search" and tool.get("type") != "x_search" for tool in sent["tools"])
+ assert sent["tools"][1]["name"] == "x_search" and sent["tools"][1].get("type", "function") == "function"
assert set(include) <= set(sent.get("include", []))
assert harness.controller.im_client.sent == ["hi"]
@@ -2527,6 +2530,98 @@ async def test_a_native_search_is_kept_as_one_hosted_call_and_replayed_next_turn
assert "https://avibe.bot/r" in replayed[1]["output"]
+_EXECUTOR = {"source_id": "src_executor01", "model_id": "grok-4.6"}
+
+
+def _anthropic_reply(*blocks: str, stop_reason: str) -> str:
+ """An Anthropic stream of whole content blocks, each given as its ``content_block_start`` JSON."""
+ events = ['data: {"type":"message_start","message":{"usage":{}}}\n\n']
+ for index, block in enumerate(blocks):
+ events.append(f'data: {{"type":"content_block_start","index":{index},"content_block":{block}}}\n\n')
+ events.append(f'data: {{"type":"content_block_stop","index":{index}}}\n\n')
+ events.append(f'data: {{"type":"message_delta","delta":{{"stop_reason":"{stop_reason}"}}}}\n\n')
+ events.append('data: {"type":"message_stop"}\n\n')
+ return "".join(events)
+
+
+ ("status", "answer", "is_error", "seen"),
+ [
+ (
+ 200,
+ {
+ "record": {"status": "completed", "sources": [{"url": "https://avibe.bot/r", "title": "Release", "snippet": "v3.2"}]},
+ "execution": {
+ "mode": "proxy",
+ "executor_origin": {"provider": "xai", "api": "openai_responses", "model": "grok-4.6"},
+ "executor_source_id": "src_executor01",
+ "executor_billing": "metered",
+ },
+ },
+ False,
+ "https://avibe.bot/r",
+ ),
+ (200, {"record": {"status": "failed", "error": "no Source is verified for web search", "sources": []}}, True, "[web_search failed: no Source is verified"),
+ (404, {"type": "error", "error": {"type": "not_found", "code": "unknown_tool"}}, True, "HTTP 404 unknown_tool"),
+ ],
+ ids=["executed", "no-executor", "refused"],
+)
+async def test_a_proxied_hosted_call_runs_on_the_bound_executor_and_keeps_its_record(
+ engine, session, tmp_path, published, status, answer, is_error, seen
+) -> None:
+ """MH-HOSTED-VIBEY-004 (vibey-hosted-tools.md §3.4): on a hop that does not run the tool natively, the model calls
+ the same-named function; Vibey asks the gateway's executor bound for the Turn, keeps the record and execution on
+ the tool result, and the model reads the record as text. A call that never reached an executor is a failed
+ record, never an empty success."""
+ import httpx
+
+ from modules.agents.vibey.models import registry_providers
+
+ served = json.dumps(
+ {"provider": "anthropic", "api": "anthropic", "model": "claude-opus-5-5", "source": "src_upstream01"},
+ separators=(",", ":"),
+ )
+ call = '{"type":"tool_use","id":"toolu_1","name":"web_search","input":{"query":"avibe release"}}'
+ replies = [
+ _anthropic_reply(call, stop_reason="tool_use"),
+ _anthropic_reply('{"type":"text","text":"done"}', stop_reason="end_turn"),
+ ]
+ models: list[dict] = []
+ executed: list[httpx.Request] = []
+
+ def gateway(request: httpx.Request) -> httpx.Response:
+ if request.url.path == "/vibey/v1/hosted-tools/web_search":
+ executed.append(request)
+ return httpx.Response(status, json=answer)
+ models.append(json.loads(request.content))
+ return httpx.Response(
+ 200, headers={"content-type": "text/event-stream", "x-avibe-served-hop": served}, text=replies.pop(0)
+ )
+
+ async with httpx.AsyncClient(transport=httpx.MockTransport(gateway)) as client:
+ harness = _Harness(
+ engine,
+ tmp_path,
+ "telegram",
+ [],
+ providers=registry_providers(media_loader=None, client=client),
+ gateway_client=client,
+ )
+ harness.controller.hub_hosted_tools = {"web_search": {"mode": "proxy", "executor": _EXECUTOR, "replay": False}}
+ await harness.agent.handle_message(harness.request("search"))
+
+ (request,) = executed
+ assert json.loads(request.content) == {"arguments": {"query": "avibe release"}, "executor": _EXECUTOR}
+ assert request.headers["authorization"] == "Bearer hub-token"
+ # The proxied tool is the canonical function, first among the Turn's tools.
+ assert models[0]["tools"][0]["name"] == "web_search" and "input_schema" in models[0]["tools"][0]
+ result = next(row.message for row in await harness.context_rows() if isinstance(row.message, ToolResultMessage))
+ assert result.is_error is is_error and result.hosted is not None
+ assert (result.hosted.execution is not None) == (not is_error)
+ sent = models[1]["messages"][-1]["content"][0]
+ assert sent["type"] == "tool_result" and seen in json.dumps(sent)
+
+
_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}