| 1 | """Web search retrieval via Brave Search, Exa, Serper, Parallel, or a keyless floor.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import math |
| 6 | import re |
| 7 | import sys |
| 8 | import threading |
| 9 | import time |
| 10 | import urllib.parse |
| 11 | from dataclasses import dataclass |
| 12 | from datetime import datetime, timedelta, timezone |
| 13 | from itertools import zip_longest |
| 14 | from urllib.parse import urlparse |
| 15 | |
| 16 | from . import dates, env, fusion, http, parallel_mcp, proxy, public_host, relevance, schema, web_search_keyless |
| 17 | |
| 18 | |
| 19 | @dataclass(frozen=True) |
| 20 | class GroundedClaimText: |
| 21 | """Candidate text with its exact primary evidence item.""" |
| 22 | |
| 23 | candidate_id: str |
| 24 | title: str |
| 25 | summary: str |
| 26 | item: schema.SourceItem |
| 27 | |
| 28 | |
| 29 | def claim_source_map(report: schema.Report) -> dict[str, GroundedClaimText]: |
| 30 | """Expose only candidate claims that have a clean primary-item trace. |
| 31 | |
| 32 | Freshness verification deliberately starts here instead of scanning all |
| 33 | report prose. A candidate without a primary ``SourceItem`` cannot produce |
| 34 | an auditable per-claim verdict. |
| 35 | """ |
| 36 | grounded: dict[str, GroundedClaimText] = {} |
| 37 | for candidate in report.ranked_candidates: |
| 38 | item = schema.candidate_primary_item(candidate) |
| 39 | if item is None: |
| 40 | continue |
| 41 | grounded[candidate.candidate_id] = GroundedClaimText( |
| 42 | candidate_id=candidate.candidate_id, |
| 43 | title=candidate.title, |
| 44 | summary=candidate.snippet or item.snippet or item.body, |
| 45 | item=item, |
| 46 | ) |
| 47 | return grounded |
| 48 | |
| 49 | |
| 50 | # --------------------------------------------------------------------------- |
| 51 | # Brave Search API |
| 52 | # --------------------------------------------------------------------------- |
| 53 | |
| 54 | def brave_search( |
| 55 | query: str, date_range: tuple[str, str], api_key: str, count: int = 5, |
| 56 | freshness: str | None = None, |
| 57 | *, |
| 58 | include_news: bool = False, |
| 59 | deadline_monotonic: float | None = None, |
| 60 | cancel: threading.Event | None = None, |
| 61 | ) -> tuple[list[dict], dict]: |
| 62 | """``freshness`` overrides the request's date-range freshness (e.g. "pm"). |
| 63 | |
| 64 | ``deadline_monotonic`` and ``cancel`` bound the request to a caller's run. |
| 65 | """ |
| 66 | url = ( |
| 67 | "https://api.search.brave.com/res/v1/web/search?" |
| 68 | + urllib.parse.urlencode( |
| 69 | { |
| 70 | "q": query, |
| 71 | "count": count, |
| 72 | "freshness": freshness or f"{date_range[0]}to{date_range[1]}", |
| 73 | } |
| 74 | ) |
| 75 | ) |
| 76 | data = http.request( |
| 77 | "GET", url, headers={"X-Subscription-Token": api_key}, timeout=15, |
| 78 | deadline_monotonic=deadline_monotonic, cancel=cancel, |
| 79 | ) |
| 80 | items = [] |
| 81 | web = _result_rows(data.get("web")) |
| 82 | for i, r in enumerate(web if include_news else web[:count]): |
| 83 | if not isinstance(r, dict) or not public_host.is_public_address_syntax(r.get("url")): |
| 84 | continue |
| 85 | raw_date = r.get("page_age") |
| 86 | pub_date = _normalize_date(raw_date[:10]) if isinstance(raw_date, str) else None |
| 87 | if _known_date_out_of_range(pub_date, date_range): |
| 88 | continue |
| 89 | items.append({ |
| 90 | "id": f"WB{i + 1}", |
| 91 | "title": r.get("title", ""), |
| 92 | "url": r.get("url", ""), |
| 93 | "source_domain": _domain(r.get("url", "")), |
| 94 | "snippet": r.get("description") or "", |
| 95 | "date": pub_date, |
| 96 | "relevance": 0.8, |
| 97 | "why_relevant": "Brave web search", |
| 98 | "metadata": {"date_window_basis": "server_bounds"}, |
| 99 | }) |
| 100 | if include_news: |
| 101 | items = _with_dated_news(items, _result_rows(data.get("news")), query, date_range, count, backend="brave") |
| 102 | artifact = {"label": "brave", "webSearchQueries": [query], "resultCount": len(items)} |
| 103 | return items, artifact |
| 104 | |
| 105 | |
| 106 | # --------------------------------------------------------------------------- |
| 107 | # Exa AI Search |
| 108 | # --------------------------------------------------------------------------- |
| 109 | |
| 110 | # Exa's company and people indexes reject publication-date filters (HTTP 400). |
| 111 | # people also rejects excludeDomains. See https://exa.ai/docs/reference/search |
| 112 | _EXA_UNDATED_CATEGORIES = frozenset({"company", "people"}) |
| 113 | _EXA_SEARCH_URL = "https://api.exa.ai/search" |
| 114 | |
| 115 | |
| 116 | def exa_api_key(config: dict | None) -> str: |
| 117 | """Return EXA_API_KEY when the caller configured one, else ''.""" |
| 118 | return str((config or {}).get("EXA_API_KEY") or "") |
| 119 | |
| 120 | |
| 121 | def _exa_snippet(result: dict) -> str: |
| 122 | """Prefer highlights (Exa's recommended excerpt) and fall back to text.""" |
| 123 | highlights = result.get("highlights") |
| 124 | if isinstance(highlights, str) and highlights.strip(): |
| 125 | return highlights[:500] |
| 126 | if isinstance(highlights, list): |
| 127 | parts = [part for part in highlights if isinstance(part, str) and part.strip()] |
| 128 | if parts: |
| 129 | return " ".join(parts)[:500] |
| 130 | return (result.get("text") or "")[:500] |
| 131 | |
| 132 | |
| 133 | def _exa_search_body( |
| 134 | query: str, |
| 135 | count: int, |
| 136 | date_range: tuple[str, str] | None = None, |
| 137 | *, |
| 138 | category: str | None = None, |
| 139 | objective: str | None = None, |
| 140 | ) -> dict: |
| 141 | """Build an Exa /search body. |
| 142 | |
| 143 | Highlights are the recommended content shape |
| 144 | (https://exa.ai/docs/search/best-practices). Publication-date filters stay |
| 145 | on dated, uncategorized paths only: ``company`` and ``people`` reject them. |
| 146 | """ |
| 147 | body: dict = { |
| 148 | "query": query, |
| 149 | "type": "auto", |
| 150 | "numResults": count, |
| 151 | "contents": {"highlights": True}, |
| 152 | } |
| 153 | if objective: |
| 154 | body["objective"] = objective |
| 155 | if category: |
| 156 | body["category"] = category |
| 157 | if date_range and category not in _EXA_UNDATED_CATEGORIES: |
| 158 | body["startPublishedDate"] = f"{date_range[0]}T00:00:00.000Z" |
| 159 | body["endPublishedDate"] = f"{date_range[1]}T23:59:59.999Z" |
| 160 | return body |
| 161 | |
| 162 | |
| 163 | def exa_search( |
| 164 | query: str, |
| 165 | date_range: tuple[str, str] | None, |
| 166 | api_key: str, |
| 167 | count: int = 5, |
| 168 | *, |
| 169 | category: str | None = None, |
| 170 | objective: str | None = None, |
| 171 | deadline_monotonic: float | None = None, |
| 172 | retries: int | None = None, |
| 173 | ) -> tuple[list[dict], dict]: |
| 174 | """Search Exa. ``date_range`` is omitted for entity lookups and for |
| 175 | ``category`` values that reject publication-date filters. A caller with a |
| 176 | wall-clock budget passes ``deadline_monotonic`` and fewer ``retries``.""" |
| 177 | limits: dict = {} |
| 178 | if deadline_monotonic is not None: |
| 179 | limits["deadline_monotonic"] = deadline_monotonic |
| 180 | if retries is not None: |
| 181 | limits["retries"] = retries |
| 182 | data = http.request( |
| 183 | "POST", _EXA_SEARCH_URL, |
| 184 | headers={"x-api-key": api_key}, |
| 185 | json_data=_exa_search_body( |
| 186 | query, count, date_range, category=category, objective=objective, |
| 187 | ), |
| 188 | timeout=15, |
| 189 | **limits, |
| 190 | ) |
| 191 | items = [] |
| 192 | for i, r in enumerate((data.get("results", []))[:count]): |
| 193 | if not isinstance(r, dict): |
| 194 | continue |
| 195 | url = r.get("url", "") |
| 196 | if not url: |
| 197 | continue |
| 198 | raw_date = r.get("publishedDate") or "" |
| 199 | pub_date = _normalize_date(raw_date.split("T")[0] if "T" in raw_date else raw_date[:10]) if raw_date else None |
| 200 | if date_range and _known_date_out_of_range(pub_date, date_range): |
| 201 | continue |
| 202 | metadata = {} |
| 203 | if date_range and category not in _EXA_UNDATED_CATEGORIES: |
| 204 | metadata["date_window_basis"] = "server_bounds" |
| 205 | items.append({ |
| 206 | "id": f"WE{i + 1}", |
| 207 | "title": r.get("title", ""), |
| 208 | "url": url, |
| 209 | "source_domain": _domain(url), |
| 210 | "snippet": _exa_snippet(r), |
| 211 | "date": pub_date, |
| 212 | "relevance": 0.8, |
| 213 | "why_relevant": "Exa web search", |
| 214 | "metadata": metadata, |
| 215 | }) |
| 216 | artifact = {"label": "exa", "webSearchQueries": [query], "resultCount": len(items)} |
| 217 | if category: |
| 218 | artifact["category"] = category |
| 219 | return items, artifact |
| 220 | |
| 221 | |
| 222 | def exa_company_search( |
| 223 | query: str, |
| 224 | api_key: str, |
| 225 | count: int = 8, |
| 226 | *, |
| 227 | objective: str | None = None, |
| 228 | ) -> tuple[list[dict], dict]: |
| 229 | """Undated ``category=company`` search. Never sends publication dates.""" |
| 230 | return exa_search( |
| 231 | query, None, api_key, count, category="company", objective=objective, |
| 232 | ) |
| 233 | |
| 234 | |
| 235 | def exa_people_search( |
| 236 | query: str, |
| 237 | api_key: str, |
| 238 | count: int = 5, |
| 239 | *, |
| 240 | objective: str | None = None, |
| 241 | deadline_monotonic: float | None = None, |
| 242 | retries: int | None = None, |
| 243 | ) -> tuple[list[dict], dict]: |
| 244 | """Undated ``category=people`` search. Never sends dates or excludeDomains.""" |
| 245 | return exa_search( |
| 246 | query, None, api_key, count, category="people", objective=objective, |
| 247 | deadline_monotonic=deadline_monotonic, retries=retries, |
| 248 | ) |
| 249 | |
| 250 | |
| 251 | # --------------------------------------------------------------------------- |
| 252 | # Serper (Google Search wrapper) |
| 253 | # --------------------------------------------------------------------------- |
| 254 | |
| 255 | def serper_search( |
| 256 | query: str, date_range: tuple[str, str], api_key: str, count: int = 5, |
| 257 | *, include_news: bool = False, |
| 258 | ) -> tuple[list[dict], dict]: |
| 259 | data = http.request( |
| 260 | "POST", "https://google.serper.dev/search", |
| 261 | headers={"X-API-KEY": api_key}, |
| 262 | json_data={ |
| 263 | "q": query, |
| 264 | "num": count, |
| 265 | "tbs": f"cdr:1,cd_min:{_serper_date_param(date_range[0])},cd_max:{_serper_date_param(date_range[1])}", |
| 266 | }, |
| 267 | timeout=15, |
| 268 | ) |
| 269 | items = [] |
| 270 | organic = _result_rows(data.get("organic")) |
| 271 | for i, r in enumerate(organic if include_news else organic[:count]): |
| 272 | if not isinstance(r, dict) or not public_host.is_public_address_syntax(r.get("link")): |
| 273 | continue |
| 274 | raw_date = r.get("date") if isinstance(r.get("date"), str) else "" |
| 275 | pub_date = _parse_serper_date(raw_date) |
| 276 | if pub_date is None and _SERPER_RELATIVE_RE.match(raw_date.strip()): |
| 277 | continue |
| 278 | if _known_date_out_of_range(pub_date, date_range): |
| 279 | continue |
| 280 | items.append({ |
| 281 | "id": f"WS{i + 1}", |
| 282 | "title": r.get("title", ""), |
| 283 | "url": r.get("link", ""), |
| 284 | "source_domain": _domain(r.get("link", "")), |
| 285 | "snippet": r.get("snippet") or "", |
| 286 | "date": pub_date, |
| 287 | "relevance": 0.8, |
| 288 | "why_relevant": "Serper web search", |
| 289 | "metadata": {"date_window_basis": "server_bounds"}, |
| 290 | }) |
| 291 | if include_news: |
| 292 | items = _with_dated_news(items, _result_rows(data.get("topStories")), query, date_range, count, backend="serper") |
| 293 | artifact = {"label": "serper", "webSearchQueries": [query], "resultCount": len(items)} |
| 294 | return items, artifact |
| 295 | |
| 296 | |
| 297 | # --------------------------------------------------------------------------- |
| 298 | # Parallel AI Search |
| 299 | # --------------------------------------------------------------------------- |
| 300 | |
| 301 | def parallel_search( |
| 302 | query: str, date_range: tuple[str, str], api_key: str, count: int = 5, |
| 303 | ) -> tuple[list[dict], dict]: |
| 304 | current_window = date_range[1] >= datetime.now(timezone.utc).date().isoformat() |
| 305 | data = http.request( |
| 306 | "POST", "https://api.parallel.ai/v1/search", |
| 307 | headers={"x-api-key": api_key, "Content-Type": "application/json"}, |
| 308 | json_data={ |
| 309 | "search_queries": [query], |
| 310 | "advanced_settings": { |
| 311 | "max_results": count, |
| 312 | "source_policy": {"after_date": date_range[0]}, |
| 313 | }, |
| 314 | }, |
| 315 | timeout=15, |
| 316 | ) |
| 317 | items = [] |
| 318 | for i, r in enumerate((data.get("results", []))[:count]): |
| 319 | if not isinstance(r, dict): |
| 320 | continue |
| 321 | url = r.get("url", "") |
| 322 | if not url: |
| 323 | continue |
| 324 | raw_date = r.get("publish_date") or "" |
| 325 | pub_date = _normalize_date(raw_date[:10]) if raw_date else None |
| 326 | if _known_date_out_of_range(pub_date, date_range): |
| 327 | continue |
| 328 | if pub_date is None and not current_window: |
| 329 | continue |
| 330 | items.append({ |
| 331 | "id": f"WP{i + 1}", |
| 332 | "title": r.get("title", ""), |
| 333 | "url": url, |
| 334 | "source_domain": _domain(url), |
| 335 | "snippet": ((r.get("excerpts") or [""])[0] or "")[:500], |
| 336 | "date": pub_date, |
| 337 | "relevance": 0.8, |
| 338 | "why_relevant": "Parallel AI web search", |
| 339 | "metadata": { |
| 340 | "date_window_basis": "server_start_current" if current_window else "server_start" |
| 341 | }, |
| 342 | }) |
| 343 | artifact = {"label": "parallel", "webSearchQueries": [query], "resultCount": len(items)} |
| 344 | return items, artifact |
| 345 | |
| 346 | |
| 347 | _SERPER_RELATIVE_RE = re.compile( |
| 348 | r"^(?:about\s+)?(\d+)\s+(minute|min|hour|hr|day|week|month|year)s?\s+ago$", re.I |
| 349 | ) |
| 350 | _SERPER_RELATIVE_DAYS = {"day": 1, "week": 7, "month": 30, "year": 365} |
| 351 | _SERPER_RELATIVE_WORDS = {"just now": 0, "today": 0, "yesterday": 1} |
| 352 | |
| 353 | |
| 354 | def _now() -> datetime: |
| 355 | """Query-time UTC clock. Isolated so tests can pin it.""" |
| 356 | return datetime.now(timezone.utc) |
| 357 | |
| 358 | |
| 359 | def _parse_serper_relative(raw: str, now: datetime | None = None) -> str | None: |
| 360 | """Resolve Serper's relative dates ("2 hours ago") to an ISO date. |
| 361 | |
| 362 | Google renders a relative date for recent results, so the fresher a result |
| 363 | is the more likely it arrives in this form. Left unparsed it becomes None |
| 364 | and `_in_date_range` drops the item, which silently empties the web lane on |
| 365 | short research windows. |
| 366 | |
| 367 | The label states the result's age **at query time**, so it resolves against |
| 368 | the clock rather than against the end of the research window. The two differ |
| 369 | whenever `--as-of` names a past window: a result inside a window ending two |
| 370 | weeks ago is still labelled with its age as of today, and anchoring to the |
| 371 | window end would place it a further two weeks back and discard it. |
| 372 | |
| 373 | Sub-day units ("N minutes/hours ago") are subtracted from the clock rather |
| 374 | than rounded up to the current date, which would name the wrong day across |
| 375 | midnight: at 00:30 "23 hours ago" is yesterday. Residual slack comes only |
| 376 | from the timezone `_now()` reads against Google's. |
| 377 | |
| 378 | An age large enough to overflow `timedelta` or run past the end of `date` |
| 379 | reads as unparseable, like any other junk label, so one malformed value |
| 380 | cannot abort the whole result loop in `serper_search`. |
| 381 | """ |
| 382 | anchor = now or _now() |
| 383 | text = raw.strip().lower() |
| 384 | if text in _SERPER_RELATIVE_WORDS: |
| 385 | return (anchor.date() - timedelta(days=_SERPER_RELATIVE_WORDS[text])).isoformat() |
| 386 | m = _SERPER_RELATIVE_RE.match(text) |
| 387 | if not m: |
| 388 | return None |
| 389 | unit = {"min": "minute", "hr": "hour"}.get(m.group(2), m.group(2)) |
| 390 | try: |
| 391 | amount = int(m.group(1).lstrip("0") or "0") |
| 392 | if unit == "minute": |
| 393 | return (anchor - timedelta(minutes=amount)).date().isoformat() |
| 394 | if unit == "hour": |
| 395 | return (anchor - timedelta(hours=amount)).date().isoformat() |
| 396 | return ( |
| 397 | anchor.date() - timedelta(days=amount * _SERPER_RELATIVE_DAYS[unit]) |
| 398 | ).isoformat() |
| 399 | except (OverflowError, ValueError): |
| 400 | return None |
| 401 | |
| 402 | |
| 403 | def _parse_serper_date(raw: str, now: datetime | None = None) -> str | None: |
| 404 | if not raw: |
| 405 | return None |
| 406 | normalized = _normalize_date(raw) |
| 407 | if normalized: |
| 408 | return normalized |
| 409 | for fmt in ("%b %d, %Y", "%B %d, %Y", "%Y-%m-%d"): |
| 410 | try: |
| 411 | return datetime.strptime(raw.strip(), fmt).date().isoformat() |
| 412 | except ValueError: |
| 413 | continue |
| 414 | return _parse_serper_relative(raw, now) |
| 415 | |
| 416 | |
| 417 | def _result_rows(section: object) -> list: |
| 418 | if isinstance(section, dict): |
| 419 | section = section.get("results") |
| 420 | return section if isinstance(section, list) else [] |
| 421 | |
| 422 | |
| 423 | def _with_dated_news( |
| 424 | web: list[dict], stories: list, query: str, date_range: tuple[str, str], count: int, *, backend: str, |
| 425 | ) -> list[dict]: |
| 426 | """Interleave dated stories and web results from one response at the requested limit.""" |
| 427 | if not stories or count <= 0: |
| 428 | return web[:max(count, 0)] |
| 429 | web_by_url = {} |
| 430 | for item in web: |
| 431 | web_by_url.setdefault(fusion._normalize_url(item["url"]), item) |
| 432 | news_by_url = {} |
| 433 | brave = backend == "brave" |
| 434 | now = _now() |
| 435 | for index, story in enumerate(stories, 1): |
| 436 | if not isinstance(story, dict): |
| 437 | continue |
| 438 | url = story.get("url" if brave else "link") |
| 439 | title = story.get("title") |
| 440 | if not public_host.is_public_address_syntax(url) or not isinstance(title, str) or not title.strip(): |
| 441 | continue |
| 442 | raw_date = (story.get("page_age") or story.get("age")) if brave else story.get("date") |
| 443 | day = _parse_serper_date(raw_date, now) if isinstance(raw_date, str) else None |
| 444 | if not _in_date_range(day, date_range): |
| 445 | continue |
| 446 | key = fusion._normalize_url(url) |
| 447 | if key in news_by_url: |
| 448 | continue |
| 449 | snippet = story.get("description" if brave else "snippet") |
| 450 | if not isinstance(snippet, str) or not snippet.strip(): |
| 451 | snippet = web_by_url.get(key, {}).get("snippet", "") |
| 452 | news_by_url[key] = { |
| 453 | "id": f"WBN{index}" if brave else f"WSN{index}", |
| 454 | "title": title.strip(), "url": url, "source_domain": _domain(url), |
| 455 | "snippet": snippet, "date": day, "relevance": 0.8, |
| 456 | "why_relevant": "Brave news result" if brave else "Serper top story", |
| 457 | "metadata": {"date_window_basis": "server_bounds", "web_result_type": "news"}, |
| 458 | } |
| 459 | if not news_by_url: |
| 460 | return web[:count] |
| 461 | # The carousel can be longer than the entire stream. Let stories that name |
| 462 | # the subject reach the report ranker, keeping the provider order on ties. |
| 463 | topic = relevance.PreparedQuery(query) |
| 464 | news = sorted(news_by_url.values(), key=lambda item: relevance.token_overlap_relevance( |
| 465 | topic, f"{item['title']} {item['snippet']}", |
| 466 | ), reverse=True) |
| 467 | other_web = (item for key, item in web_by_url.items() if key not in news_by_url) |
| 468 | items = [] |
| 469 | for pair in zip_longest(news, other_web): |
| 470 | for item in pair: |
| 471 | if item is not None: |
| 472 | items.append(item) |
| 473 | if len(items) == count: |
| 474 | return items |
| 475 | return items |
| 476 | |
| 477 | |
| 478 | |
| 479 | |
| 480 | # --------------------------------------------------------------------------- |
| 481 | # Dispatcher |
| 482 | # --------------------------------------------------------------------------- |
| 483 | |
| 484 | def configured_backend(config: dict) -> str | None: |
| 485 | """Return the first configured search API backend, excluding keyless search. |
| 486 | |
| 487 | A backend the user holds a key for wins over one served by the API-key |
| 488 | proxy (lib/proxy.py), whatever their order below. |
| 489 | """ |
| 490 | backends = ( |
| 491 | ("brave", "BRAVE_API_KEY"), |
| 492 | ("exa", "EXA_API_KEY"), |
| 493 | ("serper", "SERPER_API_KEY"), |
| 494 | ("parallel", "PARALLEL_API_KEY"), |
| 495 | ) |
| 496 | for backend, key in backends: |
| 497 | if config.get(key) and not proxy.is_sentinel(config.get(key)): |
| 498 | return backend |
| 499 | for backend, key in backends: |
| 500 | # A proxy lane the service said it cannot serve is skipped for the run. |
| 501 | if config.get(key) and not proxy.provider_unavailable(backend): |
| 502 | return backend |
| 503 | return None |
| 504 | |
| 505 | |
| 506 | def web_search( |
| 507 | query: str, |
| 508 | date_range: tuple[str, str], |
| 509 | config: dict, |
| 510 | backend: str = "auto", |
| 511 | *, |
| 512 | include_news: bool = False, |
| 513 | deadline_monotonic: float | None = None, |
| 514 | cancel: threading.Event | None = None, |
| 515 | ) -> tuple[list[dict], dict]: |
| 516 | """Run web search with the specified or auto-detected backend.""" |
| 517 | if backend != "auto": |
| 518 | return _web_search_with( |
| 519 | backend, |
| 520 | query, |
| 521 | date_range, |
| 522 | config, |
| 523 | include_news=include_news, |
| 524 | deadline_monotonic=deadline_monotonic, |
| 525 | cancel=cancel, |
| 526 | ) |
| 527 | tried: set[str] = set() |
| 528 | while True: |
| 529 | chosen = configured_backend(config) or ( |
| 530 | "keyless" if env.keyless_web_allowed(config) else "none" |
| 531 | ) |
| 532 | try: |
| 533 | return _web_search_with( |
| 534 | chosen, |
| 535 | query, |
| 536 | date_range, |
| 537 | config, |
| 538 | include_news=include_news, |
| 539 | deadline_monotonic=deadline_monotonic, |
| 540 | cancel=cancel, |
| 541 | ) |
| 542 | except Exception: |
| 543 | # The service has no key for this proxied provider: try the next |
| 544 | # backend instead of failing the web source. |
| 545 | if chosen in tried or not proxy.provider_unavailable(chosen): |
| 546 | raise |
| 547 | tried.add(chosen) |
| 548 | |
| 549 | |
| 550 | def _web_search_with( |
| 551 | backend: str, |
| 552 | query: str, |
| 553 | date_range: tuple[str, str], |
| 554 | config: dict, |
| 555 | *, |
| 556 | include_news: bool = False, |
| 557 | deadline_monotonic: float | None = None, |
| 558 | cancel: threading.Event | None = None, |
| 559 | ) -> tuple[list[dict], dict]: |
| 560 | items: list[dict] = [] |
| 561 | artifact: dict = {} |
| 562 | effective_deadline = ( |
| 563 | deadline_monotonic |
| 564 | if deadline_monotonic is not None |
| 565 | else config.get("_research_deadline") |
| 566 | ) |
| 567 | effective_cancel = ( |
| 568 | cancel |
| 569 | if cancel is not None |
| 570 | else config.get("_enrich_cancel") |
| 571 | ) |
| 572 | news_options = {"include_news": True} if include_news else {} |
| 573 | if backend == "brave": |
| 574 | key = config.get("BRAVE_API_KEY") |
| 575 | if not key: |
| 576 | raise RuntimeError("BRAVE_API_KEY is required when web_backend='brave'") |
| 577 | items, artifact = brave_search(query, date_range, key, **news_options) |
| 578 | elif backend == "exa": |
| 579 | key = config.get("EXA_API_KEY") |
| 580 | if not key: |
| 581 | raise RuntimeError("EXA_API_KEY is required when web_backend='exa'") |
| 582 | items, artifact = exa_search(query, date_range, key) |
| 583 | elif backend == "serper": |
| 584 | key = config.get("SERPER_API_KEY") |
| 585 | if not key: |
| 586 | raise RuntimeError("SERPER_API_KEY is required when web_backend='serper'") |
| 587 | items, artifact = serper_search(query, date_range, key, **news_options) |
| 588 | elif backend == "parallel": |
| 589 | key = config.get("PARALLEL_API_KEY") |
| 590 | if not key: |
| 591 | raise RuntimeError("PARALLEL_API_KEY is required when web_backend='parallel'") |
| 592 | items, artifact = parallel_search(query, date_range, key) |
| 593 | elif backend == "parallel-mcp": |
| 594 | # The MCP client is not behind the http.request proxy seam, so it |
| 595 | # never receives the proxy-lane placeholder. |
| 596 | mcp_kwargs: dict = {} |
| 597 | if effective_deadline is not None: |
| 598 | mcp_kwargs["deadline_monotonic"] = min( |
| 599 | effective_deadline, |
| 600 | time.monotonic() + parallel_mcp._DEFAULT_SEARCH_TIMEOUT, |
| 601 | ) |
| 602 | if effective_cancel is not None: |
| 603 | mcp_kwargs["cancel"] = effective_cancel |
| 604 | items, artifact = parallel_mcp.search( |
| 605 | query, date_range, proxy.real_key(config.get("PARALLEL_API_KEY")), |
| 606 | **mcp_kwargs, |
| 607 | ) |
| 608 | elif backend == "keyless": |
| 609 | keyless_kwargs: dict = {} |
| 610 | if effective_deadline is not None: |
| 611 | keyless_kwargs["deadline_monotonic"] = effective_deadline |
| 612 | if effective_cancel is not None: |
| 613 | keyless_kwargs["cancel"] = effective_cancel |
| 614 | items, artifact = web_search_keyless.keyless_search( |
| 615 | query, date_range, config, **keyless_kwargs, |
| 616 | ) |
| 617 | elif backend != "none": |
| 618 | raise ValueError(f"Unsupported web backend: {backend!r}") |
| 619 | else: |
| 620 | return [], {} |
| 621 | enrich_deadline = _reddit_enrich_deadline(effective_deadline) |
| 622 | budget_stopped = bool( |
| 623 | (effective_cancel is not None and effective_cancel.is_set()) |
| 624 | or (enrich_deadline is not None and time.monotonic() >= enrich_deadline) |
| 625 | ) |
| 626 | if items and not _reddit_excluded(config) and not budget_stopped: |
| 627 | # Reddit enrichment is a best-effort secondary fetch on already-retrieved |
| 628 | # web results. Isolate its HTTP failures in a throwaway capture sink so a |
| 629 | # reddit.com fetch failure (e.g. a 403 on a datacenter IP) is not |
| 630 | # attributed to the web/grounding source itself — which would otherwise |
| 631 | # discard the successfully retrieved results and report the source failed. |
| 632 | enrich_kwargs: dict = {} |
| 633 | if effective_deadline is not None: |
| 634 | enrich_kwargs["deadline_monotonic"] = effective_deadline |
| 635 | if effective_cancel is not None: |
| 636 | enrich_kwargs["cancel"] = effective_cancel |
| 637 | with http.capture_failures(): |
| 638 | items = _enrich_reddit_items(items, **enrich_kwargs) |
| 639 | return items, artifact |
| 640 | |
| 641 | |
| 642 | # Reserve headroom before the outer run deadline so optional Reddit enrichment |
| 643 | # never crowds the stream future timeout and causes retrieved web results to be discarded. |
| 644 | _REDDIT_ENRICH_HEADROOM_SECONDS = 3.0 |
| 645 | |
| 646 | |
| 647 | def _reddit_enrich_deadline(deadline_monotonic: float | None) -> float | None: |
| 648 | if deadline_monotonic is None: |
| 649 | return None |
| 650 | return deadline_monotonic - _REDDIT_ENRICH_HEADROOM_SECONDS |
| 651 | |
| 652 | |
| 653 | def _reddit_excluded(config: dict) -> bool: |
| 654 | """Return True when EXCLUDE_SOURCES contains 'reddit'. |
| 655 | |
| 656 | Respects the same suppression knob the pipeline uses for source gating, |
| 657 | so a user who set EXCLUDE_SOURCES=reddit doesn't get Reddit content |
| 658 | smuggled back in via web-search URLs. |
| 659 | """ |
| 660 | raw = (config.get("EXCLUDE_SOURCES") or "").split(",") |
| 661 | return any(s.strip().lower() == "reddit" for s in raw) |
| 662 | |
| 663 | |
| 664 | def _enrich_reddit_items( |
| 665 | items: list[dict], |
| 666 | *, |
| 667 | deadline_monotonic: float | None = None, |
| 668 | cancel: threading.Event | None = None, |
| 669 | ) -> list[dict]: |
| 670 | """Enrich web search results that are Reddit threads with body and comments. |
| 671 | |
| 672 | Claude Code's WebFetch blocks reddit.com, so the model can't retrieve |
| 673 | Reddit content from web search results. Anonymous thread ``.json`` has |
| 674 | been refused since 2026, so the threads are filled through the Reddit |
| 675 | hydrator (Arctic Shift), which needs no key and never calls reddit.com. |
| 676 | A thread the hydrator could not fill stays as the search result gave it. |
| 677 | |
| 678 | Callers should gate this with EXCLUDE_SOURCES=reddit handling (see |
| 679 | `_reddit_excluded`) so a user who explicitly excluded Reddit doesn't |
| 680 | get Reddit content via web-search URLs. |
| 681 | """ |
| 682 | from . import reddit_hydrate, reddit_refs |
| 683 | |
| 684 | enrich_deadline = _reddit_enrich_deadline(deadline_monotonic) |
| 685 | if (cancel is not None and cancel.is_set()) or ( |
| 686 | enrich_deadline is not None and time.monotonic() >= enrich_deadline |
| 687 | ): |
| 688 | return items |
| 689 | refs_by_item: list[tuple[dict, reddit_refs.ThreadRef]] = [] |
| 690 | for item in items: |
| 691 | ref = reddit_refs.canonical_thread(str(item.get("url") or "")) |
| 692 | if ref is not None: |
| 693 | ref.provenance.add("web") |
| 694 | refs_by_item.append((item, ref)) |
| 695 | if not refs_by_item: |
| 696 | return items |
| 697 | hydrate_kwargs: dict = {} |
| 698 | if enrich_deadline is not None: |
| 699 | hydrate_kwargs["deadline"] = enrich_deadline |
| 700 | try: |
| 701 | hydrated = reddit_hydrate.hydrate( |
| 702 | [ref for _item, ref in refs_by_item], |
| 703 | **hydrate_kwargs, |
| 704 | ) |
| 705 | except (http.DeadlineExceeded, TimeoutError) as exc: |
| 706 | sys.stderr.write(f"[Web] Reddit enrichment timed out: {exc}\n") |
| 707 | return items |
| 708 | except Exception as exc: # enrichment is best-effort on results already in hand |
| 709 | sys.stderr.write(f"[Web] Reddit enrichment failed: {exc}\n") |
| 710 | return items |
| 711 | by_id: dict[str, dict] = {} |
| 712 | for thread in hydrated.items: |
| 713 | if not isinstance(thread, dict) or thread.get("engagement_source") == reddit_refs.UNKNOWN: |
| 714 | continue |
| 715 | meta = thread.get("metadata") |
| 716 | post_id = meta.get("post_id") if isinstance(meta, dict) else None |
| 717 | if post_id: |
| 718 | by_id[str(post_id)] = thread |
| 719 | for item, ref in refs_by_item: |
| 720 | thread = by_id.get(ref.post_id) |
| 721 | if thread is None: |
| 722 | continue |
| 723 | if not item.get("date") and thread.get("date"): |
| 724 | item["date"] = thread["date"] |
| 725 | selftext = thread.get("selftext") or "" |
| 726 | if selftext: |
| 727 | item["snippet"] = selftext[:2000] |
| 728 | thread_eng = thread.get("engagement") |
| 729 | if isinstance(thread_eng, dict): |
| 730 | thread_score = thread_eng.get("score") |
| 731 | if ( |
| 732 | isinstance(thread_score, (int, float)) |
| 733 | and not isinstance(thread_score, bool) |
| 734 | and math.isfinite(thread_score) |
| 735 | ): |
| 736 | item["reddit_thread_score"] = thread_score |
| 737 | subreddit = str(thread.get("subreddit") or ref.subreddit or "").strip().removeprefix("r/") |
| 738 | if subreddit: |
| 739 | item["reddit_subreddit"] = subreddit |
| 740 | top = thread.get("top_comments") or [] |
| 741 | if top: |
| 742 | enriched_comments: list[dict] = [] |
| 743 | for c in top[:5]: |
| 744 | if not isinstance(c, dict): |
| 745 | continue |
| 746 | entry: dict = { |
| 747 | "score": c.get("score"), |
| 748 | "excerpt": str(c.get("body") or c.get("excerpt") or "")[:200], |
| 749 | "depth": c.get("depth", 0), |
| 750 | } |
| 751 | if c.get("id"): |
| 752 | entry["id"] = str(c["id"]) |
| 753 | if c.get("author"): |
| 754 | entry["author"] = str(c["author"]) |
| 755 | if c.get("date"): |
| 756 | entry["date"] = str(c["date"]) |
| 757 | comment_url = c.get("url") |
| 758 | if not comment_url: |
| 759 | permalink = str(c.get("permalink") or "") |
| 760 | if permalink.startswith(("http://", "https://")): |
| 761 | comment_url = permalink |
| 762 | elif permalink.startswith("/"): |
| 763 | comment_url = f"https://reddit.com{permalink}" |
| 764 | if comment_url: |
| 765 | entry["url"] = str(comment_url) |
| 766 | if isinstance(c.get("is_uploader"), bool): |
| 767 | entry["is_uploader"] = c["is_uploader"] |
| 768 | if c.get("score_pending"): |
| 769 | entry["score_pending"] = True |
| 770 | enriched_comments.append(entry) |
| 771 | if enriched_comments: |
| 772 | item["top_comments"] = enriched_comments |
| 773 | item["enriched_via"] = "arctic" |
| 774 | return items |
| 775 | |
| 776 | |
| 777 | # --------------------------------------------------------------------------- |
| 778 | # Helpers |
| 779 | # --------------------------------------------------------------------------- |
| 780 | |
| 781 | def _normalize_date(value: object) -> str | None: |
| 782 | if value is None: |
| 783 | return None |
| 784 | parsed = dates.parse_date(str(value).strip()) |
| 785 | if not parsed: |
| 786 | return None |
| 787 | return parsed.date().isoformat() |
| 788 | |
| 789 | |
| 790 | def _serper_date_param(iso_date: str) -> str: |
| 791 | """Convert YYYY-MM-DD to MM/DD/YYYY for Serper tbs parameter.""" |
| 792 | parts = iso_date.split("-") |
| 793 | return f"{parts[1]}/{parts[2]}/{parts[0]}" |
| 794 | |
| 795 | |
| 796 | def _in_date_range(pub_date: str | None, date_range: tuple[str, str]) -> bool: |
| 797 | if not pub_date: |
| 798 | return False |
| 799 | return date_range[0] <= pub_date <= date_range[1] |
| 800 | |
| 801 | |
| 802 | def _known_date_out_of_range(pub_date: str | None, date_range: tuple[str, str]) -> bool: |
| 803 | """True when a parseable date falls outside the window. Unknown dates stay.""" |
| 804 | return pub_date is not None and not _in_date_range(pub_date, date_range) |
| 805 | |
| 806 | |
| 807 | def _domain(url: str) -> str: |
| 808 | return urlparse(url).netloc.strip().lower() |
| 809 |