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(model-hub): verify hosted tools with a user-started call probe on the exact Source (#2578)

Call White9f3917b7f261
diff --git a/core/handlers/model_hub/hosted_probe.py b/core/handlers/model_hub/hosted_probe.py
new file mode 100644
index 000000000..9a21a2bc3
--- /dev/null
+++ b/core/handlers/model_hub/hosted_probe.py
@@ -0,0 +1,313 @@
+"""The hosted-tool call probe (``vibey-hosted-tools.md`` §3.2, capability model §3.3).
+
+A probe is the production request. Vibey's own builder makes it, from a probe
+resolution that pins the probed (Source, model) and carries the overlay's native
+declaration whatever the current evidence. Two things differ from a real turn:
+the transcript is one fixed user message, and on protocols that allow it the
+hosted tool is forced. Vibey's adapter reads the response, so a result is
+recognized only as the ``HostedToolBlock`` a real turn would keep. Nothing here
+parses a provider's wire format.
+
+Every request the adapter sends runs on exactly one Source through Model Hub's
+own invocation, with no route and no failover. This module only builds the
+request, serves each pinned call to the adapter, and names the outcome; the
+service owns the calls themselves.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from dataclasses import dataclass
+from typing import Any, AsyncIterator, Awaitable, Callable, Literal, Optional, Protocol
+
+import httpx
+
+from config.v2_config import ModelHubSourceConfig
+from core.agent_core.ai.provider import (
+ RETRYABLE_ERROR_KINDS,
+ Done,
+ HostedToolRoute,
+ ModelEndpoint,
+ ModelRequest,
+ ProviderError,
+)
+from core.agent_core.ai.registry import create_adapter
+from core.agent_core.cancel import CancelToken
+from core.agent_core.messages import HostedToolBlock, TextBlock, UserMessage
+from core.agent_core.tools.hosted import hosted_tool_spec as canonical_tool_spec
+from vibe.backend_model_catalog import HostedToolSpec
+
+from .adapter import InvokeHandle, RawCallOutcome, RawOutcomeKind
+from .classification import classify_outcome
+from .evidence_rules import LearnedEvidence
+from .stream_wire import ProtocolUsageReport
+
+ProbeOutcome = Literal["verified", "unsupported", "inconclusive", "transient"]
+
+# The tools whose results Vibey's adapters parse today. ``image_generation``
+# joins when its results are parsed: until then a probe could never see one,
+# and every image probe would read as the model not using the tool.
+PROBED_TOOLS: tuple[str, ...] = ("web_search", "x_search")
+
+_MESSAGES = {
+ "web_search": "Search the web for 'Avibe local-first agent OS' and reply with the first result's URL.",
+ "x_search": "Search X for posts about 'Avibe local-first agent OS' and reply with the first post's URL.",
+}
+_SYSTEM = "You check that a tool works: use it, then answer in one line."
+# Room for a reasoning model to think, call the tool and answer in one line; a hop whose Vibey turns ask for less
+# gets that instead.
+PROBE_MAX_OUTPUT_TOKENS = 4096
+# What one call probe is estimated to use, for its cost hint before it runs: the
+# fixed message and the tool's results in context, a one-line answer, and one
+# search (an X search reads up to ten posts). The 2026-10-13 spike measured
+# such probes at about $0.01-0.11.
+ESTIMATED_USAGE = ProtocolUsageReport.of(input_tokens=8000, cached_input_tokens=0, output_tokens=500)
+ESTIMATED_COUNTS: dict[str, dict[str, int]] = {
+ "web_search": {"web_search_calls": 1, "web_search_requests": 1},
+ "x_search": {"x_search_calls": 1, "x_posts_fetched": 10, "x_users_fetched": 0},
+}
+# The adapter's requests never leave this process: the transport serves each
+# with a Model Hub call pinned to the probed Source.
+_IN_PROCESS_URL = "http://model-hub-probe.invalid"
+# The classified failures a later try may not meet: a dropped connection or a
+# timeout, an overload or 5xx, and a rate limit.
+_TRANSIENT_REASONS = frozenset({"network", "server_error", "rate_limited"})
+
+
+def probe_request(
+ source: ModelHubSourceConfig, model_id: str, tool: str, spec: HostedToolSpec, *, max_tokens: int
+) -> ModelRequest:
+ """The call probe for ``tool`` on this Source and model, as Vibey would send it natively.
+
+ It matches a real turn's declaration, include and provider shaping, and Vibey's own adapter and transport send
+ it; ``max_tokens`` is the smallest output any Vibey turn on this hop would ask for, at most
+ ``PROBE_MAX_OUTPUT_TOKENS``.
+ """
+
+ route = HostedToolRoute(
+ mode="native",
+ executor=None,
+ replay=False,
+ declaration=spec.declaration,
+ include=tuple(spec.include),
+ )
+ return ModelRequest(
+ # As the Vibey launch builds a hop's endpoint: the Source's vendor is its provider, which shapes the
+ # request (Anthropic's one-hour cache lifetime), and the model is the one the Source serves.
+ endpoint=ModelEndpoint(
+ protocol=source.protocol, # type: ignore[arg-type]
+ base_url=_IN_PROCESS_URL,
+ model_id=model_id,
+ token="",
+ provider=source.vendor,
+ source_id=source.id,
+ hosted_tools={tool: route},
+ ),
+ system=_SYSTEM,
+ messages=(UserMessage(content=(TextBlock(text=_MESSAGES[tool]),)),),
+ tools=(canonical_tool_spec(tool),),
+ max_tokens=max_tokens,
+ # Current Claude models refuse a forced choice, so Anthropic is asked in the message alone.
+ tool_choice=None if source.protocol == "anthropic" else tool,
+ )
+
+
+# A probe sends at most this many requests: its own, and the one resend an adapter makes when an endpoint refuses
+# a field before answering (Anthropic's one-hour cache lifetime). Only an answered request runs the model.
+MAX_PROBE_REQUESTS = 2
+
+class CallResult(Protocol):
+ """How one pinned call settled: the Source it ran on, its outcome, and whether it retired that Source's own
+ pending verification marker (``ModelHubService._user_test_call``)."""
+
+ source: ModelHubSourceConfig
+ outcome: RawCallOutcome
+ retired_own_marker: bool
+
+
+# Model Hub's one pinned call for a request body: it opens the call on the probed Source, hands it to the reader,
+# and settles and meters it once the reader returns.
+PinnedCall = Callable[[dict[str, Any], Callable[[InvokeHandle], Awaitable[None]]], Awaitable[CallResult]]
+
+
+@dataclass(frozen=True)
+class ProbeCall:
+ """One request the adapter sent, and how Model Hub's pinned call for it ended."""
+
+ body: dict[str, Any]
+ source: ModelHubSourceConfig
+ outcome: RawCallOutcome
+ # Proof that this call's own success retired the Source's pending verification.
+ retired_own_marker: bool = False
+
+
+class _CallStream(httpx.AsyncByteStream):
+ """The adapter's side of one pinned call: what the call's own task read from its stream, in order.
+
+ Only that task ever iterates the call's stream, so the call can settle (and
+ close it) whatever the adapter is doing, a deadline included.
+ """
+
+ def __init__(self, chunks: asyncio.Queue, released: asyncio.Event) -> None:
+ self._chunks = chunks
+ self._released = released
+
+ async def __aiter__(self) -> AsyncIterator[bytes]:
+ while (item := await self._chunks.get()) is not None:
+ if isinstance(item, BaseException):
+ raise item
+ yield item
+
+ async def aclose(self) -> None:
+ self._released.set()
+
+
+async def _pump(handle: InvokeHandle, chunks: asyncio.Queue) -> None:
+ """Read the call's stream into ``chunks`` and always end the queue: on a failure the adapter meets the same error
+ where it would have read it."""
+
+ try:
+ if handle.stream is not None:
+ async for chunk in handle.stream:
+ chunks.put_nowait(chunk)
+ except Exception as failed:
+ chunks.put_nowait(failed)
+ finally:
+ chunks.put_nowait(None)
+
+
+def _failure_body(outcome: RawCallOutcome) -> dict[str, Any]:
+ """What an adapter reads for a call that failed before any output: the upstream's status and its own words."""
+
+ message = outcome.upstream_detail or outcome.redacted_message or "the upstream call failed"
+ return {"type": "error", "error": {"type": outcome.error_type or outcome.error_code or "api_error", "message": message}}
+
+
+class PinnedCallTransport(httpx.AsyncBaseTransport):
+ """Serves every request the adapter sends with its own pinned call of the probed Source.
+
+ The adapter runs exactly as it does for a real turn, resend included, and
+ each of its requests is one Model Hub call on that Source alone, with no
+ route and no failover. ``calls`` records them in order.
+ """
+
+ def __init__(self, call: PinnedCall) -> None:
+ self._call = call
+ # In request order: each request reserves its place before its call settles.
+ self._slots: list[Optional[ProbeCall]] = []
+ self._tasks: list[asyncio.Task[None]] = []
+ self._releases: list[asyncio.Event] = []
+
+ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
+ if len(self._tasks) >= MAX_PROBE_REQUESTS:
+ raise RuntimeError("a probe sends at most two requests")
+ body = json.loads(await request.aread())
+ slot = len(self._slots)
+ self._slots.append(None)
+ opened: asyncio.Future[InvokeHandle] = asyncio.get_running_loop().create_future()
+ released = asyncio.Event()
+ self._releases.append(released)
+ chunks: asyncio.Queue = asyncio.Queue()
+
+ async def read(handle: InvokeHandle) -> None:
+ opened.set_result(handle)
+ # The call's own reader runs until the stream ends or the adapter closes its side, as production closes a
+ # response it has finished with; it is always over before the call settles and closes the stream.
+ pump = asyncio.create_task(_pump(handle, chunks))
+ closed = asyncio.create_task(released.wait())
+ try:
+ await asyncio.wait({pump, closed}, return_when=asyncio.FIRST_COMPLETED)
+ finally:
+ pump.cancel()
+ closed.cancel()
+ await asyncio.gather(pump, closed, return_exceptions=True)
+ await released.wait()
+
+ async def run() -> None:
+ settled = await self._call(body, read)
+ self._slots[slot] = ProbeCall(body, settled.source, settled.outcome, settled.retired_own_marker)
+
+ task = asyncio.create_task(run())
+ self._tasks.append(task)
+ await asyncio.wait({opened, task}, return_when=asyncio.FIRST_COMPLETED)
+ if not opened.done() and task.exception() is not None:
+ # Refused before any call opened (the Source changed, the engine is down): ``settle`` raises it.
+ raise RuntimeError("the probe's call did not open")
+ if opened.done() and opened.result().stream is not None:
+ return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=_CallStream(chunks, released))
+ # The call failed before any output, or timed out before it opened: answer as the upstream did, so the
+ # adapter decides what to do as it would for a real turn.
+ released.set()
+ await task
+ outcome = self._slots[slot].outcome # type: ignore[union-attr]
+ status = outcome.http_status or (504 if outcome.kind is RawOutcomeKind.TIMEOUT else 502)
+ return httpx.Response(status, json=_failure_body(outcome))
+
+ @property
+ def calls(self) -> list[ProbeCall]:
+ """Every request the adapter sent whose call settled, in the order the adapter sent them."""
+
+ return [call for call in self._slots if call is not None]
+
+ async def settle(self) -> None:
+ """Let every call finish settling; re-raise the first one Model Hub refused to open."""
+
+ for released in self._releases:
+ released.set()
+ results = await asyncio.gather(*self._tasks, return_exceptions=True)
+ for result in results:
+ if isinstance(result, BaseException):
+ raise result
+
+
+async def run_probe(request: ModelRequest, call: PinnedCall) -> tuple[Done | ProviderError | None, list[ProbeCall]]:
+ """Run Vibey's adapter for ``request`` over pinned calls; its terminal event and the calls it made."""
+
+ transport = PinnedCallTransport(call)
+ terminal: Done | ProviderError | None = None
+ try:
+ async with httpx.AsyncClient(transport=transport) as client:
+ adapter = create_adapter(request.endpoint.protocol, client=client, gateway=False)
+ async for event in adapter.stream(request, CancelToken()):
+ if isinstance(event, (Done, ProviderError)):
+ terminal = event
+ finally:
+ await transport.settle()
+ return terminal, transport.calls
+
+
+def call_outcome(
+ tool: str,
+ terminal: Done | ProviderError | None,
+ outcome: RawCallOutcome,
+ learned: Optional[LearnedEvidence],
+) -> ProbeOutcome:
+ """What one call probe shows about ``tool`` on its Source and model.
+
+ * ``unsupported``: only a 400 that names the tool's declared type, through the same narrow rule real requests
+ learn from;
+ * ``verified``: a completed response that carries the tool's own completed result;
+ * ``inconclusive``: a completed response without one (the model may simply not have used the tool, which looks
+ like a silent drop), or a request that failed for another reason;
+ * ``transient``: an overload, a 5xx, a rate limit, a dropped connection or a timeout.
+
+ Only the first two are evidence. A call that failed before any output has no
+ ``terminal``; Model Hub's own reading of its ``outcome`` says which failure it was.
+ """
+
+ if learned is not None and (learned.feature.kind, learned.feature.name, learned.feature.aspect) == (
+ "hosted_tool", tool, "call"
+ ):
+ return "unsupported"
+ if isinstance(terminal, Done):
+ used = any(
+ isinstance(block, HostedToolBlock) and block.tool == tool and block.record.status == "completed"
+ for block in terminal.message.content
+ )
+ return "verified" if used else "inconclusive"
+ if terminal is not None:
+ # By what failed, not by ``retryable``: an adapter never retries a response that already streamed output,
+ # but a dropped connection or an overload is just as transient for a probe the user can run again.
+ return "transient" if terminal.kind in RETRYABLE_ERROR_KINDS else "inconclusive"
+ return "transient" if classify_outcome(outcome).reason in _TRANSIENT_REASONS else "inconclusive"
diff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.py
index aa598cd2e..f9f4cd27d 100644
--- a/core/handlers/model_hub/hosted_tools.py
+++ b/core/handlers/model_hub/hosted_tools.py
@@ -95,12 +95,30 @@ def _verified(context: _Context, source: ModelHubSourceConfig, model_id: str, fe
return view.status == "verified"
+def runs_on(source: ModelHubSourceConfig, model_id: str, tool: str, *, spec_for: SpecLookup) -> Optional[HostedToolSpec]:
+ """The declaration ``tool`` runs with on this (Source, model), or None where it may not run at all.
+
+ One rule for every place that asks: the Tools-tab candidates, a chosen
+ executor, the executor a turn binds, a hop's native mode and a probe's
+ target. The Source is a hub Source with an eligible credential and an
+ untranslated path, it serves the model as its admission rule says (an
+ API-key Source serves any model it does not list as a retired tombstone; a
+ subscription only its listed models), and the overlay declares the tool for
+ it.
+ """
+
+ if source.supply_channel != "hub" or not credential_eligible(source) or not untranslated(source):
+ return None
+ listed = next((model for model in source.models if model.id == model_id), None)
+ if (listed.retired if listed is not None else source.kind != "api_key"):
+ return None
+ return spec_for(source.vendor, source.protocol, model_id, tool)
+
+
def _runnable_spec(
context: _Context, source: ModelHubSourceConfig, model_id: str, tool: str
) -> Optional[HostedToolSpec]:
- if not credential_eligible(source) or not untranslated(source):
- return None
- spec = context.spec_for(source.vendor, source.protocol, model_id, tool)
+ spec = runs_on(source, model_id, tool, spec_for=context.spec_for)
if spec is None or not _verified(context, source, model_id, EvidenceFeature.hosted(tool, "call")):
return None
return spec
@@ -207,16 +225,23 @@ def _price_payload(price: Any) -> dict[str, Any] | None:
}
-def _candidate_sources(config: ModelHubConfig) -> list[ModelHubSourceConfig]:
- """Hub Sources that may run hosted tools, Vibey's Source order first."""
+def _candidate_targets(
+ config: ModelHubConfig, tool: str, *, spec_for: SpecLookup
+) -> list[tuple[ModelHubSourceConfig, str, HostedToolSpec]]:
+ """The (Source, model)s the Tools tab lists for ``tool``, with its declaration on each, Vibey's Source order first.
+
+ Every model a Source lists that ``runs_on`` admits. A passthrough model an
+ API-key Source may also serve is not listed: there is nothing to show for it.
+ """
by_id = {source.id: source for source in config.sources}
ordered = [by_id[source_id] for source_id in config.agents["vibey"].sources.order if source_id in by_id]
ordered += [source for source in config.sources if source not in ordered]
return [
- source
+ (source, model.id, spec)
for source in ordered
- if source.supply_channel == "hub" and credential_eligible(source) and untranslated(source)
+ for model in source.models
+ if (spec := runs_on(source, model.id, tool, spec_for=spec_for)) is not None
]
@@ -227,42 +252,44 @@ def hosted_tools_status(
spec_for: SpecLookup,
engine: str,
now: datetime,
+ probe_estimate: Callable[[ModelHubSourceConfig, str, str], Optional[dict[str, Any]]],
shape: int = HOSTED_PROBE_SHAPE,
) -> dict[str, Any]:
"""What the Tools tab reads: each tool's toggle and where it can run, with its evidence.
``candidates`` lists every (Source, model) the overlay offers the tool on,
- on an eligible credential and an untranslated path. ``reverify`` counts
+ on an eligible credential and an untranslated path, with what probing it
+ would cost (``probe_estimate``, None when unknown). ``reverify`` counts
hosted-tool probe evidence that needs a user re-verify: ``engine_upgraded``
for evidence taken on another engine or probe shape (it routes as unknown),
``aged`` for evidence that is only old (it still routes).
"""
tools = []
+ # Every (Source, model, tool) the Tools tab lists, so a re-verify it counts is one it can offer.
+ listed: set[tuple[str, str, str]] = set()
for tool in MODEL_HUB_HOSTED_TOOLS:
toggle = config.hosted_tools.get(tool)
candidates = []
- for source in _candidate_sources(config):
- for model in source.models:
- spec = spec_for(source.vendor, source.protocol, model.id, tool)
- if spec is None:
- continue
- views = {
- aspect: evidence.view(
- source, model.id, EvidenceFeature.hosted(tool, aspect), engine=engine, shape=shape, now=now
- )
- for aspect in HOSTED_TOOL_ASPECTS[tool]
- }
- candidates.append(
- {
- "source_id": source.id,
- "model_id": model.id,
- "call": _evidence_payload(views["call"]),
- "replay": _evidence_payload(views["replay"]) if "replay" in views else None,
- "billing": source.billing,
- "price": _price_payload(spec.price),
- }
+ for source, model_id, spec in _candidate_targets(config, tool, spec_for=spec_for):
+ listed.add((source.id, model_id, tool))
+ views = {
+ aspect: evidence.view(
+ source, model_id, EvidenceFeature.hosted(tool, aspect), engine=engine, shape=shape, now=now
)
+ for aspect in HOSTED_TOOL_ASPECTS[tool]
+ }
+ candidates.append(
+ {
+ "source_id": source.id,
+ "model_id": model_id,
+ "call": _evidence_payload(views["call"]),
+ "replay": _evidence_payload(views["replay"]) if "replay" in views else None,
+ "billing": source.billing,
+ "price": _price_payload(spec.price),
+ "probe_estimate": probe_estimate(source, model_id, tool),
+ }
+ )
chosen = (toggle.executor.source_id, toggle.executor.model_id) if toggle and toggle.executor else None
tools.append(
{
@@ -278,7 +305,12 @@ def hosted_tools_status(
reverify = {"engine_upgraded": 0, "aged": 0}
for record in evidence.records():
source = live.get(record.source_id)
- if record.feature.kind != "hosted_tool" or record.basis != "probe" or source is None:
+ if (
+ record.feature.kind != "hosted_tool"
+ or record.basis != "probe"
+ or source is None
+ or (record.source_id, record.model_id, record.feature.name) not in listed
+ ):
continue
stale = evidence.view(
source, record.model_id, record.feature, engine=engine, shape=shape, now=now
@@ -304,9 +336,8 @@ def parse_hosted_tool_setting(
) -> ModelHubHostedToolConfig:
"""Validate one ``PUT /api/models/hosted-tools/<tool>`` body against the current config.
- The executor must be a hub Source with that model, an eligible credential,
- an untranslated path, and the overlay's declaration for the tool. Whether
- it is verified is evidence, decided at every resolution, never here.
+ The executor must be a ``hosted_tool_target``. Whether it is verified is
+ evidence, decided at every resolution, never here.
"""
if tool not in MODEL_HUB_HOSTED_TOOLS:
@@ -316,15 +347,20 @@ def parse_hosted_tool_setting(
except ValueError:
raise HostedToolSettingRefused("invalid_parameter", 400) from None
executor = setting.executor
- if executor is None:
- return setting
- source = next((item for item in config.sources if item.id == executor.source_id), None)
+ if executor is not None:
+ hosted_tool_target(config, tool, executor.source_id, executor.model_id, spec_for=spec_for)
+ return setting
+
+
+def hosted_tool_target(
+ config: ModelHubConfig, tool: str, source_id: str, model_id: str, *, spec_for: SpecLookup
+) -> tuple[ModelHubSourceConfig, HostedToolSpec]:
+ """The Source a tool may run on with this model, as executor or for a probe, and its declaration there (``runs_on``)."""
+
+ source = next((item for item in config.sources if item.id == source_id), None)
if source is None:
raise HostedToolSettingRefused("source_not_found", 404)
- if (
- source not in _candidate_sources(config)
- or executor.model_id not in {model.id for model in source.models}
- or spec_for(source.vendor, source.protocol, executor.model_id, tool) is None
- ):
+ spec = runs_on(source, model_id, tool, spec_for=spec_for)
+ if spec is None:
raise HostedToolSettingRefused("invalid_parameter", 400)
- return setting
+ return source, spec
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index def435213..bf0d7ae46 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -219,6 +219,8 @@ async def dispatch_model_hub_rpc(
return await asyncio.to_thread(service.hosted_tools_status)
if operation == "set_hosted_tool":
return await service.set_hosted_tool(payload.get("tool"), payload.get("setting"))
+ if operation == "probe_hosted_tool":
+ return await service.probe_hosted_tool(payload.get("tool"), payload.get("target"))
if operation == "get_agent_chain":
return service.agent_chain(payload.get("backend"), payload.get("model_id"))
if operation == "get_agent_chains":
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index bf1970982..a3db52d57 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -12,7 +12,7 @@ from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timedelta, timezone
from pathlib import Path
-from typing import Any, Awaitable, Callable, Collection, Iterable, Literal, Mapping, Optional, Protocol, cast
+from typing import Any, Awaitable, Callable, Collection, Iterable, Literal, Mapping, NamedTuple, Optional, Protocol, cast
from sqlalchemy import func, literal_column, select
@@ -43,6 +43,7 @@ from config.v2_config import (
validate_model_hub_source_client_nonce,
)
from core.agent_auth_service import BackendLoginInProgressError
+from core.agent_core.ai.provider import Done, ModelCapabilities
from core.agent_core.ai.registry import sent_effort
from core.agent_core.messages import HostedCost
from core.os_errors import format_os_errno, local_error_detail
@@ -50,6 +51,7 @@ from core.services.settings import default_config
from storage.db import get_cached_sqlite_engine
from storage.models import MESSAGE_TURN_ID_SQL, agent_sessions, messages
from vibe.backend_model_catalog import (
+ HostedToolSpec,
PROTOCOL_REASONING_EFFORT_DEFAULTS,
builtin_display_name,
bundled_catalog_wire_efforts_by_model,
@@ -130,12 +132,19 @@ from .hosted_executor import (
provider_charges,
responses_result,
)
+from .hosted_probe import ESTIMATED_COUNTS as ESTIMATED_PROBE_COUNTS
+from .hosted_probe import ESTIMATED_USAGE as ESTIMATED_PROBE_USAGE
+from .hosted_probe import PROBE_MAX_OUTPUT_TOKENS, PROBED_TOOLS
+from .hosted_probe import call_outcome as hosted_call_outcome
+from .hosted_probe import probe_request as hosted_probe_request
+from .hosted_probe import run_probe as run_hosted_probe
from .hosted_tools import (
HOSTED_PROBE_SHAPE,
HostedToolSettingRefused,
credential_eligible,
untranslated,
engine_stamp,
+ hosted_tool_target,
hosted_tools_status,
parse_hosted_tool_setting,
resolve_hosted_tools,
@@ -338,6 +347,8 @@ AGENT_CHAIN_CONTRACT_VERSION = 12
PROBE_RESULT_CONTRACT_VERSION = 12
_SOURCE_DISCOVERY_TIMEOUT_SECONDS = 15
_SOURCE_PROBE_TIMEOUT_SECONDS = 60
+# A hosted-tool probe waits for the provider's search as well as the answer.
+_HOSTED_PROBE_TIMEOUT_SECONDS = 120
# Background inventory refresh. The first tick doubles as the startup delay, so
# a stale Source catches up shortly after boot without boot waiting on upstream.
_BACKGROUND_DISCOVERY_INTERVAL = timedelta(hours=6)
@@ -718,6 +729,16 @@ def _pin_unavailable() -> ModelHubError:
return ModelHubError(PIN_UNAVAILABLE_CODE, status=409)
+class UserTestCall(NamedTuple):
+ """One call a user asked for, as it settled (``ModelHubService._user_test_call``)."""
+
+ source: ModelHubSourceConfig
+ outcome: RawCallOutcome
+ elapsed_ms: int
+ # Whether this call's own success retired the pending verification it was made under.
+ retired_own_marker: bool
+
+
def _call_usage(outcome: RawCallOutcome | None, observed: ProtocolSSEState | None) -> ProtocolUsageReport | None:
"""The tokens one upstream call reported: its outcome's, else what was observed on the wire."""
@@ -5930,9 +5951,26 @@ class ModelHubService:
spec_for=hosted_tool_spec,
engine=self.engine_stamp,
now=self.now(),
+ probe_estimate=self._probe_estimate,
)
}
+ def _probe_estimate(self, source: ModelHubSourceConfig, model_id: str, tool: str) -> Optional[dict]:
+ """What one call probe of ``tool`` on this Source and model is estimated to cost; None when unknown.
+
+ Priced by the one pricing owner from the probe's nominal usage. A tool
+ that cannot be probed yet has no estimate.
+ """
+
+ if tool not in PROBED_TOOLS:
+ return None
+ cost = self.hosted_call_cost(
+ source, model_id, (tool,), usage=ESTIMATED_PROBE_USAGE, counts=ESTIMATED_PROBE_COUNTS[tool],
+ )
+ if cost is None:
+ return None
+ return {"basis": cost.basis} if cost.usd is None else {"basis": cost.basis, "usd": cost.usd}
+
async def set_hosted_tool(self, tool: str, payload: object) -> dict:
"""Replace one hosted tool's toggle and chosen executor; it applies from the next turn."""
@@ -7568,18 +7606,234 @@ class ModelHubService:
raise ModelHubError(reason, status=422)
return source
+ async def drain(handle: InvokeHandle) -> None:
+ if handle.stream is not None:
+ async for _chunk in handle.stream:
+ pass
+
+ source, outcome, elapsed_ms, _retired = await self._user_test_call(
+ source_id,
+ model_id,
+ selected,
+ # OpenCode preserves the request's explicit protocol and API keys
+ # have unrestricted origins.
+ lambda source: self._probe_request(source, model_id, "opencode", output_tokens=128),
+ stream=False,
+ origin="opencode",
+ consume=drain,
+ timeout=_SOURCE_PROBE_TIMEOUT_SECONDS,
+ )
+ succeeded = outcome.kind is RawOutcomeKind.SUCCESS
+ return {
+ "source_id": source.id,
+ "model_id": model_id,
+ "protocol": source.protocol,
+ "reachable": succeeded,
+ "latency_ms": elapsed_ms,
+ "error": None if succeeded else self._test_call_failure(outcome),
+ }
+
+ async def probe_hosted_tool(self, tool: str, payload: object) -> dict:
+ """Run the call probe of one hosted tool on one (Source, model), and record what it shows.
+
+ A user action starts every probe; nothing calls this on its own. Every
+ request it sends is its own call pinned to the probed Source, with no
+ route and no failover. Only ``verified``
+ and ``unsupported`` are evidence; an inconclusive or transient probe
+ leaves the current record as it is (``vibey-hosted-tools.md`` §3.2).
+ """
+
+ if (
+ tool not in PROBED_TOOLS
+ or not isinstance(payload, dict)
+ or set(payload) != {"source_id", "model_id"}
+ or not isinstance(payload["source_id"], str)
+ or not payload["source_id"]
+ ):
+ raise ModelHubError("invalid_parameter", status=400)
+ # The model as routing and evidence know it: the probe sends and records exactly that identity.
+ source_id, model_id = payload["source_id"], canonical_model_id(payload["model_id"])
+ if model_id is None:
+ raise ModelHubError("invalid_parameter", status=400)
+
+ def target(config: ModelHubConfig) -> tuple[ModelHubSourceConfig, HostedToolSpec]:
+ try:
+ return hosted_tool_target(config, tool, source_id, model_id, spec_for=hosted_tool_spec)
+ except HostedToolSettingRefused as refused:
+ raise ModelHubError(refused.code, status=refused.status) from None
+
+ # Reading the config parses the whole file, so that alone runs off the controller loop. Everything after
+ # reads the snapshot in memory, and recovery state stays on the loop that owns it.
+ config = await asyncio.to_thread(self.store.load)
+ source, spec = target(config)
+ request = hosted_probe_request(
+ source, model_id, tool, spec, max_tokens=self._probe_output_budget(config, source.id, model_id),
+ )
+
+ def selected(config: ModelHubConfig) -> ModelHubSourceConfig:
+ current, current_spec = target(config)
+ # The probe was built for this protocol and declaration; it is never sent as anything else.
+ if current.protocol != source.protocol or current_spec.declaration != spec.declaration:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ return current
+
+ async def pinned_call(body: dict, read: Callable[[InvokeHandle], Awaitable[None]]):
+ return await self._user_test_call(
+ source_id,
+ model_id,
+ selected,
+ lambda source: ModelHubRequest(body, protocol=source.protocol),
+ stream=True,
+ origin="vibey",
+ consume=read,
+ timeout=_HOSTED_PROBE_TIMEOUT_SECONDS,
+ )
+
+ terminal, calls = await run_hosted_probe(request, pinned_call)
+ if not calls:
+ logger.warning("Model Hub's %s probe sent no request", tool)
+ raise ModelHubError("invalid_parameter", status=400)
+ # Only the request the response ended on speaks for the tool: a resend that completes outranks a refusal
+ # of the request it replaced.
+ last = calls[-1]
+ learned = (
+ learn_from_rejection(
+ last.body,
+ last.outcome.rejection,
+ request_protocol=last.source.protocol,
+ source=last.source,
+ model_id=model_id,
+ spec_for=hosted_tool_spec,
+ )
+ if last.outcome.rejection is not None
+ else None
+ )
+ verdict = hosted_call_outcome(tool, terminal, last.outcome, learned)
+ # The evidence follows the Source as it reads now. The one change a probe may see is its own: its call's
+ # success retired the pending verification it was made under, which settlement proves. Any other change
+ # during the probe (a new credential, endpoint, protocol, or a marker another grant's call retired) means
+ # the probe vouches for nothing there.
+ current = await asyncio.to_thread(self.store.load)
+ live = next((item for item in current.sources if item.id == last.source.id), None)
+ attributable = live is not None and (
+ identity_digest(live) == identity_digest(last.source)
+ or (
+ last.retired_own_marker
+ and identity_digest(replace(last.source, verification_pending=None)) == identity_digest(live)
+ )
+ )
+ if verdict in ("verified", "unsupported") and attributable:
+ try:
+ await asyncio.to_thread(
+ self.capability_evidence.write,
+ EvidenceRecord(
+ source_id=live.id,
+ model_id=model_id,
+ feature=EvidenceFeature.hosted(tool, "call"),
+ status=verdict,
+ basis="probe",
+ observed_at=self.now(),
+ engine=self.engine_stamp,
+ shape=HOSTED_PROBE_SHAPE,
+ source_identity=identity_digest(live),
+ detail=learned.detail if verdict == "unsupported" and learned is not None else None,
+ ),
+ live=current.sources,
+ )
+ except (OSError, ValueError):
+ # Evidence is advisory state: the status read below shows what was kept.
+ logger.warning("Model Hub could not record the %s probe result", tool, exc_info=True)
+ return {
+ "probe": {
+ "tool": tool,
+ "source_id": last.source.id,
+ "model_id": model_id,
+ "call": {
+ "outcome": verdict,
+ # Why a call that never completed failed, as the Source test shows it.
+ "error": (
+ self._test_call_failure(last.outcome)
+ if verdict != "unsupported" and not isinstance(terminal, Done)
+ else None
+ ),
+ },
+ # The replay probe sends the call's native payload back, which
+ # Vibey's adapters do not do yet.
+ "replay": None,
+ },
+ **await asyncio.to_thread(self.hosted_tools_status),
+ }
+
+ def _probe_output_budget(self, config: ModelHubConfig, source_id: str, model_id: str) -> int:
+ """The smallest output any Vibey turn on this hop would ask for, at most the probe's own ceiling.
+
+ A Vibey turn asks for its menu model's ``output_budget``, so a probe on a
+ hop several menu models route to takes the smallest of theirs, and one
+ no menu model routes to takes the budget of a model nothing describes.
+ """
+
+ from modules.agents.vibey.context import output_budget
+
+ now = self.now()
+ unavailable = self._unavailable_native_sources(config, "vibey")
+ # ``config`` is the current snapshot, so recovery reads it directly rather than loading another.
+ live_recovery = self.recovery.annotations(config)
+ budgets = [
+ output_budget(ModelCapabilities(context_window=model.context_window, max_output_tokens=model.max_output_tokens))
+ for model in config.agents["vibey"].models
+ if any(
+ hop.source_id == source_id and hop.model_id == model_id
+ for hop in resolve_model_hub_turn(
+ config, "vibey", model.id, now=now, unavailable_source_ids=unavailable, live_recovery=live_recovery,
+ ).inspected_hops
+ )
+ ]
+ return min([PROBE_MAX_OUTPUT_TOKENS, *(budgets or [output_budget(ModelCapabilities())])])
+
+ def _test_call_failure(self, outcome: RawCallOutcome) -> str:
+ """A failed user test call's detail key, for display only: it blocks nothing and changes no route state."""
+
+ decision = classify_outcome(outcome)
+ if decision.action == "refresh":
+ decision = ResolutionDecision("fallback", reason="credential_revoked")
+ return self._probe_failure(outcome, decision, recovery_managed=False)[0]
+
+ async def _user_test_call(
+ self,
+ source_id: str,
+ model_id: str,
+ selected: Callable[[ModelHubConfig], ModelHubSourceConfig],
+ request: Callable[[ModelHubSourceConfig], ModelHubRequest],
+ *,
+ stream: bool,
+ origin: str,
+ consume: Callable[[InvokeHandle], Awaitable[None]],
+ timeout: float,
+ ) -> UserTestCall:
+ """One call a user asked for, on exactly this Source and model: no Agent route, no failover.
+
+ ``selected`` re-checks the Source on every snapshot it is invoked from,
+ and ``consume`` reads the opened call. The call is settled whatever
+ happens: a success counts as the retry a cooldown waits for and verifies
+ the credential, a failure changes no route state, and the call is
+ metered. Returns the Source as invoked, its outcome, its latency, and
+ whether this call retired the Source's pending verification itself.
+ """
+
handle = None
outcome = None
source = None
admitted_at = None
attempt_generation = PRE_ATTEMPT_SETTLEMENT_GENERATION
+ cancelled_observed: ProtocolSSEState | None = None
+ retired_own_marker = False
async def invoke_selected() -> None:
- nonlocal source, handle, outcome, admitted_at, attempt_generation
+ nonlocal source, handle, outcome, admitted_at, attempt_generation, cancelled_observed
# Bound local waiting too, but never call it a model failure before
# the adapter has actually admitted this Source/model invocation.
async with self._mutation_lock:
- selected(self.store.load())
+ selected(await asyncio.to_thread(self.store.load))
while True:
await self._prepare_engine_for_demand()
await self._mutation_lock.acquire()
@@ -7602,32 +7856,38 @@ class ModelHubService:
try:
source = ModelHubSourceConfig.from_payload(
- selected(self.store.load()).to_payload(),
+ selected(await asyncio.to_thread(self.store.load)).to_payload(),
)
if not self._engine_synced:
continue
- # OpenCode preserves the request's explicit protocol and
- # API keys have unrestricted origins. No Agent resolver
- # is involved: the adapter binds this exact Source.
- handle = await self._engine_call(self.adapter.invoke(
- source.id,
- model_id,
- self._probe_request(source, model_id, "opencode", output_tokens=128),
- False,
- "opencode",
- on_admitted=admitted,
- ))
+ # No Agent resolver is involved: the adapter binds this exact Source.
+ try:
+ handle = await self._engine_call(self.adapter.invoke(
+ source.id,
+ model_id,
+ request(source),
+ stream,
+ origin,
+ on_admitted=admitted,
+ ))
+ except InvokeCancelledError as cancelled_early:
+ # Cancelled after admission, before a handle (a timeout
+ # included): the wire facts already observed are billed,
+ # so they are still metered. Raised on as a plain
+ # cancellation, which the deadline below reads as its own
+ # timeout and any other canceller as theirs.
+ cancelled_observed = cancelled_early.observed
+ raise asyncio.CancelledError() from None
break
finally:
release_owner()
if admitted_at is None:
raise ModelHubError("engine_down", status=503)
- if handle.stream is not None:
- async for _chunk in handle.stream:
- pass
+ await consume(handle)
outcome = await self._engine_call(handle.outcome())
async def settle_attempt() -> None:
+ nonlocal retired_own_marker
try:
if source is not None and outcome is not None:
# The explicit test is the retry a cooldown waits for.
@@ -7635,21 +7895,22 @@ class ModelHubService:
await self._record_recovery_success(
source.id, attempt_generation, backend="system", model_id=model_id,
)
- await self._verify_successful_source(
+ retired_own_marker = await self._verify_successful_source(
source.id, source.credential_ref, source.verification_pending, outcome,
)
finally:
- if handle is not None:
- try:
+ try:
+ if handle is not None:
await handle.close_stream()
- finally:
+ 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,
+ 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_selected(), timeout=_SOURCE_PROBE_TIMEOUT_SECONDS)
+ await asyncio.wait_for(invoke_selected(), timeout=timeout)
except asyncio.TimeoutError:
if admitted_at is None:
raise ModelHubError("engine_down", status=503) from None
@@ -7677,24 +7938,7 @@ class ModelHubService:
pass
raise cancelled
assert source is not None and outcome is not None
- succeeded = outcome.kind is RawOutcomeKind.SUCCESS
- # Classify failures for display only. A selected model failure cannot
- # block other models on this Source, refresh credentials, or modify route
- # state.
- decision = classify_outcome(outcome)
- if decision.action == "refresh":
- decision = ResolutionDecision("fallback", reason="credential_revoked")
- error = None if succeeded else self._probe_failure(
- outcome, decision, recovery_managed=False,
- )[0]
- return {
- "source_id": source.id,
- "model_id": model_id,
- "protocol": source.protocol,
- "reachable": succeeded,
- "latency_ms": elapsed_ms,
- "error": error,
- }
+ return UserTestCall(source, outcome, elapsed_ms, retired_own_marker)
@staticmethod
def _probe_failure(
@@ -9014,10 +9258,10 @@ class ModelHubService:
credential_ref: str | None,
verification_pending: str | None,
outcome: RawCallOutcome,
- ) -> None:
- """Retire pending verification only for the current credential's call."""
+ ) -> bool:
+ """Retire pending verification only for the current credential's call; whether this call retired it."""
if outcome.kind is not RawOutcomeKind.SUCCESS or verification_pending is None:
- return
+ return False
retired_identity: tuple[tuple, tuple] | None = None
def clear_current(config: ModelHubConfig) -> bool:
@@ -9042,6 +9286,7 @@ class ModelHubService:
self.recovery.verification_retired(source_id, previous_identity, current_identity)
if self._source_attempt_identities.get(source_id) == previous_identity:
self._source_attempt_identities[source_id] = current_identity
+ return retired_identity is not None
except ValueError as exc:
if "recovery warnings" not in str(exc):
raise
@@ -9050,6 +9295,7 @@ class ModelHubService:
# Advisory bookkeeping must not turn a completed model call into a
# failed response. Retain pending verification for the next success.
logger.warning("Could not persist Model Hub verification state")
+ return False
async def settle_handle_outcome(
self,
diff --git a/docs/plans/model-hub-capability-model.md b/docs/plans/model-hub-capability-model.md
index 88ff89148..1c022265c 100644
--- a/docs/plans/model-hub-capability-model.md
+++ b/docs/plans/model-hub-capability-model.md
@@ -262,6 +262,10 @@ and the existing tone vocabulary (`TimeHint` for dates):
- native: the tool fee per call plus a token estimate;
- proxy: the same plus the executor model's call.
+ Before a probe runs, the Tools read states each candidate's `probe_estimate`: one call probe priced from its
+ nominal usage (`hosted_probe.ESTIMATED_USAGE` and one search's counters), `included` on a monthly Source, and
+ unknown rather than zero when the model has no token price.
+
All of it is computed by the one pricing owner, `pricing.py` (`hosted_response_cost`, reached through
`ModelHubService.hosted_call_cost`, which reads only the price table the usage writer already holds, so pricing a
response does no I/O). It is stored once per response: as the message's
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index 1c8aff9dc..a0416de6c 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -242,6 +242,7 @@ revision; the discovering lane does not reinterpret or edit the contract in plac
| `turn-provenance.schema.json` | Exactly attributed turn attempts and terminal outcome; no policy or mapping discriminator. The one versioned object persisted to disk, so it accepts every released version. |
| `usage-summary.schema.json` | Metered token usage over a trailing local-day window, aggregated from proxied turns, with its list-API-price valuation. A report only: no consumer may feed it back into resolution, admission, or cooldown. |
| `quota-summary.schema.json` | Rate-limit windows of hub-held subscriptions, parsed from each vendor's own usage report, and the API-price value of each subscription's metered usage against its monthly fee. A report only; carries no grant or raw body. |
+| `hosted-tool-probe-result.schema.json` | One user-started hosted-tool probe: per aspect, whether it verified the tool, showed it unsupported, or was inconclusive or transient (which write no evidence), with the Source test's failure detail for a request that failed. |
| `hosted-tools-status.schema.json` | The Tools tab read: each hosted tool's toggle and chosen executor, every eligible (Source, model) the overlay offers it on with its `call` and `replay` evidence, and re-verify counts. A report only; hop resolution reads config and evidence itself. |
| `resolution-event.schema.json` | Pull-feed Source/resolution records and their closed reason/detail vocabulary. |
| `oauth-flow.schema.json` | Subscription creation and re-auth presentation without secret material. |
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 867148b6d..7eaaf6079 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -39,6 +39,7 @@
{"method": "POST", "path": "/api/models/quota/refresh", "response_schema": "QuotaResponse", "exercise": {"path": "/api/models/quota/refresh", "status": 200}},
{"method": "GET", "path": "/api/models/hosted-tools", "response_schema": "HostedToolsResponse", "exercise": {"path": "/api/models/hosted-tools", "status": 200}},
{"method": "PUT", "path": "/api/models/hosted-tools/<tool>", "response_schema": "HostedToolsResponse", "exercise": {"path": "/api/models/hosted-tools/web_search", "status": 200, "json": {"enabled": true, "executor": null}}},
+ {"method": "POST", "path": "/api/models/hosted-tools/<tool>/probe", "response_schema": "HostedToolProbeResponse", "exercise": {"path": "/api/models/hosted-tools/web_search/probe", "status": 200, "json": {"source_id": "src_conform001", "model_id": "claude-opus-4-6"}}},
{"method": "POST", "path": "/api/models/oauth/start", "response_schema": "OAuthFlowResponse", "exercise": {"path": "/api/models/oauth/start", "status": 200, "json": {"vendor": "anthropic", "channel": "hub"}}},
{"method": "GET", "path": "/api/models/oauth/status/<flow_id>", "response_schema": "OAuthResultResponse", "exercise": {"path": "/api/models/oauth/status/oaf_00000001", "status": 200}},
{"method": "POST", "path": "/api/models/oauth/submit", "response_schema": "OAuthResultResponse", "exercise": {"path": "/api/models/oauth/submit", "status": 200, "json": {"flow_id": "oaf_00000001", "value": "contract-code"}}},
@@ -533,6 +534,17 @@
"hosted_tools": {"$ref": "model-hub/hosted-tools-status.schema.json"}
}
},
+ "HostedToolProbeResponse": {
+ "type": "object",
+ "required": ["ok", "contract_version", "probe", "hosted_tools"],
+ "additionalProperties": false,
+ "properties": {
+ "ok": {"const": true},
+ "contract_version": {"const": 12},
+ "probe": {"$ref": "model-hub/hosted-tool-probe-result.schema.json"},
+ "hosted_tools": {"$ref": "model-hub/hosted-tools-status.schema.json"}
+ }
+ },
"OAuthFlowResponse": {
"type": "object",
"required": ["ok", "contract_version", "flow"],
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index 1be287ea3..c9649a433 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -71,8 +71,9 @@ runtime open. Once models are configured it participates in the runtime Stop gua
| GET `/api/models/usage?days=<n>` | → `{usage: UsageSummary \| UsageReport}` | The released `days` selector remains supported and is clamped to the retained window; a Source with no metered call is absent rather than reported as zero. The exclusive modern `window=24h\|7d\|30d\|60d` selector returns the dense temporal report; sending both selectors or an invalid `window` returns `400 invalid_parameter`. |
| GET `/api/models/quota` | → `{quota: QuotaSummary}` | Rate-limit windows of every hub-held subscription Source, from the vendor's own usage report, plus each Source's API-price `value` (see Subscription quota). Served from the server cache; a Source older than five minutes is re-read before answering, bounded by a short deadline, and a Source still being read is listed in `pending`. Never starts the engine. |
| POST `/api/models/quota/refresh` | → `{quota: QuotaSummary}` | Forced re-read. Rate-limited per Source to one vendor call every 30 seconds and suppressed while a Source cools down after a vendor 429; a suppressed Source returns its cached snapshot. |
-| GET `/api/models/hosted-tools` | → `{hosted_tools: HostedToolsStatus}` | The Tools tab read (`hosted-tools-status.schema.json`): every catalog tool with its toggle and chosen executor, every (Source, model) the overlay offers it on with an eligible credential and an untranslated path, each with its `call` and `replay` evidence as routing reads it, and `reverify` counts: `engine_upgraded` for probe evidence taken on another engine or probe shape (now routed as unknown) and `aged`. Never probes and never starts the engine. |
-| PUT `/api/models/hosted-tools/<tool>` | `{enabled: boolean, executor: null \| {source_id, model_id}}` → `{hosted_tools: HostedToolsStatus}` | Replaces one tool's toggle and chosen executor; it applies from the next turn and interrupts nothing. An unknown tool or a malformed body returns `400 invalid_parameter`; an executor naming a missing Source returns `404 source_not_found`; an executor that is not a hub Source with that model, an eligible credential, an untranslated path and the overlay's declaration returns `400 invalid_parameter`. Whether the executor is verified is evidence, read at each hop resolution. |
+| GET `/api/models/hosted-tools` | → `{hosted_tools: HostedToolsStatus}` | The Tools tab read (`hosted-tools-status.schema.json`): every catalog tool with its toggle and chosen executor, every (Source, model) the overlay offers it on with an eligible credential and an untranslated path, each with its `call` and `replay` evidence as routing reads it and what one call probe there is estimated to cost (`probe_estimate`: `list` with `usd`, `included` on a monthly Source, or null when unknown, never zero), and `reverify` counts: `engine_upgraded` for probe evidence taken on another engine or probe shape (now routed as unknown) and `aged`. Never probes and never starts the engine. |
+| PUT `/api/models/hosted-tools/<tool>` | `{enabled: boolean, executor: null \| {source_id, model_id}}` → `{hosted_tools: HostedToolsStatus}` | Replaces one tool's toggle and chosen executor; it applies from the next turn and interrupts nothing. An unknown tool or a malformed body returns `400 invalid_parameter`; an executor naming a missing Source returns `404 source_not_found`; an executor that is not a hub Source serving that model (not a retired tombstone), with an eligible credential, an untranslated path and the overlay's declaration returns `400 invalid_parameter`. Whether the executor is verified is evidence, read at each hop resolution. |
+| POST `/api/models/hosted-tools/<tool>/probe` | `{source_id, model_id}` → `{probe: HostedToolProbeResult, hosted_tools: HostedToolsStatus}` | Runs the tool's call probe once on exactly that (Source, model), at the user's request: the production request Vibey would send natively, with one fixed message and, except on Anthropic, the tool forced. Vibey's adapter runs unchanged, and every request it sends is its own real, metered call pinned to that Source with no failover: at most two, the second only when the endpoint refused a field before answering (Anthropic's one-hour cache lifetime), so only one runs the model (`hosted-tool-probe-result.schema.json`). `verified` and `unsupported` write `probe` evidence for the tool's `call`; `inconclusive` (the response completed without the tool's result, or the request failed for another reason) and `transient` (overload, 5xx, rate limit, timeout) write none. `replay` is null until Vibey replays native payloads. A tool whose results Vibey does not parse yet (`image_generation`), an unknown tool or a malformed body returns `400 invalid_parameter`; the target is refused exactly as a PUT executor is. Nothing else starts a probe. |
| POST `/api/models/oauth/start` | `{vendor, channel, client_nonce?}` → `{flow: OAuthFlow}` | Starts creation of a new subscription source. Before provider work, the optional exact `(client_nonce, vendor, channel)` tuple is atomically claimed; concurrent retries coalesce to its one pending start and terminal result. |
| GET `/api/models/oauth/status/<flow_id>` | → OAuth result | Terminal create and reauth shapes are below. A `failed` flow names its cause with the closed `error_key` and, when the provider, engine, or native CLI said more, carries that reason verbatim on one bounded line in `error_detail` for the dialog's copyable details. |
| POST `/api/models/oauth/submit` | `{flow_id, value}` → OAuth result | Same terminal shape as status. A callback address is recognized with or without its `http(s)://` scheme, which browsers drop when copying a page that failed to load; any other value is a bare code. An address the flow refuses before anything reaches the provider is the non-terminal `422 submission_rejected`: one with no `code` or `error`, or one whose `state` answers a different sign-in link than this flow's (`detail: modelHub.errors.submission_rejected_other_attempt`). The flow stays `awaiting_action` and accepts another submission until its `expires_at`. |
diff --git a/docs/plans/model-hub-contracts/hosted-tool-probe-result.schema.json b/docs/plans/model-hub-contracts/hosted-tool-probe-result.schema.json
new file mode 100644
index 000000000..0952f5099
--- /dev/null
+++ b/docs/plans/model-hub-contracts/hosted-tool-probe-result.schema.json
@@ -0,0 +1,38 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "$id": "model-hub/hosted-tool-probe-result.schema.json",
+ "title": "HostedToolProbeResult",
+ "description": "One user-started hosted-tool probe on exactly one (Source, model). Only verified and unsupported are evidence; inconclusive and transient leave the current record as it was (vibey-hosted-tools.md §3.2).",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["tool", "source_id", "model_id", "call", "replay"],
+ "properties": {
+ "tool": {"enum": ["web_search", "x_search", "image_generation"]},
+ "source_id": {"type": "string", "minLength": 1},
+ "model_id": {"type": "string", "minLength": 1},
+ "call": {"$ref": "#/definitions/aspect"},
+ "replay": {
+ "description": "Null until Vibey replays native payloads, and always for a tool without a replay aspect.",
+ "oneOf": [{"type": "null"}, {"$ref": "#/definitions/aspect"}]
+ }
+ },
+ "definitions": {
+ "aspect": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["outcome", "error"],
+ "properties": {
+ "outcome": {"enum": ["verified", "unsupported", "inconclusive", "transient"]},
+ "error": {
+ "description": "The Source test's detail key for a request that failed before its response completed; null otherwise.",
+ "type": ["string", "null"],
+ "minLength": 1
+ }
+ },
+ "allOf": [{
+ "if": {"properties": {"outcome": {"enum": ["verified", "unsupported"]}}},
+ "then": {"properties": {"error": {"type": "null"}}}
+ }]
+ }
+ }
+}
diff --git a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
index 5dda25e88..ac7edd0af 100644
--- a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
+++ b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
@@ -52,7 +52,7 @@
"description": "Every (Source, model) the overlay offers the tool on, with an eligible credential and an untranslated path; Vibey's Source order first.",
"items": {
"type": "object",
- "required": ["source_id", "model_id", "call", "replay", "billing", "price"],
+ "required": ["source_id", "model_id", "call", "replay", "billing", "price", "probe_estimate"],
"additionalProperties": false,
"properties": {
"source_id": { "type": "string", "pattern": "^src_[a-z0-9]{8,}$" },
@@ -66,6 +66,24 @@
"price": {
"description": "The overlay's list price for this tool on this provider, or null when no list price is known (never zero). OpenAI lists no per-image price, so image_generation has none.",
"oneOf": [{ "type": "null" }, { "$ref": "#/definitions/ListPrice" }]
+ },
+ "probe_estimate": {
+ "description": "What one call probe here is estimated to cost before it runs, in the shape of hosted_summary.cost: list (the tool fee plus a nominal token estimate), included on a monthly Source, or null when unknown (never zero) and for a tool that cannot be probed yet.",
+ "oneOf": [
+ { "type": "null" },
+ {
+ "type": "object",
+ "required": ["basis", "usd"],
+ "additionalProperties": false,
+ "properties": { "basis": { "const": "list" }, "usd": { "type": "number", "minimum": 0 } }
+ },
+ {
+ "type": "object",
+ "required": ["basis"],
+ "additionalProperties": false,
+ "properties": { "basis": { "const": "included" } }
+ }
+ ]
}
}
}
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index 9f15b5d02..33ed420d4 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -79,10 +79,15 @@ verified for X search.
So a probe cannot pass or fail for a shape that production never sends.
- **A probe has its own resolution.** Normal resolution gives native mode only after `call: verified` (§3.5), so a
first verification could never send a native declaration. Model Hub therefore builds a probe resolution, and only
- for the user's probe action. It pins the probed (Source, model) with `x-avibe-pin-source`, carries the overlay's
- native declaration whatever the current evidence, and allows no failover. Normal turns never receive it.
-- **The `call` probe.** The fixed message is "search for 'Avibe local-first agent OS' and reply with the first
- result's URL".
+ for the user's probe action. It names the probed (Source, model) and carries the overlay's native declaration
+ whatever the current evidence, with the endpoint built as the Vibey launch builds it (the Source's vendor as its
+ provider). Vibey's adapter runs unchanged, and Model Hub serves every request it sends with its own invocation
+ of exactly that Source, never the turn gateway, so there is no route and no failover. A resend the adapter makes
+ for a field the endpoint refused before answering (Anthropic's one-hour cache lifetime) is one more such call;
+ a probe sends at most two, and only one runs the model. A result is recognized only as the hosted call a real
+ turn would keep. Normal turns never receive a probe resolution.
+- **The `call` probe.** The fixed message is "search the web for 'Avibe local-first agent OS' and reply with the
+ first result's URL" (X search: "search X for posts about …, and reply with the first post's URL").
- **`verified`:** the response completes and carries the provider's own result item for that tool (§4.2).
- **`unsupported`:** only an HTTP 400 that names the tool type (observed: `Unsupported tool type: x_search`).
- **Inconclusive, not evidence:** a completed response without that item. The model may simply not have used the
@@ -91,6 +96,10 @@ verified for X search.
paths are never native anyway (§3.5).
- **Not evidence:** a transient failure (overload, 5xx, timeout). The UI reports "couldn't verify, try again"
(observed: every OpenAI-relay web search ended with an in-stream "servers overloaded").
+- **Delivery order.** The `call` probe for `web_search` and `x_search` ships first
+ (`POST /api/models/hosted-tools/<tool>/probe`). The `replay` probe follows Vibey's verbatim native replay, and the
+ `image_generation` call probe follows Vibey's parsing of image results. Until then a probe reports `replay: null`
+ and the API refuses an image probe, because no response could show its result.
- **The `replay` probe.** A second production request with the native declaration still present. Its history is
the call probe's turn, with the native payload verbatim, followed by "give the URL of the second result you found,
without searching again".
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index c878ea878..157c7ee9e 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -51,6 +51,7 @@ capabilities:
- tests/test_model_hub_api.py
- tests/test_model_hub_hosted_tools_resolution.py
- tests/test_model_hub_hosted_tools_config.py
+ - tests/test_model_hub_hosted_probe.py
- tests/test_model_hub_capability_evidence.py
- tests/test_provider_overlay.py
- tests/test_hosted_activity.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 600f46e31..4b401d891 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -8,6 +8,7 @@ capability:
- tests/test_model_hub_hosted_pinning.py
- tests/test_model_hub_hosted_tools_resolution.py
- tests/test_model_hub_hosted_tools_config.py
+ - tests/test_model_hub_hosted_probe.py
- tests/test_model_hub_capability_evidence.py
- tests/test_provider_overlay.py
- tests/test_hosted_activity.py
@@ -280,6 +281,25 @@ scenarios:
- tests/test_model_hub_reasoning_tiers.py::test_the_hop_declares_exactly_its_models_levels
- tests/test_model_hub_reasoning_tiers.py::test_rows_saved_by_3_2_0_are_derived_again_once_at_startup
- tests/test_model_hub_evidence_rules.py::test_the_picker_menu_states_which_efforts_routing_refuses_in_menu_values
+ - id: MH-HOSTED-007
+ name: A user-started call probe sends Vibey's native request pinned to the probed Source, and records only a result or a refusal naming the tool
+ status: covered
+ kind: contract
+ layer: contract
+ test: tests/test_model_hub_hosted_probe.py::test_a_call_probe_sends_the_production_request_and_records_only_what_it_shows
+ related_tests:
+ - tests/test_model_hub_hosted_probe.py::test_a_probe_runs_only_on_a_target_the_tool_can_run_on
+ - tests/test_model_hub_hosted_probe.py::test_each_candidate_states_what_probing_it_would_cost
+ - tests/test_model_hub_hosted_probe.py::test_each_request_the_adapter_sends_is_its_own_pinned_call
+ - tests/test_model_hub_hosted_probe.py::test_a_probe_that_verifies_its_source_records_evidence_for_the_source_as_it_now_is
+ - tests/test_model_hub_hosted_probe.py::test_a_probe_records_no_evidence_for_a_grant_that_replaced_its_own_mid_probe
+ - tests/test_model_hub_hosted_probe.py::test_the_probe_reads_its_calls_in_the_order_the_adapter_sent_them
+ - tests/test_model_hub_hosted_probe.py::test_the_probe_asks_for_no_more_output_than_a_turn_on_its_hop_would
+ - tests/test_model_hub_hosted_probe.py::test_an_api_key_source_is_probed_on_a_passthrough_model_it_does_not_list
+ - tests/test_model_hub_hosted_probe.py::test_a_probe_that_times_out_before_its_handle_is_still_metered
+ - tests/test_model_hub_hosted_probe.py::test_a_probe_attributes_nothing_when_another_grant_retired_the_marker
+ - tests/test_model_hub_hosted_probe.py::test_a_deadline_mid_stream_ends_the_probe_as_transient
+ - tests/test_model_hub_hosted_probe.py::test_a_probe_settles_when_the_adapter_is_done_even_if_the_body_stays_open
- id: MH-HOSTED-VIBEY-002
name: Every native hosted item becomes one hosted call with a provider-neutral action and its record; citations stay on the text that cites them; the response's counters and reported cost go to its summary
status: covered
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index 083c065b6..8b95549c2 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -118,7 +118,7 @@ def test_complete_registered_api_management_inventory():
for method in (getattr(route, "methods", None) or ())
if method not in {"HEAD", "OPTIONS"}
}
- assert len(endpoints) == 285
+ assert len(endpoints) == 286
for method in ("PUT", "DELETE"):
assert (method, "/api/vault/secrets/{name}/fields/{field}") in endpoints
assert http_authorization_policy(method, "/api/vault/secrets/LOGIN/fields/username").minimum_role == "editor"
diff --git a/tests/test_model_hub_hosted_probe.py b/tests/test_model_hub_hosted_probe.py
new file mode 100644
index 000000000..5ae0ef219
--- /dev/null
+++ b/tests/test_model_hub_hosted_probe.py
@@ -0,0 +1,549 @@
+"""The hosted-tool call probe (``vibey-hosted-tools.md`` §3.2, capability model §3.3). Scenario MH-HOSTED-007.
+
+The real engine client invokes a loopback upstream that plays each provider's answer, and Vibey's own adapter
+reads the response, so a probe recognizes a result only as the hosted call a real turn would keep. Only
+``verified`` and ``unsupported`` are evidence; every other outcome leaves the record that was there.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from dataclasses import replace
+from datetime import timedelta
+from typing import Any
+
+import pytest
+from aiohttp import web
+
+from core.handlers.model_hub.capability_evidence import EvidenceFeature, EvidenceRecord, identity_digest
+from core.handlers.model_hub.hosted_tools import HOSTED_PROBE_SHAPE
+from core.handlers.model_hub.service import ModelHubError
+from tests.test_model_hub_l3 import _assert_valid, _source
+from tests.test_model_hub_retry_lifecycle import configured_service, loopback_engine
+from vibe.backend_model_catalog import hosted_tool_spec
+
+XAI = _source("src_probe0001", "xAI 密钥", vendor="xai", protocol="openai_responses", model_id="grok-4.6")
+ANTHROPIC = _source("src_probe0002", "Anthropic 中转", vendor="anthropic", protocol="anthropic", model_id="claude-sonnet-4-6")
+CALL = EvidenceFeature.hosted("web_search", "call")
+
+
+def _sse(*events: dict[str, Any]) -> str:
+ # Both providers name every event, as the engine's stream observer expects.
+ return "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" for event in events)
+
+
+SEARCH = {
+ "id": "ws_1",
+ "type": "web_search_call",
+ "status": "completed",
+ "action": {"type": "search", "query": "Avibe local-first agent OS", "sources": [{"type": "url", "url": "https://avibe.bot/"}]},
+}
+ANSWER = {"id": "msg_1", "type": "message", "content": [{"type": "output_text", "text": "https://avibe.bot/", "annotations": []}]}
+
+
+def _responses(*items: dict[str, Any]) -> str:
+ events: list[dict[str, Any]] = [{"type": "response.created", "response": {"status": "in_progress"}}]
+ for index, item in enumerate(items):
+ events.append({"type": "response.output_item.added", "output_index": index, "item": {**item, "status": "in_progress"}})
+ if item["type"] == "message":
+ events.append({"type": "response.output_text.delta", "output_index": index, "delta": item["content"][0]["text"]})
+ events.append({"type": "response.output_item.done", "output_index": index, "item": item})
+ usage = {"input_tokens": 900, "output_tokens": 40, "server_side_tool_usage_details": {"web_search_calls": len(items) - 1}}
+ events.append({"type": "response.completed", "response": {"status": "completed", "usage": usage}})
+ return _sse(*events)
+
+
+ANTHROPIC_SEARCH = _sse(
+ {"type": "message_start", "message": {"usage": {"input_tokens": 900}}},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "server_tool_use", "id": "srvtoolu_1", "name": "web_search", "input": {}}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "input_json_delta", "partial_json": '{"query": "Avibe"}'}},
+ {"type": "content_block_stop", "index": 0},
+ {
+ "type": "content_block_start",
+ "index": 1,
+ "content_block": {
+ "type": "web_search_tool_result",
+ "tool_use_id": "srvtoolu_1",
+ "content": [{"type": "web_search_result", "title": "Avibe", "url": "https://avibe.bot/", "encrypted_content": "opaque"}],
+ },
+ },
+ {"type": "content_block_stop", "index": 1},
+ {"type": "content_block_start", "index": 2, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_delta", "index": 2, "delta": {"type": "text_delta", "text": "https://avibe.bot/"}},
+ {"type": "content_block_stop", "index": 2},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 40, "server_tool_use": {"web_search_requests": 1}}},
+ {"type": "message_stop"},
+)
+# Output, then a server error in the stream: the call cannot be retried as a turn, but a probe can run again.
+FAILED_AFTER_OUTPUT = _sse(
+ {"type": "response.created", "response": {"status": "in_progress"}},
+ {"type": "response.output_item.added", "output_index": 0, "item": {**ANSWER, "status": "in_progress"}},
+ {"type": "response.output_text.delta", "output_index": 0, "delta": "https://"},
+ {
+ "type": "response.failed",
+ "response": {"status": "failed", "error": {"code": "server_error", "message": "The server had an error."}},
+ },
+)
+TOOL_REFUSED = {"error": {"message": "Unsupported tool type: web_search", "type": "invalid_request_error"}}
+CHOICE_REFUSED = {"error": {"message": "tool_choice 'required' is not supported", "type": "invalid_request_error", "param": "tool_choice"}}
+OVERLOADED = {"error": {"message": "The servers are overloaded", "type": "overloaded_error"}}
+
+CASES = [
+ # (case, Source, upstream status, upstream body, outcome, the record afterwards: written status or None for
+ # kept, whether the response failed to complete)
+ ("responses-result", XAI, 200, _responses(SEARCH, ANSWER), "verified", "verified", False),
+ ("anthropic-result", ANTHROPIC, 200, ANTHROPIC_SEARCH, "verified", "verified", False),
+ ("no-tool-item", XAI, 200, _responses(ANSWER), "inconclusive", None, False),
+ ("tool-type-refused", XAI, 400, TOOL_REFUSED, "unsupported", "unsupported", True),
+ ("another-400", XAI, 400, CHOICE_REFUSED, "inconclusive", None, True),
+ ("overloaded", XAI, 503, OVERLOADED, "transient", None, True),
+ ("failed-after-output", XAI, 200, FAILED_AFTER_OUTPUT, "transient", None, True),
+]
+
+
+ "source,status,body,outcome,written,failed", [case[1:] for case in CASES], ids=[case[0] for case in CASES]
+)
+async def test_a_call_probe_sends_the_production_request_and_records_only_what_it_shows(
+ tmp_path, source, status, body, outcome, written, failed
+):
+ """MH-HOSTED-007: the probe is Vibey's native request on exactly the probed Source, forced except on Anthropic;
+ only a result or a refusal naming the tool is evidence, and anything else keeps the earlier record."""
+ service, clock, _models = configured_service(tmp_path, sources=[source])
+ model_id = source.models[0].id
+ sent = []
+
+ async def respond(request):
+ sent.append(await request.json())
+ if isinstance(body, str):
+ return web.Response(status=status, body=body.encode(), content_type="text/event-stream")
+ return web.json_response(body, status=status)
+
+ async with loopback_engine(tmp_path, service, respond):
+ # A real refusal learned a day ago, for the Source as the engine now holds its credential.
+ [live] = service.store.load().sources
+ prior = EvidenceRecord(
+ source_id=source.id,
+ model_id=model_id,
+ feature=CALL,
+ status="unsupported",
+ basis="observed",
+ observed_at=clock.now() - timedelta(days=1),
+ engine=service.engine_stamp,
+ shape=HOSTED_PROBE_SHAPE,
+ source_identity=identity_digest(live),
+ detail="400 invalid_request_error",
+ )
+ service.capability_evidence.write(prior, live=[live])
+ result = await service.probe_hosted_tool("web_search", {"source_id": source.id, "model_id": model_id})
+
+ [request] = sent
+ declaration = hosted_tool_spec(source.vendor, source.protocol, model_id, "web_search").declaration
+ assert request["tools"] == [declaration]
+ assert "Avibe local-first agent OS" in json.dumps(request, ensure_ascii=False)
+ assert "reasoning" not in request and "output_config" not in request
+ if source.protocol == "anthropic":
+ assert "tool_choice" not in request
+ else:
+ assert request["tool_choice"] == "required"
+
+ probe = result["probe"]
+ _assert_valid("hosted-tool-probe-result.schema.json", probe)
+ assert (probe["tool"], probe["source_id"], probe["model_id"], probe["replay"]) == ("web_search", source.id, model_id, None)
+ assert probe["call"]["outcome"] == outcome
+ # A response that failed says why, as the Source test does; a refusal naming the tool is the answer itself.
+ assert (probe["call"]["error"] is not None) == (failed and outcome != "unsupported")
+
+ [record] = service.capability_evidence.records()
+ if written is None:
+ assert record == prior
+ else:
+ assert (record.status, record.basis, record.engine, record.shape) == (
+ written, "probe", service.engine_stamp, HOSTED_PROBE_SHAPE
+ )
+ assert record.detail == ("400 invalid_request_error" if written == "unsupported" else None)
+ assert record.observed_at > prior.observed_at
+ # The response carries the Tools tab as it reads now.
+ [candidate] = next(tool for tool in result["hosted_tools"]["tools"] if tool["name"] == "web_search")["candidates"]
+ assert candidate["call"]["status"] == (written or "unsupported")
+
+
+async def test_a_probe_runs_only_on_a_target_the_tool_can_run_on(tmp_path):
+ """MH-HOSTED-007: a refused target never reaches the upstream, so it costs nothing."""
+ subscription = replace(ANTHROPIC, id="src_probe0003", kind="subscription", billing="monthly")
+ google = _source("src_probe0004", "Gemini", vendor="google", protocol="google", model_id="gemini-3-pro")
+ retired = _source("src_probe0007", "xAI retired", vendor="xai", protocol="openai_responses", model_id="grok-4.5")
+ retired.models[0].retired = True
+ chatgpt = replace(
+ _source("src_probe0008", "ChatGPT", vendor="openai", protocol="openai_responses", model_id="gpt-6-sol"),
+ kind="subscription",
+ billing="monthly",
+ )
+ service, _clock, _models = configured_service(tmp_path, sources=[XAI, subscription, google, retired, chatgpt])
+ sent = []
+
+ async def invoke(*args, **kwargs):
+ sent.append(args)
+ raise AssertionError("a refused probe reached the upstream")
+
+ service.adapter.invoke = invoke
+ for tool, target, code, status in [
+ # Vibey does not parse generated images yet, so an image probe could never see its result.
+ ("image_generation", {"source_id": XAI.id, "model_id": "grok-4.6"}, "invalid_parameter", 400),
+ ("code_interpreter", {"source_id": XAI.id, "model_id": "grok-4.6"}, "invalid_parameter", 400),
+ ("web_search", {"source_id": XAI.id}, "invalid_parameter", 400),
+ ("web_search", {"source_id": XAI.id, "model_id": ["grok-4.6"]}, "invalid_parameter", 400),
+ ("web_search", {"source_id": 7, "model_id": "grok-4.6"}, "invalid_parameter", 400),
+ ("web_search", {"source_id": XAI.id, "model_id": " "}, "invalid_parameter", 400),
+ ("web_search", {"source_id": "src_gone0001", "model_id": "grok-4.6"}, "source_not_found", 404),
+ ("web_search", {"source_id": XAI.id, "model_id": "grok-3"}, "invalid_parameter", 400),
+ # Anthropic restricts OAuth credentials to its own apps.
+ ("web_search", {"source_id": subscription.id, "model_id": "claude-sonnet-4-6"}, "invalid_parameter", 400),
+ # Vibey reaches a google Source through a translation, never natively.
+ ("web_search", {"source_id": google.id, "model_id": "gemini-3-pro"}, "invalid_parameter", 400),
+ # A model discovery retired stays listed as a tombstone, and a tombstone never supplies work.
+ ("web_search", {"source_id": retired.id, "model_id": "grok-4.5"}, "invalid_parameter", 400),
+ # A subscription serves only its listed models; an API-key Source would serve this one as a passthrough.
+ ("web_search", {"source_id": chatgpt.id, "model_id": "gpt-6-astra"}, "invalid_parameter", 400),
+ ]:
+ with pytest.raises(ModelHubError) as refused:
+ await service.probe_hosted_tool(tool, target)
+ assert (refused.value.code, refused.value.status) == (code, status), (tool, target)
+
+ assert sent == []
+ assert service.capability_evidence.records() == []
+ # The same rule decides where the Tools tab lists the tool and what a turn binds as its executor, so even
+ # verified evidence never makes a tombstone either.
+ service.capability_evidence.write(
+ EvidenceRecord(
+ source_id=retired.id,
+ model_id="grok-4.5",
+ feature=CALL,
+ status="verified",
+ basis="probe",
+ observed_at=service.now(),
+ engine=service.engine_stamp,
+ shape=HOSTED_PROBE_SHAPE,
+ source_identity=identity_digest(retired),
+ ),
+ live=service.store.load().sources,
+ )
+ status = service.hosted_tools_status()["hosted_tools"]
+ web_search = next(tool for tool in status["tools"] if tool["name"] == "web_search")
+ assert [candidate["source_id"] for candidate in web_search["candidates"]] == [XAI.id, chatgpt.id]
+ assert web_search["bound"] is None
+ # Nor does the tombstone's record ask for a re-verify the Tools tab has no candidate for.
+ service.engine_stamp = "model-hub-engine-next"
+ assert service.hosted_tools_status()["hosted_tools"]["reverify"] == {"engine_upgraded": 0, "aged": 0}
+
+
+def test_each_candidate_states_what_probing_it_would_cost(tmp_path):
+ """MH-HOSTED-007: the Tools read prices one call probe before it runs: at list price on a metered Source,
+ included on a monthly one, and unknown (never zero) when the model has no token price."""
+ from core.handlers.model_hub.usage import UsageWriter
+ from tests.test_model_hub_pricing import _table
+
+ monthly = replace(XAI, id="src_probe0005", display_name="xAI monthly", billing="monthly", credential_ref="cred_src_probe0005")
+ unpriced = _source("src_probe0006", "xAI unlisted", vendor="xai", protocol="openai_responses", model_id="grok-4-unlisted")
+ service, _clock, _models = configured_service(tmp_path, sources=[XAI, monthly, unpriced])
+ # grok-4.6 at $2 / $6 per million tokens; xAI lists web search at $5 per 1k calls and X search at $5 per 1k posts.
+ service.usage_writer = UsageWriter(service.usage, price_table=_table)
+
+ status = service.hosted_tools_status()["hosted_tools"]
+
+ _assert_valid("hosted-tools-status.schema.json", status)
+ estimates = {
+ (tool["name"], candidate["source_id"]): candidate["probe_estimate"]
+ for tool in status["tools"]
+ for candidate in tool["candidates"]
+ }
+ tokens = 8000 * 2 / 1e6 + 500 * 6 / 1e6
+ assert estimates[("web_search", XAI.id)] == {"basis": "list", "usd": pytest.approx(tokens + 5 / 1000)}
+ assert estimates[("x_search", XAI.id)] == {"basis": "list", "usd": pytest.approx(tokens + 10 * 5 / 1000)}
+ assert estimates[("web_search", monthly.id)] == {"basis": "included"}
+ assert estimates[("web_search", unpriced.id)] is None
+
+
+ "refusal",
+ [
+ "cache_control.ttl: Extra inputs are not permitted",
+ # A refusal that also names the tool type speaks only for the request it refused: the resend's result decides.
+ "Unsupported tool type: web_search_20250305; cache_control.ttl: Extra inputs are not permitted",
+ ],
+ ids=["ttl", "ttl-and-tool-type"],
+)
+async def test_each_request_the_adapter_sends_is_its_own_pinned_call(tmp_path, monkeypatch, refusal):
+ """MH-HOSTED-007: the probe runs Vibey's adapter unchanged. A relay that refuses Anthropic's one-hour cache
+ lifetime gets the adapter's resend, as a real turn would, and each request is one call on the probed Source."""
+ from core.agent_core.ai import anthropic as anthropic_adapter
+
+ monkeypatch.setattr(anthropic_adapter, "_TTL_REJECTED_ROUTES", set())
+ service, _clock, _models = configured_service(tmp_path, sources=[ANTHROPIC])
+ sent = []
+
+ async def respond(request):
+ sent.append(await request.json())
+ if '"ttl": "1h"' in json.dumps(sent[-1]):
+ return web.json_response(
+ {"type": "error", "error": {"type": "invalid_request_error", "message": refusal}},
+ status=400,
+ )
+ return web.Response(body=ANTHROPIC_SEARCH.encode(), content_type="text/event-stream")
+
+ async with loopback_engine(tmp_path, service, respond):
+ result = await service.probe_hosted_tool(
+ "web_search", {"source_id": ANTHROPIC.id, "model_id": "claude-sonnet-4-6"}
+ )
+
+ first, resent = sent
+ assert '"ttl": "1h"' in json.dumps(first) and '"ttl": "1h"' not in json.dumps(resent)
+ assert first["tools"] == resent["tools"]
+ assert result["probe"]["call"] == {"outcome": "verified", "error": None}
+ [record] = service.capability_evidence.records()
+ assert (record.source_id, record.status, record.basis) == (ANTHROPIC.id, "verified", "probe")
+
+
+async def test_a_probe_that_verifies_its_source_records_evidence_for_the_source_as_it_now_is(tmp_path):
+ """MH-HOSTED-007: a new Source's first successful call retires its pending verification, which changes the
+ identity evidence follows; the probe's record follows the Source as it reads after that call."""
+ pending = replace(XAI, verification_pending="vp_" + "0" * 32)
+ service, _clock, _models = configured_service(tmp_path, sources=[pending])
+
+ async def respond(_request):
+ return web.Response(body=_responses(SEARCH, ANSWER).encode(), content_type="text/event-stream")
+
+ async with loopback_engine(tmp_path, service, respond):
+ result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
+
+ [live] = service.store.load().sources
+ assert live.verification_pending is None
+ assert result["probe"]["call"]["outcome"] == "verified"
+ [record] = service.capability_evidence.records()
+ assert record.source_identity == identity_digest(live)
+ [candidate] = next(tool for tool in result["hosted_tools"]["tools"] if tool["name"] == "web_search")["candidates"]
+ assert candidate["call"]["status"] == "verified"
+
+
+async def test_a_probe_records_no_evidence_for_a_grant_that_replaced_its_own_mid_probe(tmp_path):
+ """MH-HOSTED-007: only the probe's own settlement may change the identity it vouches for. A reauthentication that
+ lands mid-probe (same credential ref, a new pending marker) leaves the old grant's result without a record."""
+ first, second = "vp_" + "1" * 32, "vp_" + "2" * 32
+ service, _clock, _models = configured_service(tmp_path, sources=[replace(XAI, verification_pending=first)])
+
+ async def respond(_request):
+ config = service.store.load()
+ config.sources[0].verification_pending = second
+ service.store.save(config)
+ return web.Response(body=_responses(SEARCH, ANSWER).encode(), content_type="text/event-stream")
+
+ async with loopback_engine(tmp_path, service, respond):
+ result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
+
+ assert result["probe"]["call"]["outcome"] == "verified"
+ assert service.store.load().sources[0].verification_pending == second
+ assert service.capability_evidence.records() == []
+
+
+async def test_the_probe_reads_its_calls_in_the_order_the_adapter_sent_them():
+ """MH-HOSTED-007: a resend can settle before the request it replaces; the probe still reads the resend last."""
+ import httpx
+
+ from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
+ from core.handlers.model_hub.hosted_probe import PinnedCallTransport
+ from core.handlers.model_hub.service import UserTestCall
+
+ first_may_settle = asyncio.Event()
+
+ class Handle:
+ stream = None
+
+ async def call(body, read):
+ await read(Handle())
+ if body["n"] == 1:
+ await first_may_settle.wait()
+ else:
+ first_may_settle.set()
+ status = 400 if body["n"] == 1 else 503
+ outcome = RawCallOutcome(RawOutcomeKind.HTTP_ERROR, status, None, None, False, "grok-4.6", XAI.id)
+ return UserTestCall(XAI, outcome, 0, False)
+
+ transport = PinnedCallTransport(call)
+ async with httpx.AsyncClient(transport=transport) as client:
+ first = asyncio.create_task(client.post("http://probe.invalid/", json={"n": 1}))
+ await asyncio.sleep(0)
+ await client.post("http://probe.invalid/", json={"n": 2})
+ await first
+ await transport.settle()
+
+ assert [call.body["n"] for call in transport.calls] == [1, 2]
+
+
+async def test_the_probe_asks_for_no_more_output_than_a_turn_on_its_hop_would(tmp_path):
+ """MH-HOSTED-007: a Vibey turn asks for its menu model's output budget; a relay model that declares a small
+ output maximum is probed within it, so the probe is not refused where real turns succeed."""
+ from config.v2_config import ModelHubBackendModelConfig, ModelHubRouteConfig, ModelHubRouteHopConfig
+
+ service, _clock, _models = configured_service(tmp_path, sources=[XAI])
+ vibey = service.store.config.agents["vibey"]
+ vibey.models = [ModelHubBackendModelConfig(id="relay-grok", context_window=128000, max_output_tokens=1024)]
+ vibey.sources.order = [XAI.id]
+ vibey.routes["relay-grok"] = ModelHubRouteConfig((ModelHubRouteHopConfig(XAI.id, "grok-4.6"),))
+ sent = []
+
+ async def respond(request):
+ sent.append(await request.json())
+ return web.Response(body=_responses(SEARCH, ANSWER).encode(), content_type="text/event-stream")
+
+ async with loopback_engine(tmp_path, service, respond):
+ result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
+
+ [request] = sent
+ assert request["max_output_tokens"] == 1024
+ assert result["probe"]["call"]["outcome"] == "verified"
+
+
+async def test_an_api_key_source_is_probed_on_a_passthrough_model_it_does_not_list(tmp_path):
+ """MH-HOSTED-007: an API-key Source serves models discovery never listed, so such a hop can be probed and become
+ native like any other; the Tools tab lists only what discovery found."""
+ service, _clock, _models = configured_service(tmp_path, sources=[XAI])
+ sent = []
+
+ async def respond(request):
+ sent.append(await request.json())
+ return web.Response(body=_responses(SEARCH, ANSWER).encode(), content_type="text/event-stream")
+
+ async with loopback_engine(tmp_path, service, respond):
+ # A padded id is the model routing knows: the probe sends and records the canonical one.
+ result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": " grok-4.7 "})
+
+ [request] = sent
+ # The engine addresses a passthrough model through the Source's credential.
+ assert request["model"].rsplit("/", 1)[-1] == "grok-4.7"
+ assert result["probe"]["call"]["outcome"] == "verified"
+ [record] = service.capability_evidence.records()
+ assert (record.source_id, record.model_id, record.status) == (XAI.id, "grok-4.7", "verified")
+ # The Tools tab lists only what discovery found, so it never counts a re-verify it has no candidate for.
+ service.engine_stamp = "model-hub-engine-next"
+ assert service.hosted_tools_status()["hosted_tools"]["reverify"] == {"engine_upgraded": 0, "aged": 0}
+
+
+async def test_a_probe_that_times_out_before_its_handle_is_still_metered(tmp_path, monkeypatch):
+ """MH-HOSTED-007: a probe that times out after the engine observed billed wire facts, but before the call handed
+ back its handle, still reaches the usage ledger: the provider billed it."""
+ from core.handlers.model_hub import service as service_module
+ from core.handlers.model_hub.adapter import InvokeCancelledError
+ from core.handlers.model_hub.stream_wire import ProtocolSSEState
+ from tests.test_model_hub_l3 import _usage_of
+
+ monkeypatch.setattr(service_module, "_HOSTED_PROBE_TIMEOUT_SECONDS", 0.05)
+ service, _clock, _models = configured_service(tmp_path, sources=[XAI])
+ observed = ProtocolSSEState("openai_responses")
+ observed.observe(
+ _sse({"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": 1200, "output_tokens": 3}}}).encode()
+ )
+
+ async def stalls_after_admission(source_id, model_id, request, stream, origin, *, on_admitted=None):
+ on_admitted()
+ try:
+ await asyncio.sleep(60)
+ except asyncio.CancelledError:
+ raise InvokeCancelledError(observed) from None
+
+ service.adapter.invoke = stalls_after_admission
+ service._engine_synced = True
+ result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
+
+ assert result["probe"]["call"]["outcome"] == "transient"
+ assert _usage_of(service, XAI.id)
+
+
+async def test_a_probe_attributes_nothing_when_another_grant_retired_the_marker(tmp_path):
+ """MH-HOSTED-007: only proof that the probe's own call retired its marker lets the record follow the Source. A
+ reauth mid-probe whose new marker another call then retires reads the same, and gets no record."""
+ first, second = "vp_" + "3" * 32, "vp_" + "4" * 32
+ service, _clock, _models = configured_service(tmp_path, sources=[replace(XAI, verification_pending=first)])
+
+ async def respond(_request):
+ config = service.store.load()
+ config.sources[0].verification_pending = second
+ service.store.save(config)
+ config = service.store.load()
+ config.sources[0].verification_pending = None
+ service.store.save(config)
+ return web.Response(body=_responses(SEARCH, ANSWER).encode(), content_type="text/event-stream")
+
+ async with loopback_engine(tmp_path, service, respond):
+ result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
+
+ assert result["probe"]["call"]["outcome"] == "verified"
+ assert service.store.load().sources[0].verification_pending is None
+ assert service.capability_evidence.records() == []
+
+
+async def test_a_deadline_mid_stream_ends_the_probe_as_transient(tmp_path, monkeypatch):
+ """MH-HOSTED-007: only the call's own task reads its stream, so a deadline that fires while the adapter waits
+ for the next chunk ends the stream for the adapter and settles the call; the probe reports a transient failure."""
+ from core.handlers.model_hub import service as service_module
+
+ monkeypatch.setattr(service_module, "_HOSTED_PROBE_TIMEOUT_SECONDS", 0.5)
+ service, _clock, _models = configured_service(tmp_path, sources=[XAI])
+
+ async def respond(request):
+ response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
+ await response.prepare(request)
+ await response.write(
+ _sse(
+ {"type": "response.created", "response": {"status": "in_progress"}},
+ {"type": "response.output_item.added", "output_index": 0, "item": {**ANSWER, "status": "in_progress"}},
+ {"type": "response.output_text.delta", "output_index": 0, "delta": "https://"},
+ ).encode()
+ )
+ await asyncio.sleep(30)
+ return response
+
+ async with loopback_engine(tmp_path, service, respond):
+ result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
+
+ assert result["probe"]["call"]["outcome"] == "transient"
+ assert service.capability_evidence.records() == []
+
+
+async def test_a_probe_settles_when_the_adapter_is_done_even_if_the_body_stays_open(tmp_path, monkeypatch):
+ """MH-HOSTED-007: once the adapter has the terminal event it closes the response, as production does, so the call
+ settles as the success it was instead of waiting out the deadline with the body still open."""
+ from core.handlers.model_hub import service as service_module
+
+ monkeypatch.setattr(service_module, "_HOSTED_PROBE_TIMEOUT_SECONDS", 5)
+ service, _clock, _models = configured_service(tmp_path, sources=[replace(XAI, verification_pending="vp_" + "5" * 32)])
+
+ async def respond(request):
+ response = web.StreamResponse(headers={"Content-Type": "text/event-stream"})
+ await response.prepare(request)
+ await response.write(_responses(SEARCH, ANSWER).encode())
+ await asyncio.sleep(30)
+ return response
+
+ async with loopback_engine(tmp_path, service, respond):
+ started = asyncio.get_running_loop().time()
+ result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
+ elapsed = asyncio.get_running_loop().time() - started
+
+ assert elapsed < 5
+ assert result["probe"]["call"]["outcome"] == "verified"
+ assert service.store.load().sources[0].verification_pending is None
+ [record] = service.capability_evidence.records()
+ assert record.status == "verified"
diff --git a/tests/test_model_hub_hosted_tools_resolution.py b/tests/test_model_hub_hosted_tools_resolution.py
index b98c53b47..43dce596c 100644
--- a/tests/test_model_hub_hosted_tools_resolution.py
+++ b/tests/test_model_hub_hosted_tools_resolution.py
@@ -223,7 +223,8 @@ def test_status_lists_where_each_tool_can_run_and_counts_re_verifications(tmp_pa
live=ALL,
)
status = hosted_tools_status(
- _config({"x_search": ON}), evidence=store, spec_for=_spec_for, engine=ENGINE, now=NOW
+ _config({"x_search": ON}), evidence=store, spec_for=_spec_for, engine=ENGINE, now=NOW,
+ probe_estimate=lambda _source, _model_id, _tool: None,
)
by_name = {tool["name"]: tool for tool in status["tools"]}
assert [tool["name"] for tool in status["tools"]] == ["web_search", "x_search", "image_generation"]
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 2ce325e56..8dc49c575 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -710,10 +710,13 @@ 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 and proxied hosted-tool calls consume their own
+ # Calls a user asked for (the Source test and hosted-tool probes, both
+ # through `_user_test_call`) and proxied hosted-tool calls consume their own
# response rather than forwarding a Turn to the gateway. They reuse the same
# metering owner, exactly once.
- consumers = (invoke, _functions(service_tree)["probe_source"], _functions(service_tree)["run_hosted_tool"])
+ consumers = (
+ invoke, _functions(service_tree)["_user_test_call"], _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
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 52129603c..dd01fbf29 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -551,6 +551,7 @@ _MEMBER_HTTP_RULES = tuple(
("POST", r"^/api/models/quota/refresh$"),
("GET", r"^/api/models/hosted-tools$"),
("PUT", r"^/api/models/hosted-tools/[^/]+$"),
+ ("POST", r"^/api/models/hosted-tools/[^/]+/probe$"),
("POST", r"^/api/models/oauth/(?:start|submit|cancel)$"),
("GET", r"^/api/models/oauth/status/[^/]+$"),
("POST", r"^/api/models/migration/(?:scan|apply)$"),
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index bc2c481be..b1d8e4a72 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -300,6 +300,9 @@ class ModelHubRemoteService:
async def set_hosted_tool(self, tool: str, setting: object) -> dict:
return await _rpc("set_hosted_tool", {"tool": tool, "setting": setting})
+ async def probe_hosted_tool(self, tool: str, target: object) -> dict:
+ return await _rpc("probe_hosted_tool", {"tool": tool, "target": target})
+
def agent_chain(self, backend: str, model_id: str) -> dict:
return _rpc_sync(
"get_agent_chain",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 6a3d81ebb..52322a570 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5180,6 +5180,20 @@ async def model_hub_hosted_tool_put(tool: str, starlette_request: FastAPIRequest
return await _dispatch_native_ui_request(starlette_request, handler)
[email protected]("/api/models/hosted-tools/{tool}/probe", include_in_schema=False)
+async def model_hub_hosted_tool_probe(tool: str, starlette_request: FastAPIRequest):
+ async def handler():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ result = await _model_hub_service().probe_hosted_tool(tool, _model_hub_json_object("invalid_parameter"))
+ return _model_hub_success(**result)
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
@app.route("/api/models/agents/<backend>/chains", methods=["GET"])
def model_hub_agent_chains_get(backend):
from core.handlers.model_hub import ModelHubError