返回 last30days-skill
env.py
1 """Environment and API key management for last30days skill."""
2
3 from __future__ import annotations
4
5 import datetime
6 import errno
7 import json
8 import locale
9 import os
10 import re
11 import stat
12 import sys
13 from dataclasses import dataclass
14 from pathlib import Path
15 from typing import Any, Literal
16
17
18 def read_secret_env(name: str, default: str | None = None) -> str | None:
19 """Read a possibly-secret environment variable by name.
20
21 Call sites pass the variable name as an argument here instead of reading a
22 secret-shaped literal environment key inline at the call site. That keeps
23 those literals out of direct env-get calls, which an install-time skill
24 scanner flags as credential exfiltration. Behaviour is identical to a plain
25 environment lookup of ``name`` with ``default``.
26 """
27 return os.environ.get(name, default)
28
29
30 # Allow override via environment variable for testing
31 # Set LAST30DAYS_CONFIG_DIR="" for clean/no-config mode
32 # Set LAST30DAYS_CONFIG_DIR="/path/to/dir" for custom config location
33 _config_override = os.environ.get('LAST30DAYS_CONFIG_DIR')
34 if _config_override == "":
35 # Empty string = no config file (clean mode)
36 CONFIG_DIR = None
37 CONFIG_FILE = None
38 elif _config_override:
39 CONFIG_DIR = Path(_config_override)
40 CONFIG_FILE = CONFIG_DIR / ".env"
41 else:
42 CONFIG_DIR = Path.home() / ".config" / "last30days"
43 CONFIG_FILE = CONFIG_DIR / ".env"
44
45 # macOS Keychain integration: items stored with this service prefix are picked
46 # up automatically on Darwin as the lowest-priority credential source.
47 # Example: `security add-generic-password -a "$USER" -s last30days-XAI_API_KEY -w "xai-..."`.
48 KEYCHAIN_SERVICE_PREFIX = "last30days-"
49
50 # Optional non-secret aliases for users who already store API keys under a
51 # different Keychain naming convention. Configure as JSON in
52 # LAST30DAYS_KEYCHAIN_ALIASES, for example:
53 # {"XAI_API_KEY":{"account":"keychain-user","service":"existing-xai-api-key"}}
54 # A string value is shorthand for {"service": "..."} with the current user.
55 KEYCHAIN_ALIASES_ENV = "LAST30DAYS_KEYCHAIN_ALIASES"
56
57 # Opt-out switch for the Keychain source. Set truthy to make _load_keychain a
58 # no-op on Darwin too. Tests that assert on "no credentials configured"
59 # behaviour need this: stripping os.environ and pointing LAST30DAYS_CONFIG_DIR
60 # at nothing still leaves Keychain as a third source, so on a contributor's Mac
61 # a stored key can silently satisfy a lookup the test meant to see fail.
62 KEYCHAIN_DISABLE_ENV = "LAST30DAYS_SKIP_KEYCHAIN"
63
64 X_COOKIE_ACCESS_FIX = (
65 "Check the browser-data permissions for the terminal or agent host and retry setup. "
66 "If access remains blocked, set AUTH_TOKEN and CT0 manually or use XAI_API_KEY."
67 )
68
69 # Single source of truth for which credentials the Keychain loader looks up.
70 # The setup-keychain.sh helper mirrors this list and is held in sync via
71 # tests/test_env_keychain.py::test_keychain_keys_match_setup_script.
72 KEYCHAIN_KEYS = (
73 "OPENAI_API_KEY", "XAI_API_KEY", "GOOGLE_API_KEY", "GEMINI_API_KEY",
74 "GOOGLE_GENAI_API_KEY", "SCRAPECREATORS_API_KEY", "APIFY_API_TOKEN",
75 "AUTH_TOKEN", "CT0", "BSKY_HANDLE", "BSKY_APP_PASSWORD",
76 "TRUTHSOCIAL_TOKEN", "BRAVE_API_KEY", "EXA_API_KEY", "SERPER_API_KEY",
77 "OPENROUTER_API_KEY", "PERPLEXITY_API_KEY", "PARALLEL_API_KEY", "XQUIK_API_KEY",
78 "XIAOHONGSHU_API_BASE", "GITHUB_TOKEN", "BRIGHTDATA_API_KEY",
79 "X_BEARER_TOKEN", "DEEPLINE_API_KEY",
80 )
81
82 # pass(1) integration: Linux/Unix analog of the Keychain source. Each key in
83 # KEYCHAIN_KEYS is looked up at pass path f"{prefix}{KEY}", the direct analog of
84 # Keychain's "last30days-<KEY>" service-name convention, so any user stores keys
85 # under one namespace without editing code. The prefix is resolved at call time
86 # (in get_config) from LAST30DAYS_PASS_PREFIX in the process env or a config
87 # file, falling back to this default; included verbatim, so keep the trailing
88 # separator. Honors PASSWORD_STORE_DIR.
89 DEFAULT_PASS_PATH_PREFIX = "last30days/"
90
91 AuthSource = Literal["api_key", "none"]
92 AuthStatus = Literal["ok", "missing"]
93
94 AUTH_SOURCE_API_KEY: AuthSource = "api_key"
95 AUTH_SOURCE_NONE: AuthSource = "none"
96
97 AUTH_STATUS_OK: AuthStatus = "ok"
98 AUTH_STATUS_MISSING: AuthStatus = "missing"
99
100 XIAOHONGSHU_DEFAULT_API_BASES = (
101 "http://localhost:18060",
102 "http://host.docker.internal:18060",
103 )
104 XIAOHONGSHU_RESOLVED_API_BASE_KEY = "_XIAOHONGSHU_API_BASE_RESOLVED"
105
106
107 @dataclass(frozen=True)
108 class OpenAIAuth:
109 token: str | None
110 source: AuthSource
111 status: AuthStatus
112
113
114 BrowserCookieMode = Literal["off", "read", "plan_only"]
115
116
117 @dataclass(frozen=True)
118 class ConfigLoadPolicy:
119 """Local-read gates for configuration loading.
120
121 Bare library calls use the safe default: no browser-cookie extraction and no
122 project-scoped config. CLI entry points can opt into narrower behavior after
123 parsing command intent.
124 """
125
126 browser_cookies: BrowserCookieMode = "off"
127 allow_project_config: bool = False
128 inspect_ignored_project_config: bool = False
129 require_recorded_browser_consent: bool = False
130 load_secret_stores: bool = True
131
132
133 def _truthy(value: Any) -> bool:
134 if value is None:
135 return False
136 return str(value).strip().lower() in {"1", "true", "yes", "on"}
137
138
139 # A Claude Desktop extension maps every unset field in its config modal to the
140 # literal string ``${user_config.<field>}`` in the engine's environment. The
141 # placeholder is non-empty, so a presence check reads it as a real credential:
142 # doctor reports the source healthy, preflight returns ready, and the backend
143 # sends the literal placeholder upstream and surfaces the vendor's 401 instead
144 # of falling back. Two constraints keep legitimate values out of scope. The
145 # match is anchored to the whole trimmed value, so a real credential containing
146 # ``$`` or braces is untouched. And the field name is restricted to the
147 # identifier charset the manifest uses, so shell-default syntax is not mistaken
148 # for a placeholder - both the generic form a user may paste into ``.env``
149 # (``${VAR:-default}``) and the namespaced form with a default
150 # (``${user_config.x:-default}``). Only the extension namespace, as issue
151 # #1081's own suggested fix names, is rejected.
152 _UNSUBSTITUTED_TEMPLATE = re.compile(r"^\$\{user_config\.[A-Za-z0-9_]+\}$")
153
154 # Config-record key holding the names of values rejected above, so diagnostics
155 # report the templated state instead of silently counting the key absent.
156 TEMPLATE_CONFIG_KEYS = "_TEMPLATE_CONFIG_KEYS"
157
158
159 def is_unsubstituted_template(value: Any) -> bool:
160 """True when ``value`` is a whole, unexpanded ``${user_config.*}`` placeholder."""
161 if not isinstance(value, str):
162 return False
163 return bool(_UNSUBSTITUTED_TEMPLATE.match(value.strip()))
164
165
166 def templated_config_keys(config: dict[str, Any]) -> list[str]:
167 """Public view of the keys ``get_config()`` rejected as unsubstituted templates.
168
169 Thin reader so diagnostics report the templated state without re-deriving
170 the record key, in the same spirit as ``include_sources`` and
171 ``is_setup_complete``. Sorted here too: these call sites also see hand-built
172 configs, and the order is user-visible in both diagnostics.
173 """
174 return sorted(config.get(TEMPLATE_CONFIG_KEYS) or [])
175
176
177 def _rotate_scrapecreators_key(config: dict[str, Any]) -> None:
178 """Round-robin a comma-separated SCRAPECREATORS_API_KEY to one key per run.
179
180 Filters any unsubstituted ``${user_config.*}`` placeholders from the list
181 so a partial placeholder entry cannot be selected over a real key.
182 """
183 raw = config.get('SCRAPECREATORS_API_KEY') or ''
184 if ',' not in raw:
185 return
186 import random
187 sc_keys = [
188 k.strip()
189 for k in raw.split(',')
190 if k.strip() and not is_unsubstituted_template(k)
191 ]
192 config['SCRAPECREATORS_API_KEY'] = random.choice(sc_keys) if sc_keys else ''
193
194
195 def _strip_layer_templates(
196 mapping: dict[str, str],
197 allowed_keys: frozenset[str],
198 templated_seen: set[str],
199 *,
200 canonical_map: dict[str, str] | None = None,
201 ) -> dict[str, str]:
202 """Return a copy of ``mapping`` without ``${user_config.*}`` placeholders."""
203 cleaned: dict[str, str] = {}
204 for key, value in mapping.items():
205 if key in allowed_keys and is_unsubstituted_template(value):
206 templated_seen.add((canonical_map or {}).get(key, key))
207 continue
208 cleaned[key] = value
209 return cleaned
210
211
212 def is_timestamp_fresh(timestamp_value: Any, ttl_seconds: int) -> bool:
213 """True when ``timestamp_value`` (ISO-8601 string) is within ``ttl_seconds``.
214
215 Shared freshness gate for the doctor cache and the report cache. The guard
216 order is load-bearing: a non-positive TTL disables caching entirely, a
217 non-string or empty timestamp is stale, a malformed timestamp is stale,
218 naive timestamps are treated as UTC, and a future timestamp (negative age)
219 counts as fresh.
220 """
221 if ttl_seconds <= 0:
222 return False
223 if not isinstance(timestamp_value, str) or not timestamp_value:
224 return False
225 try:
226 created_at = datetime.datetime.fromisoformat(timestamp_value)
227 except ValueError:
228 return False
229 if created_at.tzinfo is None:
230 created_at = created_at.replace(tzinfo=datetime.timezone.utc)
231 age = datetime.datetime.now(datetime.timezone.utc) - created_at.astimezone(
232 datetime.timezone.utc
233 )
234 return age.total_seconds() <= ttl_seconds
235
236
237 def _project_config_trusted(policy: ConfigLoadPolicy, file_env: dict[str, Any]) -> bool:
238 if policy.allow_project_config:
239 return True
240 process_value = os.environ.get("LAST30DAYS_TRUST_PROJECT_CONFIG")
241 if process_value is not None and not is_unsubstituted_template(process_value):
242 return _truthy(process_value)
243 return _truthy(file_env.get("LAST30DAYS_TRUST_PROJECT_CONFIG"))
244
245
246 def _check_file_permissions(path: Path) -> None:
247 """Warn to stderr if a secrets file has overly permissive permissions."""
248 if os.name == "nt":
249 # Windows reports synthesized POSIX mode bits that do not reflect NTFS ACLs.
250 return
251
252 try:
253 mode = path.stat().st_mode
254 # Check if group or other can read (bits 0o044)
255 if mode & 0o044:
256 sys.stderr.write(
257 f"[last30days] WARNING: {path} is readable by other users. "
258 f"Run: chmod 600 {path}\n"
259 )
260 sys.stderr.flush()
261 except OSError as exc:
262 sys.stderr.write(f"[last30days] WARNING: could not stat {path}: {exc}\n")
263 sys.stderr.flush()
264
265
266 def _strip_inline_comment(value: str) -> str:
267 """Drop a trailing ``# comment`` from the right-hand side of a KEY=value line.
268
269 Unquoted: ``#`` opens a comment only as the first non-blank character or
270 when preceded by whitespace, so ``value#nothash`` stays intact. Quoted:
271 everything up to the matching close quote is kept verbatim; only a
272 whitespace-separated ``#`` after the close quote is dropped. Anything that
273 does not match those shapes is returned unchanged for the existing quote
274 handling to deal with.
275 """
276 stripped = value.lstrip()
277 if stripped[:1] in ('"', "'"):
278 end = stripped.find(stripped[0], 1)
279 if end == -1:
280 return value
281 rest = stripped[end + 1:]
282 if rest[:1].isspace() and rest.lstrip().startswith('#'):
283 return stripped[:end + 1]
284 return value
285 match = re.search(r'(?:^|\s)#', stripped)
286 if match:
287 return stripped[:match.start()]
288 return value
289
290
291 # ``export KEY=value`` is the shell spelling people paste into .env files, and
292 # python-dotenv and docker compose accept it too. The prefix only counts when
293 # whitespace and a key follow it, so a key literally named ``export`` is kept.
294 _EXPORT_PREFIX = re.compile(r'export\s+')
295
296
297 def env_line_key(lhs: str) -> str:
298 """Return the key named by the left-hand side of a ``KEY=value`` line.
299
300 Shared with the setup wizard's .env writers so that reading and writing
301 agree on which key a hand-written line sets.
302 """
303 key = lhs.strip()
304 match = _EXPORT_PREFIX.match(key)
305 return key[match.end():] if match else key
306
307
308 _MAX_ENV_FILE_BYTES = 256 * 1024
309 _ENV_IDENT_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
310
311
312 def _is_symlink_or_junction(path: Path) -> bool:
313 if path.is_symlink():
314 return True
315 isjunction = getattr(os.path, "isjunction", None)
316 return bool(isjunction and isjunction(path))
317
318
319 class ConfigReadError(OSError):
320 """A config file that exists could not be read right now (the cause is chained)."""
321
322
323 # A missing file, a path that is not a file, or a refused symlink is an ordinary
324 # absent or unsafe config. Any other read failure may pass on a later attempt.
325 _ABSENT_OR_UNSAFE_ERRNOS = frozenset({
326 errno.ENOENT, errno.ENOTDIR, errno.ELOOP, errno.EMLINK, errno.EISDIR,
327 })
328
329
330 def _is_transient_read_error(exc: OSError) -> bool:
331 if isinstance(exc, (FileNotFoundError, NotADirectoryError, IsADirectoryError)):
332 return False
333 return exc.errno not in _ABSENT_OR_UNSAFE_ERRNOS
334
335
336 def load_env_file(
337 path: Path,
338 *,
339 allow_symlink: bool = True,
340 strict_keys: bool = False,
341 raise_read_errors: bool = False,
342 ) -> dict[str, str]:
343 """Load environment variables from a file.
344
345 An unreadable file yields ``{}`` unless ``raise_read_errors`` is set. Then a
346 read failure that could pass on a later attempt raises ``ConfigReadError``, while a
347 missing file or a refused symlink still yields ``{}``.
348 """
349 env: dict[str, str] = {}
350 if not path:
351 return env
352 if not allow_symlink and (
353 _is_symlink_or_junction(path) or _is_symlink_or_junction(path.parent)
354 ):
355 return env
356
357 flags = os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)
358 if not allow_symlink:
359 flags |= getattr(os, "O_NOFOLLOW", 0)
360 fd = -1
361 parent_fd = -1
362 try:
363 if (
364 not allow_symlink
365 and path.name
366 and os.open in os.supports_dir_fd
367 and hasattr(os, "O_DIRECTORY")
368 and hasattr(os, "O_NOFOLLOW")
369 ):
370 parent_fd = os.open(
371 path.parent,
372 os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW,
373 )
374 fd = os.open(path.name, flags, dir_fd=parent_fd)
375 else:
376 fd = os.open(path, flags)
377 except OSError as exc:
378 if raise_read_errors and _is_transient_read_error(exc):
379 raise ConfigReadError(f"config file could not be opened ({type(exc).__name__})") from exc
380 return env
381 finally:
382 if parent_fd >= 0:
383 try:
384 os.close(parent_fd)
385 except OSError:
386 pass
387
388 try:
389 st = os.fstat(fd)
390 if not stat.S_ISREG(st.st_mode) or st.st_size > _MAX_ENV_FILE_BYTES:
391 return env
392 handle = os.fdopen(fd, "rb")
393 fd = -1
394 with handle:
395 raw = handle.read(_MAX_ENV_FILE_BYTES + 1)
396 except OSError as exc:
397 if raise_read_errors and _is_transient_read_error(exc):
398 raise ConfigReadError(f"config file could not be read ({type(exc).__name__})") from exc
399 return env
400 finally:
401 if fd >= 0:
402 try:
403 os.close(fd)
404 except OSError:
405 pass
406
407 if len(raw) > _MAX_ENV_FILE_BYTES:
408 return env
409
410 _check_file_permissions(path)
411
412 # Prefer UTF-8 (utf-8-sig transparently strips a BOM written by Windows
413 # editors like Notepad). Fall back to the locale decoder for a genuinely
414 # locale-encoded .env (e.g. cp1252) so an existing file that loaded before
415 # keeps loading. If it decodes as neither, let UnicodeDecodeError surface
416 # rather than corrupting keys/secrets with replacement characters.
417 try:
418 text = raw.decode('utf-8-sig')
419 except UnicodeDecodeError:
420 text = raw.decode(locale.getpreferredencoding(False))
421
422 for line in text.splitlines():
423 line = line.strip()
424 if not line or line.startswith('#'):
425 continue
426 if '=' in line:
427 key, _, value = line.partition('=')
428 key = env_line_key(key)
429 if strict_keys and not _ENV_IDENT_RE.fullmatch(key):
430 continue
431 value = _strip_inline_comment(value).strip()
432 # Remove quotes if present
433 if value and value[0] in ('"', "'") and value[-1] == value[0]:
434 value = value[1:-1]
435 # These settings use empty as a persisted disable; secrets still
436 # drop blanks instead of overriding a configured credential.
437 if key and (value or key in {'LAST30DAYS_YT_PLAYER_CLIENT', 'LAST30DAYS_MEMORY_DIR'}):
438 env.update({key: value})
439 return env
440
441
442 def _parse_keychain_aliases(raw: str | None) -> dict[str, list[dict[str, str]]]:
443 """Parse non-secret Keychain alias metadata from JSON.
444
445 Supported forms:
446 {"XAI_API_KEY": "existing-xai-api-key"}
447 {"XAI_API_KEY": {"service": "existing-xai-api-key", "account": "keychain-user"}}
448 {"XAI_API_KEY": [{"service": "primary"}, {"service": "fallback"}]}
449
450 Invalid entries are ignored so a typo never blocks canonical
451 `last30days-<KEY>` lookups; malformed JSON emits a warning.
452 """
453 if not raw:
454 return {}
455 try:
456 parsed = json.loads(raw)
457 except json.JSONDecodeError as exc:
458 sys.stderr.write(
459 f"[last30days] WARNING: {KEYCHAIN_ALIASES_ENV} is not valid JSON; "
460 f"ignoring Keychain aliases while keeping canonical lookups enabled: {exc}\n"
461 )
462 sys.stderr.flush()
463 return {}
464 if not isinstance(parsed, dict):
465 return {}
466
467 allowed = set(KEYCHAIN_KEYS)
468 aliases: dict[str, list[dict[str, str]]] = {}
469 for key, spec in parsed.items():
470 if key not in allowed:
471 continue
472 specs = spec if isinstance(spec, list) else [spec]
473 clean_specs: list[dict[str, str]] = []
474 for item in specs:
475 if isinstance(item, str):
476 service = item.strip()
477 account = ""
478 elif isinstance(item, dict):
479 service = str(item.get("service", "")).strip()
480 account = str(item.get("account", "")).strip()
481 else:
482 continue
483 if service:
484 clean_specs.append({"service": service, "account": account})
485 if clean_specs:
486 aliases[key] = clean_specs
487 return aliases
488
489
490 def _load_keychain(keys: list[str], aliases: dict[str, list[dict[str, str]]] | None = None) -> dict[str, str]:
491 """Load credentials from macOS Keychain (no-op on other platforms).
492
493 Each key is looked up as a generic password with service name
494 ``f"{KEYCHAIN_SERVICE_PREFIX}{key}"`` for the current user. Missing items
495 then fall back to optional alias metadata from
496 ``LAST30DAYS_KEYCHAIN_ALIASES``. Lookup failures are silent — Keychain is
497 the lowest-priority source and is meant to be additive over `.env` files
498 and process environment.
499
500 Set ``LAST30DAYS_SKIP_KEYCHAIN`` truthy to disable the source entirely. It
501 is read from the process environment only, never from a config file: it
502 gates a credential source that is consulted *while* the config is being
503 assembled, so a file-sourced value would be read too late to have any
504 effect.
505 """
506 if _truthy(os.environ.get(KEYCHAIN_DISABLE_ENV)):
507 return {}
508
509 import platform
510 if platform.system() != "Darwin":
511 return {}
512
513 import shutil
514 security = shutil.which("security")
515 if not security:
516 return {}
517
518 import subprocess
519 # USER can be unset under sudo, in Docker without --env USER, or in some CI
520 # runners; fall back to the OS user record so lookups still match items
521 # stored by setup-keychain.sh (which uses $USER).
522 user = os.environ.get("USER")
523 if not user:
524 try:
525 import pwd
526 except ImportError:
527 pwd = None
528
529 if pwd is not None:
530 try:
531 user = pwd.getpwuid(os.getuid()).pw_name
532 except AttributeError:
533 user = "unknown"
534 else:
535 user = "unknown"
536 env: dict[str, str] = {}
537
538 def lookup(account: str, service: str) -> str:
539 try:
540 result = subprocess.run(
541 [security, "find-generic-password",
542 "-a", account,
543 "-s", service,
544 "-w"],
545 capture_output=True, text=True, timeout=5,
546 )
547 except (subprocess.TimeoutExpired, OSError):
548 return ""
549 if result.returncode == 0 and result.stdout.strip():
550 return result.stdout.strip()
551 return ""
552
553 for key in keys:
554 value = lookup(user, f"{KEYCHAIN_SERVICE_PREFIX}{key}")
555 if not value and aliases:
556 for alias in aliases.get(key, []):
557 alias_account = alias.get("account") or user
558 value = lookup(alias_account, alias["service"])
559 if value:
560 break
561 if value:
562 env.update({key: value})
563 return env
564
565
566 def _load_pass(keys: list[str], prefix: str) -> dict[str, str]:
567 """Load credentials from a pass(1) store (no-op if `pass` is absent).
568
569 The Linux/Unix analog of the macOS Keychain source. Each env-var name is
570 looked up at pass path ``f"{prefix}{key}"`` — mirroring Keychain's
571 ``last30days-<key>`` service-name convention — so any user stores keys under
572 that namespace without editing code (prefix overridable via
573 ``LAST30DAYS_PASS_PREFIX``, used verbatim to match ``setup-pass.sh``). The
574 secret is decrypted in a subprocess and read from stdout's first line (pass
575 keeps the secret there; any metadata follows) — never written to disk, never
576 logged. Honors ``PASSWORD_STORE_DIR``. Missing entries and failures are
577 silent: pass is a lowest-priority, additive source like Keychain, so an
578 explicit .env or process-env value still wins.
579 """
580 import shutil
581 pass_bin = shutil.which("pass")
582 if not pass_bin:
583 return {}
584
585 import subprocess
586 env: dict[str, str] = {}
587 for key in keys:
588 try:
589 result = subprocess.run(
590 [pass_bin, "show", "--", f"{prefix}{key}"],
591 capture_output=True, text=True, timeout=5,
592 encoding="utf-8", errors="replace",
593 )
594 except (subprocess.TimeoutExpired, OSError):
595 # A timeout (GPG/pinentry hanging) or exec failure isn't a per-key
596 # condition — it means the store is unusable right now. Stop instead
597 # of paying the timeout once per key; otherwise a locked store would
598 # stall every config load by 5s x len(keys). A genuinely missing key
599 # returns fast with a non-zero exit and is handled below.
600 break
601 if result.returncode == 0 and result.stdout.strip():
602 env.update({key: result.stdout.strip().splitlines()[0]})
603 return env
604
605
606 def get_openai_auth(file_env: dict[str, str]) -> OpenAIAuth:
607 """Resolve OpenAI API auth from explicit user-provided API keys."""
608 env_key = read_secret_env('OPENAI_API_KEY')
609 if is_unsubstituted_template(env_key):
610 env_key = None
611 file_key = file_env.get('OPENAI_API_KEY')
612 if is_unsubstituted_template(file_key):
613 file_key = None
614 api_key = env_key or file_key
615 if api_key:
616 return OpenAIAuth(
617 token=api_key,
618 source=AUTH_SOURCE_API_KEY,
619 status=AUTH_STATUS_OK,
620 )
621
622 return OpenAIAuth(
623 token=None,
624 source=AUTH_SOURCE_NONE,
625 status=AUTH_STATUS_MISSING,
626 )
627
628
629 def _find_project_env() -> Path | None:
630 """Find per-project .env by walking up from cwd.
631
632 Searches for .claude/last30days.env in each parent directory,
633 stopping at the git root, user's home directory, or filesystem root.
634 Rejects symlinks, junctions, and non-regular files so an untrusted
635 repository cannot redirect config reads outside the project tree.
636 """
637 cwd = Path.cwd()
638 for parent in [cwd, *cwd.parents]:
639 claude_dir = parent / '.claude'
640 candidate = claude_dir / 'last30days.env'
641 if not _is_symlink_or_junction(claude_dir) and not _is_symlink_or_junction(candidate):
642 try:
643 st = candidate.lstat()
644 except OSError:
645 st = None
646 if st is not None and stat.S_ISREG(st.st_mode):
647 return candidate
648 if (parent / ".git").exists():
649 break
650 # Stop at filesystem root or home
651 if parent == Path.home() or parent == parent.parent:
652 break
653 return None
654
655
656 def _load_config_files(
657 policy: ConfigLoadPolicy,
658 *,
659 raise_read_errors: bool = False,
660 ) -> tuple[dict[str, str], dict[str, str], Path | None]:
661 file_env = (
662 load_env_file(CONFIG_FILE, raise_read_errors=raise_read_errors) if CONFIG_FILE else {}
663 )
664 project_path = _find_project_env() if _project_config_trusted(policy, file_env) else None
665 project_env = (
666 load_env_file(project_path, allow_symlink=False, raise_read_errors=raise_read_errors)
667 if project_path else {}
668 )
669 return file_env, project_env, project_path
670
671
672 def resolve_searxng_url() -> str | None:
673 """Read only the approved SearXNG setting, without exporting process settings."""
674 key = "LAST30DAYS_SEARXNG_URL"
675 value = os.environ.get(key)
676 if value and not is_unsubstituted_template(value):
677 return value
678 # A read failure that may pass raises ConfigReadError, so a caller can retry instead of
679 # remembering "no URL". A missing or unsafe file is still just absent.
680 file_env, project_env, _ = _load_config_files(ConfigLoadPolicy(), raise_read_errors=True)
681 for layer in (project_env, file_env):
682 value = layer.get(key)
683 if value is not None and not is_unsubstituted_template(value):
684 return value
685 return None
686
687
688 def has_recorded_browser_consent() -> bool:
689 """Check whether setup can reuse explicit consent without opening credential stores."""
690 file_env, project_env, _ = _load_config_files(ConfigLoadPolicy())
691 consent_keys = frozenset({"BROWSER_CONSENT", "FROM_BROWSER"})
692 discarded: set[str] = set()
693 file_env = _strip_layer_templates(file_env, consent_keys, discarded)
694 project_env = _strip_layer_templates(project_env, consent_keys, discarded)
695 file_settings = {**file_env, **project_env}
696 config = {}
697 for key in ("BROWSER_CONSENT", "FROM_BROWSER"):
698 value = os.environ.get(key)
699 config[key] = (
700 file_settings.get(key)
701 if not value or is_unsubstituted_template(value)
702 else value
703 )
704 return browser_consent_granted(config)
705
706
707 def _configured_memory_dir(*values: str | None) -> str | None:
708 for value in values:
709 if value is not None and not is_unsubstituted_template(value):
710 return value
711 return None
712
713
714 def resolve_memory_dir(save_dir: str | None = None) -> str:
715 """Resolve the skill's save directory without credential-store access."""
716 value = save_dir
717 if value is None:
718 value = _configured_memory_dir(os.environ.get("LAST30DAYS_MEMORY_DIR"))
719 if value is None:
720 file_env, project_env, _ = _load_config_files(ConfigLoadPolicy())
721 value = _configured_memory_dir(
722 project_env.get("LAST30DAYS_MEMORY_DIR"),
723 file_env.get("LAST30DAYS_MEMORY_DIR"),
724 )
725 if value is None:
726 value = str(Path.home() / "Documents" / "Last30Days")
727 if value and not value.strip():
728 raise ValueError("--save-dir / LAST30DAYS_MEMORY_DIR cannot be whitespace-only.")
729 return str(Path(value).expanduser().absolute()) if value else ""
730
731
732 def get_config(policy: ConfigLoadPolicy | None = None) -> dict[str, Any]:
733 """Load configuration from multiple sources.
734
735 Priority (highest wins):
736 1. Environment variables (os.environ)
737 2. Trusted .claude/last30days.env (per-project config)
738 3. ~/.config/last30days/.env (global config)
739 4. macOS Keychain items prefixed ``last30days-`` (Darwin only)
740 """
741 policy = policy or ConfigLoadPolicy()
742
743 keys = [
744 # Debug flag; also exported to os.environ below so log.py's lazy
745 # os.environ.get() picks up .env values after get_config() runs.
746 ('LAST30DAYS_DEBUG', None),
747 ('XAI_API_KEY', None),
748 ('GOOGLE_API_KEY', None),
749 ('GEMINI_API_KEY', None),
750 ('GOOGLE_GENAI_API_KEY', None),
751 ('XIAOHONGSHU_API_BASE', None),
752 ('LAST30DAYS_REASONING_PROVIDER', 'auto'),
753 ('LAST30DAYS_PLANNER_MODEL', None),
754 ('LAST30DAYS_RERANK_MODEL', None),
755 ('LAST30DAYS_X_MODEL', None),
756 ('LAST30DAYS_X_BACKEND', None),
757 # Wall-clock budget (seconds) for the X backend chain. Default 90; a
758 # grok call on a subscription account measured 150-170s, so pinning
759 # grok needs a larger budget to return the first call's posts. Read
760 # from the resolved config only (pipeline._x_chain_budget_seconds);
761 # blank/invalid/non-finite/non-positive falls back to 90, values above
762 # 240 clamp to 240 (the default-depth grok per-call ceiling).
763 ('LAST30DAYS_X_BUDGET_SECONDS', None),
764 ('LAST30DAYS_REDDIT_BACKEND', None),
765 ('LAST30DAYS_YOUTUBE_BACKEND', None),
766 # Jobs lane: skip a job listing its site's robots.txt disallows.
767 # job_boards.robots reads os.environ, so .env values are exported below.
768 ('LAST30DAYS_JOBS_RESPECT_ROBOTS', None),
769 # Keyless reddit.com token-bucket rate (req/sec). http.py reads it
770 # from os.environ on each acquire, so .env values are exported below.
771 ('LAST30DAYS_REDDIT_KEYLESS_RATE', None),
772 # Doctor cache freshness window in seconds (doctor --cached).
773 ('LAST30DAYS_DOCTOR_TTL', None),
774 # Per-source deadline (seconds) for doctor --probe live checks.
775 ('LAST30DAYS_DOCTOR_PROBE_TIMEOUT', None),
776 ('LAST30DAYS_REDDIT_SC_MIN_ITEMS', None),
777 ('LAST30DAYS_YT_SC_MIN_ITEMS', None),
778 ('LAST30DAYS_STORE', None),
779 # Discovery topic queue (podcast/X-article pipeline memory). Default
780 # ON; the literal value "off" disables queue writes and annotations.
781 ('LAST30DAYS_DISCOVERY_QUEUE', None),
782 # Wall-clock budget (seconds) for the deep-tier enrichment batch on
783 # the discovery resume leg (--discover --judgments). Read from the
784 # resolved config only (pipeline._resume_enrich_budget_seconds);
785 # unset/invalid falls back to 450s. The one-shot --discover path
786 # keeps its fixed 240s quick budget regardless.
787 ('LAST30DAYS_ENRICH_BUDGET_SECONDS', None),
788 # Opt-in strict exit: truthy -> CLI exits 3 when any source outcome is
789 # degraded (neither ok, no-results, nor skipped-unconfigured). #384.
790 ('LAST30DAYS_STRICT_EXIT', None),
791 ('LAST30DAYS_MEMORY_DIR', None),
792 # Optional local-only evidence source. Paths are separated with the
793 # platform path separator (":" on macOS/Linux, ";" on Windows).
794 ('LAST30DAYS_CORPUS_DIRS', None),
795 # Corpus evidence is omitted from the stable agent JSON export unless
796 # this explicit privacy opt-in is truthy.
797 ('LAST30DAYS_CORPUS_IN_EXPORT', None),
798 ('LAST30DAYS_LIBRARY_OWNER', None),
799 ('LAST30DAYS_LIBRARY_CONTEXT', 'on'),
800 ('LAST30DAYS_AUTO_CAPTURE', 'on'),
801 ('LAST30DAYS_HOOK_DEBUG', None),
802 ('LAST30DAYS_PUBLISH_PASSWORD', None),
803 ('OPENAI_MODEL_PIN', None),
804 ('XAI_MODEL_PIN', None),
805 ('OPENAI_BASE_URL', None),
806 ('XAI_BASE_URL', None),
807 ('OPENROUTER_BASE_URL', None),
808 ('SCRAPECREATORS_API_KEY', None),
809 ('SCRAPECREATORS_BASE_URL', None),
810 ('APIFY_API_TOKEN', None),
811 ('AUTH_TOKEN', None),
812 ('CT0', None),
813 ('BSKY_HANDLE', None),
814 ('BSKY_APP_PASSWORD', None),
815 ('BSKY_SEARCH_HOST', None),
816 ('TRUTHSOCIAL_TOKEN', None),
817 ('BRAVE_API_KEY', None),
818 ('EXA_API_KEY', None),
819 ('SERPER_API_KEY', None),
820 ('OPENROUTER_API_KEY', None),
821 ('PERPLEXITY_API_KEY', None),
822 ('LAST30DAYS_PERPLEXITY_MODE', 'agent'),
823 # Legacy Sonar setting. Retain it during migration so existing env
824 # files load, but the Agent adapter does not map it to a dynamic preset.
825 ('LAST30DAYS_PERPLEXITY_MODEL', None),
826 ('LAST30DAYS_PERPLEXITY_AGENT_MODEL', None),
827 ('LAST30DAYS_PERPLEXITY_AGENT_PRESET', None),
828 ('LAST30DAYS_PERPLEXITY_AGENT_MAX_STEPS', None),
829 ('LAST30DAYS_PERPLEXITY_AGENT_MAX_OUTPUT_TOKENS', None),
830 ('LAST30DAYS_PERPLEXITY_AGENT_TIMEOUT_SECONDS', '120'),
831 ('LAST30DAYS_PERPLEXITY_MAX_RESULTS', None),
832 ('LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE', None),
833 ('LAST30DAYS_PERPLEXITY_SEARCH_TYPE', None),
834 ('LAST30DAYS_PERPLEXITY_SEARCH_MODE', None),
835 ('LAST30DAYS_PERPLEXITY_DOMAIN_FILTER', None),
836 ('LAST30DAYS_PERPLEXITY_LANGUAGE_FILTER', None),
837 ('LAST30DAYS_PERPLEXITY_COUNTRY', None),
838 ('LAST30DAYS_PERPLEXITY_RECENCY_FILTER', None),
839 ('LAST30DAYS_PERPLEXITY_REASONING_EFFORT', None),
840 ('LAST30DAYS_PERPLEXITY_DEEP_TIMEOUT_SECONDS', '600'),
841 ('PARALLEL_API_KEY', None),
842 ('XQUIK_API_KEY', None),
843 # Deepline: one key for the person-run lanes (LinkedIn profile and
844 # posts, name-to-profile lookup). Called directly, never proxied.
845 ('DEEPLINE_API_KEY', None),
846 # Bright Data CLI. Optional: the CLI normally owns its own auth via
847 # `brightdata login`, so this only matters for users who prefer an
848 # explicit key in a `.env` file or the keychain. Registered here so
849 # those layers reach the gate and the subprocess environment alike.
850 ('BRIGHTDATA_API_KEY', None),
851 # Amazon marketplace the amazon source searches. Non-US users point
852 # this at their own storefront (e.g. https://www.amazon.co.uk).
853 ('LAST30DAYS_AMAZON_DOMAIN', 'https://www.amazon.com'),
854 # Ad Library country for the meta_ads source, as a two-letter code. The
855 # endpoint takes exactly one country per call. There is deliberately no
856 # durable env form of the advertiser-page override: a page id is
857 # per-topic state, and env keys ride through the competitor runner's
858 # config copy, which would attach one brand's ads to every peer.
859 ('LAST30DAYS_META_ADS_COUNTRY', 'US'),
860 # Host-native search signal: set by the SKILL.md agent-host path when the
861 # invoking runtime has its own (better) web-search tool, so the engine's
862 # keyless search floor stays off there. Defaults unset -> floor allowed.
863 ('LAST30DAYS_NATIVE_SEARCH', None),
864 # Optional SearXNG instance for the keyless-search fallback rung.
865 ('LAST30DAYS_SEARXNG_URL', None),
866 # Keyless TikTok/Instagram lane switches (lib/shortform_oss.py):
867 # discovery freshness (on/off/backend list) and TikTok creator expansion.
868 ('LAST30DAYS_SHORTFORM_FRESHNESS', None),
869 ('LAST30DAYS_SHORTFORM_CREATOR_EXPANSION', None),
870 # TikTok top comments from TikTok's public web endpoint (free, no key):
871 # on (default) or off. Off puts comment calls back on ScrapeCreators.
872 ('LAST30DAYS_TIKTOK_PUBLIC_COMMENTS', None),
873 # Optional overrides for news-rss-pp-cli (default: google,bing,local and
874 # the CLI's standard store path).
875 ('LAST30DAYS_NEWS_RSS_SOURCES', None),
876 ('LAST30DAYS_NEWS_RSS_DB', None),
877 # Truthy -> disable Trustpilot's headless-Chrome WAF-cookie harvest in
878 # automated contexts (cron/CI/eval). Read by trustpilot._harvest_allowed.
879 ('LAST30DAYS_TRUSTPILOT_NO_BROWSER', None),
880 ('FROM_BROWSER', None),
881 ('BROWSER_CONSENT', None),
882 # Opt-in logged-in Reddit session (lib/reddit_session.py). Its own
883 # consent, separate from BROWSER_CONSENT (which can only veto it),
884 # and its own browser, recorded by `setup --reddit-session`.
885 (REDDIT_CONSENT_VAR, None),
886 (REDDIT_FROM_BROWSER_VAR, None),
887 (REDDIT_OFFERED_VAR, None),
888 (REDDIT_SESSION_SCHEDULED_VAR, None),
889 # Process env only (see the loop below): a .env line must not make
890 # every run look scheduled.
891 (SCHEDULED_RUN_VAR, None),
892 ('LAST30DAYS_X_COOKIE_ACCESS_DENIED', None),
893 # agentcookie sidecar: soft-dep X cookie source (lib/agentcookie.py),
894 # active only on extra hosts (Linux / Mac mini / Darwin sink) or when
895 # set to "on". "off" disables the sidecar reader.
896 ('AGENTCOOKIE', None),
897 # Explicit Chrome DevTools endpoint for the extra-host CDP cookie
898 # lookup (lib/chrome_cdp.py), e.g. http://127.0.0.1:18800. Preferred
899 # over the 18800 / 9222+$DISPLAY defaults when set.
900 ('BROWSER_CDP_URL', None),
901 ('LAST30DAYS_TRUST_PROJECT_CONFIG', None),
902 ('SETUP_COMPLETE', None),
903 ('INCLUDE_SOURCES', ''),
904 ('EXCLUDE_SOURCES', ''),
905 ('LAST30DAYS_DEFAULT_SEARCH', ''),
906 # Resolve the user-facing default in last30days.py so an absent value
907 # stays distinguishable from an explicit `default`. That distinction
908 # lets the new key override legacy ELI5_MODE=true configurations.
909 ('LAST30DAYS_REGISTER', None),
910 ('FUN_LEVEL', 'medium'),
911 # Backward compatibility for configs written by the original `eli5 on`
912 # follow-up command. New writes use LAST30DAYS_REGISTER=eli5.
913 ('ELI5_MODE', None),
914 ('LAST30DAYS_YOUTUBE_SSH_HOST', None),
915 # Proxy for yt-dlp; YT_PROXY is the short alias. Only routes yt-dlp
916 # traffic — does not affect other HTTP calls the skill makes.
917 ('YOUTUBE_PROXY', None),
918 ('YT_PROXY', None),
919 ('LAST30DAYS_REPORT_CACHE_TTL_SECONDS', None),
920 ('LAST30DAYS_VERIFY_FRESHNESS', None),
921 ('LAST30DAYS_TRANSCRIPT_TIMEOUT', None),
922 ('DEGRADED_TRANSCRIPT_THRESHOLD', None),
923 (KEYCHAIN_ALIASES_ENV, None),
924 # Whisper transcription provider for caption-free audio/video. Groq's
925 # free tier is preferred; OPENAI_API_KEY is the paid backstop (already
926 # resolved above via openai_auth).
927 ('GROQ_API_KEY', None),
928 ('LAST30DAYS_YT_SUB_LANGS', 'en,es,pt'),
929 # youtube_yt reads this lazily from os.environ; default android is
930 # applied there when the key is absent. Empty disables.
931 ('LAST30DAYS_YT_PLAYER_CLIENT', None),
932 ('LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT', None),
933 ('LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS', None),
934 ('LAST30DAYS_YT_SEARCH_TIMEOUT', None),
935 ('GITHUB_TOKEN', None),
936 # Host self-identification. `grok-bot` switches the X policy
937 # to official-only (see x_policy); the engine never sniffs the host
938 # any other way. Persisted by first-run setup and exported per
939 # invocation by the SKILL.md rule.
940 (X_HOST_VAR, None),
941 # App-only bearer token for the direct X API v2 backend (`xapi`).
942 ('X_BEARER_TOKEN', None),
943 # Per-session X connector lane signal. Read from the process
944 # environment ONLY: a .env line is deliberately ignored (a removed
945 # connector must never leave a stale declaration), so it is handled
946 # in the loop below rather than via merged_env.
947 (X_HOST_LANE_VAR, None),
948 ]
949
950 # Strip unsubstituted ``${user_config.*}`` extension placeholders per source
951 # layer *before* trust checks, secret-store probing, layer merging, legacy
952 # alias lookup, lazy env exports, and browser-cookie preflight calculation.
953 # Bounded to registered keys so unregistered env vars (such as
954 # LAST30DAYS_API_KEY or an unused SCRAPE_CREATORS_API_KEY) remain untouched.
955 legacy_alias_map = {
956 'SCRAPE_CREATORS_API_KEY': 'SCRAPECREATORS_API_KEY',
957 'SCRAPE_CREATORS_BASE_URL': 'SCRAPECREATORS_BASE_URL',
958 }
959 registered_keys = frozenset({'OPENAI_API_KEY', *(key for key, _ in keys)})
960 file_strip_keys = registered_keys | frozenset(legacy_alias_map)
961 process_only_keys = frozenset({X_HOST_LANE_VAR, SCHEDULED_RUN_VAR})
962 preserve_none_keys = frozenset({
963 'BROWSER_CONSENT',
964 'LAST30DAYS_MEMORY_DIR',
965 X_HOST_LANE_VAR,
966 SCHEDULED_RUN_VAR,
967 })
968 templated_seen: set[str] = set()
969 for key in registered_keys:
970 if is_unsubstituted_template(os.environ.get(key)):
971 os.environ.pop(key, None)
972 templated_seen.add(key)
973
974 # Load per-project config only when trust comes from process env, global
975 # user config, or an explicit policy. A project file cannot grant trust to
976 # itself because it is not parsed until after this decision.
977 file_env, project_env, project_env_path = _load_config_files(policy)
978 ignored_project_env_path = None
979 ignored_project_keys: list[str] = []
980 if policy.inspect_ignored_project_config and not _project_config_trusted(policy, file_env):
981 ignored_project_env_path = _find_project_env()
982 if ignored_project_env_path:
983 ignored_project_keys = sorted(
984 load_env_file(
985 ignored_project_env_path,
986 allow_symlink=False,
987 strict_keys=True,
988 ).keys()
989 )
990
991 file_env = _strip_layer_templates(
992 file_env, file_strip_keys, templated_seen, canonical_map=legacy_alias_map
993 )
994 project_env = _strip_layer_templates(
995 project_env, file_strip_keys, templated_seen, canonical_map=legacy_alias_map
996 )
997
998 # Merge file sources: project > global
999 merged_env = {**file_env, **project_env}
1000
1001 # Keychain and pass(1) are the lowest-priority credential stores. Skip both
1002 # when the caller's ConfigLoadPolicy opts out (e.g. offline, mock, invalid,
1003 # or hosted-API invocations) so users are never prompted for unused secrets.
1004 keychain_env: dict[str, str] = {}
1005 pass_env: dict[str, str] = {}
1006 if policy.load_secret_stores:
1007 keychain_aliases_raw = os.environ.get(KEYCHAIN_ALIASES_ENV) or merged_env.get(KEYCHAIN_ALIASES_ENV)
1008 keychain_aliases = _parse_keychain_aliases(keychain_aliases_raw)
1009 keychain_env = _strip_layer_templates(
1010 _load_keychain(list(KEYCHAIN_KEYS), keychain_aliases),
1011 registered_keys,
1012 templated_seen,
1013 )
1014 merged_env = {**keychain_env, **merged_env}
1015 # pass(1) store: Linux/Unix analog of Keychain at convention path
1016 # {prefix}<KEY>. Decrypts transiently so secrets stay encrypted at rest (no
1017 # plaintext .env). Lowest priority: Keychain, the config files, and process
1018 # env all win over it. Two efficiency guards so a user who merely has `pass`
1019 # on PATH doesn't pay for it: resolve the prefix from the loaded config/env
1020 # (not import time, so a .env-set LAST30DAYS_PASS_PREFIX is honored), and
1021 # probe ONLY keys still unset after the higher-priority sources — an empty
1022 # list short-circuits with no gpg/pinentry calls at all.
1023 env_pass_prefix = os.environ.get("LAST30DAYS_PASS_PREFIX")
1024 if is_unsubstituted_template(env_pass_prefix):
1025 env_pass_prefix = None
1026 file_pass_prefix = next(
1027 (
1028 value
1029 for value in (
1030 project_env.get("LAST30DAYS_PASS_PREFIX"),
1031 file_env.get("LAST30DAYS_PASS_PREFIX"),
1032 )
1033 if value and not is_unsubstituted_template(value)
1034 ),
1035 None,
1036 )
1037 pass_prefix = env_pass_prefix or file_pass_prefix or DEFAULT_PASS_PATH_PREFIX
1038 pass_missing = [
1039 k
1040 for k in KEYCHAIN_KEYS
1041 if (not os.environ.get(k) or is_unsubstituted_template(os.environ.get(k)))
1042 and not merged_env.get(k)
1043 ]
1044 pass_env = _strip_layer_templates(
1045 _load_pass(pass_missing, pass_prefix),
1046 registered_keys,
1047 templated_seen,
1048 )
1049 merged_env = {**pass_env, **merged_env}
1050
1051 openai_auth = get_openai_auth(merged_env)
1052
1053 # Build config: Codex/OpenAI auth + process.env > project .env > global .env
1054 config = {
1055 'OPENAI_API_KEY': openai_auth.token,
1056 'OPENAI_AUTH_SOURCE': openai_auth.source,
1057 'OPENAI_AUTH_STATUS': openai_auth.status,
1058 }
1059
1060 for key, default in keys:
1061 if key in process_only_keys:
1062 # Process env only; the .env value never reaches config.
1063 config[key] = os.environ.get(key) or default
1064 continue
1065 if key in {'LAST30DAYS_YT_PLAYER_CLIENT', 'LAST30DAYS_MEMORY_DIR'}:
1066 # Empty string is a valid disable; `or` would treat it as unset.
1067 if key in os.environ:
1068 config[key] = os.environ.get(key)
1069 elif key in merged_env:
1070 # Mapping lookup via .get; bracket form trips a CRITICAL
1071 # scanner false positive on this identifier.
1072 config[key] = merged_env.get(key)
1073 else:
1074 config[key] = default
1075 else:
1076 config[key] = os.environ.get(key) or merged_env.get(key, default)
1077
1078 # Backward-compat: ScrapeCreators' own examples and tutorials use the
1079 # SCRAPE_CREATORS_API_KEY spelling (with underscore between SCRAPE and
1080 # CREATORS). Accept that form too so users who follow the vendor's docs
1081 # don't silently end up with has_scrapecreators=False. Canonical name
1082 # wins when both are set.
1083 if not config.get('SCRAPECREATORS_API_KEY'):
1084 env_legacy = read_secret_env('SCRAPE_CREATORS_API_KEY')
1085 if is_unsubstituted_template(env_legacy):
1086 templated_seen.add('SCRAPECREATORS_API_KEY')
1087 env_legacy = None
1088 legacy = env_legacy or merged_env.get('SCRAPE_CREATORS_API_KEY')
1089 if legacy:
1090 config['SCRAPECREATORS_API_KEY'] = legacy
1091
1092 if not config.get('SCRAPECREATORS_BASE_URL'):
1093 env_legacy_base = os.environ.get('SCRAPE_CREATORS_BASE_URL')
1094 if is_unsubstituted_template(env_legacy_base):
1095 templated_seen.add('SCRAPECREATORS_BASE_URL')
1096 env_legacy_base = None
1097 legacy_base = env_legacy_base or merged_env.get('SCRAPE_CREATORS_BASE_URL')
1098 if legacy_base:
1099 config['SCRAPECREATORS_BASE_URL'] = legacy_base
1100
1101 # Multi-key rotation: comma-separated SCRAPECREATORS_API_KEY round-robins
1102 # via random.choice per run. Originally added in #268, accidentally dropped
1103 # in v3.0.6, restored here.
1104 _rotate_scrapecreators_key(config)
1105 if is_unsubstituted_template(config.get('SCRAPECREATORS_API_KEY')):
1106 templated_seen.add('SCRAPECREATORS_API_KEY')
1107 config['SCRAPECREATORS_API_KEY'] = None
1108
1109 # Export debug flag to os.environ so log.py's lazy os.environ.get()
1110 # picks up .env values. setdefault ensures a shell-exported value is
1111 # never overwritten by the (lower-priority) .env value.
1112 if config.get('LAST30DAYS_DEBUG'):
1113 os.environ.setdefault('LAST30DAYS_DEBUG', config['LAST30DAYS_DEBUG'])
1114
1115 # youtube_yt reads these tuning knobs lazily from os.environ, so values
1116 # loaded from .env (including fallbacks restored after stripping a
1117 # placeholder) must be exported into the current engine process.
1118 for key in (
1119 'LAST30DAYS_YT_SUB_LANGS',
1120 'LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT',
1121 'LAST30DAYS_YT_TRANSCRIPT_FAST_ATTEMPTS',
1122 'LAST30DAYS_YT_SEARCH_TIMEOUT',
1123 'LAST30DAYS_REDDIT_KEYLESS_RATE',
1124 'LAST30DAYS_YT_PLAYER_CLIENT',
1125 'LAST30DAYS_JOBS_RESPECT_ROBOTS',
1126 'SCRAPECREATORS_BASE_URL',
1127 ):
1128 value = config.get(key)
1129 # Empty LAST30DAYS_YT_PLAYER_CLIENT is a valid disable; other knobs
1130 # treat empty as unset and keep their code defaults.
1131 if key == 'LAST30DAYS_YT_PLAYER_CLIENT':
1132 if value is not None:
1133 os.environ.setdefault(key, value)
1134 elif value:
1135 os.environ.setdefault(key, value)
1136
1137 # Track which config source was used (highest-priority file source wins
1138 # the label; keychain is only reported when nothing else is configured).
1139 if project_env_path:
1140 config['_CONFIG_SOURCE'] = f'project:{project_env_path}'
1141 elif CONFIG_FILE and CONFIG_FILE.exists():
1142 config['_CONFIG_SOURCE'] = f'global:{CONFIG_FILE}'
1143 elif keychain_env:
1144 config['_CONFIG_SOURCE'] = 'keychain'
1145 elif pass_env:
1146 config['_CONFIG_SOURCE'] = 'pass'
1147 else:
1148 config['_CONFIG_SOURCE'] = 'env_only'
1149 if ignored_project_env_path:
1150 config['_IGNORED_PROJECT_CONFIG'] = str(ignored_project_env_path)
1151 config['_IGNORED_PROJECT_CONFIG_KEYS'] = ignored_project_keys
1152 config['_BROWSER_COOKIE_MODE'] = policy.browser_cookies
1153 # A LAST30DAYS_X_HOST_LANE line in a config file is ignored;
1154 # remember that it was there so doctor can say so.
1155 config['_X_HOST_LANE_FILE_IGNORED'] = bool(merged_env.get(X_HOST_LANE_VAR))
1156 # Evaluated after placeholder stripping and fallback restoration so preflight
1157 # and runtime agree on browser-cookie reads.
1158 config['_BROWSER_COOKIE_BROWSERS'] = cookie_extraction_browsers(config)
1159
1160 # Report only the keys still leaving the setting unset. Preserve None for
1161 # keys where None != "" (BROWSER_CONSENT, LAST30DAYS_MEMORY_DIR, and
1162 # process-env-only keys), while keeping "" for ordinary unset templated keys.
1163 templated_keys = sorted(templated_seen)
1164 config[TEMPLATE_CONFIG_KEYS] = [
1165 key
1166 for key in templated_keys
1167 if (
1168 config.get(key) is None
1169 if key in {'LAST30DAYS_MEMORY_DIR', 'LAST30DAYS_YT_PLAYER_CLIENT'}
1170 else not config.get(key)
1171 )
1172 ]
1173 for key in templated_keys:
1174 if config.get(key) is None and key not in preserve_none_keys:
1175 config[key] = ''
1176 if 'OPENAI_API_KEY' in templated_keys and not config.get('OPENAI_API_KEY'):
1177 # Keep the derived auth record consistent with the token it describes.
1178 config['OPENAI_AUTH_SOURCE'] = AUTH_SOURCE_NONE
1179 config['OPENAI_AUTH_STATUS'] = AUTH_STATUS_MISSING
1180
1181 if policy.browser_cookies == "read":
1182 if policy.require_recorded_browser_consent and not browser_consent_granted(config):
1183 config['_BROWSER_COOKIE_MODE'] = "off"
1184 else:
1185 _discover_and_apply_x_credentials(config)
1186
1187 # Proxy mode (LAST30DAYS_API_MODE=proxy): each paid lane the user has no
1188 # key for is served through the metered proxy. Filled last, so a user's
1189 # own key from any source always wins for its provider.
1190 from . import proxy as _proxy
1191 _proxy.fill_config(config)
1192
1193 # Fixture recording (--record-fixtures) must redact a credential that
1194 # came from a file, Keychain, or pass, not only one exported in the
1195 # shell. No-op outside a recording session.
1196 from . import http as _http
1197 _http.add_fixture_redactions(_http.config_secret_values(config))
1198
1199 return config
1200
1201
1202 # ---------------------------------------------------------------------------
1203 # Extra-host X cookie discovery (Linux, Mac mini, Darwin agentcookie sink)
1204 # ---------------------------------------------------------------------------
1205
1206
1207 def _mac_model() -> str:
1208 """Darwin hardware model via ``sysctl -n hw.model``, or "" otherwise.
1209
1210 Returns "" on non-Darwin and on any sysctl failure (missing binary,
1211 non-zero exit, timeout) — the caller treats "" as "not a Mac mini", i.e. a
1212 MacBook, which is the conservative default (no extra cookie lookups).
1213 """
1214 import platform
1215 if platform.system() != "Darwin":
1216 return ""
1217 import subprocess
1218 try:
1219 out = subprocess.run(
1220 ["sysctl", "-n", "hw.model"],
1221 capture_output=True, text=True, timeout=3,
1222 )
1223 except (OSError, subprocess.SubprocessError):
1224 return ""
1225 if out.returncode != 0:
1226 return ""
1227 return (out.stdout or "").strip()
1228
1229
1230 def _is_mac_mini() -> bool:
1231 """True on a Darwin Mac mini (``hw.model`` prefix ``Macmini``).
1232
1233 sysctl failure yields "" -> False, so an unreadable model is treated as a
1234 MacBook (no extras), per the plan.
1235 """
1236 return _mac_model().startswith("Macmini")
1237
1238
1239 def x_extras_enabled(config: dict[str, Any]) -> bool:
1240 """Whether the two EXTRA bird cookie lookups (agentcookie sidecar, live
1241 Chrome CDP) apply on this host.
1242
1243 Extras apply when ANY of:
1244 * ``AGENTCOOKIE=on`` — explicit per-host opt-in (works on a MacBook too);
1245 * platform is Linux;
1246 * a Darwin Mac mini (``hw.model`` prefix ``Macmini``);
1247 * a Darwin agentcookie **sink** role (parse failure = not sink).
1248
1249 A plain MacBook (Darwin, source/unknown role, no opt-in) stays on the
1250 mainline path — no agentcookie subprocess, no CDP socket. The host is NEVER
1251 inferred from the home directory, PATH, or ``HERMES_AGENT``/``OPENCLAW_CLI``
1252 env: only the signals above.
1253 """
1254 import platform
1255 raw = (config.get("AGENTCOOKIE") or read_secret_env("AGENTCOOKIE") or "").strip().lower()
1256 if raw == "on":
1257 return True
1258 system = platform.system()
1259 if system == "Linux":
1260 return True
1261 if system == "Darwin":
1262 if _is_mac_mini():
1263 return True
1264 from . import agentcookie
1265 return agentcookie.role_is_sink(config)
1266 return False
1267
1268
1269 def _apply_x_pair(config: dict[str, Any], auth_token: str, ct0: str, source: str) -> None:
1270 """Apply a COMPLETE X cookie pair from one source, labeling its origin.
1271
1272 Atomic on purpose (both keys from the same source) so a half-pair from one
1273 source is never merged with a half-pair from another. Never written to the
1274 ``.env``; values are never logged.
1275 """
1276 config["AUTH_TOKEN"] = auth_token
1277 config["CT0"] = ct0
1278 config["_AUTH_TOKEN_SOURCE"] = source
1279 config["_CT0_SOURCE"] = source
1280
1281
1282 def _apply_browser_extract(config: dict[str, Any]) -> None:
1283 """Run the mainline in-process browser cookie extractor (unchanged from
1284 main): fills X (when a browser is opted in via FROM_BROWSER) and non-X
1285 cookie domains like truthsocial. Missing keys only; source label ``browser``."""
1286 browser_creds = extract_browser_credentials(config)
1287 for key, value in browser_creds.items():
1288 if not config.get(key):
1289 config[key] = value
1290 config[f"_{key}_SOURCE"] = "browser"
1291
1292
1293 def _discover_and_apply_x_credentials(config: dict[str, Any]) -> None:
1294 """Fill AUTH_TOKEN/CT0 for the bird backend, first COMPLETE pair wins.
1295
1296 Mainline (every host): the in-process browser extractor, gated by
1297 FROM_BROWSER exactly as on ``main``. EXTRA lookups (agentcookie sidecar,
1298 then live Chrome CDP) run ONLY on extra hosts (``x_extras_enabled``), so a
1299 MacBook with FROM_BROWSER unset/off does no agentcookie spawn and no CDP
1300 socket. Probe order:
1301
1302 1. an explicit env AUTH_TOKEN+CT0 already present — never overwritten;
1303 2. agentcookie sidecar (extras only);
1304 3. live Chrome CDP (extras only);
1305 4. the mainline browser extract (all hosts; X only when FROM_BROWSER
1306 lists a browser).
1307
1308 On a Mac mini that has already opted into browser reads (FROM_BROWSER set),
1309 the native extract runs BEFORE CDP (R19) — a local Keychain read beats a
1310 debug-port scrape. Never persists cookies; values are never logged.
1311
1312 On an official-only host (``x_policy``: ``LAST30DAYS_HOST=grok-bot``)
1313 this returns before ANY leg, for every cookie domain, unless the pin is
1314 ``bird`` (the one path that re-enables discovery for that run).
1315 """
1316 if not x_policy(config).cookie_discovery or cookie_access_denied(config):
1317 return
1318
1319 from . import agentcookie, chrome_cdp
1320
1321 def have_pair() -> bool:
1322 return bool(config.get("AUTH_TOKEN") and config.get("CT0"))
1323
1324 extras = x_extras_enabled(config)
1325
1326 # (2) agentcookie sidecar — extras only, complete pair only.
1327 if extras and not have_pair():
1328 pair = agentcookie.read_x_cookies(config)
1329 if pair:
1330 _apply_x_pair(config, pair["auth_token"], pair["ct0"], "agentcookie")
1331
1332 # Mac mini + browser opted in: native extract before CDP (R19).
1333 mini_extract_first = (
1334 extras and _is_mac_mini() and bool(cookie_extraction_browsers(config))
1335 )
1336 if mini_extract_first and not have_pair():
1337 _apply_browser_extract(config)
1338
1339 # (3) live Chrome CDP — extras only, after browser-cookie consent.
1340 if extras and not have_pair() and chrome_cdp.cookie_access_allowed(config):
1341 pair = chrome_cdp.read_x_cookies(config)
1342 if pair:
1343 _apply_x_pair(config, pair["auth_token"], pair["ct0"], "chrome cdp")
1344
1345 # (4) mainline browser extract (unless already run above for the mini case).
1346 if not mini_extract_first:
1347 _apply_browser_extract(config)
1348
1349
1350 # ---------------------------------------------------------------------------
1351 # Browser cookie extraction
1352 # ---------------------------------------------------------------------------
1353
1354 COOKIE_DOMAINS: dict[str, dict[str, Any]] = {
1355 "x": {
1356 "domain": ".x.com",
1357 "cookies": ["auth_token", "ct0"],
1358 "mapping": {"auth_token": "AUTH_TOKEN", "ct0": "CT0"},
1359 },
1360 "truthsocial": {
1361 "domain": ".truthsocial.com",
1362 "cookies": ["_session_id"],
1363 "mapping": {"_session_id": "TRUTHSOCIAL_TOKEN"},
1364 },
1365 # The logged-in Reddit session. Its own consent gates it, and it is read
1366 # from its own recorded browser, so the generic browser extract and the
1367 # X-consent setup scan always skip it (``consent_key``); only
1368 # read_reddit_session_cookie reads it, after reddit_session_gate passes.
1369 "reddit": {
1370 "domain": ".reddit.com",
1371 "cookies": ["reddit_session"],
1372 "mapping": {"reddit_session": "REDDIT_SESSION_COOKIE"},
1373 "consent_key": "REDDIT_BROWSER_CONSENT",
1374 },
1375 }
1376
1377 # --- Opt-in logged-in Reddit session ----------------------------------------
1378 #
1379 # Reading the reddit.com login cookie needs its own affirmative consent,
1380 # separate from the X browser consent: a user may want one without the other.
1381 # Every global refusal still vetoes it. The cookie lives only in process
1382 # memory; nothing persists it.
1383 REDDIT_CONSENT_VAR = "REDDIT_BROWSER_CONSENT"
1384 REDDIT_FROM_BROWSER_VAR = "REDDIT_FROM_BROWSER"
1385 # Written once the returning-user offer was made, whatever the answer.
1386 REDDIT_OFFERED_VAR = "REDDIT_SESSION_OFFERED"
1387 # In-memory key for the session cookie (never a .env key). The _COOKIE
1388 # suffix is what fixture recording redacts.
1389 REDDIT_SESSION_COOKIE_VAR = "REDDIT_SESSION_COOKIE"
1390 # Scheduled runs (cron, watchlist, briefing) export this; process env only.
1391 SCHEDULED_RUN_VAR = "LAST30DAYS_SCHEDULED_RUN"
1392 # Lets a scheduled run use the session anyway (its Keychain prompt cannot be
1393 # answered unattended, so this is off by default).
1394 REDDIT_SESSION_SCHEDULED_VAR = "LAST30DAYS_REDDIT_SESSION_SCHEDULED"
1395 REDDIT_COOKIE_DOMAIN = ".reddit.com"
1396 REDDIT_COOKIE_NAMES = ("reddit_session",)
1397 # Setup's scan order for the Reddit login: Chrome first, then the rest.
1398 REDDIT_SETUP_BROWSERS = (
1399 "chrome", "brave", "edge", "vivaldi", "opera", "arc", "dia", "ardia", "chromium", "firefox", "safari",
1400 )
1401
1402
1403 # Placeholder for a provider key served by the API-key proxy (lib/proxy.py
1404 # owns the routing; it is defined here because proxy imports this module).
1405 PROXY_SENTINEL = "last30days-proxy-lane"
1406
1407
1408 def proxy_mode_requested() -> bool:
1409 """True when LAST30DAYS_API_MODE selects the metered proxy (lib/proxy.py)."""
1410 return (os.environ.get("LAST30DAYS_API_MODE") or "").strip().lower() == "proxy"
1411
1412
1413 def hosted_backend_configured() -> bool:
1414 """True when research would run through the remote API backend.
1415
1416 Proxy mode keeps research on the local engine, so it is never hosted.
1417 """
1418 return bool(
1419 read_secret_env("LAST30DAYS_API_KEY")
1420 and os.environ.get("LAST30DAYS_API_BASE")
1421 and not proxy_mode_requested()
1422 )
1423
1424
1425 def global_cookie_refusal(config: dict[str, Any], reddit_consent: bool = False) -> str:
1426 """Why every browser-cookie read is refused this run, or "".
1427
1428 ``BROWSER_CONSENT=false``, ``FROM_BROWSER=off``, and a run that does not
1429 read browser cookies at all (``--no-browser-cookies``, the MCP default,
1430 and the plan-only ``--diagnose``/``--preflight``/``doctor`` modes).
1431
1432 ``reddit_consent`` marks an explicit yes to the Reddit session question.
1433 That yes is its own consent, so a ``BROWSER_CONSENT=false`` saved when the
1434 user skipped X does not block it. ``FROM_BROWSER=off`` still does.
1435 """
1436 if str(config.get("FROM_BROWSER") or "").strip().lower() == "off":
1437 return "FROM_BROWSER=off"
1438 if not reddit_consent and cookie_access_denied(config):
1439 return "BROWSER_CONSENT refuses browser reads"
1440 mode = config.get("_BROWSER_COOKIE_MODE") or "off"
1441 if mode == "plan_only":
1442 return "this mode reads no browser cookies"
1443 if mode != "read":
1444 return "browser cookies are off for this run"
1445 return ""
1446
1447
1448 def reddit_session_gate(config: dict[str, Any]) -> tuple[bool, str]:
1449 """Whether this run may read the Reddit login cookie: ``(allowed, why_not)``.
1450
1451 Pure: reads config and the process environment only, never a cookie. The
1452 order is the global veto, then the contexts that never use the session,
1453 then the Reddit consent itself, then a recorded browser.
1454 """
1455 refusal = global_cookie_refusal(config, reddit_consent=_truthy(config.get(REDDIT_CONSENT_VAR)))
1456 if refusal:
1457 return False, refusal
1458 if str(config.get(X_HOST_VAR) or os.environ.get(X_HOST_VAR) or "").strip().lower() == GROK_BOT_HOST:
1459 return False, "never on a Grok Bot host"
1460 if hosted_backend_configured():
1461 return False, "the hosted API backend runs research remotely"
1462 if _truthy(os.environ.get(SCHEDULED_RUN_VAR)) and not _truthy(
1463 config.get(REDDIT_SESSION_SCHEDULED_VAR) or os.environ.get(REDDIT_SESSION_SCHEDULED_VAR)
1464 ):
1465 return False, "scheduled run (set LAST30DAYS_REDDIT_SESSION_SCHEDULED=1 to allow)"
1466 if not _truthy(config.get(REDDIT_CONSENT_VAR)):
1467 return False, "no Reddit session consent"
1468 browser = str(config.get(REDDIT_FROM_BROWSER_VAR) or "").strip().lower()
1469 if browser not in COOKIE_BROWSER_NAMES:
1470 return False, "no browser recorded for the Reddit login (run setup --reddit-session)"
1471 return True, ""
1472
1473
1474 def reddit_scrapecreators_primary(config: dict[str, Any]) -> bool:
1475 return bool(
1476 config.get("SCRAPECREATORS_API_KEY")
1477 and (config.get(REDDIT_BACKEND_PIN_VAR) or "").strip().lower() == "scrapecreators"
1478 )
1479
1480
1481 def reddit_consent_state(config: dict[str, Any]) -> str:
1482 """``granted``, ``refused``, or ``unset`` (doctor and setup; no read)."""
1483 raw = config.get(REDDIT_CONSENT_VAR)
1484 if raw is None or str(raw).strip() == "":
1485 return "unset"
1486 return "granted" if _truthy(raw) else "refused"
1487
1488
1489 def read_reddit_session_cookie(
1490 config: dict[str, Any], browser: str | None = None,
1491 ) -> tuple[str | None, str]:
1492 """The ``reddit_session`` cookie from one browser: ``(value, status)``.
1493
1494 Reads only the recorded ``REDDIT_FROM_BROWSER`` (or ``browser``), never
1495 ``FROM_BROWSER``. ``status`` is ``ok``, ``not-logged-in``,
1496 ``permission-denied``, ``unsupported-encryption`` (a Windows app-bound
1497 store) or ``error``. Never logs the value. Callers check
1498 :func:`reddit_session_gate` first.
1499 """
1500 name = str(browser or config.get(REDDIT_FROM_BROWSER_VAR) or "").strip().lower()
1501 if name not in COOKIE_BROWSER_NAMES:
1502 return None, "error"
1503 if os.name == "nt" and name != "firefox":
1504 return None, "unsupported-encryption"
1505 try:
1506 from . import cookie_extract
1507 cookies = cookie_extract.extract_cookies(name, REDDIT_COOKIE_DOMAIN, list(REDDIT_COOKIE_NAMES))
1508 except PermissionError:
1509 return None, "permission-denied"
1510 except Exception:
1511 return None, "error"
1512 value = (cookies or {}).get("reddit_session")
1513 if not value:
1514 return None, "not-logged-in"
1515 from . import http as _http
1516 _http.add_fixture_redactions([value])
1517 return value, "ok"
1518
1519 COOKIE_BROWSER_NAMES = (
1520 "firefox", "safari", "chrome", "brave", "edge", "vivaldi", "opera", "arc", "dia", "ardia", "chromium"
1521 )
1522
1523
1524 def cookie_access_denied(config: dict[str, Any]) -> bool:
1525 """An explicit refusal blocks native, CDP, and sidecar cookie discovery.
1526
1527 Missing consent keeps each source's existing opt-in/default policy.
1528 A present but unrecognized consent value fails closed, as native reads do.
1529 This does not disable credentials supplied directly by the user.
1530 """
1531 if str(config.get("FROM_BROWSER") or "").strip().lower() == "off":
1532 return True
1533 consent = config.get("BROWSER_CONSENT")
1534 return consent is not None and str(consent).strip().lower() not in {
1535 "1", "true", "yes", "on",
1536 }
1537
1538
1539 def browser_consent_granted(config: dict[str, Any]) -> bool:
1540 return _truthy(config.get("BROWSER_CONSENT")) and not cookie_access_denied(config)
1541
1542
1543 def cookie_extraction_browsers(config: dict[str, Any]) -> list[str]:
1544 """Browsers to try for cookie extraction, honoring FROM_BROWSER.
1545
1546 Default (FROM_BROWSER unset): no browser-cookie reads. The Chromium family
1547 (Chrome, Brave, Edge, Vivaldi, Opera, Arc, Dia, Chromium) is available only when
1548 explicitly selected because reading their cookies on macOS requires the
1549 browser's Safe Storage Keychain key, which triggers a system password prompt
1550 that cannot be reliably suppressed. On Windows only Firefox cookie
1551 extraction is supported; Chrome and Edge use DPAPI-encrypted cookie stores
1552 that are not yet supported.
1553
1554 - ``FROM_BROWSER=<name>`` - a single browser (e.g. ``firefox``, ``brave``,
1555 ``edge``, ``arc``).
1556 - ``FROM_BROWSER=firefox,safari`` - a comma-separated explicit browser list.
1557 - ``FROM_BROWSER=auto`` - also try every Chromium browser (user accepts the
1558 Keychain dialog when needed).
1559 - ``FROM_BROWSER=off`` - returns [] (extraction disabled).
1560
1561 Returning the browser list from one place keeps the setup wizard and the
1562 steady-state path on the same policy, so neither surprises the user with an
1563 unrequested Keychain prompt. On an official-only host (``x_policy``) the
1564 list is empty regardless of ``FROM_BROWSER`` unless ``bird`` is pinned.
1565 """
1566 if not x_policy(config).cookie_discovery or cookie_access_denied(config):
1567 return []
1568 silent_browsers = list(COOKIE_BROWSER_NAMES[:2])
1569 chromium_browsers = list(COOKIE_BROWSER_NAMES[2:])
1570 known_browsers = list(COOKIE_BROWSER_NAMES)
1571 from_browser = (config.get("FROM_BROWSER") or "").strip().lower()
1572 if not from_browser:
1573 return []
1574 if from_browser == "off":
1575 return []
1576 if from_browser == "auto":
1577 return silent_browsers + chromium_browsers
1578 if "," in from_browser:
1579 requested = [b.strip() for b in from_browser.split(",") if b.strip()]
1580 resolved = [b for b in requested if b in known_browsers]
1581 unknown = [b for b in requested if b not in known_browsers]
1582 if unknown:
1583 sys.stderr.write(
1584 "[last30days] WARNING: FROM_BROWSER ignored unrecognized browser(s): "
1585 f"{', '.join(unknown)} (known: {', '.join(known_browsers)})\n"
1586 )
1587 sys.stderr.flush()
1588 return resolved
1589 if from_browser in known_browsers:
1590 return [from_browser]
1591 # Non-empty, not off/auto, not a known browser, not a list: unrecognized.
1592 # Warn rather than fail silently so a typo (FROM_BROWSER=chrme) is visible
1593 # instead of looking like "no cookies found".
1594 sys.stderr.write(
1595 f"[last30days] WARNING: FROM_BROWSER='{from_browser}' is not a recognized "
1596 f"browser; no cookies will be read (known: {', '.join(known_browsers)}, "
1597 "or 'auto'/'off')\n"
1598 )
1599 sys.stderr.flush()
1600 return []
1601
1602
1603
1604 def extract_browser_credentials(config: dict[str, Any]) -> dict[str, str]:
1605 """Extract auth cookies from local browsers.
1606
1607 Browser selection (and the Chrome-prompt caveat) is handled by
1608 ``cookie_extraction_browsers``; this function just runs the extraction for
1609 each configured cookie domain.
1610 """
1611 browsers = cookie_extraction_browsers(config)
1612 if not browsers:
1613 return {}
1614 try:
1615 from . import cookie_extract
1616 except ImportError:
1617 return {}
1618 extracted: dict[str, str] = {}
1619 for _service, spec in COOKIE_DOMAINS.items():
1620 if spec.get("consent_key"):
1621 # Its own gate and its own browser (read_reddit_session_cookie).
1622 continue
1623 missing_cookies = [
1624 name for name in spec["cookies"] if not config.get(spec["mapping"][name])
1625 ]
1626 if not missing_cookies:
1627 continue
1628 # Cookies from different browsers can belong to different sessions,
1629 # so values are never combined across browsers: a complete set from
1630 # one browser wins, else the first browser's partial set is kept.
1631 chosen: dict[str, str] | None = None
1632 chosen_index: int | None = None
1633 fallback: dict[str, str] | None = None
1634 denied_browsers: list[str] = []
1635 for index, browser in enumerate(browsers):
1636 try:
1637 cookies = cookie_extract.extract_cookies(browser, spec["domain"], spec["cookies"])
1638 except PermissionError:
1639 denied_browsers.append(browser)
1640 if len(missing_cookies) == len(spec["cookies"]):
1641 continue
1642 # Keep full-pair profile preference unless a denied profile blocks it.
1643 try:
1644 cookies = cookie_extract.extract_cookies(
1645 browser, spec["domain"], missing_cookies
1646 )
1647 except Exception:
1648 continue
1649 except Exception:
1650 continue
1651 if not cookies:
1652 continue
1653 if cookie_extract.has_complete_pair(cookies, spec["cookies"]):
1654 chosen = cookies
1655 chosen_index = index
1656 break
1657 if fallback is None:
1658 fallback = cookies
1659 if chosen is None:
1660 chosen = fallback or {}
1661 if _service == "x" and denied_browsers and not cookie_extract.has_complete_pair(
1662 chosen, spec["cookies"]
1663 ):
1664 sys.stderr.write(
1665 "[last30days] X browser cookie access permission denied in "
1666 f"{', '.join(denied_browsers)}. {X_COOKIE_ACCESS_FIX}\n"
1667 )
1668 if (
1669 _service == "x"
1670 and chosen_index is not None
1671 and len(missing_cookies) == len(spec["cookies"])
1672 ):
1673 # Remember where the X session came from and which browsers are
1674 # left, so bird can move to the next browser's session if X
1675 # rejects this one (an expired session in an earlier browser
1676 # would otherwise shadow a live one in a later browser).
1677 config[X_SESSION_STATE_KEY] = {
1678 "browser": browsers[chosen_index],
1679 "remaining": list(browsers[chosen_index + 1:]),
1680 "rejected": set(),
1681 "auth_token": chosen.get("auth_token"),
1682 "ct0": chosen.get("ct0"),
1683 }
1684 for cookie_name, env_key in spec["mapping"].items():
1685 if chosen.get(cookie_name) and not config.get(env_key):
1686 extracted[env_key] = chosen[cookie_name]
1687 return extracted
1688
1689
1690 # In-memory X browser-session failover state (never persisted). One mutable
1691 # dict per run: ``pipeline.run`` and its phases work on shallow config copies,
1692 # so keeping the live session here (not in AUTH_TOKEN/CT0) lets every copy see
1693 # a switch made by any other.
1694 X_SESSION_STATE_KEY = "_X_SESSION_STATE"
1695
1696
1697 def x_session_state(config: dict[str, Any]) -> dict[str, Any] | None:
1698 """The run's browser-session failover state, or None when not browser-sourced."""
1699 state = config.get(X_SESSION_STATE_KEY)
1700 if not isinstance(state, dict) or config.get("_AUTH_TOKEN_SOURCE") != "browser":
1701 return None
1702 return state
1703
1704
1705 def next_x_browser_pair(
1706 config: dict[str, Any],
1707 deadline: float | None = None,
1708 cancel: Any = None,
1709 ) -> tuple[str, str, str] | None:
1710 """Extract the next browser's complete X session after a rejection.
1711
1712 Marks the current session rejected, then walks the browsers left after
1713 the one that supplied it, in ``extract_browser_credentials`` order, and
1714 returns ``(auth_token, ct0, browser)`` for the first complete pair whose
1715 session has not been rejected this run. Stops early when ``deadline``
1716 (``time.monotonic()``) is under two seconds away or ``cancel`` is set,
1717 leaving unread browsers for a later search. Lazy on purpose: a later
1718 Chromium browser may cost a Keychain prompt, so it is read only after an
1719 earlier browser's session failed.
1720 """
1721 state = x_session_state(config)
1722 if state is None:
1723 return None
1724 if state.get("auth_token"):
1725 state["rejected"].add(state["auth_token"])
1726 remaining = state["remaining"]
1727 if not remaining:
1728 return None
1729 try:
1730 from . import cookie_extract
1731 except ImportError:
1732 return None
1733 import time as _time
1734 spec = COOKIE_DOMAINS["x"]
1735 while remaining:
1736 if cancel is not None and cancel.is_set():
1737 return None
1738 if deadline is not None and deadline - _time.monotonic() < 2:
1739 return None
1740 browser = remaining.pop(0)
1741 budget = None if deadline is None else deadline - _time.monotonic() - 1
1742 cookies = _bounded_cookie_read(cookie_extract, browser, spec, budget)
1743 if cookies is _READ_TIMED_OUT:
1744 # A Keychain lookup is still waiting; leave the rest for later
1745 # rather than overrunning this search's budget.
1746 return None
1747 if not cookie_extract.has_complete_pair(cookies, spec["cookies"]):
1748 continue
1749 if cookies["auth_token"] in state["rejected"]:
1750 # A session already rejected this run (e.g. a shared profile).
1751 continue
1752 state.update(browser=browser, auth_token=cookies["auth_token"], ct0=cookies["ct0"])
1753 _apply_x_pair(config, cookies["auth_token"], cookies["ct0"], "browser")
1754 return cookies["auth_token"], cookies["ct0"], browser
1755 return None
1756
1757
1758 _READ_TIMED_OUT = object()
1759
1760
1761 def _bounded_cookie_read(cookie_extract: Any, browser: str, spec: dict[str, Any], budget: float | None) -> Any:
1762 """Read one browser's X cookies, waiting at most ``budget`` seconds.
1763
1764 A Chromium read can block on a Keychain lookup (up to its own 10s
1765 timeout). With a budget the read runs on a daemon thread, and an unfinished
1766 read returns ``_READ_TIMED_OUT`` so the caller is never held past its
1767 deadline; the abandoned read finishes or times out on its own.
1768 """
1769 def read() -> Any:
1770 try:
1771 return cookie_extract.extract_cookies(browser, spec["domain"], spec["cookies"])
1772 except Exception:
1773 return None
1774
1775 if budget is None:
1776 return read()
1777 if budget <= 0:
1778 return _READ_TIMED_OUT
1779 import threading
1780 result: list[Any] = []
1781 worker = threading.Thread(target=lambda: result.append(read()), daemon=True)
1782 worker.start()
1783 worker.join(budget)
1784 if worker.is_alive():
1785 return _READ_TIMED_OUT
1786 return result[0] if result else None
1787
1788
1789 def _inject_bird_credentials(config: dict[str, Any]) -> None:
1790 """Hand the X session (and its browser failover) to the bird client.
1791
1792 For a browser-sourced session the shared run state wins over this
1793 config's AUTH_TOKEN/CT0, so a config copy made before a failover never
1794 re-injects the session X already rejected.
1795 """
1796 from . import bird_x
1797 state = x_session_state(config)
1798 if state is not None and state.get("auth_token") and state.get("ct0"):
1799 bird_x.set_credentials(state["auth_token"], state["ct0"])
1800 bird_x.set_session_failover(
1801 state.get("browser"),
1802 lambda deadline=None, cancel=None: next_x_browser_pair(config, deadline, cancel),
1803 )
1804 return
1805 bird_x.set_credentials(config.get('AUTH_TOKEN'), config.get('CT0'))
1806
1807
1808 # Auth-origin label per X backend for ``get_x_source_with_method`` (bird's
1809 # label is the cookie source recorded in ``_AUTH_TOKEN_SOURCE``).
1810 _X_METHOD_LABELS = {
1811 "xai": "xai",
1812 "xurl": "bearer", # xurl CLI (official X API v2, app-only bearer, free developer app)
1813 "xapi": "bearer",
1814 "xquik": "api_key",
1815 }
1816
1817
1818 def get_x_source_with_method(config: dict[str, Any]) -> tuple[str | None, str]:
1819 """Return (source, method) for X search, where method describes the auth origin.
1820
1821 Walks the policy's unpinned auto chain (``x_auto_chain``): on a default
1822 host bird first (cookies beat XAI_API_KEY when both are present), then
1823 xai, xurl, xquik; on an official-only host xapi, xai, xurl. Opt-in
1824 backends (grok, and xapi off Grok Bot) are never auto-selected here.
1825 """
1826 has_bird_creds = bool(config.get("AUTH_TOKEN") and config.get("CT0"))
1827 for backend in x_auto_chain(config):
1828 if backend == "bird":
1829 # Cookie presence only: the scraper install is not consulted
1830 # here (unlike ``x_backend_chain``), so a fresh cookie-bearing
1831 # config reports bird before the binary is checked.
1832 if not has_bird_creds:
1833 continue
1834 elif not _x_backend_available(backend, config, has_bird_creds):
1835 continue
1836 if backend == "bird":
1837 return "bird", config.get("_AUTH_TOKEN_SOURCE", "env")
1838 return backend, _X_METHOD_LABELS.get(backend, "none")
1839 return None, "none"
1840
1841
1842 def config_exists(policy: ConfigLoadPolicy | None = None) -> bool:
1843 """Check if any configuration source exists."""
1844 policy = policy or ConfigLoadPolicy()
1845 file_env = load_env_file(CONFIG_FILE) if CONFIG_FILE and CONFIG_FILE.exists() else {}
1846 if _project_config_trusted(policy, file_env) and _find_project_env():
1847 return True
1848 if CONFIG_FILE:
1849 return CONFIG_FILE.exists()
1850 return False
1851
1852
1853 def get_reddit_source(config: dict[str, Any]) -> str | None:
1854 """Determine which Reddit backend to use.
1855
1856 Returns: 'scrapecreators' or None
1857 """
1858 if config.get('SCRAPECREATORS_API_KEY'):
1859 return 'scrapecreators'
1860 return None
1861
1862
1863 # Default X backend priority. The first available backend is the primary X
1864 # source; the rest are ordered failover backups, tried only if the one before
1865 # returns nothing or errors. There is one X source ("x"); these are its
1866 # interchangeable backends, never run in parallel.
1867 # bird — X GraphQL scrape via the user's browser cookies (AUTH_TOKEN/CT0)
1868 # xai — xAI/Grok live search (XAI_API_KEY)
1869 # xurl — official X API v2 (xurl CLI, OAuth2)
1870 # xquik — key-based REST X search (XQUIK_API_KEY)
1871 _X_BACKEND_ORDER = ("bird", "xai", "xurl", "xquik")
1872
1873 # Opt-in backends: never in the default unpinned auto chain; require an
1874 # explicit pin. grok is here because a leftover ~/.grok/auth.json must never
1875 # steal the X lane. xapi (direct X API v2 with X_BEARER_TOKEN) is here so an
1876 # ambient bearer exported for some other tool never spends X API credits
1877 # every time the cookie scraper comes back empty; on an official-only
1878 # host it is the first rung of the auto chain instead (see _X_OFFICIAL).
1879 _X_BACKEND_OPT_IN = ("grok", "xapi")
1880
1881 # All known backends (auto chain + opt-in): valid values for the pin var.
1882 _X_BACKEND_KNOWN = _X_BACKEND_ORDER + _X_BACKEND_OPT_IN
1883
1884 # Licensed / official backends: the unpinned auto chain on an official-only
1885 # host. xapi = X API v2 with an app-only bearer, xai = xAI's licensed
1886 # X search, xurl = the X API through X's own CLI.
1887 _X_OFFICIAL = ("xapi", "xai", "xurl")
1888
1889 # Host self-identification key and the one value that switches the X
1890 # policy. The engine trusts this key alone: it never infers the host from
1891 # the home directory, PATH, platform, or agent env vars.
1892 X_HOST_VAR = 'LAST30DAYS_HOST'
1893 GROK_BOT_HOST = 'grok-bot'
1894 # Per-session X connector lane signal: process env only.
1895 X_HOST_LANE_VAR = 'LAST30DAYS_X_HOST_LANE'
1896
1897 # Agent-hosted run detection, used only to enforce SKILL.md LAW 7 (the host
1898 # model writes the query plan and passes --plan). This is separate from the
1899 # X policy above, which trusts LAST30DAYS_HOST alone. Here the engine reads
1900 # the markers agent runtimes export into the shells they spawn, because the
1901 # failure it guards against is a host that forgot to plan. Process
1902 # environment only: a .env line never makes a cron run look agent-hosted.
1903 AGENT_HOST_ENV_VARS = (
1904 'CLAUDECODE', # Claude Code
1905 'CLAUDE_CODE_ENTRYPOINT', # Claude Code / Claude Agent SDK
1906 'CODEX_THREAD_ID', # Codex
1907 'CODEX_SESSION_ID',
1908 'CODEX_SANDBOX',
1909 )
1910 # Explicit self-identification for any other agent runtime.
1911 HOST_AGENT_VAR = 'LAST30DAYS_HOST_AGENT'
1912 # Headless/cron escape hatch under an agent: let the engine plan internally.
1913 ALLOW_ENGINE_PLAN_VAR = 'LAST30DAYS_ALLOW_ENGINE_PLAN'
1914
1915
1916 def agent_host_signal(environ: Any = None) -> str:
1917 """Name of the env var that marks this process as agent-hosted, or "".
1918
1919 ``LAST30DAYS_HOST_AGENT`` counts when truthy; the runtime markers in
1920 ``AGENT_HOST_ENV_VARS`` and a host self-identification in
1921 ``LAST30DAYS_HOST`` (e.g. ``grok-bot``) count when non-empty. Returns the
1922 variable name (never its value) so messages can cite what was detected.
1923 """
1924 source = os.environ if environ is None else environ
1925 if _truthy(source.get(HOST_AGENT_VAR)):
1926 return HOST_AGENT_VAR
1927 for name in (*AGENT_HOST_ENV_VARS, X_HOST_VAR):
1928 if str(source.get(name) or '').strip():
1929 return name
1930 return ''
1931
1932
1933 def agent_hosted_run(environ: Any = None) -> bool:
1934 """True when an agent runtime appears to be hosting this engine process."""
1935 return bool(agent_host_signal(environ))
1936
1937
1938 def engine_plan_allowed(environ: Any = None) -> bool:
1939 """True when ``LAST30DAYS_ALLOW_ENGINE_PLAN`` opts back into engine planning."""
1940 source = os.environ if environ is None else environ
1941 return _truthy(source.get(ALLOW_ENGINE_PLAN_VAR))
1942
1943
1944 # A caller whose reader never sees the skill's instruction files (the MCP
1945 # `research` tool) asks for output with no Jobs Digest section.
1946 NO_JOBS_DIGEST_VAR = 'LAST30DAYS_NO_JOBS_DIGEST'
1947
1948
1949 def jobs_digest_disabled(environ: Any = None) -> bool:
1950 """True when ``LAST30DAYS_NO_JOBS_DIGEST`` asks for a run with no jobs digest."""
1951 source = os.environ if environ is None else environ
1952 return _truthy(source.get(NO_JOBS_DIGEST_VAR))
1953
1954
1955 # The same kind of caller asks for a run that does not search a company's
1956 # patent filings at all: the fetch is skipped, not just its section.
1957 NO_PATENT_DIGEST_VAR = 'LAST30DAYS_NO_PATENT_DIGEST'
1958
1959
1960 def patent_digest_disabled(environ: Any = None) -> bool:
1961 """True when ``LAST30DAYS_NO_PATENT_DIGEST`` asks for a run with no patent digest."""
1962 source = os.environ if environ is None else environ
1963 return _truthy(source.get(NO_PATENT_DIGEST_VAR))
1964
1965
1966 # The same kind of caller asks for compact stdout that ends at the canonical
1967 # boundary, with no report-format checklist after it.
1968 NO_REPORT_CHECKLIST_VAR = 'LAST30DAYS_NO_REPORT_CHECKLIST'
1969
1970
1971 def report_checklist_disabled(environ: Any = None) -> bool:
1972 """True when ``LAST30DAYS_NO_REPORT_CHECKLIST`` asks for no checklist."""
1973 source = os.environ if environ is None else environ
1974 return _truthy(source.get(NO_REPORT_CHECKLIST_VAR))
1975
1976
1977 # Set by the MCP wrapper when X_BEARER_TOKEN was explicitly configured in MCP
1978 # host config so xapi activates automatically when unpinned and no higher-
1979 # priority X backend (from env, .env, Keychain, or pass) is available.
1980 # Process environment only so a .env line cannot opt ambient tokens in.
1981 X_API_OPT_IN_VAR = 'LAST30DAYS_X_API_OPT_IN'
1982
1983
1984 def x_api_opt_in(environ: Any = None) -> bool:
1985 """True when ``LAST30DAYS_X_API_OPT_IN`` allows fallback xapi selection."""
1986 source = os.environ if environ is None else environ
1987 return _truthy(source.get(X_API_OPT_IN_VAR))
1988
1989 # Public routing definitions for the doctor/backend-descriptor layer
1990 # (lib/backends.py). These are aliases for knowledge this module already
1991 # owns — the declared X chain order and the pin/floor env var names — so
1992 # descriptors import one source of truth instead of restating it.
1993 X_BACKEND_ORDER = _X_BACKEND_ORDER
1994 X_BACKEND_OPT_IN = _X_BACKEND_OPT_IN
1995 X_BACKEND_KNOWN = _X_BACKEND_KNOWN
1996 X_OFFICIAL = _X_OFFICIAL
1997 X_BACKEND_PIN_VAR = 'LAST30DAYS_X_BACKEND'
1998 REDDIT_BACKEND_PIN_VAR = 'LAST30DAYS_REDDIT_BACKEND'
1999 # `yt-dlp` keeps YouTube off ScrapeCreators while the key still serves other
2000 # sources (#1316). It is the only pin value; anything else means auto.
2001 YOUTUBE_BACKEND_PIN_VAR = 'LAST30DAYS_YOUTUBE_BACKEND'
2002 YOUTUBE_BACKEND_PIN_VALUES = ('yt-dlp',)
2003 REDDIT_SC_MIN_ITEMS_VAR = 'LAST30DAYS_REDDIT_SC_MIN_ITEMS'
2004 # Keyed runs backfill Reddit from ScrapeCreators when the free path returns
2005 # fewer than this many items. Thin topics yield 2-3 free results; healthy
2006 # topics many more, so 5 spends credits only where it adds coverage.
2007 REDDIT_SC_MIN_ITEMS_DEFAULT = 5
2008 YOUTUBE_SC_MIN_ITEMS_VAR = 'LAST30DAYS_YT_SC_MIN_ITEMS'
2009 YOUTUBE_SC_MIN_ITEMS_DEFAULT = 3
2010
2011
2012 def reddit_sc_min_items(config: dict[str, Any]) -> int:
2013 """The Reddit ScrapeCreators backfill floor, parsed one way for every caller.
2014
2015 Unset or blank means ``REDDIT_SC_MIN_ITEMS_DEFAULT``; an explicit ``0``
2016 means backfill only when the free path is empty; a malformed value means
2017 ``0`` so a typo never spends extra credits. Negative values clamp to 0.
2018 """
2019 raw = config.get(REDDIT_SC_MIN_ITEMS_VAR)
2020 if raw is None or (isinstance(raw, str) and not raw.strip()):
2021 return REDDIT_SC_MIN_ITEMS_DEFAULT
2022 try:
2023 return max(int(raw), 0)
2024 except (TypeError, ValueError):
2025 return 0
2026
2027
2028 def youtube_sc_min_items(config: dict[str, Any]) -> int:
2029 """Minimum yt-dlp result count before keyed YouTube search backfill is skipped."""
2030 raw = config.get(YOUTUBE_SC_MIN_ITEMS_VAR)
2031 if raw is None or (isinstance(raw, str) and not raw.strip()):
2032 return YOUTUBE_SC_MIN_ITEMS_DEFAULT
2033 try:
2034 return max(int(raw), 0)
2035 except (TypeError, ValueError):
2036 return 0
2037
2038
2039 @dataclass(frozen=True)
2040 class XPolicy:
2041 """The host-conditional X routing rule, resolved once per config.
2042
2043 ``host`` is the normalized ``LAST30DAYS_HOST`` value; ``official_only``
2044 is true on a Grok Bot host; ``auto_chain`` is the unpinned chain
2045 (``_X_OFFICIAL`` when official-only, else ``_X_BACKEND_ORDER``);
2046 ``cookie_discovery`` is false when official-only unless the pin is
2047 ``bird``; ``hint_namespace`` (``official`` or ``default``) is derived
2048 from ``official_only`` as a plain string so this module never imports
2049 ``prescriptions``.
2050 """
2051
2052 host: str
2053 official_only: bool
2054 auto_chain: tuple[str, ...]
2055 cookie_discovery: bool
2056
2057 @property
2058 def hint_namespace(self) -> str:
2059 return 'official' if self.official_only else 'default'
2060
2061
2062 def x_backend_pin(config: dict[str, Any]) -> str:
2063 """The normalized ``LAST30DAYS_X_BACKEND`` pin value ("" when unset)."""
2064 return (config.get(X_BACKEND_PIN_VAR) or '').strip().lower()
2065
2066
2067 def x_policy(config: dict[str, Any]) -> XPolicy:
2068 """Resolve the X policy from ``LAST30DAYS_HOST``, ``LAST30DAYS_X_API_OPT_IN``, and the pin.
2069
2070 This is the ONLY place the Grok Bot host string is compared. It reads
2071 just the host key, the pin, the process-env ``LAST30DAYS_X_API_OPT_IN``
2072 fallback signal, and the config dict: no platform, PATH, home
2073 directory, or agent env-var inspection (the same rule ``x_extras_enabled``
2074 follows), and nothing imported from ``lib``. The pin keeps its exclusive
2075 semantics on every host and may name any known backend; a ``bird`` pin
2076 is the one path that re-enables cookie discovery on an official-only host.
2077 """
2078 host = str(config.get(X_HOST_VAR) or '').strip().lower()
2079 official_only = host == GROK_BOT_HOST
2080 pin = x_backend_pin(config)
2081 auto_chain = _X_OFFICIAL if official_only else _X_BACKEND_ORDER
2082 if not official_only and x_api_opt_in() and 'xapi' not in auto_chain:
2083 auto_chain = auto_chain + ('xapi',)
2084 return XPolicy(
2085 host=host,
2086 official_only=official_only,
2087 auto_chain=auto_chain,
2088 cookie_discovery=(not official_only) or pin == 'bird',
2089 )
2090
2091
2092 def x_auto_chain(config: dict[str, Any]) -> list[str]:
2093 """The unpinned X auto chain for this host, in failover order."""
2094 return list(x_policy(config).auto_chain)
2095
2096
2097 def x_host_lane_declared(config: dict[str, Any]) -> bool:
2098 """True when the hosting model declared the X connector lane.
2099
2100 ``get_config`` fills ``LAST30DAYS_X_HOST_LANE`` from the process
2101 environment only, so a ``.env`` line never declares the lane.
2102 Deliberately NOT ``x_pending_browser_auth``: that predicate is false in
2103 cookie-read mode by contract, which would leave the envelope path dead at
2104 research time. Host-independent: the envelope is accepted anywhere.
2105 """
2106 return _truthy(config.get(X_HOST_LANE_VAR))
2107
2108
2109 def _x_backend_available(
2110 backend: str,
2111 config: dict[str, Any],
2112 has_bird_creds: bool,
2113 local_only: bool = False,
2114 ) -> bool:
2115 if backend == 'xai':
2116 return bool(config.get('XAI_API_KEY'))
2117 if backend == 'grok':
2118 # Keyless relative to X: needs only an installed, signed-in grok CLI.
2119 # Both surfaces are filesystem-only (PATH lookup + credential store),
2120 # so local_only needs no separate branch.
2121 from . import grok_x
2122 return grok_x.has_stored_auth()
2123 if backend == 'bird':
2124 from . import bird_x
2125 return has_bird_creds and bird_x.is_bird_installed()
2126 if backend == 'xurl':
2127 from . import xurl_x
2128 if local_only:
2129 # Doctor/safe-diagnose path: local evidence only (PATH lookup +
2130 # token store) — never the live `xurl whoami` network call.
2131 return xurl_x.has_stored_auth()
2132 return xurl_x.is_available()
2133 if backend == 'xquik':
2134 return is_xquik_available(config)
2135 if backend == 'xapi':
2136 # Key presence only (no network); local_only needs no branch.
2137 return bool(config.get('X_BEARER_TOKEN'))
2138 return False
2139
2140
2141 def x_backend_chain(config: dict[str, Any], local_only: bool = False) -> list[str]:
2142 """Ordered list of available X backends.
2143
2144 ``chain[0]`` is the default X source; the remaining entries are failover
2145 backups, used only when the one before yields no items or errors. There is
2146 exactly one X source — these are its backends, never fetched in parallel.
2147
2148 A ``LAST30DAYS_X_BACKEND`` pin forces a single backend (no failover): the
2149 user explicitly chose it. Valid pin values are in ``_X_BACKEND_KNOWN``
2150 (the auto chain plus opt-in backends like grok). Browser-cookie probing
2151 is intentionally avoided (automatic Keychain access causes popups); bird
2152 counts as available only when AUTH_TOKEN and CT0 are present explicitly.
2153
2154 Unpinned runs walk only ``_X_BACKEND_ORDER``: opt-in backends like grok
2155 are never auto-selected. A leftover ~/.grok/auth.json must not steal the
2156 X lane; pin ``LAST30DAYS_X_BACKEND=grok`` to enable it explicitly.
2157
2158 ``local_only=True`` is the doctor/safe-diagnose flavor: availability is
2159 answered from local evidence only (no subprocess spawns that reach the
2160 network — xurl's live `whoami` check is replaced by its on-disk token
2161 store). Research-time callers keep the default live semantics.
2162
2163 The unpinned walk is ``x_policy(config).auto_chain``: the default order
2164 above on every host, or ``_X_OFFICIAL`` (xapi -> xai -> xurl) on an
2165 official-only host. The scraper is primed with cookies only when bird
2166 ends up in the resulting chain (never on an official-only host unless
2167 bird is pinned).
2168 """
2169 has_bird_creds = bool(config.get('AUTH_TOKEN') and config.get('CT0'))
2170
2171 preferred = x_backend_pin(config)
2172 # Pin accepted from _X_BACKEND_KNOWN (auto chain + opt-in like grok).
2173 if preferred in _X_BACKEND_KNOWN:
2174 if _x_backend_available(preferred, config, has_bird_creds, local_only):
2175 chain = [preferred]
2176 else:
2177 chain = []
2178 else:
2179 # Unpinned: walk the policy's auto chain. Opt-in backends (grok, and
2180 # xapi off an official-only host) are never auto-selected.
2181 chain = [
2182 b for b in x_policy(config).auto_chain
2183 if _x_backend_available(b, config, has_bird_creds, local_only)
2184 ]
2185 # An xAI lane served by the API-key proxy (lib/proxy.py) is paid per
2186 # call, so every backend the user set up themselves goes first.
2187 if 'xai' in chain and config.get('XAI_API_KEY') == PROXY_SENTINEL:
2188 chain = [b for b in chain if b != 'xai'] + ['xai']
2189
2190 if 'bird' in chain:
2191 _inject_bird_credentials(config)
2192 return chain
2193
2194
2195 def get_x_source(config: dict[str, Any], local_only: bool = False) -> str | None:
2196 """The default (primary) X backend, or None if no X source is available.
2197
2198 Thin wrapper over ``x_backend_chain`` returning the first/primary backend;
2199 callers that want failover should use ``x_backend_chain`` directly.
2200 ``local_only`` is forwarded (see ``x_backend_chain``).
2201 """
2202 chain = x_backend_chain(config, local_only=local_only)
2203 return chain[0] if chain else None
2204
2205
2206 def x_pending_browser_auth(config: dict[str, Any], local_only: bool = False) -> bool:
2207 """True when X is not available now but ``FROM_BROWSER`` will authenticate it at run time.
2208
2209 ``--diagnose`` / ``--preflight`` load config in ``plan_only`` mode, which
2210 deliberately skips browser-cookie extraction (no Keychain popup,
2211 ``reads_values: false``). As a result ``get_x_source`` returns None and X is
2212 dropped from ``available_sources`` even though a normal run would extract the
2213 same cookies and authenticate X fine. This predicate reports that
2214 "available pending browser auth" state without reading a single cookie — it
2215 keys only on the resolved browser list (``cookie_extraction_browsers``
2216 derives it from ``FROM_BROWSER`` alone, no secrets) OR — on extra hosts
2217 only (``x_extras_enabled``) — the agentcookie sidecar having explicit consent
2218 and being on PATH (a plain ``which`` lookup), bird being installed, and X
2219 having a cookie-domain mapping. A plain MacBook must NOT predict bird from
2220 an agentcookie binary on PATH (R18), so the sidecar leg is gated behind
2221 ``x_extras_enabled``.
2222 Side-effect free, so the safe-inspection contract of diagnose/preflight is
2223 preserved.
2224
2225 Returns False whenever X is already available outright (static AUTH_TOKEN/CT0,
2226 or xAI/xurl/xquik backend), and in ``read`` mode (a real run has already
2227 extracted creds, so its status must be unchanged — never "pending").
2228 """
2229 # Already available via a static backend (bird creds, xAI, xurl, xquik).
2230 # local_only (doctor/safe-diagnose) answers the xurl leg from the token
2231 # store instead of the live `xurl whoami` network call.
2232 if get_x_source(config, local_only=local_only):
2233 return False
2234 # An explicit pin to any backend other than bird forbids browser-cookie
2235 # fallback: runtime x_backend_chain() will never select bird.
2236 preferred = x_backend_pin(config)
2237 if preferred in _X_BACKEND_KNOWN and preferred != 'bird':
2238 return False
2239 # Only meaningful in inspection modes that skip extraction; a real ``read``
2240 # run has already attempted extraction and must report its true state.
2241 if config.get('_BROWSER_COOKIE_MODE') in {'read', 'off'}:
2242 return False
2243 # Cookie-only predicate: on an official-only host no run-time cookie
2244 # source exists unless bird is pinned (x_policy), so nothing is pending.
2245 if not x_policy(config).cookie_discovery:
2246 return False
2247 if 'x' not in COOKIE_DOMAINS:
2248 return False
2249 from . import bird_x
2250 if not bird_x.is_bird_installed():
2251 return False
2252 # A FROM_BROWSER browser is a run-time cookie source on any host.
2253 if cookie_extraction_browsers(config):
2254 return True
2255 # The agentcookie sidecar is a run-time cookie source ONLY on extra hosts
2256 # (Linux / Mac mini / Darwin sink / AGENTCOOKIE=on). Gating this keeps a
2257 # plain MacBook from predicting bird off a stray agentcookie binary (R18).
2258 # Admission precedes host classification so a refused sidecar never reads
2259 # its role file or probes the hardware model merely to predict availability.
2260 from . import agentcookie
2261 if agentcookie.is_available(config) and x_extras_enabled(config):
2262 return True
2263 return False
2264
2265
2266 def is_ytdlp_available() -> bool:
2267 """Check if yt-dlp is installed for YouTube search."""
2268 from . import youtube_yt
2269 return youtube_yt.is_ytdlp_installed()
2270
2271
2272 def is_youtube_comments_available(
2273 config: dict[str, Any], *, ytdlp_installed: bool | None = None,
2274 ) -> bool:
2275 """Check if YouTube comment enrichment is available.
2276
2277 yt-dlp fetches YouTube comments free and keyless, so when it is installed
2278 comments need no credential and no ``INCLUDE_SOURCES`` opt-in — the opt-in
2279 only ever existed to gate ScrapeCreators credit spend, and there is none to
2280 gate. ``EXCLUDE_SOURCES=youtube_comments`` remains the off-switch.
2281
2282 Without yt-dlp, the legacy ScrapeCreators path still applies: it requires
2283 SCRAPECREATORS_API_KEY AND ``youtube_comments`` in ``INCLUDE_SOURCES``
2284 (mirroring ``is_tiktok_comments_available``), bounded by
2285 ``enrich_with_comments(max_videos=3)`` at ~3 credits per run.
2286 """
2287 if 'youtube_comments' in _parse_exclude_sources(config):
2288 return False
2289 if ytdlp_installed is None:
2290 ytdlp_installed = is_ytdlp_available()
2291 if ytdlp_installed:
2292 return True
2293 if not is_youtube_sc_available(config):
2294 return False
2295 return 'youtube_comments' in _parse_include_sources(config)
2296
2297
2298 def is_tiktok_public_comments_on(config: dict[str, Any]) -> bool:
2299 """TikTok comments come from the free public endpoint unless switched off."""
2300 raw = config.get('LAST30DAYS_TIKTOK_PUBLIC_COMMENTS') or os.environ.get('LAST30DAYS_TIKTOK_PUBLIC_COMMENTS') or 'on'
2301 return str(raw).strip().lower() not in ('off', '0', 'false', 'no')
2302
2303
2304 def is_tiktok_comments_available(config: dict[str, Any]) -> bool:
2305 """Check if TikTok comment enrichment is available.
2306
2307 Requires SCRAPECREATORS_API_KEY AND tiktok_comments in INCLUDE_SOURCES.
2308 Mirrors the youtube_comments opt-in pattern.
2309 """
2310 if not config.get('SCRAPECREATORS_API_KEY'):
2311 return False
2312 include = _parse_include_sources(config)
2313 return 'tiktok_comments' in include
2314
2315
2316 def is_instagram_comments_available(config: dict[str, Any]) -> bool:
2317 """Check if Instagram comment enrichment is available.
2318
2319 Requires SCRAPECREATORS_API_KEY AND instagram_comments in INCLUDE_SOURCES.
2320 Mirrors the youtube_comments / tiktok_comments opt-in pattern. Comments are
2321 fetched via ScrapeCreators (GET /v2/instagram/post/comments) with each
2322 comment's ``comment_like_count`` used as its vote for ranking. Part of the
2323 default onboarding tier (posts on -> comments on for TikTok/Instagram/YouTube).
2324 """
2325 if not config.get('SCRAPECREATORS_API_KEY'):
2326 return False
2327 return 'instagram_comments' in _parse_include_sources(config)
2328
2329
2330 def youtube_backend_pin(config: dict[str, Any]) -> str:
2331 """The normalized ``LAST30DAYS_YOUTUBE_BACKEND`` pin ("" when unset or unknown)."""
2332 raw = (config.get(YOUTUBE_BACKEND_PIN_VAR) or '').strip().lower()
2333 if raw == 'ytdlp':
2334 raw = 'yt-dlp'
2335 return raw if raw in YOUTUBE_BACKEND_PIN_VALUES else ''
2336
2337
2338 def is_youtube_sc_available(config: dict[str, Any]) -> bool:
2339 """Check if the YouTube lane may spend ScrapeCreators credits.
2340
2341 Gates the SC search fallback, the per-video transcript rescue, and SC
2342 comments. False without a key, or when ``LAST30DAYS_YOUTUBE_BACKEND=yt-dlp``
2343 keeps YouTube keyless while the key still serves other sources.
2344 """
2345 if youtube_backend_pin(config) == 'yt-dlp':
2346 return False
2347 return bool(config.get('SCRAPECREATORS_API_KEY'))
2348
2349
2350 def is_hackernews_available() -> bool:
2351 """Check if Hacker News source is available.
2352
2353 Always returns True - HN uses free Algolia API, no key needed.
2354 """
2355 return True
2356
2357
2358 def is_native_search(config: dict[str, Any]) -> bool:
2359 """Whether the invoking host has its own (better) native web search.
2360
2361 Defined by capability, not host identity: the SKILL.md agent-host path sets
2362 ``LAST30DAYS_NATIVE_SEARCH`` when the runtime actually has a native web-search
2363 tool (e.g. Claude Code's WebSearch). When true, the engine's keyless search
2364 floor is suppressed so a worse free search never preempts the model's own.
2365 Defaults False (unset), so headless/cron and hosts without native search fall
2366 to the keyless floor.
2367 """
2368 raw = config.get('LAST30DAYS_NATIVE_SEARCH')
2369 if raw is None:
2370 return False
2371 return str(raw).strip().lower() in ('1', 'true', 'yes', 'on')
2372
2373
2374 def keyless_web_allowed(config: dict[str, Any]) -> bool:
2375 """Whether the engine may use its keyless web-search floor for this run.
2376
2377 Allowed only when the host does NOT have native search. Independent of
2378 whether a paid key is set (the grounding dispatcher prefers paid first and
2379 falls to keyless on empty/error for non-native runs).
2380 """
2381 return not is_native_search(config)
2382
2383
2384 def transcription_providers(config: dict[str, Any]) -> list[tuple[str, str]]:
2385 """Ordered (name, api_key) Whisper providers for caption-free transcription.
2386
2387 Groq (free tier) first, OpenAI (paid) as the backstop. Empty when neither
2388 key is set, in which case transcription degrades rather than runs.
2389 """
2390 providers: list[tuple[str, str]] = []
2391 if config.get('GROQ_API_KEY'):
2392 providers.append(('groq', config['GROQ_API_KEY']))
2393 if config.get('OPENAI_API_KEY'):
2394 providers.append(('openai', config['OPENAI_API_KEY']))
2395 return providers
2396
2397
2398 def is_bluesky_available(config: dict[str, Any]) -> bool:
2399 """Check if Bluesky source is available.
2400
2401 Requires BSKY_HANDLE and BSKY_APP_PASSWORD (app password from bsky.app/settings).
2402 """
2403 return bool(config.get('BSKY_HANDLE') and config.get('BSKY_APP_PASSWORD'))
2404
2405
2406 def is_truthsocial_available(config: dict[str, Any]) -> bool:
2407 """Check if Truth Social source is available.
2408
2409 Requires TRUTHSOCIAL_TOKEN (bearer token from browser dev tools).
2410 """
2411 return bool(config.get('TRUTHSOCIAL_TOKEN'))
2412
2413
2414 def is_polymarket_available() -> bool:
2415 """Check if Polymarket source is available.
2416
2417 Always returns True - Gamma API is free, no key needed.
2418 """
2419 return True
2420
2421
2422 def shortform_discovery_sources(
2423 config: dict[str, Any] | None = None, kind: str = "tiktok",
2424 ) -> list[str]:
2425 """Discovery sources armed for the keyless TikTok / Instagram lane, in
2426 the order the lane tries them.
2427
2428 Exa only counts for TikTok: its API returns 0 Instagram posts. A host
2429 with native web search (LAST30DAYS_NATIVE_SEARCH) counts as "host search":
2430 it hands the engine post URLs through --shortform-urls, and it is also
2431 why the keyless floor is off there.
2432 """
2433 cfg = config or {}
2434 armed: list[str] = []
2435 if (cfg.get('LAST30DAYS_SEARXNG_URL') or '').strip():
2436 armed.append("SearXNG")
2437 if cfg.get('SERPER_API_KEY'):
2438 armed.append("Serper")
2439 if kind == 'tiktok' and cfg.get('EXA_API_KEY'):
2440 armed.append("Exa")
2441 if cfg.get('BRAVE_API_KEY'):
2442 armed.append("Brave")
2443 if keyless_web_allowed(cfg):
2444 armed.append("keyless floor")
2445 else:
2446 armed.append("host search")
2447 return armed
2448
2449
2450 def is_shortform_oss_available(
2451 config: dict[str, Any] | None = None, kind: str = "tiktok",
2452 ) -> bool:
2453 """yt-dlp extract + a discovery source (see ``shortform_discovery_sources``).
2454
2455 kind is the short-form source ("tiktok" or "instagram"). yt-dlp presence
2456 follows the YouTube source's routing: local binary, or
2457 LAST30DAYS_YOUTUBE_SSH_HOST with yt-dlp on the remote end. Every host has
2458 a discovery source: the keyless floor, or on a native-search host the
2459 host's own search through --shortform-urls.
2460 """
2461 from . import youtube_yt
2462 if not youtube_yt.is_ytdlp_installed():
2463 return False
2464 return bool(shortform_discovery_sources(config, kind))
2465
2466
2467 def is_tiktok_available(config: dict[str, Any]) -> bool:
2468 """Check if TikTok source is available (ScrapeCreators or OSS fallback).
2469
2470 Returns True if SCRAPECREATORS_API_KEY is set, or if yt-dlp plus a
2471 web-discovery backend can serve the keyless fallback. APIFY_API_TOKEN is
2472 not a TikTok search backend (legacy alias only; it was never wired to an
2473 Apify actor).
2474 """
2475 return bool(config.get('SCRAPECREATORS_API_KEY') or is_shortform_oss_available(config))
2476
2477
2478 def get_tiktok_token(config: dict[str, Any]) -> str:
2479 """ScrapeCreators key for TikTok. Empty means the OSS fallback may run."""
2480 return config.get('SCRAPECREATORS_API_KEY') or ''
2481
2482
2483 def _parse_include_sources(config: dict[str, Any]) -> set[str]:
2484 """Parse INCLUDE_SOURCES config value into a set of lowercase source names."""
2485 raw = config.get('INCLUDE_SOURCES') or ''
2486 return {s.strip().lower() for s in raw.split(',') if s.strip()}
2487
2488
2489 _EXCLUDE_SOURCE_ALIASES: dict[str, tuple[str, ...]] = {
2490 'web': ('grounding',),
2491 'grounding': ('web',),
2492 }
2493
2494
2495 def _parse_exclude_sources(config: dict[str, Any]) -> set[str]:
2496 """Parse EXCLUDE_SOURCES config value into a set of lowercase source names."""
2497 raw = config.get('EXCLUDE_SOURCES') or ''
2498 return {s.strip().lower() for s in str(raw).split(',') if s.strip()}
2499
2500
2501 def exclude_sources(config: dict[str, Any]) -> set[str]:
2502 """Public view of EXCLUDE_SOURCES with canonical web/grounding alias parity."""
2503 raw = _parse_exclude_sources(config)
2504 expanded = set(raw)
2505 for token in raw:
2506 expanded.update(_EXCLUDE_SOURCE_ALIASES.get(token, ()))
2507 return expanded
2508
2509
2510 def excluded_source_tokens(source: str, config: dict[str, Any]) -> list[str]:
2511 """Return all configured EXCLUDE_SOURCES tokens matching ``source``."""
2512 raw = _parse_exclude_sources(config)
2513 key = (source or '').strip().lower()
2514 tokens: list[str] = []
2515 if key in raw:
2516 tokens.append(key)
2517 for alias in _EXCLUDE_SOURCE_ALIASES.get(key, ()):
2518 if alias in raw and alias not in tokens:
2519 tokens.append(alias)
2520 return tokens
2521
2522
2523 def excluded_source_token(source: str, config: dict[str, Any]) -> str | None:
2524 """Return the configured EXCLUDE_SOURCES token matching ``source``, or None."""
2525 tokens = excluded_source_tokens(source, config)
2526 return tokens[0] if tokens else None
2527
2528
2529 def include_sources(config: dict[str, Any]) -> set[str]:
2530 """Public view of the parsed INCLUDE_SOURCES set.
2531
2532 Thin wrapper over ``_parse_include_sources`` so other modules (doctor,
2533 etc.) don't reach into env's privates.
2534 """
2535 return _parse_include_sources(config)
2536
2537
2538 def is_setup_complete(config: dict[str, Any]) -> bool:
2539 """Whether guided setup marked this config complete (SETUP_COMPLETE truthy).
2540
2541 Thin wrapper over ``_truthy`` so other modules don't reach into env's
2542 privates.
2543 """
2544 return _truthy(config.get('SETUP_COMPLETE'))
2545
2546
2547 def is_threads_available(config: dict[str, Any]) -> bool:
2548 """Check if the Threads credential is available.
2549
2550 Returns True when SCRAPECREATORS_API_KEY is set. This is an availability
2551 predicate only: whether Threads is actually *scheduled* is gated in the
2552 pipeline's ``available_sources`` by an ``INCLUDE_SOURCES=threads`` opt-in
2553 (the onboarding "Everything" tier), so a key alone no longer runs Threads.
2554 """
2555 return bool(config.get('SCRAPECREATORS_API_KEY'))
2556
2557
2558 def is_instagram_available(config: dict[str, Any]) -> bool:
2559 """Check if Instagram source is available (ScrapeCreators or OSS fallback).
2560
2561 Returns True if SCRAPECREATORS_API_KEY is set, or if yt-dlp plus a
2562 web-discovery backend can serve the keyless fallback.
2563 """
2564 return bool(
2565 config.get('SCRAPECREATORS_API_KEY')
2566 or is_shortform_oss_available(config, "instagram")
2567 )
2568
2569
2570 def get_instagram_token(config: dict[str, Any]) -> str:
2571 """Get Instagram API token (same ScrapeCreators key as TikTok)."""
2572 return config.get('SCRAPECREATORS_API_KEY') or ''
2573
2574
2575 DEFAULT_SCRAPECREATORS_BASE_URL = "https://api.scrapecreators.com"
2576 SCRAPECREATORS_BASE_URL = DEFAULT_SCRAPECREATORS_BASE_URL
2577
2578
2579 def get_scrapecreators_base_url(config: dict[str, Any] | None = None) -> str:
2580 """Get ScrapeCreators API base URL.
2581
2582 Defaults to https://api.scrapecreators.com. Can be overridden via
2583 SCRAPECREATORS_BASE_URL (or SCRAPE_CREATORS_BASE_URL) in environment
2584 or config to point at a local mock server, caching proxy, or
2585 compatible alternative provider.
2586
2587 Remote overrides must be https:// (http:// is allowed only on loopback)
2588 to protect API keys from cleartext transmission. Trailing slashes are stripped.
2589 """
2590 raw = None
2591 if config:
2592 raw = config.get("SCRAPECREATORS_BASE_URL") or config.get("SCRAPE_CREATORS_BASE_URL")
2593 if not raw:
2594 raw = os.environ.get("SCRAPECREATORS_BASE_URL") or os.environ.get("SCRAPE_CREATORS_BASE_URL")
2595 if raw and str(raw).strip():
2596 val = str(raw).strip().rstrip("/")
2597 from . import providers
2598 if providers.allowed_base_url_override(val):
2599 return val
2600 sys.stderr.write(
2601 f"[last30days] WARNING: ignoring SCRAPECREATORS_BASE_URL - a provider endpoint override "
2602 "must be https:// (http:// is allowed only on localhost), otherwise the API "
2603 f"key would be sent in cleartext. Using {DEFAULT_SCRAPECREATORS_BASE_URL} instead.\n"
2604 )
2605 sys.stderr.flush()
2606 return DEFAULT_SCRAPECREATORS_BASE_URL
2607
2608
2609 def get_xiaohongshu_api_base(config: dict[str, Any]) -> str:
2610 """Get Xiaohongshu HTTP API base URL.
2611
2612 The availability probe caches the first logged-in local service it finds so
2613 the later search request uses the same browser-backed session endpoint.
2614 """
2615 cached = config.get(XIAOHONGSHU_RESOLVED_API_BASE_KEY)
2616 if cached:
2617 return str(cached).rstrip("/")
2618
2619 explicit = config.get("XIAOHONGSHU_API_BASE")
2620 if explicit:
2621 return str(explicit).rstrip("/")
2622
2623 return XIAOHONGSHU_DEFAULT_API_BASES[0]
2624
2625
2626 def _xiaohongshu_api_base_candidates(config: dict[str, Any]) -> list[str]:
2627 explicit = config.get("XIAOHONGSHU_API_BASE")
2628 if explicit:
2629 return [str(explicit).rstrip("/")]
2630
2631 candidates: list[str] = []
2632 cached = config.get(XIAOHONGSHU_RESOLVED_API_BASE_KEY)
2633 if cached:
2634 candidates.append(str(cached).rstrip("/"))
2635
2636 for base in XIAOHONGSHU_DEFAULT_API_BASES:
2637 if base not in candidates:
2638 candidates.append(base)
2639 return candidates
2640
2641
2642 def _xiaohongshu_base_logged_in(base: str, http_module: Any) -> bool:
2643 from . import xiaohongshu_api
2644
2645 try:
2646 normalized, req_kwargs = xiaohongshu_api._request_options(base)
2647 except ValueError:
2648 return False
2649
2650 # Keep the health probe snappy, but allow one retry for transient hiccups.
2651 health = http_module.get(f"{normalized}/health", timeout=3, retries=2, **req_kwargs)
2652 if not isinstance(health, dict):
2653 return False
2654 if not health.get("success"):
2655 return False
2656
2657 # Login checks can be slower because some services consult the browser
2658 # profile/session, so use a slightly longer timeout than the health probe.
2659 login = http_module.get(
2660 f"{normalized}/api/v1/login/status", timeout=8, retries=2, **req_kwargs
2661 )
2662 login_data = login.get("data") if isinstance(login, dict) else None
2663 is_logged_in = (
2664 bool(login_data.get("is_logged_in"))
2665 if isinstance(login_data, dict) else False
2666 )
2667 return is_logged_in
2668
2669
2670 def is_xiaohongshu_available(config: dict[str, Any]) -> bool:
2671 """Check whether Xiaohongshu HTTP API is reachable and logged in."""
2672 # Import here to avoid heavy imports at module load.
2673 from . import http, xiaohongshu_api
2674
2675 for base in _xiaohongshu_api_base_candidates(config):
2676 try:
2677 normalized, _ = xiaohongshu_api._validate_base_url(base)
2678 except ValueError:
2679 continue
2680 try:
2681 if _xiaohongshu_base_logged_in(normalized, http):
2682 config[XIAOHONGSHU_RESOLVED_API_BASE_KEY] = normalized
2683 return True
2684 except (OSError, http.HTTPError):
2685 continue
2686 except Exception as exc:
2687 sys.stderr.write(
2688 f"[last30days] WARNING: unexpected error checking Xiaohongshu "
2689 f"at {normalized}: {type(exc).__name__}: {exc}\n"
2690 )
2691 sys.stderr.flush()
2692 return False
2693
2694
2695 # Backward compat alias
2696 is_apify_available = is_tiktok_available
2697
2698
2699 def get_x_source_status(config: dict[str, Any], probe: bool = False) -> dict[str, Any]:
2700 """Get detailed X source status for UI decisions.
2701
2702 Args:
2703 probe: when True, run a cheap 1-tweet bird probe and downgrade
2704 ``bird_authenticated`` to False when X clearly returns nothing,
2705 so ``--diagnose`` reflects runtime reality instead of static
2706 credential presence. A transient timeout leaves the status
2707 unchanged (fail open). When False (the safe/diagnose path that
2708 doctor uses), NO network is touched: xurl availability comes
2709 from local evidence (``xurl_x.has_stored_auth``), never the
2710 live ``xurl whoami`` call.
2711
2712 Returns:
2713 Dict with keys: source, bird_installed, bird_authenticated,
2714 bird_username, xai_available, can_install_bird
2715 """
2716 from . import bird_x
2717
2718 # Backends this host may run: the policy's auto chain plus a known pin.
2719 # Bird is primed/probed and xquik is probed only when they are in that
2720 # set, so an official-only host never touches the scraper or the
2721 # third-party API unless the backend is pinned.
2722 policy = x_policy(config)
2723 pin = x_backend_pin(config)
2724 considered = set(policy.auto_chain)
2725 if pin in _X_BACKEND_KNOWN:
2726 considered.add(pin)
2727
2728 if 'bird' in considered and config.get('AUTH_TOKEN') and config.get('CT0'):
2729 _inject_bird_credentials(config)
2730 bird_status = dict(bird_x.get_bird_status())
2731 if 'bird' not in considered:
2732 # Never report the scraper as usable where the policy forbids it.
2733 bird_status["authenticated"] = False
2734 xai_available = bool(config.get('XAI_API_KEY'))
2735 xapi_available = bool(config.get('X_BEARER_TOKEN'))
2736
2737 # Report the TRUE auth lane (browser / env / keychain) rather than the static
2738 # "env AUTH_TOKEN" label — tokens usually come from live browser cookies, and
2739 # mislabeling the lane sent past debugging down a 30-minute wrong path.
2740 if bird_status["authenticated"]:
2741 lane = config.get('_AUTH_TOKEN_SOURCE') or 'env'
2742 bird_status["username"] = f"{lane} AUTH_TOKEN"
2743
2744 # Optional runtime probe: don't show X green when it's effectively dead.
2745 if probe and bird_status["authenticated"]:
2746 if bird_x.probe_works() is False:
2747 bird_status["authenticated"] = False
2748 bird_status["username"] = "probe failed (no working X auth)"
2749
2750 # Xquik: the key-based X source used when bird's cookie auth isn't available.
2751 # Probe so --diagnose reports the true state — funded, or configured-but-
2752 # unpaid (402) — instead of false-green on mere key presence.
2753 xquik_available = is_xquik_available(config)
2754 xquik_working: bool | None = None
2755 xquik_status = ""
2756 if xquik_available and 'xquik' in considered:
2757 if probe:
2758 from . import xquik
2759 xquik_working = xquik.probe_works(get_xquik_token(config))
2760 xquik_status = xquik.probe_reason()
2761 else:
2762 xquik_status = "configured (not probed)"
2763
2764 # Xurl availability, computed ONCE. probe=True (a live diagnose) may run
2765 # the real `xurl whoami`; probe=False is the safe path (doctor,
2766 # --diagnose, --preflight) and must stay local-only — the live check is
2767 # an authenticated X API network call.
2768 from . import xurl_x as _xurl_x
2769 xurl_available = _xurl_x.is_available() if probe else _xurl_x.has_stored_auth()
2770
2771 # Grok availability is filesystem-only on both paths (PATH lookup plus the
2772 # credential store), so it is safe to compute here regardless of `probe`.
2773 # Grok is opt-in only: it appears in grok_available but never wins the
2774 # unpinned source selection.
2775 from . import grok_x as _grok_x
2776 grok_available = _grok_x.has_stored_auth()
2777
2778 # Determine active source. A pin forces a single backend (R4): ANY known
2779 # pin is exclusive, mirroring x_backend_chain's [] semantics. Pinned
2780 # backend available -> that source. Pinned backend unavailable -> None.
2781 # Otherwise walk the policy's auto chain (default: bird first, cookies
2782 # beat XAI_API_KEY when both are present, then xai, xurl, xquik;
2783 # official-only: xapi, xai, xurl). Opt-in backends are never
2784 # auto-selected; a leftover ~/.grok/auth.json must not steal the X lane.
2785 usable = {
2786 'bird': bird_status["authenticated"],
2787 'xai': xai_available,
2788 'xurl': xurl_available,
2789 'xquik': xquik_available and xquik_working is not False,
2790 'grok': grok_available,
2791 'xapi': xapi_available,
2792 }
2793 if pin in _X_BACKEND_KNOWN:
2794 # Pin is exclusive: pinned backend if available, else None (no fallback).
2795 source = pin if usable.get(pin) else None
2796 else:
2797 source = next((b for b in policy.auto_chain if usable.get(b)), None)
2798
2799 return {
2800 "source": source,
2801 "bird_installed": bird_status["installed"],
2802 "bird_authenticated": bird_status["authenticated"],
2803 "bird_username": bird_status["username"],
2804 "xai_available": xai_available,
2805 "xapi_available": xapi_available,
2806 "grok_available": grok_available,
2807 "xurl_available": xurl_available,
2808 "xquik_available": xquik_available,
2809 "xquik_working": xquik_working,
2810 "xquik_status": xquik_status,
2811 "can_install_bird": bird_status["can_install"],
2812 }
2813
2814
2815 # Pinterest
2816 def is_pinterest_available(config: dict[str, Any]) -> bool:
2817 """Check if Pinterest source is available.
2818
2819 Returns True when SCRAPECREATORS_API_KEY is set AND 'pinterest' is in
2820 INCLUDE_SOURCES (or requested_sources at the pipeline level). Pinterest
2821 is opt-in because not every topic benefits from visual pin results.
2822 """
2823 return bool(config.get('SCRAPECREATORS_API_KEY'))
2824
2825
2826 def get_pinterest_token(config: dict[str, Any]) -> str:
2827 """Get Pinterest API token (same ScrapeCreators key as TikTok/Instagram)."""
2828 return config.get('SCRAPECREATORS_API_KEY') or ''
2829
2830
2831 # Xquik
2832 def is_xquik_available(config: dict[str, Any]) -> bool:
2833 """Check if Xquik X search source is available.
2834
2835 Requires XQUIK_API_KEY (API key from xquik.com).
2836 """
2837 return bool(config.get('XQUIK_API_KEY'))
2838
2839
2840 def get_xquik_token(config: dict[str, Any]) -> str:
2841 """Get Xquik API key."""
2842 return config.get('XQUIK_API_KEY') or ''
2843
2843 lines PYTHON