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): web search service chain behind the activation flag (S2b-1) (#2896)

Call White424b3fd0c929
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 7c21d1da1..b8ab7f9c5 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -17,7 +17,7 @@ import asyncio
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
-from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocol, Sequence
+from typing import Any, AsyncIterator, Awaitable, Callable, Final, Literal, Mapping, Protocol, Sequence
from .stream_wire import ProtocolSSEState, ProtocolUsageReport
@@ -578,13 +578,15 @@ class EngineAdapter(Protocol):
credential_ref: str,
request: Mapping[str, Any],
*,
- on_sent: Callable[[], None] | None = None,
+ on_sent: Callable[[], Awaitable[None] | None] | None = None,
) -> SearchResponse:
"""Make exactly one catalog-host search request from Model Hub custody.
``on_sent`` fires once after the connection (including TLS) is ready and
immediately before aiohttp writes this request. A callback failure stops
- the request before any request bytes are sent.
+ the request before any request bytes are sent. An async callback is
+ awaited for final controller admission without holding a mutation lock
+ during DNS/TCP/TLS; existing synchronous callbacks remain supported.
"""
...
diff --git a/core/handlers/model_hub/hosted_tools.py b/core/handlers/model_hub/hosted_tools.py
index 86f76359e..0804a5872 100644
--- a/core/handlers/model_hub/hosted_tools.py
+++ b/core/handlers/model_hub/hosted_tools.py
@@ -68,7 +68,7 @@ SpecLookup = Callable[[str, str, str, str], Optional[HostedToolSpec]]
UNKNOWN_ENGINE_RELEASE = "unknown-engine"
NATIVE_REPLAY_PROTOCOLS: frozenset[str] = frozenset({"anthropic", "openai_responses"})
-# S2 enables this together with the chain, after S3/S4 and disclosure ship. Never a user-facing toggle.
+# S2b-2 enables this after the S6 disclosure ships. Never a user-facing toggle.
SEARCH_SERVICES_ACTIVE: Final = False
Assumption = Literal["assumed", "unsupported"]
@@ -224,6 +224,8 @@ class ExecutorCandidate:
declaration: Mapping[str, Any]
include: tuple[str, ...]
price: Any = None
+ kind: str = "model"
+ settings: Mapping[str, Any] | None = None
def executor_candidates(
@@ -244,11 +246,51 @@ def executor_candidates(
candidate = executor_candidate(source, model_id, tool, evidence=evidence, spec_for=spec_for) if model_id else None
if candidate is not None:
candidates[source.id] = candidate
- order = hosted_tool_setting(config, tool).executor_order or ()
+ setting = hosted_tool_setting(config, tool)
+ if tool == "web_search" and SEARCH_SERVICES_ACTIVE:
+ return _search_chain(config, setting, candidates)
+ order = setting.executor_order or ()
first = [candidates[source_id] for source_id in order if source_id in candidates]
return tuple(first + [candidate for source_id, candidate in candidates.items() if source_id not in order])
+def _search_chain(
+ config: ModelHubConfig, setting: ModelHubHostedToolConfig, models: Mapping[str, ExecutorCandidate],
+) -> tuple[ExecutorCandidate, ...]:
+ """One role per Source; stale/unnamed service roles precede the first model, without a config write."""
+
+ services: dict[str, ExecutorCandidate] = {}
+ remaining = dict(models)
+ disabled: list[ExecutorCandidate] = []
+ ordered = _vibey_order(config)
+ by_id = {source.id: source for source in ordered}
+ first = [by_id[sid] for sid in (setting.service_order or ()) if sid in by_id and by_id[sid].protocol == "search"]
+ sources = first + [s for s in ordered if s.protocol == "search" and s not in first]
+ sources += [s for s in ordered if s.protocol != "search"]
+ for source in sources:
+ service = model_hub_search_service(source)
+ settings = search_service_settings(setting, source)
+ if service is None or settings is None:
+ continue
+ candidate = ExecutorCandidate(source, service["service_id"], {}, (), kind="service", settings=settings)
+ if settings["enabled"]:
+ services[source.id] = candidate
+ remaining.pop(source.id, None)
+ elif source.id not in remaining:
+ disabled.append(candidate)
+ automatic = {**services, **remaining}
+ kinds = setting.executor_order_kinds or {}
+ named = [
+ automatic[sid] for sid in (setting.executor_order or ())
+ if sid in automatic and automatic[sid].kind == kinds.get(sid, "model")
+ ]
+ named_ids = {candidate.source.id for candidate in named}
+ additions = [c for sid, c in services.items() if sid not in named_ids]
+ position = next((i for i, c in enumerate(named) if c.kind == "model"), len(named))
+ return tuple(named[:position] + additions + named[position:]
+ + [c for sid, c in remaining.items() if sid not in named_ids] + disabled)
+
+
def listed_executor_model(source: ModelHubSourceConfig, tool: str, *, spec_for: SpecLookup) -> Optional[str]:
"""The model this Source runs proxied ``tool`` searches on: the first of its executor models it lists that runs
the tool (§6).
@@ -428,13 +470,22 @@ def freeze_turn_tools(config: ModelHubConfig, *, evidence: HostedEvidence, spec_
tools = frozenset(tool for tool in enabled if tool != IMAGE_TOOL or images)
executors = {
tool: tuple(
- ExecutorSlot(candidate.source.id, candidate.model_id, identity_digest(candidate.source))
+ ExecutorSlot(
+ candidate.source.id, candidate.model_id, identity_digest(candidate.source),
+ kind=candidate.kind,
+ results=candidate.settings["results"] if candidate.settings else None,
+ enabled=candidate.settings["enabled"] if candidate.settings else True,
+ label=candidate.source.display_name[:64] if SEARCH_SERVICES_ACTIVE and tool == "web_search" else "",
+ )
for candidate in executor_candidates(config, tool, evidence=evidence, spec_for=spec_for)
)
for tool in tools
if tool != IMAGE_TOOL
}
- return TurnHostedTools(tools, executors, images)
+ return TurnHostedTools(
+ tools, executors, images,
+ prefer_native=hosted_tool_setting(config, "web_search").prefer_native if SEARCH_SERVICES_ACTIVE else None,
+ )
def hop_hosted_tools(
@@ -454,7 +505,11 @@ def hop_hosted_tools(
entries: dict[str, dict[str, Any]] = {}
for tool in sorted(turn.tools - {IMAGE_TOOL}):
- facts = hosted_tool_facts(source, model_id, tool, evidence=evidence, spec_for=spec_for)
+ facts = (
+ HostedToolFacts(native="unsupported", replay="unsupported")
+ if tool == "web_search" and turn.prefer_native is False
+ else hosted_tool_facts(source, model_id, tool, evidence=evidence, spec_for=spec_for)
+ )
entry: dict[str, Any] = {"native": facts.native, "replay": facts.replay}
if facts.native == "assumed":
entry["declaration"] = dict(facts.declaration or {})
@@ -506,7 +561,8 @@ def search_executor_kind(source: ModelHubSourceConfig, setting: ModelHubHostedTo
def _service_candidate_payload(
- source: ModelHubSourceConfig, setting: ModelHubHostedToolConfig, *, trial_pending: bool
+ source: ModelHubSourceConfig, setting: ModelHubHostedToolConfig, *, trial_pending: bool,
+ cooldown_until: str | None,
) -> dict[str, Any]:
service = model_hub_search_service(source)
assert service is not None
@@ -521,8 +577,7 @@ def _service_candidate_payload(
"settings": search_service_settings(setting, source),
"state": source.state.to_payload(),
"trial_pending": trial_pending,
- # S2's service-scoped cooldown owner supplies this at activation; S1b has no service attempts.
- "cooldown_until": None,
+ "cooldown_until": cooldown_until,
}
@@ -631,6 +686,7 @@ def hosted_tools_status(
spec_for: SpecLookup,
image_price: Callable[[ModelHubSourceConfig, ImageModelSpec], Optional[dict[str, Any]]],
search_trial_pending: Callable[[str], bool] = lambda _source_id: False,
+ search_cooldown_until: Callable[[str, str], str | None] = lambda _sid, _service: None,
) -> dict[str, Any]:
"""What Models → Tools reads (``hosted-tools-status.schema.json``): settings, saved and effective, and status."""
@@ -652,6 +708,11 @@ def hosted_tools_status(
"relay": is_relay(candidate.source),
"price": _price_payload(candidate.price),
}
+ if candidate.kind == "model" else _service_candidate_payload(
+ candidate.source, setting,
+ trial_pending=search_trial_pending(candidate.source.id),
+ cooldown_until=search_cooldown_until(candidate.source.id, candidate.model_id),
+ )
for candidate in chain
]
if tool == "web_search":
@@ -662,18 +723,7 @@ def hosted_tools_status(
if source_id in sources and (service := model_hub_search_service(sources[source_id])) is not None
}
entry["service_order"] = [source_id for source_id in (setting.service_order or ()) if source_id in sources]
- # This is the only activation gate for BOTH read additions. S2 supplies the unified chain
- # and its placement rule here when enabling it; this lane only defines the projection.
if SEARCH_SERVICES_ACTIVE:
- service_rows = [
- _service_candidate_payload(source, setting, trial_pending=search_trial_pending(source.id))
- for source in config.sources
- if model_hub_search_service(source) is not None and search_executor_kind(source, setting) == "service"
- ]
- service_ids = {row["source_id"] for row in service_rows}
- entry["executor_candidates"] = service_rows + [
- row for row in entry["executor_candidates"] if row["source_id"] not in service_ids
- ]
entry["service_vendors"] = _service_vendors(config)
else:
choices = image_choices(config, evidence=evidence)
diff --git a/core/handlers/model_hub/hosted_turn.py b/core/handlers/model_hub/hosted_turn.py
index 4d2b35bf9..14ccc27e4 100644
--- a/core/handlers/model_hub/hosted_turn.py
+++ b/core/handlers/model_hub/hosted_turn.py
@@ -25,6 +25,10 @@ class ExecutorSlot:
source_id: str
model_id: str
identity: str
+ kind: str = "model"
+ results: int | None = None
+ enabled: bool = True
+ label: str = ""
@dataclass(frozen=True)
@@ -34,3 +38,5 @@ class TurnHostedTools:
executors: Mapping[str, tuple[ExecutorSlot, ...]]
# The image_generate enum, default first; empty when the turn has no image tool.
images: tuple[ImageChoice, ...] = ()
+ # None denotes the released, activation-off turn shape.
+ prefer_native: bool | None = None
diff --git a/core/handlers/model_hub/rpc.py b/core/handlers/model_hub/rpc.py
index bb764c39b..9987fd205 100644
--- a/core/handlers/model_hub/rpc.py
+++ b/core/handlers/model_hub/rpc.py
@@ -223,6 +223,8 @@ async def dispatch_model_hub_rpc(
return await service.set_hosted_tool(payload.get("tool"), payload.get("setting"))
if operation == "clear_hosted_refusals":
return await service.clear_hosted_refusals(payload.get("tool"), payload.get("target"))
+ if operation == "clear_service_cooldown":
+ return await service.clear_service_cooldown(payload.get("source_id"), payload.get("service_id"))
if operation == "clear_source_evidence":
return await service.clear_source_evidence(payload.get("source_id"), payload.get("target"))
if operation == "get_agent_chain":
diff --git a/core/handlers/model_hub/search_chain.py b/core/handlers/model_hub/search_chain.py
new file mode 100644
index 000000000..1c1a51918
--- /dev/null
+++ b/core/handlers/model_hub/search_chain.py
@@ -0,0 +1,388 @@
+"""Controller-owned mixed search chain; the dormant producer of service attempts.
+
+The turn freezes choices, not runtime health. Every slot is classified on the
+current snapshot; a service rechecks that snapshot immediately before writing
+request bytes. Settlement owns observed status even when the caller stops.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import replace
+from typing import TYPE_CHECKING, Any, Callable
+
+from config.v2_config import ModelHubSourceStateConfig, model_hub_search_service
+
+from .adapter import SearchResponse
+from .async_owner import await_owned_task
+from .capability_evidence import identity_digest, utc_text
+from .hosted_executor import ExecutorCall, Failure, call_timeout, failed_record
+from .hosted_turn import ExecutorSlot, TurnHostedTools
+from .resolver import parse_model_hub_timestamp
+from .retry import source_identity
+from .search_services import ATTEMPT_SECONDS, ZERO, map_response, search_request
+
+if TYPE_CHECKING:
+ from .service import ModelHubService
+
+
+class _NotAdmitted(Exception):
+ pass
+
+
+class SearchChain:
+ def __init__(self, owner: ModelHubService, call: ExecutorCall, turn: TurnHostedTools, say: Callable[..., str]):
+ self.owner, self.call, self.turn, self.say = owner, call, turn, say
+ self.deadline = asyncio.get_running_loop().time() + call_timeout(call.tool)
+ self.facts: list[dict[str, Any]] = []
+ self.tried: list[Any] = []
+ self.query_limits: list[int] = []
+ self.with_facts = any(slot.kind == "service" for slot in turn.executors.get(call.tool, ()))
+
+ async def classify(self, slot: ExecutorSlot, *, locked: bool = False):
+ if not locked:
+ async with self.owner._mutation_lock:
+ return await self.classify(slot, locked=True)
+ config = await asyncio.to_thread(self.owner.store.load)
+ # Recovery owns live half-open reservations on this loop. Its annotation
+ # step is memory-only; never call recovery_annotations(), which reloads
+ # the config, or move the mutable coordinator to a worker.
+ annotations = self.owner.recovery.annotations(config)
+ return await asyncio.to_thread(self._classify, slot, config, annotations)
+
+ def _classify(self, slot: ExecutorSlot, config, annotations):
+ """First matching skip only: unavailable, disabled, blocked, cooling, query length.
+
+ No mutation: in particular a skipped slot neither reserves a trial nor
+ advances any fence. Runs on a worker over the final-admission snapshot.
+ """
+ owner = self.owner
+ source = next((s for s in config.sources if s.id == slot.source_id), None)
+ fact = {"source_id": slot.source_id, "label": slot.label or slot.source_id, "kind": slot.kind, "outcome": "skipped"}
+ unavailable = source is None or identity_digest(source) != slot.identity
+ service = None
+ if not unavailable:
+ fact["label"] = source.display_name[:64]
+ if slot.kind == "service":
+ service = model_hub_search_service(source)
+ unavailable = service is None or service["service_id"] != slot.model_id or not source.credential_ref
+ else:
+ unavailable = owner._admitted_executor(slot, self.call.tool) is None
+ if unavailable:
+ fact["skipped"] = "unavailable"
+ elif not slot.enabled:
+ fact["skipped"] = "disabled"
+ elif source.state.status in {"needs_action", "error"} and not (
+ slot.kind == "service" and owner.search_reenable_trial_armed(source.id)
+ ):
+ fact.update(skipped="blocked", needs_action=source.state.detail_key or "models.source.error.unclassified")
+ else:
+ now = owner.now()
+ deadlines = []
+ if service is not None:
+ until = owner._service_cooldowns.until(source, slot.model_id, now)
+ if until is not None:
+ deadlines.append(until)
+ if source.state.status == "cooldown" and source.state.retry_at:
+ until = parse_model_hub_timestamp(source.state.retry_at)
+ if until > now:
+ deadlines.append(until)
+ # Model Sources also honor the live recovery coordinator, including
+ # its retired persisted cooldowns and in-flight half-open requests.
+ if source.protocol != "search":
+ annotation = annotations.get(source.id)
+ if annotation is not None:
+ if annotation.retired_cooldown == (source.state.retry_at, source.state.detail_key):
+ deadlines = [d for d in deadlines if service is not None and d == owner._service_cooldowns.until(source, slot.model_id, now)]
+ if annotation.retry_at:
+ deadlines.append(parse_model_hub_timestamp(annotation.retry_at))
+ elif annotation.in_flight:
+ fact["skipped"] = "unavailable"
+ if "skipped" not in fact:
+ if deadlines:
+ fact.update(skipped="cooling", retry_at=utc_text(max(deadlines)))
+ elif service is not None and (limit := service["limits"].get("query_max_chars")) is not None and len(self.call.arguments["query"]) > limit:
+ fact["skipped"] = "query_too_long"
+ else:
+ return source, service, None
+ return source, service, fact
+
+ async def run(self) -> dict:
+ from .service import _cost_payload
+
+ slots = self.turn.executors.get(self.call.tool, ())
+ for slot in slots:
+ if asyncio.get_running_loop().time() >= self.deadline:
+ break
+ source, catalog, skip = await self.classify(slot)
+ if skip is not None:
+ self.facts.append(skip)
+ if skip["skipped"] == "query_too_long":
+ self.query_limits.append(catalog["limits"]["query_max_chars"])
+ continue
+ if slot.kind == "service":
+ attempt, skip = await self.service_attempt(slot, source, catalog)
+ else:
+ final_skip = None
+
+ async def admitted():
+ nonlocal final_skip
+ final, _, final_skip = await self.classify(slot, locked=True)
+ return final if final_skip is None else None
+
+ attempt = await self.owner._executor_attempt(
+ self.call, slot, deadline=self.deadline, say=self.say, admission=admitted,
+ )
+ skip = final_skip
+ if attempt is None:
+ if skip is None:
+ _, _, skip = await self.classify(slot)
+ self.facts.append(skip or {
+ "source_id": slot.source_id, "label": slot.label or slot.source_id,
+ "kind": slot.kind, "outcome": "skipped", "skipped": "unavailable",
+ })
+ continue
+ self.tried.append(attempt)
+ fact = {
+ "source_id": attempt.source.id, "label": attempt.source.display_name[:64], "kind": slot.kind,
+ "outcome": "completed" if attempt.record["status"] == "completed" else "failed",
+ }
+ if fact["outcome"] == "failed" and attempt.record.get("error_code"):
+ fact["error_code"] = attempt.record["error_code"]
+ cost = attempt.cost if attempt.billable or slot.kind == "service" else ZERO
+ if cost is not None:
+ fact["cost"] = _cost_payload(cost)
+ if attempt.superseded and fact["outcome"] == "failed":
+ fact["superseded"] = True
+ self.facts.append(fact)
+ if not attempt.moves_on:
+ break
+ last = self.tried[-1] if self.tried else None
+ record = last.record if last is not None else None
+ if last is None or last.record["status"] == "failed":
+ reason = self.terminal_reason()
+ if self.tried:
+ names = ", ".join(dict.fromkeys(attempt.source.display_name for attempt in self.tried))
+ reason = reason.also(self.say("modelHub.hostedTools.triedSources", sources=names))
+ if not slots:
+ from .hosted_tools import refused_executors
+ from .service import hosted_tool_spec
+
+ current = await asyncio.to_thread(self.owner.store.load)
+ refused = await asyncio.to_thread(
+ refused_executors, current, self.call.tool,
+ evidence=self.owner.hosted_evidence(), spec_for=hosted_tool_spec,
+ )
+ if refused:
+ names = self.say("modelHub.hostedTools.listSeparator").join(source.display_name for source in refused)
+ reason = Failure(self.say("modelHub.hostedTools.noExecutor.web_search.refused", sources=names), None)
+ record = failed_record(reason, last.record.get("sources") if last is not None else None)
+ if self.with_facts:
+ record = {**record, "attempts": self.facts}
+ answer = {"record": record}
+ if last is not None:
+ execution = last.execution()
+ earlier = [attempt.failed_attempt() for attempt in self.tried[:-1] if attempt.billable]
+ if earlier:
+ execution["failed_attempts"] = earlier
+ answer["execution"] = execution
+ return answer
+
+ def terminal_reason(self) -> Failure:
+ if self.query_limits:
+ return Failure(self.say("modelHub.hostedTools.queryLimit", limit=str(max(self.query_limits))), "search_query_too_long")
+ query = next((a for a in self.tried if a.record.get("error_code") == "service_refused"), None)
+ if query is not None:
+ return Failure(query.record["error"], "service_refused")
+ if any(f.get("skipped") == "blocked" for f in self.facts) or (self.facts and all(f.get("skipped") == "disabled" for f in self.facts)):
+ return Failure(self.say("hostedTools.errorCode.search_sources_blocked"), "search_sources_blocked")
+ if self.tried:
+ record = self.tried[-1].record
+ return Failure(record["error"], record.get("error_code"))
+ if self.turn.executors.get(self.call.tool):
+ return Failure(self.say("hostedTools.errorCode.service_unavailable"), "service_unavailable")
+ return Failure(self.say("modelHub.hostedTools.noSearchSource"), None)
+
+ async def service_attempt(self, slot, source, catalog):
+ from .service import _ExecutorAttempt
+
+ owner = self.owner
+ request = await asyncio.to_thread(search_request, catalog, self.call.arguments["query"], slot.results)
+ sent = False
+ health_generation = cooldown_generation = trial_epoch = None
+ response = None
+ skip = None
+ timed_out = False
+ stopped = False
+ ended_at = None
+
+ async def invoke():
+ nonlocal response, ended_at, source, skip, health_generation, cooldown_generation
+ async with owner._mutation_lock:
+ current, _, skip = await self.classify(slot, locked=True)
+ if skip is not None:
+ return None
+ source = current
+ waiting_trial = source.state.status in {"needs_action", "error"}
+ waiting_epoch = owner._search_trial_epochs.get(source.id, 0)
+ if waiting_trial:
+ # Connecting contenders have not yet won the one request.
+ # They share the re-enable fence; a skipped contender must
+ # never invalidate the winner's eventual settlement.
+ health_generation = owner._latest_source_attempt_generation.get(source.id)
+ cooldown_generation = owner._service_cooldowns.generation(source, slot.model_id)
+ else:
+ health_generation = owner._reserve_settlement_generation(source.id, source=source)
+ cooldown_generation = owner._service_cooldowns.advance(source, slot.model_id)
+
+ async def on_sent():
+ nonlocal sent, trial_epoch, source, skip, health_generation, cooldown_generation
+ # Connect/TLS holds no controller lock. Recheck identity/health
+ # and reserve the sole trial immediately before request bytes.
+ async with owner._mutation_lock:
+ current, _, skip = await self.classify(slot, locked=True)
+ if skip is not None:
+ raise _NotAdmitted
+ source = current
+ blocked = source.state.status in {"needs_action", "error"}
+ if ((waiting_trial and owner._search_trial_epochs.get(source.id, 0) != waiting_epoch)
+ or (blocked and not waiting_trial)):
+ skip = {"source_id": slot.source_id, "label": source.display_name[:64], "kind": "service",
+ "outcome": "skipped", "skipped": "unavailable"}
+ raise _NotAdmitted
+ if blocked:
+ if not owner.reserve_search_reenable_trial(source.id):
+ raise _NotAdmitted
+ trial_epoch = waiting_epoch
+ if waiting_trial:
+ # A slower contender may now see a repaired Source, or
+ # an armed trial released by a query refusal. In either
+ # case its newly admitted request owns fresh fences.
+ health_generation = owner._reserve_settlement_generation(source.id, source=source)
+ cooldown_generation = owner._service_cooldowns.advance(source, slot.model_id)
+ sent = True
+
+ response = await owner.adapter.search(
+ source.id, source.vendor, slot.model_id, source.credential_ref, request, on_sent=on_sent,
+ )
+ ended_at = owner.now()
+ return response
+
+ task = asyncio.create_task(invoke())
+ try:
+ await asyncio.wait_for(asyncio.shield(task), timeout=max(0.0, min(ATTEMPT_SECONDS, self.deadline - asyncio.get_running_loop().time())))
+ except asyncio.TimeoutError:
+ timed_out = True
+ task.cancel()
+ except asyncio.CancelledError:
+ stopped = True
+ task.cancel()
+ except _NotAdmitted:
+ return None, skip
+ except Exception:
+ response = SearchResponse(None, {}, None, "connection")
+ finally:
+ if not task.done():
+ async def drain():
+ # Convert only the child transport's cancellation to a
+ # normal completion. Cancellation of our shield is then
+ # unambiguously the caller's Stop, including on Python 3.10.
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+ draining = asyncio.create_task(drain())
+ try:
+ try:
+ await asyncio.shield(draining)
+ except asyncio.CancelledError:
+ stopped = True
+ await await_owned_task(draining)
+ except _NotAdmitted:
+ pass
+ except Exception:
+ response = SearchResponse(None, {}, None, "connection")
+ if skip is not None and not sent:
+ if stopped:
+ raise asyncio.CancelledError
+ return None, skip
+ response = response or SearchResponse(None, {}, None, "cancelled" if stopped else "timeout" if timed_out else "connection")
+ if timed_out and response.error == "cancelled":
+ response = replace(response, error="timeout")
+ stopped = stopped or response.error == "cancelled"
+ ended_at = ended_at or owner.now()
+
+ result = None
+ write = None
+
+ async def settle_result():
+ nonlocal result, write
+ result = await asyncio.to_thread(map_response, catalog, response, sent=sent, results=slot.results, say=self.say)
+ if stopped and response.http_status in {None, 200}:
+ # Stop is not a vendor failure. Keep billing/authentication facts
+ # but never infer an unreadable response or a retry deadline.
+ result = replace(result, cooling=False)
+ # Queue first, synchronously; stopped calls cannot lose sent usage.
+ write = owner.usage_writer.record_service(
+ source_id=source.id, service_id=slot.model_id, billable=result.billable,
+ uncertain=result.uncertain, reported_usd=result.reported_usd, at=ended_at,
+ ) if sent else None
+ superseded = False
+ async with owner._mutation_lock:
+ previous = await asyncio.to_thread(owner.store.load)
+ current = next((s for s in previous.sources if s.id == source.id), None)
+ identity_current = current is not None and source_identity(current) == source_identity(source)
+ health_current = identity_current and owner._settlement_current(current, health_generation)
+ cooldown_current = identity_current and owner._service_cooldowns.current(current, slot.model_id, cooldown_generation)
+ writes_health = result.blocker is not None or result.authenticated
+ writes_cooldown = result.cooling or result.record["status"] == "completed"
+ superseded = health_generation is not None and (
+ (writes_health and not health_current) or (writes_cooldown and not cooldown_current)
+ )
+ if cooldown_current:
+ owner._service_cooldowns.settle(current, slot.model_id, cooldown_generation, result, response, ended_at)
+ if health_current:
+ state = current.state
+ if result.blocker:
+ state = ModelHubSourceStateConfig(status="needs_action", detail_key=result.blocker)
+ elif trial_epoch is not None and response.http_status == 200:
+ state = ModelHubSourceStateConfig(status="standby")
+ if state != current.state or (result.authenticated and current.verification_pending is not None):
+ config = await asyncio.to_thread(owner._clone_config, previous)
+ updated = owner._source(config, source.id)
+ updated.state = state
+ if result.authenticated:
+ updated.verification_pending = None
+ await owner._save_runtime_config(previous, config)
+ if result.record["status"] == "completed":
+ await owner.record_hosted_success(source, slot.model_id, "web_search", "service")
+ return _ExecutorAttempt(
+ source, slot.model_id, result.record, result.cost, result.billable or result.uncertain,
+ result.record["status"] != "completed", kind="service", superseded=superseded,
+ )
+
+ async def settle():
+ try:
+ return await settle_result()
+ finally:
+ # These resources outlive any local mapping/evidence/config
+ # error: never strand a trial or lose an already queued charge.
+ if trial_epoch is not None:
+ async with owner._mutation_lock:
+ if owner._search_trial_epochs.get(source.id, 0) == trial_epoch:
+ owner.settle_search_reenable_trial(source.id)
+ if result is not None and result.record.get("error_code") == "service_refused":
+ owner._search_reenable_trials.add(source.id)
+ if write is not None:
+ await owner.usage_writer.wait_recorded(write)
+
+ settlement = asyncio.create_task(settle())
+ try:
+ attempt = await asyncio.shield(settlement)
+ except asyncio.CancelledError:
+ await await_owned_task(settlement)
+ raise
+ if stopped:
+ raise asyncio.CancelledError
+ return attempt, None
diff --git a/core/handlers/model_hub/search_services.py b/core/handlers/model_hub/search_services.py
new file mode 100644
index 000000000..a41750c8f
--- /dev/null
+++ b/core/handlers/model_hub/search_services.py
@@ -0,0 +1,253 @@
+"""Search APIs: bounded wire mapping, billing and service-local retry state.
+
+The catalog owns vendor facts. This module never reads a credential, calls a
+model engine or writes Source health. Decode/map on a worker; the controller
+owns admission and settlement (web-search-services.md §§3–4).
+"""
+
+from __future__ import annotations
+
+import json
+import math
+from dataclasses import dataclass
+from datetime import datetime, timedelta
+from typing import Any, Callable, Mapping
+from urllib.parse import urlsplit
+
+from config.v2_config import ModelHubConfig, ModelHubSourceConfig
+from core.agent_core.messages import HostedCost
+
+from .adapter import SearchResponse
+from .events import bounded_diagnostic_detail
+from .hosted_executor import Failure, failed_record
+from .retry import retry_after_deadline, source_identity
+
+ATTEMPT_SECONDS = 30.0
+ZERO = HostedCost(basis="list", usd=0)
+BLOCKERS = {
+ "service_key_invalid": "models.source.needs_action.credential_revoked",
+ "service_balance": "models.source.needs_action.balance_exhausted",
+ "service_limit": "models.source.needs_action.spend_limit_reached",
+}
+
+
+def _path(value: Any, path: str) -> Any:
+ for key in path.split("."):
+ value = value.get(key) if isinstance(value, Mapping) else None
+ return value
+
+
+def _put(value: dict, path: str, item: Any) -> None:
+ keys = path.split(".")
+ for key in keys[:-1]:
+ value = value.setdefault(key, {})
+ value[keys[-1]] = item
+
+
+def search_request(service: Mapping[str, Any], query: str, results: int) -> dict[str, Any]:
+ mapping = service["request"]
+ request = dict(mapping.get("defaults", {}))
+ _put(request, mapping["query"], query)
+ _put(request, mapping["results"], results)
+ if mapping.get("highlights"):
+ _put(request, mapping["highlights"], True)
+ return request
+
+
+@dataclass(frozen=True)
+class ServiceResult:
+ record: dict[str, Any]
+ cost: HostedCost | None
+ billable: bool
+ uncertain: bool
+ authenticated: bool
+ blocker: str | None
+ cooling: bool
+ reported_usd: float | None = None
+
+
+def map_response(
+ service: Mapping[str, Any], response: SearchResponse, *, sent: bool, results: int,
+ say: Callable[..., str],
+) -> ServiceResult:
+ """One outcome and one billing rule, including partial reads and stopped requests.
+
+ Status outranks transport errors: headers already received remain authoritative.
+ A malformed non-empty array can be billed even when no row survives mapping.
+ """
+
+ body = None
+ if response.body is not None:
+ try:
+ body = json.loads(response.body)
+ except (ValueError, UnicodeError, RecursionError):
+ pass
+ status = response.http_status
+ mapping = service["result"]
+ rows = _path(body, mapping["results"])
+ sources: list[dict[str, str]] = []
+ if isinstance(rows, list):
+ for row in rows:
+ url = _path(row, mapping["url"])
+ if not isinstance(url, str) or len(url) > 2048:
+ continue
+ try:
+ parsed = urlsplit(url)
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname or any(ord(c) < 32 for c in url):
+ continue
+ except ValueError:
+ continue
+ item = {"url": url}
+ for field, bound in (("title", 300), ("snippet", 1000), ("page_age", 64)):
+ value = _path(row, mapping[field])
+ if field == "snippet" and isinstance(value, list):
+ # Exa's highlights, in rank order, never its page text.
+ value = "\n".join(part[:bound] for part in value[:bound] if isinstance(part, str))
+ if isinstance(value, str):
+ item[field] = value[:bound]
+ sources.append(item)
+ if len(sources) >= results:
+ break
+ codes = service["outcomes"]
+ code = None
+ if status in codes["credential"]:
+ code = "service_key_invalid"
+ elif status in codes["balance"]:
+ code = "service_balance"
+ elif status in codes["limit"]:
+ code = "service_limit"
+ elif status == 200:
+ if not isinstance(rows, list) or (rows and not sources):
+ code = "service_unreadable"
+ elif status in service["service_refused_statuses"]:
+ code = "service_refused"
+ else:
+ code = "service_unavailable"
+ tag = body.get("tag") if isinstance(body, dict) else None
+ override = next((rule["code"] for rule in codes.get("tag_overrides", ())
+ if rule["status"] == status and rule["tag"] == tag), None)
+ code = override or code
+ if code is None:
+ record = {"status": "completed", "sources": sources}
+ else:
+ text = say(f"hostedTools.errorCode.{code}")
+ if code == "service_refused":
+ # Keep only bounded/redacted provider diagnostics, never a raw response body.
+ error = body.get("error") if isinstance(body, dict) else None
+ message = error.get("message") if isinstance(error, dict) else error
+ message = message if isinstance(message, str) else body.get("message") if isinstance(body, dict) else None
+ if not isinstance(message, str) and isinstance(body, dict):
+ message = body.get("detail")
+ if isinstance(message, dict):
+ message = message.get("error")
+ if isinstance(message, list):
+ # Tavily's validation errors: retain vendor messages, never
+ # the echoed request input or arbitrary diagnostic fields.
+ message = "; ".join(row["msg"][:512] for row in message[:5]
+ if isinstance(row, dict) and isinstance(row.get("msg"), str))
+ detail = bounded_diagnostic_detail(message) if isinstance(message, str) else None
+ if detail:
+ text = f"{text} ({detail})"
+ record = failed_record(Failure(text, code))
+
+ billing = service["billing"]
+ billable, uncertain = False, False
+ if sent:
+ if status == 200:
+ if not billing["nonempty_only"]:
+ billable = True
+ elif isinstance(rows, list):
+ billable = bool(rows)
+ else:
+ uncertain = True
+ elif status is None and response.error not in billing["unbilled_errors"]:
+ uncertain = True
+ cost = None if uncertain else ZERO
+ reported = None
+ if billable:
+ listed = service["price"]["usd_per_1k"] / 1000
+ rule = mapping.get("reported_cost")
+ value = _path(body, rule["path"]) if rule else None
+ if isinstance(value, (int, float)) and not isinstance(value, bool) and 0 <= value <= 100 * listed:
+ try:
+ if math.isfinite(value):
+ reported = float(value)
+ except OverflowError:
+ pass
+ cost = (
+ HostedCost(basis="reported", usd=reported, estimate=bool(rule["estimate"]))
+ if reported is not None else HostedCost(basis="list", usd=listed)
+ )
+ return ServiceResult(
+ record, cost, billable, uncertain,
+ authenticated=status == 200 or code in {"service_balance", "service_limit"},
+ blocker=BLOCKERS.get(code), cooling=code in {"service_unavailable", "service_unreadable"},
+ reported_usd=reported,
+ )
+
+
+@dataclass
+class _Cooldown:
+ identity: tuple
+ generation: int
+ failures: int = 0
+ until: datetime | None = None
+
+
+class ServiceCooldowns:
+ """Independent attempt generations: model calls cannot invalidate search retry state.
+
+ Identity reconciliation retires entries but never recycles a generation. All
+ mutations are controller-owned; reads may project the already-held state.
+ """
+
+ def __init__(self) -> None:
+ self._serial = 0
+ self._states: dict[tuple[str, str], _Cooldown] = {}
+
+ def reconcile(self, config: ModelHubConfig) -> None:
+ live = {source.id: source_identity(source) for source in config.sources}
+ self._states = {key: state for key, state in self._states.items() if live.get(key[0]) == state.identity}
+
+ def advance(self, source: ModelHubSourceConfig, service_id: str, *, clear: bool = False) -> int:
+ key = (source.id, service_id)
+ previous = self._states.get(key)
+ self._serial += 1
+ same = previous is not None and previous.identity == source_identity(source) and not clear
+ self._states[key] = _Cooldown(
+ source_identity(source), self._serial,
+ previous.failures if same else 0, previous.until if same else None,
+ )
+ return self._serial
+
+ def generation(self, source: ModelHubSourceConfig, service_id: str) -> int | None:
+ state = self._states.get((source.id, service_id))
+ return state.generation if state is not None and state.identity == source_identity(source) else None
+
+ def current(self, source: ModelHubSourceConfig, service_id: str, generation: int | None) -> bool:
+ return generation is not None and self.generation(source, service_id) == generation
+
+ def until(self, source: ModelHubSourceConfig, service_id: str, now: datetime) -> datetime | None:
+ state = self._states.get((source.id, service_id))
+ if state is not None and state.identity == source_identity(source) and state.until is not None and state.until > now:
+ return state.until
+ return None
+
+ def settle(
+ self, source: ModelHubSourceConfig, service_id: str, generation: int,
+ result: ServiceResult, response: SearchResponse, now: datetime,
+ ) -> bool:
+ if not self.current(source, service_id, generation):
+ return False
+ state = self._states[(source.id, service_id)]
+ if result.cooling:
+ state.failures = min(state.failures + 1, 5)
+ advice = None
+ if response.http_status in {429, 503}:
+ value = next((v for k, v in response.headers.items() if k.lower() == "retry-after"), None)
+ advice = retry_after_deadline(value, response.response_received_at or now)
+ state.until = advice if advice is not None else now + timedelta(seconds=min(30 * 2 ** (state.failures - 1), 300))
+ elif result.record["status"] == "completed":
+ state.failures = 0
+ state.until = None
+ return True
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index d17c3beb4..6147687e5 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -127,6 +127,7 @@ from .capability_evidence import (
EvidenceFeature,
EvidenceRecord,
identity_digest,
+ utc_text,
)
from .errors import ModelDiscoveryError
from .evidence_rules import LearnedEvidence
@@ -159,6 +160,9 @@ from .hosted_images import (
unsupported_argument,
)
from .hosted_turn import IMAGE_TOOL, ExecutorSlot, TurnHostedTools
+from . import hosted_tools as hosted_tools_module
+from .search_services import ServiceCooldowns
+from .search_chain import SearchChain
from .hosted_tools import (
ExecutorCandidate,
HostedEvidence,
@@ -899,7 +903,10 @@ def _executor_failure(outcome: RawCallOutcome | None, say: Callable[..., str], *
def _cost_payload(cost: HostedCost) -> dict[str, Any]:
- return {"basis": cost.basis} if cost.usd is None else {"basis": cost.basis, "usd": cost.usd}
+ payload = {"basis": cost.basis} if cost.usd is None else {"basis": cost.basis, "usd": cost.usd}
+ if cost.estimate is not None:
+ payload["estimate"] = cost.estimate
+ return payload
@dataclass(frozen=True)
@@ -929,20 +936,30 @@ class _ExecutorAttempt:
billable: bool
# Whether its failure passes the search to the next candidate.
moves_on: bool
+ kind: str = "model"
+ superseded: bool = False
+
+ @property
+ def billing(self) -> str:
+ return "metered" if self.kind == "service" else self.source.billing
def execution(self) -> dict[str, Any]:
execution: dict[str, Any] = {
"mode": "proxy",
- "executor_origin": {"provider": self.source.vendor, "api": self.source.protocol, "model": self.model_id},
+ "executor_origin": {
+ "provider": self.source.vendor,
+ "api": "search_api" if self.kind == "service" else self.source.protocol,
+ "model": self.model_id,
+ },
"executor_source_id": self.source.id,
- "executor_billing": self.source.billing,
+ "executor_billing": self.billing,
}
if self.cost is not None:
execution["cost"] = _cost_payload(self.cost)
return execution
def failed_attempt(self) -> dict[str, Any]:
- attempt: dict[str, Any] = {"source_id": self.source.id, "billing": self.source.billing}
+ attempt: dict[str, Any] = {"source_id": self.source.id, "billing": self.billing}
if self.cost is not None:
attempt["cost"] = _cost_payload(self.cost)
return attempt
@@ -1581,6 +1598,10 @@ class ModelHubService:
self._source_create_nonces: set[str] = set()
self._search_reenable_trials: set[str] = set()
self._search_reenable_trials_inflight: set[str] = set()
+ self._search_trial_epochs: dict[str, int] = {}
+ self._search_trial_identities: dict[str, tuple] = {}
+ self._search_reenable_checks: dict[str, asyncio.Task] = {}
+ self._service_cooldowns = ServiceCooldowns()
self._next_settlement_generation = PRE_ATTEMPT_SETTLEMENT_GENERATION
self._latest_source_attempt_generation: dict[str, int] = {}
self._source_attempt_identities: dict[str, tuple | None] = {}
@@ -1871,6 +1892,11 @@ class ModelHubService:
self.recovery.reconcile(canonical)
self.recovery.notify()
+ self._service_cooldowns.reconcile(canonical)
+ live = {source.id: source_identity(source) for source in canonical.sources}
+ for sid, identity in tuple(self._search_trial_identities.items()):
+ if live.get(sid) != identity:
+ self._drop_search_reenable_trial(sid)
return canonical
def _persist_config(self, payload: dict) -> ModelHubConfig:
@@ -1945,7 +1971,7 @@ class ModelHubService:
return True
def search_reenable_trial_armed(self, source_id: str) -> bool:
- """Return whether one process-local search trial is waiting for S2's gate."""
+ """Return whether one process-local search trial is waiting for admission."""
return source_id in self._search_reenable_trials
@@ -1967,11 +1993,13 @@ class ModelHubService:
return True
def settle_search_reenable_trial(self, source_id: str) -> None:
- """Forget a trial after S2 settles its admitted search attempt."""
+ """Forget a trial after its admitted search attempt settles."""
self._search_reenable_trials_inflight.discard(source_id)
def _drop_search_reenable_trial(self, source_id: str) -> None:
+ self._search_trial_epochs[source_id] = self._search_trial_epochs.get(source_id, 0) + 1
+ self._search_trial_identities.pop(source_id, None)
self._search_reenable_trials.discard(source_id)
self._search_reenable_trials_inflight.discard(source_id)
@@ -1979,10 +2007,12 @@ class ModelHubService:
self._next_settlement_generation += 1
return self._next_settlement_generation
- def _reserve_settlement_generation(self, source_id: str) -> int:
+ def _reserve_settlement_generation(self, source_id: str, *, source: ModelHubSourceConfig | None = None) -> int:
+ """Reserve on the loop; an already-admitted snapshot avoids a second config read."""
generation = self._mint_settlement_generation()
self._latest_source_attempt_generation[source_id] = generation
- source = next((item for item in self.store.load().sources if item.id == source_id), None)
+ if source is None:
+ source = next((item for item in self.store.load().sources if item.id == source_id), None)
if source is not None:
self._source_attempt_identities[source_id] = source_identity(source)
return generation
@@ -2390,7 +2420,8 @@ class ModelHubService:
# is cancelled outright. An engine listing's worker is owned and
# bounded, so these return only once nothing still uses the engine
# that `adapter.stop()` retires.
- retiring = [task for task in (discovery, viewed) if task is not None and not task.done()]
+ retiring = [task for task in (discovery, viewed, *self._search_reenable_checks.values())
+ if task is not None and not task.done()]
for task in retiring:
task.cancel()
await asyncio.gather(*retiring, return_exceptions=True)
@@ -4888,7 +4919,66 @@ class ModelHubService:
"interrupted": interrupted,
}
+ async def _reenable_search_service(self, source_id: str, payload: object) -> dict:
+ """One shared free check, or one fail-closed trial, fenced against later attempts and identity changes."""
+ if payload not in (None, {}):
+ raise ModelHubError("invalid_parameter", status=400)
+ async with self._mutation_lock:
+ joined = self._search_reenable_checks.get(source_id)
+ if joined is None:
+ source = self._source(await asyncio.to_thread(self.store.load), source_id)
+ catalog = _require_search_service_for_source(source)
+ if source.protocol != "search" or source.state.status != "needs_action" or source.state.detail_key not in {
+ "models.source.needs_action.balance_exhausted", "models.source.needs_action.spend_limit_reached",
+ }:
+ raise ModelHubError("discovery_failed")
+ if self.search_reenable_trial_pending(source_id):
+ return {"source": await asyncio.to_thread(self._source_payload, source), "removed_hops": [], "interrupted": [], "trial_armed": True}
+ generation = self._reserve_settlement_generation(source_id, source=source)
+ self._service_cooldowns.advance(source, catalog["service_id"], clear=True)
+ check = catalog.get("free_check")
+ needed = "balance" if source.state.detail_key.endswith("balance_exhausted") else "limit"
+ if not isinstance(check, Mapping) or not check.get(needed):
+ self._search_reenable_trials.add(source_id)
+ self._search_trial_identities[source_id] = source_identity(source)
+ self._search_trial_epochs[source_id] = self._search_trial_epochs.get(source_id, 0) + 1
+ return {"source": await asyncio.to_thread(self._source_payload, source), "removed_hops": [], "interrupted": [], "trial_armed": True}
+
+ async def checked() -> dict:
+ try:
+ outcome = await self._search_free_check(source)
+ async with self._mutation_lock:
+ previous = await asyncio.to_thread(self.store.load)
+ current = next((s for s in previous.sources if s.id == source_id), None)
+ if current is None:
+ raise ModelHubError("source_not_found", status=404)
+ if source_identity(current) == source_identity(source) and self._settlement_current(current, generation):
+ config = await asyncio.to_thread(self._clone_config, previous)
+ updated = self._source(config, source_id)
+ if outcome in {"pass", "balance", "limit"}:
+ updated.verification_pending = None
+ detail = {
+ "invalid": "credential_revoked", "balance": "balance_exhausted", "limit": "spend_limit_reached",
+ }.get(outcome)
+ if outcome == "pass":
+ updated.state = ModelHubSourceStateConfig(status="standby")
+ elif detail:
+ updated.state = ModelHubSourceStateConfig(status="needs_action", detail_key=f"models.source.needs_action.{detail}")
+ if updated != current:
+ await self._save_runtime_config(previous, config)
+ current = self._source(await asyncio.to_thread(self.store.load), source_id)
+ return {"source": await asyncio.to_thread(self._source_payload, current), "removed_hops": [], "interrupted": [], "trial_armed": False}
+ finally:
+ if self._search_reenable_checks.get(source_id) is asyncio.current_task():
+ self._search_reenable_checks.pop(source_id, None)
+
+ joined = asyncio.create_task(checked())
+ self._search_reenable_checks[source_id] = joined
+ return await asyncio.shield(joined)
+
async def reenable_search_source(self, source_id: str, payload: object = None) -> dict:
+ if hosted_tools_module.SEARCH_SERVICES_ACTIVE:
+ return await self._reenable_search_service(source_id, payload)
if payload not in (None, {}):
raise ModelHubError("discovery_failed")
async with self._mutation_lock:
@@ -6819,6 +6909,7 @@ class ModelHubService:
spec_for=hosted_tool_spec,
image_price=self._image_price,
search_trial_pending=self.search_reenable_trial_pending,
+ search_cooldown_until=self._search_visible_cooldown,
)
}
@@ -7143,6 +7234,30 @@ class ModelHubService:
# The frozen model while it stays listed and runnable, even if the Source now lists one its vendor prefers.
return executor_candidate(source, slot.model_id, tool, evidence=self.hosted_evidence(), spec_for=hosted_tool_spec)
+ def _search_visible_cooldown(self, source_id: str, service_id: str) -> str | None:
+ config = self.store.load()
+ source = next((item for item in config.sources if item.id == source_id), None)
+ if source is None:
+ return None
+ until = self._service_cooldowns.until(source, service_id, self.now())
+ return utc_text(until) if until is not None and (until - self.now()).total_seconds() > 60 else None
+
+ async def clear_service_cooldown(self, source_id: str, service_id: str | None = None, payload: object = None) -> dict:
+ if payload not in (None, {}):
+ raise ModelHubError("invalid_parameter", status=400)
+ async with self._mutation_lock:
+ config = await asyncio.to_thread(self.store.load)
+ source = self._source(config, source_id)
+ service = model_hub_search_service(source)
+ if service is None or (service_id is not None and service["service_id"] != service_id):
+ raise ModelHubError("source_not_found", status=404)
+ self._service_cooldowns.advance(source, service["service_id"], clear=True)
+ return {}
+
+ async def _run_search_chain(self, call: ExecutorCall, turn: TurnHostedTools, *, say: Callable[..., str]) -> dict:
+ """Run the service/model chain; all response decoding and mapping stay off the loop."""
+ return await SearchChain(self, call, turn, say).run()
+
async def run_hosted_tool(
self,
tool: str,
@@ -7173,6 +7288,8 @@ class ModelHubService:
raise ModelHubError(refused.code, status=refused.status) from None
if turn is None or tool not in turn.tools:
raise ModelHubError("tool_not_enabled", status=409)
+ if tool == "web_search" and turn.prefer_native is not None:
+ return await self._run_search_chain(call, turn, say=say)
loop = asyncio.get_running_loop()
deadline = loop.time() + call_timeout(tool)
attempts: list[_ExecutorAttempt] = []
@@ -7366,6 +7483,7 @@ class ModelHubService:
*,
deadline: float,
say: Callable[..., str],
+ admission: Callable[[], Awaitable[ModelHubSourceConfig | None]] | None = None,
) -> _ExecutorAttempt | None:
"""Call one executor candidate; None when this snapshot does not admit it, so nothing ran."""
@@ -7388,6 +7506,8 @@ class ModelHubService:
body.extend(chunk)
async def admitted_now() -> ModelHubSourceConfig | None:
+ if admission is not None:
+ return await admission()
final = await asyncio.to_thread(self._admitted_executor, slot, tool)
return final.source if final is not None else None
diff --git a/docs/plans/agent-core-contracts/model-hub-consumer.md b/docs/plans/agent-core-contracts/model-hub-consumer.md
index 5c584e39c..a89ed5520 100644
--- a/docs/plans/agent-core-contracts/model-hub-consumer.md
+++ b/docs/plans/agent-core-contracts/model-hub-consumer.md
@@ -152,8 +152,17 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
longer admits work, it is 409 `turn_not_live`; a tool outside the turn's frozen tool set, or for
`image_generate` a model outside the turn's frozen models, is 409 `tool_not_enabled`. Nothing runs. Stopping
the turn cancels an admitted call, which is still metered.
- - **A search call runs on a chain** built from the turn's frozen executor order: each candidate is a Source
- whose vendor offers the tool natively, called with the first of its vendor's `executor_models` the Source
+ - **A search call runs on a chain** built from the turn's frozen candidate list. For `web_search`, a candidate
+ is a search-service Source (including a qualifying official DeepSeek API-key Source) or a model executor;
+ one Source holds one role. Automatic order puts services before model executors. A saved order preserves
+ deliberate placements; unnamed or role-changed services, identified by `executor_order_kinds`, are placed
+ before its first model executor without a config write, unnamed models follow, and disabled entries go last
+ (`web-search-services.md` §4.1). The turn freezes `prefer_native`, candidates and their result counts.
+ `prefer_native: false` states native/replay unsupported on every hop, so native history replays synthetically.
+ A candidate is skipped by its first applicable reason: unavailable, disabled, blocked, cooling, query too long.
+ Skips write no state and cost nothing. A service sends its catalog request through the adapter custody
+ boundary, never the model engine. A model executor is a Source whose vendor offers the tool natively,
+ called with the first of its vendor's `executor_models` the Source
lists (a Source listing none is no candidate), and admitted on the final snapshot when the gateway reaches it
(`runs_on`, its identity, no current negative `call` evidence). The gateway sends one short native request
(the overlay's declaration; on Responses `tool_choice: "required"`; Anthropic is asked in the message alone;
@@ -161,7 +170,7 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
or server error included), a narrow-rule refusal, a refusal of the executor model (`model_not_found`), or a
failure mid-stream. Only the narrow rule writes negative `call` evidence; a model refusal is not a refusal of
the tool. A completed response that never ran the tool ends the chain. One deadline covers the whole chain
- (180 s).
+ (180 s), with at most 30 s per service attempt; model executors retain the remaining chain budget.
- **An `image_generate` call** runs directly on the image endpoint of the (Source, model) the turn's frozen
models name (`vibey-hosted-tools.md` §7.4), admitted on the final snapshot; there is no chain and no
fallback. Its arguments are `{model, prompt, size?, images?, n?}`, `images` being at most 4 base64 strings,
@@ -176,9 +185,18 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
- Every outcome of a well-formed call is a 200 with `{"record", "execution"?}` in the
`ToolResultMessage.hosted` encoding. `execution` names the attempt whose response the record came from (the
last one tried when all failed), with its billing and cost; earlier billable attempts are listed in
- `execution.failed_attempts: [{source_id, billing, cost?}]`. With no candidate, or every candidate failed, the
- record is `failed` and names what to add.
- - Success is an allow-list: a call is `completed` only when the response says it completed (Responses
+ `execution.failed_attempts: [{source_id, billing, cost?}]`, including an earlier possibly billed service
+ attempt whose charge is unknown (no cost). A service chain's `record.attempts[]` carries every reached
+ candidate, tried or skipped, even with no execution. Model-only chains retain the released shape.
+ With no candidate, the failed record names both remedies: add a search service or a search-capable API key.
+ Otherwise its terminal reason prioritizes query-too-long (`search_query_too_long`, largest reachable limit
+ in `error`), query-specific refusal, blocked Sources (`search_sources_blocked` with per-Source remedies;
+ disabled decides only if every candidate is disabled), last tried failure, then cooling/unavailable.
+ - A service response is `completed` exactly for HTTP 200 with a results array that is empty or retains at
+ least one row after mapping bounds: HTTP(S) URLs at most 2,048 characters, title 300, excerpt 1,000,
+ page age 64, at most the frozen result count. Missing/unreadable arrays or non-empty arrays with no usable
+ rows are `service_unreadable` and fail over. JSON decoding and mapping run off the controller loop.
+ - Model success is an allow-list: a call is `completed` only when the response says it completed (Responses
`status: completed`; Anthropic `end_turn` or `stop_sequence`) and nothing failed; a response that stopped
early is `incomplete`; any reported failure, or any other or missing ending, is `failed`. An unreadable
response is `failed`. The record's `error` is in the user's language, and every reason the gateway words
@@ -192,9 +210,21 @@ consumer's requirements, and the Model Hub lane lands the change in both places.
citations are read.
- A malformed call is 400 `invalid_request_error` (including a body over the tool's request bound), an
unauthenticated one 401, an unknown tool 404, as `{"type": "error", "error": {"type", "code"}}`.
- - Each attempt is metered on its own Source and never changes Source health. `cost` is the pricing module's
- value of that attempt: `included` on a monthly Source, the provider's own figure as `reported`, else `list`;
- absent when it cannot be valued, never zero.
+ - Each sent attempt is metered on its own Source; skips and pre-send failures are not. Model executor
+ attempts never change Source health. Service credential, balance and catalog-named limit failures do,
+ fenced by the Source attempt-start settlement generation. Transient, query-specific, redirect and unreadable
+ service failures never write health; transient/unavailable/unreadable failures use a separately fenced
+ (Source, service) cooldown. A service writes no negative hosted-tool evidence. Completed service requests
+ write positive `mode: service` evidence. A re-enable trial admits one request immediately before sending.
+ - A model attempt's cost uses the pricing module as before. A service attempt uses its catalog list price or
+ a finite non-negative reported price no larger than 100 times that price, with the catalog's estimate flag.
+ Known-unbilled outcomes carry explicit list $0: pre-send failure, non-200, empty DeepSeek results, or a
+ catalog-declared unbilled outcome. Received status survives body failure or stop: a non-200 is $0, an Exa/
+ Tavily 200 is billed, and a DeepSeek 200 with an unreadable result count is uncertain. Otherwise sent/no-status
+ failures are uncertain unless the catalog declares them unbilled. Unknown costs remain absent and make
+ known chain totals lower bounds. Stopped calls write no record but meter their observed billing facts.
+ Stop itself creates no cooldown or failure: no-status and 200 stops settle only billing/authentication/trial
+ facts, while an observed failure status still settles its health/cooldown row.
## 3. Not required
diff --git a/docs/plans/model-hub-contracts/README.md b/docs/plans/model-hub-contracts/README.md
index b518ba8a2..734b3447b 100644
--- a/docs/plans/model-hub-contracts/README.md
+++ b/docs/plans/model-hub-contracts/README.md
@@ -1,7 +1,7 @@
# Model Hub contracts
-Status: **contract_version 19**, 2026-10-21: dormant web-search-service readers
-(S2a, `../web-search-services.md` §4.3, §6.5, §8). The RC tag `gh-v3.2.2rc13`
+Status: **contract_version 19**, 2026-10-21: dormant web-search-service readers and producer
+(S2a/S2b-1, `../web-search-services.md` §3–5, §6.5, §8). The RC tag `gh-v3.2.2rc13`
carries v18, so these additions open a new event rather than changing v18.
- C-1 (`../agent-core-contracts/message.schema.json`) accepts `HostedRecord.attempts[]`
(`HostedAttempt`), `HostedCost.estimate`, and a `ServiceExecutorOrigin`
@@ -18,11 +18,17 @@ carries v18, so these additions open a new event rather than changing v18.
`kind: "service"` bucket rows, `service_reported_usd` and `excluded_service_requests`
on totals and days, and `pricing.service_price_date`. Model counts never include
service requests.
-- These are readers only. No search runs, no service request is metered, no service
- evidence is written, and `SEARCH_SERVICES_ACTIVE` stays off; service candidates and
- `service_vendors` remain absent from the Tools read. S2b owns the producers and
- activation, and the downgrade boundary of `../web-search-services.md` §12 begins
- when it writes these shapes.
+- S2b-1 adds the producer behind `SEARCH_SERVICES_ACTIVE = False`: unified service/model
+ order, per-turn frozen preference/settings, bounded mapping, independently fenced service
+ cooldowns and Source health, re-enable trials, sent-request metering and positive evidence.
+ The flag-off runtime/read remain unchanged. S2b-2 activates only with S6 disclosure;
+ the downgrade boundary of `../web-search-services.md` §12 begins when these shapes are written.
+- `POST /api/models/hosted-tools/web_search/services/<source_id>/retry` clears the controller's
+ service cooldown and advances its generation, with a plain success response. It is available
+ regardless of activation and follows the existing Member management boundary.
+- C-6's search-call contract and the turn's `hosted_tools` add the mixed chain, skip/terminal
+ rules, native preference, service billing and classified-only Source health writes.
+ Re-enable is the one non-attempt action advancing Source settlement generation.
- The versioned mirrors advance together; persisted TurnProvenance retains v5–v18
and adds v19.
@@ -61,7 +67,15 @@ withdrawn by v18 as recorded above. Later lanes extend the current version event
only while it is unshipped; an RC freezes its meaning. S2 activates the service
reads and snippet-only search chain.
-Catalog metadata verified on **2026-10-20**:
+Catalog metadata verified on **2026-10-21**:
+- DeepSeek maps the model-facing `summary` and bills only non-empty 200 results; its
+ declared unbilled timeouts follow the design's §4.3 rule. The official reference is
+ [Search](https://api-docs.deepseek.com/api/search) and the [guide](https://api-docs.deepseek.com/guides/search).
+- The catalog pins Tavily basic search and Exa Auto with highlights only. Exact status/tag
+ overrides distinguish Exa key/team budgets from balance and moderation refusals from
+ unavailable endpoints; Tavily 422 is query-specific. See
+ [Exa errors](https://exa.ai/docs/admin/error-codes) and
+ [Tavily OpenAPI](https://docs.tavily.com/documentation/api-reference/openapi.json).
- `search.auto_enroll` is explicit for model vendors with search; only DeepSeek is
enabled automatically. S1b and S2 own the resulting settings defaults.
- Exa's `search.result.reported_cost` names `costDollars.total` with `estimate: true`,
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 7c21d1da1..b8ab7f9c5 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -17,7 +17,7 @@ import asyncio
from dataclasses import dataclass, field
from datetime import datetime
from enum import Enum
-from typing import Any, AsyncIterator, Callable, Final, Literal, Mapping, Protocol, Sequence
+from typing import Any, AsyncIterator, Awaitable, Callable, Final, Literal, Mapping, Protocol, Sequence
from .stream_wire import ProtocolSSEState, ProtocolUsageReport
@@ -578,13 +578,15 @@ class EngineAdapter(Protocol):
credential_ref: str,
request: Mapping[str, Any],
*,
- on_sent: Callable[[], None] | None = None,
+ on_sent: Callable[[], Awaitable[None] | None] | None = None,
) -> SearchResponse:
"""Make exactly one catalog-host search request from Model Hub custody.
``on_sent`` fires once after the connection (including TLS) is ready and
immediately before aiohttp writes this request. A callback failure stops
- the request before any request bytes are sent.
+ the request before any request bytes are sent. An async callback is
+ awaited for final controller admission without holding a mutation lock
+ during DNS/TCP/TLS; existing synchronous callbacks remain supported.
"""
...
diff --git a/docs/plans/model-hub-contracts/api-response.schema.json b/docs/plans/model-hub-contracts/api-response.schema.json
index 2786cad03..9f3dddfd3 100644
--- a/docs/plans/model-hub-contracts/api-response.schema.json
+++ b/docs/plans/model-hub-contracts/api-response.schema.json
@@ -41,6 +41,7 @@
{"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_order": null}}},
{"method": "POST", "path": "/api/models/hosted-tools/<tool>/clear", "response_schema": "HostedToolsResponse", "exercise": {"path": "/api/models/hosted-tools/web_search/clear", "status": 200, "json": {"source_id": "src_conform001"}}},
+ {"method": "POST", "path": "/api/models/hosted-tools/web_search/services/<source_id>/retry", "response_schema": "EmptyResponse", "exercise": {"path": "/api/models/hosted-tools/web_search/services/src_searchbalance/retry", "status": 200, "json": {}}},
{"method": "POST", "path": "/api/models/sources/<source_id>/evidence/clear", "response_schema": "SourceResponse", "exercise": {"path": "/api/models/sources/src_conform001/evidence/clear", "status": 200, "json": {"model_id": "claude-opus-4-6", "feature": {"kind": "effort", "name": "max"}}}},
{"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}},
diff --git a/docs/plans/model-hub-contracts/api.md b/docs/plans/model-hub-contracts/api.md
index ebaf8f212..6752ee3e8 100644
--- a/docs/plans/model-hub-contracts/api.md
+++ b/docs/plans/model-hub-contracts/api.md
@@ -73,6 +73,7 @@ runtime open. Once models are configured it participates in the runtime Stop gua
| 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}` | Models → Tools (`hosted-tools-status.schema.json`): every catalog tool with its switch (absent setting = on), its passive status from real use (`latest_ok`, current `refused[]`, per-pair `verified[]`), for a search tool the saved and effective executor order with every eligible executor candidate and its unit rates, and for `image_generate` the saved and effective default and the available image models. Memory only; nothing is probed. |
+| POST `/api/models/hosted-tools/web_search/services/<source_id>/retry` | `{}` → `{}` | Clears the controller's `(Source, service)` cooldown, advances its generation, and leaves Source health unchanged. It is valid even while search services are dormant; the Tools read is the follow-up source of truth. Member management role. |
| PUT `/api/models/hosted-tools/<tool>` | `{enabled?: boolean, executor_order?: null \| [source_id], default_model?: null \| {source_id, model_id}, prefer_native?: boolean, services?: {source_id: null \| {results?: integer \| null, enabled?: boolean \| null}}}` → `{hosted_tools: HostedToolsStatus}` | Changes one tool's settings field by field: an absent field is unchanged, `null` resets `executor_order` to automatic or `default_model` to the default. `executor_order` is for search tools and `default_model` for `image_generate`; values are saved as given, never resolved. It applies from the next turn and interrupts nothing. An unknown tool returns `404 hosted_tool_not_found`; an empty or malformed body `400 invalid_parameter`, including a null `enabled`, an id that is not a Source id (`src_…`), or a model id with surrounding whitespace. |
| POST `/api/models/hosted-tools/<tool>/clear` | `{source_id?, model_id?}` → `{hosted_tools: HostedToolsStatus}` | Clears the tool's refusals (`call` and `replay`): on one Source and model, on one Source (every model), or with `{}` on every Source. `model_id` requires `source_id`; neither is nullable, so a malformed body is refused rather than widened into a broader clear. A Source or model with nothing to clear is a no-op that answers the read. The file is written first: a failed write returns `500 state_write_failed` and changes nothing. A cleared Source is assumed again from its next request. An unknown tool returns `404 hosted_tool_not_found`; any other body `400 invalid_parameter`. |
| POST `/api/models/sources/<source_id>/evidence/clear` | `{model_id, feature: {kind: "effort", name}}` → `{source: Source}` | Clears one effort refusal of a Source's model, so the next request at that effort may reach it. A missing record is a no-op. An unknown Source returns `404 source_not_found`; a hosted-tool feature or any other body `400 invalid_parameter` (hosted refusals clear through the Tools clear); a failed write `500 state_write_failed` with nothing changed. |
@@ -103,10 +104,10 @@ Extant retargeted or retired Sources are omitted from `services` while they cann
search, but their overrides (especially opt-out) stay in config for when capability
returns. Removed Sources' overrides are ignored.
-Until S2 activates execution, **the read contains no service candidates and omits
+Until S2b-2 activates execution with S6 disclosure, **the read contains no service candidates and omits
`service_vendors` entirely**. One internal `SEARCH_SERVICES_ACTIVE` switch gates
both. Settings load and save now, but `prefer_native` does not change hop facts
-and service settings do not change the model executor chain in S1b. No user-facing
+and service settings do not change the model executor chain while the flag is off. No user-facing
activation toggle exists.
The service variant is frozen for S4/S2 in `hosted-tools-status.schema.json`:
@@ -114,7 +115,9 @@ The service variant is frozen for S4/S2 in `hosted-tools-status.schema.json`:
`price` is the catalog list price per search, with no page-text surcharge.
`settings` holds effective `{results, enabled}`;
`state` is the Source's health, `trial_pending` covers both armed and in-flight
-one-shot trials, and `cooldown_until` is nullable (S2 owns service cooldowns).
+one-shot trials, and `cooldown_until` is non-null only while a service cooldown has more than 60 seconds
+remaining. Retry advances that cooldown's independent generation, so an older in-flight failure cannot restore it;
+it neither clears a Source blocker nor sends a request.
`service_vendors` contains `{id, name, price, free_tier, facts, results_max,
source_ids}`. Facts are the catalog's
`{tool_only, auto_enroll, free_check}` booleans. A free tier not verified in the
@@ -147,9 +150,12 @@ not named by the order or no longer naming an extant Source are ignored on load,
including before role validation, and the next authorized write drops them. An
extant retargeted/retired Source keeps its saved role. A damaged map is treated as absent with a
warning, retaining the tool switch, service opt-outs and other saved choices.
-Neither `executor_order_kinds` nor `service_order` is client-writable. S2 owns the
-read-time placement rule; S1b preserves the saved order and kinds across restart
-without changing execution.
+Neither `executor_order_kinds` nor `service_order` is client-writable. When active, the read and the gateway use
+one chain: tool-only services in `service_order`, model Sources' enabled search APIs in Vibey order, then model
+executors. Saved-role entries keep their deliberate positions. Unnamed or role-changed service entries are
+inserted before the first named model executor; remaining model entries follow. Disabled entries are last.
+No placement writes config. A turn freezes this chain, result counts and `prefer_native`; final admission can
+only skip a changed identity, never substitute a newly added Source.
Downgrade boundary: rc12 ignores `prefer_native`, `services` and
`executor_order_kinds`. Its next config write drops those fields, including
diff --git a/docs/plans/model-hub.md b/docs/plans/model-hub.md
index a72b84b47..b616c7395 100644
--- a/docs/plans/model-hub.md
+++ b/docs/plans/model-hub.md
@@ -917,7 +917,9 @@ neither changes historical provenance or authorizes an extra notification surfac
**Settlement freshness is owned by the attempt that started (round-7 audit, fixed
round-8).** Because health is source-global and every turn re-runs the algorithm, a
failure only describes the Source *as the failing attempt used it*. Each attempt
-therefore takes a monotonic settlement generation **at attempt start and nowhere else**,
+therefore takes a monotonic settlement generation **at attempt start**, with one explicit exception:
+search-service **re-enable** also advances it, without interrupting work, so an older in-flight search cannot
+restore the blocker that the user is recovering (`web-search-services.md` §4.2). No settlement mints one,
and a settlement whose generation is older than the newest attempt on that Source writes
no health. Two consequences are normative. A settlement that carries no generation cannot
prove it was not superseded, so it also writes no health — minting one at settlement time
diff --git a/docs/plans/web-search-services-s2b.md b/docs/plans/web-search-services-s2b.md
new file mode 100644
index 000000000..ce2da9a04
--- /dev/null
+++ b/docs/plans/web-search-services-s2b.md
@@ -0,0 +1,78 @@
+# S2b-1: dormant search-service producer
+
+## Change contract
+
+Implement `web-search-services.md` §§3–5 behind `SEARCH_SERVICES_ACTIVE = False`.
+The flag-off chain, hop facts, frozen turn and Tools read retain their released behavior.
+Activation is a separate S2b-2 PR coordinated with S6 disclosure; this PR does not activate or merge itself.
+
+Owning boundaries:
+- `hosted_tools` / `hosted_turn`: one-role candidate order, read-time placement, disabled tail,
+ frozen prefer-native/results/identities and the same chain in the read.
+- `search_services`: catalog request/response mapping, bounded records, outcomes, billing and
+ service-scoped cooldown fencing; no credential access or model-engine requests.
+- `ModelHubService`: final admission, Source settlement fencing, one-shot recovery trials,
+ cancellation-safe metering, evidence and mixed service/model calls under one deadline.
+- Model Hub RPC/UI API and authorization: explicit cooldown clear, plain success response.
+- C-6 and Model Hub contract: authoritative search behavior and fixtures.
+
+Invariants and primary regression coverage:
+- A turn's frozen roles/settings cannot be altered by later settings writes; re-identification
+ can only prevent admission. Automatic and deliberate orders use one placement rule.
+- Every reached candidate has exactly one attempt fact, including a pre-send failure or skip;
+ model-only chains retain the released record shape. Skip precedence and terminal selection
+ do not mistake disabled providers for enabled blockers.
+- Only credential/balance/catalog-limit responses write Source blockers; service retries
+ never change model-route health. Source and service generations fence independent state.
+- Exactly one trial reserves immediately before sending. Connecting contenders share the
+ re-enable fence until the admitted winner starts its request; a skipped loser cannot invalidate
+ that winner. A slow contender admitted after recovery or re-arming takes fresh fences, using the
+ trial epoch rather than another request's generation to validate its authorization. Async final admission
+ holds a short lock after connection, never during DNS/TLS, and runs only after the HTTP client owns the
+ connection so rejection closes it. Trial release and queued usage drain survive persistence failures.
+ Identity changes retire trials; stopped calls leave no record and settle observed status/billing.
+ Stop alone creates no failure/cooldown; a received failure status still settles its outcome.
+- The chain has one 180 s budget. Only service attempts have a 30 s limit; model executors
+ retain the remaining chain budget rather than paying for an additional attempt after 30 s.
+- Sent/status/body facts determine billing once: known-unbilled is explicit zero, unknown
+ charge is never falsely priced. Each sent request is metered exactly once.
+- Mapping/JSON parsing run off the controller loop, preserve ranking, bound every output
+ field and request excerpts only. Empty result arrays complete.
+- Retry is available regardless of activation and obeys Model Hub Member authorization.
+
+Tests use synthetic vendor bytes and a fake adapter search boundary, never paid traffic or
+real keys. A local TCP/real-aiohttp test additionally owns transport-closure coverage that fake sessions
+cannot provide; it never contacts a vendor. Focused tests run through `~/.local/bin/hd1-test`; full repository checks run in CI.
+Existing released-chain tests are the flag-off control; new tables target each owner boundary.
+Scenario: `MH-SEARCH-SERVICES-001` in `tests/scenarios/model_hub/catalog.yaml`.
+
+Local validation (2026-10-21):
+- Initial broad API/runtime/authorization/settings/custody/C-6/producer run: 1,755 passed.
+- After review fixes: runtime, producer, released executors/settings/read/config: 909 passed;
+ the scenario registry's new canonical-test entry was corrected and checked separately.
+- Baseline S2a `01fc7b0`: all nine selected vendor producer/order cases fail for missing
+ requests or service ordering; the exact same flag-off control passes. No paid calls.
+- First-head review regressions: six owner-boundary cases fail on `9f25a9162` (slow trial contenders,
+ vendor error text, persistence cleanup, and hidden config reads); three real-connector cases fail
+ because rejected/cancelled admission leaks the connected socket. All pass with the fixes.
+- Review-fix runtime/structure/producer/transport suite: 873 passed. CI-failure parity/structure/mirror
+ checks and real transport tests: 200 passed. Python 3.10.19 isolated producer/transport run: 132 passed,
+ including Stop during timeout teardown; cancellation does not rely on Python 3.11 Task APIs.
+- Changed Python files pass Ruff. CI owns the full suite; no runtime restart/deployment or
+ live-vendor/manual UI acceptance is included in this dormant change.
+
+## Contract version
+
+At start, 2026-10-21: `git tag --contains 01fc7b0` returned none; latest RC release
+was `gh-v3.2.2rc13`, before S2a. Recheck before first push and close-out. Use v19 while
+unshipped; open v20 if a release has carried S2a in the meantime.
+
+Pre-push recheck, 2026-10-21: no tag contains `01fc7b0`. The new `v3.2.2` release
+(published 03:00:15 UTC) points to `399fc34c1`, before S2a. Therefore this change
+extends the still-unshipped v19 rather than opening v20.
+
+## Known by design
+
+The design's §12 governs downgrade loss, official endpoints only, no paid checks, no page
+content, vendor result quality and existing native/model-executor behavior. No UI or public
+docs changes are part of this producer PR; S4 is the consumer and S6 owns disclosure.
diff --git a/docs/plans/web-search-services.md b/docs/plans/web-search-services.md
index 7030ac9c6..7866befda 100644
--- a/docs/plans/web-search-services.md
+++ b/docs/plans/web-search-services.md
@@ -155,7 +155,8 @@ The user has an Anthropic API key and a DeepSeek API key, adds Tavily, and chang
outcome: status, a bounded header subset, `response_received_at` (the instant the headers arrived, which the retry
coordinator anchors `Retry-After` to, as `model-hub-retry-experience.md` requires) and the body, the status and
receipt time surviving a later body-read failure. Like the invocation contract's `on_admitted`, it takes an `on_sent`
- callback that it calls exactly once just before writing the request, after connect and TLS succeed; a failure or
+ callback (sync or awaitable) that it calls exactly once just before writing the request, after connect and TLS
+ succeed; final admission and trial reservation hold a short controller lock, never during connection setup. A failure or
cancellation before that call is pre-send ($0); one after it and before any status is billing-unknown; and one
after a status arrived is settled by that status (§4.3). It reads the key from the state store (`read_api_key`, as credential
retargeting does today) only for the duration of the request.
@@ -238,7 +239,8 @@ Hosted tools §6 holds, with these changes:
`services.<id>.enabled: false`; the frozen list carries such Sources last, so they are reached only after every
other candidate, and never sent a request). A skip costs nothing, writes no state, and is recorded in `attempts[]` (§4.3).
- **One attempt** sends the catalog's request for the canonical query, the turn's frozen `results`, and
- waits at most 30 s, inside the chain's single 180 s deadline.
+ waits at most 30 s, inside the chain's single 180 s deadline. This attempt bound applies only to services;
+ model executors retain hosted tools §6's remaining chain budget.
### 4.2 Outcomes
@@ -255,6 +257,11 @@ Hosted tools §6 holds, with these changes:
| any other 4xx (404, 405, 410 and the like: the endpoint or protocol, which a different query cannot fix) | next candidate, `service_unavailable` | none; a service cooldown |
| a body the mapping cannot read (`service_unreadable`) | next candidate | none; a service cooldown, because a 200 may be billed |
+A catalog row may refine a status with an exact vendor tag before applying this table. The first batch uses Exa's
+`402 API_KEY_BUDGET_EXCEEDED` and `TEAM_BUDGET_EXCEEDED` as `service_limit`, Exa's `403 PROHIBITED_CONTENT`
+and `CONTENT_FILTER_ERROR` as `service_refused`, and Tavily's `422` validation response as `service_refused`;
+unrecognized tags keep the status-only fallback (including `403 FEATURE_DISABLED` as unavailable).
+
- **A model Source with a search API (DeepSeek)** shares its key and balance with its models, so a search 401 or 402
writes the Source's health exactly as a model call would. DeepSeek documents no 403 for Search (its security-policy
403 is listed for Fetch), so a Search 403 is an undocumented status: `service_unavailable` with a cooldown, and no
@@ -286,7 +293,9 @@ Hosted tools §6 holds, with these changes:
query-specific `service_refused` is unbilled and says nothing about the account, so it releases the reservation
and leaves the trial armed: the model's corrected query uses it. Every other outcome ends the reservation, so the user can arm a new trial; a cancelled turn (the user
stops it while the trial request is in flight) releases the reservation and, if no status had arrived, keeps the
- blocker like a transient failure; a status that arrived before the stop settles the trial by the outcome table. A restart
+ blocker like a transient failure; Stop itself creates no cooldown or failure class: no status settles only billing,
+ a received 200 also authenticates and clears the trial blocker without inferring an unreadable body, and an observed
+ failure status settles its own outcome row, including health or cooldown. A restart
drops an unused trial, so the Source stays blocked and the user can press again. This fails closed. While a
trial is armed or in flight, "重新启用" is disabled (the read reports `trial_pending`), and a repeated request is
answered with the current trial without arming another or advancing the generation. Nothing retries on its own. A model Source with
@@ -398,7 +407,7 @@ Hosted tools §6 holds, with these changes:
remedy is turning "用于网页搜索" back on;
- a skipped entry's remedy is checked against the Source's current state when the record is projected: a Source
since repaired, re-enabled or removed shows no remedy (the entry still says it was skipped);
- - `superseded: true` marks a failed entry whose settlement any fence dropped (a newer attempt, a key replacement,
+ - `superseded: true` marks a failed entry whose actual health or cooldown write its owning fence dropped (a newer attempt, a key replacement,
a removal or "重新启用"). The projection also treats an entry as superseded when the Source's current health no
longer matches it, for example a key replaced after the failure settled but before the call ended. The surfaces
say "这次请求失败,状态已由之后的操作更新" for it and show no repair, since the Source's current state is not
@@ -494,7 +503,7 @@ includes, so the recorded list price stays exact.
| --- | --- | --- | --- | --- | --- | --- |
| DeepSeek | `POST https://api.deepseek.com/v1/tools/search` `{query, count}` | Bearer | 1–50 | `summary` | $0.75 / 1k successful requests; empty results, failures and timeouts not billed | `GET /user/balance`: 200 with `is_available: true` is `pass`, with `false` is `balance`; 401 is `invalid` |
| Tavily | `POST https://api.tavily.com/search` | Bearer | 1–20 | `content` (a query-relevant snippet; `include_raw_content` is never sent) | $8 / 1k basic searches | `GET https://api.tavily.com/usage`: a 200 needs at least one numeric usage/limit pair (`key.usage`/`key.limit`, `account.plan_usage`/`account.plan_limit`, `account.paygo_usage`/`account.paygo_limit`), and each recognized pair must be wholly absent or have both members as valid numbers, otherwise the result is `unknown`; a `key.limit` of null is Tavily's unlimited key ([OpenAPI](https://docs.tavily.com/documentation/api-reference/openapi.json), 2026-10-20) and counts as a key pair with headroom. A present key pair at its limit is `limit`. Otherwise, with no account pair (Tavily's schema makes `account` optional) the answer still authenticates the key and is `pass`, payment being confirmed by the first search as for a vendor without a free check; with one, it is `pass` when the plan pair or the pay-as-you-go pair has headroom (pay-as-you-go continues after the plan allowance) and `limit` when none does; 401 is `invalid` |
-| Exa | `POST https://api.exa.ai/search` | `x-api-key` | 1–10 (the base price includes 10) | always `contents.highlights` (the `snippet` source, since a base result has no excerpt), included in the search price since Exa 3.0 ([announcement](https://exa.ai/blog/exa-3), 2026-10-19); `contents.text` is never requested | $7 / 1k (Exa Auto); the response's `costDollars` is used when present | none known |
+| Exa | `POST https://api.exa.ai/search` | `x-api-key` | 1–10 (the base price includes 10) | always `contents.highlights` (the `snippet` source, since a base result has no excerpt), included in the search price since Exa 3.0 ([announcement](https://exa.ai/blog/exa-3), 2026-10-19); `contents.text` is never requested | $7 / 1k (Exa Auto); the response's `costDollars` is used when present | none known; status/tag mappings use the [error-codes page](https://exa.ai/docs/admin/error-codes) (2026-10-21) |
- DeepSeek facts that shape the UI (DeepSeek's Search & Fetch guide, 2026-10-19): the query is 1–128 characters and
supports operators (`site:`, `lang:`, `after:`, quoted phrases). The catalog records the list price only. Any
diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yaml
index 16176f01b..d091cf2bf 100644
--- a/tests/scenarios/INDEX.yaml
+++ b/tests/scenarios/INDEX.yaml
@@ -106,6 +106,7 @@ capabilities:
- tests/test_model_hub_migration_bearer.py
- tests/test_model_hub_transport_leases.py
- tests/test_model_hub_hosted_executor.py
+ - tests/test_model_hub_search_chain.py
- tests/test_model_hub_hosted_evidence.py
- tests/test_model_hub_hosted_images.py
- tests/test_model_hub_usage.py
diff --git a/tests/scenarios/model_hub/catalog.yaml b/tests/scenarios/model_hub/catalog.yaml
index 927a70083..f8b15879b 100644
--- a/tests/scenarios/model_hub/catalog.yaml
+++ b/tests/scenarios/model_hub/catalog.yaml
@@ -47,6 +47,7 @@ capability:
- tests/test_model_hub_migration_bearer.py
- tests/test_model_hub_transport_leases.py
- tests/test_model_hub_hosted_executor.py
+ - tests/test_model_hub_search_chain.py
- tests/test_model_hub_hosted_evidence.py
- tests/test_model_hub_hosted_images.py
- tests/test_model_hub_usage.py
@@ -2584,6 +2585,23 @@ scenarios:
related_tests:
- tests/test_model_hub_service_acceptance_helpers.py::test_an_ignored_override_that_installs_the_packaged_engine_fails_the_run
- tests/test_model_hub_service_acceptance_helpers.py::test_a_selected_manifest_without_a_usable_version_fails_the_run
+ - id: MH-SEARCH-SERVICES-001
+ name: The dormant search-service producer freezes a one-role service and model chain, bounds excerpts, fences health and cooldown independently, admits one recovery trial, and meters every sent request by observed billing facts without changing flag-off behavior
+ status: covered
+ kind: contract
+ layer: contract
+ test: tests/test_model_hub_search_chain.py::test_vendor_request_mapping_meter_and_evidence
+ related_tests:
+ - tests/test_model_hub_search_chain.py::test_order_placement_is_read_only_and_survives_reload
+ - tests/test_model_hub_search_chain.py::test_skip_precedence_terminal_reason_and_attempts_without_execution
+ - tests/test_model_hub_search_chain.py::test_billing_is_a_function_of_sent_status_and_original_results
+ - tests/test_model_hub_search_chain.py::test_connect_holds_no_mutation_lock_and_only_the_first_ready_trial_sends
+ - tests/test_model_hub_search_chain.py::test_stop_during_timeout_teardown_never_runs_the_next_paid_candidate
+ - tests/test_model_hub_search_chain.py::test_model_executor_retains_the_chain_budget_not_the_service_attempt_limit
+ - tests/test_model_hub_search_chain.py::test_health_and_cooldown_fences_each_protect_only_their_own_state
+ - tests/test_model_hub_search_chain.py::test_prefer_native_off_flows_through_the_hop_to_function_declaration_and_synthetic_history
+ - tests/test_model_hub_search_chain.py::test_retry_http_client_rpc_clears_only_the_service_fence_with_plain_success
+ - tests/test_model_hub_search_chain.py::test_flag_off_retains_the_released_frozen_read_and_chain
- id: MH-HOSTED-GATEWAY-004
name: A proxied search runs one native request on the turn's first admitted executor, without an effort, and answers its canonical record and execution with the pricing module's cost and the same positive evidence a native call writes
status: covered
diff --git a/tests/test_instance_authorization.py b/tests/test_instance_authorization.py
index 2a47893bc..20c819917 100644
--- a/tests/test_instance_authorization.py
+++ b/tests/test_instance_authorization.py
@@ -513,6 +513,7 @@ def test_all_registered_model_hub_routes_follow_instance_management_roles() -> N
}
assert len(endpoints) >= 40
assert ("POST", "/api/models/sources/sample-1/reenable") in endpoints
+ assert ("POST", "/api/models/hosted-tools/web_search/services/sample-1/retry") in endpoints
for method, path in endpoints:
picker = method == "GET" and re.fullmatch(r"/api/models/agents/[^/]+/models", path)
minimum_role = http_authorization_policy(method, path).minimum_role
@@ -545,6 +546,7 @@ def test_model_hub_unknown_siblings_remain_owner_only(method: str) -> None:
assert http_authorization_policy(method, path).minimum_role == "owner"
if method != "POST":
assert http_authorization_policy(method, "/api/models/sources/src-1/reenable").minimum_role == "owner"
+ assert http_authorization_policy(method, "/api/models/hosted-tools/web_search/services/src-1/retry").minimum_role == "owner"
@pytest.mark.parametrize("method", ["PATCH", "DELETE"])
diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.py
index 2ce3c26b2..cc7cf5a13 100644
--- a/tests/test_member_management_parity.py
+++ b/tests/test_member_management_parity.py
@@ -118,7 +118,10 @@ def test_complete_registered_api_management_inventory():
for method in (getattr(route, "methods", None) or ())
if method not in {"HEAD", "OPTIONS"}
}
- assert len(endpoints) == 290
+ assert len(endpoints) == 291
+ retry_route = "/api/models/hosted-tools/web_search/services/{source_id}/retry"
+ assert ("POST", retry_route) in endpoints
+ assert http_authorization_policy("POST", retry_route).minimum_role == "member"
assert ("GET", "/api/sessions/main") in endpoints
assert http_authorization_policy("POST", "/api/vault/requests/{request_id}/approve-delete").minimum_role == "editor"
# Approvers still read policy and remember duration; protection fields add a service check.
diff --git a/tests/test_model_hub_runtime.py b/tests/test_model_hub_runtime.py
index d7ebdcf2d..fa40e8604 100644
--- a/tests/test_model_hub_runtime.py
+++ b/tests/test_model_hub_runtime.py
@@ -2328,8 +2328,16 @@ def test_search_free_check_uses_bounded_catalog_transport(monkeypatch):
},
}
+ matches = runtime_adapter_module._search_check_matches
+
+ def checked_off_loop(*args):
+ calls["mapping_thread"] = threading.current_thread().name
+ return matches(*args)
+
+ monkeypatch.setattr(runtime_adapter_module, "_search_check_matches", checked_off_loop)
outcome = asyncio.run(adapter.check_search_credential("cred_search", catalog))
+ assert calls["mapping_thread"] != caller_thread
assert outcome.outcome == "pass"
timeout = calls["session_kwargs"]["timeout"]
assert timeout.total == 10.0
@@ -2375,23 +2383,25 @@ def test_search_response_retains_wire_facts_after_body_read_failure(
headers = {"Content-Type": "application/json", "Retry-After": "2"}
content = ResponseContent()
+ async def write(_request, _connection):
+ calls.append("write")
+ return Response()
+
+ monkeypatch.setattr(runtime_adapter_module.aiohttp.ClientRequest, "send", write)
+
class Request:
- def __init__(self, traces):
- self.traces = traces
+ def __init__(self, request_class):
+ self.request_class = request_class
async def __aenter__(self):
- for trace in self.traces:
- for callback in trace.on_connection_create_end:
- await callback(None, None, None)
- calls.append("write")
- return Response()
+ return await self.request_class.send(object.__new__(self.request_class), None)
async def __aexit__(self, *_args):
return None
class Session:
- def __init__(self, *, trace_configs, **_kwargs):
- self.traces = trace_configs
+ def __init__(self, *, request_class, **_kwargs):
+ self.request_class = request_class
async def __aenter__(self):
return self
@@ -2400,7 +2410,7 @@ def test_search_response_retains_wire_facts_after_body_read_failure(
return None
def request(self, _method, _endpoint, **_kwargs):
- return Request(self.traces)
+ return Request(self.request_class)
monkeypatch.setattr(runtime_adapter_module.aiohttp, "ClientSession", Session)
adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=Store()) # type: ignore[arg-type]
@@ -2424,7 +2434,8 @@ def test_search_response_retains_wire_facts_after_body_read_failure(
assert calls == ["sent", "write"]
-def test_search_on_sent_fires_once_after_connection_ready_before_write(monkeypatch):
[email protected]("admission", ["sync", "async", "refused", "cancelled"])
+def test_search_on_sent_fires_once_after_connection_ready_before_write(monkeypatch, admission):
calls: list[str] = []
class Store:
@@ -2443,25 +2454,25 @@ def test_search_on_sent_fires_once_after_connection_ready_before_write(monkeypat
headers = {}
content = ResponseContent()
+ async def write(_request, _connection):
+ calls.append("write")
+ return Response()
+
+ monkeypatch.setattr(runtime_adapter_module.aiohttp.ClientRequest, "send", write)
+
class Request:
- def __init__(self, traces):
- self.traces = traces
+ def __init__(self, request_class):
+ self.request_class = request_class
async def __aenter__(self):
- for trace in self.traces:
- for callback in trace.on_connection_create_end:
- await callback(None, None, None)
- for callback in trace.on_connection_reuseconn:
- await callback(None, None, None)
- calls.append("write")
- return Response()
+ return await self.request_class.send(object.__new__(self.request_class), None)
async def __aexit__(self, *_args):
return None
class Session:
- def __init__(self, *, trace_configs, **_kwargs):
- self.traces = trace_configs
+ def __init__(self, *, request_class, **_kwargs):
+ self.request_class = request_class
async def __aenter__(self):
return self
@@ -2470,11 +2481,19 @@ def test_search_on_sent_fires_once_after_connection_ready_before_write(monkeypat
return None
def request(self, _method, _endpoint, **_kwargs):
- return Request(self.traces)
+ return Request(self.request_class)
monkeypatch.setattr(runtime_adapter_module.aiohttp, "ClientSession", Session)
adapter = CLIProxyEngineAdapter(supervisor=object(), state_store=Store()) # type: ignore[arg-type]
+ async def final_admission():
+ await asyncio.sleep(0)
+ if admission == "refused":
+ raise ValueError("not admitted")
+ if admission == "cancelled":
+ raise asyncio.CancelledError
+ calls.append("sent")
+
response = asyncio.run(
adapter.search(
"src_search",
@@ -2482,10 +2501,14 @@ def test_search_on_sent_fires_once_after_connection_ready_before_write(monkeypat
"tavily/search",
"cred_search",
{"query": "hello", "max_results": 1},
- on_sent=lambda: calls.append("sent"),
+ on_sent=(lambda: calls.append("sent")) if admission == "sync" else final_admission,
)
)
+ if admission in {"refused", "cancelled"}:
+ assert calls == [] and response.on_sent_fired is False and response.http_status is None
+ assert response.error == ("connection" if admission == "refused" else "cancelled")
+ return
assert response.http_status == 200
assert response.on_sent_fired is True
assert calls == ["sent", "write"]
@@ -2730,7 +2753,7 @@ def test_shipped_api_key_vendor_catalog_matches_its_schema() -> None:
@pytest.mark.parametrize("vendor,protocol,snippet", [
- ("deepseek", "openai_chat", "snippet"), ("tavily", "search", "content"), ("exa", "search", "highlights"),
+ ("deepseek", "openai_chat", "summary"), ("tavily", "search", "content"), ("exa", "search", "highlights"),
])
def test_search_catalog_maps_only_snippets_without_page_text_or_surcharges(vendor, protocol, snippet) -> None:
"""The bundled wire mapping is the owner of what S2 may request: no paid page text.
@@ -2739,7 +2762,10 @@ def test_search_catalog_maps_only_snippets_without_page_text_or_surcharges(vendo
the snippet-only shape while keeping Exa's included highlights and reported cost.
"""
service = search_service(vendor, protocol)
- assert set(service["request"]) == {"method", "query", "results"} | ({"highlights"} if vendor == "exa" else set())
+ assert set(service["request"]) == (
+ {"method", "query", "results"} | ({"highlights"} if vendor == "exa" else set())
+ | ({"defaults"} if vendor in {"exa", "tavily"} else set())
+ )
assert set(service["result"]) == {"results", "url", "title", "snippet", "page_age"} | (
{"reported_cost"} if vendor == "exa" else set()
)
diff --git a/tests/test_model_hub_search_chain.py b/tests/test_model_hub_search_chain.py
new file mode 100644
index 000000000..1b14f70c9
--- /dev/null
+++ b/tests/test_model_hub_search_chain.py
@@ -0,0 +1,994 @@
+"""MH-SEARCH-SERVICES-001: producer contracts at the chain/custody boundary.
+
+Existing hosted executor tests cover model-only calls, not adapter search calls,
+service-only retries or one-shot trials. These tables exercise real resolution,
+settlement, C-1 serialization and metering; only the credential adapter is faked.
+"""
+
+import asyncio
+import copy
+import json
+import threading
+from datetime import timedelta
+
+import pytest
+
+from config.v2_config import ModelHubConfig, ModelHubSourceStateConfig
+from core.handlers.model_hub import hosted_tools
+from core.handlers.model_hub.adapter import SearchCredentialCheck, SearchResponse
+from core.handlers.model_hub.capability_evidence import EvidenceFeature
+from tests.test_model_hub_api import _service
+from tests.test_model_hub_hosted_executor import _hosted_result
+from tests.test_model_hub_l3 import NOW
+from tests.test_model_hub_search_settings import (
+ DEEPSEEK, EXA, MODEL, TAVILY, _config, _web,
+)
+
+IDS = {"deepseek": DEEPSEEK, "tavily": TAVILY, "exa": EXA}
+ROW = {"url": "https://example.test/a", "title": "Title", "summary": "Model excerpt",
+ "snippet": "UI excerpt", "content": "Tavily excerpt", "highlights": ["First", "Second"],
+ "date": "2026-10-21", "published_date": "today", "publishedDate": "yesterday"}
+
+
[email protected](autouse=True)
+def active(monkeypatch):
+ monkeypatch.setattr(hosted_tools, "SEARCH_SERVICES_ACTIVE", True)
+
+
+def owner(tmp_path, vendors=("exa",), *, web=None, model=False):
+ service, store, adapter = _service(tmp_path)
+ config = _config(web)
+ selected = [IDS[vendor] for vendor in vendors]
+ config.sources = [next(s for s in config.sources if s.id == sid) for sid in selected] + (
+ [next(s for s in config.sources if s.id == MODEL)] if model else []
+ )
+ store.config = config
+ service.now = lambda: NOW
+ return service
+
+
+def wire(status=200, body=None, *, error="", headers=None):
+ return SearchResponse(status, headers or {}, json.dumps(body if body is not None else {"results": [ROW]}).encode(),
+ error, response_received_at=NOW)
+
+
+def answers(monkeypatch, service, *responses, sent=True):
+ calls = []
+ pending = iter(responses)
+
+ async def search(source_id, vendor, service_id, credential_ref, request, *, on_sent):
+ calls.append((source_id, vendor, service_id, credential_ref, request))
+ if sent:
+ await on_sent()
+ value = next(pending)
+ if isinstance(value, BaseException):
+ raise value
+ return value
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ return calls
+
+
+async def run(service, query="query", turn=None):
+ return await service.run_hosted_tool(
+ "web_search", {"arguments": {"query": query}}, turn=turn or service.freeze_turn_hosted_tools(service.store.load()),
+ )
+
+
+def summary(service):
+ return service.usage_summary(days=7)
+
+
[email protected]("vendor,expected_request,snippet,cost", [
+ ("deepseek", {"query": "query", "count": 5}, "Model excerpt", .00075),
+ ("tavily", {"query": "query", "max_results": 5, "search_depth": "basic", "include_answer": False}, "Tavily excerpt", .008),
+ ("exa", {"query": "query", "numResults": 5, "type": "auto", "contents": {"highlights": True}}, "First\nSecond", .007),
+])
+async def test_vendor_request_mapping_meter_and_evidence(tmp_path, monkeypatch, vendor, expected_request, snippet, cost):
+ """MH-SEARCH-SERVICES-001: one catalog request produces bounded C-1 facts, usage and service evidence."""
+ service = owner(tmp_path, (vendor,))
+ calls = answers(monkeypatch, service, wire())
+ result = await run(service)
+ assert calls == [(IDS[vendor], vendor, f"{vendor}/search", f"cred_{IDS[vendor]}", expected_request)]
+ loaded = _hosted_result("web_search", result)
+ assert loaded.record.status == "completed"
+ assert loaded.record.sources[0].snippet == snippet
+ assert result["execution"]["executor_origin"] == {"provider": vendor, "api": "search_api", "model": f"{vendor}/search"}
+ assert result["record"]["attempts"] == [{"source_id": IDS[vendor], "label": vendor, "kind": "service",
+ "outcome": "completed", "cost": {"basis": "list", "usd": cost}}]
+ usage = summary(service)
+ assert usage["services"][0]["requests"] == usage["services"][0]["billable_requests"] == 1
+ assert usage["totals"]["requests"] == 0
+ assert usage["sources"] == []
+ assert _web(service)["status"]["latest_ok"]["mode"] == "service"
+
+
[email protected]("vendor,status,tag,error,expected,health,cooling", [
+ ("exa", 401, None, "", "service_key_invalid", "credential_revoked", False),
+ ("deepseek", 402, None, "", "service_balance", "balance_exhausted", False),
+ ("tavily", 432, None, "", "service_limit", "spend_limit_reached", False),
+ ("tavily", 433, None, "", "service_limit", "spend_limit_reached", False),
+ ("exa", 402, "API_KEY_BUDGET_EXCEEDED", "", "service_limit", "spend_limit_reached", False),
+ ("exa", 402, "TEAM_BUDGET_EXCEEDED", "", "service_limit", "spend_limit_reached", False),
+ ("exa", 402, "NEW_TAG", "", "service_balance", "balance_exhausted", False),
+ ("exa", 403, "PROHIBITED_CONTENT", "", "service_refused", None, False),
+ ("exa", 403, "CONTENT_FILTER_ERROR", "", "service_refused", None, False),
+ ("exa", 403, "FEATURE_DISABLED", "", "service_unavailable", None, True),
+ ("exa", 403, "NEW_TAG", "", "service_unavailable", None, True),
+ ("deepseek", 403, None, "", "service_unavailable", None, True),
+ ("tavily", 422, None, "", "service_refused", None, False),
+ ("exa", 400, None, "", "service_refused", None, False),
+ ("exa", 408, None, "", "service_unavailable", None, True),
+ ("exa", 429, None, "", "service_unavailable", None, True),
+ ("exa", 500, None, "", "service_unavailable", None, True),
+ ("exa", 503, None, "", "service_unavailable", None, True),
+ ("exa", 302, None, "redirect", "service_unavailable", None, True),
+ ("exa", 404, None, "", "service_unavailable", None, True),
+ ("exa", 405, None, "", "service_unavailable", None, True),
+ ("exa", 410, None, "", "service_unavailable", None, True),
+ ("exa", None, None, "connection", "service_unavailable", None, True),
+])
+async def test_outcome_table_writes_only_classified_health(tmp_path, monkeypatch, vendor, status, tag, error, expected, health, cooling):
+ service = owner(tmp_path, (vendor,))
+ before = service.store.load().sources[0].state
+ answers(monkeypatch, service, wire(status, {"tag": tag, "error": "query detail"}, error=error))
+ result = await run(service)
+ assert result["record"]["error_code"] == expected
+ assert result["record"]["attempts"][0]["error_code"] == expected
+ source = service.store.load().sources[0]
+ if health:
+ assert source.state == ModelHubSourceStateConfig(status="needs_action", detail_key=f"models.source.needs_action.{health}")
+ else:
+ assert source.state == before
+ assert (service._service_cooldowns.until(source, f"{vendor}/search", NOW) is not None) == cooling
+ assert not service.hosted_evidence().unsupported(source, f"{vendor}/search", EvidenceFeature.hosted("web_search", "call"))
+ if status is not None:
+ assert result["execution"]["cost"] == {"basis": "list", "usd": 0}
+ if expected == "service_refused":
+ assert "query detail" in result["record"]["error"]
+
+
[email protected]("vendor,status,body,error,sent,usd,billable,uncertain", [
+ ("deepseek", 200, {"results": []}, "", True, 0, 0, 0),
+ ("exa", 200, {"results": []}, "", True, .007, 1, 0),
+ ("tavily", 200, {"results": []}, "", True, .008, 1, 0),
+ ("deepseek", 200, {}, "", True, None, 0, 1),
+ ("deepseek", 200, {"results": [{"url": "file:///bad"}]}, "", True, .00075, 1, 0),
+ ("exa", 200, {}, "body_too_large", True, .007, 1, 0),
+ ("tavily", 200, {}, "timeout", True, .008, 1, 0),
+ ("deepseek", 200, {}, "timeout", True, None, 0, 1),
+ ("deepseek", None, {}, "timeout", True, 0, 0, 0),
+ ("exa", None, {}, "timeout", True, None, 0, 1),
+ ("deepseek", None, {}, "connection", True, None, 0, 1),
+ ("exa", None, {}, "connection", True, None, 0, 1),
+ ("exa", 401, {}, "timeout", True, 0, 0, 0),
+ ("tavily", 402, {}, "connection", True, 0, 0, 0),
+ ("deepseek", None, {}, "connection", False, 0, 0, 0),
+ ("exa", None, {}, "timeout", False, 0, 0, 0),
+])
+async def test_billing_is_a_function_of_sent_status_and_original_results(tmp_path, monkeypatch, vendor, status, body, error, sent, usd, billable, uncertain):
+ service = owner(tmp_path, (vendor,))
+ answers(monkeypatch, service, wire(status, body, error=error), sent=sent)
+ result = await run(service)
+ attempt = result["record"]["attempts"][0]
+ if usd is None:
+ assert "cost" not in attempt and "cost" not in result["execution"]
+ else:
+ assert attempt["cost"] == {"basis": "list", "usd": usd}
+ rows = summary(service)["services"]
+ if sent:
+ assert (rows[0]["requests"], rows[0]["billable_requests"], rows[0]["uncertain_requests"]) == (1, billable, uncertain)
+ else:
+ assert rows == [] and attempt["outcome"] == "failed"
+ _hosted_result("web_search", result)
+
+
[email protected]("reported,expected", [(0, 0), (.012, .012), (.7, .7), (.701, None), (-1, None), (True, None), ("0.01", None), (float("nan"), None), (float("inf"), None), (10**100, None)])
+async def test_reported_cost_is_bounded_estimated_and_metered(tmp_path, monkeypatch, reported, expected):
+ service = owner(tmp_path)
+ answers(monkeypatch, service, wire(body={"results": [ROW], "costDollars": {"total": reported}}))
+ result = await run(service)
+ assert result["execution"]["cost"] == (
+ {"usd": expected, "basis": "reported", "estimate": True} if expected is not None else {"usd": .007, "basis": "list"}
+ )
+ assert summary(service)["services"][0]["reported_requests"] == int(expected is not None)
+
+
[email protected]("body,status", [
+ ({"results": []}, "completed"), ({}, "failed"), ({"results": None}, "failed"),
+ ({"results": [{"url": "ftp://example.test"}, {"url": "https://x/" + "a" * 2048}]}, "failed"),
+ ({"results": [None, 1, {"url": "https://[bad"}]}, "failed"),
+])
+async def test_empty_results_complete_but_nonempty_unmappable_results_fail_over(tmp_path, monkeypatch, body, status):
+ service = owner(tmp_path, ("exa", "tavily"))
+ calls = answers(monkeypatch, service, wire(body=body), wire())
+ result = await run(service)
+ assert result["record"]["status"] == "completed"
+ assert len(calls) == (1 if status == "completed" else 2)
+ if status == "failed":
+ assert result["record"]["attempts"][0]["error_code"] == "service_unreadable"
+ assert result["execution"]["failed_attempts"] == [{"source_id": EXA, "billing": "metered", "cost": {"basis": "list", "usd": .007}}]
+
+
+async def test_mapping_bounds_and_decode_are_off_loop(tmp_path, monkeypatch):
+ from core.handlers.model_hub import search_chain
+
+ service = owner(tmp_path, ("deepseek",), web={"services": {DEEPSEEK: {"results": 2}}})
+ row = {"url": "https://x/" + "u" * 2038, "title": "t" * 900, "summary": "s" * 3000, "date": "d" * 100}
+ rows = [{"url": "data:bad"}, row, {**row, "url": "https://second.test"}, ROW]
+ answers(monkeypatch, service, wire(body={"results": rows}))
+ mapped = search_chain.map_response
+ threads = []
+
+ def recording(*args, **kwargs):
+ threads.append(threading.get_ident())
+ return mapped(*args, **kwargs)
+
+ monkeypatch.setattr(search_chain, "map_response", recording)
+ result = await run(service)
+ assert len(result["record"]["sources"]) == 2
+ first = result["record"]["sources"][0]
+ assert [len(first[key]) for key in ("url", "title", "snippet", "page_age")] == [2048, 300, 1000, 64]
+ assert threads and threading.get_ident() not in threads
+
+
[email protected]("saved,kinds,expected", [
+ (None, None, [EXA, TAVILY, DEEPSEEK, MODEL]),
+ ([MODEL], None, [EXA, TAVILY, DEEPSEEK, MODEL]),
+ ([MODEL, DEEPSEEK], None, [EXA, TAVILY, DEEPSEEK, MODEL]),
+ ([MODEL, DEEPSEEK], {MODEL: "model", DEEPSEEK: "service"}, [EXA, TAVILY, MODEL, DEEPSEEK]),
+ ([DEEPSEEK], {DEEPSEEK: "service"}, [DEEPSEEK, EXA, TAVILY, MODEL]),
+ ([EXA, MODEL], {EXA: "model", MODEL: "model"}, [EXA, TAVILY, DEEPSEEK, MODEL]),
+])
+def test_order_placement_is_read_only_and_survives_reload(tmp_path, saved, kinds, expected):
+ web = {"service_order": [EXA, TAVILY]}
+ if saved is not None:
+ web["executor_order"] = saved
+ if kinds is not None:
+ web["executor_order_kinds"] = kinds
+ service = owner(tmp_path, ("tavily", "deepseek", "exa"), web=web, model=True)
+ before = copy.deepcopy(service.store.load().to_payload())
+ assert _web(service)["effective_order"] == expected
+ assert [slot.source_id for slot in service.freeze_turn_hosted_tools(service.store.load()).executors["web_search"]] == expected
+ service.store.config = ModelHubConfig.from_payload(before)
+ assert _web(service)["effective_order"] == expected
+ assert service.store.load().to_payload() == before
+
+
+async def test_turn_freezes_preference_candidates_results_and_disabled_tail(tmp_path, monkeypatch):
+ service = owner(tmp_path, ("exa", "deepseek"), model=True,
+ web={"prefer_native": False, "services": {EXA: {"results": 2}, DEEPSEEK: {"enabled": False}}})
+ turn = service.freeze_turn_hosted_tools(service.store.load())
+ assert [slot.source_id for slot in turn.executors["web_search"]] == [EXA, MODEL, DEEPSEEK]
+ model = service.store.load().sources[-1]
+ facts = service.hosted_tools_for_hop(model, "grok-4.6", turn)["web_search"]
+ assert facts == {"native": "unsupported", "replay": "unsupported"}
+ await service.set_hosted_tool("web_search", {"prefer_native": True, "services": {EXA: {"results": 9}, DEEPSEEK: {"enabled": True}}})
+ calls = answers(monkeypatch, service, wire())
+ await run(service, turn=turn)
+ assert calls[0][-1]["numResults"] == 2
+ assert service.hosted_tools_for_hop(model, "grok-4.6", turn)["web_search"] == facts
+ fresh = service.freeze_turn_hosted_tools(service.store.load())
+ assert fresh.prefer_native is True and fresh.executors["web_search"][0].results == 9
+ assert service.hosted_tools_for_hop(model, "grok-4.6", fresh)["web_search"]["native"] == "assumed"
+
+
[email protected]("mix,code,skips", [
+ ("disabled", "search_sources_blocked", ["disabled", "disabled"]),
+ ("blocked", "search_sources_blocked", ["blocked", "disabled"]),
+ ("cooling", "service_unavailable", ["cooling", "disabled"]),
+ ("unavailable", "service_unavailable", ["unavailable", "disabled"]),
+ ("long", "search_query_too_long", ["query_too_long", "disabled"]),
+ ("blocked_long", "search_sources_blocked", ["blocked", "disabled"]),
+ ("cooling_long", "service_unavailable", ["cooling", "disabled"]),
+])
+async def test_skip_precedence_terminal_reason_and_attempts_without_execution(tmp_path, mix, code, skips):
+ service = owner(tmp_path, ("deepseek", "exa"), web={"services": {EXA: {"enabled": False}, DEEPSEEK: {"enabled": mix != "disabled"}}})
+ source = service.store.load().sources[0]
+ if mix.startswith("blocked"):
+ source.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.credential_revoked")
+ elif mix.startswith("cooling"):
+ source.state = ModelHubSourceStateConfig(status="cooldown", detail_key="models.source.cooldown.rate_limited", retry_at=(NOW + timedelta(seconds=70)).isoformat())
+ turn = service.freeze_turn_hosted_tools(service.store.load())
+ if mix == "unavailable":
+ source.credential_generation = "vp_" + "2" * 32
+ result = await run(service, "x" * 129, turn)
+ assert result["record"]["error_code"] == code
+ assert [attempt["skipped"] for attempt in result["record"]["attempts"]] == skips
+ assert "execution" not in result
+ assert all("cost" not in attempt for attempt in result["record"]["attempts"])
+ assert summary(service)["services"] == []
+ if mix.startswith("blocked"):
+ assert result["record"]["attempts"][0]["needs_action"].endswith("credential_revoked")
+ if mix == "long":
+ assert "128" in result["record"]["error"]
+ _hosted_result("web_search", result)
+
+
+async def test_service_retry_advice_backoff_and_clear_are_independent_of_model_calls(tmp_path, monkeypatch):
+ service = owner(tmp_path, ("deepseek",))
+ source = service.store.load().sources[0]
+ clock = [NOW]
+ service.now = lambda: clock[0]
+ answers(monkeypatch, service, wire(503, headers={"Retry-After": "900"}), *(wire(500) for _ in range(4)), wire())
+ await run(service)
+ assert source.state.status == "standby"
+ assert _web(service)["executor_candidates"][0]["cooldown_until"] == (NOW + timedelta(seconds=900)).isoformat().replace("+00:00", "Z")
+ service._reserve_settlement_generation(source.id) # A model call does not touch the service fence.
+ assert (await run(service))["record"]["attempts"][0]["skipped"] == "cooling"
+ clock[0] += timedelta(seconds=901)
+ for delay in (60, 120, 240, 300):
+ await run(service)
+ until = service._service_cooldowns.until(source, "deepseek/search", clock[0])
+ assert until == clock[0] + timedelta(seconds=delay)
+ clock[0] = until + timedelta(seconds=1)
+ await service.clear_service_cooldown(source.id, "deepseek/search")
+ assert _web(service)["executor_candidates"][0]["cooldown_until"] is None
+ assert (await run(service))["record"]["status"] == "completed"
+
+
[email protected]("status", [200, 402, 432])
+async def test_authenticating_outcomes_clear_pending_without_changing_identity(tmp_path, monkeypatch, status):
+ service = owner(tmp_path, ("tavily",))
+ source = service.store.load().sources[0]
+ source.verification_pending = source.credential_generation = "vp_" + "1" * 32
+ before = hosted_tools.identity_digest(source)
+ answers(monkeypatch, service, wire(status))
+ await run(service)
+ current = service.store.load().sources[0]
+ assert current.verification_pending is None
+ assert hosted_tools.identity_digest(current) == before
+
+
[email protected]("status,body,pending,detail", [
+ (200, {"results": []}, False, None),
+ (200, {}, False, None),
+ (401, {}, False, "credential_revoked"),
+ (402, {}, False, "balance_exhausted"),
+ (400, {}, True, "spend_limit_reached"),
+ (503, {}, False, "spend_limit_reached"),
+])
+async def test_trial_is_one_request_and_settles_by_observed_outcome(tmp_path, monkeypatch, status, body, pending, detail):
+ service = owner(tmp_path)
+ source = service.store.load().sources[0]
+ source.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.spend_limit_reached")
+ await service.reenable_search_source(source.id)
+ generation = service._latest_source_attempt_generation[source.id]
+ assert (await service.reenable_search_source(source.id))["trial_armed"] is True
+ assert service._latest_source_attempt_generation[source.id] == generation
+ entered, finish = asyncio.Event(), asyncio.Event()
+
+ async def search(*args, on_sent):
+ await on_sent()
+ entered.set()
+ await finish.wait()
+ return wire(status, body)
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ task = asyncio.create_task(run(service))
+ await entered.wait()
+ assert _web(service)["executor_candidates"][0]["trial_pending"] is True
+ assert (await run(service))["record"]["attempts"][0]["skipped"] == "blocked"
+ assert (await service.reenable_search_source(source.id))["trial_armed"] is True
+ finish.set()
+ await task
+ assert service.search_reenable_trial_pending(source.id) == pending
+ current = service.store.load().sources[0]
+ assert current.state.detail_key == (f"models.source.needs_action.{detail}" if detail else None)
+ assert summary(service)["services"][0]["requests"] == 1
+
+
[email protected]("sent,status,vendor,expected", [
+ (False, None, "exa", None), (True, None, "exa", (0, 1)),
+ (True, 401, "exa", (0, 0)), (True, 200, "exa", (1, 0)),
+ (True, 200, "deepseek", (0, 1)), (True, 503, "exa", (0, 0)),
+])
+async def test_stop_has_no_record_but_keeps_received_status_and_metering(tmp_path, monkeypatch, sent, status, vendor, expected):
+ service = owner(tmp_path, (vendor,))
+ source = service.store.load().sources[0]
+ source.verification_pending = source.credential_generation = "vp_" + "4" * 32
+ entered = asyncio.Event()
+
+ async def search(*args, on_sent):
+ if sent:
+ await on_sent()
+ entered.set()
+ try:
+ await asyncio.Future()
+ except asyncio.CancelledError:
+ return SearchResponse(status, {}, None, "cancelled", sent, NOW if status else None)
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ task = asyncio.create_task(run(service))
+ await entered.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ current = service.store.load().sources[0]
+ assert (service._service_cooldowns.until(current, f"{vendor}/search", NOW) is not None) is (status == 503)
+ assert (current.state.status == "needs_action") is (status == 401)
+ assert (current.verification_pending is None) is (status == 200)
+ rows = summary(service)["services"]
+ if expected is None:
+ assert rows == []
+ else:
+ assert (rows[0]["billable_requests"], rows[0]["uncertain_requests"]) == expected
+ assert rows[0]["requests"] == 1
+
+
[email protected]("mutation", ["new_attempt", "replace", "remove", "retry", "reenable"])
+async def test_late_failures_are_fenced_and_report_supersession(tmp_path, monkeypatch, mutation):
+ service = owner(tmp_path)
+ source = service.store.load().sources[0]
+ entered, finish = asyncio.Event(), asyncio.Event()
+
+ async def search(*args, on_sent):
+ await on_sent()
+ entered.set()
+ await finish.wait()
+ return wire(401)
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ task = asyncio.create_task(run(service))
+ await entered.wait()
+ if mutation == "new_attempt":
+ service._reserve_settlement_generation(source.id)
+ elif mutation == "retry":
+ await service.clear_service_cooldown(source.id)
+ elif mutation == "reenable":
+ source.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.spend_limit_reached")
+ await service.reenable_search_source(source.id)
+ else:
+ config = service._clone_config(service.store.load())
+ if mutation == "replace":
+ config.sources[0].credential_generation = "vp_" + "2" * 32
+ else:
+ config.sources = []
+ await service._save_config(config)
+ result = None
+ finish.set()
+ result = await task
+ assert result["record"]["attempts"][0].get("superseded", False) is (mutation != "retry")
+ current = service.store.load().sources
+ if current and mutation not in {"retry"}:
+ assert current[0].state.detail_key != "models.source.needs_action.credential_revoked"
+ assert summary(service)["services"][0]["requests"] == 1
+
+
+async def test_free_check_is_joined_without_holding_the_mutation_lock(tmp_path, monkeypatch):
+ service = owner(tmp_path, ("tavily",))
+ source = service.store.load().sources[0]
+ source.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.spend_limit_reached")
+ entered, finish = asyncio.Event(), asyncio.Event()
+ calls = []
+
+ async def check(*args):
+ calls.append(args)
+ entered.set()
+ await finish.wait()
+ return SearchCredentialCheck("pass")
+
+ monkeypatch.setattr(service.adapter, "check_search_credential", check)
+ first = asyncio.create_task(service.reenable_search_source(source.id))
+ await entered.wait()
+ second = asyncio.create_task(service.reenable_search_source(source.id))
+ await asyncio.sleep(0)
+ assert not service._mutation_lock.locked()
+ finish.set()
+ a, b = await asyncio.gather(first, second)
+ assert a == b and len(calls) == 1
+ assert service.store.load().sources[0].state.status == "standby"
+
+
+async def test_flag_off_retains_the_released_frozen_read_and_chain(tmp_path, monkeypatch):
+ service = owner(tmp_path, ("exa",), web={"prefer_native": False})
+ monkeypatch.setattr(hosted_tools, "SEARCH_SERVICES_ACTIVE", False)
+ calls = answers(monkeypatch, service, wire())
+ frozen = service.freeze_turn_hosted_tools(service.store.load())
+ assert getattr(frozen, "prefer_native", None) is None and frozen.executors["web_search"] == ()
+ assert _web(service)["executor_candidates"] == [] and "service_vendors" not in _web(service)
+ answer = await run(service, turn=frozen)
+ assert not calls and "attempts" not in answer["record"]
+ assert "Add an API key" in answer["record"]["error"]
+
+
[email protected]("first", ["unreadable", "unknown", "model"])
+async def test_mixed_chain_keeps_every_attempts_cost_even_when_the_last_failed_before_send(tmp_path, monkeypatch, first):
+ """MH-SEARCH-SERVICES: existing model/reader tests cannot generate a mixed producer chain."""
+ from config.v2_config import ModelHubHostedToolConfig
+ from tests.test_model_hub_hosted_executor import BILLED, WEB_CALL, _event, _responses
+ from tests.test_model_hub_l3 import LiveInvokeHandle, RawOutcomeKind, _outcome
+ from tests.test_model_hub_vibey_consumer import _vibey_service
+
+ if first == "model":
+ config = _config()
+ model = next(s for s in config.sources if s.id == MODEL)
+ handle = LiveInvokeHandle(
+ _outcome(RawOutcomeKind.HTTP_ERROR, source_id=MODEL, status=200, code="server_error", stream_started=True, usage=BILLED),
+ (*_responses(WEB_CALL)[:-1], _event({"type": "response.failed", "response": {
+ "status": "failed", "usage": {"input_tokens": 900, "output_tokens": 40, "cost_in_usd_ticks": 1_234_000_000},
+ }})),
+ )
+ service = _vibey_service(tmp_path, [model], handles=[handle])
+ service.store.config.sources.append(next(s for s in config.sources if s.id == EXA))
+ service.store.config.hosted_tools["web_search"] = ModelHubHostedToolConfig(
+ executor_order=(MODEL, EXA), executor_order_kinds={MODEL: "model", EXA: "service"},
+ )
+ calls = answers(monkeypatch, service, wire(None, {}, error="connection"), sent=False)
+ expected = [MODEL, EXA]
+ else:
+ service = owner(tmp_path, ("exa", "tavily"))
+ calls = []
+
+ async def search(source_id, *args, on_sent):
+ calls.append(source_id)
+ if source_id == EXA:
+ await on_sent()
+ return wire(200, {}) if first == "unreadable" else wire(None, {}, error="connection")
+ return wire(None, {}, error="connection")
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ expected = [EXA, TAVILY]
+ result = await run(service)
+ attempts = result["record"]["attempts"]
+ assert [row["source_id"] for row in attempts] == expected
+ assert attempts[-1]["cost"] == {"basis": "list", "usd": 0}
+ assert len(calls) == (1 if first == "model" else 2)
+ earlier = result["execution"]["failed_attempts"][0]
+ assert earlier["source_id"] == expected[0]
+ assert earlier.get("cost") == attempts[0].get("cost")
+ if first == "unknown":
+ assert "cost" not in attempts[0]
+ else:
+ assert attempts[0]["cost"]["usd"] > 0
+ assert result["execution"]["executor_source_id"] == expected[-1]
+ _hosted_result("web_search", result)
+
+
[email protected]("mutation", ["replace", "remove", "later_attempt"])
+async def test_free_check_cannot_repair_a_replaced_removed_or_newer_settlement(tmp_path, monkeypatch, mutation):
+ """The check is asynchronous: joining tests alone cannot expose stale repairs."""
+ from core.handlers.model_hub.service import ModelHubError
+
+ service = owner(tmp_path, ("tavily",))
+ source = service.store.load().sources[0]
+ blocker = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.spend_limit_reached")
+ source.state = blocker
+ entered, finish = asyncio.Event(), asyncio.Event()
+
+ async def check(*args):
+ entered.set()
+ await finish.wait()
+ return SearchCredentialCheck("pass")
+
+ monkeypatch.setattr(service.adapter, "check_search_credential", check)
+ task = asyncio.create_task(service.reenable_search_source(source.id))
+ await entered.wait()
+ if mutation == "later_attempt":
+ service._reserve_settlement_generation(source.id)
+ else:
+ config = service._clone_config(service.store.load())
+ if mutation == "replace":
+ config.sources[0].credential_generation = "vp_" + "3" * 32
+ else:
+ config.sources = []
+ await service._save_config(config)
+ finish.set()
+ if mutation == "remove":
+ with pytest.raises(ModelHubError, match="source_not_found"):
+ await task
+ else:
+ await task
+ assert service.store.load().sources[0].state == blocker
+
+
[email protected]("cancel_phase", ["before_send", "after_send", "received_200"])
+async def test_trial_stop_releases_only_the_reservation_and_restart_fails_closed(tmp_path, monkeypatch, cancel_phase):
+ """A stopped trial has different admission/billing facts from an ordinary stopped search."""
+ service = owner(tmp_path)
+ source = service.store.load().sources[0]
+ source.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.balance_exhausted")
+ await service.reenable_search_source(source.id)
+ entered = asyncio.Event()
+
+ async def search(*args, on_sent):
+ if cancel_phase != "before_send":
+ await on_sent()
+ entered.set()
+ try:
+ await asyncio.Future()
+ except asyncio.CancelledError:
+ return SearchResponse(200 if cancel_phase == "received_200" else None, {}, None, "cancelled")
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ task = asyncio.create_task(run(service))
+ await entered.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert service._service_cooldowns.until(service.store.load().sources[0], "exa/search", NOW) is None
+ assert service.search_reenable_trial_pending(source.id) is (cancel_phase == "before_send")
+ assert service.store.load().sources[0].state.status == ("standby" if cancel_phase == "received_200" else "needs_action")
+ saved = service.store.load().to_payload()
+ fresh = owner(tmp_path / "restart")
+ fresh.store.config = ModelHubConfig.from_payload(saved)
+ assert not fresh.search_reenable_trial_pending(source.id)
+ assert _web(fresh)["executor_candidates"][0]["cooldown_until"] is None
+ if cancel_phase != "received_200":
+ assert (await run(fresh))["record"]["attempts"][0]["skipped"] == "blocked"
+
+
+async def test_attempt_deadlines_share_one_chain_budget_and_preserve_timeout_billing(tmp_path, monkeypatch):
+ """A per-attempt timeout must not reset the chain deadline or lose a sent request."""
+ from core.handlers.model_hub import search_chain
+
+ service = owner(tmp_path, ("deepseek", "exa", "tavily"), web={"service_order": [EXA, TAVILY]})
+ monkeypatch.setattr(search_chain, "ATTEMPT_SECONDS", .2)
+ monkeypatch.setattr(search_chain, "call_timeout", lambda tool: .3)
+ calls = []
+
+ async def search(source_id, *args, on_sent):
+ await on_sent()
+ calls.append(source_id)
+ await asyncio.Future()
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ result = await asyncio.wait_for(run(service), timeout=1)
+ assert calls == [EXA, TAVILY]
+ assert len(result["record"]["attempts"]) == 2
+ assert all("cost" not in attempt for attempt in result["record"]["attempts"])
+ assert sum(row["requests"] for row in summary(service)["services"]) == 2
+
+
[email protected]("failure", [401, 503])
[email protected]("newer", ["model", "retry"])
+async def test_health_and_cooldown_fences_each_protect_only_their_own_state(tmp_path, monkeypatch, failure, newer):
+ """A shared credential does not make model settlement the owner of service cooldown."""
+ service = owner(tmp_path, ("deepseek",))
+ source = service.store.load().sources[0]
+ entered, finish = asyncio.Event(), asyncio.Event()
+
+ async def search(*args, on_sent):
+ await on_sent()
+ entered.set()
+ await finish.wait()
+ return wire(failure)
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ task = asyncio.create_task(run(service))
+ await entered.wait()
+ if newer == "model":
+ service._reserve_settlement_generation(source.id)
+ else:
+ await service.clear_service_cooldown(source.id)
+ finish.set()
+ result = await task
+ current = service.store.load().sources[0]
+ assert (current.state.status == "needs_action") == (failure == 401 and newer == "retry")
+ assert (service._service_cooldowns.until(current, "deepseek/search", NOW) is not None) == (failure == 503 and newer == "model")
+ assert result["record"]["attempts"][0].get("superseded", False) == (
+ (failure == 401 and newer == "model") or (failure == 503 and newer == "retry")
+ )
+
+
+async def test_prefer_native_off_flows_through_the_hop_to_function_declaration_and_synthetic_history(tmp_path):
+ """C-6 consumer fixture: facts alone miss a declaration/replay integration regression."""
+ from core.agent_core.ai.provider import ModelRequest
+ from core.agent_core.tools.hosted import hosted_tool_spec
+ from core.handlers.model_hub.turn_gateway import ModelHubTurnGateway
+ from modules.agents.model_hub import ModelHubRuntimeRouter
+ from modules.agents.vibey.models import selection_from_hop
+ from tests.agent_core.ai._wire import build_wire_request
+ from tests.agent_core.ai.test_hosted_transform import ANSWER, SEARCH, SEARCH_TEXT, _follow_up, _response
+ from tests.test_model_hub_vibey_consumer import _vibey_service, _validate
+
+ config = _config({"prefer_native": False})
+ service = _vibey_service(tmp_path, [next(s for s in config.sources if s.id == MODEL)])
+ service.store.config.hosted_tools = config.hosted_tools
+ gateway = ModelHubTurnGateway(service)
+ router = ModelHubRuntimeRouter(service=service, turn_gateway=gateway)
+ try:
+ hop = await router.resolve_hop("menu-alias", process_scope="vibey:services", turn_id="turn-search-services")
+ _validate("hop-resolution.schema.json", hop)
+ selection = selection_from_hop(hop)
+ assert selection.endpoint.hosted_tools["web_search"].mode == "proxy"
+ request = ModelRequest(endpoint=selection.endpoint, system="system", messages=(_response(SEARCH, ANSWER), _follow_up()),
+ tools=(hosted_tool_spec("web_search"),), max_tokens=256)
+ sent = (await build_wire_request(request, gateway=True)).body
+ assert sent["tools"][0]["type"] == "function" and sent["tools"][0]["name"] == "web_search"
+ assert not any(item.get("type") == "web_search_call" for item in sent["input"])
+ assert next(item["output"] for item in sent["input"] if item.get("type") == "function_call_output") == SEARCH_TEXT
+ await service.set_hosted_tool("web_search", {"prefer_native": True})
+ again = await router.resolve_hop("menu-alias", process_scope="vibey:services", turn_id="turn-search-services")
+ assert again["hosted_tools"]["web_search"] == hop["hosted_tools"]["web_search"]
+ finally:
+ await gateway.close()
+
+
[email protected]("scenario", ["retarget", "retired", "new_catalog", "opt_in"])
+def test_read_time_role_changes_never_duplicate_sources_or_rewrite_config(tmp_path, monkeypatch, scenario):
+ """New capabilities and official retargets use the same saved-role placement rule."""
+ from dataclasses import replace
+ from config.v2_config import ModelHubHostedToolConfig, ModelHubSearchServiceSettings
+ from vibe.model_hub_runtime import api_key_vendors
+
+ service = owner(tmp_path, ("deepseek", "exa"), model=True,
+ web={"executor_order": [MODEL, DEEPSEEK], "executor_order_kinds": {MODEL: "model", DEEPSEEK: "model"}})
+ config = service.store.load()
+ deepseek = next(s for s in config.sources if s.id == DEEPSEEK)
+ if scenario == "retarget":
+ deepseek.base_url = "https://relay.example.test/v1"
+ assert DEEPSEEK not in _web(service)["effective_order"]
+ deepseek.base_url = None
+ elif scenario == "retired":
+ next(s for s in config.sources if s.id == EXA).vendor = "retired-search-vendor"
+ else:
+ original = api_key_vendors.api_key_vendor_entry
+ vendor = original("xai")
+ search = copy.deepcopy(original("deepseek").search)
+ search.update(service_id="xai/search", auto_enroll=False)
+ monkeypatch.setattr(api_key_vendors, "api_key_vendor_entry", lambda key: replace(vendor, search=search) if key == "xai" else original(key))
+ if scenario == "opt_in":
+ config.hosted_tools["web_search"] = ModelHubHostedToolConfig(
+ executor_order=(MODEL,), executor_order_kinds={MODEL: "model"},
+ services={MODEL: ModelHubSearchServiceSettings(enabled=True)},
+ )
+ before = copy.deepcopy(config.to_payload())
+ rows = _web(service)["executor_candidates"]
+ ids = [row["source_id"] for row in rows]
+ assert len(ids) == len(set(ids))
+ if scenario == "retired":
+ assert ids == [DEEPSEEK, MODEL]
+ elif scenario == "opt_in":
+ assert ids == [EXA, DEEPSEEK, MODEL] and all(row["kind"] == "service" for row in rows)
+ else:
+ assert ids == [EXA, DEEPSEEK, MODEL] and rows[-1]["kind"] == "model"
+ assert config.to_payload() == before
+
+
[email protected]("phase", ["concurrent", "recovered", "rearmed"])
+async def test_connect_holds_no_mutation_lock_and_only_the_first_ready_trial_sends(tmp_path, monkeypatch, phase):
+ """Connection latency cannot stall other sessions or let a losing contender fence the winner."""
+ service = owner(tmp_path)
+ source = service.store.load().sources[0]
+ source.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.balance_exhausted")
+ await service.reenable_search_source(source.id)
+ connecting = [asyncio.Event(), asyncio.Event()]
+ connect = [asyncio.Event(), asyncio.Event()]
+ sent, finish = asyncio.Event(), asyncio.Event()
+ connections, sends = [], []
+
+ async def search(*args, on_sent):
+ index = len(connections)
+ connections.append(index)
+ connecting[index].set()
+ await connect[index].wait()
+ await on_sent()
+ sends.append(index)
+ sent.set()
+ await finish.wait()
+ return wire(400 if phase == "rearmed" and index == 0 else 401 if phase == "recovered" and index == 1 else 200)
+
+ async def another_session():
+ async with service._mutation_lock:
+ return True
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ first = asyncio.create_task(run(service))
+ await connecting[0].wait()
+ assert await asyncio.wait_for(another_session(), timeout=.2)
+ second = asyncio.create_task(run(service))
+ await asyncio.wait_for(connecting[1].wait(), timeout=.2)
+ connect[0].set()
+ await sent.wait()
+ if phase != "concurrent":
+ finish.set()
+ await first
+ connect[1].set()
+ loser = await asyncio.wait_for(second, timeout=.2)
+ if phase == "concurrent":
+ assert loser["record"]["attempts"][0]["skipped"] == "blocked"
+ else:
+ assert loser["record"]["attempts"][0]["outcome"] == ("failed" if phase == "recovered" else "completed")
+ assert not loser["record"]["attempts"][0].get("superseded")
+ finish.set()
+ assert (await first)["record"]["status"] == ("failed" if phase == "rearmed" else "completed")
+ assert sends == ([0] if phase == "concurrent" else [0, 1])
+ assert summary(service)["services"][0]["requests"] == len(sends)
+ assert service.store.load().sources[0].state.status == ("needs_action" if phase == "recovered" else "standby")
+
+
+async def test_stop_during_timeout_teardown_never_runs_the_next_paid_candidate(tmp_path, monkeypatch):
+ """The finite adapter drain may outlive its timeout; a later Stop still owns the call."""
+ from core.handlers.model_hub import search_chain
+
+ service = owner(tmp_path, ("exa", "tavily"))
+ monkeypatch.setattr(search_chain, "ATTEMPT_SECONDS", .1)
+ draining, finish = asyncio.Event(), asyncio.Event()
+ calls = []
+
+ async def search(source_id, *args, on_sent):
+ await on_sent()
+ calls.append(source_id)
+ if source_id == TAVILY:
+ return wire()
+ try:
+ await asyncio.Future()
+ except asyncio.CancelledError:
+ draining.set()
+ await finish.wait()
+ return SearchResponse(None, {}, None, "cancelled")
+
+ monkeypatch.setattr(service.adapter, "search", search, raising=False)
+ task = asyncio.create_task(run(service))
+ await asyncio.wait_for(draining.wait(), timeout=2)
+ task.cancel()
+ finish.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ assert calls == [EXA]
+ assert summary(service)["services"][0]["uncertain_requests"] == 1
+ assert service._service_cooldowns.until(service.store.load().sources[0], "exa/search", NOW) is None
+
+
[email protected]("mixed", [False, True])
+async def test_model_executor_retains_the_chain_budget_not_the_service_attempt_limit(tmp_path, monkeypatch, mixed):
+ """A native model search is not cut short and paid for again just because services are active."""
+ from config.v2_config import ModelHubHostedToolConfig
+ from core.handlers.model_hub import search_chain
+ from tests.test_model_hub_hosted_executor import WEB_ANSWER, WEB_CALL, _responses
+ from tests.test_model_hub_l3 import LiveInvokeHandle, RawOutcomeKind, _outcome
+ from tests.test_model_hub_vibey_consumer import _vibey_service
+
+ class SlowModel(LiveInvokeHandle):
+ @staticmethod
+ async def _iterate(chunks):
+ await asyncio.sleep(.04)
+ for chunk in chunks:
+ yield chunk
+
+ config = _config()
+ service = _vibey_service(tmp_path, [next(s for s in config.sources if s.id == MODEL)], handles=[
+ SlowModel(_outcome(RawOutcomeKind.SUCCESS, source_id=MODEL), _responses(WEB_CALL, WEB_ANSWER)),
+ ])
+ if mixed:
+ service.store.config.sources.append(next(s for s in config.sources if s.id == EXA))
+ service.store.config.hosted_tools["web_search"] = ModelHubHostedToolConfig(
+ executor_order=(MODEL, EXA) if mixed else (MODEL,),
+ executor_order_kinds={MODEL: "model", EXA: "service"} if mixed else {MODEL: "model"},
+ )
+ monkeypatch.setattr(search_chain, "ATTEMPT_SECONDS", .01)
+ monkeypatch.setattr(search_chain, "call_timeout", lambda tool: 1)
+ calls = answers(monkeypatch, service, wire())
+ result = await run(service)
+ assert not calls and result["record"]["status"] == "completed"
+ assert result["execution"]["executor_source_id"] == MODEL
+ assert ("attempts" in result["record"]) is mixed
+
+
[email protected]("detail", ["Query is invalid", {"error": "Query is invalid"}, [{"msg": "Field required", "input": "do not echo me"}]])
+async def test_tavily_validation_error_keeps_bounded_vendor_text_but_not_echoed_inputs(tmp_path, monkeypatch, detail):
+ service = owner(tmp_path, ("tavily",))
+ answers(monkeypatch, service, wire(422, {"detail": detail}))
+ result = await run(service)
+ assert result["record"]["error_code"] == "service_refused"
+ assert ("Field required" if isinstance(detail, list) else "Query is invalid") in result["record"]["error"]
+ assert "do not echo me" not in result["record"]["error"]
+
+
[email protected]("enabled", [False, True])
+def test_retry_http_client_rpc_clears_only_the_service_fence_with_plain_success(tmp_path, monkeypatch, enabled):
+ """The existing route inventory checks registration, not forwarding or controller-owned state."""
+ from core.handlers.model_hub.rpc import dispatch_model_hub_rpc
+ from tests.test_model_hub_api import app, csrf_headers, save_config
+ from vibe import model_hub_client, ui_server
+
+ save_config(tmp_path / "home")
+ service = owner(tmp_path)
+ monkeypatch.setattr(hosted_tools, "SEARCH_SERVICES_ACTIVE", enabled)
+ source = service.store.load().sources[0]
+ source.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.balance_exhausted")
+ generation = service._service_cooldowns.advance(source, "exa/search")
+ calls = []
+
+ async def rpc(operation, payload):
+ calls.append((operation, payload))
+ return await dispatch_model_hub_rpc(service, operation, payload)
+
+ monkeypatch.setattr(model_hub_client, "_rpc", rpc)
+ monkeypatch.setattr(ui_server, "_model_hub_service", model_hub_client.ModelHubRemoteService)
+ client = app.test_client()
+ response = client.post(f"/api/models/hosted-tools/web_search/services/{EXA}/retry", json={},
+ headers=csrf_headers(client, "http://127.0.0.1:15131"))
+ assert response.status_code == 200
+ assert response.get_json() == {"ok": True, "contract_version": 19}
+ assert calls == [("clear_service_cooldown", {"source_id": EXA, "service_id": None})]
+ assert not service._service_cooldowns.current(source, "exa/search", generation)
+ assert service.store.load().sources[0].state == source.state
+ assert summary(service)["services"] == []
+
+
+async def test_blocked_model_executor_keeps_its_own_remedy_beside_a_disabled_service(tmp_path):
+ """The model role must carry its health remedy, not a tool-only re-enable instruction."""
+ service = owner(tmp_path, ("exa",), model=True, web={"services": {EXA: {"enabled": False}}})
+ model = next(s for s in service.store.load().sources if s.id == MODEL)
+ model.state = ModelHubSourceStateConfig(status="error", detail_key="models.source.error.unclassified")
+ result = await run(service)
+ assert result["record"]["error_code"] == "search_sources_blocked"
+ assert result["record"]["attempts"] == [
+ {"source_id": MODEL, "label": model.display_name, "kind": "model", "outcome": "skipped",
+ "skipped": "blocked", "needs_action": "models.source.error.unclassified"},
+ {"source_id": EXA, "label": "exa", "kind": "service", "outcome": "skipped", "skipped": "disabled"},
+ ]
+ assert "execution" not in result
+ _hosted_result("web_search", result)
+
+
+async def test_trial_reservation_is_released_even_when_health_persistence_fails(tmp_path, monkeypatch):
+ """A failed local write keeps the persisted blocker, not an unreleasable in-flight trial."""
+ service = owner(tmp_path)
+ source = service.store.load().sources[0]
+ source.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.balance_exhausted")
+ await service.reenable_search_source(source.id)
+ answers(monkeypatch, service, wire())
+
+ async def disk_unavailable(*args, **kwargs):
+ raise OSError("test-owned persistence failure")
+
+ monkeypatch.setattr(service, "_save_runtime_config", disk_unavailable)
+ with pytest.raises(OSError, match="test-owned persistence failure"):
+ await run(service)
+ assert not service.search_reenable_trial_pending(source.id)
+ assert service.store.load().sources[0].state.status == "needs_action"
+ assert summary(service)["services"][0]["requests"] == 1
+
+
[email protected]("trial", [False, True])
+async def test_service_admission_and_settlement_never_reload_config_on_the_controller_loop(tmp_path, monkeypatch, trial):
+ """A generation helper's hidden store read must not bypass the off-loop snapshots."""
+ service = owner(tmp_path)
+ source = service.store.load().sources[0]
+ if trial:
+ source.state = ModelHubSourceStateConfig(status="needs_action", detail_key="models.source.needs_action.balance_exhausted")
+ turn = service.freeze_turn_hosted_tools(service.store.load())
+ load = service.store.load
+ threads = []
+
+ def observed():
+ threads.append(threading.get_ident())
+ return load()
+
+ monkeypatch.setattr(service.store, "load", observed)
+ answers(monkeypatch, service, wire())
+ if trial:
+ await service.reenable_search_source(source.id)
+ assert (await run(service, turn=turn))["record"]["status"] == "completed"
+ assert threads and threading.get_ident() not in threads
diff --git a/tests/test_model_hub_search_transport.py b/tests/test_model_hub_search_transport.py
new file mode 100644
index 000000000..aac054cea
--- /dev/null
+++ b/tests/test_model_hub_search_transport.py
@@ -0,0 +1,93 @@
+"""Search final admission owns a connected transport before it can refuse.
+
+Fake-session custody tests cannot detect an orphaned socket. This local-only
+real-aiohttp probe verifies EOF on refused/cancelled admission, with no request
+bytes sent and no external host or credential store contacted.
+"""
+
+import asyncio
+
+import aiohttp
+import pytest
+
+from vibe.model_hub_runtime import adapter as runtime_adapter
+
+
[email protected]("admission", ["refused", "cancelled", "stopped"])
+async def test_search_rejected_final_admission_closes_the_real_connected_socket(monkeypatch, admission):
+ accepted, closed, checking = asyncio.Event(), asyncio.Event(), asyncio.Event()
+ received = []
+ peers, handlers = [], []
+
+ async def peer(reader, writer):
+ handlers.append(asyncio.current_task())
+ peers.append(writer)
+ accepted.set()
+ try:
+ received.append(await reader.read(1))
+ finally:
+ writer.close()
+ await writer.wait_closed()
+ closed.set()
+
+ server = await asyncio.start_server(peer, "127.0.0.1", 0)
+ port = server.sockets[0].getsockname()[1]
+ real_session = aiohttp.ClientSession
+
+ class LocalSession:
+ def __init__(self, **kwargs):
+ self.session = real_session(**kwargs)
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, *args):
+ await self.session.close()
+
+ def request(self, method, url, **kwargs):
+ # The production endpoint has already passed catalog HTTPS/host
+ # validation. Replace egress only, retaining the real connector and
+ # ClientRequest lifecycle without needing a local test CA.
+ assert url == "https://api.tavily.com/search"
+ return self.session.request(method, f"http://127.0.0.1:{port}/search", **kwargs)
+
+ class Store:
+ def read_api_key(self, _ref):
+ return "test-only-search-key"
+
+ def credential_metadata(self, _ref):
+ return {"vendor": "tavily"}
+
+ async def on_sent():
+ await accepted.wait()
+ checking.set()
+ if admission == "refused":
+ raise ValueError("final admission refused")
+ if admission == "cancelled":
+ raise asyncio.CancelledError
+ await asyncio.Future()
+
+ monkeypatch.setattr(runtime_adapter.aiohttp, "ClientSession", LocalSession)
+ adapter = runtime_adapter.CLIProxyEngineAdapter(supervisor=object(), state_store=Store())
+ task = asyncio.create_task(adapter.search("src_test", "tavily", "tavily/search", "cred_test", {"query": "test"}, on_sent=on_sent))
+ try:
+ await asyncio.wait_for(checking.wait(), timeout=2)
+ if admission == "stopped":
+ task.cancel()
+ response = await asyncio.wait_for(task, timeout=2)
+ assert response.http_status is None and response.on_sent_fired is False
+ assert response.error == ("connection" if admission == "refused" else "cancelled")
+ await asyncio.wait_for(closed.wait(), timeout=1)
+ assert received == [b""]
+ finally:
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ server.close()
+ for writer in peers:
+ writer.transport.abort()
+ for handler in handlers:
+ handler.cancel()
+ await asyncio.wait_for(asyncio.gather(*handlers, return_exceptions=True), timeout=1)
+ await asyncio.wait_for(server.wait_closed(), timeout=1)
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 89572e6df..ef63f53cb 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -539,9 +539,11 @@ def test_g3_settlement_returns_are_consumed() -> None:
def test_settlement_generations_are_reserved_only_at_attempt_start() -> None:
+ """Search re-enable is the one explicit non-attempt exception (model-hub.md settlement freshness)."""
allowed_owners = {
- SERVICE: {"_invoke_admitted"},
+ SERVICE: {"_invoke_admitted", "_reenable_search_service"},
ROUTER: {"resolve"},
+ ROOT / "core/handlers/model_hub/search_chain.py": {"invoke", "on_sent"},
}
for path, expected in allowed_owners.items():
tree = _tree(path)
diff --git a/vibe/authorization.py b/vibe/authorization.py
index 899263873..8d85fe02e 100644
--- a/vibe/authorization.py
+++ b/vibe/authorization.py
@@ -553,6 +553,7 @@ _MEMBER_HTTP_RULES = tuple(
("GET", r"^/api/models/hosted-tools$"),
("PUT", r"^/api/models/hosted-tools/[^/]+$"),
("POST", r"^/api/models/hosted-tools/[^/]+/clear$"),
+ ("POST", r"^/api/models/hosted-tools/web_search/services/[^/]+/retry$"),
("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/data/api_key_vendors.json b/vibe/data/api_key_vendors.json
index defd00d35..bb6747742 100644
--- a/vibe/data/api_key_vendors.json
+++ b/vibe/data/api_key_vendors.json
@@ -43,7 +43,7 @@
"results": "results",
"url": "url",
"title": "title",
- "snippet": "snippet",
+ "snippet": "summary",
"page_age": "date"
},
"limits": {
@@ -56,7 +56,7 @@
"usd_per_1k": 0.75,
"extra": [],
"as_of": "2026-10-19",
- "url": "https://api-docs.deepseek.com/guides/search-tool"
+ "url": "https://api-docs.deepseek.com/guides/search"
},
"free_check": {
"method": "GET",
@@ -66,6 +66,8 @@
"invalid_statuses": [401]
},
"service_refused_statuses": [400],
+ "outcomes": {"credential": [401], "balance": [402], "limit": []},
+ "billing": {"nonempty_only": true, "unbilled_errors": ["timeout"]},
"auto_enroll": true,
"tool_only": false
}
@@ -138,7 +140,8 @@
"request": {
"method": "POST",
"query": "query",
- "results": "max_results"
+ "results": "max_results",
+ "defaults": {"search_depth": "basic", "include_answer": false}
},
"result": {
"results": "results",
@@ -173,7 +176,9 @@
"balance": null,
"invalid_statuses": [401]
},
- "service_refused_statuses": [400],
+ "service_refused_statuses": [400, 422],
+ "outcomes": {"credential": [401], "balance": [402], "limit": [432, 433]},
+ "billing": {"nonempty_only": false, "unbilled_errors": []},
"tool_only": true
}
},
@@ -190,7 +195,8 @@
"method": "POST",
"query": "query",
"results": "numResults",
- "highlights": "contents.highlights"
+ "highlights": "contents.highlights",
+ "defaults": {"type": "auto"}
},
"result": {
"results": "results",
@@ -214,6 +220,16 @@
},
"free_check": null,
"service_refused_statuses": [400],
+ "outcomes": {
+ "credential": [401], "balance": [402], "limit": [],
+ "tag_overrides": [
+ {"status": 402, "tag": "API_KEY_BUDGET_EXCEEDED", "code": "service_limit"},
+ {"status": 402, "tag": "TEAM_BUDGET_EXCEEDED", "code": "service_limit"},
+ {"status": 403, "tag": "PROHIBITED_CONTENT", "code": "service_refused"},
+ {"status": 403, "tag": "CONTENT_FILTER_ERROR", "code": "service_refused"}
+ ]
+ },
+ "billing": {"nonempty_only": false, "unbilled_errors": []},
"tool_only": true
}
}
diff --git a/vibe/data/api_key_vendors.schema.json b/vibe/data/api_key_vendors.schema.json
index 1a71c2900..34dcd9003 100644
--- a/vibe/data/api_key_vendors.schema.json
+++ b/vibe/data/api_key_vendors.schema.json
@@ -3,6 +3,9 @@
"$id": "model-hub/api-key-vendors.schema.json",
"title": "Model Hub API-key vendor catalog",
"type": "array",
+ "definitions": {
+ "statuses": {"type": "array", "items": {"type": "integer", "minimum": 400, "maximum": 499}, "uniqueItems": true}
+ },
"items": {
"type": "object",
"required": ["id", "label", "official_base_url", "protocol"],
@@ -15,7 +18,7 @@
"models_dev_provider": {"type": ["string", "null"]},
"search": {
"type": ["object", "null"],
- "required": ["service_id", "endpoint", "auth", "request", "result", "limits", "price", "free_check", "service_refused_statuses", "tool_only"],
+ "required": ["service_id", "endpoint", "auth", "request", "result", "limits", "price", "free_check", "service_refused_statuses", "outcomes", "billing", "tool_only"],
"allOf": [
{
"if": {"type": "object", "required": ["tool_only"], "properties": {"tool_only": {"const": false}}},
@@ -107,6 +110,31 @@
}
}
},
+ "outcomes": {
+ "type": "object", "required": ["credential", "balance", "limit"], "additionalProperties": false,
+ "properties": {
+ "credential": {"$ref": "#/definitions/statuses"},
+ "balance": {"$ref": "#/definitions/statuses"},
+ "limit": {"$ref": "#/definitions/statuses"},
+ "tag_overrides": {
+ "type": "array", "items": {
+ "type": "object", "required": ["status", "tag", "code"], "additionalProperties": false,
+ "properties": {
+ "status": {"type": "integer", "minimum": 400, "maximum": 499},
+ "tag": {"type": "string", "minLength": 1},
+ "code": {"enum": ["service_limit", "service_refused"]}
+ }
+ }
+ }
+ }
+ },
+ "billing": {
+ "type": "object", "required": ["nonempty_only", "unbilled_errors"], "additionalProperties": false,
+ "properties": {
+ "nonempty_only": {"type": "boolean"},
+ "unbilled_errors": {"type": "array", "items": {"enum": ["timeout"]}, "uniqueItems": true}
+ }
+ },
"service_refused_statuses": {
"type": "array",
"items": {"type": "integer", "minimum": 400, "maximum": 499},
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index ff08c59d0..192c338c5 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -1190,6 +1190,8 @@
"web_search": {"one": "No Source can run web search right now. Add an API key from {vendors} as a Source in Models › Sources & gateway; a key stored in Vaults is not used for this.", "several": "No Source can run web search right now. Add an API key from one of {vendors} as a Source in Models › Sources & gateway; a key stored in Vaults is not used for this.", "refused": "{sources} refused web search, so no Source can run it right now. Clear the refusal in Models › Tools to try again."},
"x_search": {"one": "No Source can run X search right now. Add an API key from {vendors} as a Source in Models › Sources & gateway; a key stored in Vaults is not used for this.", "several": "No Source can run X search right now. Add an API key from one of {vendors} as a Source in Models › Sources & gateway; a key stored in Vaults is not used for this.", "refused": "{sources} refused X search, so no Source can run it right now. Clear the refusal in Models › Tools to try again."}
},
+ "noSearchSource": "No Source can run web search. Add a search service in Models › Tools or an API key from a vendor that offers web search in Models › Providers.",
+ "queryLimit": "The query exceeds {limit} characters. Shorten it and try again.",
"listSeparator": ", ",
"providerRefused": "The executor's provider refused the call ({detail}).",
"providerUnavailable": "The executor's provider is unavailable right now ({detail}). Try again later.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 682633738..ea21d260b 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -1190,6 +1190,8 @@
"web_search": {"one": "当前没有能运行网页搜索的供应商。请在 模型 › 供应商与路由 中把 {vendors} 的 API Key 添加为供应商;存在 Vaults 里的密钥不会用于这里。", "several": "当前没有能运行网页搜索的供应商。请在 模型 › 供应商与路由 中把 {vendors} 其中一家的 API Key 添加为供应商;存在 Vaults 里的密钥不会用于这里。", "refused": "{sources} 拒绝了网页搜索,当前没有能运行它的供应商。在 模型 › 工具 中清除拒绝记录后会再试。"},
"x_search": {"one": "当前没有能运行 X 搜索的供应商。请在 模型 › 供应商与路由 中把 {vendors} 的 API Key 添加为供应商;存在 Vaults 里的密钥不会用于这里。", "several": "当前没有能运行 X 搜索的供应商。请在 模型 › 供应商与路由 中把 {vendors} 其中一家的 API Key 添加为供应商;存在 Vaults 里的密钥不会用于这里。", "refused": "{sources} 拒绝了 X 搜索,当前没有能运行它的供应商。在 模型 › 工具 中清除拒绝记录后会再试。"}
},
+ "noSearchSource": "目前没有供应商可以执行网页搜索。请在 模型 › 工具 中添加搜索服务,或在 模型 › 供应商 中添加提供网页搜索的厂商 API Key。",
+ "queryLimit": "搜索词超过 {limit} 个字符,请缩短后重试。",
"listSeparator": "、",
"providerRefused": "执行方的供应商拒绝了此次调用({detail})。",
"providerUnavailable": "执行方的供应商暂时不可用({detail}),请稍后重试。",
diff --git a/vibe/model_hub_client.py b/vibe/model_hub_client.py
index ed6cdb9e5..f33fbde1f 100644
--- a/vibe/model_hub_client.py
+++ b/vibe/model_hub_client.py
@@ -310,6 +310,9 @@ class ModelHubRemoteService:
async def clear_hosted_refusals(self, tool: str, target: object) -> dict:
return await _rpc("clear_hosted_refusals", {"tool": tool, "target": target})
+ async def clear_service_cooldown(self, source_id: str, service_id: str | None = None) -> dict:
+ return await _rpc("clear_service_cooldown", {"source_id": source_id, "service_id": service_id})
+
async def clear_source_evidence(self, source_id: str, target: object) -> dict:
return await _rpc("clear_source_evidence", {"source_id": source_id, "target": target})
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index 126b22f63..b3d826e9e 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import email.utils
+import inspect
import json
import logging
import math
@@ -13,7 +14,7 @@ import uuid
from dataclasses import dataclass, field, replace
from datetime import datetime, timedelta, timezone
from enum import Enum
-from typing import Any, Callable, Literal, Mapping, Sequence, TypeVar
+from typing import Any, Awaitable, Callable, Literal, Mapping, Sequence, TypeVar
import aiohttp
@@ -2061,7 +2062,7 @@ class CLIProxyEngineAdapter:
payload: Mapping[str, Any] | None = None,
timeout_total: float = _SEARCH_TIMEOUT_SECONDS,
connect_timeout: float | None = None,
- on_sent: Callable[[], None] | None = None,
+ on_sent: Callable[[], Awaitable[None] | None] | None = None,
) -> SearchResponse:
"""Call only the immutable catalog endpoint for one search operation."""
vendor, service = self._search_catalog_parts(catalog)
@@ -2100,26 +2101,28 @@ class CLIProxyEngineAdapter:
else:
headers["Authorization"] = f"Bearer {key}"
timeout = aiohttp.ClientTimeout(total=timeout_total, connect=connect_timeout)
- trace = aiohttp.TraceConfig()
callback_called = False
response_status: int | None = None
response_headers: dict[str, str] = {}
response_received_at: datetime | None = None
- async def request_connection_ready(*_args: Any, **_kwargs: Any) -> None:
- nonlocal callback_called
- if callback_called or on_sent is None:
- return
- callback_called = True
- on_sent()
-
- trace.on_connection_create_end.append(request_connection_ready)
- trace.on_connection_reuseconn.append(request_connection_ready)
+ class SearchRequest(aiohttp.ClientRequest):
+ async def send(self, conn):
+ nonlocal callback_called
+ # At send(), aiohttp owns the Connection and closes it if
+ # admission fails. Raising from connection-create trace hooks
+ # can instead orphan the not-yet-owned transport.
+ if not callback_called and on_sent is not None:
+ admission = on_sent()
+ if inspect.isawaitable(admission):
+ await admission
+ callback_called = True
+ return await super().send(conn)
try:
async with aiohttp.ClientSession(
timeout=timeout,
trust_env=False,
- trace_configs=[trace],
+ request_class=SearchRequest,
) as session:
async with session.request(
method,
@@ -2217,26 +2220,30 @@ class CLIProxyEngineAdapter:
return SearchCredentialCheck("unknown")
if response.http_status != 200 or response.body is None:
return SearchCredentialCheck("unknown")
- try:
- body = json.loads(response.body.decode("utf-8"))
- except (UnicodeDecodeError, json.JSONDecodeError):
- return SearchCredentialCheck("unknown")
- limit_rule = check.get("limit")
- if isinstance(limit_rule, Mapping):
- limit_outcome = _search_limit_outcome(body, limit_rule)
- if limit_outcome == "limit":
- return SearchCredentialCheck("limit")
- if limit_outcome == "unknown":
+ def decode() -> SearchCredentialCheck:
+ # The free check shares search's 8 MiB body bound, not the event loop.
+ try:
+ body = json.loads(response.body.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError, RecursionError):
return SearchCredentialCheck("unknown")
- passed = check.get("pass")
- balance = check.get("balance")
- if isinstance(passed, Mapping) and _search_check_matches(body, passed):
- return SearchCredentialCheck("pass")
- if isinstance(balance, Mapping) and _search_check_matches(body, balance):
- return SearchCredentialCheck("balance")
- if balance is None and isinstance(passed, Mapping) and passed.get("status") == 200:
- return SearchCredentialCheck("pass")
- return SearchCredentialCheck("unknown")
+ limit_rule = check.get("limit")
+ if isinstance(limit_rule, Mapping):
+ limit_outcome = _search_limit_outcome(body, limit_rule)
+ if limit_outcome == "limit":
+ return SearchCredentialCheck("limit")
+ if limit_outcome == "unknown":
+ return SearchCredentialCheck("unknown")
+ passed = check.get("pass")
+ balance = check.get("balance")
+ if isinstance(passed, Mapping) and _search_check_matches(body, passed):
+ return SearchCredentialCheck("pass")
+ if isinstance(balance, Mapping) and _search_check_matches(body, balance):
+ return SearchCredentialCheck("balance")
+ if balance is None and isinstance(passed, Mapping) and passed.get("status") == 200:
+ return SearchCredentialCheck("pass")
+ return SearchCredentialCheck("unknown")
+
+ return await asyncio.to_thread(decode)
async def search(
self,
@@ -2246,7 +2253,7 @@ class CLIProxyEngineAdapter:
credential_ref: str,
request: Mapping[str, Any],
*,
- on_sent: Callable[[], None] | None = None,
+ on_sent: Callable[[], Awaitable[None] | None] | None = None,
) -> SearchResponse:
service = search_service(vendor, "search" if vendor in {"tavily", "exa"} else "openai_chat")
if service is None or service.get("service_id") != service_id:
diff --git a/vibe/model_hub_runtime/api_key_vendors.py b/vibe/model_hub_runtime/api_key_vendors.py
index db223a984..41dee79dd 100644
--- a/vibe/model_hub_runtime/api_key_vendors.py
+++ b/vibe/model_hub_runtime/api_key_vendors.py
@@ -160,7 +160,7 @@ def _validate_search_catalog(item: object, *, protocol: str) -> dict[str, Any] |
return None
if not isinstance(item, dict):
raise ValueError("api-key vendor search catalog is invalid")
- required = {"service_id", "endpoint", "auth", "request", "result", "limits", "price", "free_check", "service_refused_statuses", "tool_only"}
+ required = {"service_id", "endpoint", "auth", "request", "result", "limits", "price", "free_check", "service_refused_statuses", "outcomes", "billing", "tool_only"}
if protocol != "search":
required.add("auto_enroll")
if set(item) != required:
@@ -202,6 +202,28 @@ def _validate_search_catalog(item: object, *, protocol: str) -> dict[str, Any] |
for status in item["service_refused_statuses"]
) or len(set(item["service_refused_statuses"])) != len(item["service_refused_statuses"]):
raise ValueError("api-key vendor search catalog refusal statuses are invalid")
+ outcomes, billing = item.get("outcomes"), item.get("billing")
+ if not isinstance(outcomes, dict) or set(outcomes) - {"credential", "balance", "limit", "tag_overrides"} or any(
+ not isinstance(statuses, list) or any(type(status) is not int or not 400 <= status < 500 for status in statuses)
+ or len(set(statuses)) != len(statuses) for statuses in (outcomes.get(key) for key in ("credential", "balance", "limit"))
+ ):
+ raise ValueError("api-key vendor search outcome statuses are invalid")
+ overrides = outcomes.get("tag_overrides", [])
+ if not isinstance(overrides, list) or any(
+ not isinstance(rule, dict) or set(rule) != {"status", "tag", "code"}
+ or type(rule["status"]) is not int or not 400 <= rule["status"] < 500
+ or not isinstance(rule["tag"], str) or not rule["tag"]
+ or rule["code"] not in {"service_limit", "service_refused"} for rule in overrides
+ ):
+ raise ValueError("api-key vendor search outcome tag overrides are invalid")
+ if (
+ not isinstance(billing, dict) or set(billing) != {"nonempty_only", "unbilled_errors"}
+ or not isinstance(billing["nonempty_only"], bool)
+ or not isinstance(billing["unbilled_errors"], list)
+ or any(error != "timeout" for error in billing["unbilled_errors"])
+ or len(set(billing["unbilled_errors"])) != len(billing["unbilled_errors"])
+ ):
+ raise ValueError("api-key vendor search billing rule is invalid")
free_check = item.get("free_check")
if free_check is not None:
if not isinstance(free_check, dict):
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 7ad758d0a..39d4682c2 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5207,6 +5207,22 @@ async def model_hub_hosted_tool_clear(tool: str, starlette_request: FastAPIReque
return await _dispatch_native_ui_request(starlette_request, handler)
[email protected]("/api/models/hosted-tools/web_search/services/{source_id}/retry", include_in_schema=False)
+async def model_hub_search_service_retry(source_id: str, starlette_request: FastAPIRequest):
+ async def handler():
+ from core.handlers.model_hub import ModelHubError
+
+ try:
+ if _model_hub_json_object("invalid_parameter"):
+ raise ModelHubError("invalid_parameter", status=400)
+ await _model_hub_service().clear_service_cooldown(source_id)
+ return _model_hub_success()
+ except ModelHubError as exc:
+ return _model_hub_error(exc)
+
+ return await _dispatch_native_ui_request(starlette_request, handler)
+
+
@app.post("/api/models/sources/{source_id}/evidence/clear", include_in_schema=False)
async def model_hub_source_evidence_clear(source_id: str, starlette_request: FastAPIRequest):
async def handler():