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.

fix(model-hub): follow cookie-setting redirects and classify WAF challenges in web_fetch (#3072)

Call White339faf69c56c
diff --git a/core/handlers/model_hub/fetch_services.py b/core/handlers/model_hub/fetch_services.py
index 93bd958df..d608f7ab1 100644
--- a/core/handlers/model_hub/fetch_services.py
+++ b/core/handlers/model_hub/fetch_services.py
@@ -189,6 +189,13 @@ def _url_matches(value: Any, requested_url: str) -> bool:
)
+def _jina_target_error(body: Mapping[str, Any] | None) -> bool:
+ # Reader's documented FormattedPageDto.httpStatus is the crawled target's
+ # status, unlike the API's outer code/status. Never parse content or warning.
+ status = _path(body, "data.httpStatus")
+ return isinstance(status, (int, float)) and not isinstance(status, bool) and 400 <= status <= 599 and status == int(status)
+
+
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"))
@@ -377,6 +384,8 @@ def map_fetch_response(
uncertain = sent and not free
elif status != 200:
code = "service_unavailable" if status is None or status >= 500 else "service_refused"
+ elif vendor == "jina-reader" and _jina_target_error(body):
+ code, target_failure = "fetch_target_unreadable", True
elif vendor in {"tavily", "exa", "deepseek"}:
outcome, content, title, provider_truncated = _configured_content(service, body, requested_url)
if outcome == "malformed":
diff --git a/core/handlers/model_hub/local_fetch.py b/core/handlers/model_hub/local_fetch.py
index 591b20cca..17207c6a3 100644
--- a/core/handlers/model_hub/local_fetch.py
+++ b/core/handlers/model_hub/local_fetch.py
@@ -22,6 +22,7 @@ import psutil
from .async_owner import await_owned_task
from core.web_fetch_worker.policy import FetchFailure, parse_url
from .retry import retry_after_deadline
+from .service_diagnostics import log_local_failure
_WORKER = "import sys; sys.path.insert(0, sys.argv.pop(1)); from core.web_fetch_worker.worker import main; main()"
@@ -107,10 +108,19 @@ class LocalFetchEngine:
return {"error_code": code, "terminal": False, "cooldown_suppressed": code == "fetch_timeout"}
async def _run(self, operation, url, *, deadline, locale="en", on_sent=None):
+ started_at = time.monotonic()
state = {"operation": operation, "sent": False, "host": None, "held_host": None, "slot": False,
- "waiting": True, "phase": "policy" if operation == "gate" else "admission"}
+ "waiting": True, "phase": "policy" if operation == "gate" else "admission",
+ "http_status": None, "hop_count": 0}
try:
- return await self._run_owned(operation, url, state, deadline=deadline, locale=locale, on_sent=on_sent)
+ result = await self._run_owned(operation, url, state, deadline=deadline, locale=locale, on_sent=on_sent)
+ if operation == "fetch" and result.get("error_code") and (state["sent"] or not result.get("skipped")):
+ await log_local_failure(
+ error_code=result["error_code"], http_status=state["http_status"], hop_count=state["hop_count"],
+ phase=state["phase"], transport_degraded=state.get("transport", {}).get("transport_degraded"),
+ elapsed_ms=round((time.monotonic() - started_at) * 1000),
+ )
+ return result
finally:
# Publish the settled host-health outcome before waking any waiter.
# Child reaping completes inside _run_owned on success/timeout/Stop.
@@ -219,6 +229,10 @@ class LocalFetchEngine:
if until > time.time():
return {"error_code": "fetch_unavailable", "skipped": "cooling", "terminal": False,
"retry_at": datetime.fromtimestamp(until, timezone.utc).isoformat()}
+ elif kind == "response":
+ state["http_status"] = event["http_status"]
+ elif kind == "hop":
+ state["hop_count"] += 1
elif kind == "phase":
state["phase"] = event["phase"]
elif kind == "fallback":
diff --git a/core/handlers/model_hub/service_diagnostics.py b/core/handlers/model_hub/service_diagnostics.py
index 6b6b2a429..b0d5c6e96 100644
--- a/core/handlers/model_hub/service_diagnostics.py
+++ b/core/handlers/model_hub/service_diagnostics.py
@@ -1,4 +1,4 @@
-"""Redacted diagnostics for failed hosted service attempts.
+"""Redacted diagnostics for failed hosted service and local fetch attempts.
This module deliberately inspects only bounded transport envelopes and emits
stable fields. It never includes the request arguments or response content.
@@ -9,6 +9,7 @@ from __future__ import annotations
import asyncio
import json
import logging
+import re
from collections.abc import Mapping
from typing import Any
@@ -17,6 +18,7 @@ from .adapter import SearchResponse
logger = logging.getLogger(__name__)
_JSONRPC_ERROR_CODE_FIELD = "code"
+_CRAWL_ERROR_TAG = re.compile(r"CRAWL_[A-Z_]{1,40}")
def _safe_field(value: object) -> str:
@@ -72,6 +74,27 @@ def _mcp_is_error(values: tuple[Mapping[str, Any], ...]) -> bool:
)
+def _mcp_crawl_error_tag(values: tuple[Mapping[str, Any], ...]) -> str | None:
+ for value in values:
+ result = value.get("result")
+ if not isinstance(result, Mapping) or result.get("isError") is not True:
+ continue
+ content = result.get("content")
+ if not isinstance(content, list):
+ continue
+ for item in content[:8]:
+ if not isinstance(item, Mapping) or item.get("type") != "text":
+ continue
+ text = item.get("text")
+ # Only the provider error wrapper, never a successful page's text.
+ if isinstance(text, str) and len(text) <= 16384 and text.startswith("Error fetching URL(s):"):
+ # The tag follows the final ': '; a tag-looking URL path/query
+ # is not a cause and must never be copied into a diagnostic.
+ if match := _CRAWL_ERROR_TAG.fullmatch(text.rsplit(": ", 1)[-1].strip()):
+ return match.group()
+ return None
+
+
def transport_cause(response: SearchResponse) -> str:
"""Return transport facts only, never provider prose or request content."""
@@ -81,7 +104,7 @@ def transport_cause(response: SearchResponse) -> str:
if (code := _jsonrpc_error_code(values)) is not None:
return f"jsonrpc_error={code}"
if _mcp_is_error(values):
- return "mcp_isError=true"
+ return _mcp_crawl_error_tag(values) or "mcp_isError=true"
if response.http_status is not None:
return f"http_status={response.http_status}"
return "unknown"
@@ -147,4 +170,37 @@ def _write_service_failure(
logger.warning(message, *values)
-__all__ = ["log_service_failure", "transport_cause"]
+async def log_local_failure(
+ *, error_code: str, http_status: int | None, hop_count: int,
+ phase: str, transport_degraded: bool | None, elapsed_ms: int,
+) -> None:
+ """One warning per failed local attempt; no request or header inputs.
+
+ Causes are closed categories, not exception messages. Unknown HTTP exchange
+ failures share http_status (which is None before any response). extract_empty
+ includes rejected/unusable extraction, not only a zero-length body.
+ """
+ if error_code == "fetch_dns_unverified":
+ cause = "dns"
+ elif error_code in {"fetch_url_blocked", "fetch_refused"}:
+ cause = "policy"
+ elif error_code in {"fetch_timeout", "service_busy"}:
+ cause = "timeout"
+ elif error_code == "fetch_challenge":
+ cause = "challenge"
+ elif phase == "loop":
+ cause = "loop"
+ elif phase == "extract":
+ cause = "extract_empty"
+ else:
+ cause = "http_status"
+ transport = "unknown" if transport_degraded is None else "degraded" if transport_degraded else "native"
+ await asyncio.to_thread(
+ logger.warning,
+ "Model Hub local attempt failed tool=web_fetch source_id=src_localfetch "
+ "error_code=%s http_status=%s hop_count=%d cause=%s transport=%s elapsed_ms=%d",
+ _safe_field(error_code), http_status, hop_count, cause, transport, max(0, int(elapsed_ms)),
+ )
+
+
+__all__ = ["log_local_failure", "log_service_failure", "transport_cause"]
diff --git a/core/web_fetch_worker/transport.py b/core/web_fetch_worker/transport.py
index 575a63387..a19e4b942 100644
--- a/core/web_fetch_worker/transport.py
+++ b/core/web_fetch_worker/transport.py
@@ -81,6 +81,7 @@ def native_available() -> tuple[bool, str | None]:
class TransferBudget:
wire: int = 0
decoded: int = 0
+ on_response: Callable[[int], None] | None = None
@dataclass
@@ -104,6 +105,13 @@ class _Receiver:
header_bytes: int = 0
native_decoded: bool = False
+ def received_status(self, status: int) -> None:
+ self.status = status
+ if status >= 200 and self.budget.on_response is not None:
+ # Publish before reading the body: a later timeout/size abort must
+ # not erase the last observed status in parent-owned diagnostics.
+ self.budget.on_response(status)
+
def header(self, data: bytes) -> int:
self.header_bytes += len(data)
if self.header_bytes > HEADER_LIMIT:
@@ -114,7 +122,7 @@ class _Receiver:
self.headers.clear()
self.limit = TEXT_LIMIT
try:
- self.status = int(data.split()[1])
+ self.received_status(int(data.split()[1]))
except (ValueError, IndexError):
raise FetchFailure("fetch_target_unreadable") from None
elif b":" in data:
@@ -314,7 +322,7 @@ def httpx_hop(target: CheckedTarget, headers: dict, budget: TransferBudget, time
with httpx.Client(transport=PinnedTransport(target), trust_env=False, follow_redirects=False,
timeout=httpx.Timeout(timeout, connect=min(5, timeout)), headers=headers) as client:
with client.stream("GET", target.address.url, extensions={"trace": trace}) as response:
- receiver.status = response.status_code
+ receiver.received_status(response.status_code)
for k, v in response.headers.raw:
receiver.header(k + b":" + v + b"\r\n")
receiver.header(b"\r\n")
diff --git a/core/web_fetch_worker/worker.py b/core/web_fetch_worker/worker.py
index de587d660..d04b6eecc 100644
--- a/core/web_fetch_worker/worker.py
+++ b/core/web_fetch_worker/worker.py
@@ -6,6 +6,7 @@ only bounded facts (never cookies, headers, or credentials).
"""
from __future__ import annotations
+import hashlib
import json
import os
import re
@@ -173,7 +174,8 @@ def fetch_document(url: str, locale: str, exchange, *, remaining_seconds: float
exchange({"event": "phase", "phase": "fetch"})
return result
- budget, cookies, seen = TransferBudget(), OriginCookies(), set()
+ budget = TransferBudget(on_response=lambda status: exchange({"event": "response", "http_status": status}))
+ cookies, seen = OriginCookies(), set()
native, reason = native_available()
exchange({"event": "transport", "transport_degraded": not native, "transport_degraded_reason": reason})
hop = curl_hop if native else httpx_hop
@@ -196,11 +198,16 @@ def fetch_document(url: str, locale: str, exchange, *, remaining_seconds: float
resolve(current) # Policy precedes even a host-cooldown skip.
exchange({"event": "host", "host": address.host})
target = resolve(current)
- if target.address.url in seen:
+ cookie = cookies.header(address)
+ # Only effective cookies for this URL may justify a revisit. Unrelated
+ # origins/paths and refreshed expiry timestamps cannot disguise a loop.
+ visit = (target.address.url, hashlib.sha256(cookie.encode("utf-8")).digest())
+ if visit in seen:
+ exchange({"event": "phase", "phase": "loop"})
raise FetchFailure("fetch_target_unreadable")
- seen.add(target.address.url)
+ seen.add(visit)
headers = request_headers(degraded=not native, locale=locale, previous_origin=previous, target=target)
- if cookie := cookies.header(address):
+ if cookie:
headers["Cookie"] = cookie
stage = "fetch"
allowance = max(0.01, deadline - time.monotonic())
@@ -208,12 +215,19 @@ def fetch_document(url: str, locale: str, exchange, *, remaining_seconds: float
def mark_hop_sent():
nonlocal hop_sent
- on_sent()
- hop_sent = True
+ if not hop_sent:
+ on_sent()
+ exchange({"event": "hop"})
+ hop_sent = True
try:
response = hop(target, headers, budget, allowance, mark_hop_sent)
cookies.receive(address, response.headers)
+ # Explicit WAF headers are authoritative on any status (including
+ # AWS's 202/405). Do not broaden status-only detection or scan prose.
+ if (response.header("cf-mitigated").strip().lower() == "challenge"
+ or response.header("x-amzn-waf-action").strip().lower() in {"challenge", "captcha"}):
+ raise FetchFailure("fetch_challenge")
if response.status == 401:
raise FetchFailure("fetch_refused", terminal=True)
if response.status == 429:
@@ -226,10 +240,8 @@ def fetch_document(url: str, locale: str, exchange, *, remaining_seconds: float
# Always gate the selected redirect, even at the hop bound.
resolve(current)
continue
- if response.status in {404, 410, 408}:
+ if response.status in {403, 404, 410, 408}:
raise FetchFailure("fetch_target_unreadable")
- if response.status == 403 or (response.status == 503 and response.header("cf-mitigated").lower() == "challenge"):
- raise FetchFailure("fetch_challenge")
if response.status != 200:
raise FetchFailure("fetch_unavailable" if response.status >= 500 else "fetch_target_unreadable",
retry_after=response.header("retry-after") or None)
@@ -283,6 +295,7 @@ def fetch_document(url: str, locale: str, exchange, *, remaining_seconds: float
break
raise FetchFailure(code, cooldown_suppressed=suppressed) from None
else:
+ exchange({"event": "phase", "phase": "loop"})
raise FetchFailure("fetch_target_unreadable")
for field in ("follow_url", "follow_kind"):
result.pop(field, None)
diff --git a/docs/plans/web-fetch.md b/docs/plans/web-fetch.md
index 2e4e1d8b0..2e07c5d61 100644
--- a/docs/plans/web-fetch.md
+++ b/docs/plans/web-fetch.md
@@ -302,7 +302,8 @@ tested. No service restart or user installation is part of this design lane.
One chain deadline: **180 s**; each local/service attempt: **30 s**, including
DNS, lock wait, redirects and extraction; connect/TLS: **5 s** within that.
-Local: five redirect hops, 16 MiB HTML/text/JSON or 32 MiB PDF, separately counted
+Local: at most six fetches (the initial request plus five redirects/follows),
+16 MiB HTML/text/JSON or 32 MiB PDF, separately counted
on the wire and after decompression across all hops/alternates. Bound headers
(64 KiB per hop, including informational headers/trailers), URLs and cookies (64 entries, 4 KiB each); reject oversized announced
lengths and abort streamed unknown lengths at the same cap. Native libcurl
@@ -337,10 +338,18 @@ credential, custom proxy or user secret. A fresh in-memory jar accepts only vali
cookies received in this redirect chain, sends them only back to the issuing
origin (stricter than Domain matching), and is discarded; no cookies or headers
in logs/history. Never forward them to an API executor. Referer is absent.
+Loop detection keys each normalized URL by a digest of the effective outgoing
+cookie header for that URL. A callback that changes an origin's applicable
+cookies can revisit the original page; unrelated-origin/path cookies or expiry
+refreshes with the same outgoing value cannot buy another visit. Remember every
+visited state, including older states if cookies cycle back. The six-fetch bound
+and policy/DNS gate on every hop stay unchanged: four sign-in redirects plus the
+final document use five fetches. Cookie digests are worker-local and never logged.
No JS, iframe requests, images or other subresources. No separate `robots.txt`
preflight for a user-selected page: recommendation avoids a second crawl/policy
surface; respect direct refusals and 429 advice. This is not an assertion that
-sites permit automated access.
+sites permit automated access. HTTP challenge classification requires an explicit
+known WAF header (§6); a bare 403 is a target failure, not evidence of verification.
| Input | Local normalization |
| --- | --- |
@@ -530,6 +539,17 @@ is Markdown, with title/URL metadata when present. Do not use
engines); no OCR, screenshots, proxy/cookie headers, generated captions or script
injection. Default Reader renders JS server-side. Provider truncation uses §4.
+Target-error mapping rechecked **2026-10-30** against `https://jina.ai/reader/`,
+`https://docs.jina.ai/` and its `https://docs.jina.ai/openapi.json`. The Reader JSON
+response references `FormattedPageDto`, whose optional numeric `httpStatus`
+(and `httpStatusText`) describes the crawled page. On an API HTTP 200, an integral
+`data.httpStatus` in 400–599 is `fetch_target_unreadable`, even with nonempty
+`data.content`; it is not a service failure or shared cooldown. Never use the
+outer API `code`, free-form `warning`, or phrases in `data.content` as target
+status evidence. Missing/malformed target status is not evidence of an HTTP
+error; the existing content checks still apply. No live Jina API call is needed
+to validate this mapping.
+
The Reader page lists **20 RPM without a key**, per-IP/key limits; the API docs'
general bearer-auth examples do not negate that specific keyless table. Reserve
an in-memory rolling-minute slot before send (20 per runtime, not per Session);
@@ -583,14 +603,40 @@ is a no-send `service_busy` skip, not a provider fault, cost or shared cooldown.
| Invalid argument / address refusal / DNS failure or full DNS allowance expiry | terminal, no third-party forwarding; preserve any earlier sent attempts |
| Local attempt budget exhausted during admission/revalidation | no-send `service_busy` skip, or `fetch_timeout` after a local send; no cooldown; re-gate only the original requested URL before the next candidate |
| Usable content | end with completed record |
-| Local 403/503 challenge, JS shell, empty page, unsupported type | next enabled candidate, no local retry/headless path |
-| Local 404/410, connect/TLS/timeout/server failure | next; bounded host cooldown where transient |
+| Local explicit WAF challenge, JS shell, empty page, unsupported type | next enabled candidate, no local retry/headless path |
+| Local bare 403/404/410, connect/TLS/timeout/server failure | next; bounded host cooldown where transient |
| Local 401/login wall | terminal `fetch_refused`, no forwarding or credential access |
| Configured 401 / catalog credential-403; 402; named spend limit | Source needs-action with existing generation fences, next |
| Provider URL refusal / proven target failure | `service_refused` / `fetch_target_unreadable`, next; no service health write |
| 429 | rate-limit attempt + scope-specific cooldown above, next **without sleeping**; server advice never shortened |
| Service redirect, unexpected HTTP error, timeout, malformed/oversized response | existing `service_unavailable`/`service_unreadable`, next |
+Local HTTP challenge detection recognizes `cf-mitigated: challenge` and
+`x-amzn-waf-action: challenge` / `captcha` on **any** HTTP status (including AWS
+202/405), before ordinary status handling. There is **no status-only challenge
+set**: bare 403 and unmarked 202/405 are non-terminal target-unreadable failures;
+unmarked 503 is unavailable.
+No new page-body phrase matching or JS/WAF bypass is introduced.
+
+The shared `service_diagnostics` owner writes exactly one WARNING per failed
+local attempt (not a policy-only gate, no-send skip, Stop, success, or retained
+HTML success). It includes only `tool=web_fetch`, `source_id=src_localfetch`,
+`error_code`, last observed `http_status` (None before any response), `hop_count`
+(number of HTTP requests sent, including the initial request), `cause`, transport
+(`native`/`degraded`; `unknown` only if worker startup failed before selection),
+and `elapsed_ms`. Causes are closed categories: `loop` (including hop exhaustion),
+`http_status` (including HTTP exchange failures), `challenge`, `extract_empty`
+(including unusable/rejected extraction), `timeout`, `dns`, or `policy`.
+The parent receives status before body reading so timeout/size aborts retain it.
+These are internal IPC/log facts only, not persisted record/attempt fields; no
+contract version change. Never log URL, host, query, cookie/digest, headers,
+exception prose or body content. For Exa MCP failures, `isError: true` plus the
+`Error fetching URL(s): <url>: <tag>` wrapper can supply a bounded terminal tag
+matching `CRAWL_[A-Z_]{1,40}` as `transport_cause`. Neither successful document
+text nor tag-looking URL paths/queries may supply it. Missing/invalid tags keep
+`mcp_isError=true`; this diagnostic does not change target-failure settlement or
+introduce a service cooldown. Wrapper shape rechecked by the owner on 2026-10-30.
+
Use existing stable service codes, adding `service_busy` for no-send contention
and `fetch_target_unreadable` for the target boundary. Local adds `fetch_url_blocked`,
`fetch_dns_unverified`, `fetch_challenge`, `fetch_js_shell`, `fetch_timeout`,
@@ -805,7 +851,8 @@ Checked 2026-10-24; implementation re-verifies its pinned versions before shippi
pricing: `https://exa.ai/pricing`.
- DeepSeek: `https://api-docs.deepseek.com/guides/search/`.
- Anthropic: `https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-fetch-tool`.
-- Jina: `https://jina.ai/reader/`, `https://docs.jina.ai/`, `https://jina.ai/legal/`.
+- Jina: `https://jina.ai/reader/`, `https://docs.jina.ai/`,
+ `https://docs.jina.ai/openapi.json`, `https://jina.ai/legal/`.
- curl_cffi wheel manifest: `https://pypi.org/pypi/curl-cffi/0.16.3/json`;
pinned adapter: `https://github.com/lexiforest/curl_cffi/tree/v0.16.3/curl_cffi`;
libcurl pin: `https://curl.se/libcurl/c/CURLOPT_RESOLVE.html`.
diff --git a/tests/test_model_hub_fetch_chain.py b/tests/test_model_hub_fetch_chain.py
index edf72888c..b692493b4 100644
--- a/tests/test_model_hub_fetch_chain.py
+++ b/tests/test_model_hub_fetch_chain.py
@@ -60,6 +60,34 @@ async def test_jina_builtin_fetch_is_admitted_with_reader_headers():
assert limited.cooling and not limited.target_failure
[email protected]("target_status", [400, 401, 403, 404, 408, 429, 500, 599])
+def test_jina_target_http_error_is_not_completed_content(target_status):
+ """Reader FormattedPageDto.httpStatus describes the target, not API health."""
+ jina = next(item for item in fetch_service_catalog() if item["vendor"] == "jina-reader")
+ mapped = map_fetch_response(
+ jina, SearchResponse(200, {}, json.dumps({"code": 200, "data": {
+ "httpStatus": target_status, "content": "404: Not Found", "url": "https://example.com/",
+ }}).encode()), requested_url="https://example.com/", sent=True, say=lambda key, **_: key,
+ )
+ assert mapped.record["status"] == "failed"
+ assert mapped.record["error_code"] == "fetch_target_unreadable"
+ assert mapped.target_failure and not mapped.cooling and mapped.blocker is None
+ assert mapped.cost.usd == 0 and not mapped.billable and not mapped.uncertain
+
+
[email protected]("target_status", [None, 200, 399, "404", True, 600])
+def test_jina_never_guesses_target_error_from_content_or_warning(target_status):
+ jina = next(item for item in fetch_service_catalog() if item["vendor"] == "jina-reader")
+ mapped = map_fetch_response(
+ jina, SearchResponse(200, {}, json.dumps({"data": {
+ "httpStatus": target_status, "content": "404: Not Found",
+ "warning": "Target URL returned error 404: Not Found",
+ }}).encode()), requested_url="https://example.com/", sent=True, say=lambda key, **_: key,
+ )
+ assert mapped.record["status"] == "completed"
+ assert mapped.record["content"] == "404: Not Found"
+
+
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"
@@ -162,6 +190,52 @@ async def test_failed_fetch_service_attempt_logs_redacted_transport_facts(tmp_pa
assert "secret.example" not in message and "secret page body" not in message
[email protected]("text,is_error,expected_cause,expected_code", [
+ ("Error fetching URL(s): https://private.example/x?q=secret: CRAWL_LIVECRAWL_TIMEOUT", True,
+ "CRAWL_LIVECRAWL_TIMEOUT", "fetch_target_unreadable"),
+ ("Error fetching URL(s): https://private.example/x: CRAWL_NOT_FOUND", True,
+ "CRAWL_NOT_FOUND", "fetch_target_unreadable"),
+ ("Error fetching URL(s): https://private.example/CRAWL_FROM_URL: CRAWL_NOT_FOUND", True,
+ "CRAWL_NOT_FOUND", "fetch_target_unreadable"),
+ ("Error fetching URL(s): https://private.example/CRAWL_FROM_URL", True,
+ "mcp_isError=true", "fetch_target_unreadable"),
+ ("Error fetching URL(s): https://private.example/x: CRAWL_" + "A" * 41, True,
+ "mcp_isError=true", "fetch_target_unreadable"),
+ ("Error fetching URL(s): https://private.example/x: CRAWL_ERROR_123", True,
+ "mcp_isError=true", "fetch_target_unreadable"),
+ ("secret page body", True, "mcp_isError=true", "service_unavailable"),
+ ("An article discussing CRAWL_NOT_FOUND", False, None, None),
+])
+async def test_exa_keyless_fetch_logs_only_bounded_error_wrapper_tag(tmp_path, caplog, text, is_error, expected_cause, expected_code):
+ """An error wrapper supplies a cause, not a URL/prose or service cooldown."""
+ service, config = _service(
+ tmp_path, enabled={LOCAL: False, EXA: False, FREE_EXA: True, JINA: False}, order=(FREE_EXA,),
+ )
+ caplog.set_level(logging.WARNING, logger="core.handlers.model_hub.service_diagnostics")
+
+ async def fetch(*args, on_sent):
+ await on_sent()
+ return SearchResponse(200, {}, json.dumps({"result": {
+ "isError": is_error, "content": [{"type": "text", "text": text}],
+ }}).encode())
+
+ service.adapter.fetch = fetch
+ result = await service.run_hosted_tool(
+ "web_fetch", {"arguments": {"url": "https://private.example/x?q=secret"}},
+ turn=service.freeze_turn_hosted_tools(config),
+ )
+ assert result["record"].get("error_code") == expected_code
+ records = [r for r in caplog.records if r.name == "core.handlers.model_hub.service_diagnostics"]
+ assert len(records) == (0 if expected_cause is None else 1)
+ if records:
+ message = records[0].getMessage()
+ assert f"transport_cause={expected_cause} elapsed_ms=" in message
+ assert "private.example" not in message and "secret" not in message and "https://" not in message
+ if expected_code == "fetch_target_unreadable":
+ assert service._service_cooldowns.until(model_hub_builtin_source(FREE_EXA), "exa/mcp", service.now()) is None
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("sid,status,body,expected,delay", [
(FREE_EXA, 429, {}, "service_rate_limited", 600),
@@ -184,6 +258,7 @@ async def test_failed_fetch_service_attempt_logs_redacted_transport_facts(tmp_pa
(JINA, 500, {}, "service_unavailable", 60),
(JINA, 401, {}, "service_refused", None),
(JINA, 403, {}, "service_refused", None),
+ (JINA, 200, {"data": {"httpStatus": 404, "content": "404: Not Found"}}, "fetch_target_unreadable", 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."""
diff --git a/tests/test_model_hub_fetch_transport.py b/tests/test_model_hub_fetch_transport.py
index 8f3211338..5dadd0edb 100644
--- a/tests/test_model_hub_fetch_transport.py
+++ b/tests/test_model_hub_fetch_transport.py
@@ -5,6 +5,8 @@ exercise real libcurl/HTTPcore sockets, not a mock implementing the pin policy.
"""
import gzip
import io
+import logging
+import time
import zlib
import socket
import threading
@@ -13,8 +15,9 @@ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import httpcore
import pytest
-from core.web_fetch_worker import transport
-from core.web_fetch_worker.policy import CheckedTarget, FetchFailure, FetchURL
+from core.handlers.model_hub import local_fetch
+from core.web_fetch_worker import transport, worker
+from core.web_fetch_worker.policy import CheckedTarget, FetchFailure, FetchURL, parse_url
# Static codec fixtures keep optional Python codecs out of every install/test
@@ -38,6 +41,50 @@ def stub():
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
requests.append((self.path, dict(self.headers)))
+ if self.path.startswith(("/gemini-api/", "/oauth2", "/o/oauth2/", "/loop")):
+ port = self.server.server_port
+ routes = {
+ "/gemini-api/docs/thought-signatures": "/oauth2authorize",
+ "/oauth2authorize": f"http://accounts.example:{port}/o/oauth2/v2/auth",
+ "/o/oauth2/v2/auth": f"http://public.example:{port}/oauth2callback",
+ "/oauth2callback": "/gemini-api/docs/thought-signatures",
+ "/loop": "/loop",
+ }
+ if self.path == "/gemini-api/docs/thought-signatures" and "signin=autosignin" in self.headers.get("Cookie", ""):
+ self.send_response(200)
+ self.send_header("Content-Type", "text/markdown")
+ self.end_headers()
+ self.wfile.write(b"# Thought signatures | Gemini API\n\nA readable public document.")
+ else:
+ self.send_response(302)
+ self.send_header("Location", routes[self.path])
+ if self.path == "/oauth2callback":
+ self.send_header("Set-Cookie", "signin=autosignin; Path=/; HttpOnly")
+ self.end_headers()
+ return
+ if self.path == "/challenge":
+ self.send_response(202)
+ self.send_header("x-amzn-waf-action", "challenge")
+ self.end_headers()
+ return
+ if self.path == "/empty":
+ self.send_response(200)
+ self.send_header("Content-Type", "text/plain")
+ self.end_headers()
+ return
+ if self.path == "/slow-body":
+ self.send_response(200)
+ self.send_header("Content-Type", "text/plain")
+ self.send_header("Content-Length", "10")
+ self.end_headers()
+ time.sleep(2)
+ return
+ if self.path.startswith("/diagnostic"):
+ self.send_response(302)
+ self.send_header("Location", "/status/404")
+ self.send_header("Set-Cookie", "private-cookie=never-log-this; Path=/")
+ self.end_headers()
+ return
if self.path.startswith("/encoded/") or self.path == "/wire-padding":
if self.path == "/wire-padding":
stream = io.BytesIO()
@@ -112,6 +159,86 @@ def stub():
server.server_close()
[email protected]("native", [True, False])
+def test_cookie_setting_signin_redirect_revisits_original_url(stub, monkeypatch, native):
+ """WF-LOCAL-002: real sockets reproduce four redirects, then a cookie-only 200.
+
+ The URL-only loop guard rejects the last request; ordinary redirect tests
+ never revisit a URL after the origin's outgoing cookie header changes.
+ """
+ if native:
+ pytest.importorskip("curl_cffi")
+ port, requests = stub
+ gates, events = [], []
+
+ def resolve(url):
+ gates.append(url)
+ return CheckedTarget(parse_url(url), ("127.0.0.1",))
+
+ monkeypatch.setattr(worker, "resolve_target", resolve)
+ monkeypatch.setattr(transport, "native_available", lambda: (native, None if native else "native_library_unavailable"))
+ url = f"http://public.example:{port}/gemini-api/docs/thought-signatures"
+ result = worker.fetch_document(url, "en", events.append)
+ assert result["final_url"] == url and "Thought signatures" in result["content"]
+ assert len(requests) == 5 # Four redirects plus final fetch fits six-fetch bound.
+ assert requests[-1][1]["Cookie"] == "signin=autosignin"
+ assert all("Cookie" not in headers for _, headers in requests[:-1])
+ assert len([event for event in events if event["event"] == "sent"]) == 1
+ assert all(f"http://{headers['Host']}{path}" in gates for path, headers in requests)
+ requests.clear()
+ with pytest.raises(FetchFailure, match="fetch_target_unreadable"):
+ worker.fetch_document(f"http://public.example:{port}/loop", "en", events.append)
+ assert len(requests) == 1 # No cookie change: a genuine loop is still rejected.
+
+
[email protected]("native", [True, False])
[email protected]("path,status,hops,cause,code", [
+ ("/diagnostic?private-query=do-not-log", 404, 2, "http_status", "fetch_target_unreadable"),
+ ("/loop", 302, 1, "loop", "fetch_target_unreadable"),
+ ("/challenge", 202, 1, "challenge", "fetch_challenge"),
+ ("/empty", 200, 1, "extract_empty", "fetch_target_unreadable"),
+ ("/slow-body", 200, 1, "timeout", "fetch_timeout"),
+])
+async def test_local_failure_logs_one_redacted_warning_from_real_worker(stub, monkeypatch, caplog, native, path, status, hops, cause, code):
+ """The worker/parent IPC must preserve facts without persisting URL or headers."""
+ if native:
+ pytest.importorskip("curl_cffi")
+ port, _ = stub
+ script = '''import sys
+sys.path.insert(0, sys.argv.pop(1))
+from core.web_fetch_worker import worker, transport
+from core.web_fetch_worker.policy import CheckedTarget, parse_url
+worker.resolve_target = lambda url: CheckedTarget(parse_url(url), ("127.0.0.1",))
+transport.native_available = lambda: (NATIVE, None if NATIVE else "native_library_unavailable")
+original_hop = transport.curl_hop if NATIVE else transport.httpx_hop
+def bounded_hop(target, headers, budget, timeout, on_sent):
+ if target.address.url.endswith("/slow-body"):
+ timeout = 1 # Transport timeout starts after worker startup, not before it.
+ return original_hop(target, headers, budget, timeout, on_sent)
+if NATIVE:
+ transport.curl_hop = bounded_hop
+else:
+ transport.httpx_hop = bounded_hop
+worker.main()
+'''.replace("NATIVE", repr(native))
+ monkeypatch.setattr(local_fetch, "_WORKER", script)
+ caplog.set_level(logging.WARNING, logger="core.handlers.model_hub.service_diagnostics")
+ url = f"http://public.example:{port}{path}"
+ result = await local_fetch.LocalFetchEngine().fetch(url, deadline=time.monotonic() + 10)
+ assert result["error_code"] == code
+ records = [r for r in caplog.records if r.name == "core.handlers.model_hub.service_diagnostics"]
+ assert len(records) == 1 and records[0].levelno == logging.WARNING
+ message = records[0].getMessage()
+ for field in ("tool=web_fetch", "source_id=src_localfetch", f"error_code={code}",
+ f"http_status={status}", f"hop_count={hops}", f"cause={cause}",
+ f"transport={'native' if native else 'degraded'}", "elapsed_ms="):
+ assert field in message
+ assert int(message.split("elapsed_ms=")[1].split()[0]) >= 0
+ for private in (url, "public.example", "accounts.example", "private-query", "private-cookie", "never-log-this", "not gzip"):
+ assert private not in message
+ assert "http_status" not in result and "hop_count" not in result and "cause" not in result
+
+
@pytest.mark.parametrize("native", [True, False])
def test_real_hop_uses_numeric_pin_original_host_and_no_ambient_credentials(stub, monkeypatch, tmp_path, native):
if native:
diff --git a/tests/test_model_hub_local_fetch.py b/tests/test_model_hub_local_fetch.py
index 6e00d0758..e161969ab 100644
--- a/tests/test_model_hub_local_fetch.py
+++ b/tests/test_model_hub_local_fetch.py
@@ -256,7 +256,7 @@ def test_native_load_failure_selects_honest_transport_before_send(local_fixture,
@pytest.mark.parametrize("status,code,terminal", [
- (401, "fetch_refused", True), (403, "fetch_challenge", False),
+ (401, "fetch_refused", True), (403, "fetch_target_unreadable", False),
(404, "fetch_target_unreadable", False), (410, "fetch_target_unreadable", False),
(429, "service_rate_limited", False), (503, "fetch_unavailable", False),
])
@@ -278,6 +278,31 @@ def test_503_explicit_challenge_has_no_transient_host_class(local_fixture):
worker.fetch_document("https://example.com/", "en", events.append)
[email protected]("status,header,value,code", [
+ (202, "x-amzn-waf-action", "challenge", "fetch_challenge"),
+ (405, "x-amzn-waf-action", "captcha", "fetch_challenge"),
+ (200, "X-Amzn-Waf-Action", "CHALLENGE", "fetch_challenge"),
+ (401, "x-amzn-waf-action", "captcha", "fetch_challenge"),
+ (429, "x-amzn-waf-action", "challenge", "fetch_challenge"),
+ (302, "x-amzn-waf-action", "challenge", "fetch_challenge"),
+ (503, "cf-mitigated", "challenge", "fetch_challenge"),
+ (200, "cf-mitigated", "challenge", "fetch_challenge"),
+ (202, "x-amzn-waf-action", "allow", "fetch_target_unreadable"),
+ (405, "unrelated", "captcha", "fetch_target_unreadable"),
+ (503, "cf-mitigated", "other", "fetch_unavailable"),
+ (403, "cf-mitigated", "other", "fetch_target_unreadable"),
+ (403, "cf-mitigated", "challenge", "fetch_challenge"),
+])
+def test_explicit_waf_challenge_headers_on_any_status(local_fixture, status, header, value, code):
+ """Header facts, not page prose or a broad status set, identify challenges."""
+ responses, calls, _, events = local_fixture
+ responses["https://example.com/"] = HopResponse(status, [(header, value)], b"")
+ with pytest.raises(FetchFailure) as raised:
+ worker.fetch_document("https://example.com/", "en", events.append)
+ assert raised.value.code == code and not raised.value.terminal
+ assert len(calls) == 1
+
+
def test_redirect_to_private_terminates_without_second_connect(local_fixture):
responses, calls, gates, events = local_fixture
responses["https://example.com/"] = HopResponse(302, [("location", "http://169.254.169.254/latest")], b"")
diff --git a/tests/test_model_hub_structure_guards.py b/tests/test_model_hub_structure_guards.py
index 826b8aac6..edea58c7a 100644
--- a/tests/test_model_hub_structure_guards.py
+++ b/tests/test_model_hub_structure_guards.py
@@ -1281,6 +1281,7 @@ def test_machine_error_field_access_has_one_extractor() -> None:
type_readers = {
"request.py": ("_plain_history", "declared_tool_types", "replays_history_items"),
"fetch_services.py": ("_mcp_payload",),
+ "service_diagnostics.py": ("_mcp_crawl_error_tag",),
}
functions = _functions(tree) if path.name in type_readers else {}
history_nodes = {