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): follow a verified call probe with the replay probe, and probe image generation (#2611)

Call White6a4295762d4c
diff --git a/core/handlers/model_hub/hosted_probe.py b/core/handlers/model_hub/hosted_probe.py
index 9a21a2bc3..9e31edb9d 100644
--- a/core/handlers/model_hub/hosted_probe.py
+++ b/core/handlers/model_hub/hosted_probe.py
@@ -1,4 +1,4 @@
-"""The hosted-tool call probe (``vibey-hosted-tools.md`` §3.2, capability model §3.3).
+"""The hosted-tool probes (``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
@@ -8,6 +8,11 @@ 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.
+The ``call`` probe asks the model to use the tool. When it verifies, the
+``replay`` probe sends that turn back with the tool's native payload in place,
+as Vibey replays history to the Source that produced it, and asks for a result
+without using the tool again.
+
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
@@ -17,9 +22,12 @@ service owns the calls themselves.
from __future__ import annotations
import asyncio
+import base64
+import binascii
import json
-from dataclasses import dataclass
-from typing import Any, AsyncIterator, Awaitable, Callable, Literal, Optional, Protocol
+import re
+from dataclasses import dataclass, replace
+from typing import Any, AsyncIterator, Awaitable, Callable, Final, Literal, Optional, Protocol
import httpx
@@ -34,8 +42,17 @@ from core.agent_core.ai.provider import (
)
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.messages import (
+ IMAGE_MIME_TYPES,
+ AssistantMessage,
+ HostedImage,
+ HostedToolBlock,
+ TextBlock,
+ ThinkingBlock,
+ UserMessage,
+)
from core.agent_core.tools.hosted import hosted_tool_spec as canonical_tool_spec
+from core.agent_core.tools.read import detect_supported_image_mime_type
from vibe.backend_model_catalog import HostedToolSpec
from .adapter import InvokeHandle, RawCallOutcome, RawOutcomeKind
@@ -45,16 +62,25 @@ 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")
+# Every catalog tool: Vibey's adapters parse each one's results.
+PROBED_TOOLS: tuple[str, ...] = ("web_search", "x_search", "image_generation")
+# The web search asks for fresh articles: the replay probe asks about the other results, and a model given only the
+# first could infer the rest of a fixed topic's results (its site's other pages), but not a page published after it
+# was trained.
_MESSAGES = {
- "web_search": "Search the web for 'Avibe local-first agent OS' and reply with the first result's URL.",
+ "web_search": "Search the web for a news article published today about technology and reply with its URL.",
"x_search": "Search X for posts about 'Avibe local-first agent OS' and reply with the first post's URL.",
+ "image_generation": "Generate a small, simple image: a blue circle on a white background.",
}
+# The replay probe's question: one a model can answer only from the results the replayed payload holds, since the
+# answer it already gave shows just the first.
+_REPLAY_MESSAGE = (
+ "Without using any tool again, list the URLs of the other results you found, beyond the one you already gave."
+)
_SYSTEM = "You check that a tool works: use it, then answer in one line."
+# The replay's own instructions: the call's would ask for the very call the replay checks the model does not need.
+_REPLAY_SYSTEM = "You check that a tool's earlier results can be read back: answer from them in one line, without using any tool."
# 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
@@ -66,7 +92,13 @@ ESTIMATED_USAGE = ProtocolUsageReport.of(input_tokens=8000, cached_input_tokens=
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},
+ "image_generation": {},
}
+# What the replay probe is estimated to use: the call probe's turn with its results, a question, and a one-line
+# answer, with no tool fee (the answer uses no tool).
+ESTIMATED_REPLAY_USAGE = ProtocolUsageReport.of(input_tokens=12000, cached_input_tokens=0, output_tokens=300)
+# The protocols whose adapters send a hosted call's native payload back in place (``transform.native_replay``).
+NATIVE_REPLAY_PROTOCOLS: frozenset[str] = frozenset({"anthropic", "openai_responses"})
# 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"
@@ -113,6 +145,112 @@ def probe_request(
)
+def replay_request(call: ModelRequest, tool: str, answered: AssistantMessage) -> ModelRequest:
+ """The replay probe after a verified ``call`` probe: its turn sent back, with the native declaration still
+ present and the hop allowed to take the tool's native payload, and a question only those results answer.
+
+ The answer goes back without its reasoning, which may restate the results, readably or encrypted: a Source that
+ dropped the payload could read a result there. A provider that wants a completed turn's reasoning back refuses
+ the request, which no narrow rule learns from, so the replay reads as inconclusive, never as unsupported.
+ """
+
+ route = call.endpoint.hosted_tools[tool]
+ answered = replace(answered, content=tuple(block for block in answered.content if not isinstance(block, ThinkingBlock)))
+ return replace(
+ call,
+ endpoint=replace(
+ call.endpoint, hosted_tools={tool: HostedToolRoute("native", None, True, route.declaration, route.include)}
+ ),
+ system=_REPLAY_SYSTEM,
+ messages=(*call.messages, answered, UserMessage(content=(TextBlock(text=_REPLAY_MESSAGE),))),
+ # A forced choice would ask for the very call the replay checks the model does not need.
+ tool_choice=None,
+ )
+
+
+def hidden_result_urls(message: AssistantMessage) -> frozenset[str]:
+ """The result URLs a response's hosted calls returned that its visible answer does not show.
+
+ Only these prove a replay: a model that names one read the replayed native
+ payload, since nothing else it was sent holds it. A URL the answer wrote or
+ cited is visible text, which any request carries.
+ """
+
+ returned = {source.url for block in message.content if isinstance(block, HostedToolBlock) for source in block.record.sources}
+ # Read generously, a trailing slash aside: a result the answer shows but the probe takes for hidden is what could
+ # verify a replay falsely.
+ shown = {key.rstrip("/") for key in written_urls(message)}
+ return frozenset(url for url in returned if url and not {key.rstrip("/") for key in _readings(url)} & shown)
+
+
+def written_urls(message: AssistantMessage) -> frozenset[str]:
+ """Every URL a response's answer shows, as comparison keys: each reading of a URL its text writes
+ (``_readings``) and each URL it cites, as given."""
+
+ text = " ".join(block.text for block in message.content if isinstance(block, TextBlock) and block.text)
+ keys = {key for url in _URL.findall(text) for key in _readings(url)}
+ cited = [
+ citation.url
+ for block in message.content
+ if isinstance(block, TextBlock) and block.citations
+ for citation in block.citations
+ ]
+ if message.hosted_summary is not None:
+ cited.extend(source.url for source in message.hosted_summary.cited_sources)
+ keys.update(_same_url(url) for url in cited if url)
+ return frozenset(keys)
+
+
+def carries_native_payload(body: Any, message: AssistantMessage) -> bool:
+ """Whether a request body sends every hosted call of ``message`` back verbatim, its provider items in place."""
+
+ def canonical(value: Any) -> str:
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
+
+ # Every object the body holds, once, then a lookup per item: one walk, whatever the payload's size.
+ held: set[str] = set()
+ pending = [body]
+ while pending:
+ node = pending.pop()
+ if isinstance(node, dict):
+ held.add(canonical(node))
+ pending.extend(node.values())
+ elif isinstance(node, list):
+ pending.extend(node)
+ items = [item for block in message.content if isinstance(block, HostedToolBlock) for item in block.native.payload]
+ return bool(items) and all(canonical(item) in held for item in items)
+
+
+class ProbeImageCheck:
+ """The image probe's media sink: it checks a generated image is one Vibey can keep, and keeps nothing.
+
+ A probe asks whether the tool works, so its image is decoded and recognized
+ exactly as a turn's would be, and then discarded.
+ """
+
+ async def save_image(self, encoded: str) -> HostedImage:
+ return await asyncio.to_thread(self._check, encoded)
+
+ @staticmethod
+ def _check(encoded: str) -> HostedImage:
+ try:
+ data = base64.b64decode(encoded, validate=True)
+ except (binascii.Error, ValueError):
+ raise ValueError("the image is not valid base64") from None
+ mime_type = detect_supported_image_mime_type(data)
+ # The kinds a turn's sink keeps (``IMAGE_MIME_TYPES``, which ``MediaSnapshots`` stores); any other is refused there.
+ if mime_type not in IMAGE_MIME_TYPES:
+ raise ValueError("the image is not a PNG, JPEG, GIF or WebP")
+ return HostedImage(path="probe:discarded", mime=mime_type, bytes=len(data))
+
+
+# How long the UI process waits for any Model Hub RPC (``vibe/model_hub_client.py`` reads it from here). A probe
+# answers inside it, with room for the RPC's own overhead.
+MODEL_HUB_RPC_TIMEOUT_SECONDS: Final = 300.0
+PROBE_BUDGET_SECONDS: Final = MODEL_HUB_RPC_TIMEOUT_SECONDS - 20.0
+# The replay probe runs only with at least this long left; otherwise it reports a transient failure, sending nothing.
+REPLAY_MIN_SECONDS: Final = 60.0
+
# 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
@@ -261,14 +399,22 @@ class PinnedCallTransport(httpx.AsyncBaseTransport):
raise result
-async def run_probe(request: ModelRequest, call: PinnedCall) -> tuple[Done | ProviderError | None, list[ProbeCall]]:
+async def run_probe(
+ request: ModelRequest, call: PinnedCall, *, media_sink: Optional[ProbeImageCheck] = None
+) -> 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)
+ # Only the image probe has an image to keep, and only the Responses adapter produces one.
+ adapter = create_adapter(
+ request.endpoint.protocol,
+ client=client,
+ gateway=False,
+ **({"media_sink": media_sink} if media_sink is not None else {}),
+ )
async for event in adapter.stream(request, CancelToken()):
if isinstance(event, (Done, ProviderError)):
terminal = event
@@ -302,10 +448,94 @@ def call_outcome(
return "unsupported"
if isinstance(terminal, Done):
used = any(
- isinstance(block, HostedToolBlock) and block.tool == tool and block.record.status == "completed"
+ isinstance(block, HostedToolBlock)
+ and block.tool == tool
+ and block.record.status == "completed"
+ # A generated image counts only once Vibey could keep it.
+ and (block.record.images is None or bool(block.record.images))
for block in terminal.message.content
)
return "verified" if used else "inconclusive"
+ return _failure(terminal, outcome)
+
+
+def replay_outcome(
+ tool: str,
+ terminal: Done | ProviderError | None,
+ outcome: RawCallOutcome,
+ learned: Optional[LearnedEvidence],
+ *,
+ asked: frozenset[str],
+ carried: bool,
+) -> ProbeOutcome:
+ """What one replay probe shows about sending ``tool``'s native payload back to its Source (§12 item 23).
+
+ * ``unsupported``: a 400 naming the replayed content, through the narrow rule real requests learn from, or an
+ answer that calls the tool again instead of using the results it holds;
+ * ``verified``: an answer that names a URL only those results hold (``asked``, ``hidden_result_urls``) without
+ calling the tool;
+ * ``inconclusive``: an answer that names none, or a refusal, and any request that did not carry the native
+ payload verbatim (``carried``), since it tested nothing;
+ * ``transient``: as for the call probe.
+ """
+
+ if not carried:
+ # A request that did not send the payload verbatim tested nothing, whatever the provider said about it.
+ return "inconclusive"
+ if learned is not None and (learned.feature.kind, learned.feature.name, learned.feature.aspect) == (
+ "hosted_tool", tool, "replay"
+ ):
+ return "unsupported"
+ if isinstance(terminal, Done):
+ message = terminal.message
+ if any(isinstance(block, HostedToolBlock) and block.tool == tool for block in message.content):
+ return "unsupported"
+ if message.stop_reason in ("refusal", "safety"):
+ # A refused or blocked answer proves nothing, whatever it quotes.
+ return "inconclusive"
+ named = written_urls(message) & {_same_url(url) for url in asked}
+ return "verified" if named else "inconclusive"
+ return _failure(terminal, outcome)
+
+
+# A URL as an answer writes it: up to the whitespace, quote or bracket that ends it. Parentheses stay, since a URL
+# may hold them; one that closes the prose around it is trailing text.
+_URL = re.compile(r"https?://[^\s<>\[\]{}\"'`]+", re.IGNORECASE)
+# What prose and Markdown can leave right after a URL, and a URL can also end in.
+_TRAILING = ".,;:!?)*_"
+
+
+def _readings(written: str) -> frozenset[str]:
+ """The comparison keys a URL written in prose can stand for: as written, and without each run of the trailing
+ text a sentence may leave on it. A provider's URL is exact; only where prose ends a URL is ambiguous."""
+
+ readings = {_same_url(written)}
+ while written and written[-1] in _TRAILING:
+ written = written[:-1]
+ readings.add(_same_url(written))
+ return frozenset(readings)
+
+
+def _same_url(url: str) -> str:
+ """A URL as a comparison key: exactly as given but for what RFC 3986 makes equivalent, the case of its scheme and
+ host and an empty path, which is ``/``. Anything else, such as a trailing slash or the case of its user
+ information, names another URL."""
+
+ scheme, separator, rest = url.partition("://")
+ if not separator:
+ return url
+ authority = _AUTHORITY.match(rest)[0]
+ path = rest[len(authority):]
+ userinfo, at, host = authority.rpartition("@")
+ return f"{scheme.lower()}://{userinfo}{at}{host.lower()}{path if path.startswith('/') else '/' + path}"
+
+
+_AUTHORITY = re.compile(r"[^/?#]*")
+
+
+def _failure(terminal: ProviderError | None, outcome: RawCallOutcome) -> ProbeOutcome:
+ """A probe request that failed: ``transient`` when a later try may not meet the same failure."""
+
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.
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index ac2d24b39..d15319463 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -114,7 +114,13 @@ from .events import (
build_resolution_event,
contains_credential_material,
)
-from .capability_evidence import CapabilityEvidenceStore, EvidenceFeature, EvidenceRecord, identity_digest
+from .capability_evidence import (
+ HOSTED_TOOL_ASPECTS,
+ CapabilityEvidenceStore,
+ EvidenceFeature,
+ EvidenceRecord,
+ identity_digest,
+)
from .errors import ModelDiscoveryError
from .evidence_rules import LearnedEvidence
from .evidence_rules import learn as learn_from_rejection
@@ -135,10 +141,22 @@ from .hosted_executor import (
responses_result,
)
from .hosted_probe import ESTIMATED_COUNTS as ESTIMATED_PROBE_COUNTS
+from .hosted_probe import ESTIMATED_REPLAY_USAGE as ESTIMATED_REPLAY_PROBE_USAGE
from .hosted_probe import ESTIMATED_USAGE as ESTIMATED_PROBE_USAGE
-from .hosted_probe import PROBE_MAX_OUTPUT_TOKENS, PROBED_TOOLS
+from .hosted_probe import (
+ NATIVE_REPLAY_PROTOCOLS,
+ PROBE_MAX_OUTPUT_TOKENS,
+ PROBE_BUDGET_SECONDS,
+ PROBED_TOOLS,
+ REPLAY_MIN_SECONDS,
+ ProbeImageCheck,
+ carries_native_payload,
+ hidden_result_urls,
+)
from .hosted_probe import call_outcome as hosted_call_outcome
from .hosted_probe import probe_request as hosted_probe_request
+from .hosted_probe import replay_outcome as hosted_replay_outcome
+from .hosted_probe import replay_request as hosted_replay_request
from .hosted_probe import run_probe as run_hosted_probe
from .hosted_tools import (
HOSTED_PROBE_SHAPE,
@@ -349,8 +367,6 @@ 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)
@@ -6025,20 +6041,27 @@ class ModelHubService:
}
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.
+ """What probing ``tool`` on this Source and model is estimated to cost at most; 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.
+ Priced by the one pricing owner from each probe's nominal usage: the call
+ probe, plus the replay probe that follows a verified call where the tool's
+ payload can go back verbatim (that request uses no tool, so no tool fee).
"""
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:
+ costs = [
+ self.hosted_call_cost(
+ source, model_id, (tool,), usage=ESTIMATED_PROBE_USAGE, counts=ESTIMATED_PROBE_COUNTS[tool],
+ )
+ ]
+ if "replay" in HOSTED_TOOL_ASPECTS[tool] and source.protocol in NATIVE_REPLAY_PROTOCOLS:
+ costs.append(self.hosted_call_cost(source, model_id, (), usage=ESTIMATED_REPLAY_PROBE_USAGE, counts={}))
+ if any(cost is None for cost in costs):
return None
- return {"basis": cost.basis} if cost.usd is None else {"basis": cost.basis, "usd": cost.usd}
+ if any(cost.usd is None for cost in costs):
+ return {"basis": "included"}
+ return {"basis": "list", "usd": round(sum(cost.usd for cost in costs), 6)}
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."""
@@ -7746,92 +7769,198 @@ class ModelHubService:
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,
- )
+ # The whole probe answers inside the UI's RPC wait. Each call gets as long as a turn's executor gives the
+ # tool, but never more than the probe has left.
+ deadline = time.monotonic() + PROBE_BUDGET_SECONDS
- terminal, calls = await run_hosted_probe(request, pinned_call)
+ def remaining() -> float:
+ return deadline - time.monotonic()
+
+ def pinned(select: Callable[[ModelHubConfig], ModelHubSourceConfig]):
+ async def call(body: dict, read: Callable[[InvokeHandle], Awaitable[None]]):
+ return await self._user_test_call(
+ source_id,
+ model_id,
+ select,
+ lambda source: ModelHubRequest(body, protocol=source.protocol),
+ stream=True,
+ origin="vibey",
+ consume=read,
+ timeout=max(1.0, min(call_timeout(tool), remaining())),
+ )
+
+ return call
+
+ pinned_call = pinned(selected)
+
+ media_sink = ProbeImageCheck() if tool == "image_generation" else None
+ terminal, calls = await run_hosted_probe(request, pinned_call, media_sink=media_sink)
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
+ call_last = calls[-1]
+ replays_natively = "replay" in HOSTED_TOOL_ASPECTS[tool] and source.protocol in NATIVE_REPLAY_PROTOCOLS
+
+ # Each step reads what the provider sent, which can be megabytes of results and payload, off the controller
+ # loop.
+ def judge_call() -> tuple[Optional[LearnedEvidence], str, frozenset[str]]:
+ learned = self._probe_rejection(call_last, model_id)
+ verdict = hosted_call_outcome(tool, terminal, call_last.outcome, learned)
+ # Only a result the visible answer does not show proves a replayed payload was read; with none, the
+ # replay stays unknown and turns replay synthetically, which is lossless.
+ verified = verdict == "verified" and isinstance(terminal, Done)
+ return learned, verdict, hidden_result_urls(terminal.message) if verified and replays_natively else frozenset()
+
+ call_learned, call_verdict, asked = await asyncio.to_thread(judge_call)
+ recorded_for = await self._record_probe_evidence(
+ EvidenceFeature.hosted(tool, "call"), call_verdict, call_last, call_learned, model_id,
+ )
+ replay: Optional[dict] = None
+ # The replay probe follows a call probe that verified and was recorded for the Source as it is, on a tool
+ # whose payload can go back verbatim, when the call returned a result the replay can ask about.
+ replayable = recorded_for is not None and bool(asked)
+ if replayable and remaining() < REPLAY_MIN_SECONDS:
+ # Too little of the probe's time is left for a replay that could finish: try again.
+ replay = {"outcome": "transient", "error": None}
+ elif replayable:
+ assert isinstance(terminal, Done)
+
+ def replay_selected(config: ModelHubConfig) -> ModelHubSourceConfig:
+ current = selected(config)
+ # The replay carries the call's provider-native payload, so it goes only to the Source identity that
+ # produced it and was recorded for it: never through a credential or endpoint that replaced it.
+ if identity_digest(current) != recorded_for:
+ raise ModelHubError("mapping_target_unavailable", status=409)
+ return current
+
+ try:
+ replay_terminal, replay_calls = await run_hosted_probe(
+ hosted_replay_request(request, tool, terminal.message), pinned(replay_selected),
+ )
+ except ModelHubError as refused:
+ # The call's result stands; the replay did not run. A Source that changed has no replay to report,
+ # and anything else (the engine went away) is worth trying again.
+ replay_terminal, replay_calls = None, []
+ if refused.code != "mapping_target_unavailable":
+ replay = {"outcome": "transient", "error": None}
+ if replay_calls:
+ replay_last = replay_calls[-1]
+
+ def judge_replay() -> tuple[Optional[LearnedEvidence], str]:
+ learned = self._probe_rejection(replay_last, model_id)
+ carried = carries_native_payload(replay_last.body, terminal.message)
+ return learned, hosted_replay_outcome(
+ tool, replay_terminal, replay_last.outcome, learned, asked=asked, carried=carried,
+ )
+
+ replay_learned, replay_verdict = await asyncio.to_thread(judge_replay)
+ await self._record_probe_evidence(
+ EvidenceFeature.hosted(tool, "replay"),
+ replay_verdict,
+ replay_last,
+ replay_learned,
+ model_id,
+ identity=recorded_for,
+ )
+ replay = self._probe_aspect(replay_verdict, replay_terminal, replay_last)
+ return {
+ "probe": {
+ "tool": tool,
+ "source_id": call_last.source.id,
+ "model_id": model_id,
+ "call": self._probe_aspect(call_verdict, terminal, call_last),
+ "replay": replay,
+ },
+ **await asyncio.to_thread(self.hosted_tools_status),
+ }
+
+ def _probe_rejection(self, call: Any, model_id: str) -> LearnedEvidence | None:
+ """The one feature a probe request's refusal names, through the narrow rules real requests learn from.
+
+ Only the request the response ended on speaks for the tool: a resend that completes outranks a refusal of
+ the request it replaced.
+ """
+
+ if call.outcome.rejection is None:
+ return None
+ return learn_from_rejection(
+ call.body,
+ call.outcome.rejection,
+ request_protocol=call.source.protocol,
+ source=call.source,
+ model_id=model_id,
+ spec_for=hosted_tool_spec,
)
- 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.
+
+ def _probe_aspect(self, verdict: str, terminal: Any, last: Any) -> dict:
+ """One probe aspect's result, with why a request that never completed failed, as the Source test shows it."""
+
+ return {
+ "outcome": verdict,
+ "error": (
+ self._test_call_failure(last.outcome)
+ if verdict != "unsupported" and not isinstance(terminal, Done)
+ else None
+ ),
+ }
+
+ async def _record_probe_evidence(
+ self,
+ feature: EvidenceFeature,
+ verdict: str,
+ last: Any,
+ learned: LearnedEvidence | None,
+ model_id: str,
+ *,
+ identity: str | None = None,
+ ) -> str | None:
+ """Record what a probe showed for the Source as it reads now; the identity recorded for, or None.
+
+ Only ``verified`` and ``unsupported`` are evidence. 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. ``identity``, when
+ given, is the one the probe's earlier aspect was recorded for: both
+ records then describe the same Source.
+ """
+
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 (
+ if live is None or not (
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:
+ ):
+ return None
+ digest = identity_digest(live)
+ if identity is not None and digest != identity:
+ return None
+ if verdict in ("verified", "unsupported"):
try:
await asyncio.to_thread(
self.capability_evidence.write,
EvidenceRecord(
source_id=live.id,
model_id=model_id,
- feature=EvidenceFeature.hosted(tool, "call"),
+ feature=feature,
status=verdict,
basis="probe",
observed_at=self.now(),
engine=self.engine_stamp,
shape=HOSTED_PROBE_SHAPE,
- source_identity=identity_digest(live),
+ source_identity=digest,
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),
- }
+ # Evidence is advisory state: the status read the probe returns shows what was kept.
+ logger.warning("Model Hub could not record the %s probe result", feature.name, exc_info=True)
+ return None
+ return digest
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.
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index c9649a433..365f82f44 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -73,7 +73,7 @@ runtime open. Once models are configured it participates in the runtime Stop gua
| 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 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/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. Each probe step (the call, and the replay below) sends at most two requests, the second only when the endpoint refused a field before answering (Anthropic's one-hour cache lifetime), so each step runs the model once: an action makes at most four requests, of which at most two run 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. A generated image counts only when Vibey's parsing could keep it; the probe keeps no file. When the call verifies and was recorded, a tool with a `replay` aspect (`web_search`, `x_search`) on a protocol that replays natively (Anthropic, Responses) gets the replay probe in the same action. It sends the call's turn back with the native payload in place, with nothing forced, and asks for result URLs the visible answer did not show. It is `verified` when the answer names one of those without calling the tool, `unsupported` on a 400 naming the replayed content or a new call to the tool, and otherwise `inconclusive`, as is any request that did not carry the payload verbatim. It writes `replay` evidence by the same rules. `replay` is null when no replay ran, including when no result was hidden from the visible answer. The whole probe answers inside the UI's RPC timeout; a replay with under a minute left is not sent and reads `transient`. 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
index 0952f5099..f72967b45 100644
--- a/docs/plans/model-hub-contracts/hosted-tool-probe-result.schema.json
+++ b/docs/plans/model-hub-contracts/hosted-tool-probe-result.schema.json
@@ -12,7 +12,7 @@
"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.",
+ "description": "The replay probe that follows a verified, recorded call: null when none ran (the call did not verify or was not recorded, the tool has no replay aspect, the protocol does not replay natively, or no result URL was hidden from the visible answer). transient with a null error when the probe had too little time left to send it.",
"oneOf": [{"type": "null"}, {"$ref": "#/definitions/aspect"}]
}
},
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 ac7edd0af..58149204d 100644
--- a/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
+++ b/docs/plans/model-hub-contracts/hosted-tools-status.schema.json
@@ -68,7 +68,7 @@
"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.",
+ "description": "What probing here is estimated to cost at most before it runs, in the shape of hosted_summary.cost: the call probe (its tool fee plus a nominal token estimate) and, for a tool with a replay aspect on a protocol that replays natively, the replay probe that may follow (tokens only). list, included on a monthly Source, or null when unknown (never zero), which is always so for image_generation (no list price).",
"oneOf": [
{ "type": "null" },
{
diff --git a/docs/plans/vibey-hosted-tools.md b/docs/plans/vibey-hosted-tools.md
index 6a05af182..4ca8eb6f3 100644
--- a/docs/plans/vibey-hosted-tools.md
+++ b/docs/plans/vibey-hosted-tools.md
@@ -84,10 +84,13 @@ verified for X search.
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").
+ each probe step (call, then replay) sends at most two requests and runs the model once. 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 a news article published today about technology and
+ reply with its URL" (X search: "search X for posts about 'Avibe local-first agent OS' and reply with the first
+ post's URL"). The web search asks for fresh articles because the replay probe asks about the other results: a
+ fixed topic's other results (its site's other pages) can be inferred from the first, while a page published after
+ the model was trained cannot, and a post's URL carries its id.
- **`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
@@ -96,19 +99,30 @@ 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.
+- **One action, both aspects.** `POST /api/models/hosted-tools/<tool>/probe` runs the `call` probe. When it
+ verifies and is recorded, and the tool has a `replay` aspect on a protocol that replays natively, the `replay`
+ probe follows at once, on the call's own turn. The `image_generation` call probe reads the image through Vibey's own
+ parsing, which keeps it only when it is an image; the probe keeps no file. The Tools tab's estimate covers both
+ requests.
- **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".
- - **`verified`:** the answer contains a URL from the first response's results, and the response makes no new
- call to the tool.
+ the call probe's turn, with the native payload verbatim and without the answer's reasoning (which may restate the
+ results, readably or encrypted), followed by "list the URLs of the other results you
+ found, without using any tool again", under instructions that ask for an answer from those results without a
+ tool (the call's would ask for the tool). Nothing is forced.
+ - **`verified`:** the answer names a result URL the call returned that its visible answer does not show (only the
+ replayed payload holds it), and the response makes no new call to the tool.
- **`unsupported`:** a 400 that names the replayed hosted content (observed on the Anthropic relay, 3 of 3:
- `Invalid encrypted_content in search_result block`), or an answer that does not use the earlier results (a new
- tool call, or no URL from them). Transport acceptance alone is never verification. xAI accepted verbatim
- replay, 3 of 3.
+ `Invalid encrypted_content in search_result block`), or a new call to the tool (§12 item 23). Transport
+ acceptance alone is never verification. xAI accepted verbatim replay, 3 of 3.
+ - **Inconclusive:** an answer naming no such URL, or a refusal, and any request that did not carry the native
+ payload verbatim. With no hidden URL to ask about, no replay runs.
+ - **Matching:** a result's URL is matched exactly but for the equivalences RFC 3986 allows (the case of its scheme
+ and host, an empty path as `/`); only where prose ends a written URL is read both ways.
+ - **Known by design:** a result that is a section or home page can still be guessed by a model whose payload was
+ dropped. The fresh-article query makes such results rare, and a re-probe replaces a wrong record.
+ - **Within the UI's wait:** the whole probe answers inside the UI's RPC timeout. Each call's deadline is the
+ tool's (as for a turn's proxied call) or what the probe has left, whichever is shorter. A replay with under a
+ minute left is not sent and reads as transient: try again.
- **Cost and when probes run.** A probe pair costs about $0.02–0.15 (spike: xAI $0.01–0.11 per call, Anthropic $0.01
per search plus tokens). The Tools tab shows the estimate before running.
- **What changes probe results** (capability model §3.3). A Source identity change drops them. An engine upgrade or
@@ -827,9 +841,11 @@ encoded either as a schema clause or as a producer test. The PR names which for
unverified, so it keeps no payload or signature of any response.
22. The `generate` action records the output's resolved `quality` and `size`; pricing uses those output values, not
the declaration's.
-23. The replay probe asks for a URL the call probe actually returned (such as the first). An answer with no earlier
- URL, or a refusal, is inconclusive; `unsupported` comes only from a 400 naming the replayed content or a new call
- to the tool.
+23. The replay probe asks for a result URL the call returned that its visible answer does not show, since only the
+ replayed native payload holds it. With no such URL (a single result, or results that stay encrypted, such as
+ xAI's X search) no replay runs and replay evidence stays unknown, so turns replay synthetically. An answer without
+ such a URL, or a refusal, is inconclusive; `unsupported` comes only from a 400 naming the replayed content or a new
+ call to the tool.
24. For OpenAI and xAI executors, each source's `snippet` is the answer text its `url_citation` span covers, extended
to the enclosing sentence; the executor instruction asks for one or two cited sentences per result so the spans
align. A source without a span has no snippet; Anthropic keeps `cited_text`. Tested against a recorded executor
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 79b7a0b25..f146d8239 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -314,7 +314,7 @@ scenarios:
- 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
+ name: A user-started probe sends Vibey's native request pinned to the probed Source, follows a verified call with the replay probe, and records only a result, a refusal naming the tool or its replayed content, or a new call
status: covered
kind: contract
layer: contract
@@ -332,6 +332,14 @@ scenarios:
- 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
+ - tests/test_model_hub_hosted_probe.py::test_an_image_probe_verifies_only_an_image_vibey_could_keep
+ - tests/test_model_hub_hosted_probe.py::test_a_verified_call_is_followed_by_the_replay_probe
+ - tests/test_model_hub_hosted_probe.py::test_a_replay_sends_the_results_only_in_their_native_payload
+ - tests/test_model_hub_hosted_probe.py::test_a_replay_goes_only_to_the_source_identity_the_call_was_recorded_for
+ - tests/test_model_hub_hosted_probe.py::test_a_re_probe_restores_replay_a_narrow_rule_demoted
+ - tests/test_model_hub_hosted_probe.py::test_a_replay_answer_counts_only_when_it_completed_and_names_a_hidden_result
+ - tests/test_model_hub_hosted_probe.py::test_a_replay_answer_names_a_result_by_its_exact_url
+ - tests/test_model_hub_hosted_probe.py::test_a_result_the_answer_shows_in_any_reading_is_not_hidden
- 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_model_hub_hosted_probe.py b/tests/test_model_hub_hosted_probe.py
index 5ae0ef219..5edf52299 100644
--- a/tests/test_model_hub_hosted_probe.py
+++ b/tests/test_model_hub_hosted_probe.py
@@ -1,4 +1,4 @@
-"""The hosted-tool call probe (``vibey-hosted-tools.md`` §3.2, capability model §3.3). Scenario MH-HOSTED-007.
+"""The hosted-tool probes (``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
@@ -8,6 +8,7 @@ reads the response, so a probe recognizes a result only as the hosted call a rea
from __future__ import annotations
import asyncio
+import base64
import json
from dataclasses import replace
from datetime import timedelta
@@ -26,6 +27,11 @@ 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")
+REPLAY = EvidenceFeature.hosted("web_search", "replay")
+
+
+def _records(service, feature) -> list:
+ return [record for record in service.capability_evidence.records() if record.feature == feature]
def _sse(*events: dict[str, Any]) -> str:
@@ -33,11 +39,17 @@ def _sse(*events: dict[str, Any]) -> str:
return "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" for event in events)
+# A result the call returned that its visible answer never shows: only the replayed native payload holds it.
+HIDDEN = "https://avibe.bot/docs/hosted-tools"
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/"}]},
+ "action": {
+ "type": "search",
+ "query": "Avibe local-first agent OS",
+ "sources": [{"type": "url", "url": "https://avibe.bot/"}, {"type": "url", "url": HIDDEN}],
+ },
}
ANSWER = {"id": "msg_1", "type": "message", "content": [{"type": "output_text", "text": "https://avibe.bot/", "annotations": []}]}
@@ -65,7 +77,10 @@ ANTHROPIC_SEARCH = _sse(
"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"}],
+ "content": [
+ {"type": "web_search_result", "title": "Avibe", "url": "https://avibe.bot/", "encrypted_content": "opaque"},
+ {"type": "web_search_result", "title": "Hosted tools", "url": HIDDEN, "encrypted_content": "opaque"},
+ ],
},
},
{"type": "content_block_stop", "index": 1},
@@ -75,6 +90,48 @@ ANTHROPIC_SEARCH = _sse(
{"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 40, "server_tool_use": {"web_search_requests": 1}}},
{"type": "message_stop"},
)
+def _anthropic_text(text: str) -> str:
+ return _sse(
+ {"type": "message_start", "message": {"usage": {"input_tokens": 1200}}},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": text}},
+ {"type": "content_block_stop", "index": 0},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 12}},
+ {"type": "message_stop"},
+ )
+
+
+def _responses_text(text: str) -> str:
+ return _responses({"id": "msg_2", "type": "message", "content": [{"type": "output_text", "text": text, "annotations": []}]})
+
+
+REFUSAL = _sse(
+ {"type": "response.created", "response": {"status": "in_progress"}},
+ {"type": "response.output_item.added", "output_index": 0, "item": {"id": "msg_3", "type": "message", "status": "in_progress", "content": []}},
+ {"type": "response.refusal.delta", "output_index": 0, "delta": f"I won't repeat {HIDDEN}."},
+ {
+ "type": "response.output_item.done",
+ "output_index": 0,
+ "item": {"id": "msg_3", "type": "message", "status": "completed", "content": [{"type": "refusal", "refusal": f"I won't repeat {HIDDEN}."}]},
+ },
+ {"type": "response.completed", "response": {"status": "completed", "usage": {"input_tokens": 900, "output_tokens": 9}}},
+)
+
+
+def _replay_reply(protocol: str, request: dict) -> str:
+ """A model answering the replay probe from what it was sent: it can name the result only the native payload
+ holds when that payload came back, and nothing more otherwise."""
+
+ text = HIDDEN if HIDDEN in json.dumps(request) else "I can't tell without searching again."
+ return _anthropic_text(text) if protocol == "anthropic" else _responses_text(text)
+
+
+
+
+def _stream(body: str) -> web.Response:
+ return web.Response(body=body.encode(), content_type="text/event-stream")
+
+
# 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"}},
@@ -117,6 +174,8 @@ async def test_a_call_probe_sends_the_production_request_and_records_only_what_i
async def respond(request):
sent.append(await request.json())
+ if len(sent) > 1:
+ return _stream(_replay_reply(source.protocol, sent[-1]))
if isinstance(body, str):
return web.Response(status=status, body=body.encode(), content_type="text/event-stream")
return web.json_response(body, status=status)
@@ -139,10 +198,10 @@ async def test_a_call_probe_sends_the_production_request_and_records_only_what_i
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
+ request = sent[0]
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 "news article published today" 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
@@ -151,12 +210,16 @@ async def test_a_call_probe_sends_the_production_request_and_records_only_what_i
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["tool"], probe["source_id"], probe["model_id"]) == ("web_search", source.id, model_id)
assert probe["call"]["outcome"] == outcome
+ # Only a verified call is followed by the replay probe; its answer here names the first result without searching.
+ assert len(sent) == (2 if written == "verified" else 1)
+ assert probe["replay"] == ({"outcome": "verified", "error": None} if written == "verified" else None)
# 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()
+ [record] = _records(service, CALL)
+ assert len(_records(service, REPLAY)) == (1 if written == "verified" else 0)
if written is None:
assert record == prior
else:
@@ -191,7 +254,7 @@ async def test_a_probe_runs_only_on_a_target_the_tool_can_run_on(tmp_path):
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.
+ # xAI's overlay declares no image tool, so there is nothing to probe.
("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),
@@ -241,8 +304,9 @@ async def test_a_probe_runs_only_on_a_target_the_tool_can_run_on(tmp_path):
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."""
+ """MH-HOSTED-007: the Tools read prices a probe before it runs, the call and the replay that may follow it: 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
@@ -261,8 +325,10 @@ def test_each_candidate_states_what_probing_it_would_cost(tmp_path):
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)}
+ # The replay sends the call's turn back and asks one question, using no tool, so it has no tool fee.
+ replay = 12000 * 2 / 1e6 + 300 * 6 / 1e6
+ assert estimates[("web_search", XAI.id)] == {"basis": "list", "usd": pytest.approx(tokens + 5 / 1000 + replay)}
+ assert estimates[("x_search", XAI.id)] == {"basis": "list", "usd": pytest.approx(tokens + 10 * 5 / 1000 + replay)}
assert estimates[("web_search", monthly.id)] == {"basis": "included"}
assert estimates[("web_search", unpriced.id)] is None
@@ -288,6 +354,8 @@ async def test_each_request_the_adapter_sends_is_its_own_pinned_call(tmp_path, m
async def respond(request):
sent.append(await request.json())
+ if len(sent) > 2:
+ return _stream(_replay_reply("anthropic", sent[-1]))
if '"ttl": "1h"' in json.dumps(sent[-1]):
return web.json_response(
{"type": "error", "error": {"type": "invalid_request_error", "message": refusal}},
@@ -300,11 +368,11 @@ async def test_each_request_the_adapter_sends_is_its_own_pinned_call(tmp_path, m
"web_search", {"source_id": ANTHROPIC.id, "model_id": "claude-sonnet-4-6"}
)
- first, resent = sent
+ first, resent, _replay = 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()
+ [record] = _records(service, CALL)
assert (record.source_id, record.status, record.basis) == (ANTHROPIC.id, "verified", "probe")
@@ -324,7 +392,7 @@ async def test_a_probe_that_verifies_its_source_records_evidence_for_the_source_
[live] = service.store.load().sources
assert live.verification_pending is None
assert result["probe"]["call"]["outcome"] == "verified"
- [record] = service.capability_evidence.records()
+ [record] = _records(service, CALL)
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"
@@ -406,8 +474,8 @@ async def test_the_probe_asks_for_no_more_output_than_a_turn_on_its_hop_would(tm
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
+ # The replay probe that follows asks for the same output.
+ assert [request["max_output_tokens"] for request in sent] == [1024, 1024]
assert result["probe"]["call"]["outcome"] == "verified"
@@ -426,11 +494,11 @@ async def test_an_api_key_source_is_probed_on_a_passthrough_model_it_does_not_li
# 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
+ request = sent[0]
# 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()
+ [record] = _records(service, CALL)
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"
@@ -446,7 +514,7 @@ async def test_a_probe_that_times_out_before_its_handle_is_still_metered(tmp_pat
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)
+ monkeypatch.setattr(service_module, "call_timeout", lambda _tool: 0.05)
service, _clock, _models = configured_service(tmp_path, sources=[XAI])
observed = ProtocolSSEState("openai_responses")
observed.observe(
@@ -498,7 +566,7 @@ async def test_a_deadline_mid_stream_ends_the_probe_as_transient(tmp_path, monke
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)
+ monkeypatch.setattr(service_module, "call_timeout", lambda _tool: 0.5)
service, _clock, _models = configured_service(tmp_path, sources=[XAI])
async def respond(request):
@@ -527,7 +595,7 @@ async def test_a_probe_settles_when_the_adapter_is_done_even_if_the_body_stays_o
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)
+ monkeypatch.setattr(service_module, "call_timeout", lambda _tool: 5)
service, _clock, _models = configured_service(tmp_path, sources=[replace(XAI, verification_pending="vp_" + "5" * 32)])
async def respond(request):
@@ -545,5 +613,353 @@ async def test_a_probe_settles_when_the_adapter_is_done_even_if_the_body_stays_o
assert elapsed < 5
assert result["probe"]["call"]["outcome"] == "verified"
assert service.store.load().sources[0].verification_pending is None
- [record] = service.capability_evidence.records()
+ [record] = _records(service, CALL)
assert record.status == "verified"
+
+
+PNG = (
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=="
+)
+
+
+ "result,outcome",
+ [
+ (PNG, "verified"),
+ ("bm90IGFuIGltYWdl", "inconclusive"),
+ # A BMP is an image, but not one a turn's sink keeps, so it proves nothing a turn could use.
+ (base64.b64encode(b"BM" + bytes(52)).decode(), "inconclusive"),
+ ],
+ ids=["image", "not-an-image", "bmp"],
+)
+async def test_an_image_probe_verifies_only_an_image_vibey_could_keep(tmp_path, result, outcome):
+ """MH-HOSTED-007: the image call probe reads the generated image through Vibey's own parsing, which keeps it
+ only when it is an image; a probe keeps no file, and an image has no replay."""
+ openai = _source("src_probe0009", "OpenAI 密钥", vendor="openai", protocol="openai_responses", model_id="gpt-6-astra")
+ service, _clock, _models = configured_service(tmp_path, sources=[openai])
+ sent = []
+ image_call = {
+ "id": "ig_1",
+ "type": "image_generation_call",
+ "status": "completed",
+ "result": result,
+ "revised_prompt": "A blue circle on a white background",
+ "size": "1024x1024",
+ }
+
+ async def respond(request):
+ sent.append(await request.json())
+ return _stream(_responses(image_call))
+
+ async with loopback_engine(tmp_path, service, respond):
+ result_payload = await service.probe_hosted_tool("image_generation", {"source_id": openai.id, "model_id": "gpt-6-astra"})
+
+ [request] = sent
+ declaration = hosted_tool_spec("openai", "openai_responses", "gpt-6-astra", "image_generation").declaration
+ assert request["tools"] == [declaration] and request["tool_choice"] == "required"
+ probe = result_payload["probe"]
+ _assert_valid("hosted-tool-probe-result.schema.json", probe)
+ assert (probe["call"]["outcome"], probe["replay"]) == (outcome, None)
+ records = _records(service, EvidenceFeature.hosted("image_generation", "call"))
+ assert [record.status for record in records] == (["verified"] if outcome == "verified" else [])
+
+
+REPLAY_CASES = [
+ # (case, Source, the call's response, the replay's response or status and body, replay outcome, record)
+ ("names-a-result", XAI, _responses(SEARCH, ANSWER), "answer-from-payload", "verified", "verified"),
+ ("anthropic-names-a-result", ANTHROPIC, ANTHROPIC_SEARCH, "answer-from-payload", "verified", "verified"),
+ # Restating the answer it already gave proves nothing: that text came back in the visible transcript.
+ ("restates-the-visible-answer", XAI, _responses(SEARCH, ANSWER), _responses_text("https://avibe.bot/"), "inconclusive", None),
+ # A URL that only starts like the hidden result is a different URL, and so is one with another fragment.
+ ("names-a-longer-url", XAI, _responses(SEARCH, ANSWER), _responses_text(HIDDEN + "-old"), "inconclusive", None),
+ ("names-another-fragment", XAI, _responses(SEARCH, ANSWER), _responses_text(HIDDEN + "#other"), "inconclusive", None),
+ # Linked text names the result as surely as the URL written out.
+ ("cites-the-result", XAI, _responses(SEARCH, ANSWER), _responses({
+ "id": "msg_2",
+ "type": "message",
+ "content": [{
+ "type": "output_text",
+ "text": "The hosted tools docs.",
+ "annotations": [{"type": "url_citation", "url": HIDDEN, "start_index": 4, "end_index": 21, "title": "docs"}],
+ }],
+ }), "verified", "verified"),
+ # A refusal is inconclusive, even one that quotes the result.
+ ("refuses-quoting-the-result", XAI, _responses(SEARCH, ANSWER), REFUSAL, "inconclusive", None),
+ # The way a sentence ends a URL does not change it.
+ ("names-it-in-a-sentence", XAI, _responses(SEARCH, ANSWER), _responses_text(f"The other one was {HIDDEN}."), "verified", "verified"),
+ # Searching again instead of using the results it holds is what a dropped replay looks like.
+ ("searches-again", XAI, _responses(SEARCH, ANSWER), _responses(SEARCH, ANSWER), "unsupported", "unsupported"),
+ ("names-no-result", XAI, _responses(SEARCH, ANSWER), _responses_text("I can't tell."), "inconclusive", None),
+ (
+ "anthropic-refuses-the-replayed-result",
+ ANTHROPIC,
+ ANTHROPIC_SEARCH,
+ (400, {"type": "error", "error": {"type": "invalid_request_error", "message": "Invalid encrypted_content in search_result block"}}),
+ "unsupported",
+ "unsupported",
+ ),
+]
+
+
+ "source,first,second,outcome,written", [case[1:] for case in REPLAY_CASES], ids=[case[0] for case in REPLAY_CASES]
+)
+async def test_a_verified_call_is_followed_by_the_replay_probe(tmp_path, source, first, second, outcome, written):
+ """MH-HOSTED-007 (§3.2, §12 item 23): the replay probe sends the call's turn back with its native payload in
+ place, asks for a result it returned, and records only a named result, a new call or a refusal of the payload."""
+ 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 len(sent) == 1:
+ return _stream(first)
+ if isinstance(second, tuple):
+ return web.json_response(second[1], status=second[0])
+ if second == "answer-from-payload":
+ return _stream(_replay_reply(source.protocol, sent[-1]))
+ return _stream(second)
+
+ async with loopback_engine(tmp_path, service, respond):
+ result = await service.probe_hosted_tool("web_search", {"source_id": source.id, "model_id": model_id})
+
+ call, replay = sent
+ # The native declaration is still present, nothing is forced, and the call's own items go back verbatim.
+ assert replay["tools"] == call["tools"] and "tool_choice" not in replay
+ # Its instructions ask for an answer from the results it holds, never for the call the question rules out.
+ system = "instructions" if source.protocol == "openai_responses" else "system"
+ assert replay[system] != call[system] and "without using any tool" in json.dumps(replay[system])
+ native = SEARCH if source.protocol == "openai_responses" else {"type": "web_search_tool_result"}
+ assert json.dumps(native["type"]) in json.dumps(replay)
+ assert "other results you found" in json.dumps(replay)
+ assert HIDDEN in json.dumps(replay)
+ probe = result["probe"]
+ _assert_valid("hosted-tool-probe-result.schema.json", probe)
+ assert probe["call"]["outcome"] == "verified"
+ assert probe["replay"]["outcome"] == outcome
+ # Every reply here completed (or named the payload in a refusal): the verdict is read from it, not from a failure.
+ assert probe["replay"]["error"] is None
+ assert [record.status for record in _records(service, REPLAY)] == ([written] if written else [])
+
+
+async def test_a_replay_sends_the_results_only_in_their_native_payload(tmp_path):
+ """MH-HOSTED-007: the call's reasoning, readable or encrypted, can restate a result; it never goes back with the
+ replay, so a Source that drops the payload has nowhere else to read the result from."""
+ reasoning = {
+ "id": "rs_1",
+ "type": "reasoning",
+ "summary": [{"type": "summary_text", "text": f"The results were https://avibe.bot/ and {HIDDEN}."}],
+ "encrypted_content": "opaque-reasoning",
+ }
+ service, _clock, _models = configured_service(tmp_path, sources=[XAI])
+ sent = []
+
+ async def respond(request):
+ sent.append(await request.json())
+ return _stream(_responses(reasoning, SEARCH, ANSWER) if len(sent) == 1 else _replay_reply("openai_responses", sent[-1]))
+
+ async with loopback_engine(tmp_path, service, respond):
+ await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
+
+ replay = sent[1]
+ elsewhere = [item for item in replay["input"] if item.get("type") != "web_search_call"]
+ assert any(item.get("type") == "web_search_call" for item in replay["input"])
+ assert HIDDEN not in json.dumps(elsewhere) and "reasoning" not in json.dumps(elsewhere)
+
+
+async def test_no_replay_runs_when_the_visible_answer_shows_every_result(tmp_path):
+ """MH-HOSTED-007: a replay is proved only by a result the visible answer does not show; with none, no replay is
+ spent, and the replay stays unknown, so turns replay synthetically."""
+ single = {**SEARCH, "action": {**SEARCH["action"], "sources": [{"type": "url", "url": "https://avibe.bot/"}]}}
+ service, _clock, _models = configured_service(tmp_path, sources=[XAI])
+ sent = []
+
+ async def respond(request):
+ sent.append(await request.json())
+ return _stream(_responses(single, ANSWER))
+
+ 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 len(sent) == 1
+ assert (result["probe"]["call"]["outcome"], result["probe"]["replay"]) == ("verified", None)
+ assert _records(service, REPLAY) == []
+
+
+async def test_a_replay_the_probe_has_no_time_left_for_reports_try_again(tmp_path, monkeypatch):
+ """MH-HOSTED-007: the whole probe answers inside the UI's RPC wait; a replay that could not finish in what is left
+ is not sent, and reads as a transient failure to try again."""
+ from core.handlers.model_hub import service as service_module
+
+ monkeypatch.setattr(service_module, "PROBE_BUDGET_SECONDS", 30.0)
+ service, _clock, _models = configured_service(tmp_path, sources=[XAI])
+ sent = []
+
+ async def respond(request):
+ sent.append(await request.json())
+ return _stream(_responses(SEARCH, ANSWER))
+
+ 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 len(sent) == 1
+ assert result["probe"]["replay"] == {"outcome": "transient", "error": None}
+ assert _records(service, REPLAY) == []
+
+
+async def test_a_replay_goes_only_to_the_source_identity_the_call_was_recorded_for(tmp_path, monkeypatch):
+ """MH-HOSTED-007: the replay carries the call's provider-native payload, so a Source whose endpoint or credential
+ changed after the call never receives it; the call's result stands and no replay is reported."""
+ from core.handlers.model_hub import service as service_module
+
+ # The fixture store keeps the Source object it is given, and this test edits it.
+ service, _clock, _models = configured_service(tmp_path, sources=[replace(XAI)])
+ sent = []
+ build_replay = service_module.hosted_replay_request
+
+ def replaced_endpoint_first(*args, **kwargs):
+ config = service.store.load()
+ config.sources[0].base_url = "https://relay.invalid/v1"
+ service.store.save(config)
+ return build_replay(*args, **kwargs)
+
+ monkeypatch.setattr(service_module, "hosted_replay_request", replaced_endpoint_first)
+
+ async def respond(request):
+ sent.append(await request.json())
+ return _stream(_responses(SEARCH, ANSWER) if len(sent) == 1 else _replay_reply("openai_responses", sent[-1]))
+
+ 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 len(sent) == 1
+ assert (result["probe"]["call"]["outcome"], result["probe"]["replay"]) == ("verified", None)
+ assert [record.status for record in _records(service, CALL)] == ["verified"]
+ assert _records(service, REPLAY) == []
+
+
+ "stop_reason,text,outcome",
+ [
+ ("stop", HIDDEN, "verified"),
+ ("safety", HIDDEN, "inconclusive"),
+ ("refusal", HIDDEN, "inconclusive"),
+ # Provider text that is not a well-formed URL compares as written and never fails the probe.
+ ("stop", "https://[invalid", "inconclusive"),
+ ],
+)
+def test_a_replay_answer_counts_only_when_it_completed_and_names_a_hidden_result(stop_reason, text, outcome):
+ """MH-HOSTED-007: a blocked or refused answer proves nothing, whatever it quotes, and a malformed URL is just text."""
+ assert _replay_verdict(text, {HIDDEN, "https://[also-invalid"}, stop_reason=stop_reason) == outcome
+
+
+WIKI = "https://en.wikipedia.org/wiki/Search_(computing)"
+
+
+ "asked,text,outcome",
+ [
+ # Prose and Markdown around a URL do not change it.
+ (HIDDEN, f"See [the docs]({HIDDEN}).", "verified"),
+ (HIDDEN, f"**{HIDDEN}**", "verified"),
+ (WIKI, f"It is {WIKI}.", "verified"),
+ (WIKI, f"(see {WIKI})", "verified"),
+ # A result's own URL is exact: an answer without the punctuation it ends in names another URL.
+ (HIDDEN + "!", f"It is {HIDDEN}, I think.", "inconclusive"),
+ (HIDDEN + "!", f"It is {HIDDEN}!.", "verified"),
+ (WIKI, "https://en.wikipedia.org/wiki/Search_", "inconclusive"),
+ # Only the scheme and host are case-insensitive; a trailing slash or another user name is another URL.
+ ("https://Example.COM/result", "HTTPS://example.com/result", "verified"),
+ ("https://Alice:[email protected]/result", "https://alice:[email protected]/result", "inconclusive"),
+ (HIDDEN, f"It is {HIDDEN}/", "inconclusive"),
+ ],
+)
+def test_a_replay_answer_names_a_result_by_its_exact_url(asked, text, outcome):
+ """MH-HOSTED-007: only where prose ends a written URL is ambiguous; the result's URL is never trimmed."""
+ assert _replay_verdict(text, {asked}) == outcome
+
+
+def test_a_result_the_answer_shows_in_any_reading_is_not_hidden():
+ """MH-HOSTED-007: a shown result taken for hidden could verify a replay that only restated the visible answer."""
+ from core.agent_core.messages import (
+ AssistantMessage, HostedAction, HostedNative, HostedRecord, HostedSource, HostedSummary, HostedToolBlock, Origin,
+ TextBlock,
+ )
+ from core.handlers.model_hub.hosted_probe import hidden_result_urls
+
+ call = HostedToolBlock(
+ id="ws_1",
+ tool="web_search",
+ action=HostedAction(type="search", queries=("avibe",)),
+ record=HostedRecord(status="completed", sources=(HostedSource(url=HIDDEN + "."), HostedSource(url=WIKI))),
+ native=HostedNative(source_id=XAI.id, payload=({"type": "web_search_call", "id": "ws_1"},)),
+ )
+ for text, hidden in [
+ (f"Read {HIDDEN}", {WIKI}),
+ (f"Read {WIKI}.", {HIDDEN + "."}),
+ (f"Read {WIKI}/", {HIDDEN + "."}),
+ ("Read none", {HIDDEN + ".", WIKI}),
+ ]:
+ answer = AssistantMessage(
+ content=(call, TextBlock(text=text)),
+ origin=Origin("xai", "openai_responses", "grok-4.6"),
+ stop_reason="stop",
+ hosted_summary=HostedSummary(),
+ )
+ assert hidden_result_urls(answer) == hidden
+
+
+def _replay_verdict(text, asked, *, stop_reason="stop"):
+ from core.agent_core.ai.provider import Done
+ from core.agent_core.messages import AssistantMessage, Origin, TextBlock
+ from core.handlers.model_hub.adapter import RawCallOutcome, RawOutcomeKind
+ from core.handlers.model_hub.hosted_probe import replay_outcome
+
+ answer = AssistantMessage(
+ content=(TextBlock(text=text),), origin=Origin("xai", "openai_responses", "grok-4.6"), stop_reason=stop_reason,
+ )
+ ok = RawCallOutcome(RawOutcomeKind.SUCCESS, 200, None, None, True, "grok-4.6", XAI.id)
+ return replay_outcome("web_search", Done(answer), ok, None, asked=frozenset(asked), carried=True)
+
+
+async def test_a_re_probe_restores_replay_a_narrow_rule_demoted(tmp_path):
+ """MH-HOSTED-007: a 400 on a replayed payload teaches 'replay unsupported' for this Source, also when the payload
+ was minted under an identity it had before (a wrong attribution: it refuses a foreign blob, not replay). That
+ record expires on its own and never outlives a user's re-probe, which replaces it."""
+ service, clock, _models = configured_service(tmp_path, sources=[XAI])
+ sent = []
+
+ async def respond(request):
+ sent.append(await request.json())
+ return _stream(_responses(SEARCH, ANSWER) if len(sent) == 1 else _replay_reply("openai_responses", sent[-1]))
+
+ async with loopback_engine(tmp_path, service, respond):
+ [live] = service.store.load().sources
+ service.capability_evidence.write(
+ EvidenceRecord(
+ source_id=XAI.id,
+ model_id="grok-4.6",
+ feature=REPLAY,
+ status="unsupported",
+ basis="observed",
+ observed_at=clock.now(),
+ engine=service.engine_stamp,
+ shape=HOSTED_PROBE_SHAPE,
+ source_identity=identity_digest(live),
+ detail="400 invalid_request_error",
+ ),
+ live=[live],
+ )
+ result = await service.probe_hosted_tool("web_search", {"source_id": XAI.id, "model_id": "grok-4.6"})
+
+ assert result["probe"]["replay"]["outcome"] == "verified"
+ [record] = _records(service, REPLAY)
+ assert (record.status, record.basis) == ("verified", "probe")
diff --git a/ui/src/components/settings/models/modelsApi.ts b/ui/src/components/settings/models/modelsApi.ts
index 7065c3643..6fbef1603 100644
--- a/ui/src/components/settings/models/modelsApi.ts
+++ b/ui/src/components/settings/models/modelsApi.ts
@@ -443,7 +443,7 @@ export const apiFailure = (
// backstop for a server that never answers, so it must outlast that controlled
// failure. The margin covers CSRF acquisition, both transits (including a
// tunnel), one fast CSRF-rejected attempt and replay, handler dispatch, and body
-// decoding. Keep the ceiling aligned with model_hub_client.py:_RPC_TIMEOUT_SECONDS.
+// decoding. Keep the ceiling aligned with core/handlers/model_hub/hosted_probe.py:MODEL_HUB_RPC_TIMEOUT_SECONDS.
export const MODEL_HUB_RPC_CEILING_MS = 300_000;
const TRANSPORT_MARGIN_MS = 30_000;
export const MODEL_HUB_REQUEST_DEADLINE_MS =
diff --git a/ui/src/components/settings/models/modelsApiDeadline.test.ts b/ui/src/components/settings/models/modelsApiDeadline.test.ts
index d63fcc310..19f7957f1 100644
--- a/ui/src/components/settings/models/modelsApiDeadline.test.ts
+++ b/ui/src/components/settings/models/modelsApiDeadline.test.ts
@@ -18,8 +18,9 @@ afterEach(() => {
describe('Model Hub request deadlines', () => {
it('keeps the browser backstop beyond the backend RPC ceiling', async () => {
- const backendSource = await readFile('../vibe/model_hub_client.py', 'utf8');
- const match = backendSource.match(/_RPC_TIMEOUT_SECONDS\s*=\s*([\d.]+)/);
+ // The server side owns the RPC ceiling; the UI-process client imports it from there.
+ const backendSource = await readFile('../core/handlers/model_hub/hosted_probe.py', 'utf8');
+ const match = backendSource.match(/MODEL_HUB_RPC_TIMEOUT_SECONDS(?::\s*Final)?\s*=\s*([\d.]+)/);
expect(match?.[1]).toBeDefined();
expect(MODEL_HUB_RPC_CEILING_MS).toBe(Number(match![1]) * 1_000);
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index b1d8e4a72..fed9e51cb 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -8,6 +8,7 @@ import httpx
from core.handlers.model_hub import ModelHubError
from vibe import internal_client
+from core.handlers.model_hub.hosted_probe import MODEL_HUB_RPC_TIMEOUT_SECONDS
from core.handlers.model_hub.usage import USAGE_DEFAULT_WINDOW_DAYS
@@ -17,7 +18,6 @@ _TRANSPORT_ERRORS = (
OSError,
internal_client.InternalServerUnavailable,
)
-MODEL_HUB_RPC_TIMEOUT_SECONDS = 300.0
_REORDER_ORDER_UNSET = object()