返回 last30days-skill
backends.py
根目录 / skills / last30days / scripts / lib / backends.py
1 """Backend-chain descriptors with predicted selection (doctor, R4).
2
3 Chained sources declare their routing here ONCE — imported from the
4 definitions ``lib/env.py`` already owns (chain order, pin var names) — and
5 ``resolve()`` turns side-effect-free probes into a truthful prediction of
6 what the next run will do.
7
8 Two resolution modes:
9
10 - ``alternative`` (X, YouTube, web search): the pipeline tries genuinely
11 interchangeable backends in a declared order. Resolution probes ALL
12 candidates first, then picks (collect-then-pick): the first fully-usable
13 backend wins the "will use" prediction; otherwise the best degraded
14 candidate resolves with a warn tier; otherwise the source is an error
15 carrying the highest-priority backend's prescription. Collecting before
16 picking prevents an installed-but-unauthenticated preferred backend from
17 shadowing a fully working fallback.
18
19 - ``conditional`` (Reddit): routing is per-query and outcome-dependent —
20 public keyless composite by default, ScrapeCreators backfill only when
21 results fall below the configured thinness floor (see the gating in
22 ``lib/pipeline.py``). No probe can pick one winner, so resolution renders
23 honest conditional wording instead of an ``active_backend``. Reddit's
24 internal keyless paths (web rungs, arctic, site search, listings) are
25 sub-probe detail inside the public composite, never chain entries; doctor
26 shows them as per-path rows.
27
28 ``active_backend`` semantics: a PREDICTION — "the first backend the probes
29 say the next run will try" — rendered as "will use". It is not an
30 observation of what served a past run, and runtime failover can still
31 diverge mid-run (a present-but-expired paid key passes a presence probe).
32
33 Paid lanes (xai, xapi, xquik, serper, and every other API-key backend,
34 including ScrapeCreators) probe KEY PRESENCE ONLY: a dict lookup, never a
35 network call or credential spend. Binary-backed lanes reuse the U1 dependency
36 probe layer (``health.probe_dependency``) so a stale shim reads as BROKEN,
37 not available (#692).
38
39 This module observes and predicts only. It must never alter which backend
40 the pipeline actually uses; parity with the pipeline's pre-failover
41 selection is asserted in ``tests/test_backend_descriptors.py``. The X chain
42 is shaped by ``env.x_policy``: on an official-only host the findings and
43 the chain carry only the policy's backends (plus a pinned one), so doctor
44 JSON never names a non-official backend there unless it is pinned.
45 """
46
47 from __future__ import annotations
48
49 import os
50 from dataclasses import dataclass
51 from shutil import which
52 from typing import Any, Callable, Dict, List, Optional, Tuple
53
54 from . import env, health, prescriptions, proxy
55
56 # Resolution modes.
57 MODE_ALTERNATIVE = "alternative" # probe-ordered chain, first-usable wins
58 MODE_CONDITIONAL = "conditional" # per-query routing; wording, never a winner
59
60 # Rollup tiers for a resolved chain (doctor maps these into its R1 table).
61 TIER_OK = "ok"
62 TIER_WARN = "warn"
63 TIER_ERROR = "error"
64
65 # Web search backend order. grounding.web_search's auto branch owns the
66 # runtime behavior (brave -> exa -> serper -> parallel -> keyless floor);
67 # parallel-mcp is opt-in only (--web-backend parallel-mcp) and never auto-selected.
68 WEB_BACKEND_ORDER: Tuple[str, ...] = ("brave", "exa", "serper", "parallel", "keyless", "parallel-mcp")
69
70 # YouTube backend order (pipeline: yt-dlp first, ScrapeCreators search
71 # fallback when yt-dlp is absent or fails — see lib/pipeline.py).
72 YOUTUBE_BACKEND_ORDER: Tuple[str, ...] = ("yt-dlp", "scrapecreators")
73
74 # Chain-failure fixes embed the registry's CLI forms (KTD 7): the command a
75 # backend finding prescribes and the one doctor/quality-nudge render for the
76 # same failure mode come from one entry and cannot drift.
77 _SC_PRESCRIPTION = (
78 "set SCRAPECREATORS_API_KEY (free 10,000-call signup: "
79 f"{prescriptions.get('scrapecreators', 'key_missing').fix_cli})"
80 )
81
82
83 def _x_cookies_prescription(config: Dict[str, Any]) -> str:
84 """Bird's unconfigured fix, routed through the X policy.
85
86 Off an official-only host this is the cookie-consent command; on one
87 the same lookup yields the official-path entry (connector lane, bearer,
88 xAI key), so a pinned-but-unconfigured scraper never prescribes a
89 cookie read there.
90 """
91 entry = prescriptions.for_x(config, "cookies_missing")
92 if entry.failure == "cookies_missing":
93 return f"run setup with browser-cookie consent: {entry.fix_cli}"
94 return f"{entry.fix_nl} (cli: {entry.fix_cli})"
95
96
97 @dataclass
98 class BackendFinding:
99 """Side-effect-free probe outcome for one backend of a chained source.
100
101 ``status`` uses the ``lib.health`` vocabulary (OK/DEGRADED/MISSING/
102 BROKEN/TIMEOUT/ERROR). ``prescription`` is the fix when non-OK.
103 ``requires`` is the backend's requirement note for report rendering.
104 """
105
106 name: str
107 status: str
108 detail: str = ""
109 prescription: str = ""
110 requires: str = ""
111
112 @property
113 def usable(self) -> bool:
114 """Fully or partially usable (OK/DEGRADED) — eligible for selection."""
115 return self.status in (health.OK, health.DEGRADED)
116
117
118 @dataclass(frozen=True)
119 class BackendSpec:
120 """One backend in a chain: name, probe, requirement note, paid flag.
121
122 ``probe`` must be side-effect-free. When ``paid`` is True the probe is
123 key-presence only: no subprocess, no network, no credential spend.
124 ``opt_in`` marks backends that are never auto-selected and require an
125 explicit pin (grok).
126 """
127
128 name: str
129 requires: str
130 probe: Callable[[Dict[str, Any]], "BackendFinding"]
131 paid: bool = False
132 opt_in: bool = False
133
134
135 @dataclass(frozen=True)
136 class ChainDescriptor:
137 """A chained source's declared routing: backends, mode, and pin knob."""
138
139 source: str
140 mode: str
141 backends: Tuple[BackendSpec, ...]
142 pin_var: Optional[str] = None # env var pin (X, Reddit, YouTube)
143 pin_flag: Optional[str] = None # CLI flag pin (web: --web-backend)
144 # Env pin values the runtime honors; None means any backend name.
145 pin_values: Optional[Tuple[str, ...]] = None
146
147
148 @dataclass
149 class BackendResolution:
150 """Resolved routing for one chained source.
151
152 ``active_backend`` is the will-use PREDICTION for alternative chains
153 and always None for conditional mode (Reddit never gets a computed
154 winner — ``conditional`` carries the honest wording instead).
155 """
156
157 source: str
158 mode: str
159 chain: List[str]
160 findings: List[BackendFinding]
161 active_backend: Optional[str] = None
162 tier: str = TIER_OK
163 pinned: bool = False
164 pin: Optional[str] = None
165 prescription: str = ""
166 conditional: str = ""
167
168 @property
169 def summary(self) -> str:
170 """One-line rendering: will-use prediction or conditional wording."""
171 if self.mode == MODE_CONDITIONAL:
172 return self.conditional
173 if self.active_backend is None:
174 line = f"no usable backend (chain: {' -> '.join(self.chain)})"
175 if self.prescription:
176 line += f"; fix: {self.prescription}"
177 return line
178 line = f"will use: {self.active_backend}"
179 if self.pinned:
180 line += f" (pinned via {self._pin_origin()})"
181 return line
182
183 def _pin_origin(self) -> str:
184 d = DESCRIPTORS.get(self.source)
185 if d is None:
186 return "pin"
187 return d.pin_var or d.pin_flag or "pin"
188
189
190 # ---------------------------------------------------------------------------
191 # Probes. All side-effect-free; paid lanes are pure dict lookups.
192 # ---------------------------------------------------------------------------
193
194 def _key_probe(name: str, key_var: str, requires: str, note: str = "") -> Callable:
195 """Key-presence probe for a paid API lane. Never touches the network."""
196
197 def probe(config: Dict[str, Any]) -> BackendFinding:
198 if config.get(key_var):
199 return BackendFinding(
200 name=name,
201 status=health.OK,
202 detail="via API key" if proxy.is_sentinel(config.get(key_var)) else f"{key_var} present",
203 requires=requires,
204 )
205 prescription = note or f"set {key_var} in ~/.config/last30days/.env"
206 return BackendFinding(
207 name=name,
208 status=health.MISSING,
209 detail=f"{key_var} not set",
210 prescription=prescription,
211 requires=requires,
212 )
213
214 return probe
215
216
217 def _probe_bird(config: Dict[str, Any]) -> BackendFinding:
218 """Bird = vendored X GraphQL client (node script) + browser-cookie creds.
219
220 Cookie presence is checked FIRST, mirroring ``env._x_backend_available``'s
221 gating (``has_bird_creds and is_bird_installed()``): without cookies bird
222 is unconfigured regardless of node/script state, and the fix is the
223 cookie-consent flow — a broken node runtime must not turn an unconfigured
224 backend into an error carrying a node prescription.
225 """
226 from . import bird_x
227
228 requires = "X browser cookies (AUTH_TOKEN/CT0) + node"
229 if not (config.get("AUTH_TOKEN") and config.get("CT0")):
230 return BackendFinding(
231 name="bird",
232 status=health.MISSING,
233 detail="X browser cookies (AUTH_TOKEN/CT0) not configured",
234 prescription=_x_cookies_prescription(config),
235 requires=requires,
236 )
237 if not bird_x.is_bird_installed():
238 # Distinguish a missing/broken node runtime from a missing script.
239 node = health.probe_dependency("node")
240 if node.status != health.OK:
241 return BackendFinding(
242 name="bird",
243 status=node.status,
244 detail=node.detail,
245 prescription=node.prescription,
246 requires=requires,
247 )
248 return BackendFinding(
249 name="bird",
250 status=health.MISSING,
251 detail="vendored bird-search client not found",
252 prescription="reinstall the skill (npx skills add . -g -y) to restore lib/vendor/bird-search",
253 requires=requires,
254 )
255 node = health.probe_dependency("node")
256 if node.status != health.OK:
257 # Resolvable-but-broken node (stale shim) must not read as usable.
258 return BackendFinding(
259 name="bird",
260 status=node.status,
261 detail=node.detail,
262 prescription=node.prescription,
263 requires=requires,
264 )
265 return BackendFinding(
266 name="bird",
267 status=health.OK,
268 detail="browser-cookie auth (AUTH_TOKEN/CT0) configured",
269 requires=requires,
270 )
271
272
273 def _probe_grok(config: Dict[str, Any]) -> BackendFinding:
274 """grok CLI = keyless X. LOCAL-ONLY probe, like _probe_xurl.
275
276 Deliberately does NOT call ``health.probe_dependency``: that helper runs
277 ``subprocess.run([name, "--version"])``, and the whole-doctor-path test
278 patches ``subprocess.run`` to raise.
279
280 Consequence to be honest about: a grok binary that resolves on PATH but
281 will not execute (the stale-shim class) reports OK here and fails only when
282 a real run shells out. ``grok_x.is_available`` does not close that gap
283 either -- it is also filesystem-only. ``health.probe_dependency("grok")``
284 is the executing probe, and it runs in doctor's CLI-health block rather
285 than on this no-subprocess path.
286 """
287 from . import grok_x
288
289 requires = "grok CLI installed + signed in (no X credential)"
290 if which("grok") is None:
291 off_path = health._off_path_binary("grok")
292 if off_path is not None:
293 return BackendFinding(
294 name="grok",
295 status=health.MISSING,
296 requires=requires,
297 detail=f"grok is installed at {off_path} but that directory is not on this process's PATH",
298 prescription=health.path_edit_prescription(str(off_path.parent), "grok"),
299 )
300 return BackendFinding(
301 name="grok",
302 status=health.MISSING,
303 requires=requires,
304 detail="grok CLI not found on PATH",
305 prescription=(
306 "install the Grok CLI: npm install -g @xai-official/grok (see https://docs.grok.com/ for other install options), "
307 "then run `grok login`"
308 ),
309 )
310 from . import grok_audit
311
312 audit = grok_audit.cached_status(os.path.realpath(which("grok")))
313 if audit and audit["verdict"] == grok_audit.FAIL:
314 return BackendFinding(
315 name="grok",
316 status=health.ERROR,
317 requires=requires,
318 detail=f"{audit['version']} failed the grok tool-boundary audit ({audit['check']})",
319 prescription=(
320 "update the grok CLI or use another X backend; "
321 "running `doctor` again clears this result so the next run re-audits"
322 ),
323 )
324 if audit:
325 audit_note = f"; {audit['version']} passed the tool-boundary audit"
326 else:
327 audit_note = "; this grok build is audited on its first run (local, no credits)"
328 store_status, store_detail, expires_at = grok_x.stored_auth_status()
329 if store_status == grok_x.AUTH_OK:
330 return BackendFinding(
331 name="grok",
332 status=health.OK,
333 requires=requires,
334 detail=f"{store_detail} (not live-verified until a run){audit_note}",
335 )
336 if store_status == grok_x.AUTH_EXPIRED:
337 expiry_str = expires_at.isoformat() if expires_at else "unknown"
338 return BackendFinding(
339 name="grok",
340 status=health.DEGRADED,
341 requires=requires,
342 detail=(
343 f"Grok session expired at {expiry_str}; "
344 "refresh happens at run time (if revoked, run `grok login --device-auth`)"
345 ),
346 prescription="grok login --device-auth",
347 )
348 if store_status == grok_x.AUTH_ERROR:
349 return BackendFinding(
350 name="grok",
351 status=health.ERROR,
352 requires=requires,
353 detail=store_detail,
354 prescription="grok login",
355 )
356 return BackendFinding(
357 name="grok",
358 status=health.MISSING,
359 requires=requires,
360 detail="grok CLI installed but not signed in",
361 prescription="grok login",
362 )
363
364
365 def _probe_xapi(config: Dict[str, Any]) -> BackendFinding:
366 """xapi = direct X API v2 with an app-only bearer. KEY PRESENCE ONLY.
367
368 Never a network call. The unconfigured fix is the official-path
369 prescription on an official-only host (connector lane, bearer, xAI key,
370 with the about-a-week caveat); elsewhere the plain key hint,
371 since xapi runs there only under an explicit pin.
372 """
373 requires = "X_BEARER_TOKEN (X API v2)"
374 if config.get("X_BEARER_TOKEN"):
375 return BackendFinding(
376 name="xapi",
377 status=health.OK,
378 detail="X_BEARER_TOKEN present",
379 requires=requires,
380 )
381 if env.x_policy(config).official_only:
382 entry = prescriptions.get("x", "bearer_missing")
383 prescription = f"{entry.fix_nl} (cli: {entry.fix_cli})"
384 else:
385 prescription = "set X_BEARER_TOKEN in ~/.config/last30days/.env"
386 return BackendFinding(
387 name="xapi",
388 status=health.MISSING,
389 detail="X_BEARER_TOKEN not set",
390 prescription=prescription,
391 requires=requires,
392 )
393
394
395 def _probe_xurl(config: Dict[str, Any]) -> BackendFinding:
396 """xurl = official X API v2 CLI (app-only bearer). Free lane; LOCAL-ONLY probe.
397
398 Doctor's no-network guarantee forbids the live ``xurl whoami`` check
399 (``xurl_x.is_available()`` — reserved for research time). This probe keys
400 on local evidence instead: the binary on PATH plus xurl's on-disk token
401 store (~/.xurl/auth.yml or legacy ~/.xurl). Stored app-only bearer
402 credentials read as OK with an explicit "not live-verified" caveat; a store
403 holding only OAuth user tokens without ``bearer_token`` is reported as
404 MISSING because ``xurl_x.search_x`` pins ``--auth app``; an unreadable
405 token store is a typed ERROR (broken, not unconfigured).
406 """
407 from . import xurl_x
408
409 requires = "xurl CLI installed + app-only bearer auth"
410 if which("xurl") is None:
411 return BackendFinding(
412 name="xurl",
413 status=health.MISSING,
414 detail="xurl CLI not found on PATH",
415 prescription="npm install -g @xdevplatform/xurl && xurl auth app-only <bearer-token>",
416 requires=requires,
417 )
418 store_status, store_detail = xurl_x.stored_auth_status()
419 if store_status == xurl_x.AUTH_OK:
420 return BackendFinding(
421 name="xurl",
422 status=health.OK,
423 detail=(
424 "installed; stored app-only bearer credentials present; "
425 "auth not live-verified (no network)"
426 ),
427 requires=requires,
428 )
429 if store_status == xurl_x.AUTH_ERROR:
430 return BackendFinding(
431 name="xurl",
432 status=health.ERROR,
433 detail=store_detail,
434 prescription="xurl auth app-only <bearer-token>",
435 requires=requires,
436 )
437 if "oauth user tokens only" in str(store_detail).lower():
438 return BackendFinding(
439 name="xurl",
440 status=health.MISSING,
441 detail=(
442 "xurl token store has OAuth user tokens only; "
443 "search requires app-only bearer auth"
444 ),
445 prescription="xurl auth app-only <bearer-token>",
446 requires=requires,
447 )
448 return BackendFinding(
449 name="xurl",
450 status=health.MISSING,
451 detail="xurl installed but not authenticated",
452 prescription="xurl auth app-only <bearer-token>",
453 requires=requires,
454 )
455
456
457 def _probe_ytdlp(config: Dict[str, Any]) -> BackendFinding:
458 """yt-dlp via the U1 dependency-probe layer (missing/broken/timeout)."""
459 dep = health.probe_dependency("yt-dlp")
460 return BackendFinding(
461 name="yt-dlp",
462 status=dep.status,
463 detail=dep.detail,
464 prescription=dep.prescription,
465 requires="yt-dlp on the agent-subprocess PATH",
466 )
467
468
469 def _probe_web_keyless(config: Dict[str, Any]) -> BackendFinding:
470 """The keyless web-search floor: works keyless, but degraded quality."""
471 requires = "no key; suppressed on native-search hosts"
472 if env.keyless_web_allowed(config):
473 return BackendFinding(
474 name="keyless",
475 status=health.DEGRADED,
476 detail="keyless search floor (no paid key; lower quality)",
477 requires=requires,
478 )
479 return BackendFinding(
480 name="keyless",
481 status=health.MISSING,
482 detail="keyless floor suppressed: host has native web search",
483 prescription="",
484 requires=requires,
485 )
486
487
488 def _probe_web_parallel_mcp(config: Dict[str, Any]) -> BackendFinding:
489 """Opt-in Parallel Search MCP: anonymous hosted endpoint, optional bearer auth."""
490 requires = "opt-in only (--web-backend parallel-mcp; PARALLEL_API_KEY optional)"
491 real_key = proxy.real_key(config.get("PARALLEL_API_KEY"))
492 detail = (
493 "hosted Parallel Search MCP (opt-in; PARALLEL_API_KEY present)"
494 if real_key
495 else "hosted Parallel Search MCP (opt-in; anonymous, no key required)"
496 )
497 return BackendFinding(
498 name="parallel-mcp",
499 status=health.OK,
500 detail=detail,
501 requires=requires,
502 )
503
504
505 def _probe_reddit_public(config: Dict[str, Any]) -> BackendFinding:
506 """Reddit's keyless floor: Brave web search finds threads, Arctic Shift
507 ``/posts/ids`` hydrates them.
508
509 Side-effect-free like every probe here: it reads the persisted path health
510 (``reddit_health``) that runs and doctor's live probe write, never the
511 network and never a cookie. The floor is degraded when every web rung, or
512 the archive, is inside a recorded skip.
513 """
514 from . import reddit_health
515
516 requires = "none (keyless web search + Arctic Shift)"
517 detail = "keyless floor (paths: brave, ddg, startpage web search; arctic /posts/ids)"
518 try:
519 skipped = [p for p in (*reddit_health.WEB_RUNGS, "arctic") if reddit_health.skip_until(p)]
520 except Exception:
521 skipped = []
522 if not skipped:
523 return BackendFinding(name="public", status=health.OK, detail=detail, requires=requires)
524 web_down = all(rung in skipped for rung in reddit_health.WEB_RUNGS)
525 status = health.DEGRADED if web_down or "arctic" in skipped else health.OK
526 return BackendFinding(
527 name="public",
528 status=status,
529 detail=f"{detail}; skipped after a refusal: {', '.join(skipped)}",
530 prescription="run doctor to clear the skips and re-probe" if status != health.OK else "",
531 requires=requires,
532 )
533
534
535 # ---------------------------------------------------------------------------
536 # Registry: routing declared once, from env.py's definitions where they exist.
537 # ---------------------------------------------------------------------------
538
539 _X_PROBES: Dict[str, Callable[[Dict[str, Any]], BackendFinding]] = {
540 "xai": _key_probe("xai", "XAI_API_KEY", "XAI_API_KEY (xAI/Grok live search)"),
541 "grok": _probe_grok,
542 "bird": _probe_bird,
543 "xurl": _probe_xurl,
544 "xquik": _key_probe("xquik", "XQUIK_API_KEY", "XQUIK_API_KEY (xquik.com)"),
545 # Direct X API v2 with an app-only bearer: key presence only, no network.
546 "xapi": _probe_xapi,
547 }
548 _X_PAID = {"xai", "xquik", "xapi"}
549 # Opt-in backends: never auto-selected; require explicit pin.
550 _X_OPT_IN = set(env.X_BACKEND_OPT_IN)
551
552 _WEB_PROBES: Dict[str, Callable[[Dict[str, Any]], BackendFinding]] = {
553 "brave": _key_probe("brave", "BRAVE_API_KEY", "BRAVE_API_KEY"),
554 "exa": _key_probe("exa", "EXA_API_KEY", "EXA_API_KEY"),
555 "serper": _key_probe("serper", "SERPER_API_KEY", "SERPER_API_KEY"),
556 "parallel": _key_probe("parallel", "PARALLEL_API_KEY", "PARALLEL_API_KEY"),
557 "keyless": _probe_web_keyless,
558 "parallel-mcp": _probe_web_parallel_mcp,
559 }
560 _WEB_KEYED = {"brave", "exa", "serper", "parallel"}
561 _WEB_OPT_IN = {"parallel-mcp"}
562 _WEB_REQUIRES: Dict[str, str] = {
563 "brave": "BRAVE_API_KEY",
564 "exa": "EXA_API_KEY",
565 "serper": "SERPER_API_KEY",
566 "parallel": "PARALLEL_API_KEY",
567 "keyless": "no key; suppressed on native-search hosts",
568 "parallel-mcp": "opt-in only (--web-backend parallel-mcp; PARALLEL_API_KEY optional)",
569 }
570
571 _SC_SPEC = BackendSpec(
572 name="scrapecreators",
573 requires="SCRAPECREATORS_API_KEY",
574 probe=_key_probe(
575 "scrapecreators", "SCRAPECREATORS_API_KEY", "SCRAPECREATORS_API_KEY",
576 note=_SC_PRESCRIPTION,
577 ),
578 paid=True,
579 )
580
581 # X backend requirements, keyed by name.
582 _X_REQUIRES: Dict[str, str] = {
583 "xai": "XAI_API_KEY (xAI/Grok live search)",
584 "grok": "grok CLI installed + signed in (opt-in only; pin to enable)",
585 "bird": "X browser cookies (AUTH_TOKEN/CT0) + node",
586 "xurl": "xurl CLI installed + app-only bearer auth",
587 "xquik": "XQUIK_API_KEY (xquik.com)",
588 "xapi": "X_BEARER_TOKEN (X API v2)",
589 }
590
591 DESCRIPTORS: Dict[str, ChainDescriptor] = {
592 # X: chain order and pin var imported from env.py (single source of truth).
593 # Backends include the auto chain (X_BACKEND_ORDER) plus opt-in entries
594 # (X_BACKEND_OPT_IN) for doctor visibility. Opt-in backends like grok
595 # appear in findings but are never auto-selected; pin to enable.
596 "x": ChainDescriptor(
597 source="x",
598 mode=MODE_ALTERNATIVE,
599 backends=tuple(
600 BackendSpec(
601 name=name,
602 requires=_X_REQUIRES[name],
603 probe=_X_PROBES[name],
604 paid=name in _X_PAID,
605 opt_in=name in _X_OPT_IN,
606 )
607 for name in env.X_BACKEND_ORDER + env.X_BACKEND_OPT_IN
608 ),
609 pin_var=env.X_BACKEND_PIN_VAR,
610 ),
611 "youtube": ChainDescriptor(
612 source="youtube",
613 mode=MODE_ALTERNATIVE,
614 backends=(
615 BackendSpec(
616 name="yt-dlp",
617 requires="yt-dlp on the agent-subprocess PATH",
618 probe=_probe_ytdlp,
619 ),
620 _SC_SPEC,
621 ),
622 pin_var=env.YOUTUBE_BACKEND_PIN_VAR,
623 pin_values=env.YOUTUBE_BACKEND_PIN_VALUES,
624 ),
625 "web": ChainDescriptor(
626 source="web",
627 mode=MODE_ALTERNATIVE,
628 backends=tuple(
629 BackendSpec(
630 name=name,
631 requires=_WEB_REQUIRES[name],
632 probe=_WEB_PROBES[name],
633 paid=name in _WEB_KEYED,
634 opt_in=name in _WEB_OPT_IN,
635 )
636 for name in WEB_BACKEND_ORDER
637 ),
638 pin_var=None, # pinned per-run via --web-backend, not an env var
639 pin_flag="--web-backend",
640 ),
641 "reddit": ChainDescriptor(
642 source="reddit",
643 mode=MODE_CONDITIONAL,
644 backends=(
645 BackendSpec(
646 name="public",
647 requires="none (keyless web search + Arctic Shift)",
648 probe=_probe_reddit_public,
649 ),
650 _SC_SPEC,
651 ),
652 pin_var=env.REDDIT_BACKEND_PIN_VAR,
653 ),
654 }
655
656
657 def get_descriptor(source: str) -> ChainDescriptor:
658 """Return the declared routing descriptor for ``source`` (KeyError if none)."""
659 return DESCRIPTORS[source]
660
661
662 # ---------------------------------------------------------------------------
663 # Resolution
664 # ---------------------------------------------------------------------------
665
666 def resolve(
667 source: str,
668 config: Dict[str, Any],
669 pin: Optional[str] = None,
670 ) -> BackendResolution:
671 """Resolve a chained source's routing into a truthful prediction.
672
673 ``pin`` is an explicit per-run pin (the ``--web-backend`` flag); it
674 takes precedence over the descriptor's env pin var. ``"auto"``/None
675 mean unpinned. Probing is side-effect-free and collect-then-pick.
676
677 Time budget: backends are probed sequentially, so a chain's budget is
678 ADDITIVE across its backends — each binary-backed probe is bounded by
679 ``health.PROBE_TIMEOUT`` and paid/key lanes are dict lookups that cost
680 nothing, giving a worst case of roughly (binary probes in the chain) x
681 ``health.PROBE_TIMEOUT``. Deliberately no intra-chain concurrency:
682 probes are memoized per process and the worst case only occurs when
683 multiple binaries are simultaneously hung.
684 """
685 descriptor = get_descriptor(source)
686 normalized_pin = pin.strip().lower() if isinstance(pin, str) and pin.strip() else None
687 specs, auto_names = _specs_for_policy(descriptor, config, pin=normalized_pin)
688 findings = [_run_probe(spec, config) for spec in specs]
689 if descriptor.mode == MODE_CONDITIONAL:
690 return _resolve_conditional(descriptor, config, findings, pin=normalized_pin)
691 return _resolve_alternative(descriptor, config, findings, normalized_pin, auto_names)
692
693
694 def _specs_for_policy(
695 descriptor: ChainDescriptor,
696 config: Dict[str, Any],
697 pin: Optional[str] = None,
698 ) -> Tuple[List[BackendSpec], set]:
699 """The backends to probe for this host, and which of them auto-select.
700
701 Every source except X keeps its declared backends; auto-selection is the
702 non-opt-in set. For X the answer comes from ``env.x_policy``: on a
703 default host the declared chain (auto order plus opt-in entries for
704 doctor visibility) is unchanged; on an official-only host the findings
705 are the policy's chain in its order, plus the pinned backend when the
706 pin names something outside it, so neither doctor JSON nor the chain
707 string carries a non-official backend unless it is pinned. Observation
708 only: this mirrors ``env.x_backend_chain``, it never alters it.
709 """
710 specs = list(descriptor.backends)
711 if descriptor.source != "x":
712 return specs, {spec.name for spec in specs if not spec.opt_in}
713 policy = env.x_policy(config)
714 auto_names = set(policy.auto_chain)
715 if not policy.official_only:
716 return specs, auto_names
717 by_name = {spec.name: spec for spec in specs}
718 ordered = [by_name[name] for name in policy.auto_chain if name in by_name]
719 norm_pin = pin.strip().lower() if isinstance(pin, str) and pin.strip() else ""
720 effective_pin = (
721 norm_pin
722 if norm_pin and norm_pin not in ("auto", "none")
723 else env.x_backend_pin(config)
724 )
725 if effective_pin in by_name and effective_pin not in auto_names:
726 ordered.append(by_name[effective_pin])
727 return ordered, auto_names
728
729
730 def _run_probe(spec: BackendSpec, config: Dict[str, Any]) -> BackendFinding:
731 """Run one probe, isolating failures so one bad probe can't blank a chain."""
732 try:
733 finding = spec.probe(config)
734 except Exception as exc: # a probe bug must not take the report down
735 finding = BackendFinding(
736 name=spec.name,
737 status=health.ERROR,
738 detail=f"probe failed: {type(exc).__name__}: {exc}",
739 requires=spec.requires,
740 )
741 if not finding.requires:
742 finding.requires = spec.requires
743 return finding
744
745
746 # Key behind each backend the API-key proxy can serve (lib/proxy.py).
747 _PROXY_KEY_VARS = {
748 "xai": "XAI_API_KEY",
749 "serper": "SERPER_API_KEY",
750 "parallel": "PARALLEL_API_KEY",
751 "scrapecreators": "SCRAPECREATORS_API_KEY",
752 }
753
754
755 def _demote_proxied(
756 source: str, findings: List[BackendFinding], config: Dict[str, Any],
757 ) -> List[BackendFinding]:
758 """Order findings the way the runtime ranks proxy-served backends.
759
760 A backend served by the API-key proxy ranks after every backend the user
761 holds a key for: last in the X chain (env.x_backend_chain), and after the
762 keyed web backends but ahead of the keyless floor
763 (grounding.configured_backend). Without proxy lanes the order is unchanged.
764 """
765 proxied = [
766 f for f in findings
767 if proxy.is_sentinel(config.get(_PROXY_KEY_VARS.get(f.name, "")))
768 ]
769 if not proxied:
770 return findings
771 proxied_ids = {id(f) for f in proxied}
772 rest = [f for f in findings if id(f) not in proxied_ids]
773 if source == "web":
774 cut = next((i for i, f in enumerate(rest) if f.name not in _WEB_KEYED), len(rest))
775 return rest[:cut] + proxied + rest[cut:]
776 return rest + proxied
777
778
779 def _resolve_alternative(
780 descriptor: ChainDescriptor,
781 config: Dict[str, Any],
782 findings: List[BackendFinding],
783 pin: Optional[str],
784 auto_names: Optional[set] = None,
785 ) -> BackendResolution:
786 names = [f.name for f in findings]
787 by_name = {f.name: f for f in findings}
788 if auto_names is None:
789 auto_names = {spec.name for spec in descriptor.backends if not spec.opt_in}
790 # Backends outside the auto set are opt-in here (never auto-selected).
791 opt_in_names = {name for name in names if name not in auto_names}
792 res = BackendResolution(
793 source=descriptor.source,
794 mode=MODE_ALTERNATIVE,
795 chain=list(names),
796 findings=findings,
797 )
798
799 pin_name: Optional[str] = None
800 norm_pin = pin.strip().lower() if isinstance(pin, str) else ""
801 if norm_pin and norm_pin not in ("auto", "none") and norm_pin in by_name:
802 pin_name = norm_pin
803 elif descriptor.pin_var:
804 if descriptor.pin_var == env.YOUTUBE_BACKEND_PIN_VAR:
805 # Same spelling rules as the runtime gate (strip, "ytdlp" alias).
806 raw = env.youtube_backend_pin(config)
807 elif descriptor.pin_var == env.X_BACKEND_PIN_VAR:
808 raw = env.x_backend_pin(config)
809 else:
810 raw = (config.get(descriptor.pin_var) or "").strip().lower()
811 if raw in by_name and (
812 descriptor.pin_values is None or raw in descriptor.pin_values
813 ):
814 pin_name = raw
815
816 if pin_name:
817 # A pin forces a single backend (no failover) — mirror
818 # env.x_backend_chain's pin semantics exactly.
819 res.pinned = True
820 res.pin = pin_name
821 finding = by_name[pin_name]
822 if finding.status == health.OK:
823 res.active_backend = pin_name
824 res.tier = TIER_OK
825 elif finding.status == health.DEGRADED:
826 res.active_backend = pin_name
827 res.tier = TIER_WARN
828 else:
829 res.tier = TIER_ERROR
830 res.prescription = finding.prescription or (
831 f"unpin {descriptor.pin_var or descriptor.pin_flag} or fix {pin_name}"
832 )
833 return res
834
835 # Collect-then-pick: first fully-usable wins; else best degraded; else
836 # error carrying the highest-priority backend's prescription.
837 # Opt-in backends are NEVER auto-selected; skip them entirely.
838 auto_findings = _demote_proxied(
839 descriptor.source, [f for f in findings if f.name not in opt_in_names], config,
840 )
841 res.chain = [f.name for f in _demote_proxied(descriptor.source, findings, config)]
842 for finding in auto_findings:
843 if finding.status == health.OK:
844 res.active_backend = finding.name
845 res.tier = TIER_OK
846 return res
847 for finding in auto_findings:
848 if finding.status == health.DEGRADED:
849 res.active_backend = finding.name
850 res.tier = TIER_WARN
851 return res
852 res.tier = TIER_ERROR
853 # Prescription comes from the first auto-chain backend, not opt-in.
854 res.prescription = auto_findings[0].prescription if auto_findings else ""
855 return res
856
857
858 def _resolve_conditional(
859 descriptor: ChainDescriptor,
860 config: Dict[str, Any],
861 findings: List[BackendFinding],
862 pin: Optional[str] = None,
863 ) -> BackendResolution:
864 """Reddit: render the real per-query semantics, never a computed winner."""
865 res = BackendResolution(
866 source=descriptor.source,
867 mode=MODE_CONDITIONAL,
868 chain=[spec.name for spec in descriptor.backends],
869 findings=findings,
870 active_backend=None, # conditional mode never picks a winner
871 tier=TIER_OK, # the public keyless composite is always reachable
872 )
873 has_key = bool(config.get("SCRAPECREATORS_API_KEY"))
874 norm_pin = pin.strip().lower() if isinstance(pin, str) else ""
875 if norm_pin and norm_pin not in ("auto", "none"):
876 raw_pin = norm_pin
877 else:
878 raw_pin = (config.get(descriptor.pin_var) or "").strip().lower() if descriptor.pin_var else ""
879 pinned_sc = has_key and raw_pin == "scrapecreators"
880 floor = env.reddit_sc_min_items(config)
881
882 if pinned_sc:
883 res.pinned = True
884 res.pin = "scrapecreators"
885 res.conditional = (
886 f"ScrapeCreators primary (pinned via {descriptor.pin_var}); "
887 "public keyless composite fallback"
888 )
889 return res
890
891 if has_key:
892 if floor > 0:
893 backfill = (
894 f"ScrapeCreators backfill when results fall below the "
895 f"{floor}-item floor"
896 )
897 else:
898 backfill = "ScrapeCreators backfill when the free path returns nothing"
899 res.conditional = f"public keyless composite (default); {backfill}"
900 return res
901
902 res.conditional = "public keyless composite (default); no ScrapeCreators key for backfill"
903 if raw_pin == "scrapecreators":
904 # The pipeline ignores the pin without a key; say so honestly.
905 res.conditional += (
906 f" ({descriptor.pin_var} pin ignored: SCRAPECREATORS_API_KEY not set)"
907 )
908 return res
909
909 lines PYTHON