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
@@ -0,0 +1,42 @@
1
+ """One browser window and tab kept for a serial MCP batch, on its Playwright
2
+ worker thread. Used when the backend declares ``batch_window``
3
+ (browser/backend.py); only plain Playwright calls, no backend of its own."""
4
+ from contextvars import ContextVar
5
+
6
+ from .preview import ensure_enabled
7
+
8
+
9
+ class BatchBrowser:
10
+ def __init__(self):
11
+ self.context = None
12
+ self.page = None
13
+ self.info = None
14
+ self.id = ""
15
+
16
+ def open(self, downloader, *, relaunch=""):
17
+ if self.context is not None and not self.context.pages:
18
+ self.close()
19
+ if self.context is None:
20
+ self.context = downloader._launch_context(relaunch=relaunch)
21
+ self.info = downloader.browser
22
+ else:
23
+ downloader.browser = self.info
24
+ ensure_enabled(self.context, downloader.config)
25
+ if self.page is None or self.page.is_closed():
26
+ self.page = self.context.new_page()
27
+ return self.context
28
+
29
+ def finish_item(self):
30
+ # Keep the original tab and its native window. Article/PDF/login
31
+ # popups cannot leak into the next publisher's page detection.
32
+ for page in self.context.pages:
33
+ if page is not self.page and not page.is_closed():
34
+ page.close()
35
+
36
+ def close(self):
37
+ context, self.context, self.page, self.info = self.context, None, None, None
38
+ if context is not None:
39
+ context.close()
40
+
41
+
42
+ active_batch: ContextVar[BatchBrowser | None] = ContextVar("active_browser_batch", default=None)
@@ -14,11 +14,12 @@ from urllib.parse import urlsplit
14
14
  _OBSERVE_SCRIPT = """() => {
15
15
  const key = Symbol.for('papersearch.turnstile.ready');
16
16
  if (window[key]) return;
17
- const ready = window[key] = new WeakSet();
17
+ const ready = window[key] = new WeakMap();
18
+ let revision = 0;
18
19
  addEventListener('message', event => {
19
20
  if (event.origin !== 'https://challenges.cloudflare.com' || !event.source
20
21
  || event.data?.source !== 'cloudflare-challenge') return;
21
- if (event.data.event === 'interactiveBegin') ready.add(event.source);
22
+ if (event.data.event === 'interactiveBegin') ready.set(event.source, ++revision);
22
23
  else if (['interactiveEnd', 'complete', 'fail', 'tokenExpired']
23
24
  .includes(event.data.event)) ready.delete(event.source);
24
25
  });
@@ -27,7 +28,9 @@ _OBSERVE_SCRIPT = """() => {
27
28
 
28
29
  def observe_checkbox(page: Any) -> None:
29
30
  """Observe readiness only; never read or write the verification response."""
30
- page.evaluate(_OBSERVE_SCRIPT)
31
+ from .driver import main_world
32
+
33
+ page.evaluate(_OBSERVE_SCRIPT, **main_world(page)) # where the init script observes
31
34
 
32
35
 
33
36
  def prepare_context(context: Any) -> None:
@@ -64,24 +67,41 @@ def is_turnstile_frame(url: str) -> bool:
64
67
  and "/turnstile/" in parsed.path)
65
68
 
66
69
 
70
+ # A page that navigated away while it was read: the next check reads the new page.
71
+ _NAVIGATED = ("frame was detached", "frame has been detached", "element is not attached",
72
+ "execution context was destroyed")
73
+
74
+
67
75
  def is_image_verification(page: Any) -> bool:
68
76
  """Image puzzles expose controls but may have no readable instructions."""
69
- return page.evaluate("""() => document.title.trim().toLowerCase() === 'human verification'
77
+ from .driver import Error
78
+
79
+ try:
80
+ return page.evaluate("""() => document.title.trim().toLowerCase() === 'human verification'
70
81
  && !document.querySelector('meta[name="citation_doi"]')
71
82
  && [...document.querySelectorAll('button, [role="button"], canvas, iframe')].some(el =>
72
83
  el.getClientRects().length > 0)""") is True
84
+ except Error as exc:
85
+ # A passed verification navigates while it is being read (Wiley and
86
+ # ScienceDirect on Chrome, 2026-11-07): no puzzle on a page that is gone.
87
+ if any(text in str(exc).lower() for text in _NAVIGATED):
88
+ return False
89
+ raise
73
90
 
74
91
 
75
92
  def needs_manual_verification(page: Any) -> bool:
76
- """A visible reCAPTCHA on an already recognised verification page.
93
+ """A puzzle or reCAPTCHA on an already recognised verification page.
77
94
 
78
95
  Reading a checked box or a response token cannot prove that the enclosing
79
96
  page's confirmation was submitted. Leave both actions to the user.
80
97
  """
81
- from playwright.sync_api import Error
98
+ return is_image_verification(page) or has_visible_recaptcha(page)
99
+
100
+
101
+ def has_visible_recaptcha(page: Any) -> bool:
102
+ """Detect a reCAPTCHA prompt that remains after the outer page changes."""
103
+ from .driver import Error
82
104
 
83
- if is_image_verification(page):
84
- return True # image/puzzle tasks are always left to the user
85
105
  for frame in page.frames:
86
106
  parsed = urlsplit(str(frame.url or ""))
87
107
  if (parsed.scheme != "https" or parsed.hostname not in {
@@ -99,7 +119,8 @@ def needs_manual_verification(page: Any) -> bool:
99
119
  return False
100
120
 
101
121
 
102
- def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]) -> Literal[
122
+ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None],
123
+ observation: Callable[[str], None] | None = None) -> Literal[
103
124
  "absent", "clicked", "unavailable"
104
125
  ]:
105
126
  """Try one visible checkbox; never force a click through an overlay.
@@ -108,13 +129,18 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
108
129
  compact-height Cloudflare widget with its identifying iframe title can
109
130
  use its standard checkbox position. Expanded puzzles are left alone.
110
131
  """
111
- from playwright.sync_api import Error, TimeoutError
132
+ from .driver import Error, TimeoutError, main_world
133
+
134
+ def note(reason: str) -> None:
135
+ if observation is not None:
136
+ observation(reason)
112
137
 
113
138
  until = time.monotonic() + max(0, timeout_ms) / 1000
139
+ unavailable = False
114
140
  for frame in page.frames:
115
141
  checkpoint()
116
142
  if time.monotonic() >= until:
117
- return "absent"
143
+ return "unavailable" if unavailable else "absent"
118
144
  if not is_turnstile_frame(str(frame.url or "")):
119
145
  continue
120
146
  try:
@@ -123,60 +149,68 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
123
149
  observe_checkbox(page)
124
150
  element = frame.frame_element()
125
151
  if not element.is_visible():
152
+ note("hidden_frame")
126
153
  continue
127
154
  controls = frame.locator('input[type="checkbox"], [role="checkbox"]')
128
155
  count = controls.count()
129
156
  position = None
130
157
  if count:
131
158
  if count != 1:
132
- return "unavailable"
159
+ note("multiple_controls")
160
+ unavailable = True
161
+ continue
133
162
  target = controls.first
134
- if not target.is_visible() or not target.is_enabled() or target.is_checked():
135
- return "unavailable"
163
+ if not target.is_visible():
164
+ note("hidden_control")
165
+ continue
166
+ if not target.is_enabled() or target.is_checked():
167
+ note("disabled_or_checked")
168
+ unavailable = True
169
+ continue
136
170
  else:
137
171
  title = (element.get_attribute("title") or "").lower()
138
172
  box = element.bounding_box()
139
173
  if ("cloudflare" not in title or "challenge" not in title or not box
140
174
  or not 250 <= box["width"] <= 350 or not 60 <= box["height"] <= 80):
141
- return "unavailable"
142
- if not element.evaluate("""iframe =>
143
- window[Symbol.for('papersearch.turnstile.ready')]?.has(iframe.contentWindow) === true
144
- """):
145
- return "absent" # loading/automatic check; no click has been attempted
175
+ geometry = f" width={box['width']:.0f} height={box['height']:.0f}" if box else ""
176
+ note("unsupported_geometry_or_title" + geometry)
177
+ unavailable = True
178
+ continue
179
+ readiness = element.evaluate("""iframe =>
180
+ window[Symbol.for('papersearch.turnstile.ready')]?.get(iframe.contentWindow) || 0
181
+ """, **main_world(element))
182
+ if not readiness:
183
+ note("waiting_ready_signal")
184
+ continue # loading/automatic check; no click has been attempted
146
185
  target = element
147
186
  position = {"x": 28, "y": box["height"] / 2}
148
187
  checkpoint()
149
188
  remaining_ms = int((until - time.monotonic()) * 1000)
150
189
  if remaining_ms <= 0:
151
190
  return "unavailable"
152
- if position:
153
- # A covered/moving widget has not received an input action.
154
- # Keep its readiness until native actionability checks pass.
155
- # Trial clicks on an iframe can reach its child document in
156
- # Playwright. Hover checks visibility/stability/hit targeting
157
- # without ever dispatching a checkbox click.
158
- target.hover(timeout=remaining_ms, position=position, trial=True)
159
- checkpoint()
160
- remaining_ms = int((until - time.monotonic()) * 1000)
161
- if remaining_ms <= 0:
162
- return "unavailable"
163
- # One readiness signal permits only one closed-shadow click. Wait
164
- # for a fresh interactiveBegin before retrying; otherwise a stale
165
- # signal could toggle an already checked or processing widget.
166
- if position and not element.evaluate("""iframe =>
167
- window[Symbol.for('papersearch.turnstile.ready')]?.delete(iframe.contentWindow) === true
168
- """):
169
- return "absent"
170
- remaining_ms = int((until - time.monotonic()) * 1000)
171
- if remaining_ms <= 0:
172
- return "unavailable"
191
+ # click performs visibility, stability and hit-target checks itself.
192
+ # A separate humanized hover uses the same short action budget twice.
193
+ # Keep readiness on actionability timeout so an overlay can clear.
173
194
  # The engine observes the navigation separately. A dispatched click
174
195
  # must not be reported as unavailable while waiting for that load.
175
196
  target.click(timeout=remaining_ms, no_wait_after=True,
176
197
  **({"position": position} if position else {}))
198
+ if position:
199
+ try:
200
+ element.evaluate("""(iframe, revision) => {
201
+ const ready = window[Symbol.for('papersearch.turnstile.ready')];
202
+ if (ready?.get(iframe.contentWindow) === revision) ready.delete(iframe.contentWindow);
203
+ }""", readiness, **main_world(element))
204
+ except Error as exc:
205
+ if not any(text in str(exc).lower() for text in (
206
+ "frame was detached", "frame has been detached", "element is not attached",
207
+ "execution context was destroyed")):
208
+ raise
209
+ note("click_dispatched")
177
210
  return "clicked"
178
211
  except TimeoutError:
179
- return "unavailable" # hidden/covered/stale; no repeated forced clicks
212
+ note("actionability_timeout")
213
+ unavailable = True
180
214
  except Error as exc:
181
215
  # Navigation can remove the widget before its action. Browser close,
182
216
  # crash, watchdog and cancellation errors must still reach the caller.
@@ -184,6 +218,8 @@ def click_checkbox(page: Any, *, timeout_ms: int, checkpoint: Callable[[], None]
184
218
  "frame was detached", "frame has been detached", "element is not attached",
185
219
  "execution context was destroyed",
186
220
  )):
187
- return "unavailable"
221
+ note("frame_detached")
222
+ unavailable = True
223
+ continue
188
224
  raise
189
- return "absent"
225
+ return "unavailable" if unavailable else "absent"
@@ -1,6 +1,6 @@
1
- """Extract cookies via Camoufox for publisher access.
1
+ """Extract cookies via the download browser for publisher access.
2
2
 
3
- Opens a visible Camoufox window, lets user log in to their institution,
3
+ Opens a visible browser window, lets user log in to their institution,
4
4
  then captures and saves publisher cookies for automated downloads.
5
5
  """
6
6
 
@@ -114,19 +114,19 @@ def extract_via_browser(
114
114
  Result dict with success, cookies_count, domains, etc.
115
115
  """
116
116
  try:
117
- from .backend import launch
117
+ from .backend import CHROME_MISSING, launch
118
118
  from .backend import is_available as _browser_backend_available
119
- if not _browser_backend_available():
119
+ if not _browser_backend_available(config=config):
120
120
  return {
121
121
  "success": False,
122
122
  "error": "no browser backend available",
123
- "fix": "pip install 'camoufox[geoip]' && python -m camoufox fetch",
123
+ "fix": CHROME_MISSING,
124
124
  }
125
125
  except ImportError:
126
126
  return {
127
127
  "success": False,
128
128
  "error": "no browser backend available",
129
- "fix": "pip install 'camoufox[geoip]' && python -m camoufox fetch",
129
+ "fix": "paper-search carsi update",
130
130
  }
131
131
 
132
132
  from ..config import DATA_DIR
@@ -189,7 +189,7 @@ def extract_via_browser(
189
189
  _save_cookies_json(save_cookies, cookie_file)
190
190
  _save_cookies_netscape(save_cookies, netscape_file)
191
191
 
192
- # Import into Camoufox server if running
192
+ # Import into the shared browser if available
193
193
  browser_imported = 0
194
194
  try:
195
195
  from .engine import import_cookies, is_available
@@ -339,7 +339,7 @@ def publisher_login(
339
339
  Takes a DOI or publisher name, resolves to the article page, and opens
340
340
  a visible stealth browser. User clicks "Access through your institution",
341
341
  completes SSO login, then closes the browser. Cookies are captured and
342
- imported into Camoufox for automated downloads.
342
+ imported into the download browser for automated downloads.
343
343
 
344
344
  Args:
345
345
  identifier: DOI (e.g. 10.1126/science.aec6396) or publisher name
@@ -0,0 +1,29 @@
1
+ """The Playwright API package both browser backends run on: Patchright.
2
+
3
+ Patchright is Playwright's code under another package name, with Chromium's
4
+ automation traces removed. Its errors are its own classes, and ``evaluate``
5
+ runs in an isolated world unless told otherwise.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from typing import Any
10
+
11
+ from patchright.sync_api import Error, TimeoutError # noqa: F401 (``except Error``)
12
+
13
+
14
+ def main_world(_target: Any = None) -> dict[str, Any]:
15
+ """``evaluate`` options for the page's own world, where init scripts run and
16
+ page globals live; Patchright evaluates in an isolated world by default."""
17
+ return {"isolated_context": False}
18
+
19
+
20
+ def is_driver_error(exc: BaseException, name: str = "") -> bool:
21
+ """An error raised by the driver (optionally of class ``name``), not a program bug."""
22
+ return type(exc).__module__.startswith("patchright.") and (not name or type(exc).__name__ == name)
23
+
24
+
25
+ def sync_bases() -> list[type]:
26
+ """The SyncBase classes whose calls the watchdog times."""
27
+ from patchright._impl import _sync_base
28
+
29
+ return [_sync_base.SyncBase]
@@ -1,10 +1,9 @@
1
- """Browser engine: Camoufox-based replacement for the old camofox daemon API.
1
+ """Browser engine: a shared browser for the routes outside the batch downloader.
2
2
 
3
- Provides the same public API as the old camofox.py (is_available, solve_url,
4
- get_cookies, get_html, import_cookies, evaluate_js, create_tab, close_tab,
5
- navigate_tab, get_snapshot, download_pdf_via_browser, fetch_url,
6
- get_captured_responses, close_all_tabs) but uses Camoufox's direct
7
- Playwright API instead of HTTP calls to an external daemon.
3
+ Public API (is_available, solve_url, get_cookies, get_html, import_cookies,
4
+ evaluate_js, create_tab, close_tab, navigate_tab, get_snapshot,
5
+ download_pdf_via_browser, fetch_url, get_captured_responses, close_all_tabs)
6
+ over the configured backend's Playwright API (backend.py).
8
7
 
9
8
  Uses a single shared browser instance with multiple tabs (pages). Cookies,
10
9
  login sessions, and Cloudflare bypass state are shared across all tabs.
@@ -28,14 +27,14 @@ from urllib.parse import urlparse
28
27
  logger = logging.getLogger(__name__)
29
28
 
30
29
  # ---------------------------------------------------------------------------
31
- # Browser backend (Camoufox via Playwright; ego-lite has its own driver)
30
+ # Browser backend (Chrome or ego-lite, both through Patchright)
32
31
  # ---------------------------------------------------------------------------
33
32
  # Everything in this module drives the Playwright sync API, shared by both
34
- # Camoufox and ego-lite. Backend selection lives in backend.py.
33
+ # backends. Backend selection lives in backend.py.
35
34
  # ---------------------------------------------------------------------------
36
35
 
37
36
  from .backend import ( # noqa: E402
38
- BACKEND_CAMOUFOX,
37
+ CHROME_MISSING,
39
38
  launch,
40
39
  launch_persistent_context,
41
40
  resolve_backend,
@@ -48,13 +47,14 @@ from .backend import ( # noqa: E402
48
47
  def _check_browser_backend(config: dict[str, Any] | None = None) -> bool:
49
48
  """True when the resolved backend can serve the Playwright API here.
50
49
 
51
- Camoufox when installed; ego always (whether its remote debugging is on
52
- is checked, with a hint for the user, when the browser is attached).
50
+ Chrome when installed; ego always (whether its remote
51
+ debugging is on is checked, with a hint for the user, when the browser is
52
+ attached).
53
53
  """
54
54
  from .backend import BACKEND_EGO, is_available
55
55
 
56
56
  backend = resolve_backend(config)
57
- return backend == BACKEND_EGO or (backend == BACKEND_CAMOUFOX and is_available(BACKEND_CAMOUFOX))
57
+ return backend == BACKEND_EGO or is_available(backend, config)
58
58
 
59
59
 
60
60
  # ---------------------------------------------------------------------------
@@ -233,10 +233,7 @@ def _get_shared_browser(config: dict[str, Any] | None = None):
233
233
  )
234
234
 
235
235
  if not _check_browser_backend(config):
236
- raise RuntimeError(
237
- "no Playwright browser backend available. Run: pip install 'camoufox[geoip]' && python -m camoufox fetch "
238
- "(browser_backend=ego routes through the ego driver instead)"
239
- )
236
+ raise RuntimeError(f"no browser backend available: {CHROME_MISSING}")
240
237
 
241
238
  # scihub_browser_headless overrides browser_headless for THIS shared
242
239
  # browser (the grey-source racing engine). It exists because the racing
@@ -286,10 +283,7 @@ def get_persistent_context(
286
283
  stable identity across multiple download runs.
287
284
  """
288
285
  if not _check_browser_backend(config):
289
- raise RuntimeError(
290
- "no Playwright browser backend available. Run: pip install 'camoufox[geoip]' && python -m camoufox fetch "
291
- "(browser_backend=ego routes through the ego driver instead)"
292
- )
286
+ raise RuntimeError(f"no browser backend available: {CHROME_MISSING}")
293
287
 
294
288
  headless = False
295
289
  humanize = True
@@ -352,7 +346,7 @@ def shutdown_shared_browser():
352
346
 
353
347
 
354
348
  # ---------------------------------------------------------------------------
355
- # Public API — drop-in replacements for camofox.py functions
349
+ # Public API
356
350
  # ---------------------------------------------------------------------------
357
351
 
358
352
  def is_available(config: dict[str, Any] | None = None) -> bool:
@@ -414,7 +408,7 @@ def solve_url(
414
408
  *,
415
409
  max_timeout: int = 60000,
416
410
  ) -> dict[str, Any] | None:
417
- """Fetch URL via Camoufox shared browser. Returns dict with status/solution keys."""
411
+ """Fetch URL via the shared browser. Returns dict with status/solution keys."""
418
412
  page = None
419
413
  try:
420
414
  _, context = _get_shared_browser(config)
@@ -582,7 +576,7 @@ def download_pdf_via_browser(
582
576
  *,
583
577
  timeout: float = 60.0,
584
578
  ) -> bool:
585
- """Download a PDF URL via Camoufox shared browser. Returns True on success.
579
+ """Download a PDF URL via the shared browser. Returns True on success.
586
580
 
587
581
  4-strategy cascade:
588
582
  1. Network response capture (from page.on("response"))
@@ -9,6 +9,7 @@ import ctypes
9
9
  import os
10
10
  import subprocess
11
11
  import threading
12
+ from collections.abc import Callable
12
13
  from concurrent.futures import Future
13
14
  from typing import Any
14
15
 
@@ -70,7 +71,7 @@ def _browser_pids(page: Any, config: dict) -> list[int]:
70
71
  return found
71
72
 
72
73
 
73
- def _activate_windows(pids: list[int], title: str = "") -> bool:
74
+ def _activate_windows(pids: list[int], window_title: Callable[[], str]) -> bool:
74
75
  from ctypes import wintypes
75
76
 
76
77
  user = ctypes.WinDLL("user32", use_last_error=True)
@@ -98,14 +99,17 @@ def _activate_windows(pids: list[int], title: str = "") -> bool:
98
99
  user.EnumWindows(visit, 0)
99
100
  if not found:
100
101
  return False
101
- matches = []
102
- for hwnd in found:
103
- text = ctypes.create_unicode_buffer(1024)
104
- user.GetWindowTextW(hwnd, text, len(text))
105
- if title and text.value.casefold().startswith(title.casefold()):
106
- matches.append(hwnd)
102
+ # The window whose caption starts with the waiting tab's title, else any.
103
+ candidates = []
104
+ title = window_title().casefold()
105
+ if title:
106
+ for hwnd in found:
107
+ caption = ctypes.create_unicode_buffer(1024)
108
+ user.GetWindowTextW(hwnd, caption, len(caption))
109
+ if caption.value.casefold().startswith(title):
110
+ candidates.append(hwnd)
111
+ candidates = candidates or found
107
112
  active = user.GetForegroundWindow()
108
- candidates = matches or found
109
113
  hwnd = active if active in candidates else candidates[0]
110
114
  if user.IsIconic(hwnd):
111
115
  user.ShowWindow(hwnd, 9) # SW_RESTORE, only this browser's minimized window
@@ -145,7 +149,7 @@ def activate_mac(pid: int) -> bool:
145
149
  else:
146
150
  activated = bool(app.activateWithOptions_(AppKit.NSApplicationActivateIgnoringOtherApps
147
151
  | AppKit.NSApplicationActivateAllWindows))
148
- # Activation alone leaves miniaturized Firefox windows in the Dock.
152
+ # Activation alone leaves miniaturized windows in the Dock.
149
153
  # The same reopen event as a Dock click restores them. Address the
150
154
  # existing PID, so a stale request can never launch another browser.
151
155
  return activated and _reopen_mac(pid)
@@ -190,12 +194,14 @@ def show(page: Any, config: dict) -> None:
190
194
  page.bring_to_front() # select this task's tab; macOS activation is done by the capsule
191
195
  if os.name != "nt":
192
196
  return
193
- from playwright.sync_api import TimeoutError as PlaywrightTimeoutError
197
+ from .driver import TimeoutError as PlaywrightTimeoutError
194
198
 
195
- try:
196
- title = page.locator('head > title').first.text_content(timeout=1000) or ""
197
- except PlaywrightTimeoutError:
198
- title = "" # a title is optional; native activation still selects the task browser
199
- if _activate_windows(_browser_pids(page, config), title.strip()):
199
+ def window_title() -> str:
200
+ try:
201
+ return (page.locator('head > title').first.text_content(timeout=1000) or "").strip()
202
+ except PlaywrightTimeoutError:
203
+ return ""
204
+
205
+ if _activate_windows(_browser_pids(page, config), window_title):
200
206
  return
201
207
  raise RuntimeError("the download browser window could not be activated")
@@ -8,14 +8,8 @@ import atexit
8
8
  from pathlib import Path
9
9
  from typing import Any
10
10
 
11
- try:
12
- from .backend import launch
13
- from .backend import BACKEND_CAMOUFOX
14
- from .backend import is_available as _browser_backend_available
15
- _HAS_CLOAKBROWSER = _browser_backend_available(BACKEND_CAMOUFOX)
16
- except ImportError:
17
- launch = None # type: ignore[assignment]
18
- _HAS_CLOAKBROWSER = False
11
+ from .backend import CHROME_MISSING, launch
12
+ from .backend import is_available as _browser_backend_available
19
13
  from ..log import get_logger
20
14
 
21
15
  log = get_logger()
@@ -53,8 +47,8 @@ class PersistentBrowser:
53
47
 
54
48
  def _start(self, config: dict[str, Any] | None = None):
55
49
  """Start a new browser instance. Restores saved state if available."""
56
- if not _HAS_CLOAKBROWSER:
57
- raise RuntimeError("camoufox not installed. Run: pip install 'camoufox[geoip]' && python -m camoufox fetch")
50
+ if not _browser_backend_available(config=config):
51
+ raise RuntimeError(f"no browser backend available: {CHROME_MISSING}")
58
52
  log.info(" [browser] Starting persistent browser...")
59
53
  self._browser = launch(
60
54
  headless=False, humanize=True,
@@ -207,23 +201,23 @@ def _save_cookies_json(cookies: list[dict[str, Any]], cookie_file: Path) -> None
207
201
 
208
202
 
209
203
  def _save_cookies_netscape(cookies: list[dict[str, Any]], cookie_file: Path) -> None:
210
- """Save cookies in Netscape format (Camoufox import compatible)."""
204
+ """Save cookies in Netscape format (the shared browser imports this format)."""
211
205
  from .cookies import cookies_to_netscape
212
206
  cookie_file.write_text(cookies_to_netscape(cookies), encoding="utf-8")
213
207
 
214
208
 
215
209
  def _import_to_browser(cookie_file: Path, config: dict[str, Any]) -> int:
216
- """Import cookies into Camoufox. Returns count imported."""
210
+ """Import cookies into the shared browser. Returns count imported."""
217
211
  try:
218
212
  from .engine import import_cookies, is_available
219
213
  if not is_available(config):
220
- log.info(" [browser] Camoufox not running, skipping auto-import")
214
+ log.info(" [browser] no browser backend, skipping auto-import")
221
215
  return 0
222
216
  count = import_cookies(cookie_file, config)
223
- log.info(f" [browser] Imported {count} cookies into Camoufox")
217
+ log.info(f" [browser] Imported {count} cookies into the browser")
224
218
  return count
225
219
  except Exception as exc:
226
- log.info(f" [browser] Could not auto-import to Camoufox: {exc}")
220
+ log.info(f" [browser] Could not auto-import to the browser: {exc}")
227
221
  return 0
228
222
 
229
223
 
@@ -246,7 +240,7 @@ def open_login_browser(
246
240
  cookie_file: Path to save captured cookies (JSON).
247
241
  detect_login: Optional callable(browser_context, page) -> bool for custom login detection.
248
242
  max_wait: Max seconds to wait for login.
249
- auto_import: Whether to auto-import cookies into Camoufox.
243
+ auto_import: Whether to auto-import cookies into the shared browser.
250
244
  keep_alive: If True, return (True, context, page) without closing browser.
251
245
  publisher: Publisher name (unused; kept for callers).
252
246
 
@@ -257,8 +251,8 @@ def open_login_browser(
257
251
  print(f"\n 请在浏览器中登录 ({url})")
258
252
  print(" 程序会自动检测登录完成...\n")
259
253
 
260
- if not _HAS_CLOAKBROWSER:
261
- log.info(" [browser] camoufox not installed")
254
+ if not _browser_backend_available(config=config):
255
+ log.info(f" [browser] {CHROME_MISSING}")
262
256
  return (False, None, None, None) if keep_alive else False
263
257
 
264
258
  try: