AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary
Python ai-promptsai-skillblueskyclaudeclaude-codeclawhubdeep-researchhackernewsinstagramopenclawpolymarketrecencyredditresearchsocial-mediatiktoktrendstwitterweb-searchyoutube
feat(grounding): add keyless URL-to-markdown fetch (U1)
Matt Van Horn358525d38bec
diff --git a/skills/last30days/scripts/lib/web_fetch_keyless.py b/skills/last30days/scripts/lib/web_fetch_keyless.pynew file mode 100644index 00000000..a93e190f--- /dev/null+++ b/skills/last30days/scripts/lib/web_fetch_keyless.py@@ -0,0 +1,105 @@+"""Keyless URL-to-markdown fetch (floor tier for engine-side page reads).++Turns any URL into clean, JS-rendered markdown via Jina Reader's free hosted+endpoint (``https://r.jina.ai/{url}``) with no API key. This is a *fallback*+tier, never the primary firehose:++- On agent hosts with a native fetch tool, prefer that (this module exists for+ headless/cron and hosts without one).+- The free tier is rate-limited and returns cached snapshots (staleness), so+ callers should treat results as best-effort and record when it was used.+- The target URL is sent to a third party; only use for public-research fetches.++Never raises. Returns a typed :class:`KeylessFetchResult` carrying the failure+reason on any error, so tiered callers (and the source-health layer) can fall+through or report degradation instead of seeing a bare empty string.+"""++from __future__ import annotations++from dataclasses import dataclass+from typing import Optional+from urllib.parse import urlparse++from . import http++JINA_READER_PREFIX = "https://r.jina.ai/"++# Conservative timeout: Jina renders the page server-side, so it is slower than+# a plain GET, but we are the floor tier and must not stall the pipeline.+DEFAULT_FETCH_TIMEOUT = 30+++@dataclass+class KeylessFetchResult:+ """Result of a keyless page fetch.++ ``ok`` is True only when markdown was retrieved. On failure, ``markdown`` is+ empty and ``reason`` explains why (consumed by the source-health layer).+ """++ url: str+ ok: bool+ markdown: str = ""+ reason: str = ""+ cached_snapshot: bool = False+++def _looks_like_http_url(url: str) -> bool:+ try:+ parsed = urlparse(url)+ except (ValueError, AttributeError):+ return False+ return parsed.scheme in ("http", "https") and bool(parsed.netloc)+++def _detect_cached_snapshot(markdown: str) -> bool:+ """Best-effort detection of Jina's cached-snapshot warning.++ Jina prepends a small metadata/warning header to the text response; when it+ serves a cached copy it says so. We scan only the leading window to avoid+ false positives from article bodies that happen to mention caching.+ """+ head = markdown[:600].lower()+ return "cached" in head and "snapshot" in head+++def fetch_markdown(+ url: str,+ timeout: int = DEFAULT_FETCH_TIMEOUT,+ retries: int = 2,+) -> KeylessFetchResult:+ """Fetch ``url`` as clean markdown via the keyless reader endpoint.++ Args:+ url: The http(s) URL to fetch.+ timeout: Per-attempt HTTP timeout in seconds.+ retries: Retry budget (kept low; this is a fail-fast floor tier).++ Returns:+ A :class:`KeylessFetchResult`. ``ok`` is False with a populated+ ``reason`` on invalid input, network failure, or empty body.+ """+ if not url or not _looks_like_http_url(url):+ return KeylessFetchResult(url=url or "", ok=False, reason="invalid-url")++ reader_url = f"{JINA_READER_PREFIX}{url}"+ text = http.get_text(+ reader_url,+ timeout=timeout,+ retries=retries,+ accept="text/plain",+ )++ if text is None:+ return KeylessFetchResult(url=url, ok=False, reason="fetch-failed")++ if not text.strip():+ return KeylessFetchResult(url=url, ok=False, reason="empty-body")++ return KeylessFetchResult(+ url=url,+ ok=True,+ markdown=text,+ cached_snapshot=_detect_cached_snapshot(text),+ )diff --git a/tests/test_web_fetch_keyless.py b/tests/test_web_fetch_keyless.pynew file mode 100644index 00000000..c4e17e26--- /dev/null+++ b/tests/test_web_fetch_keyless.py@@ -0,0 +1,55 @@+"""Tests for scripts/lib/web_fetch_keyless.py — keyless URL-to-markdown fetch."""++from unittest import mock++from lib import web_fetch_keyless+++class TestFetchMarkdown:+ """fetch_markdown turns a URL into clean markdown via the keyless reader."""++ def test_happy_path(self):+ body = "Title: Example\nURL Source: https://example.com\n\n# Example\n\nReal content."+ with mock.patch.object(web_fetch_keyless.http, "get_text", return_value=body) as gt:+ result = web_fetch_keyless.fetch_markdown("https://example.com")+ assert result.ok is True+ assert "Real content." in result.markdown+ assert result.cached_snapshot is False+ # Requests the reader-prefixed URL with a text accept header.+ called_url = gt.call_args.args[0]+ assert called_url == "https://r.jina.ai/https://example.com"+ assert gt.call_args.kwargs.get("accept") == "text/plain"++ def test_cached_snapshot_flagged(self):+ body = "Warning: showing a cached snapshot of this page.\n\n# Title\n\nbody"+ with mock.patch.object(web_fetch_keyless.http, "get_text", return_value=body):+ result = web_fetch_keyless.fetch_markdown("https://example.com/post")+ assert result.ok is True+ assert result.cached_snapshot is True++ def test_fetch_failure_returns_typed_empty(self):+ with mock.patch.object(web_fetch_keyless.http, "get_text", return_value=None):+ result = web_fetch_keyless.fetch_markdown("https://example.com")+ assert result.ok is False+ assert result.markdown == ""+ assert result.reason == "fetch-failed"++ def test_empty_body_returns_typed_empty(self):+ with mock.patch.object(web_fetch_keyless.http, "get_text", return_value=" \n "):+ result = web_fetch_keyless.fetch_markdown("https://example.com")+ assert result.ok is False+ assert result.reason == "empty-body"++ def test_invalid_url_makes_no_request(self):+ with mock.patch.object(web_fetch_keyless.http, "get_text") as gt:+ result = web_fetch_keyless.fetch_markdown("not a url")+ assert result.ok is False+ assert result.reason == "invalid-url"+ gt.assert_not_called()++ def test_empty_url_makes_no_request(self):+ with mock.patch.object(web_fetch_keyless.http, "get_text") as gt:+ result = web_fetch_keyless.fetch_markdown("")+ assert result.ok is False+ assert result.reason == "invalid-url"+ gt.assert_not_called()