papersearch 0.4.9 → 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.
- package/README.en.md +50 -63
- package/README.md +50 -63
- package/assets/overview.en.png +0 -0
- package/assets/overview.png +0 -0
- package/assets/progress-capsule.en.png +0 -0
- package/assets/progress-capsule.png +0 -0
- package/carsi/README.md +5 -6
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
- package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
- package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
- package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
- package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
- package/carsi/paper_search_carsi/assets/capsule.html +114 -15
- package/carsi/paper_search_carsi/browser/backend.py +269 -233
- package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +28 -9
- package/carsi/paper_search_carsi/browser/cookies.py +8 -8
- package/carsi/paper_search_carsi/browser/driver.py +29 -0
- package/carsi/paper_search_carsi/browser/engine.py +17 -23
- package/carsi/paper_search_carsi/browser/foreground.py +21 -15
- package/carsi/paper_search_carsi/browser/login.py +12 -18
- package/carsi/paper_search_carsi/browser/preview.py +31 -12
- package/carsi/paper_search_carsi/browser/profiles.py +16 -23
- package/carsi/paper_search_carsi/browser/watchdog.py +61 -55
- package/carsi/paper_search_carsi/cli.py +22 -7
- package/carsi/paper_search_carsi/cold_start.py +65 -51
- package/carsi/paper_search_carsi/config.py +6 -4
- package/carsi/paper_search_carsi/engine/batch.py +9 -5
- package/carsi/paper_search_carsi/engine/batch_capture.py +56 -20
- package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
- package/carsi/paper_search_carsi/engine/batch_institution.py +122 -13
- package/carsi/paper_search_carsi/engine/batch_login.py +30 -2
- package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
- package/carsi/paper_search_carsi/engine/batch_waits.py +21 -7
- package/carsi/paper_search_carsi/engine/bridge.py +23 -13
- package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
- package/carsi/paper_search_carsi/mcp_progress.py +13 -5
- package/carsi/paper_search_carsi/network.py +1 -1
- package/carsi/paper_search_carsi/progress_reporter.py +88 -7
- package/carsi/paper_search_carsi/progress_view.py +61 -0
- package/carsi/paper_search_carsi/server.py +47 -10
- package/carsi/paper_search_carsi/session_broker.py +1 -1
- package/carsi/pyproject.toml +7 -7
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.js +15 -5
- package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batchSummary.d.ts +22 -0
- package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
- package/dist/capabilities/pdf-discovery/batchSummary.js +131 -0
- package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +52 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +8 -4
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +89 -30
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +4 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +10 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts +36 -0
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/handler.js +11 -6
- package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
- package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
- package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
- package/dist/cli.js +13 -9
- package/dist/cli.js.map +1 -1
- package/dist/management/carsi/installer.d.ts +26 -14
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +113 -69
- package/dist/management/carsi/installer.js.map +1 -1
- package/dist/management/carsi/runtime.d.ts +12 -1
- package/dist/management/carsi/runtime.d.ts.map +1 -1
- package/dist/management/carsi/runtime.js +30 -1
- package/dist/management/carsi/runtime.js.map +1 -1
- package/package.json +1 -1
- package/skills/paper-search/SKILL.md +4 -4
- package/skills/paper-search/references/browser-download.md +3 -3
- package/skills/paper-search/references/carsi-setup.md +7 -6
- package/skills/paper-search/references/cli-contract.md +4 -4
- package/skills/paper-search/references/management-layer.md +2 -2
- package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
- package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
- package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
- package/carsi/paper_search_carsi/browser/background.py +0 -68
|
@@ -1,15 +1,14 @@
|
|
|
1
|
-
"""Browser backends:
|
|
1
|
+
"""Browser backends: Chrome (default) or ego-lite, both driven by Patchright.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
config key:
|
|
3
|
+
Two backends are supported, selected by the ``browser_backend`` config key:
|
|
5
4
|
|
|
6
|
-
* ``
|
|
7
|
-
|
|
8
|
-
Playwright
|
|
9
|
-
|
|
10
|
-
|
|
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
|
|
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
|
|
22
|
-
configs, logged, and mapped to ``
|
|
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
|
-
|
|
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 =
|
|
63
|
-
SUPPORTED_BACKENDS = (
|
|
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
|
-
#
|
|
67
|
-
|
|
68
|
-
|
|
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
|
|
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)
|
|
180
|
-
|
|
181
|
-
back to
|
|
182
|
-
is off stays selected and the launch
|
|
183
|
-
missing
|
|
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
|
-
|
|
189
|
-
|
|
190
|
-
"'
|
|
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
|
-
"""
|
|
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
|
-
"""(
|
|
217
|
-
from
|
|
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
|
-
#
|
|
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
|
-
#
|
|
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
|
-
"""
|
|
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
|
|
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,70 +555,120 @@ def _close_with_driver(target: Any, pw: Any) -> Any:
|
|
|
542
555
|
return target
|
|
543
556
|
|
|
544
557
|
|
|
545
|
-
def
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
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
|
-
|
|
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 =
|
|
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
|
|
561
|
-
|
|
562
|
-
from
|
|
563
|
-
from playwright.sync_api import sync_playwright
|
|
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
|
|
564
618
|
|
|
565
|
-
opts =
|
|
566
|
-
if not headless:
|
|
567
|
-
# Gecko's automatic Troubleshoot Mode dialog blocks the download
|
|
568
|
-
# browser and disables its background helper. Keep recovery and the
|
|
569
|
-
# startup keyboard shortcut from opening it in this child only.
|
|
570
|
-
env = opts.get("env")
|
|
571
|
-
opts["env"] = {**(os.environ if env is None else env),
|
|
572
|
-
"MOZ_DISABLE_AUTO_SAFE_MODE": "1", "MOZ_DISABLE_SAFE_MODE_KEY": "1"}
|
|
573
|
-
if os.name == "nt" and not headless:
|
|
574
|
-
# Let the owned helper create the first window without activation.
|
|
575
|
-
from .background import ADDON_DIR, install_startup_helper
|
|
576
|
-
install_startup_helper(Path(user_data_dir))
|
|
577
|
-
opts["addons"] = [p for p in opts["addons"] if str(p) != str(ADDON_DIR)]
|
|
578
|
-
opts["ignore_default_args"] = [*(opts.get("ignore_default_args") or []), "about:blank"]
|
|
579
|
-
opts["args"] = [*(opts.get("args") or []), "-silent"]
|
|
580
|
-
opts["firefox_user_prefs"].update({
|
|
581
|
-
"papersearch.background.bootstrap": True,
|
|
582
|
-
"xpinstall.signatures.required": False,
|
|
583
|
-
"extensions.autoDisableScopes": 0,
|
|
584
|
-
"extensions.enabledScopes": 1,
|
|
585
|
-
"extensions.startupScanScopes": 1,
|
|
586
|
-
# Gecko's first-profile video self-test opens an offscreen dialog
|
|
587
|
-
# that still steals focus before any download window is created.
|
|
588
|
-
"media.sanity-test.disabled": True,
|
|
589
|
-
})
|
|
619
|
+
opts = _chrome_options(headless, proxy, args, config)
|
|
590
620
|
pw = sync_playwright().start()
|
|
591
621
|
try:
|
|
592
|
-
context =
|
|
622
|
+
context = pw.chromium.launch_persistent_context(str(profile), **opts)
|
|
593
623
|
except Exception:
|
|
594
624
|
pw.stop()
|
|
595
625
|
raise
|
|
626
|
+
_note_chrome_launch(getattr(context.browser, "version", ""), opts["executable_path"])
|
|
596
627
|
return _close_with_driver(context, pw)
|
|
597
628
|
|
|
598
629
|
|
|
599
|
-
def
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
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]
|
|
605
668
|
|
|
606
669
|
|
|
607
670
|
# ---------------------------------------------------------------------------
|
|
608
|
-
# Public entry points (Playwright sync API,
|
|
671
|
+
# Public entry points (Playwright sync API, through Patchright)
|
|
609
672
|
# ---------------------------------------------------------------------------
|
|
610
673
|
|
|
611
674
|
def launch(
|
|
@@ -615,18 +678,17 @@ def launch(
|
|
|
615
678
|
args: list[str] | None = None,
|
|
616
679
|
humanize: bool = True,
|
|
617
680
|
config: dict[str, Any] | None = None,
|
|
618
|
-
**kwargs: Any,
|
|
619
681
|
) -> Any:
|
|
620
|
-
"""Launch
|
|
682
|
+
"""Launch Chrome (or attach to ego); returns a ``Browser``. ``humanize`` is kept for callers."""
|
|
621
683
|
if resolve_backend(config) == BACKEND_EGO:
|
|
622
684
|
return _launch_ego(config)
|
|
623
685
|
if proxy is None:
|
|
624
686
|
proxy = _proxy_from_config(config)
|
|
625
|
-
return
|
|
687
|
+
return _launch_chrome(headless, proxy, args, config)
|
|
626
688
|
|
|
627
689
|
|
|
628
|
-
# The last
|
|
629
|
-
#
|
|
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.
|
|
630
692
|
LAST_LAUNCH: dict[str, Any] = {}
|
|
631
693
|
|
|
632
694
|
|
|
@@ -638,45 +700,22 @@ def launch_persistent_context(
|
|
|
638
700
|
args: list[str] | None = None,
|
|
639
701
|
humanize: bool = True,
|
|
640
702
|
config: dict[str, Any] | None = None,
|
|
641
|
-
**kwargs: Any,
|
|
642
703
|
) -> Any:
|
|
643
|
-
"""
|
|
704
|
+
"""Chrome with a persistent profile, or the running ego; returns a ``BrowserContext``.
|
|
644
705
|
|
|
645
|
-
|
|
706
|
+
Chrome: the profile lives in a ``-chrome`` sibling of ``user_data_dir``;
|
|
646
707
|
waits (bounded) for a previous browser process to release it. ego: the
|
|
647
708
|
user's running browser and its own profile (``user_data_dir`` unused).
|
|
709
|
+
``humanize`` is kept for callers.
|
|
648
710
|
"""
|
|
649
711
|
LAST_LAUNCH.clear()
|
|
650
712
|
if resolve_backend(config) == BACKEND_EGO:
|
|
651
713
|
return _launch_ego_persistent(config)
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
holder = profile_holder(str(profile))
|
|
658
|
-
waited_from = time.monotonic()
|
|
659
|
-
released = wait_for_profile_release(str(profile))
|
|
660
|
-
LAST_LAUNCH.update(holder=holder or "free", waited=round(time.monotonic() - waited_from, 1), released=released)
|
|
661
|
-
if proxy is None:
|
|
662
|
-
proxy = _proxy_from_config(config)
|
|
663
|
-
from uuid import uuid4
|
|
664
|
-
background_session = uuid4().hex
|
|
665
|
-
if not headless:
|
|
666
|
-
kwargs["firefox_user_prefs"] = {**(kwargs.get("firefox_user_prefs") or {}),
|
|
667
|
-
"papersearch.background.session": background_session}
|
|
668
|
-
context = _launch_camoufox_persistent(
|
|
669
|
-
str(profile), headless=headless, proxy=proxy, args=args, humanize=humanize, **kwargs
|
|
670
|
-
)
|
|
671
|
-
if not callable(getattr(context, "close", None)):
|
|
672
|
-
return context
|
|
673
|
-
if not headless:
|
|
674
|
-
from .background import ready as background_ready
|
|
675
|
-
try:
|
|
676
|
-
background_ready(profile, background_session)
|
|
677
|
-
except Exception:
|
|
678
|
-
context.close()
|
|
679
|
-
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."""
|
|
680
719
|
restored = _restore_session_cookies(context, profile)
|
|
681
720
|
if restored:
|
|
682
721
|
logger.info("browser_backend: restored %d session cookie(s) from the previous run", restored)
|
|
@@ -687,21 +726,17 @@ def launch_persistent_context(
|
|
|
687
726
|
close(*a, **kw)
|
|
688
727
|
|
|
689
728
|
context.close = _close_keeping_session # type: ignore[method-assign]
|
|
690
|
-
_reuse_startup_page(context)
|
|
691
|
-
return context
|
|
692
729
|
|
|
693
730
|
|
|
694
731
|
def _reuse_startup_page(context: Any) -> None:
|
|
695
|
-
"""A persistent
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
``new_page()``
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
therefore first opens a blank one, which the next ``new_page()`` returns;
|
|
704
|
-
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)."""
|
|
705
740
|
spare = [page for page in list(getattr(context, "pages", None) or [])
|
|
706
741
|
if str(getattr(page, "url", "")) in ("about:blank", "")]
|
|
707
742
|
open_page = context.new_page
|
|
@@ -740,12 +775,13 @@ def browser_info(config: dict[str, Any] | None = None) -> dict[str, str]:
|
|
|
740
775
|
"""The browser and version of this process's last launch, else what a launch
|
|
741
776
|
would use; kept with each download's record (ADR 0013).
|
|
742
777
|
|
|
743
|
-
|
|
778
|
+
Chrome: ``{"backend", "app", "version", "driver"}`` (the user's browser,
|
|
779
|
+
recorded, not pinned); ego: ``{"backend", "app", "chromium"}``.
|
|
744
780
|
"""
|
|
745
781
|
if _launched:
|
|
746
782
|
return dict(_launched)
|
|
747
783
|
if resolve_backend(config) == BACKEND_EGO:
|
|
748
784
|
return {"backend": BACKEND_EGO, "app": ego_app_version(config), "chromium": ""}
|
|
749
|
-
|
|
750
|
-
return {"backend":
|
|
751
|
-
"
|
|
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()}"}
|