| 1 | """X (Twitter) search via xurl CLI — official X API v2. |
| 2 | |
| 3 | xurl is X's official CLI for the X API |
| 4 | (https://github.com/xdevplatform/xurl). It requires only a free |
| 5 | X Developer App. No xAI subscription or browser cookies needed. |
| 6 | |
| 7 | Install: npm install -g @xdevplatform/xurl |
| 8 | Auth: xurl auth app-only <bearer-token> (search / availability) |
| 9 | xurl auth oauth1 ... (optional; not used for search) |
| 10 | |
| 11 | Priority: xAI API > Bird/GraphQL > xurl > web-only fallback |
| 12 | """ |
| 13 | |
| 14 | import json |
| 15 | import os |
| 16 | import re |
| 17 | import shutil |
| 18 | import stat |
| 19 | import subprocess |
| 20 | import time |
| 21 | from pathlib import Path |
| 22 | from typing import Any, Dict, List, Optional, Tuple |
| 23 | |
| 24 | from . import health, http, log, private_files, usage |
| 25 | from . import x_api |
| 26 | # One X API v2 depth table and one parser: xurl_x re-imports both. |
| 27 | from .x_api import DEPTH_CONFIG |
| 28 | |
| 29 | # xurl auth status marks a configured app-only bearer as "bearer: ✓". |
| 30 | # Search uses --auth app, so availability must require this — oauth1 alone |
| 31 | # is not enough. |
| 32 | _BEARER_CONFIGURED_RE = re.compile(r"bearer:\s*✓") |
| 33 | |
| 34 | |
| 35 | def _log(msg: str) -> None: |
| 36 | log.source_log("xurl", msg, tty_only=False) |
| 37 | |
| 38 | |
| 39 | |
| 40 | # Memoized availability, mirroring health.py's per-process dependency-probe |
| 41 | # cache: each uncached is_available() check spawns an `xurl auth status` |
| 42 | # subprocess (local credential status; no network). The doctor/safe-diagnose |
| 43 | # path never uses it — see stored_auth_status()/has_stored_auth() below — |
| 44 | # but research-time callers may consult it more than once per process. |
| 45 | # None means "not yet probed". |
| 46 | _availability_cache: Optional[bool] = None |
| 47 | |
| 48 | |
| 49 | def clear_availability_cache() -> None: |
| 50 | """Reset the memoized is_available() result (tests, or a re-check after auth).""" |
| 51 | global _availability_cache |
| 52 | _availability_cache = None |
| 53 | |
| 54 | |
| 55 | def is_available() -> bool: |
| 56 | """Check if xurl is installed and has app-only bearer auth. |
| 57 | |
| 58 | Returns True only if xurl binary is found AND ``xurl auth status`` |
| 59 | exits 0 with a configured app-only bearer (``bearer: ✓``). OAuth1 |
| 60 | alone is insufficient — ``search_x`` pins ``--auth app``. |
| 61 | Memoized per process; ``clear_availability_cache()`` resets. |
| 62 | """ |
| 63 | global _availability_cache |
| 64 | if _availability_cache is None: |
| 65 | _availability_cache = _is_available_uncached() |
| 66 | return _availability_cache |
| 67 | |
| 68 | |
| 69 | def _is_available_uncached() -> bool: |
| 70 | try: |
| 71 | result = subprocess.run( |
| 72 | ["xurl", "auth", "status"], |
| 73 | capture_output=True, |
| 74 | text=True, |
| 75 | encoding="utf-8", |
| 76 | errors="replace", |
| 77 | timeout=10, |
| 78 | ) |
| 79 | return ( |
| 80 | result.returncode == 0 |
| 81 | and _BEARER_CONFIGURED_RE.search(result.stdout or "") is not None |
| 82 | ) |
| 83 | except (OSError, subprocess.TimeoutExpired): |
| 84 | # OSError covers FileNotFoundError (no xurl on PATH) and |
| 85 | # PermissionError (a non-executable match on PATH, e.g. WSL's |
| 86 | # /mnt/c/.../WindowsApps shim returning EACCES on exec). |
| 87 | return False |
| 88 | |
| 89 | |
| 90 | # --------------------------------------------------------------------------- |
| 91 | # Local auth evidence (doctor / safe-diagnose path — no subprocess, no |
| 92 | # network). |
| 93 | # |
| 94 | # xurl persists OAuth credentials to an on-disk token store at ~/.xurl |
| 95 | # (YAML in current releases; legacy versions wrote JSON — see the upstream |
| 96 | # store package at github.com/xdevplatform/xurl). A populated store is the |
| 97 | # strongest LOCAL evidence of authentication obtainable without spending a |
| 98 | # network call, so doctor keys on it and reports "auth not live-verified" |
| 99 | # instead of running `xurl whoami` (a real, authenticated X API request |
| 100 | # that would violate doctor's no-network guarantee). |
| 101 | # --------------------------------------------------------------------------- |
| 102 | |
| 103 | AUTH_OK = "ok" # token store present with stored credentials |
| 104 | AUTH_MISSING = "missing" # no token store, or no credentials stored in it |
| 105 | AUTH_ERROR = "error" # token store exists but could not be read |
| 106 | |
| 107 | # Substrings a populated store carries in both YAML and legacy JSON formats. |
| 108 | # Runtime search pins ``--auth app`` (app-only bearer), so only a non-empty |
| 109 | # ``bearer_token`` satisfies AUTH_OK; OAuth1/OAuth2 user tokens alone do not. |
| 110 | _TOKEN_STORE_MARKERS = ( |
| 111 | "bearer_token", |
| 112 | ) |
| 113 | _OAUTH_USER_TOKEN_MARKERS = ( |
| 114 | "access_token", |
| 115 | "oauth2_tokens", |
| 116 | "oauth1_tokens", |
| 117 | ) |
| 118 | _YAML_EMPTY_VALUES = frozenset({"", "''", '""', "null", "~", "{}", "[]"}) |
| 119 | _BEARER_VALUE_KEYS = frozenset({"bearer", "token", "value"}) |
| 120 | _BEARER_KEY_LINE_RE = re.compile(r"^(\s*)['\"]?bearer_token['\"]?\s*:\s*(.*)$") |
| 121 | _MAX_TOKEN_STORE_BYTES = 65536 |
| 122 | |
| 123 | |
| 124 | def _json_has_bearer_token(obj: Any) -> bool: |
| 125 | if isinstance(obj, dict): |
| 126 | for key, value in obj.items(): |
| 127 | if key == "bearer_token": |
| 128 | if isinstance(value, str) and value.strip(): |
| 129 | return True |
| 130 | if isinstance(value, dict) and any( |
| 131 | isinstance(subkey, str) |
| 132 | and subkey.strip().lower() in _BEARER_VALUE_KEYS |
| 133 | and isinstance(subval, str) |
| 134 | and subval.strip() |
| 135 | for subkey, subval in value.items() |
| 136 | ): |
| 137 | return True |
| 138 | elif _json_has_bearer_token(value): |
| 139 | return True |
| 140 | elif isinstance(obj, list): |
| 141 | return any(_json_has_bearer_token(item) for item in obj) |
| 142 | return False |
| 143 | |
| 144 | |
| 145 | def _content_has_bearer_token(content: str) -> bool: |
| 146 | stripped = content.lstrip() |
| 147 | if stripped.startswith(("{", "[")): |
| 148 | try: |
| 149 | return _json_has_bearer_token(json.loads(content)) |
| 150 | except (ValueError, TypeError): |
| 151 | pass |
| 152 | lines = content.splitlines() |
| 153 | for idx, line in enumerate(lines): |
| 154 | if line.lstrip().startswith("#"): |
| 155 | continue |
| 156 | match = _BEARER_KEY_LINE_RE.match(line) |
| 157 | if not match: |
| 158 | continue |
| 159 | indent = len(match.group(1)) |
| 160 | rest = match.group(2).split("#", 1)[0].strip() |
| 161 | if rest.lower() not in _YAML_EMPTY_VALUES: |
| 162 | return True |
| 163 | if rest: |
| 164 | continue |
| 165 | for child in lines[idx + 1 :]: |
| 166 | child_stripped = child.strip() |
| 167 | if not child_stripped or child_stripped.startswith("#"): |
| 168 | continue |
| 169 | child_indent = len(child) - len(child.lstrip()) |
| 170 | if child_indent <= indent: |
| 171 | break |
| 172 | if ":" in child_stripped: |
| 173 | child_key, child_raw = child_stripped.split(":", 1) |
| 174 | if child_key.strip().strip("'\"").lower() not in _BEARER_VALUE_KEYS: |
| 175 | continue |
| 176 | child_val = child_raw.split("#", 1)[0].strip() |
| 177 | if child_val.lower() not in _YAML_EMPTY_VALUES: |
| 178 | return True |
| 179 | return False |
| 180 | |
| 181 | |
| 182 | def _read_token_store_text(path: Any) -> str: |
| 183 | """Read an on-disk xurl token store safely (no symlink follow, non-blocking, bounded).""" |
| 184 | if not isinstance(path, (str, os.PathLike)): |
| 185 | return path.read_text(encoding="utf-8", errors="replace")[:_MAX_TOKEN_STORE_BYTES] |
| 186 | target = Path(path) |
| 187 | if os.name == "posix": |
| 188 | flags = ( |
| 189 | os.O_RDONLY |
| 190 | | getattr(os, "O_NOFOLLOW", 0) |
| 191 | | getattr(os, "O_NONBLOCK", 0) |
| 192 | | getattr(os, "O_CLOEXEC", 0) |
| 193 | ) |
| 194 | fd = os.open(target, flags) |
| 195 | try: |
| 196 | st = os.fstat(fd) |
| 197 | if not stat.S_ISREG(st.st_mode): |
| 198 | raise OSError(f"Expected a regular token store file: {target}") |
| 199 | with os.fdopen(fd, "r", encoding="utf-8", errors="replace") as stream: |
| 200 | fd = -1 |
| 201 | return stream.read(_MAX_TOKEN_STORE_BYTES) |
| 202 | finally: |
| 203 | if fd != -1: |
| 204 | os.close(fd) |
| 205 | private_files._reject_symlink_or_nonregular(target) |
| 206 | with target.open("r", encoding="utf-8", errors="replace") as stream: |
| 207 | return stream.read(_MAX_TOKEN_STORE_BYTES) |
| 208 | |
| 209 | |
| 210 | def _is_file(path: Path) -> bool: |
| 211 | """True when *path* is a regular file; raise on an unreadable stat. |
| 212 | |
| 213 | ``pathlib.Path.is_file()`` swallows ``OSError`` into ``False``, which |
| 214 | would silently misreport a permission-denied (EACCES) store as absent. |
| 215 | Probing via ``stat`` keeps the typed ``AUTH_ERROR`` path reachable for |
| 216 | real stat failures. A missing path (``FileNotFoundError``) returns False — |
| 217 | absence is a normal state (this also covers a dangling symlink whose |
| 218 | target is gone). Path stubs without ``stat``/``is_file`` support (test |
| 219 | doubles) fall back to their own behavior. |
| 220 | """ |
| 221 | try: |
| 222 | return stat.S_ISREG(path.stat().st_mode) |
| 223 | except FileNotFoundError: |
| 224 | return False |
| 225 | except (AttributeError, TypeError): |
| 226 | try: |
| 227 | return bool(path.is_file()) |
| 228 | except AttributeError: |
| 229 | return False |
| 230 | |
| 231 | |
| 232 | def _is_dir(path: Path) -> bool: |
| 233 | """True when *path* is a directory; raise on an unreadable stat. |
| 234 | |
| 235 | Same rationale as :func:`_is_file` — pathlib's ``is_dir()`` hides |
| 236 | ``OSError``, so a permission-denied parent would read as a missing store. |
| 237 | """ |
| 238 | try: |
| 239 | return stat.S_ISDIR(path.stat().st_mode) |
| 240 | except FileNotFoundError: |
| 241 | return False |
| 242 | except (AttributeError, TypeError): |
| 243 | try: |
| 244 | return bool(path.is_dir()) |
| 245 | except AttributeError: |
| 246 | return False |
| 247 | |
| 248 | |
| 249 | def token_store_path() -> Path: |
| 250 | """xurl's on-disk OAuth token store (~/.xurl/auth.yml). |
| 251 | |
| 252 | Current xurl (>=1.1) stores credentials in a YAML file at |
| 253 | ``~/.xurl/auth.yml``; ``~/.xurl`` itself is a directory. Legacy |
| 254 | releases wrote a flat file at ``~/.xurl``. ``stored_auth_status()`` |
| 255 | resolves both layouts; this returns the canonical current path. |
| 256 | """ |
| 257 | return Path.home() / ".xurl" / "auth.yml" |
| 258 | |
| 259 | |
| 260 | def stored_auth_status() -> Tuple[str, str]: |
| 261 | """Local-only evidence of xurl authentication: ``(status, detail)``. |
| 262 | |
| 263 | Reads only the on-disk token store — never spawns xurl, never touches |
| 264 | the network. ``status`` is AUTH_OK (store holds an app-only bearer token), |
| 265 | AUTH_MISSING (no store / empty store / OAuth user tokens only without |
| 266 | ``bearer_token``), or AUTH_ERROR (store exists but cannot be read — |
| 267 | surfaced as a typed error, not as "unconfigured"). |
| 268 | """ |
| 269 | # Resolve the actual credential file across layouts. Current xurl keeps |
| 270 | # ~/.xurl/auth.yml inside the ~/.xurl directory; legacy installs wrote a |
| 271 | # flat ~/.xurl file. Honor whatever token_store_path() resolves to and |
| 272 | # check both shapes so a valid directory layout is never misread as a |
| 273 | # missing token store. Path stubs that cannot combine (e.g. an unreadable |
| 274 | # store stub without / support) still reach the typed error path below. |
| 275 | path = token_store_path() |
| 276 | try: |
| 277 | base = path.parent if path.name == "auth.yml" else path |
| 278 | except (AttributeError, TypeError): |
| 279 | # A path stub with no parent/name support: treat it as the file itself. |
| 280 | base = path |
| 281 | try: |
| 282 | # Use stat rather than is_file()/is_dir(): pathlib swallows OSError |
| 283 | # into False, which would silently turn a permission-denied store into |
| 284 | # "no token store" instead of the typed AUTH_ERROR. |
| 285 | candidates = [base / "auth.yml", base] if _is_dir(base) else [base, base / "auth.yml"] |
| 286 | except (TypeError, AttributeError): |
| 287 | # A path stub that cannot combine (no __truediv__): the path itself is |
| 288 | # the only candidate. |
| 289 | candidates = [path] |
| 290 | except OSError as exc: |
| 291 | return ( |
| 292 | AUTH_ERROR, |
| 293 | f"token store {base} unreadable: {type(exc).__name__}: {exc}", |
| 294 | ) |
| 295 | try: |
| 296 | path = next(c for c in candidates if _is_file(c)) |
| 297 | except StopIteration: |
| 298 | return AUTH_MISSING, f"no token store at {token_store_path()}" |
| 299 | except OSError as exc: |
| 300 | return ( |
| 301 | AUTH_ERROR, |
| 302 | f"token store {base} unreadable: {type(exc).__name__}: {exc}", |
| 303 | ) |
| 304 | try: |
| 305 | content = _read_token_store_text(path) |
| 306 | except OSError as exc: |
| 307 | return ( |
| 308 | AUTH_ERROR, |
| 309 | f"token store {path} unreadable: {type(exc).__name__}: {exc}", |
| 310 | ) |
| 311 | if _content_has_bearer_token(content): |
| 312 | return AUTH_OK, f"stored app-only bearer credentials found in {path}" |
| 313 | if any(marker in content for marker in _OAUTH_USER_TOKEN_MARKERS): |
| 314 | return ( |
| 315 | AUTH_MISSING, |
| 316 | f"token store {path} has OAuth user tokens only; search requires app-only bearer auth", |
| 317 | ) |
| 318 | return AUTH_MISSING, f"token store {path} has no stored credentials" |
| 319 | |
| 320 | |
| 321 | def has_stored_auth() -> bool: |
| 322 | """Local-only availability: xurl on PATH with stored credentials. |
| 323 | |
| 324 | The doctor/safe-diagnose counterpart of ``is_available()`` — the same |
| 325 | "installed and authenticated" question answered from local evidence |
| 326 | only (PATH lookup + token store), never a live ``xurl whoami``. A |
| 327 | broken token store reads as unavailable here; the doctor probe layer |
| 328 | (``backends._probe_xurl``) reports that case as a typed error. |
| 329 | """ |
| 330 | return shutil.which("xurl") is not None and stored_auth_status()[0] == AUTH_OK |
| 331 | |
| 332 | |
| 333 | # Engine-authored fixed error strings (the same rule as x_api): xurl's |
| 334 | # stderr can echo the request, the bearer, or an account id, so it never |
| 335 | # reaches the outcome detail. Each string carries a marker that |
| 336 | # http.classify_failure recognizes. |
| 337 | ERR_PAYMENT_REQUIRED = "xurl: payment required (X API credits exhausted)" |
| 338 | ERR_UNAUTHORIZED = "xurl: unauthorized (bearer token rejected)" |
| 339 | ERR_FORBIDDEN = "xurl: forbidden (bearer token lacks access)" |
| 340 | ERR_RATE_LIMITED = "xurl: rate limit exceeded (X API)" |
| 341 | ERR_FAILED = "xurl: search failed" |
| 342 | # HTTP 400 from X's query grammar (for example a bare lowercase "and"). |
| 343 | ERR_INVALID_REQUEST = "xurl: X rejected the query (invalid request)" |
| 344 | ERR_EMPTY_QUERY = "xurl: no searchable keywords left after removing X search operators" |
| 345 | ERR_INVALID_JSON = "xurl: invalid JSON from xurl" |
| 346 | ERR_NOT_FOUND = "xurl not found in PATH" |
| 347 | ERR_TIMED_OUT = "xurl search timed out (30s)" |
| 348 | |
| 349 | |
| 350 | def _classify_cli_failure(output: str) -> str: |
| 351 | """Map xurl's stderr/stdout to a fixed string via the shared classifier.""" |
| 352 | text = output or "" |
| 353 | state = http.classify_failure(message=text) |
| 354 | if state == health.PAYMENT_REQUIRED: |
| 355 | return ERR_PAYMENT_REQUIRED |
| 356 | if state == health.AUTH_FAILED: |
| 357 | # The shared vocabulary has one auth state; split the wording only. |
| 358 | lowered = text.lower() |
| 359 | if "401" in lowered or "unauthorized" in lowered: |
| 360 | return ERR_UNAUTHORIZED |
| 361 | return ERR_FORBIDDEN |
| 362 | if state == health.RATE_LIMITED: |
| 363 | return ERR_RATE_LIMITED |
| 364 | # X's v2 problem type (".../2/problems/invalid-request") or its title |
| 365 | # ("Invalid Request"). Only the fixed string leaves; the body may echo |
| 366 | # the query or request headers. |
| 367 | lowered = text.lower() |
| 368 | if "invalid-request" in lowered or "invalid request" in lowered: |
| 369 | return ERR_INVALID_REQUEST |
| 370 | return ERR_FAILED |
| 371 | |
| 372 | |
| 373 | def search_x( |
| 374 | query: str, |
| 375 | depth: str = "default", |
| 376 | deadline: Optional[float] = None, |
| 377 | ) -> Dict[str, Any]: |
| 378 | """Search X via xurl CLI using X API v2 search/recent. |
| 379 | |
| 380 | The topic is sanitized into space-joined keywords first |
| 381 | (``x_api.build_keyword_query``): X's v2 grammar rejects a bare lowercase |
| 382 | ``and``/``or`` with HTTP 400 and treats ``from:``-style tokens, leading |
| 383 | ``-``, parentheses and quotes as operators, and the pipeline always |
| 384 | passes the raw user topic here. |
| 385 | |
| 386 | Args: |
| 387 | query: Search topic (raw user text is fine; it is sanitized) |
| 388 | depth: "quick", "default", or "deep" |
| 389 | deadline: Optional shared wall-clock deadline (``time.monotonic()`` |
| 390 | instant) from the X backend chain. The single subprocess timeout |
| 391 | is clamped to the time left; a call past the deadline never starts. |
| 392 | |
| 393 | Returns: |
| 394 | Raw JSON response from X API v2 tweets/search/recent, or a dict |
| 395 | with an "error" key holding a fixed string on failure. The CLI's |
| 396 | own output reaches only the debug log, never the error. |
| 397 | """ |
| 398 | search_query = x_api.build_keyword_query(query) |
| 399 | if not search_query: |
| 400 | return {"error": ERR_EMPTY_QUERY} |
| 401 | |
| 402 | max_results = DEPTH_CONFIG.get(depth, DEPTH_CONFIG["default"]) |
| 403 | # X API v2 search/recent requires max_results in 10–100 range |
| 404 | max_results = max(10, min(100, max_results)) |
| 405 | timeout = 30 |
| 406 | if deadline is not None: |
| 407 | remaining = deadline - time.monotonic() |
| 408 | if remaining < 1: |
| 409 | return {"error": "xurl: chain budget exhausted"} |
| 410 | timeout = max(1, min(timeout, int(remaining))) |
| 411 | |
| 412 | charge = None |
| 413 | try: |
| 414 | # --auth app (app-only bearer): xurl >=1.1 mis-signs OAuth1 requests |
| 415 | # whose query needs percent-encoding (spaces, parens, ...) -> 401. |
| 416 | # Bearer auth sends no signature, so multi-word queries work. |
| 417 | charge = usage.begin("x") |
| 418 | result = subprocess.run( |
| 419 | ["xurl", "search", search_query, "-n", str(max_results), "--auth", "app"], |
| 420 | capture_output=True, |
| 421 | text=True, |
| 422 | encoding="utf-8", |
| 423 | errors="replace", |
| 424 | timeout=timeout, |
| 425 | ) |
| 426 | |
| 427 | if result.returncode != 0: |
| 428 | error_text = result.stderr.strip() or result.stdout.strip() |
| 429 | classified = _classify_cli_failure(error_text) |
| 430 | # The raw CLI output can echo the bearer; only the fixed string |
| 431 | # and its size reach the debug log. |
| 432 | log.debug(f"xurl exit {result.returncode}: {classified} ({len(error_text)} chars)") |
| 433 | return {"error": classified} |
| 434 | |
| 435 | return json.loads(result.stdout) |
| 436 | |
| 437 | except FileNotFoundError: |
| 438 | usage.cancel(charge) |
| 439 | return {"error": ERR_NOT_FOUND} |
| 440 | except subprocess.TimeoutExpired: |
| 441 | return {"error": ERR_TIMED_OUT} |
| 442 | except json.JSONDecodeError: |
| 443 | return {"error": ERR_INVALID_JSON} |
| 444 | except Exception as exc: |
| 445 | return {"error": f"xurl: {type(exc).__name__}"} |
| 446 | |
| 447 | |
| 448 | def parse_x_response( |
| 449 | response: Dict[str, Any], |
| 450 | topic: str = "", |
| 451 | ) -> List[Dict[str, Any]]: |
| 452 | """Parse an xurl search response into normalized item dicts. |
| 453 | |
| 454 | Delegates to the shared X API v2 parser (``x_api.parse_v2_response``) |
| 455 | so xurl and xapi never drift; only the id prefix differs. |
| 456 | |
| 457 | Args: |
| 458 | response: Raw X API v2 response dict from search_x() |
| 459 | topic: Original search topic (used for relevance scoring) |
| 460 | |
| 461 | Returns: |
| 462 | List of item dicts. Empty list on error or no results. |
| 463 | """ |
| 464 | if isinstance(response, dict) and "error" in response: |
| 465 | _log(f"Error in response: {response['error']}") |
| 466 | return [] |
| 467 | return x_api.parse_v2_response(response, topic, None, id_prefix="XURL") |
| 468 |