papersearch 0.4.8 → 0.4.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.en.md +50 -62
  2. package/README.md +50 -62
  3. package/assets/overview.en.png +0 -0
  4. package/assets/overview.png +0 -0
  5. package/assets/progress-capsule.en.png +0 -0
  6. package/assets/progress-capsule.png +0 -0
  7. package/carsi/README.md +5 -6
  8. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
  9. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
  10. package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
  11. package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
  12. package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
  13. package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
  14. package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
  15. package/carsi/paper_search_carsi/assets/capsule.html +199 -24
  16. package/carsi/paper_search_carsi/browser/backend.py +270 -227
  17. package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
  18. package/carsi/paper_search_carsi/browser/challenge_interaction.py +79 -43
  19. package/carsi/paper_search_carsi/browser/cookies.py +8 -8
  20. package/carsi/paper_search_carsi/browser/driver.py +29 -0
  21. package/carsi/paper_search_carsi/browser/engine.py +17 -23
  22. package/carsi/paper_search_carsi/browser/foreground.py +21 -15
  23. package/carsi/paper_search_carsi/browser/login.py +12 -18
  24. package/carsi/paper_search_carsi/browser/preview.py +31 -12
  25. package/carsi/paper_search_carsi/browser/profiles.py +16 -23
  26. package/carsi/paper_search_carsi/browser/watchdog.py +61 -55
  27. package/carsi/paper_search_carsi/capsule_placement.py +266 -0
  28. package/carsi/paper_search_carsi/cli.py +22 -7
  29. package/carsi/paper_search_carsi/cold_start.py +65 -51
  30. package/carsi/paper_search_carsi/config.py +6 -4
  31. package/carsi/paper_search_carsi/engine/batch.py +9 -5
  32. package/carsi/paper_search_carsi/engine/batch_access.py +2 -4
  33. package/carsi/paper_search_carsi/engine/batch_capture.py +56 -20
  34. package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
  35. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +4 -2
  36. package/carsi/paper_search_carsi/engine/batch_institution.py +146 -17
  37. package/carsi/paper_search_carsi/engine/batch_login.py +79 -26
  38. package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
  39. package/carsi/paper_search_carsi/engine/batch_waits.py +92 -37
  40. package/carsi/paper_search_carsi/engine/bridge.py +23 -13
  41. package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
  42. package/carsi/paper_search_carsi/engine/page_activity.py +15 -15
  43. package/carsi/paper_search_carsi/mcp_progress.py +13 -5
  44. package/carsi/paper_search_carsi/network.py +1 -1
  45. package/carsi/paper_search_carsi/progress_capsule.py +233 -93
  46. package/carsi/paper_search_carsi/progress_reporter.py +88 -7
  47. package/carsi/paper_search_carsi/progress_view.py +61 -0
  48. package/carsi/paper_search_carsi/server.py +47 -10
  49. package/carsi/paper_search_carsi/session_broker.py +1 -1
  50. package/carsi/paper_search_carsi/user_settings.py +1 -1
  51. package/carsi/pyproject.toml +7 -7
  52. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
  53. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
  54. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  55. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  56. package/dist/capabilities/pdf-discovery/batch.js +15 -5
  57. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  58. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +22 -0
  59. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
  60. package/dist/capabilities/pdf-discovery/batchSummary.js +131 -0
  61. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
  62. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
  63. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  64. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +52 -1
  65. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  66. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +8 -4
  67. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  68. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +89 -30
  69. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  70. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +4 -0
  71. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  72. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +10 -0
  73. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  74. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
  75. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  76. package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
  77. package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
  78. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +36 -0
  79. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  80. package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
  81. package/dist/capabilities/pdf-discovery/handler.js +11 -6
  82. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  83. package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
  84. package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
  85. package/dist/cli.js +13 -9
  86. package/dist/cli.js.map +1 -1
  87. package/dist/management/carsi/installer.d.ts +26 -14
  88. package/dist/management/carsi/installer.d.ts.map +1 -1
  89. package/dist/management/carsi/installer.js +113 -69
  90. package/dist/management/carsi/installer.js.map +1 -1
  91. package/dist/management/carsi/runtime.d.ts +12 -1
  92. package/dist/management/carsi/runtime.d.ts.map +1 -1
  93. package/dist/management/carsi/runtime.js +30 -1
  94. package/dist/management/carsi/runtime.js.map +1 -1
  95. package/package.json +1 -1
  96. package/skills/paper-search/SKILL.md +4 -4
  97. package/skills/paper-search/references/browser-download.md +3 -3
  98. package/skills/paper-search/references/carsi-setup.md +7 -6
  99. package/skills/paper-search/references/cli-contract.md +4 -4
  100. package/skills/paper-search/references/management-layer.md +2 -2
  101. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
  102. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
  103. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
  104. package/carsi/paper_search_carsi/browser/background.py +0 -68
@@ -1,15 +1,14 @@
1
- """Browser backends: Camoufox (default) or ego-lite.
1
+ """Browser backends: Chrome (default) or ego-lite, both driven by Patchright.
2
2
 
3
- Exactly two backends are supported, selected by the ``browser_backend``
4
- config key:
3
+ Two backends are supported, selected by the ``browser_backend`` config key:
5
4
 
6
- * ``camoufox`` (default) — an open-source anti-detect Firefox build driven
7
- through the standard Playwright sync API (``launch*`` return ordinary
8
- Playwright objects). Every Playwright-based route in this package runs on
9
- it. It is Firefox, so Chromium-only features (CDP sessions, Chromium launch
10
- flags) are skipped by their callers.
5
+ * ``chrome`` (default) — the user's installed, self-updating Google Chrome,
6
+ launched with a profile of its own by Patchright
7
+ (Playwright with Chromium's automation traces removed). Only Chrome's public
8
+ switches: automated clicks do not activate its window, and the default
9
+ switches keep a covered window rendering, so it needs no helper.
11
10
  * ``ego`` — the user's own, already running ego-lite browser (a Chromium
12
- fork), reached over the Chrome DevTools Protocol with Playwright's
11
+ fork), reached over the Chrome DevTools Protocol with Patchright's
13
12
  ``connect_over_cdp``. The user turns this on once (ego keeps it in Local
14
13
  State, devtools.remote_debugging.user-enabled) at
15
14
  ``chrome://inspect/#remote-debugging`` ("Allow remote debugging for this
@@ -18,8 +17,9 @@ config key:
18
17
  The package only ever sees and closes the tabs it opened (and their popups),
19
18
  never closes the browser, and does not save or restore cookies there.
20
19
 
21
- The former ``patchright`` and ``cloakbrowser`` values are accepted for old
22
- configs, logged, and mapped to ``camoufox``.
20
+ The retired values ``camoufox``, ``patchright`` and ``cloakbrowser`` are
21
+ accepted for old configs, logged once, and mapped to ``chrome``; the config
22
+ file is left as it is.
23
23
  """
24
24
 
25
25
  from __future__ import annotations
@@ -27,6 +27,7 @@ from __future__ import annotations
27
27
  import json
28
28
  import logging
29
29
  import os
30
+ import re
30
31
  import shutil
31
32
  import sys
32
33
  import time
@@ -50,22 +51,22 @@ from .profiles import (
50
51
 
51
52
  logger = logging.getLogger(__name__)
52
53
 
53
- BACKEND_CAMOUFOX = "camoufox"
54
+ BACKEND_CHROME = "chrome"
54
55
  BACKEND_EGO = "ego"
55
- # The Camoufox browser build this release is tested with: the stable build
56
- # paired with the pinned camoufox package (pyproject.toml; stable releases only,
57
- # ADR 0013). It is launched by path, so another program changing the shared
58
- # cache's active version does not change ours.
59
- CAMOUFOX_BROWSER = "156.0.1-beta.36"
60
56
  # The browser and version the last launch in this process used (browser_info).
61
57
  _launched: dict[str, str] = {}
62
- DEFAULT_BACKEND = BACKEND_CAMOUFOX
63
- SUPPORTED_BACKENDS = (BACKEND_CAMOUFOX, BACKEND_EGO)
64
- _RETIRED_BACKENDS = ("patchright", "cloakbrowser")
58
+ DEFAULT_BACKEND = BACKEND_CHROME
59
+ SUPPORTED_BACKENDS = (BACKEND_CHROME, BACKEND_EGO)
60
+ _RETIRED_BACKENDS = ("camoufox", "patchright", "cloakbrowser")
61
+ _retired_noted: set[str] = set()
65
62
 
66
- # A Firefox profile cannot share a directory with the Chromium profiles that
67
- # earlier backends left behind, so Camoufox keeps its own sibling directory.
68
- CAMOUFOX_PROFILE_SUFFIX = "-camoufox"
63
+ # Chrome keeps its own profile, never the profile of the user's everyday Chrome.
64
+ CHROME_PROFILE_SUFFIX = "-chrome"
65
+ CHROME_DOWNLOAD_URL = "https://www.google.com/chrome/"
66
+ CHROME_MISSING = (f"Google Chrome was not found: install it from {CHROME_DOWNLOAD_URL} "
67
+ "(or set chrome_executable to the path of a Chrome installed elsewhere)")
68
+ # The Chrome version this release was tested with (acceptance); older ones are reported.
69
+ TESTED_CHROME = "156.0.8078.80"
69
70
 
70
71
 
71
72
  class EgoUnavailable(RuntimeError):
@@ -159,36 +160,121 @@ def ego_endpoint(config: dict[str, Any] | None = None) -> str | None:
159
160
  return f"ws://127.0.0.1:{lines[0]}{lines[1]}"
160
161
 
161
162
 
162
- def is_available(name: str | None = None) -> bool:
163
+ def find_chrome(config: dict[str, Any] | None = None) -> Path | None:
164
+ """The installed Google Chrome for the ``chrome`` backend.
165
+
166
+ Config ``chrome_executable`` (the path of a Chrome installed elsewhere)
167
+ overrides. Chrome is the user's stable, self-updating browser; the backend
168
+ runs it with a profile of its own.
169
+ """
170
+ configured = str((config or {}).get("chrome_executable") or "").strip()
171
+ if configured:
172
+ path = Path(configured).expanduser()
173
+ return path if path.exists() else None
174
+ if sys.platform == "darwin":
175
+ candidates = [Path(base) / "Google Chrome.app" / "Contents" / "MacOS" / "Google Chrome"
176
+ for base in ("/Applications", str(Path.home() / "Applications"))]
177
+ elif os.name == "nt":
178
+ roots = [os.environ.get(key, "") for key in ("PROGRAMFILES", "PROGRAMFILES(X86)", "LOCALAPPDATA")]
179
+ candidates = [Path(root) / "Google" / "Chrome" / "Application" / "chrome.exe" for root in roots if root]
180
+ else:
181
+ candidates = [Path(found) for found in (shutil.which(name) for name in
182
+ ("google-chrome", "google-chrome-stable")) if found]
183
+ return next((c for c in candidates if c.exists()), None)
184
+
185
+
186
+ def _version_key(version: str) -> tuple[int, ...]:
187
+ return tuple(int(part) for part in re.findall(r"\d+", version)[:4])
188
+
189
+
190
+ def chrome_version(executable: str | Path | None) -> str:
191
+ """The installed Chrome's version, read without starting it ("" when unknown).
192
+
193
+ macOS: the app bundle's Info.plist. Windows: the version folder next to the
194
+ program (``Application/156.0.8078.80``; the newest after an update). Linux:
195
+ ``--version``.
196
+ """
197
+ if executable is None:
198
+ return ""
199
+ path = Path(executable)
200
+ if sys.platform == "darwin":
201
+ import plistlib
202
+
203
+ bundle = next((p for p in path.parents if p.suffix == ".app"), None)
204
+ try:
205
+ with open((bundle or path) / "Contents" / "Info.plist", "rb") as handle:
206
+ return str(plistlib.load(handle).get("CFBundleShortVersionString") or "")
207
+ except (OSError, plistlib.InvalidFileException):
208
+ return ""
209
+ if sys.platform == "win32":
210
+ try:
211
+ folders = [p.name for p in path.parent.iterdir() if p.is_dir() and re.fullmatch(r"\d+(?:\.\d+){3}", p.name)]
212
+ except OSError:
213
+ return ""
214
+ return max(folders, key=_version_key, default="")
215
+ import subprocess
216
+
217
+ try:
218
+ answer = subprocess.run([str(path), "--version"], capture_output=True, text=True, timeout=10).stdout
219
+ except (OSError, subprocess.SubprocessError):
220
+ return ""
221
+ found = re.search(r"\d+(?:\.\d+){1,3}", answer or "")
222
+ return found.group(0) if found else ""
223
+
224
+
225
+ def patchright_version() -> str:
226
+ """The installed Patchright, which drives both backends; "" when missing."""
227
+ try:
228
+ from importlib.metadata import version
229
+
230
+ return version("patchright")
231
+ except Exception:
232
+ return ""
233
+
234
+
235
+ def browser_check(config: dict[str, Any] | None = None) -> dict[str, Any]:
236
+ """The Chrome the chrome backend would run, for health checks: where, its
237
+ version against the version this release was tested with, and the driver.
238
+ ``outdated``: older than the tested version."""
239
+ found = find_chrome(config)
240
+ driver = patchright_version()
241
+ report: dict[str, Any] = {"browser": "", "path": "", "version": "", "tested": TESTED_CHROME,
242
+ "outdated": False, "driver": f"patchright {driver}" if driver else ""}
243
+ if found is None:
244
+ return report
245
+ version = chrome_version(found)
246
+ report.update(browser="Google Chrome", path=str(found), version=version,
247
+ outdated=bool(version) and _version_key(version) < _version_key(TESTED_CHROME))
248
+ return report
249
+
250
+
251
+ def is_available(name: str | None = None, config: dict[str, Any] | None = None) -> bool:
163
252
  """Whether a backend is installed. None → the default backend."""
164
253
  name = name or DEFAULT_BACKEND
165
- if name == BACKEND_CAMOUFOX:
166
- try:
167
- import camoufox # noqa: F401
168
- except ImportError:
169
- return False
170
- return True
171
254
  if name == BACKEND_EGO:
172
- return ego_user_data_dir().exists()
255
+ return ego_user_data_dir(config).exists() and bool(patchright_version())
256
+ if name == BACKEND_CHROME:
257
+ return find_chrome(config) is not None and bool(patchright_version())
173
258
  return False
174
259
 
175
260
 
176
261
  def resolve_backend(config: dict[str, Any] | None = None) -> str:
177
262
  """Effective backend from config.
178
263
 
179
- Retired values (patchright, cloakbrowser) and unknown values map to
180
- camoufox with a warning. ``ego`` without an ego-lite installation falls
181
- back to camoufox with a warning; an installed ego whose remote debugging
182
- is off stays selected and the launch explains how to turn it on. A
183
- missing camoufox is not swapped for anything.
264
+ Retired values (camoufox, patchright, cloakbrowser) map to chrome, logged
265
+ once per process; unknown values map to chrome with a warning. ``ego``
266
+ without an ego-lite installation falls back to chrome with a warning; an
267
+ installed ego whose remote debugging is off stays selected and the launch
268
+ explains how to turn it on. A missing Chrome is not swapped for anything:
269
+ the launch says how to install it.
184
270
  """
185
271
  cfg = config or {}
186
272
  requested = str(cfg.get("browser_backend", DEFAULT_BACKEND) or DEFAULT_BACKEND).strip().lower()
187
273
  if requested in _RETIRED_BACKENDS:
188
- logger.warning(
189
- "browser_backend: '%s' is no longer supported, using %s (set browser_backend to "
190
- "'camoufox' or 'ego')", requested, DEFAULT_BACKEND,
191
- )
274
+ if requested not in _retired_noted:
275
+ _retired_noted.add(requested)
276
+ logger.warning("browser_backend: '%s' is retired, using %s (set browser_backend to 'chrome' or 'ego')",
277
+ requested, DEFAULT_BACKEND)
192
278
  return DEFAULT_BACKEND
193
279
  if requested not in SUPPORTED_BACKENDS:
194
280
  logger.warning("browser_backend: unknown backend '%s', using %s", requested, DEFAULT_BACKEND)
@@ -198,9 +284,26 @@ def resolve_backend(config: dict[str, Any] | None = None) -> str:
198
284
  return DEFAULT_BACKEND
199
285
  return requested
200
286
 
287
+ # What a backend offers beyond plain Playwright. Callers ask for a capability,
288
+ # never for a backend's name, so a new backend only declares its own entry.
289
+ # batch_window: a serial batch keeps one browser window and tab from paper
290
+ # to paper (browser/batch_session.py); without it every paper opens and
291
+ # closes its own browser, as before.
292
+ BACKEND_CAPABILITIES: dict[str, frozenset[str]] = {
293
+ BACKEND_CHROME: frozenset({"batch_window"}),
294
+ # The user's own running browser: one tab per paper until a batch there
295
+ # has been tried.
296
+ BACKEND_EGO: frozenset(),
297
+ }
298
+
299
+
300
+ def supports(capability: str, config: dict[str, Any] | None = None) -> bool:
301
+ """Whether the effective backend declares ``capability``."""
302
+ return capability in BACKEND_CAPABILITIES.get(resolve_backend(config), frozenset())
303
+
201
304
 
202
305
  def uses_playwright(config: dict[str, Any] | None = None) -> bool:
203
- """Both backends are driven through the Playwright API."""
306
+ """Every backend is driven through the Playwright API (Patchright's)."""
204
307
  return resolve_backend(config) in SUPPORTED_BACKENDS
205
308
 
206
309
 
@@ -213,8 +316,8 @@ _EGO_HINT = ("在 ego 中打开 chrome://inspect/#remote-debugging,勾选 "
213
316
 
214
317
 
215
318
  def _connect_ego(config: dict[str, Any] | None) -> tuple[Any, Any]:
216
- """(playwright, browser) connected to the running ego-lite."""
217
- from playwright.sync_api import sync_playwright
319
+ """(driver, browser) connected to the running ego-lite."""
320
+ from patchright.sync_api import sync_playwright
218
321
 
219
322
  if not ego_running(config) and not _start_ego(config):
220
323
  raise EgoUnavailable(f"ego-lite is not running and could not be started with remote "
@@ -387,7 +490,7 @@ def _launch_ego_persistent(config: dict[str, Any] | None) -> Any:
387
490
  except Exception:
388
491
  pass
389
492
  try:
390
- # Playwright took over downloads for this context; give them back.
493
+ # The driver took over downloads for this context; give them back.
391
494
  browser.new_browser_cdp_session().send("Browser.setDownloadBehavior", {"behavior": "default"})
392
495
  except Exception as exc:
393
496
  logger.info("browser_backend: ego download behaviour not reset (%s)", type(exc).__name__)
@@ -423,110 +526,20 @@ def _launch_ego(config: dict[str, Any] | None) -> Any:
423
526
 
424
527
 
425
528
  # ---------------------------------------------------------------------------
426
- # Camoufox launchers
529
+ # Chrome launchers
427
530
  # ---------------------------------------------------------------------------
428
531
 
429
- def _host_os() -> str:
430
- """Camoufox fingerprint OS matching the real machine (fonts, UA, platform agree)."""
431
- if sys.platform == "darwin":
432
- return "macos"
433
- if os.name == "nt":
434
- return "windows"
435
- return "linux"
436
-
437
-
438
532
  def _proxy_from_config(config: dict[str, Any] | None) -> Any:
439
- """Playwright proxy dict from config, or None.
440
-
441
- Firefox ignores Chromium's --proxy-server launch arg, so the configured
442
- egress (browser_static_proxy, else network_proxy) is passed explicitly.
443
- """
533
+ """The driver's proxy dict from config, or None: the configured egress
534
+ (browser_static_proxy, else network_proxy)."""
444
535
  cfg = config or {}
445
536
  proxy = (str(cfg.get("browser_static_proxy", "") or "").strip()
446
537
  or str(cfg.get("network_proxy", "") or "").strip())
447
538
  return {"server": proxy} if proxy else None
448
539
 
449
540
 
450
- def _camoufox_options(headless: bool, proxy: Any, args: list[str] | None, humanize: bool,
451
- kwargs: dict[str, Any]) -> dict[str, Any]:
452
- if args:
453
- # Callers pass Chromium flags; handed to Firefox they would be read as
454
- # URLs to open. Camoufox configures its own anti-fingerprinting.
455
- logger.debug("browser_backend: camoufox ignores %d Chromium arg(s)", len(args))
456
- from camoufox import DefaultAddons
457
-
458
- opts = dict(kwargs)
459
- # The bundled uBlock addon is downloaded at build time and can fail or be
460
- # rate-limited; download sessions do not need it.
461
- opts.setdefault("exclude_addons", [DefaultAddons.UBO])
462
- opts.setdefault("os", _host_os())
463
- # No disk cache: a PDF cached by an earlier download is revalidated and
464
- # comes back as 304 Not Modified, without a body to capture (Springer,
465
- # 2026-10-31). The browser starts anew for every article, so its memory
466
- # cache never holds an earlier article's PDF.
467
- # Camoufox 156 with Fission loses cross-process Turnstile frames and sends
468
- # input to their parent container. Keep CARSI's owned automation browser
469
- # compatible with Juggler; explicit caller preferences still take priority.
470
- opts["firefox_user_prefs"] = {
471
- "browser.cache.disk.enable": False,
472
- "fission.autostart": False,
473
- # Keep this owned browser usable while the user works in another app.
474
- "focusmanager.testmode": True,
475
- "dom.disable_window_flip": True,
476
- "browser.tabs.loadDivertedInBackground": True,
477
- "browser.link.open_newwindow": 3,
478
- "browser.link.open_newwindow.restriction": 0,
479
- **(opts.get("firefox_user_prefs") or {}),
480
- "papersearch.background.enabled": not headless,
481
- "papersearch.background.bootstrap": False,
482
- }
483
- if not headless and opts.get("ignore_default_args") is not True:
484
- # Playwright adds -foreground to every headed Firefox launch.
485
- opts["ignore_default_args"] = list(dict.fromkeys([
486
- *(opts.get("ignore_default_args") or []), "-foreground",
487
- ]))
488
- if not headless:
489
- from .background import options as background_options
490
- background_options(opts)
491
- opts.update(headless=headless, humanize=humanize, proxy=proxy)
492
- pinned = pinned_camoufox_dir()
493
- if pinned is not None and "executable_path" not in opts:
494
- from camoufox.pkgman import launch_path
495
-
496
- try:
497
- opts["executable_path"] = launch_path(pinned)
498
- except Exception as exc: # CamoufoxNotInstalled: a partial download
499
- logger.info("browser_backend: pinned Camoufox %s not usable (%s); the active build is used",
500
- pinned.name, type(exc).__name__)
501
- _launched.clear()
502
- _launched.update(backend=BACKEND_CAMOUFOX, pinned="yes" if "executable_path" in opts else "no",
503
- version=pinned.name if pinned is not None and "executable_path" in opts
504
- else _active_camoufox_version())
505
- return opts
506
-
507
-
508
- def pinned_camoufox_dir() -> Path | None:
509
- """The installed ``CAMOUFOX_BROWSER``: ``<cache>/browsers/official/<version>-<sha8>``."""
510
- try:
511
- from camoufox.pkgman import INSTALL_DIR
512
- except ImportError:
513
- return None
514
- found = sorted((Path(INSTALL_DIR) / "browsers" / "official").glob(f"{CAMOUFOX_BROWSER}-*"))
515
- return found[-1] if found else None
516
-
517
-
518
- def _active_camoufox_version() -> str:
519
- """The shared cache's active build, used when the pinned one is not installed."""
520
- try:
521
- from camoufox.pkgman import Version
522
-
523
- return Version.from_path().full_string
524
- except Exception:
525
- return ""
526
-
527
-
528
541
  def _close_with_driver(target: Any, pw: Any) -> Any:
529
- """Stop the Playwright driver when the browser/context closes."""
542
+ """Stop the driver when the browser/context closes."""
530
543
  original_close = target.close
531
544
 
532
545
  def _close_with_cleanup(*a: Any, **kw: Any) -> None:
@@ -542,63 +555,120 @@ def _close_with_driver(target: Any, pw: Any) -> Any:
542
555
  return target
543
556
 
544
557
 
545
- def _launch_camoufox(headless: bool, proxy: Any, args: list[str] | None, humanize: bool,
546
- **kwargs: Any) -> Any:
547
- from camoufox import NewBrowser
548
- from playwright.sync_api import sync_playwright
558
+ def chrome_profile_dir(user_data_dir: str | Path) -> Path:
559
+ """Chrome's own profile directory next to the given one."""
560
+ path = Path(user_data_dir)
561
+ if path.name.endswith(CHROME_PROFILE_SUFFIX):
562
+ return path
563
+ return path.with_name(path.name + CHROME_PROFILE_SUFFIX)
564
+
565
+
566
+ def _chrome_options(headless: bool, proxy: Any, args: list[str] | None,
567
+ config: dict[str, Any] | None) -> dict[str, Any]:
568
+ """Launch options for the installed Chrome: its public switches only.
549
569
 
550
- opts = _camoufox_options(headless, proxy, args, humanize, kwargs)
570
+ The driver's defaults already include --disable-backgrounding-occluded-windows,
571
+ --disable-renderer-backgrounding and --disable-background-timer-throttling,
572
+ so a covered window keeps rendering, and CDP input does not activate it.
573
+ Patchright itself adds --disable-blink-features=AutomationControlled and
574
+ drops --enable-automation.
575
+ """
576
+ executable = find_chrome(config)
577
+ if executable is None:
578
+ raise RuntimeError(f"browser_backend chrome: {CHROME_MISSING}")
579
+ switches = [arg for arg in (args or []) if not (proxy and arg.startswith("--proxy-server="))]
580
+ # Patchright's --disable-blink-features=AutomationControlled is on Chrome's
581
+ # list of unsupported flags, shown on a warning bar; Chrome's own
582
+ # --test-type switch skips that prompt.
583
+ switches = list(dict.fromkeys([*switches, "--test-type"]))
584
+ opts: dict[str, Any] = {"executable_path": str(executable), "headless": headless, "args": switches,
585
+ # Without it the driver adds --no-sandbox, and Chrome shows a warning bar.
586
+ "chromium_sandbox": True}
587
+ if proxy:
588
+ opts["proxy"] = proxy
589
+ if not headless:
590
+ opts["no_viewport"] = True # the window's own size, as the user sees it
591
+ return opts
592
+
593
+
594
+ def _note_chrome_launch(version: str, executable: str) -> None:
595
+ _launched.clear()
596
+ _launched.update(backend=BACKEND_CHROME, app=Path(executable).stem, version=str(version or ""),
597
+ driver=f"patchright {patchright_version()}")
598
+
599
+
600
+ def _launch_chrome(headless: bool, proxy: Any, args: list[str] | None, config: dict[str, Any] | None) -> Any:
601
+ from patchright.sync_api import sync_playwright
602
+
603
+ opts = _chrome_options(headless, proxy, args, config)
604
+ opts.pop("no_viewport", None) # a context option, not a launch option
551
605
  pw = sync_playwright().start()
552
606
  try:
553
- browser = NewBrowser(pw, **opts)
607
+ browser = pw.chromium.launch(**opts)
554
608
  except Exception:
555
609
  pw.stop()
556
610
  raise
611
+ _note_chrome_launch(browser.version, opts["executable_path"])
557
612
  return _close_with_driver(browser, pw)
558
613
 
559
614
 
560
- def _launch_camoufox_persistent(user_data_dir: str, headless: bool, proxy: Any,
561
- args: list[str] | None, humanize: bool, **kwargs: Any) -> Any:
562
- from camoufox import NewBrowser
563
- from playwright.sync_api import sync_playwright
564
-
565
- opts = _camoufox_options(headless, proxy, args, humanize, kwargs)
566
- if os.name == "nt" and not headless:
567
- # Let the owned helper create the first window without activation.
568
- from .background import ADDON_DIR, install_startup_helper
569
- install_startup_helper(Path(user_data_dir))
570
- opts["addons"] = [p for p in opts["addons"] if str(p) != str(ADDON_DIR)]
571
- opts["ignore_default_args"] = [*(opts.get("ignore_default_args") or []), "about:blank"]
572
- opts["args"] = [*(opts.get("args") or []), "-silent"]
573
- opts["firefox_user_prefs"].update({
574
- "papersearch.background.bootstrap": True,
575
- "xpinstall.signatures.required": False,
576
- "extensions.autoDisableScopes": 0,
577
- "extensions.enabledScopes": 1,
578
- "extensions.startupScanScopes": 1,
579
- # Gecko's first-profile video self-test opens an offscreen dialog
580
- # that still steals focus before any download window is created.
581
- "media.sanity-test.disabled": True,
582
- })
615
+ def _launch_chrome_persistent(profile: Path, headless: bool, proxy: Any, args: list[str] | None,
616
+ config: dict[str, Any] | None) -> Any:
617
+ from patchright.sync_api import sync_playwright
618
+
619
+ opts = _chrome_options(headless, proxy, args, config)
583
620
  pw = sync_playwright().start()
584
621
  try:
585
- context = NewBrowser(pw, persistent_context=True, user_data_dir=user_data_dir, **opts)
622
+ context = pw.chromium.launch_persistent_context(str(profile), **opts)
586
623
  except Exception:
587
624
  pw.stop()
588
625
  raise
626
+ _note_chrome_launch(getattr(context.browser, "version", ""), opts["executable_path"])
589
627
  return _close_with_driver(context, pw)
590
628
 
591
629
 
592
- def camoufox_profile_dir(user_data_dir: str | Path) -> Path:
593
- """Camoufox's own profile directory next to the given (Chromium-era) one."""
594
- path = Path(user_data_dir)
595
- if path.name.endswith(CAMOUFOX_PROFILE_SUFFIX):
596
- return path
597
- return path.with_name(path.name + CAMOUFOX_PROFILE_SUFFIX)
630
+ def _chrome_persistent(user_data_dir: str, *, headless: bool, proxy: Any, args: list[str] | None,
631
+ config: dict[str, Any] | None) -> Any:
632
+ profile = chrome_profile_dir(user_data_dir)
633
+ profile.mkdir(parents=True, exist_ok=True)
634
+ holder = profile_holder(str(profile))
635
+ waited_from = time.monotonic()
636
+ released = wait_for_profile_release(str(profile))
637
+ LAST_LAUNCH.update(holder=holder or "free", waited=round(time.monotonic() - waited_from, 1), released=released)
638
+ if proxy is None:
639
+ proxy = _proxy_from_config(config)
640
+ context = _launch_chrome_persistent(profile, headless, proxy, args, config)
641
+ _keep_session_cookies(context, profile)
642
+ if not headless:
643
+ _open_tabs_in_background(context)
644
+ _reuse_startup_page(context)
645
+ return context
646
+
647
+
648
+ def _open_tabs_in_background(context: Any) -> None:
649
+ """New tabs leave Chrome where the user put it.
650
+
651
+ The driver opens a page with Target.createTarget, which Chrome shows in the
652
+ foreground, bringing its window to the front: 3 of 3 times on macOS
653
+ (2026-11-07), once per supplements page and file. The same public command
654
+ with ``background`` left the user's front app in front 3 of 3 times, and
655
+ clicks in the new tab still worked.
656
+ """
657
+ session = context.browser.new_browser_cdp_session()
658
+ open_page = context.new_page
659
+
660
+ def new_page(*args: Any, **kwargs: Any) -> Any:
661
+ if args or kwargs:
662
+ return open_page(*args, **kwargs)
663
+ with context.expect_page() as created:
664
+ session.send("Target.createTarget", {"url": "about:blank", "background": True})
665
+ return created.value
666
+
667
+ context.new_page = new_page # type: ignore[method-assign]
598
668
 
599
669
 
600
670
  # ---------------------------------------------------------------------------
601
- # Public entry points (Playwright sync API, Camoufox)
671
+ # Public entry points (Playwright sync API, through Patchright)
602
672
  # ---------------------------------------------------------------------------
603
673
 
604
674
  def launch(
@@ -608,18 +678,17 @@ def launch(
608
678
  args: list[str] | None = None,
609
679
  humanize: bool = True,
610
680
  config: dict[str, Any] | None = None,
611
- **kwargs: Any,
612
681
  ) -> Any:
613
- """Launch Camoufox (or attach to ego); returns a ``playwright.sync_api.Browser``."""
682
+ """Launch Chrome (or attach to ego); returns a ``Browser``. ``humanize`` is kept for callers."""
614
683
  if resolve_backend(config) == BACKEND_EGO:
615
684
  return _launch_ego(config)
616
685
  if proxy is None:
617
686
  proxy = _proxy_from_config(config)
618
- return _launch_camoufox(headless=headless, proxy=proxy, args=args, humanize=humanize, **kwargs)
687
+ return _launch_chrome(headless, proxy, args, config)
619
688
 
620
689
 
621
- # The last Camoufox launch of this process, for the article's record: who held
622
- # the profile, how long the launch waited for it, whether it was released.
690
+ # The last launch of this process, for the article's record: who held the
691
+ # profile, how long the launch waited for it, whether it was released.
623
692
  LAST_LAUNCH: dict[str, Any] = {}
624
693
 
625
694
 
@@ -631,45 +700,22 @@ def launch_persistent_context(
631
700
  args: list[str] | None = None,
632
701
  humanize: bool = True,
633
702
  config: dict[str, Any] | None = None,
634
- **kwargs: Any,
635
703
  ) -> Any:
636
- """Camoufox with a persistent profile, or the running ego; returns a ``BrowserContext``.
704
+ """Chrome with a persistent profile, or the running ego; returns a ``BrowserContext``.
637
705
 
638
- Camoufox: the profile lives in a ``-camoufox`` sibling of ``user_data_dir``;
706
+ Chrome: the profile lives in a ``-chrome`` sibling of ``user_data_dir``;
639
707
  waits (bounded) for a previous browser process to release it. ego: the
640
708
  user's running browser and its own profile (``user_data_dir`` unused).
709
+ ``humanize`` is kept for callers.
641
710
  """
642
711
  LAST_LAUNCH.clear()
643
712
  if resolve_backend(config) == BACKEND_EGO:
644
713
  return _launch_ego_persistent(config)
645
- profile = camoufox_profile_dir(user_data_dir)
646
- profile.mkdir(parents=True, exist_ok=True)
647
- # Each item runs in a new process with the same profile: the previous item's
648
- # browser may still be closing; a launch then lost its pages a few seconds
649
- # later (OUP and Wiley items, TargetClosedError at the first page, 2026-11-02).
650
- holder = profile_holder(str(profile))
651
- waited_from = time.monotonic()
652
- released = wait_for_profile_release(str(profile))
653
- LAST_LAUNCH.update(holder=holder or "free", waited=round(time.monotonic() - waited_from, 1), released=released)
654
- if proxy is None:
655
- proxy = _proxy_from_config(config)
656
- from uuid import uuid4
657
- background_session = uuid4().hex
658
- if not headless:
659
- kwargs["firefox_user_prefs"] = {**(kwargs.get("firefox_user_prefs") or {}),
660
- "papersearch.background.session": background_session}
661
- context = _launch_camoufox_persistent(
662
- str(profile), headless=headless, proxy=proxy, args=args, humanize=humanize, **kwargs
663
- )
664
- if not callable(getattr(context, "close", None)):
665
- return context
666
- if not headless:
667
- from .background import ready as background_ready
668
- try:
669
- background_ready(profile, background_session)
670
- except Exception:
671
- context.close()
672
- raise
714
+ return _chrome_persistent(user_data_dir, headless=headless, proxy=proxy, args=args, config=config)
715
+
716
+
717
+ def _keep_session_cookies(context: Any, profile: Path) -> None:
718
+ """Session cookies (a school login) survive a browser that closes between runs."""
673
719
  restored = _restore_session_cookies(context, profile)
674
720
  if restored:
675
721
  logger.info("browser_backend: restored %d session cookie(s) from the previous run", restored)
@@ -680,21 +726,17 @@ def launch_persistent_context(
680
726
  close(*a, **kw)
681
727
 
682
728
  context.close = _close_keeping_session # type: ignore[method-assign]
683
- _reuse_startup_page(context)
684
- return context
685
729
 
686
730
 
687
731
  def _reuse_startup_page(context: Any) -> None:
688
- """A persistent Firefox profile opens with one blank window; callers then
689
- ask for a page and got a second window. The first ``new_page()`` now
690
- returns that untouched startup page instead.
691
-
692
- Firefox on Windows cannot open a window once its last one is closed:
693
- ``new_page()`` then fails with "window is null" (2026-11-01, the
694
- supplements step after the main text had closed its page; macOS keeps a
695
- hidden window, so it never showed there). Closing the last open page
696
- therefore first opens a blank one, which the next ``new_page()`` returns;
697
- the same on every system."""
732
+ """A persistent profile opens with one blank window; callers then ask for a
733
+ page and got a second window. The first ``new_page()`` now returns that
734
+ untouched startup page instead.
735
+
736
+ Closing the last open page first opens a blank one, which the next
737
+ ``new_page()`` returns, so the browser keeps its window between steps (the
738
+ earlier Firefox-based browser could not open one on Windows once its last
739
+ had closed: "window is null", 2026-11-01)."""
698
740
  spare = [page for page in list(getattr(context, "pages", None) or [])
699
741
  if str(getattr(page, "url", "")) in ("about:blank", "")]
700
742
  open_page = context.new_page
@@ -733,12 +775,13 @@ def browser_info(config: dict[str, Any] | None = None) -> dict[str, str]:
733
775
  """The browser and version of this process's last launch, else what a launch
734
776
  would use; kept with each download's record (ADR 0013).
735
777
 
736
- Camoufox: ``{"backend", "version", "pinned"}``; ego: ``{"backend", "app", "chromium"}``.
778
+ Chrome: ``{"backend", "app", "version", "driver"}`` (the user's browser,
779
+ recorded, not pinned); ego: ``{"backend", "app", "chromium"}``.
737
780
  """
738
781
  if _launched:
739
782
  return dict(_launched)
740
783
  if resolve_backend(config) == BACKEND_EGO:
741
784
  return {"backend": BACKEND_EGO, "app": ego_app_version(config), "chromium": ""}
742
- pinned = pinned_camoufox_dir()
743
- return {"backend": BACKEND_CAMOUFOX, "pinned": "yes" if pinned else "no",
744
- "version": pinned.name if pinned else _active_camoufox_version()}
785
+ found = find_chrome(config)
786
+ return {"backend": BACKEND_CHROME, "app": found.stem if found else "", "version": chrome_version(found),
787
+ "driver": f"patchright {patchright_version()}"}