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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(model-hub): add keyed web_fetch providers (#2976)
Call White1a1c139ffae5
diff --git a/core/handlers/model_hub/fetch_chain.py b/core/handlers/model_hub/fetch_chain.pyindex 347611603..021776dc8 100644--- a/core/handlers/model_hub/fetch_chain.py+++ b/core/handlers/model_hub/fetch_chain.py@@ -2,8 +2,8 @@The chain freezes order in ``TurnHostedTools`` but rechecks identity, enablementand 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.+isolated in ``LocalFetchEngine``; all remote transports stay behind+``EngineAdapter`` and configured Source health settles through fenced generations."""from __future__ import annotations@@ -110,7 +110,7 @@ class FetchChain: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"}:+ if not service.get("available", False) or service.get("kind") not in {"local", "service"}:fact["skipped"] = "unavailable"return source, service, factif not slot.enabled:@@ -175,7 +175,10 @@ class FetchChain: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}+ cost = {"basis": attempt.cost.basis, "usd": attempt.cost.usd}+ if attempt.cost.estimate is not None:+ cost["estimate"] = attempt.cost.estimate+ fact["cost"] = costreturn factasync def _record_local_usage(self, source, slot):@@ -265,6 +268,7 @@ class FetchChain:sent = Falseresponse: SearchResponse | None = Nonecooldown_generation = None+ health_generation = Noneasync def invoke():nonlocal source, response@@ -275,8 +279,8 @@ class FetchChain:source = currentasync def on_sent():- nonlocal sent, source, cooldown_generation- await self._engine.check(self.requested_url, deadline=self.deadline)+ nonlocal sent, source, cooldown_generation, health_generation+ await self._engine.check(self.requested_url, deadline=attempt_deadline)async with self.owner._mutation_lock:current, _, skip = await self._classify(slot, locked=True)if skip is not None:@@ -298,6 +302,8 @@ class FetchChain:"retry_at": utc_text(retry_at),})cooldown_generation = self.owner._service_cooldowns.advance(source, slot.model_id)+ if service.get("source_id") is None:+ health_generation = self.owner._reserve_settlement_generation(source.id, source=source)sent = Truerequest = self._request_for(service)@@ -356,7 +362,7 @@ class FetchChain:)if stopped:result = replace(result, cooling=False)- await self._settle_owned(source, slot, result, response, cooldown_generation, sent)+ await self._settle_owned(source, slot, result, response, cooldown_generation, health_generation, sent)return resultsettlement = asyncio.create_task(settle_response())@@ -373,9 +379,9 @@ class FetchChain: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):+ async def _settle_owned(self, source, slot, result, response, cooldown_generation, health_generation, sent):await await_owned_task(asyncio.create_task(- self._settle_service(source, slot, result, response, cooldown_generation, sent)+ self._settle_service(source, slot, result, response, cooldown_generation, health_generation, sent)))@staticmethod@@ -393,6 +399,10 @@ class FetchChain:value = urlif value is None:raise ValueError("fetch URL is required")+ limits = service.get("limits") if isinstance(service.get("limits"), Mapping) else {}+ max_chars = limits.get("url_chars")+ if isinstance(max_chars, int) and len(value) > max_chars:+ raise ValueError("fetch URL exceeds provider limit")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@@ -401,7 +411,7 @@ class FetchChain: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):+ async def _settle_service(self, source, slot, result: FetchServiceResult, response, cooldown_generation, health_generation, sent):write = self.owner.usage_writer.record_service(source_id=source.id,service_id=slot.model_id,@@ -417,6 +427,23 @@ class FetchChain: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())+ health_current = (+ identity_current and health_generation is not None+ and self.owner._settlement_current(current, health_generation)+ )+ if health_current and (result.blocker is not None or result.authenticated):+ from config.v2_config import ModelHubSourceStateConfig+ desired_state = (+ ModelHubSourceStateConfig(status="needs_action", detail_key=result.blocker)+ if result.blocker is not None else current.state+ )+ if desired_state != current.state or (result.authenticated and current.verification_pending is not None):+ config = await asyncio.to_thread(self.owner._clone_config, previous)+ updated = self.owner._source(config, source.id)+ updated.state = desired_state+ if result.authenticated:+ updated.verification_pending = None+ await self.owner._save_runtime_config(previous, config)if write is not None:await self.owner.usage_writer.wait_recorded(write)if sent and result.record.get("status") == "completed":diff --git a/core/handlers/model_hub/fetch_services.py b/core/handlers/model_hub/fetch_services.pyindex 443e62091..93bd958df 100644--- a/core/handlers/model_hub/fetch_services.py+++ b/core/handlers/model_hub/fetch_services.py@@ -1,12 +1,13 @@-"""Keyless web-fetch service mappings.+"""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.+The adapter owns credential custody and bounded HTTP/MCP transport. This module+maps one completed response into fetch facts, billing evidence and target/service+scope; it never decides chain order or writes Source health."""from __future__ import annotationsimport json+import mathimport refrom dataclasses import dataclassfrom typing import Any, Callable, Mapping@@ -165,6 +166,29 @@ def _url_value(value: Any) -> str | None:return value+def _url_matches(value: Any, requested_url: str) -> bool:+ if not isinstance(value, str):+ return False+ if value == requested_url:+ return True+ try:+ left, right = urlsplit(value), urlsplit(requested_url)+ left_port, right_port = left.port, right.port+ except ValueError:+ return False+ return (+ left.username is None and left.password is None+ and right.username is None and right.password is None+ and left.scheme.lower() == right.scheme.lower()+ and (left.hostname or "").lower() == (right.hostname or "").lower()+ and left_port == right_port+ and left.path.rstrip("/") == right.path.rstrip("/")+ and left.query == right.query+ and not left.fragment+ and not right.fragment+ )++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"))@@ -193,6 +217,74 @@ def _content(service: Mapping[str, Any], body: Mapping[str, Any] | None) -> tupl)+def _configured_content(+ service: Mapping[str, Any], body: Mapping[str, Any] | None, requested_url: str,+) -> tuple[str, str | None, str | None, bool]:+ """Return success/target/malformed plus bounded content facts for keyed APIs."""+ vendor = str(service.get("vendor") or "")+ result = service.get("result") if isinstance(service.get("result"), Mapping) else {}+ if not isinstance(body, Mapping):+ return "malformed", None, None, False+ if vendor == "tavily":+ rows = _path(body, result.get("items"))+ failures = _path(body, result.get("failures"))+ if not isinstance(rows, list) or not isinstance(failures, list):+ return "malformed", None, None, False+ if any(not isinstance(row, Mapping) for row in (*rows, *failures)):+ return "malformed", None, None, False+ row = next((item for item in rows if _url_matches(item.get("url"), requested_url)), None)+ if row is None:+ failure = next((item for item in failures if _url_matches(item.get("url"), requested_url)), None)+ return ("target", None, None, False) if failure is not None else ("malformed", None, None, False)+ content = row.get(result.get("content", "raw_content"))+ if not isinstance(content, str) or not content.strip():+ return "target", None, None, False+ title = row.get(result.get("title", "title"))+ return "success", content, title[:300] if isinstance(title, str) else None, False+ if vendor == "exa":+ rows = _path(body, result.get("items", "results"))+ statuses = _path(body, result.get("statuses"))+ if not isinstance(rows, list) or not isinstance(statuses, list):+ return "malformed", None, None, False+ if any(not isinstance(row, Mapping) for row in rows) or any(not isinstance(item, Mapping) for item in statuses):+ return "malformed", None, None, False+ row = next(+ (item for item in rows if _url_matches(item.get("id"), requested_url) or _url_matches(item.get("url"), requested_url)),+ None,+ )+ status_row = next(+ (item for item in statuses if _url_matches(item.get("id"), requested_url) or _url_matches(item.get("url"), requested_url)),+ statuses[0] if len(statuses) == 1 and not any(item.get("id") or item.get("url") for item in statuses) else None,+ )+ if status_row is None or not isinstance(status_row.get("status"), str):+ return "malformed", None, None, False+ status_ok = status_row["status"].lower() in {"success", "completed"}+ if row is None:+ return ("malformed", None, None, False) if status_ok else ("target", None, None, False)+ if not status_ok:+ return "target", None, None, False+ content = row.get(result.get("content", "text"))+ if not isinstance(content, str) or not content.strip():+ return "target", None, None, False+ title = row.get(result.get("title", "title"))+ provider_truncated = any(+ value is True+ for key, value in _nested(body)+ if key.lower() in {"truncated", "istruncated", "is_truncated"}+ )+ return "success", content, title[:300] if isinstance(title, str) else None, provider_truncated+ if vendor == "deepseek":+ content_key = result.get("content", "content")+ if content_key not in body or not isinstance(body.get(content_key), str):+ return "malformed", None, None, False+ content = body[content_key]+ if not content.strip():+ return "target", None, None, False+ title = body.get(result.get("title", "title"))+ return "success", content, title[:300] if isinstance(title, str) else None, False+ return "malformed", None, None, False++@dataclass(frozen=True)class FetchServiceResult:record: dict[str, Any]@@ -204,6 +296,7 @@ class FetchServiceResult:target_failure: bool = Falseretry_after: str | None = Nonereported_usd: float | None = None+ authenticated: bool = Falsedef _failed(code: str, say: Callable[..., str], *, detail: str | None = None) -> dict[str, Any]:@@ -221,13 +314,16 @@ def map_fetch_response(sent: bool,say: Callable[..., str],) -> FetchServiceResult:- """Map one service response, keeping target failures separate from service health."""+ """Map one completed response without confusing target facts with service health."""body, decoded = _decode(response.body)status = response.http_statusoutcomes = 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")+ if vendor not in {"exa-mcp", "jina-reader", "tavily", "exa", "deepseek"}:+ raise ValueError("unsupported web-fetch service mapping")+ free = bool(service.get("source_id"))+ billing = service.get("billing") if isinstance(service.get("billing"), Mapping) else {}+ unbilled_errors = {str(item) for item in billing.get("unbilled_errors", ())}mcp_error = Falsemcp_target_failure = Falseif vendor == "exa-mcp":@@ -238,7 +334,20 @@ def map_fetch_response(refusal_tags = {str(item).upper() for item in outcomes.get("refusal_tags", ())}code: str | None = Nonetarget_failure = False- if status == 429:+ uncertain = False+ authenticated = False+ content = title = final_url = None+ provider_truncated = False++ if status in set(outcomes.get("credential") or ()):+ code = "service_key_invalid"+ elif status in set(outcomes.get("balance") or ()):+ code = "service_balance"+ authenticated = True+ elif status in set(outcomes.get("limit") or ()):+ code = "service_limit"+ authenticated = True+ elif status == 429:code = "service_rate_limited"elif status in set(outcomes.get("refused") or ()):code = "service_refused"@@ -246,7 +355,7 @@ def map_fetch_response(code, target_failure = "fetch_target_unreadable", Trueelif vendor == "exa-mcp" and _keyless_rate_limited(status, body):code = "service_rate_limited"- elif mcp_error and tag and tag in refusal_tags:+ elif tag and tag in refusal_tags and (vendor != "exa-mcp" or mcp_error):code = "service_refused"elif vendor == "exa-mcp" and mcp_target_failure:code, target_failure = "fetch_target_unreadable", True@@ -259,42 +368,89 @@ def map_fetch_response(code = "service_refused"else:code = "service_unavailable"+ elif response.error in {"timeout", "connection", "redirect", "body_too_large", "invalid_endpoint", "cancelled"} and status != 200:+ code = "service_unreadable" if response.error == "body_too_large" else "service_unavailable"+ uncertain = sent and not free and response.error not in unbilled_errors and status is Noneelif status == 200 and not decoded:- # A provider envelope that cannot be decoded is a service fault, not- # evidence that this particular target was unreadable.+ # A 200 whose body cannot be recovered is not evidence of an empty target.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"+ uncertain = sent and not freeelif status != 200:code = "service_unavailable" if status is None or status >= 500 else "service_refused"+ elif vendor in {"tavily", "exa", "deepseek"}:+ outcome, content, title, provider_truncated = _configured_content(service, body, requested_url)+ if outcome == "malformed":+ code, uncertain = "service_unreadable", sent and not free+ elif outcome == "target":+ code, target_failure = "fetch_target_unreadable", True+ else:+ if vendor == "exa" and isinstance(body, Mapping):+ rows = _path(body, (service.get("result") or {}).get("items", "results"))+ row = next(+ (item for item in rows if isinstance(item, Mapping)+ and (_url_matches(item.get("id"), requested_url) or _url_matches(item.get("url"), requested_url))),+ None,+ ) if isinstance(rows, list) else None+ final_url = _url_value(row.get((service.get("result") or {}).get("url", "url"))) if row else None+ authenticated = Trueelse:content, title, final_url, provider_truncated = _content(service, body)if content is None:code, target_failure = "fetch_target_unreadable", Trueelse:- 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)+ authenticated = True++ if status == 200 and vendor in {"tavily", "exa", "deepseek"}:+ # A response from the configured endpoint is positive credential+ # evidence even when its body is malformed or target-scoped.+ authenticated = Trueif code is None:- code = "service_unavailable"- result = FetchServiceResult(+ listed = float((service.get("price") or {}).get("usd_per_1k", 0)) / 1000+ if free:+ cost = ZERO if sent else None+ return FetchServiceResult(+ {"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},+ cost, False, False, None, False, retry_after=retry_after, authenticated=True,+ )+ reported_usd = None+ result_spec = service.get("result") if isinstance(service.get("result"), Mapping) else {}+ reported_spec = result_spec.get("reported_cost") if isinstance(result_spec.get("reported_cost"), Mapping) else None+ reported = _path(body, reported_spec.get("path")) if reported_spec else None+ ceiling = reported_spec.get("max_usd") if reported_spec else None+ if not isinstance(ceiling, (int, float)) or isinstance(ceiling, bool) or ceiling < 0:+ ceiling = listed * 100+ if isinstance(reported, (int, float)) and not isinstance(reported, bool):+ try:+ if math.isfinite(float(reported)) and 0 <= float(reported) <= float(ceiling):+ reported_usd = float(reported)+ except (OverflowError, ValueError):+ pass+ cost = HostedCost(+ basis="reported", usd=reported_usd, estimate=bool(reported_spec.get("estimate"))+ ) if reported_usd is not None else HostedCost(basis="list", usd=listed)+ return FetchServiceResult(+ {"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},+ cost if sent else None, bool(sent), False, None, False,+ retry_after=retry_after, reported_usd=reported_usd, authenticated=True,+ )++ blocker = {+ "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",+ }.get(code)+ return FetchServiceResult(_failed(code, say, detail=_provider_error(body) if code == "service_refused" else None),- ZERO if sent else None,- False,+ ZERO if sent and not uncertain else None,False,- None,+ uncertain,+ blocker,not target_failure and code in {"service_unavailable", "service_unreadable", "service_rate_limited"},target_failure,retry_after,- reported_usd=None,+ authenticated=authenticated,)- return resultdiff --git a/core/handlers/model_hub/service.py b/core/handlers/model_hub/service.pyindex be8d86f46..47e3f8962 100644--- a/core/handlers/model_hub/service.py+++ b/core/handlers/model_hub/service.py@@ -7329,8 +7329,9 @@ class ModelHubService:on after a failure normal routing fails over from, a narrow-rulerefusal, a refusal of the executor model, or a failure mid-response;any other outcome ends it. Every candidate called is metered on its own- Source. A proxy call never changes Source health: it is a tool call,- not the turn's model hop.+ Source. A proxy call may update service-local retry state; configured+ Source health changes only from an actual sent provider outcome and+ remains identity/generation fenced."""def say(key: str, **params: str) -> str:diff --git a/tests/test_model_hub_fetch_chain.py b/tests/test_model_hub_fetch_chain.pyindex 52b0cfb54..c7ab86d48 100644--- a/tests/test_model_hub_fetch_chain.py+++ b/tests/test_model_hub_fetch_chain.py@@ -10,7 +10,7 @@ from pathlib import Pathimport pytest-from config.v2_config import ModelHubFetchServiceSettings, model_hub_builtin_source+from config.v2_config import ModelHubFetchServiceSettings, ModelHubSourceStateConfig, model_hub_builtin_sourcefrom core.handlers.model_hub import fetch_chain as fetch_chain_modulefrom core.handlers.model_hub import hosted_toolsfrom core.handlers.model_hub.adapter import SearchResponse@@ -95,7 +95,7 @@ def test_http_200_malformed_provider_envelopes_are_service_failures(body, vendor@pytest.mark.asyncio@pytest.mark.parametrize("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."""+ """The activation flag still blocks the new producer while the adapter is ready for hermetic tests."""sid = IDS[vendor]service, config = _service(tmp_path, vendor=vendor,@@ -108,19 +108,29 @@ async def test_configured_fetch_is_dormant_at_chain_and_adapter_boundaries(tmp_praise 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() == []+ turn = service.freeze_turn_hosted_tools(config)+ hosted_tools.WEB_FETCH_ACTIVE = 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"adapter = object.__new__(CLIProxyEngineAdapter)- adapter._search_http = unexpected+ captured = {}++ async def transport(**kwargs):+ captured.update(kwargs)+ return SearchResponse(200, {}, b"{}")++ adapter._search_http = transportcatalog = 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"+ request = dict(catalog["request"]["fixed"])+ request[catalog["request"]["url_field"]] = ["https://example.com/"] if catalog["request"]["url_array"] else "https://example.com/"+ response = await adapter.fetch(sid, vendor, catalog["service_id"], f"cred_{sid}", request)+ assert response.http_status == 200+ assert captured["endpoint"] == catalog["endpoint"]+ assert captured["payload"] == requestassert calls == []@@ -333,6 +343,256 @@ async def test_extractor_overflow_survives_short_normalized_content_into_record_assert ("Final paragraph." in record.content) is (not overflow)assert "content_overflow" not in result["record"][email protected]("vendor,body,expected_request,expected_cost", [+ ("tavily", {"results": [{"url": "https://example.com/", "raw_content": "Tavily body", "title": "T"}], "failed_results": []},+ {"urls": ["https://example.com/"], "extract_depth": "basic", "format": "markdown"}, 0.0016),+ ("exa", {"results": [{"id": "https://example.com/", "url": "https://final.example/", "text": "Exa body", "title": "E"}],+ "statuses": [{"id": "https://example.com/", "status": "success"}], "costDollars": {"total": 0.02}},+ {"ids": ["https://example.com/"], "text": {"maxCharacters": 48000}}, 0.02),+ ("deepseek", {"title": "D", "content": "DeepSeek body"}, {"url": "https://example.com/"}, 0.00075),+])+async def test_configured_fetch_maps_request_content_cost_and_source_success(+ tmp_path, vendor, body, expected_request, expected_cost,+):+ 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 fetch(source_id, actual_vendor, service_id, credential_ref, request, *, on_sent):+ calls.append((source_id, actual_vendor, service_id, credential_ref, request))+ await on_sent()+ 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"] in {"Tavily body", "Exa body", "DeepSeek body"}+ assert result["execution"]["cost"]["usd"] == expected_cost+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == vendor)+ assert result["record"]["attempts"][0]["cost"] == (+ {"basis": "reported", "usd": expected_cost, "estimate": True}+ if vendor == "exa" else {"basis": "list", "usd": expected_cost}+ )+ assert calls == [(sid, vendor, catalog["service_id"], f"cred_{sid}", expected_request)]+ row = next(row for row in service.usage_summary(days=7)["services"] if row["tool"] == "web_fetch")+ assert row["requests"] == row["billable_requests"] == 1+ assert service.store.load().sources[0].state.status == "standby"++[email protected]("vendor,body", [+ ("tavily", {"results": [], "failed_results": [{"url": "https://example.com/", "error": "blocked"}]}),+ ("exa", {"results": [{"id": "https://example.com/", "text": ""}], "statuses": [{"id": "https://example.com/", "status": "error"}]}),+])+def test_configured_target_failures_do_not_cool_or_mark_source(tmp_path, vendor, body):+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == vendor)+ result = map_fetch_response(+ catalog, SearchResponse(200, {}, json.dumps(body).encode()),+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,+ )+ assert result.record["error_code"] == "fetch_target_unreadable"+ assert result.target_failure and not result.cooling and not result.uncertain+ assert result.cost is not None and result.cost.usd == 0 and not result.billable+++def test_tavily_nonmatching_failure_is_malformed_service_evidence():+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == "tavily")+ body = {"results": [], "failed_results": [{"url": "https://other.example/", "error": "blocked"}]}+ result = map_fetch_response(+ catalog, SearchResponse(200, {}, json.dumps(body).encode()),+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,+ )+ assert result.record["error_code"] == "service_unreadable"+ assert result.uncertain and result.cooling and result.cost is None+++def test_exa_nonmatching_status_is_malformed_service_evidence():+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == "exa")+ body = {+ "results": [],+ "statuses": [{"id": "https://other.example/", "status": "error"}],+ }+ result = map_fetch_response(+ catalog, SearchResponse(200, {}, json.dumps(body).encode()),+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,+ )+ assert result.record["error_code"] == "service_unreadable"+ assert result.uncertain and result.cooling and result.cost is None++[email protected]("vendor,status,body,error,expected_code,expected_usd,expected_billable,expected_uncertain", [+ ("tavily", 503, {}, "", "service_unavailable", 0, False, False),+ ("exa", 429, {}, "", "service_rate_limited", 0, False, False),+ ("deepseek", 401, {}, "", "service_key_invalid", 0, False, False),+ ("deepseek", 404, {}, "", "fetch_target_unreadable", 0, False, False),+ ("deepseek", None, {}, "timeout", "service_unavailable", 0, False, False),+ ("deepseek", None, {}, "connection", "service_unavailable", None, False, True),+ ("exa", None, {}, "timeout", "service_unavailable", None, False, True),+ ("deepseek", 200, {"title": "missing content"}, "", "service_unreadable", None, False, True),+ ("tavily", 200, {"results": [], "failed_results": [{"url": "https://example.com/"}]}, "",+ "fetch_target_unreadable", 0, False, False),+])+def test_configured_billing_distinguishes_known_zero_from_unknown_sent_cost(+ vendor, status, body, error, expected_code, expected_usd, expected_billable, expected_uncertain,+):+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == vendor)+ result = map_fetch_response(+ catalog, SearchResponse(status, {}, json.dumps(body).encode() if status is not None else None, error),+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,+ )+ assert result.record["error_code"] == expected_code+ assert result.billable is expected_billable and result.uncertain is expected_uncertain+ assert (None if result.cost is None else result.cost.usd) == expected_usd+++def test_configured_url_matching_rejects_malformed_provider_urls_without_mapper_failure():+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == "exa")+ body = {+ "results": [{"id": "https://example.com:bad/", "text": "body"}],+ "statuses": [{"id": "https://example.com:bad/", "status": "success"}],+ }+ result = map_fetch_response(+ catalog, SearchResponse(200, {}, json.dumps(body).encode()),+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,+ )+ assert result.record["error_code"] == "service_unreadable"+ assert result.uncertain and result.cooling and result.cost is None+++def test_deepseek_200_unrecoverable_body_is_uncertain_and_cooling():+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == "deepseek")+ result = map_fetch_response(+ catalog, SearchResponse(200, {}, b'{"title":"missing content"}'),+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,+ )+ assert result.record["error_code"] == "service_unreadable"+ assert result.uncertain and result.cooling and result.cost is None+++def test_exa_reported_cost_outside_catalog_ceiling_falls_back_to_list_estimate():+ catalog = next(item for item in fetch_service_catalog() if item["vendor"] == "exa")+ body = {"results": [{"id": "https://example.com/", "text": "body"}],+ "statuses": [{"id": "https://example.com/", "status": "success"}],+ "costDollars": {"total": 0.1001}}+ result = map_fetch_response(+ catalog, SearchResponse(200, {}, json.dumps(body).encode()),+ requested_url="https://example.com/", sent=True, say=lambda key, **_: key,+ )+ assert result.cost == result.cost.__class__(basis="list", usd=0.001)+ assert result.reported_usd is None+++async def test_stale_configured_fetch_health_generation_cannot_overwrite_newer_source(tmp_path):+ sid = IDS["deepseek"]+ service, config = _service(+ tmp_path, vendor="deepseek",+ enabled={LOCAL: False, FREE_EXA: False, JINA: False, sid: True}, order=(sid,),+ )++ async def fetch(*args, on_sent):+ await on_sent()+ service._reserve_settlement_generation(sid, source=service.store.load().sources[0])+ return SearchResponse(401, {}, 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_key_invalid"+ assert service.store.load().sources[0].state.status == "standby"+++async def test_paid_sent_cancellation_is_uncertain_and_does_not_cool(tmp_path):+ service, config = _service(+ tmp_path, vendor="deepseek",+ enabled={LOCAL: False, FREE_EXA: False, JINA: False, IDS["deepseek"]: True},+ order=(IDS["deepseek"],),+ )+ started = asyncio.Event()++ async def fetch(*args, 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 and row["billable_requests"] == 0 and row["uncertain_requests"] == 1+ assert service._service_cooldowns.until(service.store.load().sources[0], "deepseek/fetch", service.now()) is None++[email protected]("vendor,status,detail", [+ ("deepseek", 401, "credential_revoked"),+ ("tavily", 432, "spend_limit_reached"),+])+async def test_configured_blocker_response_settles_source_health(tmp_path, vendor, status, detail):+ sid = IDS[vendor]+ service, config = _service(+ tmp_path, vendor=vendor,+ enabled={LOCAL: False, FREE_EXA: False, JINA: False, sid: True}, order=(sid,),+ )++ async def fetch(*args, on_sent):+ await on_sent()+ return SearchResponse(status, {}, 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_key_invalid" if detail == "credential_revoked" else "service_limit"+ )+ source = service.store.load().sources[0]+ assert source.state.status == "needs_action"+ assert source.state.detail_key == f"models.source.needs_action.{detail}"+++async def test_configured_fetch_auth_evidence_preserves_model_cooldown(tmp_path):+ sid = IDS["deepseek"]+ service, config = _service(+ tmp_path, vendor="deepseek",+ enabled={LOCAL: False, FREE_EXA: False, JINA: False, sid: True}, order=(sid,),+ )+ retry_at = "2026-10-25T16:00:00Z"+ source = config.sources[0]+ source.state = ModelHubSourceStateConfig(+ status="cooldown", detail_key="models.source.cooldown.rate_limited", retry_at=retry_at,+ )++ async def fetch(*args, on_sent):+ await on_sent()+ return SearchResponse(200, {}, json.dumps({"title": "D", "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"]["status"] == "completed"+ current = service.store.load().sources[0]+ assert current.state == source.state+class _Local:def __init__(self):@@ -531,6 +791,30 @@ async def test_pre_send_service_result_is_skipped_without_usage_or_cooldown(tmp_assert service._service_cooldowns.until(source, "exa/mcp", service.now()) is None[email protected]("vendor,sid", [("exa", FREE_EXA), ("deepseek", IDS["deepseek"])])+async def test_keyed_pre_send_adapter_rejection_is_skipped_and_unmetered(tmp_path, vendor, sid):+ service, config = _service(+ tmp_path, vendor=vendor,+ enabled={LOCAL: False, EXA: False, FREE_EXA: False, JINA: False, sid: True},+ order=(sid,),+ )++ 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"]["error_code"] == "fetch_unavailable"+ attempt = result["record"]["attempts"][0]+ assert attempt["source_id"] == sid and attempt["kind"] == "service"+ assert attempt["outcome"] == "skipped" and attempt["skipped"] == "unavailable"+ assert service.usage_summary(days=7)["services"] == []++@pytest.mark.asyncioasync def test_local_failure_code_survives_record_cleanup(tmp_path):service, config = _service(diff --git a/vibe/data/web_fetch_services.json b/vibe/data/web_fetch_services.jsonindex 6696ffdf4..02fe36d03 100644--- a/vibe/data/web_fetch_services.json+++ b/vibe/data/web_fetch_services.json@@ -14,16 +14,18 @@"result": {"items": "results", "content": "raw_content", "failures": "failed_results"},"content_types": ["markdown"],"price": {"unit": "fetch", "usd_per_1k": 1.6, "extra": [], "as_of": "2026-10-24", "url": "https://docs.tavily.com/documentation/api-credits"},- "limits": {"attempt_seconds": 30, "urls": 1}, "outcomes": {"credential": [401], "limit": [432, 433]}+ "limits": {"attempt_seconds": 30, "urls": 1}, "outcomes": {"credential": [401], "refused": [403], "limit": [432, 433]},+ "billing": {"nonempty_only": true, "unbilled_errors": []}},{"vendor": "exa", "label": "Exa", "kind": "service", "service_id": "exa/contents","available": true, "auto_enroll": true, "endpoint": "https://api.exa.ai/contents", "auth": "x-api-key","request": {"url_field": "ids", "url_array": true, "fixed": {"text": {"maxCharacters": 48000}}},- "result": {"items": "results", "content": "text", "statuses": "statuses", "reported_cost": "costDollars.total"},+ "result": {"items": "results", "content": "text", "statuses": "statuses", "reported_cost": {"path": "costDollars.total", "estimate": true, "max_usd": 0.1}},"content_types": ["markdown"],"price": {"unit": "fetch", "usd_per_1k": 1, "extra": [], "as_of": "2026-10-24", "url": "https://exa.ai/pricing"},- "limits": {"attempt_seconds": 30, "urls": 1}, "outcomes": {"credential": [401], "refusal_tags": ["PROHIBITED_CONTENT", "CONTENT_FILTER_ERROR"]}+ "limits": {"attempt_seconds": 30, "urls": 1}, "outcomes": {"credential": [401], "refusal_tags": ["PROHIBITED_CONTENT", "CONTENT_FILTER_ERROR"]},+ "billing": {"nonempty_only": true, "unbilled_errors": []}},{"vendor": "deepseek", "label": "DeepSeek", "kind": "service", "service_id": "deepseek/fetch",@@ -31,7 +33,8 @@"request": {"url_field": "url", "url_array": false, "fixed": {}}, "result": {"content": "content", "title": "title"},"content_types": ["markdown"],"price": {"unit": "fetch", "usd_per_1k": 0.75, "extra": [], "as_of": "2026-10-24", "url": "https://api-docs.deepseek.com/guides/search/"},- "limits": {"attempt_seconds": 30, "url_chars": 8192}, "outcomes": {"credential": [401], "balance": [402], "refused": [403], "target_unreadable": [404, 408]}+ "limits": {"attempt_seconds": 30, "url_chars": 8192}, "outcomes": {"credential": [401], "balance": [402], "refused": [403], "target_unreadable": [404, 408]},+ "billing": {"nonempty_only": true, "unbilled_errors": ["timeout"]}},{"vendor": "exa-mcp", "label": "Exa (free)", "source_id": "src_exakeyless", "kind": "service",diff --git a/vibe/data/web_fetch_services.schema.json b/vibe/data/web_fetch_services.schema.jsonindex 349e48efe..be086f22b 100644--- a/vibe/data/web_fetch_services.schema.json+++ b/vibe/data/web_fetch_services.schema.json@@ -15,6 +15,14 @@"endpoint": {"type": ["string", "null"], "pattern": "^https://"},"auth": {"enum": ["none", "bearer", "x-api-key"]},"request": {"type": "object"}, "result": {"type": "object"}, "outcomes": {"type": "object"},+ "billing": {+ "type": "object", "additionalProperties": false,+ "required": ["nonempty_only", "unbilled_errors"],+ "properties": {+ "nonempty_only": {"type": "boolean"},+ "unbilled_errors": {"type": "array", "uniqueItems": true, "items": {"type": "string"}}+ }+ },"content_types": {"type": "array", "uniqueItems": true, "items": {"enum": ["html", "pdf", "text", "markdown", "json"]}},"price": {"type": "object", "additionalProperties": false,diff --git a/vibe/model_hub_runtime/adapter.py b/vibe/model_hub_runtime/adapter.pyindex b8a52b8bb..4acbfe8e4 100644--- a/vibe/model_hub_runtime/adapter.py+++ b/vibe/model_hub_runtime/adapter.py@@ -2328,33 +2328,45 @@ class CLIProxyEngineAdapter: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")+ # Keyed services use the same custody and bounded HTTP transport as search,+ # but their immutable fetch catalog owns a different endpoint and body shape.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+ and entry.get("kind") == "service"+ and (entry.get("source_id") is None)),None,)- if service is None or service.get("kind") != "service":- return SearchResponse(None, {}, None, "invalid_endpoint")+ if service is None or vendor not in {"tavily", "exa", "deepseek"} or credential_ref is None:+ # The built-in Reader is the only credentialless HTTP fetch service.+ 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 and entry.get("kind") == "service"+ ),+ None,+ )+ if service is None:+ 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}"}+ if vendor == "jina-reader":+ 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,+ extra_headers=headers or None,on_sent=on_sent,)