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): wire dormant local and keyless web_fetch (#2968)

Call White19429f6c2173
diff --git a/core/handlers/model_hub/adapter.py b/core/handlers/model_hub/adapter.py
index 7adc0828b..ff0febf2a 100644
--- a/core/handlers/model_hub/adapter.py
+++ b/core/handlers/model_hub/adapter.py
@@ -673,6 +673,19 @@ class EngineAdapter(Protocol):
"""
...
+ async def fetch(
+ self,
+ source_id: str,
+ vendor: str,
+ service_id: str,
+ credential_ref: str | None,
+ request: Mapping[str, Any],
+ *,
+ on_sent: Callable[[], Awaitable[None] | None] | None = None,
+ ) -> SearchResponse:
+ """Make exactly one catalog web-fetch request from Model Hub custody."""
+ ...
+
async def revoke_search_credential(self, credential_ref: str) -> None:
"""Remove a search-only credential from Model Hub custody."""
...
diff --git a/core/handlers/model_hub/fetch_chain.py b/core/handlers/model_hub/fetch_chain.py
new file mode 100644
index 000000000..347611603
--- /dev/null
+++ b/core/handlers/model_hub/fetch_chain.py
@@ -0,0 +1,543 @@
+"""Controller-owned web_fetch chain and service settlement.
+
+The chain freezes order in ``TurnHostedTools`` but rechecks identity, enablement
+and shared service cooldown immediately before each send. Local execution is
+isolated in ``LocalFetchEngine``; keyless transports stay behind EngineAdapter.
+Configured provider execution remains unavailable until its separate delivery.
+"""
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass, replace
+from datetime import datetime, timezone
+from typing import Any, Callable, Mapping
+
+from config.v2_config import (
+ KEYLESS_EXA_SOURCE_ID,
+ is_keyless_exa_source,
+ model_hub_builtin_source,
+)
+from core.agent_core.messages import HostedAttempt, HostedCost, WebFetchRecord
+from core.web_fetch_worker.policy import FetchFailure
+
+from .adapter import SearchResponse
+from .async_owner import await_owned_task
+from .capability_evidence import identity_digest, utc_text
+from .fetch_services import FetchServiceResult, ZERO, map_fetch_response
+from .hosted_executor import ExecutorCall, call_timeout
+from .hosted_turn import ExecutorSlot, TurnHostedTools
+from .retry import source_identity
+from .search_services import ATTEMPT_SECONDS
+from vibe.model_hub_runtime.fetch_catalog import fetch_service
+
+
+class _NotAdmitted(Exception):
+ def __init__(self, skip: dict[str, Any] | None = None):
+ super().__init__()
+ self.skip = skip
+
+
+@dataclass(frozen=True)
+class FetchAttempt:
+ source: Any
+ service_id: str
+ kind: str
+ record: dict[str, Any]
+ cost: HostedCost | None
+ billable: bool
+ uncertain: bool
+ moves_on: bool
+ sent: bool
+
+ def execution(self) -> dict[str, Any]:
+ api = "local_fetch" if self.kind == "local" else "fetch_api"
+ execution: dict[str, Any] = {
+ "mode": "proxy",
+ "executor_origin": {"provider": self.source.vendor, "api": api, "model": self.service_id},
+ "executor_source_id": self.source.id,
+ "executor_billing": "metered",
+ }
+ if self.cost is not None:
+ execution["cost"] = {"basis": self.cost.basis, "usd": self.cost.usd}
+ if self.cost.estimate is not None:
+ execution["cost"]["estimate"] = self.cost.estimate
+ return execution
+
+
+class FetchChain:
+ def __init__(self, owner: Any, call: ExecutorCall, turn: TurnHostedTools, say: Callable[..., str]):
+ self.owner = owner
+ self.call = call
+ self.turn = turn
+ self.say = say
+ self.deadline = asyncio.get_running_loop().time() + call_timeout(call.tool)
+ self.requested_url = str(call.arguments["url"])
+ self.facts: list[dict[str, Any]] = []
+ self.tried: list[FetchAttempt] = []
+ self._gate_error: str | None = None
+
+ @property
+ def _engine(self):
+ engine = getattr(self.owner, "_local_fetch_engine", None)
+ if engine is None:
+ from .local_fetch import LocalFetchEngine
+ engine = LocalFetchEngine()
+ self.owner._local_fetch_engine = engine
+ return engine
+
+ 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)
+ return await asyncio.to_thread(self._classify_sync, slot, config)
+
+ def _classify_sync(self, slot: ExecutorSlot, config):
+ source = model_hub_builtin_source(slot.source_id) or next(
+ (item for item in config.sources if item.id == slot.source_id), None
+ )
+ fact = {
+ "source_id": slot.source_id,
+ "label": slot.label or slot.source_id,
+ "kind": slot.kind,
+ "outcome": "skipped",
+ }
+ if source is None or identity_digest(source) != slot.identity:
+ fact["skipped"] = "unavailable"
+ return None, None, fact
+ fact["label"] = source.display_name[:64]
+ service = fetch_service(source)
+ if service is None or service.get("service_id") != slot.model_id:
+ fact["skipped"] = "unavailable"
+ return source, service, fact
+ if not service.get("available", False) or service.get("vendor") not in {"local", "exa-mcp", "jina-reader"}:
+ fact["skipped"] = "unavailable"
+ return source, service, fact
+ if not slot.enabled:
+ fact["skipped"] = "disabled"
+ return source, service, fact
+ if source.id != KEYLESS_EXA_SOURCE_ID and source.state.status in {"needs_action", "error"}:
+ fact.update(skipped="blocked", needs_action=source.state.detail_key or "models.source.error.unclassified")
+ return source, service, fact
+ if service.get("kind") != "local":
+ until = self.owner._service_cooldowns.until(source, slot.model_id, self.owner.now())
+ if until is not None:
+ fact.update(skipped="cooling", retry_at=utc_text(until))
+ return source, service, fact
+ return source, service, None
+
+ async def run(self) -> dict[str, Any]:
+ try:
+ await self._engine.check(self.requested_url, deadline=self.deadline)
+ except FetchFailure as exc:
+ self._gate_error = exc.code
+ return self._finish(None)
+ slots = self.turn.executors.get(self.call.tool, ())
+ for slot in slots:
+ if asyncio.get_running_loop().time() >= self.deadline:
+ break
+ source, service, skip = await self._classify(slot)
+ if skip is not None:
+ self.facts.append(skip)
+ continue
+ if service is None or source is None:
+ self.facts.append({
+ "source_id": slot.source_id, "label": slot.label or slot.source_id,
+ "kind": slot.kind, "outcome": "skipped", "skipped": "unavailable",
+ })
+ continue
+ if service.get("kind") == "local":
+ attempt, skip = await self._local_attempt(slot, source)
+ else:
+ attempt, skip = await self._service_attempt(slot, source, service)
+ if attempt is None:
+ self.facts.append(skip or {
+ "source_id": slot.source_id, "label": slot.label or slot.source_id,
+ "kind": slot.kind, "outcome": "skipped", "skipped": "unavailable",
+ })
+ if self._gate_error:
+ return self._finish(None)
+ continue
+ self.tried.append(attempt)
+ self.facts.append(self._fact(attempt))
+ if not attempt.moves_on:
+ break
+ return self._finish(self.tried[-1] if self.tried else None)
+
+ def _fact(self, attempt: FetchAttempt) -> dict[str, Any]:
+ record = attempt.record
+ fact: dict[str, Any] = {
+ "source_id": attempt.source.id,
+ "label": attempt.source.display_name[:64],
+ "kind": attempt.kind,
+ "outcome": "completed" if record.get("status") == "completed" else "failed",
+ }
+ if record.get("error_code"):
+ fact["error_code"] = record["error_code"]
+ if attempt.cost is not None:
+ fact["cost"] = {"basis": attempt.cost.basis, "usd": attempt.cost.usd}
+ return fact
+
+ async def _record_local_usage(self, source, slot):
+ write = self.owner.usage_writer.record_service(
+ source_id=source.id, service_id=slot.model_id, tool="web_fetch",
+ billable=False, uncertain=False, at=self.owner.now(),
+ )
+ settlement = asyncio.create_task(self.owner.usage_writer.wait_recorded(write))
+ try:
+ await asyncio.shield(settlement)
+ except asyncio.CancelledError as cancelled:
+ try:
+ await await_owned_task(settlement)
+ except BaseException:
+ # Drain owns the write; Stop still owns the public outcome.
+ pass
+ raise cancelled
+
+ async def _local_attempt(self, slot: ExecutorSlot, source):
+ sent = False
+
+ def on_sent():
+ nonlocal sent
+ sent = True
+
+ try:
+ raw = await self._engine.fetch(
+ self.requested_url,
+ deadline=self.deadline,
+ on_sent=on_sent,
+ )
+ except asyncio.CancelledError:
+ if sent:
+ await self._record_local_usage(source, slot)
+ raise
+ except FetchFailure as exc:
+ raw = {"error_code": exc.code, "terminal": exc.terminal, "sent": sent}
+ sent = bool(raw.get("sent", sent))
+ skipped = raw.get("skipped")
+ if skipped and not sent:
+ return None, {
+ "source_id": slot.source_id, "label": source.display_name[:64], "kind": "local",
+ "outcome": "skipped", "skipped": skipped,
+ **({"retry_at": raw["retry_at"]} if raw.get("retry_at") else {}),
+ }
+ code = raw.get("error_code") or ("fetch_unavailable" if skipped else None)
+ if code:
+ record = {
+ "status": "failed", "error_code": code,
+ "error": self.say(f"hostedTools.errorCode.{code}"),
+ "content": self.say(f"hostedTools.errorCode.{code}"),
+ }
+ moves_on = not raw.get("terminal", False)
+ else:
+ record = {"status": "completed", **raw}
+ moves_on = False
+ cost = ZERO if sent else None
+ if sent:
+ await self._record_local_usage(source, slot)
+ if record.get("status") == "completed":
+ await self.owner.record_hosted_success(source, slot.model_id, "web_fetch", "direct")
+ for key in ("terminal", "sent", "retry_at", "cooldown_code", "cooldown_suppressed", "skipped"):
+ record.pop(key, None)
+ return FetchAttempt(
+ source, slot.model_id, "local", record, cost, False, False, moves_on, sent,
+ ), None
+
+ async def _service_attempt(self, slot: ExecutorSlot, source, service):
+ loop = asyncio.get_running_loop()
+ attempt_deadline = min(self.deadline, loop.time() + ATTEMPT_SECONDS)
+ if is_keyless_exa_source(source):
+ remaining = max(0.0, attempt_deadline - loop.time())
+ try:
+ await asyncio.wait_for(self.owner._keyless_exa_attempt_lock.acquire(), timeout=remaining)
+ except asyncio.TimeoutError:
+ return None, {
+ "source_id": slot.source_id, "label": source.display_name[:64], "kind": "service",
+ "outcome": "skipped", "skipped": "service_busy",
+ }
+ try:
+ return await self._service_attempt_locked(slot, source, service, attempt_deadline=attempt_deadline)
+ finally:
+ self.owner._keyless_exa_attempt_lock.release()
+ return await self._service_attempt_locked(slot, source, service, attempt_deadline=attempt_deadline)
+
+ async def _service_attempt_locked(self, slot, source, service, *, attempt_deadline: float):
+ sent = False
+ response: SearchResponse | None = None
+ cooldown_generation = None
+
+ async def invoke():
+ nonlocal source, response
+ async with self.owner._mutation_lock:
+ current, _, skip = await self._classify(slot, locked=True)
+ if skip is not None:
+ raise _NotAdmitted(skip)
+ source = current
+
+ async def on_sent():
+ nonlocal sent, source, cooldown_generation
+ await self._engine.check(self.requested_url, deadline=self.deadline)
+ async with self.owner._mutation_lock:
+ current, _, skip = await self._classify(slot, locked=True)
+ if skip is not None:
+ raise _NotAdmitted(skip)
+ source = current
+ if source.vendor == "jina-reader":
+ limits = service.get("limits") if isinstance(service.get("limits"), Mapping) else {}
+ requests_per_minute = limits.get("requests_per_minute", 20)
+ if not isinstance(requests_per_minute, int) or requests_per_minute < 1:
+ raise _NotAdmitted()
+ retry_at = self.owner._reserve_jina_fetch_slot(self.owner.now(), requests_per_minute)
+ if retry_at is not None:
+ raise _NotAdmitted({
+ "source_id": slot.source_id,
+ "label": source.display_name[:64],
+ "kind": "service",
+ "outcome": "skipped",
+ "skipped": "cooling",
+ "retry_at": utc_text(retry_at),
+ })
+ cooldown_generation = self.owner._service_cooldowns.advance(source, slot.model_id)
+ sent = True
+
+ request = self._request_for(service)
+ response = await self.owner.adapter.fetch(
+ source.id, source.vendor, slot.model_id, source.credential_ref,
+ request, on_sent=on_sent,
+ )
+ return response
+
+ task = asyncio.create_task(invoke())
+ timed_out = stopped = False
+ try:
+ await asyncio.wait_for(asyncio.shield(task), timeout=max(0.0, attempt_deadline - asyncio.get_running_loop().time()))
+ except asyncio.TimeoutError:
+ timed_out = True
+ task.cancel()
+ except asyncio.CancelledError:
+ stopped = True
+ task.cancel()
+ except _NotAdmitted as exc:
+ return None, exc.skip or {
+ "source_id": slot.source_id, "label": source.display_name[:64], "kind": "service",
+ "outcome": "skipped", "skipped": "unavailable",
+ }
+ except FetchFailure as exc:
+ self._gate_error = exc.code
+ response = SearchResponse(None, {}, None, "invalid_endpoint")
+ except Exception:
+ response = SearchResponse(None, {}, None, "connection")
+ finally:
+ if not task.done():
+ draining = asyncio.create_task(self._drain(task))
+ try:
+ await asyncio.shield(draining)
+ except asyncio.CancelledError:
+ stopped = True
+ await await_owned_task(draining)
+ if stopped and not sent:
+ raise asyncio.CancelledError
+ 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"
+ if not sent:
+ if stopped:
+ raise asyncio.CancelledError
+ return None, {
+ "source_id": slot.source_id, "label": source.display_name[:64], "kind": "service",
+ "outcome": "skipped", "skipped": "service_busy" if timed_out else "unavailable",
+ }
+
+ async def settle_response():
+ result = await asyncio.to_thread(
+ map_fetch_response, service, response, requested_url=self.requested_url,
+ sent=sent, say=self.say,
+ )
+ if stopped:
+ result = replace(result, cooling=False)
+ await self._settle_owned(source, slot, result, response, cooldown_generation, sent)
+ return result
+
+ settlement = asyncio.create_task(settle_response())
+ try:
+ result = await asyncio.shield(settlement)
+ except asyncio.CancelledError:
+ await await_owned_task(settlement)
+ raise
+ if stopped:
+ raise asyncio.CancelledError
+ record = dict(result.record)
+ if result.retry_after:
+ record["retry_after"] = result.retry_after
+ moves_on = result.record.get("status") != "completed"
+ return FetchAttempt(source, slot.model_id, "service", record, result.cost, result.billable, result.uncertain, moves_on, sent), None
+
+ async def _settle_owned(self, source, slot, result, response, cooldown_generation, sent):
+ await await_owned_task(asyncio.create_task(
+ self._settle_service(source, slot, result, response, cooldown_generation, sent)
+ ))
+
+ @staticmethod
+ async def _drain(task):
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+
+ @staticmethod
+ def _request_payload(service: Mapping[str, Any], url: str) -> dict[str, Any]:
+ # The request is deliberately one URL. Catalog mappings are data, not
+ # transport code, so the adapter can validate the fixed endpoint.
+ request_spec = service.get("request") if isinstance(service.get("request"), Mapping) else {}
+ value = url
+ if value is None:
+ raise ValueError("fetch URL is required")
+ field = str(request_spec.get("url_field") or "url")
+ payload = dict(request_spec.get("fixed") or {})
+ payload[field] = [value] if request_spec.get("url_array") else value
+ return payload
+
+ def _request_for(self, service: Mapping[str, Any]) -> dict[str, Any]:
+ return self._request_payload(service, self.requested_url)
+
+ async def _settle_service(self, source, slot, result: FetchServiceResult, response, cooldown_generation, sent):
+ write = self.owner.usage_writer.record_service(
+ source_id=source.id,
+ service_id=slot.model_id,
+ tool="web_fetch",
+ billable=result.billable,
+ uncertain=result.uncertain,
+ reported_usd=result.reported_usd,
+ at=self.owner.now(),
+ ) if sent else None
+ async with self.owner._mutation_lock:
+ previous = await asyncio.to_thread(self.owner.store.load)
+ current = model_hub_builtin_source(source.id) or next((item for item in previous.sources if item.id == source.id), None)
+ identity_current = current is not None and source_identity(current) == source_identity(source)
+ if identity_current and cooldown_generation is not None:
+ self.owner._service_cooldowns.settle(current, slot.model_id, cooldown_generation, _search_compatible(result), response, self.owner.now())
+ if write is not None:
+ await self.owner.usage_writer.wait_recorded(write)
+ if sent and result.record.get("status") == "completed":
+ await self.owner.record_hosted_success(source, slot.model_id, "web_fetch", "service")
+
+ def _finish(self, last: FetchAttempt | None) -> dict[str, Any]:
+ if self._gate_error:
+ code = self._gate_error
+ raw = {"status": "failed", "error_code": code,
+ "error": self.say(f"hostedTools.errorCode.{code}"),
+ "content": self.say(f"hostedTools.errorCode.{code}")}
+ execution = None
+ elif last is None:
+ if self.facts and all(f.get("skipped") in {"blocked", "disabled"} for f in self.facts):
+ code = "fetch_sources_blocked"
+ else:
+ code = "fetch_unavailable"
+ error = self.say(f"hostedTools.errorCode.{code}")
+ raw, execution = {"status": "failed", "error_code": code, "error": error, "content": error}, None
+ else:
+ raw, execution = last.record, last.execution()
+ if last.moves_on:
+ raw = dict(raw)
+ tried = ", ".join(dict.fromkeys(item.source.display_name for item in self.tried))
+ raw["error"] = f"{raw.get('error', '')} {self.say('modelHub.hostedTools.triedSources', sources=tried)}".strip()[:1000]
+ record = self._record(raw)
+ if self.facts:
+ record["attempts"] = self.facts
+ answer: dict[str, Any] = {"record": record}
+ if execution is not None:
+ earlier = [item.execution().get("cost") for item in self.tried[:-1] if item.cost is not None]
+ if earlier:
+ execution["failed_attempts"] = [
+ {"source_id": item.source.id, "billing": "metered", "cost": item.execution()["cost"]}
+ for item in self.tried[:-1] if item.cost is not None
+ ]
+ answer["execution"] = execution
+ return answer
+
+ def _record(self, raw: Mapping[str, Any]) -> dict[str, Any]:
+ content = raw.get("content") if isinstance(raw.get("content"), str) else str(raw.get("error") or "No page content was retained.")
+ status = "completed" if raw.get("status") == "completed" else "failed"
+ provider_truncated = bool(raw.get("provider_truncated"))
+ attempts = tuple(self._attempt_objects())
+ base = {
+ "status": status,
+ "requested_url": self.requested_url,
+ "content": content,
+ "size_bytes": len(content.encode("utf-8", "surrogatepass")),
+ "retrieved_at": datetime.now(timezone.utc).isoformat(),
+ "budget_method": "utf8_bytes_div4_v1",
+ "final_url": raw.get("final_url"),
+ "canonical_url": raw.get("canonical_url"),
+ "title": raw.get("title"),
+ "content_type": raw.get("content_type", "text/markdown" if status == "completed" else None),
+ "source_content_type": raw.get("source_content_type"),
+ "source_size_bytes": raw.get("source_size_bytes"),
+ "error": raw.get("error") if status == "failed" else None,
+ "error_code": raw.get("error_code") if status == "failed" else None,
+ "attempts": attempts,
+ "transport_degraded": raw.get("transport_degraded"),
+ "transport_degraded_reason": raw.get("transport_degraded_reason"),
+ "charset_fallback": raw.get("charset_fallback"),
+ }
+ # Extraction may have capped the source before sanitization shrank it;
+ # a small retained frame does not prove the original document was whole.
+ reason = "budget" if raw.get("content_overflow") else "provider_limit" if provider_truncated else None
+ try:
+ candidate = WebFetchRecord(**base, truncated=reason is not None, truncation_reason=reason)
+ if reason is None:
+ return _record_payload(candidate)
+ except ValueError:
+ reason = reason or "budget"
+ hi = len(content)
+ lo = 1
+ best = None
+ while lo <= hi:
+ mid = (lo + hi) // 2
+ candidate_content = content[:mid]
+ try:
+ candidate = WebFetchRecord(
+ **{**base, "content": candidate_content, "size_bytes": len(candidate_content.encode("utf-8", "surrogatepass")),
+ "truncated": True, "truncation_reason": reason},
+ )
+ except ValueError:
+ hi = mid - 1
+ else:
+ best = candidate
+ lo = mid + 1
+ if best is None:
+ best = WebFetchRecord(
+ **{**base, "content": " ", "size_bytes": 1, "truncated": True, "truncation_reason": reason},
+ )
+ return _record_payload(best)
+
+ def _attempt_objects(self):
+ for fact in self.facts:
+ yield HostedAttempt(
+ source_id=fact["source_id"], label=fact["label"], kind=fact["kind"], outcome=fact["outcome"],
+ error_code=fact.get("error_code"), skipped=fact.get("skipped"), retry_at=fact.get("retry_at"),
+ needs_action=fact.get("needs_action"), cost=_cost(fact.get("cost")),
+ )
+
+
+def _cost(value: object) -> HostedCost | None:
+ if not isinstance(value, Mapping):
+ return None
+ return HostedCost(basis=str(value.get("basis")), usd=value.get("usd"), estimate=value.get("estimate"))
+
+
+def _record_payload(record: WebFetchRecord) -> dict[str, Any]:
+ from core.agent_core.web_fetch import fetch_record_to_dict
+ return fetch_record_to_dict(record)
+
+
+def _search_compatible(result: FetchServiceResult):
+ # ServiceCooldowns is intentionally shared with web_search; it only needs
+ # the stable fields used by settle, not the search mapper's concrete class.
+ from .search_services import ServiceResult
+ return ServiceResult(
+ result.record, result.cost, result.billable, result.uncertain,
+ result.blocker is None and result.record.get("status") == "completed",
+ result.blocker, result.cooling,
+ )
diff --git a/core/handlers/model_hub/fetch_services.py b/core/handlers/model_hub/fetch_services.py
new file mode 100644
index 000000000..443e62091
--- /dev/null
+++ b/core/handlers/model_hub/fetch_services.py
@@ -0,0 +1,300 @@
+"""Keyless web-fetch service mappings.
+
+The adapter owns bounded HTTP/MCP transport. This module maps completed free
+service responses into fetch facts; configured paid mappings ship separately.
+It never decides chain order or writes health.
+"""
+from __future__ import annotations
+
+import json
+import re
+from dataclasses import dataclass
+from typing import Any, Callable, Mapping
+from urllib.parse import urlsplit
+
+from core.agent_core.messages import HostedCost
+
+from .adapter import SearchResponse
+from .events import bounded_diagnostic_detail
+from .search_services import _keyless_rate_limited
+
+ZERO = HostedCost(basis="list", usd=0)
+
+
+def _path(value: Any, path: str | None) -> Any:
+ if not path:
+ return None
+ for part in path.split("."):
+ value = value.get(part) if isinstance(value, Mapping) else None
+ return value
+
+
+def _nested(value: Any, *, depth: int = 0):
+ if depth > 5:
+ return
+ if isinstance(value, Mapping):
+ for key, item in value.items():
+ yield str(key), item
+ yield from _nested(item, depth=depth + 1)
+ elif isinstance(value, list):
+ for item in value[:16]:
+ yield from _nested(item, depth=depth + 1)
+
+
+def _decode(body: bytes | None) -> tuple[Mapping[str, Any] | None, bool]:
+ if body is None:
+ return None, False
+ try:
+ value = json.loads(body.decode("utf-8"))
+ except (UnicodeDecodeError, json.JSONDecodeError, RecursionError):
+ return None, False
+ return (value, True) if isinstance(value, Mapping) else (None, False)
+
+
+def _provider_error(body: Mapping[str, Any] | None) -> str | None:
+ if not isinstance(body, Mapping):
+ return None
+ for key, value in _nested(body):
+ if key.lower() in {"message", "detail", "error", "text"} and isinstance(value, str):
+ return bounded_diagnostic_detail(value)
+ return None
+
+
+def _tag(body: Mapping[str, Any] | None) -> str | None:
+ if not isinstance(body, Mapping):
+ return None
+ for key, value in _nested(body):
+ if key.lower() in {"tag", "code", "type"} and isinstance(value, str):
+ upper = value.upper()
+ if upper.startswith(("CRAWL_", "PROHIBITED_", "CONTENT_FILTER")):
+ return upper
+ return None
+
+
+_EXA_MARKDOWN_HEADER = re.compile(
+ r"\A(?:#\s+|Title:\s*)(?P<title>[^\r\n]*)\r?\n"
+ r"URL:\s*(?P<url>https?://[^\r\n]*)\r?\n"
+ r"(?:(?:Published|Author):[^\r\n]*\r?\n)*"
+ r"(?:\r?\n)?(?P<content>.*)\Z",
+ re.DOTALL,
+)
+_EXA_NO_CONTENT = re.compile(r"\ANo content found(?: for the provided URL\(s\))?\.\Z", re.IGNORECASE)
+_EXA_CRAWL_TAG = re.compile(r"\b(CRAWL_[A-Z0-9_]+)\b")
+
+
+def _exa_markdown_payload(text: str) -> dict[str, Any]:
+ """Keep one Exa Markdown block intact, peeling only its leading wrapper."""
+ match = _EXA_MARKDOWN_HEADER.match(text)
+ if match is None:
+ stripped = text.strip()
+ payload: dict[str, Any] = {"content": text}
+ tag = _EXA_CRAWL_TAG.search(stripped) if stripped.startswith("Error fetching URL(s):") else None
+ if _EXA_NO_CONTENT.fullmatch(stripped) or _EXA_CRAWL_TAG.fullmatch(stripped) or tag:
+ payload["_mcp_target_failure"] = True
+ if tag:
+ payload["tag"] = tag.group(1)
+ return payload
+ payload = {
+ "content": match.group("content"),
+ "title": match.group("title"),
+ "url": match.group("url"),
+ }
+ if not match.group("content").strip():
+ payload["_mcp_target_failure"] = True
+ return payload
+
+
+def _mcp_payload(body: Mapping[str, Any] | None) -> tuple[Mapping[str, Any] | None, bool]:
+ """Separate RPC/tool failures from successfully returned document text."""
+ if not isinstance(body, Mapping):
+ return body, False
+ if body.get("error") is not None:
+ return body, True
+ result = body.get("result")
+ if not isinstance(result, Mapping):
+ return body, True
+ is_error = result.get("isError") is True
+
+ def normalize(payload: Mapping[str, Any]):
+ normalized = dict(payload)
+ metadata = result.get("_meta")
+ if isinstance(metadata, Mapping):
+ normalized["_meta"] = dict(metadata)
+ # Missing/wrong-shaped payloads are protocol faults, not proof of an
+ # empty target. A genuine empty content string remains target-scoped.
+ failed = is_error or not isinstance(normalized.get("content"), str)
+ if failed:
+ normalized["_mcp_is_error"] = True
+ return normalized, failed
+
+ structured = result.get("structuredContent")
+ if isinstance(structured, Mapping):
+ return normalize(structured)
+ content = result.get("content")
+ if isinstance(content, list):
+ for item in content[:8]:
+ if not isinstance(item, Mapping) or item.get("type") != "text":
+ continue
+ text = item.get("text")
+ if not isinstance(text, str):
+ continue
+ if is_error:
+ try:
+ value = json.loads(text)
+ except (json.JSONDecodeError, RecursionError):
+ value = None
+ if isinstance(value, Mapping):
+ return normalize(value)
+ # Successful text blocks are documents regardless of their JSON
+ # keys; structured provider results belong in structuredContent.
+ value = _exa_markdown_payload(text)
+ if is_error:
+ value["text"] = text
+ return normalize(value)
+ return body, True
+
+def _url_value(value: Any) -> str | None:
+ if not isinstance(value, str) or len(value) > 8192:
+ return None
+ try:
+ parsed = urlsplit(value)
+ except ValueError:
+ return None
+ if parsed.scheme not in {"http", "https"} or not parsed.hostname or parsed.username or parsed.password:
+ return None
+ return value
+
+
+def _content(service: Mapping[str, Any], body: Mapping[str, Any] | None) -> tuple[str | None, str | None, str | None, bool]:
+ result = service.get("result") if isinstance(service.get("result"), Mapping) else {}
+ content = _path(body, result.get("content"))
+ title = _path(body, result.get("title"))
+ final_url = _path(body, result.get("url"))
+ if service.get("vendor") == "exa-mcp":
+ content = _path(body, result.get("content", "content"))
+ title = _path(body, result.get("title", "title"))
+ final_url = _path(body, result.get("url", "url"))
+ if service.get("vendor") == "jina-reader" and isinstance(body, Mapping):
+ data = body.get("data")
+ if isinstance(data, Mapping):
+ content = data.get("content")
+ title = data.get("title")
+ final_url = data.get("url")
+ provider_truncated = any(
+ value is True
+ for key, value in _nested(body)
+ if key.lower() in {"truncated", "istruncated", "is_truncated"}
+ )
+ return (
+ content if isinstance(content, str) and content.strip() else None,
+ title[:300] if isinstance(title, str) else None,
+ _url_value(final_url),
+ provider_truncated,
+ )
+
+
+@dataclass(frozen=True)
+class FetchServiceResult:
+ record: dict[str, Any]
+ cost: HostedCost | None
+ billable: bool
+ uncertain: bool
+ blocker: str | None
+ cooling: bool
+ target_failure: bool = False
+ retry_after: str | None = None
+ reported_usd: float | None = None
+
+
+def _failed(code: str, say: Callable[..., str], *, detail: str | None = None) -> dict[str, Any]:
+ error = say(f"hostedTools.errorCode.{code}")
+ if detail:
+ error = f"{error} ({detail})"
+ return {"status": "failed", "error": error[:1000], "error_code": code, "content": error[:1000]}
+
+
+def map_fetch_response(
+ service: Mapping[str, Any],
+ response: SearchResponse,
+ *,
+ requested_url: str,
+ sent: bool,
+ say: Callable[..., str],
+) -> FetchServiceResult:
+ """Map one service response, keeping target failures separate from service health."""
+ body, decoded = _decode(response.body)
+ status = response.http_status
+ outcomes = service.get("outcomes") if isinstance(service.get("outcomes"), Mapping) else {}
+ vendor = str(service.get("vendor") or "")
+ if vendor not in {"exa-mcp", "jina-reader"}:
+ raise ValueError("configured fetch mappings are not available in this build")
+ mcp_error = False
+ mcp_target_failure = False
+ if vendor == "exa-mcp":
+ body, mcp_error = _mcp_payload(body)
+ mcp_target_failure = bool(isinstance(body, Mapping) and body.get("_mcp_target_failure") is True)
+ retry_after = next((value for key, value in response.headers.items() if key.lower() == "retry-after"), None)
+ tag = _tag(body)
+ refusal_tags = {str(item).upper() for item in outcomes.get("refusal_tags", ())}
+ code: str | None = None
+ target_failure = False
+ if status == 429:
+ code = "service_rate_limited"
+ elif status in set(outcomes.get("refused") or ()):
+ code = "service_refused"
+ elif status in set(outcomes.get("target_unreadable") or ()):
+ code, target_failure = "fetch_target_unreadable", True
+ elif vendor == "exa-mcp" and _keyless_rate_limited(status, body):
+ code = "service_rate_limited"
+ elif mcp_error and tag and tag in refusal_tags:
+ code = "service_refused"
+ elif vendor == "exa-mcp" and mcp_target_failure:
+ code, target_failure = "fetch_target_unreadable", True
+ if tag and not tag.startswith("CRAWL_"):
+ code, target_failure = "service_unavailable", False
+ elif vendor == "exa-mcp" and mcp_error:
+ if tag and tag.startswith("CRAWL_"):
+ code, target_failure = "fetch_target_unreadable", True
+ elif tag and tag.startswith("PROHIBITED"):
+ code = "service_refused"
+ else:
+ code = "service_unavailable"
+ elif status == 200 and not decoded:
+ # A provider envelope that cannot be decoded is a service fault, not
+ # evidence that this particular target was unreadable.
+ code = "service_unreadable" if response.error == "body_too_large" else "service_unavailable"
+ elif response.error in {"timeout", "connection", "redirect", "body_too_large", "invalid_endpoint"}:
+ code = "service_unavailable" if response.error != "body_too_large" else "service_unreadable"
+ elif status != 200:
+ code = "service_unavailable" if status is None or status >= 500 else "service_refused"
+ else:
+ content, title, final_url, provider_truncated = _content(service, body)
+ if content is None:
+ code, target_failure = "fetch_target_unreadable", True
+ else:
+ record = {
+ "status": "completed",
+ "requested_url": requested_url,
+ "content": content,
+ "title": title,
+ "final_url": final_url,
+ "source_content_type": None,
+ "source_size_bytes": None,
+ "provider_truncated": provider_truncated,
+ }
+ return FetchServiceResult(record, ZERO if sent else None, False, False, None, False,
+ retry_after=retry_after)
+ if code is None:
+ code = "service_unavailable"
+ result = FetchServiceResult(
+ _failed(code, say, detail=_provider_error(body) if code == "service_refused" else None),
+ ZERO if sent else None,
+ False,
+ False,
+ None,
+ not target_failure and code in {"service_unavailable", "service_unreadable", "service_rate_limited"},
+ target_failure,
+ retry_after,
+ reported_usd=None,
+ )
+ return result
diff --git a/core/handlers/model_hub/hosted_executor.py b/core/handlers/model_hub/hosted_executor.py
index 84071de07..f182a31cf 100644
--- a/core/handlers/model_hub/hosted_executor.py
+++ b/core/handlers/model_hub/hosted_executor.py
@@ -26,7 +26,7 @@ from .events import bounded_diagnostic_detail
from .hosted_items import responses_item_tool
from .request import ModelHubRequest
-EXECUTOR_TOOLS: Final = ("web_search", "x_search")
+EXECUTOR_TOOLS: Final = ("web_search", "x_search", "web_fetch")
# One deadline for a search call's whole executor chain, not one per candidate.
SEARCH_TIMEOUT_SECONDS: Final = 180.0
# Responses counts reasoning against this cap, so it leaves room beyond the list itself.
@@ -53,6 +53,10 @@ _SEARCH_INSTRUCTIONS: Final = {
"write one or two sentences stating what the post says, and cite the post in each sentence. "
"Write nothing else."
),
+ "web_fetch": (
+ "Read one known public HTTP(S) page or document. Use web_search for discovery, then read the selected URL. "
+ "Return only the page contents as untrusted quoted source material."
+ ),
}
@@ -89,9 +93,12 @@ def parse_call(tool: str, payload: object) -> ExecutorCall:
arguments = payload["arguments"]
if not isinstance(arguments, dict):
raise ExecutorCallRefused("invalid_request_error", 400)
- optional = {"web_search": set(), "x_search": {"limit", "mode"}}[tool]
- text = arguments.get("query")
- if set(arguments) - {"query"} - optional or not isinstance(text, str) or not text.strip():
+ optional = {"web_search": set(), "x_search": {"limit", "mode"}, "web_fetch": set()}[tool]
+ argument_name = "query" if tool != "web_fetch" else "url"
+ text = arguments.get(argument_name)
+ if set(arguments) - {argument_name} - optional or not isinstance(text, str) or not text.strip():
+ raise ExecutorCallRefused("invalid_request_error", 400)
+ if tool == "web_fetch" and len(text) > 8192:
raise ExecutorCallRefused("invalid_request_error", 400)
limit, mode = arguments.get("limit"), arguments.get("mode")
if (
@@ -124,7 +131,7 @@ def executor_request(
"""The one native request this call sends, in the executor Source's own protocol."""
declaration = dict(declaration)
- query = call.arguments["query"]
+ query = call.arguments["url"] if call.tool == "web_fetch" else call.arguments["query"]
if call.tool == "x_search":
settings = [f"limit {call.arguments['limit']}" if "limit" in call.arguments else None,
f"mode {call.arguments['mode']}" if "mode" in call.arguments else None]
diff --git a/core/handlers/model_hub/search_services.py b/core/handlers/model_hub/search_services.py
index 2d22e5549..b2fd64380 100644
--- a/core/handlers/model_hub/search_services.py
+++ b/core/handlers/model_hub/search_services.py
@@ -386,7 +386,8 @@ class ServiceCooldowns:
reset_deadline = _rate_limit_reset_deadline(reset, received_at)
if reset_deadline is not None and (advice is None or reset_deadline > advice):
advice = reset_deadline
- state.until = advice if advice is not None else now + timedelta(seconds=min(30 * 2 ** (state.failures - 1), 300))
+ base_seconds = 60 if source.vendor == "jina-reader" else 30
+ state.until = advice if advice is not None else now + timedelta(seconds=min(base_seconds * 2 ** (state.failures - 1), 300))
elif result.record["status"] == "completed":
state.failures = 0
state.until = None
diff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.py
index bd01f3db4..be8d86f46 100644
--- a/core/handlers/model_hub/service.py
+++ b/core/handlers/model_hub/service.py
@@ -10,6 +10,7 @@ import logging
import threading
import time
import uuid
+from collections import deque
from contextlib import asynccontextmanager
from dataclasses import dataclass, replace
from datetime import datetime, timedelta, timezone
@@ -1608,6 +1609,8 @@ class ModelHubService:
self._search_reenable_checks: dict[str, asyncio.Task] = {}
self._service_cooldowns = ServiceCooldowns()
self._keyless_exa_attempt_lock = asyncio.Lock()
+ self._jina_fetch_sent_at: deque[datetime] = deque()
+ self._local_fetch_engine = None
self._next_settlement_generation = PRE_ATTEMPT_SETTLEMENT_GENERATION
self._latest_source_attempt_generation: dict[str, int] = {}
self._source_attempt_identities: dict[str, tuple | None] = {}
@@ -2019,6 +2022,16 @@ class ModelHubService:
self._next_settlement_generation += 1
return self._next_settlement_generation
+ def _reserve_jina_fetch_slot(self, now: datetime, limit: int = 20) -> datetime | None:
+ """Reserve one runtime-wide keyless Reader call in its rolling minute."""
+ cutoff = now - timedelta(minutes=1)
+ while self._jina_fetch_sent_at and self._jina_fetch_sent_at[0] <= cutoff:
+ self._jina_fetch_sent_at.popleft()
+ if len(self._jina_fetch_sent_at) >= limit:
+ return self._jina_fetch_sent_at[0] + timedelta(minutes=1)
+ self._jina_fetch_sent_at.append(now)
+ return None
+
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()
@@ -7291,6 +7304,11 @@ class ModelHubService:
self._service_cooldowns.advance(source, service["service_id"], clear=True)
return {}
+ async def _run_fetch_chain(self, call: ExecutorCall, turn: TurnHostedTools, *, say: Callable[..., str]) -> dict:
+ """Run the dormant web_fetch service/local chain behind the activation flag."""
+ from .fetch_chain import FetchChain
+ return await FetchChain(self, call, turn, say).run()
+
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()
@@ -7325,6 +7343,10 @@ 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_fetch" and not hosted_tools_module.WEB_FETCH_ACTIVE:
+ raise ModelHubError("tool_not_enabled", status=409)
+ if tool == "web_fetch":
+ return await self._run_fetch_chain(call, turn, say=say)
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()
diff --git a/core/handlers/model_hub/usage.py b/core/handlers/model_hub/usage.py
index ffb71168a..b3a94fa33 100644
--- a/core/handlers/model_hub/usage.py
+++ b/core/handlers/model_hub/usage.py
@@ -1411,6 +1411,7 @@ def _service_increment(
"day": owner_day,
"source_id": source_key,
"service_id": service_key,
+ **({"tool": call.tool} if call.tool == "web_fetch" else {}),
**counts,
"last_metered_at": metered_at.isoformat(),
"hours": [
@@ -2472,16 +2473,19 @@ class ServiceUsageCall:
reported_requests: int = 0
reported_usd: float = 0.0
owner_day: str = ""
+ tool: str = "web_search"
def __post_init__(self) -> None:
+ if self.tool not in ("web_search", "web_fetch"):
+ raise ValueError("unsupported hosted service tool")
if not self.owner_day:
object.__setattr__(self, "owner_day", local_usage_day(self.at).isoformat())
@property
- def fold_key(self) -> tuple[str, str, str, str, str]:
+ def fold_key(self) -> tuple[str, str, str, str, str, str]:
"""What makes two calls one daily row and one hourly slice; never a model's key."""
- return ("service", self.owner_day, _hour_key(self.at), self.source_id, self.service_id)
+ return ("service", self.owner_day, _hour_key(self.at), self.source_id, self.service_id, self.tool)
def folded_with(self, other: "ServiceUsageCall") -> "ServiceUsageCall":
"""Fold a call that shares this one's row: every count adds, the later stamp wins."""
@@ -2664,6 +2668,7 @@ class UsageWriter:
uncertain: bool = False,
reported_usd: Optional[float] = None,
at: datetime,
+ tool: str = "web_search",
) -> "asyncio.Future[None]":
"""Own one sent search-service request and queue it, as `record` does a model call.
@@ -2684,6 +2689,7 @@ class UsageWriter:
uncertain_requests=_flag_count(uncertain),
reported_requests=int(reported_usd is not None),
reported_usd=reported_usd if reported_usd is not None else 0.0,
+ tool=tool,
)
)
diff --git a/docs/plans/model-hub-contracts/adapter-interface.py b/docs/plans/model-hub-contracts/adapter-interface.py
index 7adc0828b..ff0febf2a 100644
--- a/docs/plans/model-hub-contracts/adapter-interface.py
+++ b/docs/plans/model-hub-contracts/adapter-interface.py
@@ -673,6 +673,19 @@ class EngineAdapter(Protocol):
"""
...
+ async def fetch(
+ self,
+ source_id: str,
+ vendor: str,
+ service_id: str,
+ credential_ref: str | None,
+ request: Mapping[str, Any],
+ *,
+ on_sent: Callable[[], Awaitable[None] | None] | None = None,
+ ) -> SearchResponse:
+ """Make exactly one catalog web-fetch request from Model Hub custody."""
+ ...
+
async def revoke_search_credential(self, credential_ref: str) -> None:
"""Remove a search-only credential from Model Hub custody."""
...
diff --git a/docs/plans/web-fetch-gateway-delivery.md b/docs/plans/web-fetch-gateway-delivery.md
new file mode 100644
index 000000000..38369ad61
--- /dev/null
+++ b/docs/plans/web-fetch-gateway-delivery.md
@@ -0,0 +1,82 @@
+# WF-2G gateway delivery
+
+Status: 2026-10-25, dormant implementation; `WEB_FETCH_ACTIVE=False`.
+The behavior contract remains [web-fetch.md](web-fetch.md), especially §§3–6.
+This plan narrows delivery units, not the activation/release scope.
+
+## Delivery units and ownership
+
+1. **Local engine and packaging:** PR #2962 merged. No activation.
+2. **Chain and keyless services:** PR #2968 retains the URL/DNS gate, local
+ wiring, keyless Exa/Jina, ordered fallback, no-send/skipped contract,
+ additive fetch usage attribution, and endpoint routing.
+3. **Configured services:** a separate PR from the updated `master` after
+ #2968 merges adds Tavily Extract, keyed Exa `/contents`, and DeepSeek Fetch.
+ Both producer PRs must merge before WF-3 enables the feature.
+
+The gateway lane prepares exact-head review/CI evidence; the orchestrator owns
+merging. No service restart, regression deployment, release or live paid probe is
+part of this lane. Tests use test-owned state and loopback fixtures only.
+
+## Convergence boundary
+
+The third reviewed head of #2968 again had multiple provider-mapping/settlement
+findings, triggering the orchestrator's split guard. The configured transport,
+content mapping, price/reported-cost mapping, and Source credential-health
+settlement are removed from #2968, not merely hidden behind the global flag.
+The chain and adapter independently reject configured fetch candidates before
+admission. Existing catalog identities and saved user choices remain intact.
+
+The pre-split implementation is preserved in commit
+`7f29c924082251f4868804c37f5210e1e2a141f2`; it is a reference, **not** a reviewed
+implementation to restore wholesale. In particular, its paid pre-status billing
+uncertainty and admission-generation propagation are known defects. The follow-up
+must not cherry-pick the entire chain or become a stacked PR.
+
+## Remaining producer invariants
+
+Prior tests checked mapped results without exercising the full admission →
+response → settlement lifecycle. Boundary tests now own these invariants:
+
+| Boundary | Required evidence |
+| --- | --- |
+| Dormancy | Global flag rejects stale turns; configured providers cannot reach either adapter or transport even in flag-enabled test fixtures. |
+| Admission | Every service submission re-gates only the original URL; a refusal stops forwarding but retains usage for earlier sent attempts. |
+| Attempt ownership | One capped deadline starts before the shared Exa lock, includes subsequent transport work, and allows Jina fallback on expiry. |
+| No-send | Disabled/unavailable/contended/over-budget candidates have only skipped facts, no usage, no capability success and no cooldown write. |
+| Shared health | The actual sent callback carries the cooldown generation into settlement; stale generations cannot overwrite newer search/fetch state. Built-ins never reserve or write credential health. |
+| Scope | Catalog MCP refusals precede generic errors; target failures/refusals never cool the service. Service failures and 429 do, honoring server advice. Jina's no-advice backoff starts at 60 seconds. |
+| Protocol vs document | Top-level JSON-RPC errors, tool errors and missing/wrong-shaped result payloads are service faults unless a recognized target/refusal/rate signal overrides them. Valid JSON alone is not a successful envelope. Successful text documents (including JSON/scalars/error-looking prose) remain literal content. Search and fetch reuse the error-shaped MCP rate-limit classifier. |
+| Truncation | An extractor's `content_overflow` survives normalization into the stored budget-truncation fact and model-facing marker, even when sanitization leaves fewer than 48,000 bytes. |
+| Accounting | Every sent local/keyless attempt, including cancellation and failure, has exactly one zero-cost fetch usage row; mapping/settlement survive cancellation. |
+| MCP transport | Search and fetch reuse one session; fetch sends `urls` and the explicit character bound, rejects missing controls/unknown required inputs before `tools/call`, and handles JSON/SSE. |
+
+Primary tests: `tests/test_model_hub_fetch_chain.py` and the real loopback MCP
+fixture in `tests/test_model_hub_keyless_exa.py`. Existing search-chain and fetch
+reader tests cover shared cooldown/ledger/read compatibility. Local engine tests
+remain the gate/transport/extraction owner; no live providers are test or CI inputs.
+
+## Configured-provider follow-up acceptance
+
+Build one explicit table across provider × response phase × failure scope before
+implementing the smaller PR:
+
+- request shapes: Tavily basic/Markdown `urls`, Exa `/contents` `ids` and bounded
+ text, DeepSeek `url`; use only the catalog endpoint and opaque credential owner;
+- distinguish valid target-empty/failed results from malformed/missing successful
+ envelopes and service faults;
+- sent + no response status means uncertain paid billing unless a documented
+ provider-specific unbilled exception applies; received 200 with unrecoverable
+ body stays uncertain, including DeepSeek;
+- a proven successful billable result is priced even if normalization later
+ fails; validate Exa reported cost without inventing a definitive zero;
+- reserve and propagate credential-health and service-cooldown generations at
+ actual admission; stale responses cannot damage recovered Source health;
+- test transport cancellation, response-mapping cancellation, invalid endpoint,
+ disabled/replaced Source, target refusal and real sent settlement through the
+ chain boundary, rather than only the mapper;
+- keep the same C-1 record/endpoint/usage contracts and keep activation off.
+
+Use focused hermetic checks through `~/.local/bin/hd1-test`, then exact-head Codex
+review and required CI for each PR. A passing smaller PR does not waive the other
+producer PR or WF-3's activation gate.
diff --git a/tests/test_model_hub_fetch_chain.py b/tests/test_model_hub_fetch_chain.py
new file mode 100644
index 000000000..52b0cfb54
--- /dev/null
+++ b/tests/test_model_hub_fetch_chain.py
@@ -0,0 +1,761 @@
+"""WF-2G fetch producer contracts: no-send settlement, local wiring and free accounting."""
+from __future__ import annotations
+
+import asyncio
+import json
+import threading
+from dataclasses import replace
+from datetime import timedelta
+from pathlib import Path
+
+import pytest
+
+from config.v2_config import ModelHubFetchServiceSettings, model_hub_builtin_source
+from core.handlers.model_hub import fetch_chain as fetch_chain_module
+from core.handlers.model_hub import hosted_tools
+from core.handlers.model_hub.adapter import SearchResponse
+from core.handlers.model_hub.fetch_services import map_fetch_response
+from tests.test_model_hub_search_chain import EXA, IDS, owner
+from tests.test_model_hub_web_fetch_readers import FREE_EXA, JINA, LOCAL, fetch_config
+from vibe.model_hub_runtime.adapter import CLIProxyEngineAdapter
+from vibe.model_hub_runtime.fetch_catalog import fetch_service_catalog
+from core.handlers.model_hub.service import ModelHubError
+
+
[email protected](autouse=True)
+def _reset_fetch_flag(monkeypatch):
+ monkeypatch.setattr(hosted_tools, "WEB_FETCH_ACTIVE", False)
+ yield
+
+
+async def test_jina_builtin_fetch_is_admitted_with_reader_headers():
+ adapter = object.__new__(CLIProxyEngineAdapter)
+ captured = {}
+
+ async def search_http(**kwargs):
+ captured.update(kwargs)
+ return SearchResponse(200, {}, b'{"data":{"content":"body"}}')
+
+ adapter._search_http = search_http
+ response = await adapter.fetch(
+ "src_jinakeyless", "jina-reader", "jina/reader", None,
+ {"url": "https://example.com/"},
+ )
+ assert response.http_status == 200
+ assert captured["extra_headers"]["X-Return-Format"] == "markdown"
+ assert captured["extra_headers"]["User-Agent"].startswith("Avibe/")
+
+
+ jina = next(item for item in fetch_service_catalog() if item["vendor"] == "jina-reader")
+ mapped = map_fetch_response(
+ jina,
+ SearchResponse(200, {}, json.dumps({"data": {"content": "body", "title": "t" * 400}}).encode()),
+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,
+ )
+ assert mapped.record["title"] == "t" * 300
+
+ exa = next(item for item in fetch_service_catalog() if item["vendor"] == "exa-mcp")
+ limited = map_fetch_response(
+ exa,
+ SearchResponse(200, {}, json.dumps({"result": {"_meta": {"ai.exa/rateLimited": True}, "content": []}}).encode()),
+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,
+ )
+ assert limited.record["error_code"] == "service_rate_limited"
+ assert limited.cooling and not limited.target_failure
+
+
+def test_exa_mcp_markdown_text_block_preserves_page_text_and_leading_metadata():
+ exa = next(item for item in fetch_service_catalog() if item["vendor"] == "exa-mcp")
+ text = "# Example page\nURL: https://example.com/page\nPublished: 2026-10-25\nAuthor: Example\n\n# Body\nURL: https://example.com/in-page\n"
+ mapped = map_fetch_response(
+ exa,
+ SearchResponse(200, {}, json.dumps({"result": {"content": [{"type": "text", "text": text}]}}).encode()),
+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,
+ )
+ assert mapped.record["status"] == "completed"
+ assert mapped.record["title"] == "Example page"
+ assert mapped.record["final_url"] == "https://example.com/page"
+ assert mapped.record["content"] == "# Body\nURL: https://example.com/in-page\n"
+
+
[email protected]("vendor", ["exa-mcp", "jina-reader"])
[email protected]("body", [b"<html>broken provider</html>", b"[1, 2, 3]"])
+def test_http_200_malformed_provider_envelopes_are_service_failures(body, vendor):
+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == vendor)
+ mapped = map_fetch_response(
+ catalog, SearchResponse(200, {}, body), requested_url="https://example.com/", sent=True,
+ say=lambda key, **_: key,
+ )
+ assert mapped.record["error_code"] == "service_unavailable"
+ assert mapped.cooling and not mapped.target_failure
+ assert mapped.cost.usd == 0 and not mapped.uncertain and not mapped.billable
+
+
[email protected]("vendor", ["exa", "tavily", "deepseek"])
+async def test_configured_fetch_is_dormant_at_chain_and_adapter_boundaries(tmp_path, vendor):
+ """The split must not expose an unreviewed paid transport even if the flag is enabled."""
+ sid = IDS[vendor]
+ service, config = _service(
+ tmp_path, vendor=vendor,
+ enabled={LOCAL: False, FREE_EXA: False, JINA: False, sid: True}, order=(sid,),
+ )
+ calls = []
+
+ async def unexpected(*args, **kwargs):
+ calls.append(args)
+ raise AssertionError("configured fetch must remain unavailable")
+
+ service.adapter.fetch = unexpected
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ first = result["record"]["attempts"][0]
+ assert first["source_id"] == sid and first["skipped"] == "unavailable"
+ assert service.usage_summary(days=7)["services"] == []
+ assert service.capability_evidence.records() == []
+ adapter = object.__new__(CLIProxyEngineAdapter)
+ adapter._search_http = unexpected
+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == vendor)
+ response = await adapter.fetch(sid, vendor, catalog["service_id"], f"cred_{sid}", {"url": "https://example.com/"})
+ assert response.error == "invalid_endpoint"
+ assert calls == []
+
+
[email protected]("sid,status,body,expected,delay", [
+ (FREE_EXA, 429, {}, "service_rate_limited", 600),
+ (FREE_EXA, 500, {}, "service_unavailable", 30),
+ (FREE_EXA, 200, {"jsonrpc": "2.0", "id": 1, "error": {"code": -32603, "message": "Internal error"}}, "service_unavailable", 30),
+ (FREE_EXA, 200, {"jsonrpc": "2.0", "id": 1, "error": {"code": -32000, "message": "Unauthorized"}}, "service_unavailable", 30),
+ (FREE_EXA, 200, {"jsonrpc": "2.0", "id": 1, "error": {"code": -32000, "message": "Free MCP rate limit exceeded"}}, "service_rate_limited", 30),
+ (FREE_EXA, 200, {"jsonrpc": "2.0", "id": 1, "error": {"code": "CONTENT_FILTER_ERROR"}}, "service_refused", None),
+ (FREE_EXA, 200, {"result": {}}, "service_unavailable", 30),
+ (FREE_EXA, 200, {"result": []}, "service_unavailable", 30),
+ (FREE_EXA, 200, {"result": {"structuredContent": {}}}, "service_unavailable", 30),
+ (FREE_EXA, 200, {"result": {"structuredContent": {"content": []}}}, "service_unavailable", 30),
+ (FREE_EXA, 200, {"result": {"structuredContent": {"content": ""}}}, "fetch_target_unreadable", None),
+ (FREE_EXA, 200, {"result": {"_meta": {"ai.exa/rateLimited": True}, "content": []}}, "service_rate_limited", 30),
+ (FREE_EXA, 200, {"result": {"isError": True, "content": [{"type": "text", "text": '{"error":{"code":"CONTENT_FILTER_ERROR"}}'}]}}, "service_refused", None),
+ (FREE_EXA, 200, {"result": {"isError": True, "structuredContent": {"error": {"code": "PROHIBITED_CONTENT"}}}}, "service_refused", None),
+ (FREE_EXA, 200, {"result": {"isError": True, "structuredContent": {"error": {"code": "CRAWL_UNKNOWN_ERROR"}}}}, "fetch_target_unreadable", None),
+ (FREE_EXA, 200, {"result": {"isError": True, "structuredContent": {"error": {"code": "NEW_ERROR"}}}}, "service_unavailable", 30),
+ (JINA, 429, {}, "service_rate_limited", 600),
+ (JINA, 500, {}, "service_unavailable", 60),
+ (JINA, 401, {}, "service_refused", None),
+ (JINA, 403, {}, "service_refused", None),
+])
+async def test_keyless_response_settles_real_shared_cooldown_and_free_usage(tmp_path, sid, status, body, expected, delay):
+ """Mapper-only checks missed the lost admission generation and generic MCP refusal branch."""
+ service, config = _service(
+ tmp_path, enabled={LOCAL: False, EXA: False, FREE_EXA: sid == FREE_EXA, JINA: sid == JINA}, order=(sid,),
+ )
+ sent = []
+
+ async def fetch(*args, on_sent):
+ await on_sent()
+ sent.append(True)
+ return SearchResponse(status, {"Retry-After": "600"} if status == 429 else {}, json.dumps(body).encode())
+
+ service.adapter.fetch = fetch
+ turn = service.freeze_turn_hosted_tools(config)
+ result = await service.run_hosted_tool("web_fetch", {"arguments": {"url": "https://example.com/"}}, turn=turn)
+ assert result["record"]["error_code"] == expected
+ assert result["record"]["attempts"][0]["cost"] == {"basis": "list", "usd": 0}
+ source = model_hub_builtin_source(sid)
+ service_id = "exa/mcp" if sid == FREE_EXA else "jina/reader"
+ until = service._service_cooldowns.until(source, service_id, service.now())
+ assert until == (None if delay is None else service.now() + timedelta(seconds=delay))
+ assert not service._latest_source_attempt_generation # built-ins have no credential health
+ if delay is not None:
+ again = await service.run_hosted_tool("web_fetch", {"arguments": {"url": "https://example.com/"}}, turn=turn)
+ assert again["record"]["attempts"][0]["skipped"] == "cooling"
+ assert sent == [True]
+ row = next(row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch")
+ assert row["requests"] == 1
+ assert row["billable_requests"] == row["uncertain_requests"] == row["reported_requests"] == 0
+
+
+async def test_stale_keyless_fetch_cannot_overwrite_a_newer_shared_generation(tmp_path):
+ """A search retry/reset can advance the same identity while a fetch is in flight."""
+ service, config = _service(
+ tmp_path, enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: False}, order=(FREE_EXA,),
+ )
+ source = model_hub_builtin_source(FREE_EXA)
+
+ async def fetch(*args, on_sent):
+ await on_sent()
+ assert service._service_cooldowns.generation(source, "exa/mcp") is not None
+ service._service_cooldowns.advance(source, "exa/mcp", clear=True)
+ return SearchResponse(429, {}, b"{}")
+
+ service.adapter.fetch = fetch
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}}, turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["error_code"] == "service_rate_limited"
+ assert service._service_cooldowns.until(source, "exa/mcp", service.now()) is None
+
+
[email protected]("release_lock", [False, True])
+async def test_keyless_attempt_deadline_includes_lock_wait_and_allows_jina_fallback(tmp_path, monkeypatch, release_lock):
+ """The original chain consumed 180s in the lock; resetting 30s after admission is also wrong."""
+ monkeypatch.setattr(fetch_chain_module, "ATTEMPT_SECONDS", 0.3, raising=False)
+ service, config = _service(
+ tmp_path, enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: True}, order=(FREE_EXA, JINA),
+ )
+ await service._keyless_exa_attempt_lock.acquire()
+ sent = []
+
+ async def fetch(source_id, *args, on_sent):
+ await on_sent()
+ sent.append(source_id)
+ if source_id == FREE_EXA:
+ await asyncio.sleep(0.22)
+ body = {"result": {"structuredContent": {"content": "late Exa"}}}
+ else:
+ body = {"data": {"content": "Jina fallback"}}
+ return SearchResponse(200, {}, json.dumps(body).encode())
+
+ service.adapter.fetch = fetch
+ release_handle = asyncio.get_running_loop().call_later(0.12, service._keyless_exa_attempt_lock.release) if release_lock else None
+ try:
+ result = await asyncio.wait_for(service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}}, turn=service.freeze_turn_hosted_tools(config),
+ ), timeout=2)
+ finally:
+ if release_handle:
+ release_handle.cancel()
+ if service._keyless_exa_attempt_lock.locked():
+ service._keyless_exa_attempt_lock.release()
+ assert result["record"]["content"] == "Jina fallback"
+ first = result["record"]["attempts"][0]
+ assert first["outcome"] == ("failed" if release_lock else "skipped")
+ if not release_lock:
+ assert first["skipped"] == "service_busy"
+ assert sent == ([FREE_EXA, JINA] if release_lock else [JINA])
+ rows = {row["source_id"]: row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch"}
+ assert rows[JINA]["requests"] == 1
+ assert (FREE_EXA in rows) == release_lock
+
+
[email protected]("code", ["fetch_url_blocked", "fetch_dns_unverified"])
+async def test_fallback_regate_failure_is_terminal_without_forwarding(tmp_path, code):
+ """A sent local failure may not bypass the original-URL gate on service fallback."""
+ from core.web_fetch_worker.policy import FetchFailure
+
+ service, config = _service(
+ tmp_path, enabled={LOCAL: True, EXA: False, FREE_EXA: True, JINA: True}, order=(LOCAL, FREE_EXA, JINA),
+ )
+ checks, submissions = [], []
+ url = "https://example.com/"
+
+ async def check(value, *, deadline):
+ checks.append(value)
+ if len(checks) > 1:
+ raise FetchFailure(code, terminal=True)
+
+ async def local(value, *, deadline, on_sent):
+ on_sent()
+ return {"sent": True, "error_code": "fetch_timeout", "terminal": False}
+
+ async def fetch(*args, on_sent):
+ await on_sent()
+ submissions.append(args)
+ raise AssertionError("blocked fallback must not forward the URL")
+
+ service._local_fetch_engine.check = check
+ service._local_fetch_engine.fetch = local
+ service.adapter.fetch = fetch
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": url}}, turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["error_code"] == code
+ assert checks == [url, url] and submissions == []
+ assert [(fact["source_id"], fact["outcome"]) for fact in result["record"]["attempts"]] == [(LOCAL, "failed"), (FREE_EXA, "skipped")]
+ rows = service.usage_summary(days=7)["services"]
+ assert len(rows) == 1 and rows[0]["source_id"] == LOCAL and rows[0]["requests"] == 1
+
+
+ '{"content":"Article body","other":"Important details","title":"Document title","url":"https://other.example/"}',
+ '{"content":"","other":"Still a nonempty JSON document"}',
+ '{"error":{"code":"CONTENT_FILTER_ERROR","message":"Free MCP rate limit exceeded"}}',
+ '[{"error":"Internal error"}]',
+ '123',
+ 'A page discussing rate limits and CONTENT_FILTER_ERROR is still page content.',
+])
+def test_successful_mcp_text_documents_are_not_reinterpreted_as_error_envelopes(text):
+ """Successful text blocks are documents, even when a JSON page resembles an RPC error."""
+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == "exa-mcp")
+ result = map_fetch_response(
+ catalog, SearchResponse(200, {}, json.dumps({"result": {"content": [{"type": "text", "text": text}]}}).encode()),
+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,
+ )
+ assert result.record["status"] == "completed"
+ assert result.record["content"] == text
+ assert result.record["title"] is None and result.record["final_url"] is None
+ assert not result.cooling and not result.target_failure
+
+
[email protected]("overflow", [False, True])
+async def test_extractor_overflow_survives_short_normalized_content_into_record_and_frame(tmp_path, overflow):
+ """Extractor pre-capping can lose the tail even when later sanitization makes the result tiny."""
+ from core.agent_core.web_fetch import BUDGET_MARKER, fetch_record_from_dict, frame_fetch_record
+ from core.web_fetch_worker.extract import extract_page
+
+ service, config = _service(
+ tmp_path, enabled={LOCAL: True, EXA: False, FREE_EXA: False, JINA: False}, order=(LOCAL,),
+ )
+ source = b"Retained paragraph.\n\n<script>" + b"x" * (200000 if overflow else 20) + b"</script>\n\nFinal paragraph."
+
+ async def fetch(url, *, deadline, on_sent):
+ on_sent()
+ page = await asyncio.to_thread(extract_page, source, "text/markdown", url)
+ assert page.content_overflow is overflow
+ assert len(page.content.encode()) < 1000
+ return {**page.payload(), "sent": True, "source_size_bytes": len(source), "final_url": url}
+
+ service._local_fetch_engine.fetch = fetch
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}}, turn=service.freeze_turn_hosted_tools(config),
+ )
+ record = fetch_record_from_dict(result["record"])
+ assert record.status == "completed" and record.truncated is overflow
+ assert record.truncation_reason == ("budget" if overflow else None)
+ assert (BUDGET_MARKER in frame_fetch_record(record)) is overflow
+ assert ("Final paragraph." in record.content) is (not overflow)
+ assert "content_overflow" not in result["record"]
+
+
+class _Local:
+ def __init__(self):
+ self.checks = 0
+
+ async def check(self, url, *, deadline):
+ self.checks += 1
+
+ async def fetch(self, url, *, deadline, on_sent=None):
+ if on_sent is not None:
+ on_sent()
+ return {
+ "content": "local page",
+ "content_type": "text/markdown",
+ "final_url": url,
+ "source_size_bytes": 10,
+ "sent": True,
+ }
+
+
+def _service(tmp_path: Path, *, enabled: dict[str, bool], order=(LOCAL, EXA), vendor="exa"):
+ service = owner(tmp_path, (vendor,) if vendor else (), include_keyless=False)
+ raw = fetch_config().hosted_tools["web_fetch"]
+ saved = {sid: ModelHubFetchServiceSettings(enabled=value) for sid, value in enabled.items()}
+ config = service.store.config
+ config.hosted_tools["web_fetch"] = replace(
+ raw,
+ services=saved,
+ executor_order=order,
+ executor_order_kinds={sid: ("local" if sid == LOCAL else "service") for sid in order},
+ )
+ service.store.config = config
+ service._local_fetch_engine = _Local()
+ hosted_tools.WEB_FETCH_ACTIVE = True
+ return service, config
+
+
+async def test_flag_off_rejects_fetch_without_running_gate_or_adapter(tmp_path, monkeypatch):
+ service, config = _service(tmp_path, enabled={LOCAL: True, EXA: True, FREE_EXA: False, JINA: False})
+ turn = service.freeze_turn_hosted_tools(config)
+ hosted_tools.WEB_FETCH_ACTIVE = False
+ called = []
+ monkeypatch.setattr(service.adapter, "fetch", lambda *args, **kwargs: called.append(args), raising=False)
+ with pytest.raises(ModelHubError) as raised:
+ await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=turn,
+ )
+ assert raised.value.code == "tool_not_enabled"
+ assert called == []
+
+
+async def test_local_sent_attempt_is_recorded_as_exact_zero_fetch_usage(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: True, EXA: False, FREE_EXA: False, JINA: False},
+ order=(LOCAL, EXA),
+ )
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["status"] == "completed"
+ assert result["record"]["attempts"][0]["kind"] == "local"
+ assert result["execution"]["executor_origin"]["api"] == "local_fetch"
+ assert result["execution"]["cost"] == {"basis": "list", "usd": 0}
+ row = next(row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch")
+ assert row["requests"] == 1 and row["billable_requests"] == 0 and row["uncertain_requests"] == 0
+
+
+async def test_disabled_candidates_are_skipped_and_never_metered(tmp_path):
+ service, config = _service(
+ tmp_path, vendor=None,
+ enabled={LOCAL: False, FREE_EXA: False, JINA: False},
+ order=(LOCAL,),
+ )
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["status"] == "failed"
+ assert result["record"]["error_code"] == "fetch_sources_blocked"
+ assert all(attempt["outcome"] == "skipped" for attempt in result["record"]["attempts"])
+ assert service.usage_summary(days=7)["services"] == []
+
+
+async def test_keyless_target_failure_is_sent_but_does_not_cool_shared_service(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: False},
+ order=(FREE_EXA,),
+ )
+
+ async def fetch(source_id, vendor, service_id, credential_ref, request, *, on_sent):
+ await on_sent()
+ return SearchResponse(
+ 200,
+ {},
+ json.dumps({"result": {"content": [{"type": "text", "text": "No content found."}]}}).encode(),
+ )
+
+ service.adapter.fetch = fetch
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["error_code"] == "fetch_target_unreadable"
+ source = model_hub_builtin_source(FREE_EXA)
+ assert service._service_cooldowns.until(source, "exa/mcp", service.now()) is None
+ row = next(row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch")
+ assert row["requests"] == 1 and row["billable_requests"] == 0
+
+
+async def test_remote_submission_rechecks_original_url_gate(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: False},
+ order=(FREE_EXA,),
+ )
+
+ async def fetch(source_id, vendor, service_id, credential_ref, request, *, on_sent):
+ await on_sent()
+ body = {"result": {"structuredContent": {"content": "body", "title": "T", "url": request["urls"][0]}}}
+ return SearchResponse(200, {}, json.dumps(body).encode())
+
+ service.adapter.fetch = fetch
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["status"] == "completed"
+ assert service._local_fetch_engine.checks == 2
+
+
+async def test_keyless_mcp_fetch_is_free_and_preserves_record_shape(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: False},
+ order=(FREE_EXA,),
+ )
+
+ async def fetch(source_id, vendor, service_id, credential_ref, request, *, on_sent):
+ await on_sent()
+ body = {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "result": {
+ "structuredContent": {
+ "content": "keyless body",
+ "title": "Free title",
+ "url": request["urls"][0],
+ }
+ },
+ }
+ return SearchResponse(200, {}, json.dumps(body).encode())
+
+ service.adapter.fetch = fetch
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["status"] == "completed"
+ assert result["record"]["content"] == "keyless body"
+ row = next(row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch")
+ assert row["requests"] == 1 and row["billable_requests"] == 0
+
+
+async def test_pre_send_service_result_is_skipped_without_usage_or_cooldown(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: False},
+ order=(FREE_EXA,),
+ )
+
+ async def fetch(*args, **kwargs):
+ return SearchResponse(None, {}, None, "invalid_endpoint")
+
+ service.adapter.fetch = fetch
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["status"] == "failed"
+ assert result["record"]["error_code"] == "fetch_unavailable"
+ assert result["record"]["attempts"][0]["outcome"] == "skipped"
+ assert service.usage_summary(days=7)["services"] == []
+ assert service.capability_evidence.records() == []
+ source = model_hub_builtin_source(FREE_EXA)
+ assert service._service_cooldowns.until(source, "exa/mcp", service.now()) is None
+
+
+async def test_local_failure_code_survives_record_cleanup(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: True, EXA: False, FREE_EXA: False, JINA: False},
+ order=(LOCAL,),
+ )
+
+ class FailedLocal:
+ async def check(self, url, *, deadline):
+ return url
+
+ async def fetch(self, url, *, deadline, on_sent=None):
+ on_sent()
+ return {"error_code": "fetch_url_blocked", "terminal": True, "sent": True}
+
+ service._local_fetch_engine = FailedLocal()
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["error_code"] == "fetch_url_blocked"
+ assert result["record"]["attempts"][0]["error_code"] == "fetch_url_blocked"
+
+
+async def test_jina_rolling_minute_budget_is_reserved_before_send(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: False, EXA: False, FREE_EXA: False, JINA: True},
+ order=(JINA,),
+ )
+ service._jina_fetch_sent_at.extend([service.now()] * 20)
+ sent = []
+
+ async def fetch(*args, on_sent):
+ await on_sent()
+ sent.append(True)
+ return SearchResponse(200, {}, json.dumps({"data": {"content": "body"}}).encode())
+
+ service.adapter.fetch = fetch
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["attempts"][0]["skipped"] == "cooling"
+ assert result["record"]["attempts"][0]["retry_at"]
+ assert sent == []
+ assert service.usage_summary(days=7)["services"] == []
+
+
+async def test_remote_mapping_cancellation_waits_for_sent_settlement(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: False},
+ order=(FREE_EXA,),
+ )
+ mapping_started = threading.Event()
+ release_mapping = threading.Event()
+ original_mapper = fetch_chain_module.map_fetch_response
+
+ def blocked_mapper(*args, **kwargs):
+ mapping_started.set()
+ assert release_mapping.wait(10)
+ return original_mapper(*args, **kwargs)
+
+ fetch_chain_module.map_fetch_response = blocked_mapper
+ try:
+ async def fetch(*args, on_sent):
+ await on_sent()
+ return SearchResponse(200, {}, json.dumps({"result": {"structuredContent": {"content": "body"}}}).encode())
+
+ service.adapter.fetch = fetch
+ task = asyncio.create_task(service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ ))
+ assert await asyncio.to_thread(mapping_started.wait, 10)
+ task.cancel()
+ release_mapping.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ release_mapping.set()
+ fetch_chain_module.map_fetch_response = original_mapper
+ row = next(row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch")
+ assert row["requests"] == 1
+
+
+async def test_sent_local_cancellation_is_metered(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: True, EXA: False, FREE_EXA: False, JINA: False},
+ order=(LOCAL,),
+ )
+ started = asyncio.Event()
+
+ class HangingLocal:
+ async def check(self, url, *, deadline):
+ return url
+
+ async def fetch(self, url, *, deadline, on_sent=None):
+ on_sent()
+ started.set()
+ await asyncio.Event().wait()
+
+ service._local_fetch_engine = HangingLocal()
+ task = asyncio.create_task(service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ ))
+ await started.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ row = next(row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch")
+ assert row["requests"] == 1 and row["billable_requests"] == 0
+
+
[email protected]("local_succeeded", [False, True])
+async def test_cancellation_during_local_usage_drains_once_and_cannot_return_or_fallback(tmp_path, monkeypatch, local_succeeded):
+ """Stop can arrive after transport completes; draining is not permission to continue the chain."""
+ service, config = _service(
+ tmp_path, enabled={LOCAL: True, EXA: False, FREE_EXA: True, JINA: True}, order=(LOCAL, FREE_EXA, JINA),
+ )
+ waiting, release = asyncio.Event(), asyncio.Event()
+ original_wait = service.usage_writer.wait_recorded
+ remote_calls = []
+
+ async def wait_recorded(write):
+ waiting.set()
+ await release.wait()
+ await original_wait(write)
+
+ async def local(url, *, deadline, on_sent):
+ on_sent()
+ return ({"sent": True, "content": "Finished local page"} if local_succeeded else
+ {"sent": True, "error_code": "fetch_challenge", "terminal": False})
+
+ async def fetch(*args, **kwargs):
+ remote_calls.append(args)
+ raise AssertionError("Stop must not forward the URL to the next provider")
+
+ monkeypatch.setattr(service.usage_writer, "wait_recorded", wait_recorded)
+ service._local_fetch_engine.fetch = local
+ service.adapter.fetch = fetch
+ task = asyncio.create_task(service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}}, turn=service.freeze_turn_hosted_tools(config),
+ ))
+ try:
+ await asyncio.wait_for(waiting.wait(), 2)
+ task.cancel()
+ await asyncio.sleep(0)
+ task.cancel()
+ await asyncio.sleep(0)
+ assert not task.done()
+ release.set()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ finally:
+ release.set()
+ if not task.done():
+ task.cancel()
+ await asyncio.gather(task, return_exceptions=True)
+ assert remote_calls == []
+ rows = service.usage_summary(days=7)["services"]
+ assert len(rows) == 1 and rows[0]["source_id"] == LOCAL and rows[0]["requests"] == 1
+ assert rows[0]["billable_requests"] == rows[0]["uncertain_requests"] == 0
+ assert service.capability_evidence.records() == []
+
+
+async def test_sent_local_redirect_skip_is_a_failed_metered_attempt(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: True, EXA: False, FREE_EXA: False, JINA: False},
+ order=(LOCAL,),
+ )
+
+ class RedirectCoolingLocal:
+ async def check(self, url, *, deadline):
+ return url
+
+ async def fetch(self, url, *, deadline, on_sent=None):
+ on_sent()
+ return {"error_code": "fetch_unavailable", "skipped": "cooling", "sent": True}
+
+ service._local_fetch_engine = RedirectCoolingLocal()
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"]["status"] == "failed"
+ assert result["record"]["attempts"][0]["outcome"] == "failed"
+ row = next(row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch")
+ assert row["requests"] == 1
+
+
+async def test_cancellation_settles_a_sent_fetch_before_rethrowing(tmp_path):
+ service, config = _service(
+ tmp_path,
+ enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: False},
+ order=(FREE_EXA,),
+ )
+ started = asyncio.Event()
+
+ async def fetch(source_id, vendor, service_id, credential_ref, request, *, on_sent):
+ await on_sent()
+ started.set()
+ await asyncio.Event().wait()
+
+ service.adapter.fetch = fetch
+ task = asyncio.create_task(service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://example.com/"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ ))
+ await started.wait()
+ task.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await task
+ row = next(row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch")
+ assert row["requests"] == 1
+ source = model_hub_builtin_source(FREE_EXA)
+ assert service._service_cooldowns.until(source, "exa/mcp", service.now()) is None
diff --git a/tests/test_model_hub_keyless_exa.py b/tests/test_model_hub_keyless_exa.py
index 980a132b5..d386005ca 100644
--- a/tests/test_model_hub_keyless_exa.py
+++ b/tests/test_model_hub_keyless_exa.py
@@ -49,6 +49,7 @@ async def _mcp_stub(
stale_tools_once: bool = False,
invalid_init_once: bool = False,
notification_status: int | None = None,
+ fetch_schema: dict | None = None,
):
calls: list[dict] = []
state = {"session": "stub-session-1", "stale_tools": stale_tools_once, "invalid_init": invalid_init_once}
@@ -77,7 +78,10 @@ async def _mcp_stub(
if state["stale_tools"]:
state["stale_tools"] = False
return web.json_response({"error": {"message": "MCP session not found"}}, status=404)
- return web.json_response(_rpc(request_id, {"tools": [_tool_schema(missing=missing)]}))
+ tools = [_tool_schema(missing=missing)]
+ if fetch_schema is not None:
+ tools.append({"name": "web_fetch_exa", "inputSchema": fetch_schema})
+ return web.json_response(_rpc(request_id, {"tools": tools}))
if method == "tools/call":
result = {
"content": [{"type": "text", "text": json.dumps({
@@ -90,6 +94,8 @@ async def _mcp_stub(
}],
})}],
}
+ if payload["params"]["name"] == "web_fetch_exa":
+ result = {"content": [{"type": "text", "text": "# Fetched page\nURL: https://example.com/\n\nPage body"}]}
body = json.dumps(_rpc(request_id, result), separators=(",", ":"))
if sse:
return web.Response(
@@ -158,6 +164,53 @@ async def test_keyless_mcp_negotiates_once_adapts_live_schema_and_maps_highlight
assert not mapped.billable and not mapped.uncertain
[email protected]("sse", [False, True])
+async def test_fetch_reuses_search_mcp_session_and_sends_explicit_page_bound(sse):
+ """WF-2G: exercise the real MCP fetch transport, not only an adapter-result fake."""
+ from core.handlers.model_hub.fetch_services import map_fetch_response
+ from vibe.model_hub_runtime.fetch_catalog import fetch_service_catalog
+
+ schema = {"type": "object", "properties": {"urls": {"type": "array"}, "maxCharacters": {"type": "integer"}}, "required": ["urls"]}
+ async with _mcp_stub(sse=sse, fetch_schema=schema) as (endpoint, calls):
+ client = KeylessExaMcpClient(endpoint=endpoint, client_version="test")
+ await client.search({"query": "avibe", "numResults": 1, "enableHighlights": True, "textMaxCharacters": 1})
+ sent = []
+ response = await client.fetch({"urls": ["https://example.com/"], "maxCharacters": 48000}, on_sent=lambda: sent.append(True))
+ assert [call["payload"]["method"] for call in calls] == [
+ "initialize", "notifications/initialized", "tools/list", "tools/call", "tools/list", "tools/call",
+ ]
+ assert calls[-1]["headers"]["Mcp-Session-Id"] == calls[-3]["headers"]["Mcp-Session-Id"]
+ assert calls[-1]["payload"]["params"] == {
+ "name": "web_fetch_exa", "arguments": {"urls": ["https://example.com/"], "maxCharacters": 48000},
+ }
+ assert sent == [True]
+ catalog = next(entry for entry in fetch_service_catalog() if entry["vendor"] == "exa-mcp")
+ result = map_fetch_response(catalog, response, requested_url="https://example.com/", sent=True, say=lambda key, **_: key)
+ assert result.record["status"] == "completed" and result.record["content"] == "Page body"
+
+
[email protected]("variant", ["missing_bound", "unknown_required", "missing_url"])
+async def test_fetch_incompatible_live_schema_or_arguments_never_send(variant):
+ """WF-2G: a fetch must not drop its cap or send an unsatisfied new required input."""
+ schema = {"type": "object", "properties": {"urls": {"type": "array"}, "maxCharacters": {"type": "integer"}}, "required": ["urls"]}
+ arguments = {"urls": ["https://example.com/"], "maxCharacters": 48000}
+ if variant == "missing_bound":
+ schema["properties"].pop("maxCharacters")
+ elif variant == "unknown_required":
+ schema["properties"]["newControl"] = {"type": "string"}
+ schema["required"].append("newControl")
+ else:
+ arguments.pop("urls")
+ async with _mcp_stub(fetch_schema=schema) as (endpoint, calls):
+ sent = []
+ response = await KeylessExaMcpClient(endpoint=endpoint).fetch(arguments, on_sent=lambda: sent.append(True))
+ assert response.error == "invalid_endpoint"
+ assert sent == []
+ assert [call["payload"]["method"] for call in calls] == ["initialize", "notifications/initialized", "tools/list"]
+
+
@pytest.mark.asyncio
async def test_keyless_mcp_does_not_continue_after_initialized_transport_error() -> None:
"""KEX-2: notification transport failures stop the handshake before tools/list."""
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index ef63f53cb..c26cbd748 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -1266,13 +1266,17 @@ def test_machine_error_field_access_has_one_extractor() -> None:
if path.name == "migration.py":
continue # its ``type`` field is an auth-record kind, not an error code
tree = _tree(path)
- # Request history and declared tools discriminate request items, not
- # error envelopes. Exempt only those functions' type reads; code reads
- # and the rest of request.py remain subject to the extraction-owner guard.
- functions = _functions(tree) if path.name == "request.py" else {}
+ # History, declared tools and MCP content blocks discriminate payload
+ # items, not error envelopes. Exempt only these functions' type reads;
+ # code reads and all other functions still have one extraction owner.
+ type_readers = {
+ "request.py": ("_plain_history", "declared_tool_types", "replays_history_items"),
+ "fetch_services.py": ("_mcp_payload",),
+ }
+ functions = _functions(tree) if path.name in type_readers else {}
history_nodes = {
node
- for name in ("_plain_history", "declared_tool_types", "replays_history_items")
+ for name in type_readers.get(path.name, ())
if (history := functions.get(name)) is not None
for node in ast.walk(history)
}
diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.py
index c13ac7741..b8a52b8bb 100644
--- a/vibe/model_hub_runtime/adapter.py
+++ b/vibe/model_hub_runtime/adapter.py
@@ -67,6 +67,7 @@ from vibe.model_hub_runtime.client import (
probe_models,
upstream_api_url,
)
+from vibe import __version__ as AVIBE_VERSION
from vibe.model_hub_runtime.api_key_vendors import (
anthropic_api_key_header,
pinned_api_key_protocol,
@@ -2062,10 +2063,11 @@ class CLIProxyEngineAdapter:
self,
*,
catalog: Mapping[str, Any],
- credential_ref: str,
+ credential_ref: str | None,
method: str,
endpoint: str,
payload: Mapping[str, Any] | None = None,
+ extra_headers: Mapping[str, str] | None = None,
timeout_total: float = _SEARCH_TIMEOUT_SECONDS,
connect_timeout: float | None = None,
on_sent: Callable[[], Awaitable[None] | None] | None = None,
@@ -2094,18 +2096,28 @@ class CLIProxyEngineAdapter:
):
return SearchResponse(None, {}, None, "invalid_endpoint")
try:
- key = await asyncio.to_thread(self.state_store.read_api_key, credential_ref)
- metadata = await asyncio.to_thread(self.state_store.credential_metadata, credential_ref)
+ if credential_ref is None:
+ key = None
+ metadata = {}
+ else:
+ key = await asyncio.to_thread(self.state_store.read_api_key, credential_ref)
+ metadata = await asyncio.to_thread(self.state_store.credential_metadata, credential_ref)
except Exception:
return SearchResponse(None, {}, None, "connection")
- if vendor is None or metadata.get("vendor") != vendor:
+ if vendor is None or (credential_ref is not None and metadata.get("vendor") != vendor):
return SearchResponse(None, {}, None, "invalid_endpoint")
auth = str(service.get("auth") or "bearer")
headers = {"Accept": "application/json", "Content-Type": "application/json"}
- if auth == "x-api-key":
+ if auth == "x-api-key" and key is not None:
headers["x-api-key"] = key
- else:
+ elif auth != "none" and key is not None:
headers["Authorization"] = f"Bearer {key}"
+ elif auth != "none":
+ return SearchResponse(None, {}, None, "invalid_endpoint")
+ if isinstance(service.get("headers"), Mapping):
+ headers.update({str(name): str(value) for name, value in service["headers"].items()})
+ if extra_headers:
+ headers.update(extra_headers)
timeout = aiohttp.ClientTimeout(total=timeout_total, connect=connect_timeout)
callback_called = False
response_status: int | None = None
@@ -2288,6 +2300,64 @@ class CLIProxyEngineAdapter:
async def revoke_search_credential(self, credential_ref: str) -> None:
await asyncio.to_thread(self.state_store.revoke_search_credential, credential_ref)
+ async def fetch(
+ self,
+ source_id: str,
+ vendor: str,
+ service_id: str,
+ credential_ref: str | None,
+ request: Mapping[str, Any],
+ *,
+ on_sent: Callable[[], Awaitable[None] | None] | None = None,
+ ) -> SearchResponse:
+ from vibe.model_hub_runtime.fetch_catalog import fetch_service_catalog
+
+ if service_id == KEYLESS_EXA_SERVICE_ID:
+ if (
+ not model_hub_config.KEYLESS_EXA_ACTIVE
+ or source_id != KEYLESS_EXA_SOURCE_ID
+ or vendor != "exa-mcp"
+ or credential_ref is not None
+ ):
+ return SearchResponse(None, {}, None, "invalid_endpoint")
+ service = next(
+ (entry for entry in fetch_service_catalog() if entry.get("service_id") == service_id),
+ None,
+ )
+ if service is None:
+ return SearchResponse(None, {}, None, "invalid_endpoint")
+ return await self._keyless_exa_client.fetch(request, on_sent=on_sent)
+
+ # Keyed transports/mappings are delivered separately. This boundary
+ # admits only the exact built-in Reader identity, never a credential.
+ if vendor != "jina-reader" or credential_ref is not None:
+ return SearchResponse(None, {}, None, "invalid_endpoint")
+ service = next(
+ (
+ entry for entry in fetch_service_catalog()
+ if entry.get("service_id") == service_id and entry.get("vendor") == vendor
+ and entry.get("source_id") == source_id
+ ),
+ None,
+ )
+ if service is None or service.get("kind") != "service":
+ return SearchResponse(None, {}, None, "invalid_endpoint")
+ payload = dict(request)
+ request_spec = service.get("request") if isinstance(service.get("request"), Mapping) else {}
+ headers = request_spec.get("headers") if isinstance(request_spec.get("headers"), Mapping) else {}
+ if isinstance(service.get("headers"), Mapping):
+ headers = {**headers, **service["headers"]}
+ headers = {**headers, "User-Agent": f"Avibe/{AVIBE_VERSION}"}
+ return await self._search_http(
+ catalog={"vendor": vendor, **service},
+ credential_ref=credential_ref,
+ method="POST",
+ endpoint=str(service.get("endpoint") or ""),
+ payload=payload,
+ extra_headers=headers,
+ on_sent=on_sent,
+ )
+
async def provision_oauth_credential(
self,
source_id: str,
diff --git a/vibe/model_hub_runtime/keyless_exa_mcp.py b/vibe/model_hub_runtime/keyless_exa_mcp.py
index 57d836040..5fa568489 100644
--- a/vibe/model_hub_runtime/keyless_exa_mcp.py
+++ b/vibe/model_hub_runtime/keyless_exa_mcp.py
@@ -23,12 +23,14 @@ from vibe import __version__ as AVIBE_VERSION
KEYLESS_EXA_ENDPOINT = "https://mcp.exa.ai/mcp?tools=web_search_advanced_exa,web_fetch_exa"
KEYLESS_EXA_SEARCH_TOOL = "web_search_advanced_exa"
+KEYLESS_EXA_FETCH_TOOL = "web_fetch_exa"
MCP_PROTOCOL_VERSION = "2025-06-18"
MCP_SESSION_HEADER = "Mcp-Session-Id"
_MAX_BODY_BYTES = 8 * 1024 * 1024
_TIMEOUT_SECONDS = 30.0
_CONNECT_TIMEOUT_SECONDS = 5.0
_REQUIRED_SEARCH_FIELDS = frozenset({"query", "numResults", "enableHighlights", "textMaxCharacters"})
+_REQUIRED_FETCH_FIELDS = frozenset({"urls", "maxCharacters"})
@dataclass(frozen=True)
@@ -100,7 +102,12 @@ def _session_not_found(exchange: _Exchange) -> bool:
return "session" in text and "not found" in text
-def _tool_properties(tool: Mapping[str, Any], *, require_search_controls: bool = False) -> Mapping[str, Any] | None:
+def _tool_properties(
+ tool: Mapping[str, Any],
+ *,
+ require_search_controls: bool = False,
+ require_fetch_controls: bool = False,
+) -> Mapping[str, Any] | None:
schema = tool.get("inputSchema")
if not isinstance(schema, Mapping):
return None
@@ -109,6 +116,8 @@ def _tool_properties(tool: Mapping[str, Any], *, require_search_controls: bool =
return None
if require_search_controls and not _REQUIRED_SEARCH_FIELDS.issubset(properties):
return None
+ if require_fetch_controls and not _REQUIRED_FETCH_FIELDS.issubset(properties):
+ return None
return properties
@@ -353,12 +362,21 @@ class KeylessExaMcpClient:
properties = _tool_properties(
tool,
require_search_controls=tool_name == KEYLESS_EXA_SEARCH_TOOL,
+ require_fetch_controls=tool_name == KEYLESS_EXA_FETCH_TOOL,
) if isinstance(tool, Mapping) else None
if properties is None:
return SearchResponse(None, {}, None, "invalid_endpoint")
adapted = self._adapt_arguments(properties, arguments)
if adapted is None:
return SearchResponse(None, {}, None, "invalid_endpoint")
+ if tool_name == KEYLESS_EXA_FETCH_TOOL:
+ required = tool["inputSchema"].get("required", [])
+ if (
+ not isinstance(required, list)
+ or not all(isinstance(name, str) and name in adapted for name in required)
+ or not _REQUIRED_FETCH_FIELDS.issubset(adapted)
+ ):
+ return SearchResponse(None, {}, None, "invalid_endpoint")
called = await self._request(
"tools/call",
{"name": tool_name, "arguments": adapted},
@@ -381,6 +399,14 @@ class KeylessExaMcpClient:
) -> SearchResponse:
return await self.call_tool(KEYLESS_EXA_SEARCH_TOOL, arguments, on_sent=on_sent)
+ async def fetch(
+ self,
+ arguments: Mapping[str, Any],
+ *,
+ on_sent: Callable[[], Awaitable[None] | None] | None = None,
+ ) -> SearchResponse:
+ return await self.call_tool(KEYLESS_EXA_FETCH_TOOL, arguments, on_sent=on_sent)
+
@staticmethod
async def _as_search_response(exchange: _Exchange) -> SearchResponse:
body = exchange.body
@@ -412,4 +438,4 @@ class KeylessExaMcpClient:
)
-__all__ = ["KEYLESS_EXA_ENDPOINT", "KEYLESS_EXA_SEARCH_TOOL", "KeylessExaMcpClient"]
+__all__ = ["KEYLESS_EXA_ENDPOINT", "KEYLESS_EXA_SEARCH_TOOL", "KEYLESS_EXA_FETCH_TOOL", "KeylessExaMcpClient"]