| 1 | """Bird X search client for the v3.0.0 last30days pipeline. |
| 2 | |
| 3 | Uses a vendored subset of @steipete/bird v0.8.0 (MIT License) to search X |
| 4 | via Twitter's GraphQL API. No external `bird` CLI binary needed - just Node.js. |
| 5 | See scripts/lib/vendor/bird-search/package.json for authoritative version. |
| 6 | """ |
| 7 | |
| 8 | import json |
| 9 | import os |
| 10 | import shutil |
| 11 | import sys |
| 12 | import threading |
| 13 | import time |
| 14 | from pathlib import Path |
| 15 | |
| 16 | from . import env, health, http, log, subproc |
| 17 | from datetime import date, datetime, timedelta |
| 18 | from typing import Any, Dict, List, Optional, Tuple |
| 19 | |
| 20 | from .relevance import token_overlap_relevance as _compute_relevance |
| 21 | |
| 22 | # How many times to retry the bird-search subprocess when stdout is non-JSON |
| 23 | # (typically an HTML anti-bot interstitial from Twitter's edge). |
| 24 | MAX_JSON_DECODE_RETRIES = 2 |
| 25 | JSON_DECODE_RETRY_DELAY = 5.0 # seconds between retry attempts |
| 26 | |
| 27 | |
| 28 | def _leading_mentions(text: str) -> list: |
| 29 | """Leading-run @mention parse, shared with other X-shaped sources (xquik). |
| 30 | |
| 31 | Thin wrapper over ``query.leading_mentions`` so bird and xquik share one |
| 32 | implementation; kept here for existing call sites and tests. |
| 33 | """ |
| 34 | from .query import leading_mentions |
| 35 | return leading_mentions(text) |
| 36 | |
| 37 | |
| 38 | def _first_of(*values): |
| 39 | """Return first value that is not None.""" |
| 40 | for v in values: |
| 41 | if v is not None: |
| 42 | return v |
| 43 | return None |
| 44 | |
| 45 | # Path to the vendored bird-search wrapper |
| 46 | _BIRD_SEARCH_MJS = Path(__file__).parent / "vendor" / "bird-search" / "bird-search.mjs" |
| 47 | |
| 48 | # Depth configurations: number of results to request |
| 49 | DEPTH_CONFIG = { |
| 50 | "quick": 12, |
| 51 | "default": 30, |
| 52 | "deep": 60, |
| 53 | } |
| 54 | |
| 55 | # Module-level credentials injected from .env config |
| 56 | _credentials: Dict[str, str] = {} |
| 57 | _SECRET_ENV_NAMES = ("AUTH_TOKEN", "CT0", "TWITTER_AUTH_TOKEN", "TWITTER_CT0") |
| 58 | _seen_secrets: set[str] = set() |
| 59 | _secrets_lock = threading.Lock() |
| 60 | |
| 61 | |
| 62 | def _secret_variants(value: Optional[str]) -> List[str]: |
| 63 | if not isinstance(value, str) or not value: |
| 64 | return [] |
| 65 | variants: List[str] = [] |
| 66 | for candidate in (value, value.strip()): |
| 67 | # Short values would match too much ordinary text to be worth it. |
| 68 | if len(candidate) >= 8: |
| 69 | variants.append(candidate) |
| 70 | escaped = json.dumps(candidate)[1:-1] |
| 71 | if escaped != candidate and len(escaped) >= 8: |
| 72 | variants.append(escaped) |
| 73 | return variants |
| 74 | |
| 75 | |
| 76 | def _record_secret(value: Optional[str]) -> None: |
| 77 | variants = _secret_variants(value) |
| 78 | if not variants: |
| 79 | return |
| 80 | with _secrets_lock: |
| 81 | _seen_secrets.update(variants) |
| 82 | |
| 83 | # The vendored bird-search client reads exactly this env surface, and the |
| 84 | # node subprocess it spawns needs the node-runtime env (platform, locale, |
| 85 | # TLS/proxy config) to run in every environment it runs in today. Ambient |
| 86 | # BIRD_* vars pass through as well. Everything else in os.environ - unrelated |
| 87 | # API keys, tokens, .env contents - must not reach the scan-excluded vendored |
| 88 | # client (issue #1063). Mirrors the platform-var surface grok_x keeps for its |
| 89 | # node child (grok_x._subprocess_env). |
| 90 | _SUBPROCESS_ENV_ALLOWLIST = ( |
| 91 | # Runtime / platform vars the node subprocess needs (mirrors grok_x) |
| 92 | "PATH", "HOME", "LANG", "LC_ALL", "TMPDIR", "SystemRoot", |
| 93 | "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "SystemDrive", "COMSPEC", |
| 94 | "PATHEXT", "TEMP", "TMP", |
| 95 | # Node TLS / proxy / CA config for custom-CA and proxied environments |
| 96 | "NODE_ENV", "NODE_OPTIONS", "NODE_EXTRA_CA_CERTS", |
| 97 | "NODE_TLS_REJECT_UNAUTHORIZED", "NODE_USE_ENV_PROXY", |
| 98 | "SSL_CERT_FILE", "SSL_CERT_DIR", "HTTP_PROXY", "HTTPS_PROXY", "NO_PROXY", |
| 99 | "http_proxy", "https_proxy", "no_proxy", |
| 100 | # X session cookies the vendored client reads from the environment |
| 101 | "AUTH_TOKEN", "CT0", "TWITTER_AUTH_TOKEN", "TWITTER_CT0", |
| 102 | # Browser-cookie consent/disable flags the client reads (cookies.js) |
| 103 | "LAST30DAYS_DISABLE_BROWSER_COOKIES", "FROM_BROWSER", "BROWSER_CONSENT", |
| 104 | ) |
| 105 | |
| 106 | _BIRD_CAPTURE_LIMIT_BYTES = 8 * 1024 * 1024 |
| 107 | |
| 108 | |
| 109 | def _set_credentials_only(auth_token: Optional[str], ct0: Optional[str]) -> None: |
| 110 | """Update injected AUTH_TOKEN/CT0 without altering browser-failover state.""" |
| 111 | _record_secret(_credentials.get('AUTH_TOKEN')) |
| 112 | _record_secret(_credentials.get('CT0')) |
| 113 | if auth_token: |
| 114 | _record_secret(auth_token) |
| 115 | _credentials['AUTH_TOKEN'] = auth_token |
| 116 | else: |
| 117 | _credentials.pop('AUTH_TOKEN', None) |
| 118 | if ct0: |
| 119 | _record_secret(ct0) |
| 120 | _credentials['CT0'] = ct0 |
| 121 | else: |
| 122 | _credentials.pop('CT0', None) |
| 123 | |
| 124 | |
| 125 | def set_credentials(auth_token: Optional[str], ct0: Optional[str]): |
| 126 | """Inject AUTH_TOKEN/CT0 from .env config so Node subprocesses can use them.""" |
| 127 | global _session_browser, _next_session |
| 128 | with _session_lock: |
| 129 | _set_credentials_only(auth_token, ct0) |
| 130 | _session_browser = None |
| 131 | _next_session = None |
| 132 | |
| 133 | |
| 134 | # Browser-session failover: the browser that supplied the current session and |
| 135 | # a callback that extracts the next browser's session after X rejects it. |
| 136 | _session_browser: Optional[str] = None |
| 137 | _next_session: Optional[Any] = None |
| 138 | _session_lock = threading.Lock() |
| 139 | |
| 140 | |
| 141 | def set_session_failover(browser: Optional[str], next_session: Optional[Any]) -> None: |
| 142 | """Register where the injected session came from and how to replace it. |
| 143 | |
| 144 | ``next_session`` takes no arguments and returns ``(auth_token, ct0, |
| 145 | browser)`` for the next browser's session, or None when none is left. |
| 146 | """ |
| 147 | global _session_browser, _next_session |
| 148 | with _session_lock: |
| 149 | _session_browser = browser |
| 150 | _next_session = next_session |
| 151 | |
| 152 | |
| 153 | # X answers a search made with an expired or revoked session either with a |
| 154 | # 401 "Could not authenticate you" (code 32) or, for the POST SearchTimeline |
| 155 | # call, with HTTP 200 and a GraphQL "Internal server error" on the timeline. |
| 156 | _SESSION_REJECTED_MARKERS = ("could not authenticate", "http 401", "\"code\":32") |
| 157 | _SESSION_SUSPECT_MARKERS = ("internal server error",) |
| 158 | |
| 159 | |
| 160 | def _session_rejected(error: str) -> bool: |
| 161 | text = error.lower() |
| 162 | return any(m in text for m in _SESSION_REJECTED_MARKERS) |
| 163 | |
| 164 | |
| 165 | def _session_suspect(error: str) -> bool: |
| 166 | text = error.lower() |
| 167 | return _session_rejected(error) or any(m in text for m in _SESSION_SUSPECT_MARKERS) |
| 168 | |
| 169 | |
| 170 | def _has_injected_credentials() -> bool: |
| 171 | """Return True when both X session cookies were injected from config.""" |
| 172 | return bool(_credentials.get('AUTH_TOKEN') and _credentials.get('CT0')) |
| 173 | |
| 174 | |
| 175 | def _has_process_credentials() -> bool: |
| 176 | """Return True when AUTH_TOKEN/CT0 are present in process env.""" |
| 177 | return bool(env.read_secret_env("AUTH_TOKEN") and env.read_secret_env("CT0")) |
| 178 | |
| 179 | |
| 180 | def _subprocess_env() -> Dict[str, str]: |
| 181 | """Build env dict for Node subprocesses, merging injected credentials. |
| 182 | |
| 183 | The child env is limited to the vendored client's env surface (see |
| 184 | ``_SUBPROCESS_ENV_ALLOWLIST``) plus injected credentials, so unrelated |
| 185 | ambient secrets never reach scan-excluded vendored code (issue #1063). |
| 186 | The ambient-credential lane behaves exactly as before. |
| 187 | """ |
| 188 | env = { |
| 189 | name: os.environ[name] |
| 190 | for name in _SUBPROCESS_ENV_ALLOWLIST |
| 191 | if name in os.environ |
| 192 | } |
| 193 | env.update({ |
| 194 | key: value for key, value in os.environ.items() |
| 195 | if key.startswith("BIRD_") |
| 196 | }) |
| 197 | env.update(_credentials) |
| 198 | for secret_name in _SECRET_ENV_NAMES: |
| 199 | _record_secret(env.get(secret_name)) |
| 200 | # Hard-disable browser-cookie fallback so normal pipeline runs never hit |
| 201 | # Safari/Chrome Keychain prompts during source detection or search. |
| 202 | env["BIRD_DISABLE_BROWSER_COOKIES"] = "1" |
| 203 | return env |
| 204 | |
| 205 | |
| 206 | def _log(msg: str): |
| 207 | log.source_log("Bird", msg, tty_only=False) |
| 208 | |
| 209 | |
| 210 | def _scrub_credentials(text: str) -> str: |
| 211 | """Redact X session cookie values from subprocess output. |
| 212 | |
| 213 | A failure reason built from bird-search's stderr reaches the run's |
| 214 | ``source_status`` detail, which is rendered in the report and returned by |
| 215 | ``--emit=json``. The vendored client receives AUTH_TOKEN/CT0 in its |
| 216 | environment, so an error message that echoes a rejected cookie would |
| 217 | otherwise carry it into user-facing output. Log lines get the same |
| 218 | treatment because stderr is captured in agent harnesses. |
| 219 | """ |
| 220 | if not text: |
| 221 | return "" if text is None else text |
| 222 | scrubbed = str(text) |
| 223 | candidates: set[str] = set() |
| 224 | for name in _SECRET_ENV_NAMES: |
| 225 | cred_val = _credentials.get(name) |
| 226 | if cred_val: |
| 227 | _record_secret(cred_val) |
| 228 | candidates.update(_secret_variants(cred_val)) |
| 229 | env_val = os.environ.get(name) |
| 230 | if env_val: |
| 231 | _record_secret(env_val) |
| 232 | candidates.update(_secret_variants(env_val)) |
| 233 | with _secrets_lock: |
| 234 | candidates.update(_seen_secrets) |
| 235 | for secret in sorted(candidates, key=len, reverse=True): |
| 236 | scrubbed = scrubbed.replace(secret, "<redacted>") |
| 237 | return scrubbed |
| 238 | |
| 239 | |
| 240 | def classify_run_failure(detail: str) -> str: |
| 241 | """Map Bird's subprocess-only failure shapes to run outcome states.""" |
| 242 | text = detail.lower() |
| 243 | if any(marker in text for marker in ("interstitial", "non-json", "invalid json")): |
| 244 | return health.SCHEMA_DRIFT |
| 245 | if any( |
| 246 | marker in text |
| 247 | for marker in ( |
| 248 | "cookie expired", "expired cookie", "unauthorized", "forbidden", |
| 249 | "login required", "could not authenticate", "session rejected", |
| 250 | ) |
| 251 | ): |
| 252 | return health.AUTH_FAILED |
| 253 | return http.classify_failure(message=detail) |
| 254 | |
| 255 | |
| 256 | def _extract_core_subject(topic: str) -> str: |
| 257 | """Extract core subject from verbose query for X search. |
| 258 | |
| 259 | X search is literal keyword AND matching — all words must appear. |
| 260 | Aggressively strip question/meta/research words to keep only the |
| 261 | core product/concept name (max 5 words). |
| 262 | """ |
| 263 | from .query import extract_core_subject |
| 264 | return extract_core_subject(topic, max_words=5, strip_suffixes=True) |
| 265 | |
| 266 | |
| 267 | _PHRASE_MARKER = "\x00" |
| 268 | _QUERY_SEPARATORS = str.maketrans({char: " " for char in "“”()[]{}\\" + _PHRASE_MARKER}) |
| 269 | |
| 270 | # Use the public X recent-search query budget for Bird's SearchTimeline queries. |
| 271 | MAX_QUERY_CHARS = 512 |
| 272 | |
| 273 | |
| 274 | def _topic_query_terms(topic: str) -> list[str]: |
| 275 | """Return safe keywords and whole quoted phrases for the Bird compiler.""" |
| 276 | sections = topic.split('"') |
| 277 | if len(sections) % 2 == 0: |
| 278 | sections = [" ".join(sections)] |
| 279 | terms = [] |
| 280 | for index, section in enumerate(sections): |
| 281 | if index % 2: |
| 282 | phrase = section.replace(_PHRASE_MARKER, " ").strip() |
| 283 | if phrase: |
| 284 | terms.append(f'"{phrase}"') |
| 285 | continue |
| 286 | for token in section.translate(_QUERY_SEPARATORS).split(): |
| 287 | word = token.strip("'‘’") |
| 288 | if word.endswith(":") and word.count(":") == 1: |
| 289 | word = word[:-1] |
| 290 | if not word or ":" in word or word.startswith("-"): |
| 291 | continue |
| 292 | if word.upper() in ("AND", "OR"): |
| 293 | continue |
| 294 | terms.append(word) |
| 295 | return terms |
| 296 | |
| 297 | |
| 298 | def _fit_query(terms: list[str], filters: str, *, disjunction: bool = False) -> str: |
| 299 | """Fit complete terms and the date filters without emitting a window-only query.""" |
| 300 | prefix = "(" if disjunction else "" |
| 301 | suffix = f") {filters}" if disjunction else f" {filters}" |
| 302 | separator = " OR " if disjunction else " " |
| 303 | length = len(prefix) + len(suffix) |
| 304 | if not disjunction and terms and terms[0].startswith('"'): |
| 305 | if len(terms[0]) + terms[0].count("\\") + length > MAX_QUERY_CHARS: |
| 306 | terms = _topic_query_terms(terms[0][1:-1]) + terms[1:] |
| 307 | |
| 308 | fitted = [] |
| 309 | for term in terms: |
| 310 | if term.startswith('"'): |
| 311 | term = term.replace("\\", "\\\\") |
| 312 | added = len(term) + (len(separator) if fitted else 0) |
| 313 | if length + added > MAX_QUERY_CHARS: |
| 314 | if disjunction: |
| 315 | continue |
| 316 | break |
| 317 | fitted.append(term) |
| 318 | length += added |
| 319 | if not fitted: |
| 320 | return "" |
| 321 | return f"{prefix}{separator.join(fitted)}{suffix}" |
| 322 | |
| 323 | |
| 324 | def _date_filters(from_date: str, to_date: Optional[str] = None) -> str: |
| 325 | filters = f"since:{from_date}" |
| 326 | if to_date is not None: |
| 327 | end = date.fromisoformat(to_date) |
| 328 | if end == date.max: |
| 329 | # No supported post date lies beyond this inclusive upper bound. |
| 330 | return filters |
| 331 | # The research window includes to_date; X's until bound is exclusive. |
| 332 | until = end + timedelta(days=1) |
| 333 | filters += f" until:{until.isoformat()}" |
| 334 | return filters |
| 335 | |
| 336 | |
| 337 | def build_topic_query( |
| 338 | topic: str, from_date: str, to_date: Optional[str] = None |
| 339 | ) -> str: |
| 340 | """Build a bounded topic query with literal phrases and engine-owned dates.""" |
| 341 | return _fit_query(_topic_query_terms(topic), _date_filters(from_date, to_date)) |
| 342 | |
| 343 | |
| 344 | def is_bird_installed() -> bool: |
| 345 | """Check if vendored Bird search module is available. |
| 346 | |
| 347 | Returns: |
| 348 | True if bird-search.mjs exists and Node.js is in PATH. |
| 349 | """ |
| 350 | if not _BIRD_SEARCH_MJS.exists(): |
| 351 | return False |
| 352 | return shutil.which("node") is not None |
| 353 | |
| 354 | |
| 355 | def is_bird_authenticated() -> Optional[str]: |
| 356 | """Check if explicit X credentials are available. |
| 357 | |
| 358 | Returns: |
| 359 | Auth source string if authenticated, None otherwise. |
| 360 | """ |
| 361 | if not is_bird_installed(): |
| 362 | return None |
| 363 | |
| 364 | if _has_injected_credentials(): |
| 365 | return "env AUTH_TOKEN" |
| 366 | if _has_process_credentials(): |
| 367 | return "env AUTH_TOKEN" |
| 368 | return None |
| 369 | |
| 370 | |
| 371 | _probe_cache: Optional[Optional[bool]] = "unset" # "unset" | True | False | None |
| 372 | |
| 373 | |
| 374 | def probe_works(timeout: int = 8) -> Optional[bool]: |
| 375 | """Cheap runtime check that X auth actually returns data. |
| 376 | |
| 377 | Returns True when a 1-result probe comes back without an error, False on a |
| 378 | clear failure (auth error / generic search failure), and None when the |
| 379 | result is inconclusive (network timeout) so callers can fail open and keep |
| 380 | the static credential-presence status rather than reporting a false-down. |
| 381 | Cached per process so repeated diagnose calls don't re-probe. |
| 382 | """ |
| 383 | global _probe_cache |
| 384 | if _probe_cache != "unset": |
| 385 | return _probe_cache # type: ignore[return-value] |
| 386 | if not (_has_injected_credentials() or _has_process_credentials()): |
| 387 | _probe_cache = False |
| 388 | return False |
| 389 | from datetime import datetime, timedelta, timezone |
| 390 | since = (datetime.now(timezone.utc) - timedelta(days=30)).strftime("%Y-%m-%d") |
| 391 | # @x (the platform's own account) posts frequently, so a no-error response |
| 392 | # means auth works even if this particular window is quiet. |
| 393 | resp = _run_bird_search(f"from:x since:{since}", count=1, timeout=timeout) |
| 394 | if isinstance(resp, dict) and resp.get("error"): |
| 395 | err = str(resp.get("error")).lower() |
| 396 | if "timed out" in err or "timeout" in err: |
| 397 | _probe_cache = None # inconclusive — don't downgrade on a transient timeout |
| 398 | return None |
| 399 | _probe_cache = False |
| 400 | return False |
| 401 | _probe_cache = True |
| 402 | return True |
| 403 | |
| 404 | |
| 405 | def check_npm_available() -> bool: |
| 406 | """Check if npm is available (kept for API compatibility). |
| 407 | |
| 408 | Returns: |
| 409 | True if 'npm' command is available in PATH, False otherwise. |
| 410 | """ |
| 411 | return shutil.which("npm") is not None |
| 412 | |
| 413 | |
| 414 | def install_bird() -> Tuple[bool, str]: |
| 415 | """No-op. Bird search is vendored in v3.0.0, no installation needed. |
| 416 | |
| 417 | Returns: |
| 418 | Tuple of (success, message). |
| 419 | """ |
| 420 | if is_bird_installed(): |
| 421 | return True, "Bird search is bundled with /last30days v3.0.0 - no installation needed." |
| 422 | if not shutil.which("node"): |
| 423 | return False, "Node.js 22+ is required for X search. Install Node.js first." |
| 424 | return False, f"Vendored bird-search.mjs not found at {_BIRD_SEARCH_MJS}" |
| 425 | |
| 426 | |
| 427 | def get_bird_status() -> Dict[str, Any]: |
| 428 | """Get comprehensive Bird search status. |
| 429 | |
| 430 | Returns: |
| 431 | Dict with keys: installed, authenticated, username, can_install |
| 432 | """ |
| 433 | installed = is_bird_installed() |
| 434 | auth_source = is_bird_authenticated() if installed else None |
| 435 | |
| 436 | return { |
| 437 | "installed": installed, |
| 438 | "authenticated": auth_source is not None, |
| 439 | "username": auth_source, # Now returns auth source (e.g., "Safari", "env AUTH_TOKEN") |
| 440 | "can_install": True, # Always vendored in v3.0.0 |
| 441 | } |
| 442 | |
| 443 | |
| 444 | _MAX_NODE_TIMEOUT_MS = 2_147_483_647 |
| 445 | |
| 446 | |
| 447 | def _bird_timeout_ms(timeout: int, deadline: Optional[float]) -> int: |
| 448 | """Compute Node --timeout-ms with headroom before Python kills the child.""" |
| 449 | budget_ms = max(1, int(timeout * 1000)) |
| 450 | if deadline is not None: |
| 451 | remaining_ms = max(1, int((deadline - time.monotonic()) * 1000)) |
| 452 | budget_ms = min(budget_ms, remaining_ms) |
| 453 | # Leave flush headroom so Node self-aborts and writes partial JSON to stdout |
| 454 | # before subproc.run_with_timeout terminates the child process. |
| 455 | if budget_ms > 1000: |
| 456 | headroom_ms = min(1500, budget_ms // 5) |
| 457 | budget_ms = max(250, budget_ms - headroom_ms) |
| 458 | elif budget_ms > 250: |
| 459 | budget_ms = max(1, budget_ms - budget_ms // 5) |
| 460 | return min(budget_ms, _MAX_NODE_TIMEOUT_MS) |
| 461 | |
| 462 | |
| 463 | def _invoke_bird_subprocess( |
| 464 | query: str, |
| 465 | count: int, |
| 466 | timeout: int, |
| 467 | top: bool = False, |
| 468 | *, |
| 469 | deadline: Optional[float] = None, |
| 470 | cancel: Any = None, |
| 471 | ): |
| 472 | """Invoke the vendored bird-search.mjs subprocess once. |
| 473 | |
| 474 | Returns (result, error_dict). If error_dict is non-None, treat it as the |
| 475 | final result and do not retry — those errors are terminal (timeout, |
| 476 | spawn failure). If error_dict is None, the subprocess ran to completion |
| 477 | and `result` is the SubprocResult; the caller decides whether to retry |
| 478 | based on the result.stdout content. |
| 479 | """ |
| 480 | timeout_ms = _bird_timeout_ms(timeout, deadline) |
| 481 | cmd = [ |
| 482 | "node", str(_BIRD_SEARCH_MJS), |
| 483 | "--count", str(count), |
| 484 | "--timeout-ms", str(timeout_ms), |
| 485 | "--json", |
| 486 | ] |
| 487 | if top: |
| 488 | cmd.append("--top") |
| 489 | cmd.extend(["--", query]) |
| 490 | |
| 491 | try: |
| 492 | result = subproc.run_with_timeout( |
| 493 | cmd, |
| 494 | timeout=timeout, |
| 495 | env=_subprocess_env(), |
| 496 | cancel=cancel, |
| 497 | deadline_monotonic=deadline, |
| 498 | capture_limit_bytes=_BIRD_CAPTURE_LIMIT_BYTES, |
| 499 | ) |
| 500 | except subproc.SubprocTimeout: |
| 501 | if cancel is not None and cancel.is_set(): |
| 502 | return None, {"error": "bird: research cancelled", "items": []} |
| 503 | return None, {"error": f"Search timed out after {timeout}s", "items": []} |
| 504 | except Exception as e: |
| 505 | return None, {"error": _scrub_credentials(str(e)), "items": []} |
| 506 | |
| 507 | return result, None |
| 508 | |
| 509 | |
| 510 | def _invalid_json_error( |
| 511 | attempts: int, |
| 512 | decode_error: Optional[str], |
| 513 | budget_exhausted: bool = False, |
| 514 | ) -> Dict[str, Any]: |
| 515 | noun = "attempt" if attempts == 1 else "attempts" |
| 516 | skipped = ", retry skipped: chain budget exhausted" if budget_exhausted else "" |
| 517 | return { |
| 518 | "error": ( |
| 519 | f"Invalid JSON response after {attempts} {noun}{skipped} " |
| 520 | f"(likely Twitter anti-bot interstitial): {decode_error}" |
| 521 | ), |
| 522 | "items": [], |
| 523 | } |
| 524 | |
| 525 | |
| 526 | def _usable_item_count(response: Any) -> int: |
| 527 | """Count raw tweets in a Bird response that parse_bird_response will keep.""" |
| 528 | if isinstance(response, list): |
| 529 | raw_items = response |
| 530 | elif isinstance(response, dict): |
| 531 | raw_items = response.get("items", response.get("tweets", [])) |
| 532 | else: |
| 533 | return 0 |
| 534 | if not isinstance(raw_items, list): |
| 535 | return 0 |
| 536 | count = 0 |
| 537 | for tweet in raw_items: |
| 538 | if not isinstance(tweet, dict): |
| 539 | continue |
| 540 | url = tweet.get("permanent_url") or tweet.get("url", "") |
| 541 | if not url and tweet.get("id"): |
| 542 | author = tweet.get("author") or tweet.get("user") or {} |
| 543 | if isinstance(author, dict) and (author.get("username") or author.get("screen_name")): |
| 544 | url = "ok" |
| 545 | if url: |
| 546 | count += 1 |
| 547 | return count |
| 548 | |
| 549 | |
| 550 | def _run_bird_search( |
| 551 | query: str, |
| 552 | count: int, |
| 553 | timeout: int, |
| 554 | deadline: Optional[float] = None, |
| 555 | cancel: Any = None, |
| 556 | top: bool = False, |
| 557 | ) -> Dict[str, Any]: |
| 558 | """Run one search, moving to the next browser's X session on rejection. |
| 559 | |
| 560 | When X rejects the injected browser session (see ``_session_suspect``) |
| 561 | and another configured browser holds a different complete session, the |
| 562 | search is retried with that session, which then stays injected for the |
| 563 | rest of the run. Without a usable alternate, the error names the browser |
| 564 | whose session failed so the report says what to fix. |
| 565 | """ |
| 566 | best_partial: Optional[Dict[str, Any]] = None |
| 567 | best_partial_count = 0 |
| 568 | |
| 569 | def _keep_best_partial( |
| 570 | current: Dict[str, Any], current_error: str, current_count: int |
| 571 | ) -> Dict[str, Any]: |
| 572 | if best_partial is None or current_count >= best_partial_count: |
| 573 | return current |
| 574 | if current_error: |
| 575 | return {**best_partial, "error": _scrub_credentials(current_error)} |
| 576 | return best_partial |
| 577 | |
| 578 | while True: |
| 579 | started_with = _credentials.get('AUTH_TOKEN') |
| 580 | response = _run_bird_search_once( |
| 581 | query, count, timeout, deadline=deadline, cancel=cancel, top=top, |
| 582 | ) |
| 583 | error = str(response.get("error") or "") if isinstance(response, dict) else "" |
| 584 | usable_count = _usable_item_count(response) |
| 585 | if not error or not _session_suspect(error): |
| 586 | if best_partial is not None and usable_count < best_partial_count and (error or usable_count == 0): |
| 587 | return _keep_best_partial(response, error, usable_count) |
| 588 | return response |
| 589 | if usable_count > best_partial_count: |
| 590 | best_partial = response |
| 591 | best_partial_count = usable_count |
| 592 | if cancel is not None and cancel.is_set(): |
| 593 | return _keep_best_partial(response, error, usable_count) |
| 594 | failed_browser = _session_browser |
| 595 | # Never start browser reads (possible Keychain prompts) once the |
| 596 | # search budget can no longer fit a retry. |
| 597 | if deadline is not None and _clamped_bird_timeout(timeout, deadline) is None: |
| 598 | chosen = _keep_best_partial(response, error, usable_count) |
| 599 | return _annotate_session_error(chosen, error, failed_browser) |
| 600 | wait = -1 if deadline is None else max(0.0, deadline - time.monotonic()) |
| 601 | if not _session_lock.acquire(timeout=wait): |
| 602 | chosen = _keep_best_partial(response, error, usable_count) |
| 603 | return _annotate_session_error(chosen, error, failed_browser) |
| 604 | try: |
| 605 | if _credentials.get('AUTH_TOKEN') != started_with: |
| 606 | switched = True # another search already moved to a new session |
| 607 | else: |
| 608 | switched = False |
| 609 | failed_browser = _session_browser |
| 610 | nxt = ( |
| 611 | _next_session(deadline=deadline, cancel=cancel) |
| 612 | if _next_session is not None else None |
| 613 | ) |
| 614 | if nxt: |
| 615 | auth_token, ct0, browser = nxt |
| 616 | _set_credentials_only(auth_token, ct0) |
| 617 | _session_browser_update(browser) |
| 618 | log.source_log( |
| 619 | "X/bird", |
| 620 | f"X rejected the {failed_browser} session; retrying with {browser} cookies", |
| 621 | tty_only=False, |
| 622 | ) |
| 623 | switched = True |
| 624 | finally: |
| 625 | _session_lock.release() |
| 626 | if switched: |
| 627 | timeout = _clamped_bird_timeout(timeout, deadline) |
| 628 | if timeout is None: |
| 629 | return _keep_best_partial(response, error, usable_count) |
| 630 | continue |
| 631 | chosen = _keep_best_partial(response, error, usable_count) |
| 632 | return _annotate_session_error(chosen, error, failed_browser) |
| 633 | |
| 634 | |
| 635 | def _annotate_session_error( |
| 636 | response: Dict[str, Any], error: str, failed_browser: Optional[str] |
| 637 | ) -> Dict[str, Any]: |
| 638 | """Name the browser whose X session failed so the report says what to fix.""" |
| 639 | error = _scrub_credentials(error) |
| 640 | if not failed_browser: |
| 641 | return {**response, "error": error} if "error" in response else response |
| 642 | if _session_rejected(error): |
| 643 | return { |
| 644 | **response, |
| 645 | "error": ( |
| 646 | f"X session rejected (cookies from {failed_browser}): {error}. " |
| 647 | f"Log in to x.com again in {failed_browser}, or set FROM_BROWSER " |
| 648 | "to the browser you use for X." |
| 649 | ), |
| 650 | } |
| 651 | return { |
| 652 | **response, |
| 653 | "error": ( |
| 654 | f"{error} (X can return this when the {failed_browser} session " |
| 655 | f"is expired; if it persists, log in to x.com again in " |
| 656 | f"{failed_browser} or set FROM_BROWSER to the browser you use for X)" |
| 657 | ), |
| 658 | } |
| 659 | |
| 660 | |
| 661 | def _session_browser_update(browser: str) -> None: |
| 662 | global _session_browser |
| 663 | _session_browser = browser |
| 664 | |
| 665 | |
| 666 | def _run_bird_search_once( |
| 667 | query: str, |
| 668 | count: int, |
| 669 | timeout: int, |
| 670 | deadline: Optional[float] = None, |
| 671 | cancel: Any = None, |
| 672 | top: bool = False, |
| 673 | ) -> Dict[str, Any]: |
| 674 | """Run a search using the vendored bird-search.mjs module. |
| 675 | |
| 676 | Retries the subprocess on JSON-decode failure (typically a Twitter |
| 677 | anti-bot HTML interstitial in stdout) up to MAX_JSON_DECODE_RETRIES |
| 678 | times with JSON_DECODE_RETRY_DELAY seconds between attempts. Terminal |
| 679 | errors (subprocess timeout, non-zero return code) are returned |
| 680 | immediately without retry. |
| 681 | |
| 682 | Args: |
| 683 | query: Full search query string (including since: filter) |
| 684 | count: Number of results to request |
| 685 | timeout: Timeout in seconds (per attempt) |
| 686 | deadline: Optional shared ``time.monotonic()`` deadline. A decode |
| 687 | retry runs only when the delay plus at least one second of |
| 688 | subprocess time still fits; its timeout is re-clamped after the |
| 689 | delay. |
| 690 | |
| 691 | Returns: |
| 692 | Raw Bird JSON response or error dict. |
| 693 | """ |
| 694 | last_decode_error: Optional[str] = None |
| 695 | attempt_timeout: Optional[int] = timeout |
| 696 | |
| 697 | for attempt in range(MAX_JSON_DECODE_RETRIES): |
| 698 | if cancel is not None and cancel.is_set(): |
| 699 | return {"error": "bird: research cancelled", "items": []} |
| 700 | if attempt > 0: |
| 701 | attempt_timeout = _clamped_bird_timeout(timeout, deadline) |
| 702 | if attempt_timeout is None: |
| 703 | return _invalid_json_error( |
| 704 | attempt, last_decode_error, budget_exhausted=True, |
| 705 | ) |
| 706 | result, terminal_error = _invoke_bird_subprocess( |
| 707 | query, |
| 708 | count, |
| 709 | attempt_timeout, |
| 710 | top=top, |
| 711 | deadline=deadline, |
| 712 | cancel=cancel, |
| 713 | ) |
| 714 | if terminal_error is not None: |
| 715 | return terminal_error |
| 716 | |
| 717 | output = result.stdout.strip() |
| 718 | if result.returncode != 0: |
| 719 | if not output: |
| 720 | error = _scrub_credentials(result.stderr.strip()) or "Bird search failed" |
| 721 | return {"error": error, "items": []} |
| 722 | # Windows/Node 24: the vendored Bird CLI uses native fetch (undici), |
| 723 | # and calling process.exit() while keep-alive sockets are still |
| 724 | # closing trips a libuv assertion -> non-zero exit code AFTER it has |
| 725 | # already written a complete, valid JSON result to stdout. Trust |
| 726 | # stdout when it has content; only treat a non-zero exit as a real |
| 727 | # failure when stdout is empty. |
| 728 | |
| 729 | if not output: |
| 730 | return {"items": []} |
| 731 | |
| 732 | try: |
| 733 | parsed = json.loads(output) |
| 734 | except json.JSONDecodeError as e: |
| 735 | # Twitter's edge sometimes serves an HTML anti-bot interstitial |
| 736 | # in place of JSON. Tag the failure shape so it's distinguishable |
| 737 | # from "no results" in logs, then retry the subprocess. |
| 738 | looks_html = output.lstrip().lower().startswith(("<!doctype", "<html", "<")) |
| 739 | attempt_num = attempt + 1 |
| 740 | scrubbed_output = _scrub_credentials(output) |
| 741 | log_msg = ( |
| 742 | f"Bird search returned non-JSON stdout " |
| 743 | f"(looks_html={looks_html}, attempt {attempt_num}/{MAX_JSON_DECODE_RETRIES}, " |
| 744 | f"first 80 chars: {scrubbed_output[:80]!r})" |
| 745 | ) |
| 746 | last_decode_error = _scrub_credentials(str(e)) |
| 747 | if attempt_num < MAX_JSON_DECODE_RETRIES: |
| 748 | if deadline is not None and ( |
| 749 | deadline - time.monotonic() < JSON_DECODE_RETRY_DELAY + 1 |
| 750 | ): |
| 751 | log.source_log( |
| 752 | "X/bird", |
| 753 | f"{log_msg}; retry skipped, chain budget exhausted", |
| 754 | tty_only=False, |
| 755 | ) |
| 756 | return _invalid_json_error( |
| 757 | attempt_num, last_decode_error, budget_exhausted=True, |
| 758 | ) |
| 759 | log.source_log( |
| 760 | "X/bird", |
| 761 | f"{log_msg}; retrying in {JSON_DECODE_RETRY_DELAY:.0f}s", |
| 762 | tty_only=False, |
| 763 | ) |
| 764 | if cancel is not None: |
| 765 | cancel.wait(JSON_DECODE_RETRY_DELAY) |
| 766 | else: |
| 767 | time.sleep(JSON_DECODE_RETRY_DELAY) |
| 768 | continue |
| 769 | log.source_log("X/bird", log_msg, tty_only=False) |
| 770 | return _invalid_json_error(attempt_num, last_decode_error) |
| 771 | |
| 772 | if isinstance(parsed, list): |
| 773 | return {"items": parsed} |
| 774 | if isinstance(parsed, dict) and parsed.get("error"): |
| 775 | return {**parsed, "error": _scrub_credentials(str(parsed["error"]))} |
| 776 | return parsed |
| 777 | |
| 778 | # Defensive fallthrough — loop should always return above. |
| 779 | return { |
| 780 | "error": f"Bird search exhausted retries: {last_decode_error}", |
| 781 | "items": [], |
| 782 | } |
| 783 | |
| 784 | |
| 785 | def _clamped_bird_timeout(base: int, deadline: Optional[float]) -> Optional[int]: |
| 786 | """Per-attempt timeout clamped to the chain's remaining budget. |
| 787 | |
| 788 | Returns None when the deadline already passed so the caller skips the |
| 789 | subprocess instead of starting a call guaranteed to overrun the chain. |
| 790 | """ |
| 791 | if deadline is None: |
| 792 | return base |
| 793 | remaining = deadline - time.monotonic() |
| 794 | if remaining < 1: |
| 795 | return None |
| 796 | return max(1, min(base, int(remaining))) |
| 797 | |
| 798 | |
| 799 | def _budget_stop( |
| 800 | response: Dict[str, Any], |
| 801 | last_clean_response: Optional[Dict[str, Any]], |
| 802 | ) -> Dict[str, Any]: |
| 803 | """Outcome when an optional zero-result retry no longer fits the budget. |
| 804 | |
| 805 | A clean empty response stays a no-results outcome with a coverage warning; |
| 806 | otherwise the earlier search's own error (interstitial, timeout) is more |
| 807 | diagnostic than a generic budget message. |
| 808 | """ |
| 809 | _log("chain budget exhausted; skipping remaining zero-result retries") |
| 810 | if last_clean_response is not None: |
| 811 | return { |
| 812 | **last_clean_response, |
| 813 | "warning": "Partial coverage: optional zero-result retries skipped because the search budget was exhausted.", |
| 814 | } |
| 815 | return response |
| 816 | |
| 817 | |
| 818 | def search_x( |
| 819 | topic: str, |
| 820 | from_date: str, |
| 821 | to_date: str, |
| 822 | depth: str = "default", |
| 823 | deadline: Optional[float] = None, |
| 824 | cancel: Any = None, |
| 825 | ) -> Dict[str, Any]: |
| 826 | """Search X using Bird CLI with automatic retry on 0 results. |
| 827 | |
| 828 | Args: |
| 829 | topic: Search topic |
| 830 | from_date: Start date (YYYY-MM-DD) |
| 831 | to_date: Inclusive end date (YYYY-MM-DD) |
| 832 | depth: Research depth - "quick", "default", or "deep" |
| 833 | deadline: Optional shared wall-clock deadline (``time.monotonic()`` |
| 834 | instant) from the X backend chain. Each of the up-to-four |
| 835 | sequential searches clamps its per-attempt timeout to the time |
| 836 | left; searches past the deadline never start. |
| 837 | |
| 838 | Returns: |
| 839 | Raw Bird JSON response or error dict. |
| 840 | """ |
| 841 | count = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 842 | search_kwargs = {"cancel": cancel} if cancel is not None else {} |
| 843 | # Topic searches read X's Top tab. Latest is a time-ordered feed, so on a |
| 844 | # busy topic its first page is the last few minutes of zero-engagement |
| 845 | # posts, and handle expansion then promotes whoever happened to post in |
| 846 | # those minutes. Handle and mention searches keep Latest for coverage. |
| 847 | search_kwargs["top"] = True |
| 848 | base_timeout = 30 if depth == "quick" else 45 if depth == "default" else 60 |
| 849 | timeout = _clamped_bird_timeout(base_timeout, deadline) |
| 850 | if timeout is None: |
| 851 | return {"error": "bird: chain budget exhausted", "items": []} |
| 852 | |
| 853 | terms = _topic_query_terms(topic) |
| 854 | # Protect literal phrases from the shared subject extractor's casing, |
| 855 | # noise filtering, and word cap. |
| 856 | phrases = {} |
| 857 | protected_terms = [] |
| 858 | for index, term in enumerate(terms): |
| 859 | if term.startswith('"'): |
| 860 | marker = f"{_PHRASE_MARKER}{index}" |
| 861 | phrases[marker] = term |
| 862 | term = marker |
| 863 | protected_terms.append(term) |
| 864 | core_subject = _extract_core_subject(" ".join(protected_terms)) |
| 865 | core_terms = _topic_query_terms(" ".join(phrases.get(word, word) for word in core_subject.split())) |
| 866 | exact_phrases = list(phrases.values()) |
| 867 | retry_keywords = exact_phrases + [term for term in core_terms if not term.startswith('"')] |
| 868 | core_topic = " ".join(core_terms).replace('"', "") |
| 869 | date_filters = _date_filters(from_date, to_date) |
| 870 | query = _fit_query(core_terms, date_filters) |
| 871 | if not query: |
| 872 | return {"error": "bird: no searchable keywords fit the topic query", "items": []} |
| 873 | |
| 874 | _log(f"Searching: {query}") |
| 875 | response = _run_bird_search(query, count, timeout, deadline=deadline, **search_kwargs) |
| 876 | last_clean_response = response if not response.get("error") else None |
| 877 | |
| 878 | # Check if we got results |
| 879 | items = parse_bird_response(response, query=core_topic) |
| 880 | |
| 881 | # Retry with OR groups for multi-word queries (X supports OR operator) |
| 882 | if not items and len(core_terms) >= 2: |
| 883 | from .query import extract_compound_terms |
| 884 | alternatives = exact_phrases |
| 885 | if not alternatives: |
| 886 | compounds = extract_compound_terms(" ".join(terms)) |
| 887 | alternatives = ['"' + term.strip('"') + '"' for term in compounds] |
| 888 | query = _fit_query(alternatives[:3], date_filters, disjunction=True) |
| 889 | if query: |
| 890 | _log(f"0 results for '{core_topic}', retrying with OR groups: {query}") |
| 891 | timeout = _clamped_bird_timeout(base_timeout, deadline) |
| 892 | if timeout is None: |
| 893 | return _budget_stop(response, last_clean_response) |
| 894 | response = _run_bird_search(query, count, timeout, deadline=deadline, **search_kwargs) |
| 895 | if not response.get("error"): |
| 896 | last_clean_response = response |
| 897 | items = parse_bird_response(response, query=core_topic) |
| 898 | |
| 899 | # Retry with fewer keywords if still 0 results and query has 3+ words |
| 900 | query = "" |
| 901 | if not items and len(retry_keywords) > 2: |
| 902 | query = _fit_query(retry_keywords[:2], date_filters) |
| 903 | if query: |
| 904 | _log(f"0 results for '{core_topic}', retrying with '{query}'") |
| 905 | timeout = _clamped_bird_timeout(base_timeout, deadline) |
| 906 | if timeout is None: |
| 907 | return _budget_stop(response, last_clean_response) |
| 908 | response = _run_bird_search(query, count, timeout, deadline=deadline, **search_kwargs) |
| 909 | if not response.get("error"): |
| 910 | last_clean_response = response |
| 911 | items = parse_bird_response(response, query=core_topic) |
| 912 | |
| 913 | # Last-chance retry: use strongest remaining token (often the product name) |
| 914 | if not items: |
| 915 | low_signal = { |
| 916 | 'trendiest', 'trending', 'hottest', 'hot', 'popular', 'viral', |
| 917 | 'best', 'top', 'latest', 'new', 'plugin', 'plugins', |
| 918 | 'skill', 'skills', 'tool', 'tools', |
| 919 | } |
| 920 | candidates = [term for term in retry_keywords if term not in low_signal] |
| 921 | query = "" |
| 922 | if candidates: |
| 923 | # Keep an entity anchor (the first distinctive topic token) in the |
| 924 | # retry so it can't collapse to a bare generic token like "compound" |
| 925 | # and flood the X pool with off-topic noise. Add the strongest |
| 926 | # (longest) distinctive token when it differs from the anchor; |
| 927 | # otherwise query the anchor alone. Better to return 0 than to |
| 928 | # over-broaden to an unanchored generic term. |
| 929 | anchor = candidates[0] |
| 930 | strongest = max(candidates, key=len) |
| 931 | anchored_terms = [anchor] if strongest == anchor else [anchor, strongest] |
| 932 | query = _fit_query(anchored_terms, date_filters) |
| 933 | if query: |
| 934 | _log(f"0 results for '{core_topic}', retrying anchored on '{query}'") |
| 935 | timeout = _clamped_bird_timeout(base_timeout, deadline) |
| 936 | if timeout is None: |
| 937 | return _budget_stop(response, last_clean_response) |
| 938 | response = _run_bird_search(query, count, timeout, deadline=deadline, **search_kwargs) |
| 939 | if not response.get("error"): |
| 940 | last_clean_response = response |
| 941 | items = parse_bird_response(response, query=core_topic) |
| 942 | |
| 943 | if cancel is not None and cancel.is_set(): |
| 944 | return {**response, "error": "bird: research cancelled"} |
| 945 | if response.get("error") and not items and last_clean_response is not None: |
| 946 | _log("Optional retry failed after a clean empty response; preserving no-results outcome") |
| 947 | return last_clean_response |
| 948 | return response |
| 949 | |
| 950 | |
| 951 | def search_handles( |
| 952 | handles: List[str], |
| 953 | topic: Optional[str], |
| 954 | from_date: str, |
| 955 | count_per: int = 5, |
| 956 | failure_out: Optional[List[str]] = None, |
| 957 | *, |
| 958 | to_date: Optional[str] = None, |
| 959 | deadline: Optional[float] = None, |
| 960 | cancel: Any = None, |
| 961 | ) -> List[Dict[str, Any]]: |
| 962 | """Search specific X handles for topic-related content. |
| 963 | |
| 964 | Pulls each handle's actual timeline via `from:handle since:` — the FROM |
| 965 | lane (tweets BY the person), engagement-weighted downstream. The topic is |
| 966 | used for relevance RANKING, never AND'd into the query: X search is literal, |
| 967 | so `from:handle <their name>` only matched tweets where they wrote their own |
| 968 | name and returned ~0. Used in Phase 2 after entity extraction. |
| 969 | |
| 970 | Args: |
| 971 | handles: List of X handles to search (without @) |
| 972 | topic: Search topic — used for relevance ranking only, not the query |
| 973 | from_date: Start date (YYYY-MM-DD) |
| 974 | count_per: Results to request per handle |
| 975 | failure_out: When provided, a short reason is appended for every |
| 976 | per-handle failure branch, so the caller can distinguish a |
| 977 | transport failure from a handle that genuinely posted nothing. |
| 978 | to_date: Inclusive end date (YYYY-MM-DD), when supplied |
| 979 | |
| 980 | Returns: |
| 981 | List of raw item dicts (same format as parse_bird_response output). |
| 982 | """ |
| 983 | if not handles: |
| 984 | return [] |
| 985 | core_topic = _extract_core_subject(topic) if topic else None |
| 986 | date_filters = _date_filters(from_date, to_date) |
| 987 | |
| 988 | def _note(msg: str) -> None: |
| 989 | if failure_out is not None: |
| 990 | failure_out.append(msg) |
| 991 | |
| 992 | def _search_one_handle(handle: str) -> List[Dict[str, Any]]: |
| 993 | timeout = _clamped_bird_timeout(15, deadline) |
| 994 | if timeout is None or (cancel is not None and cancel.is_set()): |
| 995 | _note("bird handle research cancelled or timed out") |
| 996 | return [] |
| 997 | handle = handle.lstrip("@") |
| 998 | # Always unfiltered: pull the timeline, rank by topic relevance below. |
| 999 | query = f"from:{handle} {date_filters}" |
| 1000 | |
| 1001 | timeout_ms = _bird_timeout_ms(timeout, deadline) |
| 1002 | cmd = [ |
| 1003 | "node", str(_BIRD_SEARCH_MJS), |
| 1004 | "--count", str(count_per), |
| 1005 | "--timeout-ms", str(timeout_ms), |
| 1006 | "--json", |
| 1007 | "--", |
| 1008 | query, |
| 1009 | ] |
| 1010 | |
| 1011 | try: |
| 1012 | result = subproc.run_with_timeout( |
| 1013 | cmd, |
| 1014 | timeout=timeout, |
| 1015 | env=_subprocess_env(), |
| 1016 | cancel=cancel, |
| 1017 | deadline_monotonic=deadline, |
| 1018 | capture_limit_bytes=_BIRD_CAPTURE_LIMIT_BYTES, |
| 1019 | ) |
| 1020 | except subproc.SubprocTimeout: |
| 1021 | if cancel is not None and cancel.is_set(): |
| 1022 | _log(f"Handle search cancelled for @{handle}") |
| 1023 | _note(f"@{handle}: bird-search cancelled") |
| 1024 | else: |
| 1025 | _log(f"Handle search timed out for @{handle}") |
| 1026 | _note(f"@{handle}: bird-search timed out after {timeout}s") |
| 1027 | return [] |
| 1028 | except OSError as e: |
| 1029 | err = _scrub_credentials(str(e)) |
| 1030 | _log(f"Handle search error for @{handle}: {err}") |
| 1031 | _note(f"@{handle}: could not spawn bird-search ({err})") |
| 1032 | return [] |
| 1033 | |
| 1034 | output = result.stdout.strip() |
| 1035 | if result.returncode != 0: |
| 1036 | if not output: |
| 1037 | _log(f"Handle search failed for @{handle}: {_scrub_credentials(result.stderr.strip())}") |
| 1038 | _note( |
| 1039 | f"@{handle}: bird-search exited {result.returncode} " |
| 1040 | f"({_scrub_credentials(result.stderr.strip())[:160] or 'no stderr'})" |
| 1041 | ) |
| 1042 | return [] |
| 1043 | # Windows/Node 24 benign libuv assertion or partial-page JSON error: |
| 1044 | # stdout carries the JSON payload. |
| 1045 | |
| 1046 | if not output: |
| 1047 | return [] |
| 1048 | |
| 1049 | try: |
| 1050 | response = json.loads(output) |
| 1051 | except json.JSONDecodeError: |
| 1052 | _log(f"Invalid JSON from handle search for @{handle}") |
| 1053 | _note(f"@{handle}: bird-search returned invalid JSON") |
| 1054 | return [] |
| 1055 | if isinstance(response, dict) and response.get("error"): |
| 1056 | err = _scrub_credentials(str(response["error"])) |
| 1057 | _log(f"Handle search error for @{handle}: {err}") |
| 1058 | _note(f"@{handle}: {err[:160]}") |
| 1059 | items = parse_bird_response(response, query=core_topic) |
| 1060 | # Log on success/empty too (not only on failure): a silent handle search |
| 1061 | # made the from: query look like it never ran and caused wrong diagnoses. |
| 1062 | _log(f"Searching: {query} -> {len(items)} results") |
| 1063 | return items |
| 1064 | |
| 1065 | from concurrent.futures import ThreadPoolExecutor, as_completed |
| 1066 | |
| 1067 | all_items: List[Dict[str, Any]] = [] |
| 1068 | with ThreadPoolExecutor(max_workers=min(5, len(handles))) as executor: |
| 1069 | futures = {executor.submit(_search_one_handle, h): h for h in handles} |
| 1070 | for future in as_completed(futures): |
| 1071 | all_items.extend(future.result()) |
| 1072 | |
| 1073 | return all_items |
| 1074 | |
| 1075 | |
| 1076 | def search_mentions( |
| 1077 | handles: List[str], |
| 1078 | from_date: str, |
| 1079 | count_per: int = 5, |
| 1080 | failure_out: Optional[List[str]] = None, |
| 1081 | *, |
| 1082 | to_date: Optional[str] = None, |
| 1083 | deadline: Optional[float] = None, |
| 1084 | cancel: Any = None, |
| 1085 | ) -> List[Dict[str, Any]]: |
| 1086 | """Search for tweets ABOUT/TO each handle — the mention lane. |
| 1087 | |
| 1088 | Queries `@handle since:` (tweets that mention the account) and excludes the |
| 1089 | handle's OWN tweets (those belong to the FROM lane via search_handles), so |
| 1090 | this surfaces what OTHERS are saying about the person. Engagement-weighted |
| 1091 | downstream; deduped against the FROM lane by URL at normalize time. |
| 1092 | |
| 1093 | Args: |
| 1094 | handles: List of X handles (without @) |
| 1095 | from_date: Start date (YYYY-MM-DD) |
| 1096 | count_per: Results to request per handle |
| 1097 | failure_out: When provided, a short reason is appended for every |
| 1098 | per-handle failure branch, so the caller can distinguish a |
| 1099 | transport failure from a handle nobody mentioned. |
| 1100 | to_date: Inclusive end date (YYYY-MM-DD), when supplied |
| 1101 | |
| 1102 | Returns: |
| 1103 | List of raw item dicts (same format as parse_bird_response output). |
| 1104 | """ |
| 1105 | if not handles: |
| 1106 | return [] |
| 1107 | date_filters = _date_filters(from_date, to_date) |
| 1108 | |
| 1109 | def _note(msg: str) -> None: |
| 1110 | if failure_out is not None: |
| 1111 | failure_out.append(msg) |
| 1112 | |
| 1113 | def _search_one(handle: str) -> List[Dict[str, Any]]: |
| 1114 | timeout = _clamped_bird_timeout(15, deadline) |
| 1115 | if timeout is None or (cancel is not None and cancel.is_set()): |
| 1116 | _note("bird mention research cancelled or timed out") |
| 1117 | return [] |
| 1118 | handle = handle.lstrip("@") |
| 1119 | query = f"@{handle} {date_filters}" |
| 1120 | timeout_ms = _bird_timeout_ms(timeout, deadline) |
| 1121 | cmd = [ |
| 1122 | "node", str(_BIRD_SEARCH_MJS), |
| 1123 | "--count", str(count_per), |
| 1124 | "--timeout-ms", str(timeout_ms), |
| 1125 | "--json", |
| 1126 | "--", |
| 1127 | query, |
| 1128 | ] |
| 1129 | try: |
| 1130 | result = subproc.run_with_timeout( |
| 1131 | cmd, |
| 1132 | timeout=timeout, |
| 1133 | env=_subprocess_env(), |
| 1134 | cancel=cancel, |
| 1135 | deadline_monotonic=deadline, |
| 1136 | capture_limit_bytes=_BIRD_CAPTURE_LIMIT_BYTES, |
| 1137 | ) |
| 1138 | except subproc.SubprocTimeout: |
| 1139 | if cancel is not None and cancel.is_set(): |
| 1140 | _log(f"Mention search cancelled for @{handle}") |
| 1141 | _note(f"@{handle}: bird-search cancelled") |
| 1142 | else: |
| 1143 | _log(f"Mention search timed out for @{handle}") |
| 1144 | _note(f"@{handle}: bird-search timed out after {timeout}s") |
| 1145 | return [] |
| 1146 | except OSError as e: |
| 1147 | err = _scrub_credentials(str(e)) |
| 1148 | _log(f"Mention search error for @{handle}: {err}") |
| 1149 | _note(f"@{handle}: could not spawn bird-search ({err})") |
| 1150 | return [] |
| 1151 | output = result.stdout.strip() |
| 1152 | if result.returncode != 0: |
| 1153 | if not output: |
| 1154 | _log(f"Mention search failed for @{handle}: {_scrub_credentials(result.stderr.strip())}") |
| 1155 | _note( |
| 1156 | f"@{handle}: bird-search exited {result.returncode} " |
| 1157 | f"({_scrub_credentials(result.stderr.strip())[:160] or 'no stderr'})" |
| 1158 | ) |
| 1159 | return [] |
| 1160 | # Windows/Node 24 benign libuv assertion or partial-page JSON error: |
| 1161 | # stdout carries the JSON payload. |
| 1162 | if not output: |
| 1163 | return [] |
| 1164 | try: |
| 1165 | response = json.loads(output) |
| 1166 | except json.JSONDecodeError: |
| 1167 | _log(f"Invalid JSON from mention search for @{handle}") |
| 1168 | _note(f"@{handle}: bird-search returned invalid JSON") |
| 1169 | return [] |
| 1170 | if isinstance(response, dict) and response.get("error"): |
| 1171 | err = _scrub_credentials(str(response["error"])) |
| 1172 | _log(f"Mention search error for @{handle}: {err}") |
| 1173 | _note(f"@{handle}: {err[:160]}") |
| 1174 | items = parse_bird_response(response, query=None) |
| 1175 | # ABOUT lane = OTHERS mentioning the handle. Drop the handle's own tweets |
| 1176 | # (the FROM lane already covers those); identify by the status URL author. |
| 1177 | hl = handle.lower() |
| 1178 | # The Bird API may return either x.com or twitter.com permalinks, so |
| 1179 | # match both when excluding the handle's own tweets. |
| 1180 | def _is_own(url): |
| 1181 | u = (url or "").lower() |
| 1182 | return f"x.com/{hl}/status" in u or f"twitter.com/{hl}/status" in u |
| 1183 | about = [it for it in items if not _is_own(it.get("url"))] |
| 1184 | _log(f"Searching: {query} -> {len(about)} mentions") |
| 1185 | return about |
| 1186 | |
| 1187 | from concurrent.futures import ThreadPoolExecutor, as_completed |
| 1188 | |
| 1189 | all_items: List[Dict[str, Any]] = [] |
| 1190 | with ThreadPoolExecutor(max_workers=min(5, len(handles))) as executor: |
| 1191 | futures = {executor.submit(_search_one, h): h for h in handles} |
| 1192 | for future in as_completed(futures): |
| 1193 | all_items.extend(future.result()) |
| 1194 | return all_items |
| 1195 | |
| 1196 | |
| 1197 | def parse_bird_response(response: Dict[str, Any], query: str = "") -> List[Dict[str, Any]]: |
| 1198 | """Parse Bird response to match xai_x output format. |
| 1199 | |
| 1200 | Args: |
| 1201 | response: Raw Bird JSON response |
| 1202 | query: Original search query for relevance scoring |
| 1203 | |
| 1204 | Returns: |
| 1205 | List of normalized item dicts matching xai_x.parse_x_response() format. |
| 1206 | """ |
| 1207 | items = [] |
| 1208 | |
| 1209 | # Log any reported error (scrubbed), while still parsing partial items when |
| 1210 | # a multi-page search succeeded on page 1 before failing on page 2+. |
| 1211 | if isinstance(response, dict) and "error" in response and response["error"]: |
| 1212 | _log(f"Bird error: {_scrub_credentials(str(response['error']))}") |
| 1213 | |
| 1214 | # Bird returns a list of tweets directly or under a key |
| 1215 | raw_items = response if isinstance(response, list) else ( |
| 1216 | response.get("items", response.get("tweets", [])) if isinstance(response, dict) else [] |
| 1217 | ) |
| 1218 | |
| 1219 | if not isinstance(raw_items, list): |
| 1220 | return items |
| 1221 | |
| 1222 | for i, tweet in enumerate(raw_items): |
| 1223 | if not isinstance(tweet, dict): |
| 1224 | continue |
| 1225 | |
| 1226 | # Extract URL - Bird uses permanent_url or we construct from id |
| 1227 | url = tweet.get("permanent_url") or tweet.get("url", "") |
| 1228 | if not url and tweet.get("id"): |
| 1229 | # Try different field structures Bird might use |
| 1230 | author = tweet.get("author", {}) or tweet.get("user", {}) |
| 1231 | screen_name = author.get("username") or author.get("screen_name", "") |
| 1232 | if screen_name: |
| 1233 | url = f"https://x.com/{screen_name}/status/{tweet['id']}" |
| 1234 | |
| 1235 | if not url: |
| 1236 | continue |
| 1237 | |
| 1238 | # Parse date from created_at/createdAt (e.g., "Wed Jan 15 14:30:00 +0000 2026") |
| 1239 | date = None |
| 1240 | created_at = tweet.get("createdAt") or tweet.get("created_at", "") |
| 1241 | if created_at: |
| 1242 | try: |
| 1243 | # Try ISO format first (e.g., "2026-02-03T22:33:32Z") |
| 1244 | # Check for ISO date separator, not just "T" (which appears in "Tue") |
| 1245 | if len(created_at) > 10 and created_at[10] == "T": |
| 1246 | dt = datetime.fromisoformat(created_at.replace("Z", "+00:00")) |
| 1247 | else: |
| 1248 | # Twitter format: "Wed Jan 15 14:30:00 +0000 2026" |
| 1249 | dt = datetime.strptime(created_at, "%a %b %d %H:%M:%S %z %Y") |
| 1250 | date = dt.strftime("%Y-%m-%d") |
| 1251 | except (ValueError, TypeError): |
| 1252 | pass |
| 1253 | |
| 1254 | # Extract user info (Bird uses author.username, older format uses user.screen_name) |
| 1255 | author = tweet.get("author", {}) or tweet.get("user", {}) |
| 1256 | author_handle = author.get("username") or author.get("screen_name", "") or tweet.get("author_handle", "") |
| 1257 | |
| 1258 | # Build engagement dict (Bird uses camelCase: likeCount, retweetCount, etc.) |
| 1259 | engagement = { |
| 1260 | "likes": _first_of(tweet.get("likeCount"), tweet.get("like_count"), tweet.get("favorite_count")), |
| 1261 | "reposts": _first_of(tweet.get("retweetCount"), tweet.get("retweet_count")), |
| 1262 | "replies": _first_of(tweet.get("replyCount"), tweet.get("reply_count")), |
| 1263 | "quotes": _first_of(tweet.get("quoteCount"), tweet.get("quote_count")), |
| 1264 | } |
| 1265 | # Convert to int where possible |
| 1266 | for key in engagement: |
| 1267 | if engagement[key] is not None: |
| 1268 | try: |
| 1269 | engagement[key] = int(engagement[key]) |
| 1270 | except (ValueError, TypeError): |
| 1271 | engagement[key] = None |
| 1272 | |
| 1273 | # Build normalized item |
| 1274 | text = str(tweet.get("text", tweet.get("full_text", ""))).strip()[:500] |
| 1275 | item = { |
| 1276 | "id": f"X{i+1}", |
| 1277 | "text": text, |
| 1278 | "url": url, |
| 1279 | "author_handle": author_handle.lstrip("@"), |
| 1280 | # Leading @mentions parsed from the post text identify who a reply is |
| 1281 | # directed at (X replies open with the target handle(s)). Used by the |
| 1282 | # interaction-signal classifier in rerank. |
| 1283 | "mentioned_handles": _leading_mentions(text), |
| 1284 | "date": date, |
| 1285 | "engagement": engagement if any(v is not None for v in engagement.values()) else None, |
| 1286 | "why_relevant": "", # Bird doesn't provide relevance explanations |
| 1287 | "relevance": _compute_relevance(query, str(tweet.get("text", ""))) if query else 0.7, |
| 1288 | } |
| 1289 | |
| 1290 | items.append(item) |
| 1291 | |
| 1292 | return items |
| 1293 |