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.
Files changed (98) hide show
  1. package/README.en.md +50 -63
  2. package/README.md +50 -63
  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 +114 -15
  16. package/carsi/paper_search_carsi/browser/backend.py +269 -233
  17. package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
  18. package/carsi/paper_search_carsi/browser/challenge_interaction.py +28 -9
  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/cli.py +22 -7
  28. package/carsi/paper_search_carsi/cold_start.py +65 -51
  29. package/carsi/paper_search_carsi/config.py +6 -4
  30. package/carsi/paper_search_carsi/engine/batch.py +9 -5
  31. package/carsi/paper_search_carsi/engine/batch_capture.py +56 -20
  32. package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
  33. package/carsi/paper_search_carsi/engine/batch_institution.py +122 -13
  34. package/carsi/paper_search_carsi/engine/batch_login.py +30 -2
  35. package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
  36. package/carsi/paper_search_carsi/engine/batch_waits.py +21 -7
  37. package/carsi/paper_search_carsi/engine/bridge.py +23 -13
  38. package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
  39. package/carsi/paper_search_carsi/mcp_progress.py +13 -5
  40. package/carsi/paper_search_carsi/network.py +1 -1
  41. package/carsi/paper_search_carsi/progress_reporter.py +88 -7
  42. package/carsi/paper_search_carsi/progress_view.py +61 -0
  43. package/carsi/paper_search_carsi/server.py +47 -10
  44. package/carsi/paper_search_carsi/session_broker.py +1 -1
  45. package/carsi/pyproject.toml +7 -7
  46. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
  47. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
  48. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  49. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  50. package/dist/capabilities/pdf-discovery/batch.js +15 -5
  51. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  52. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +22 -0
  53. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
  54. package/dist/capabilities/pdf-discovery/batchSummary.js +131 -0
  55. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
  56. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
  57. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  58. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +52 -1
  59. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  60. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +8 -4
  61. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  62. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +89 -30
  63. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  64. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +4 -0
  65. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  66. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +10 -0
  67. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  68. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
  69. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  70. package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
  71. package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
  72. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +36 -0
  73. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  74. package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
  75. package/dist/capabilities/pdf-discovery/handler.js +11 -6
  76. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  77. package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
  78. package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
  79. package/dist/cli.js +13 -9
  80. package/dist/cli.js.map +1 -1
  81. package/dist/management/carsi/installer.d.ts +26 -14
  82. package/dist/management/carsi/installer.d.ts.map +1 -1
  83. package/dist/management/carsi/installer.js +113 -69
  84. package/dist/management/carsi/installer.js.map +1 -1
  85. package/dist/management/carsi/runtime.d.ts +12 -1
  86. package/dist/management/carsi/runtime.d.ts.map +1 -1
  87. package/dist/management/carsi/runtime.js +30 -1
  88. package/dist/management/carsi/runtime.js.map +1 -1
  89. package/package.json +1 -1
  90. package/skills/paper-search/SKILL.md +4 -4
  91. package/skills/paper-search/references/browser-download.md +3 -3
  92. package/skills/paper-search/references/carsi-setup.md +7 -6
  93. package/skills/paper-search/references/cli-contract.md +4 -4
  94. package/skills/paper-search/references/management-layer.md +2 -2
  95. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
  96. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
  97. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
  98. package/carsi/paper_search_carsi/browser/background.py +0 -68
@@ -16,6 +16,7 @@ from urllib.parse import urlencode
16
16
  import requests
17
17
 
18
18
  from ..browser import watchdog
19
+ from ..browser.driver import is_driver_error
19
20
  from ..browser.challenges import looks_like_challenge
20
21
 
21
22
 
@@ -129,9 +130,8 @@ def _observe_preview(page: Any) -> None:
129
130
 
130
131
 
131
132
  def _is_browser_error(exc: BaseException, name: str = "") -> bool:
132
- """A Playwright/Patchright error (optionally of class ``name``), not a program bug."""
133
- return (type(exc).__module__.startswith(("playwright.", "patchright."))
134
- and (not name or type(exc).__name__ == name))
133
+ """A driver error (optionally of class ``name``), not a program bug."""
134
+ return is_driver_error(exc, name)
135
135
 
136
136
 
137
137
  def page_title(page: Any) -> str:
@@ -158,11 +158,10 @@ def _is_navigation_cut(exc: BaseException) -> bool:
158
158
  return _is_browser_error(exc) and any(marker in str(exc) for marker in _NAVIGATION_CUT)
159
159
 
160
160
 
161
- # The publisher's site did not answer: Firefox's and Chromium's network errors,
162
- # and a page load that ran out of time. Not a program error (thieme-connect.de's
163
- # empty response and pubs.acs.org's 60 s loads, 2026-11-01).
164
- _NETWORK_FAILURE = ("NS_ERROR_NET_", "NS_ERROR_CONNECTION_REFUSED", "NS_ERROR_UNKNOWN_HOST",
165
- "NS_ERROR_PROXY_", "net::ERR_")
161
+ # The publisher's site did not answer: Chromium's network errors, and a page
162
+ # load that ran out of time. Not a program error (thieme-connect.de's empty
163
+ # response and pubs.acs.org's 60 s loads, 2026-11-01).
164
+ _NETWORK_FAILURE = ("net::ERR_",)
166
165
 
167
166
 
168
167
  def _is_network_failure(exc: BaseException) -> bool:
@@ -218,12 +217,54 @@ _DOCUMENT_STATE_JS = """() => [document.readyState,
218
217
  document.readyState === 'loading' && document.body ? document.body.textContent.length : 0]"""
219
218
 
220
219
 
220
+ # A connection the network dropped before the site answered: Chromium's codes for a
221
+ # closed, reset or timed-out connection, a failed proxy tunnel or name lookup, a
222
+ # broken protocol stream. A system proxy in front of doi.org dropped 1 of 6
223
+ # connections and 3 articles failed on it, each fine on the next try (Windows,
224
+ # 2026-11-07); such a navigation is tried again after these pauses.
225
+ _DROPPED_CONNECTION = (
226
+ "net::ERR_CONNECTION_CLOSED", "net::ERR_CONNECTION_RESET", "net::ERR_CONNECTION_TIMED_OUT",
227
+ "net::ERR_TIMED_OUT", "net::ERR_EMPTY_RESPONSE", "net::ERR_NETWORK_CHANGED",
228
+ "net::ERR_PROXY_CONNECTION_FAILED", "net::ERR_TUNNEL_CONNECTION_FAILED", "net::ERR_NAME_NOT_RESOLVED",
229
+ "net::ERR_SSL_PROTOCOL_ERROR", "net::ERR_HTTP2_PROTOCOL_ERROR", "net::ERR_QUIC_PROTOCOL_ERROR",
230
+ )
231
+ DROPPED_CONNECTION_RETRY_MS = (2_000, 5_000)
232
+
233
+
234
+ def goto_retrying(page: Any, url: str, *, timeout_ms: int, wait_until: str = "commit",
235
+ started: float | None = None, **kwargs: Any) -> Any:
236
+ """``page.goto``, again after a dropped connection while ``timeout_ms`` (counted
237
+ from ``started``, default now) allows. Every navigation of the download goes
238
+ through here: the article (``open_page``), its PDF, supplement tabs."""
239
+ started = time.monotonic() if started is None else started
240
+ dropped: BaseException | None = None
241
+ for attempt, pause_ms in enumerate((*DROPPED_CONNECTION_RETRY_MS, None)):
242
+ spent_ms = int((time.monotonic() - started) * 1000) if attempt else 0 # the first try: the whole budget
243
+ try:
244
+ return page.goto(url, wait_until=wait_until, timeout=max(1_000, timeout_ms - spent_ms), **kwargs)
245
+ except Exception as exc:
246
+ message = str(exc) if _is_browser_error(exc) else ""
247
+ if any(code in message for code in _DROPPED_CONNECTION):
248
+ dropped = exc
249
+ elif not (dropped and "net::ERR_ABORTED" in message):
250
+ raise
251
+ # After a dropped connection Chromium's error page reloads by itself and
252
+ # can cut the next try short (net::ERR_ABORTED): still the dropped
253
+ # connection, and reported as such (T&F through doi.org, Windows 2026-11-07).
254
+ spent_ms = int((time.monotonic() - started) * 1000)
255
+ if pause_ms is None or spent_ms + pause_ms >= timeout_ms:
256
+ raise dropped from (exc if exc is not dropped else None)
257
+ logger.info(" [Navigation] %s; trying again in %d s", message.splitlines()[0][:200], pause_ms // 1000)
258
+ page.wait_for_timeout(pause_ms)
259
+ raise AssertionError("unreachable")
260
+
261
+
221
262
  def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int = 15_000, **kwargs: Any) -> Any:
222
263
  """Go to ``url`` and on as soon as its document can be read: the navigation
223
- commits within ``timeout_ms``, then at most ``ready_ms`` until the document is
224
- parsed or its text stops growing; a verification page is left untouched at
225
- once. The caller checks the page state it needs (``settle``, the access rule,
226
- the verification wait). Returns the response."""
264
+ commits within ``timeout_ms`` (a dropped connection is tried again), then at
265
+ most ``ready_ms`` until the document is parsed or its text stops growing; a
266
+ verification page is left untouched at once. The caller checks the page state
267
+ it needs (``settle``, the access rule, the verification wait). Returns the response."""
227
268
  committed = False
228
269
 
229
270
  def navigated(frame: Any) -> None:
@@ -235,13 +276,12 @@ def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int =
235
276
  page.on("framenavigated", navigated)
236
277
  try:
237
278
  try:
238
- response = page.goto(url, wait_until="commit", timeout=timeout_ms, **kwargs)
279
+ response = goto_retrying(page, url, timeout_ms=timeout_ms, started=started, **kwargs)
239
280
  except Exception as exc:
240
281
  # A script redirect can replace the requested navigation before goto
241
- # returns (Firefox NS_ERROR_ABORT). Continue only after an observed
282
+ # returns (net::ERR_ABORTED). Continue only after an observed
242
283
  # top-level document commit; the caller still checks identity/access.
243
- if not _is_browser_error(exc) or not any(
244
- marker in str(exc) for marker in ("NS_ERROR_ABORT", "net::ERR_ABORTED")):
284
+ if not _is_browser_error(exc) or "net::ERR_ABORTED" not in str(exc):
245
285
  raise
246
286
  left = max(0, min(ready_ms, timeout_ms - int((time.monotonic() - started) * 1000)))
247
287
  if not committed and not pump_until(page, lambda: committed, left):
@@ -7,7 +7,7 @@ from __future__ import annotations
7
7
  import re
8
8
  import time
9
9
  from typing import Any
10
- from urllib.parse import parse_qs, unquote, urlencode, urlparse
10
+ from urllib.parse import parse_qs, unquote, urlencode, urljoin, urlparse
11
11
 
12
12
  from .batch_common import DownloadResult, _is_browser_error, logger, open_page, pump_until, settle
13
13
 
@@ -86,6 +86,12 @@ class InstitutionMixin:
86
86
  return True
87
87
  if self.institution_query and self._assist_configured_institution(page, result):
88
88
  return True
89
+ if self.institution_query and self._select_carsi_federation_link(page, result, here):
90
+ return True
91
+ if self.institution_query and not getattr(result, "_institution_not_listed", False):
92
+ self._check_carsi_school_links(page, result, here)
93
+ if getattr(result, "_institution_not_listed", False):
94
+ return False
89
95
  if self.adapter.prepare_institution_choice(page, result) is False:
90
96
  return False
91
97
  if self._open_seamlessaccess_chooser(page, result):
@@ -225,6 +231,8 @@ class InstitutionMixin:
225
231
  return null;
226
232
  }"""
227
233
  _CARSI_OPTION = re.compile(r"\bCARSI\b", re.I)
234
+ _FEDERATION_LINK_LIST = "ul.federation--list"
235
+ _FEDERATION_SCHOOL_LIST = "ul.federation--list-inner"
228
236
  # How long one pass waits for the school's option once the federation is chosen
229
237
  # (ACS answered after 35-50 s, 2026-11-02; the login loop asks again).
230
238
  LIST_WAIT_SEC = 15
@@ -325,6 +333,61 @@ class InstitutionMixin:
325
333
  result._federation_pages = getattr(result, "_federation_pages", set()) | {here}
326
334
  self._event(result, "institution_federation_selected", detail)
327
335
 
336
+ def _select_carsi_federation_link(self, page: Any, result: DownloadResult, url: str) -> bool:
337
+ if not self._on_publisher_host(url):
338
+ return False
339
+ listing = page.locator(self._FEDERATION_LINK_LIST).first
340
+ try:
341
+ if listing.is_visible() is not True:
342
+ return False
343
+ links = listing.get_by_role("link", name=self._CARSI_OPTION)
344
+ if links.count() != 1:
345
+ return False
346
+ href = links.first.get_attribute("href", timeout=800)
347
+ if not href or not self._manual_institution_target_allowed(urljoin(url, href)):
348
+ return False
349
+ here = self._federation_choice_page(page, result)
350
+ if here is None or not self._click_control(page, links.first, result, "choose CARSI federation"):
351
+ return False
352
+ except Exception as exc:
353
+ if not _is_browser_error(exc):
354
+ raise
355
+ self._event(result, "institution_step_interrupted", type(exc).__name__)
356
+ return False
357
+ self._federation_chosen(result, here, f"carsi: federation link @ {url}")
358
+ return True
359
+
360
+ def _check_carsi_school_links(self, page: Any, result: DownloadResult, url: str) -> None:
361
+ """Only a complete link directory can establish absence after choosing CARSI."""
362
+ if not self._on_publisher_host(url):
363
+ return
364
+ try:
365
+ listing = page.locator(self._FEDERATION_SCHOOL_LIST).first
366
+ if listing.is_visible() is not True:
367
+ return
368
+ heading = page.get_by_role("heading", level=1, name=self._CARSI_OPTION).first
369
+ if heading.is_visible() is not True or self._is_challenge_page(page):
370
+ return
371
+ rows = listing.locator(":scope > li")
372
+ entries = page.evaluate(self._ENTRIES_JS, self._FEDERATION_SCHOOL_LIST + " > li > a[href]")
373
+ if (not entries or len(entries) != rows.count()
374
+ or listing.evaluate("""el => !!el.closest('[aria-busy=true]') ||
375
+ !!el.closest('section')?.querySelector('input:not([type=hidden]), [aria-busy=true], [rel=next]')""",
376
+ timeout=800)):
377
+ return
378
+ # Even a partial name match is enough to leave the choice open for the user.
379
+ entity_id = self._entity_id()
380
+ names = {self._canonical_school_name(name) for name in self._institution_names()} - {""}
381
+ if any(self._institution_entry_score(entry, entity_id)
382
+ or self._canonical_school_name(entry["t"]) in names for entry in entries):
383
+ return
384
+ self._event(result, "auto_institution_not_found", f"{self.institution_query} (CARSI list, {len(entries)} schools) @ {url}")
385
+ result._institution_not_listed = True
386
+ except Exception as exc:
387
+ if not _is_browser_error(exc):
388
+ raise
389
+ self._event(result, "institution_step_interrupted", type(exc).__name__)
390
+
328
391
  def _close_blank_overlay(self, page: Any, result: DownloadResult) -> None:
329
392
  try:
330
393
  closed = page.evaluate(self._BLANK_OVERLAY_JS)
@@ -487,6 +550,11 @@ class InstitutionMixin:
487
550
  .filter(it => it.t && it.t.length <= 160);
488
551
  }"""
489
552
 
553
+ def _institution_entry_score(self, entry: dict, entity_id: str) -> int:
554
+ if self._carries_entity_id(str(entry.get("ids") or ""), entity_id):
555
+ return 4
556
+ return self._institution_match_score(entry.get("t", ""))
557
+
490
558
  def _click_unique_institution_entry(self, page: Any, result: DownloadResult, url: str) -> bool:
491
559
  """Click the single best visible entry for the configured school.
492
560
 
@@ -506,12 +574,7 @@ class InstitutionMixin:
506
574
  return False
507
575
  entity_id = self._entity_id()
508
576
 
509
- def score(item: dict) -> int:
510
- if self._carries_entity_id(str(item.get("ids") or ""), entity_id):
511
- return 4
512
- return self._institution_match_score(item.get("t", ""))
513
-
514
- scored = [(score(it), it) for it in items if isinstance(it, dict)]
577
+ scored = [(self._institution_entry_score(it, entity_id), it) for it in items if isinstance(it, dict)]
515
578
  top = max([score for score, _ in scored] or [0])
516
579
  best = [it for score, it in scored if score == top]
517
580
  same = (len(best) == 1 or top == 4
@@ -543,8 +606,8 @@ class InstitutionMixin:
543
606
  # leaves the option unselected even though no error is raised.
544
607
  # This is only the already matched institution, never a challenge
545
608
  # widget, credential field or another default choice.
546
- # Omit MouseEventInit.view: Camoufox rejects the evaluation
547
- # world's window as a Window, and the selection does not need it.
609
+ # Omit MouseEventInit.view: an isolated evaluation world's window
610
+ # can be rejected as a Window, and the selection does not need it.
548
611
  try:
549
612
  clicked = page.evaluate("""() => {
550
613
  const el = document.querySelector('[data-paper-search-entry]');
@@ -595,11 +658,55 @@ class InstitutionMixin:
595
658
  return False
596
659
  if not _is_browser_error(exc):
597
660
  raise
598
- # The wait was cut off by the navigation itself (Firefox's
599
- # NS_BINDING_ABORTED, a detached frame: an Atypon chooser going on to
600
- # the school failed the article, 2026-11-01): the page has gone on.
661
+ # The wait was cut off by the navigation itself (an aborted
662
+ # navigation, a detached frame: an Atypon chooser going on to the
663
+ # school failed the article, 2026-11-01): the page has gone on.
601
664
  return True
602
665
 
666
+ _NO_INSTITUTION_SEARCH_RESULTS = re.compile(
667
+ r"^(?:no (?:institutions?|results?|matches) found(?:[.!]?$|\s+for\b)"
668
+ r"|we couldn['’]t find any results? for\b)", re.I)
669
+ _INSTITUTION_LIST_LINK = re.compile(r"^(?:select|choose) (?:your|an) institution from (?:a|the) list$", re.I)
670
+
671
+ def _handle_institution_search_miss(self, page: Any, result: DownloadResult, url: str) -> bool:
672
+ """Use a visible negative result for our search, and try an offered list first."""
673
+ if (not (self._on_publisher_host(url) or self._is_federation_chooser(url))
674
+ or self._is_challenge_page(page)
675
+ or any(e["state"] == "auto_institution_list_opened" and e.get("detail") == url for e in result.events)):
676
+ return False
677
+ queries = {e.get("detail", "") for e in result.events if e["state"] == "auto_institution_search"}
678
+ try:
679
+ notice = page.get_by_text(self._NO_INSTITUTION_SEARCH_RESULTS).filter(visible=True).first
680
+ if notice.is_visible() is not True:
681
+ return False # no candidate yet does not establish an empty result
682
+ message = notice.inner_text(timeout=800)
683
+ named = re.split(r"\bfor\b", message, maxsplit=1, flags=re.I)[1:]
684
+ for selector in self._institution_search_selectors(page):
685
+ box = page.locator(selector).first
686
+ if box.is_visible() is not True:
687
+ continue
688
+ typed = str(box.input_value(timeout=800) or "").strip()
689
+ if f"{typed} @ {url}" not in queries:
690
+ continue
691
+ if named and self._canonical_school_name(named[0]) != self._canonical_school_name(typed):
692
+ continue # the reply names a different query
693
+ listing = page.get_by_role("link", name=self._INSTITUTION_LIST_LINK).filter(visible=True).first
694
+ if listing.is_visible() is True:
695
+ href = listing.get_attribute("href", timeout=800)
696
+ if (href and self._manual_institution_target_allowed(urljoin(url, href))
697
+ and self._click_control(page, listing, result, "open institution list")):
698
+ self._event(result, "auto_institution_list_opened", url)
699
+ return True
700
+ return False # there is another route; don't call the school missing
701
+ self._event(result, "auto_institution_not_found", f"{message[:120]} @ {url}")
702
+ result._institution_not_listed = True
703
+ return False
704
+ except Exception as exc:
705
+ if not _is_browser_error(exc):
706
+ raise
707
+ self._event(result, "institution_step_interrupted", type(exc).__name__)
708
+ return False
709
+
603
710
  def _assist_configured_institution(self, page: Any, result: DownloadResult) -> bool:
604
711
  """Pick the user's configured institution on the current page.
605
712
 
@@ -678,7 +785,9 @@ class InstitutionMixin:
678
785
  # 4. type the school into an empty institution search box (once per page);
679
786
  # never on a verification page, which the challenge wait takes first: a
680
787
  # search there found no school and ended the login (fixture, 2026-11-01).
681
- if not self._is_challenge_page(page) and once("institution_search"):
788
+ if not once("institution_search"):
789
+ return self._handle_institution_search_miss(page, result, url)
790
+ if not self._is_challenge_page(page):
682
791
  if self._assist_carsi_discovery(page, result):
683
792
  self._event(result, "auto_institution_search", f"carsi @ {url}")
684
793
  return True
@@ -596,6 +596,12 @@ class LoginMixin:
596
596
  or any(self._CARSI_OPTION.search(label) for label in entries)):
597
597
  continue
598
598
  return f"{name}: {', '.join(label[:40] for label in entries[:6])}"
599
+ if self._on_publisher_host(str(getattr(page, "url", "") or "")):
600
+ listing = page.locator(self._FEDERATION_LINK_LIST).first
601
+ if listing.is_visible() is True:
602
+ entries = [label.strip() for label in listing.get_by_role("link").all_text_contents() if label.strip()]
603
+ if len(entries) >= 2 and not any(self._CARSI_OPTION.search(label) for label in entries):
604
+ return f"federation links: {', '.join(label[:40] for label in entries[:6])}"
599
605
  return ""
600
606
 
601
607
  def _openathens_lacks_school(self, page: Any) -> bool:
@@ -1265,6 +1271,23 @@ class LoginMixin:
1265
1271
  return True
1266
1272
  # Username-first and QR login pages may have no password box. Inspect
1267
1273
  # only visibility and labels; never collect input or QR contents.
1274
+ try:
1275
+ return self._idp_controls(page)
1276
+ except Exception as exc:
1277
+ if not _is_navigation_cut(exc):
1278
+ raise
1279
+ return self._read_cut_as_users_step("login controls", exc)
1280
+
1281
+ def _read_cut_as_users_step(self, what: str, exc: BaseException) -> bool:
1282
+ """A read cut off by the page navigating (Ovid right after the remembered
1283
+ school, on Chrome, 2026-11-07): this pass leaves the page to the user, as
1284
+ ``_has_visible_editable_input`` does, and the next pass reads the new page."""
1285
+ self._event(getattr(self, "_item_result", None), "page_read_interrupted",
1286
+ f"{what}, taken as the user's step: {type(exc).__name__}: {(str(exc).splitlines() or [''])[0][:160]}")
1287
+ return True
1288
+
1289
+ @staticmethod
1290
+ def _idp_controls(page: Any) -> bool:
1268
1291
  return page.evaluate("""() => {
1269
1292
  const visible = el => el.getClientRects().length > 0;
1270
1293
  const input = [...document.querySelectorAll('input')].some(el => visible(el)
@@ -1302,8 +1325,13 @@ class LoginMixin:
1302
1325
 
1303
1326
  def _school_password_box(self, page: Any, url: str) -> bool:
1304
1327
  """A password or one-time-code field that is not a personal account's box on the publisher's site."""
1305
- return bool(page.locator('input[type="password"]:visible, input[autocomplete="one-time-code"]:visible').count()
1306
- and not self._personal_login_box(page, url))
1328
+ try:
1329
+ return bool(page.locator('input[type="password"]:visible, input[autocomplete="one-time-code"]:visible').count()
1330
+ and not self._personal_login_box(page, url))
1331
+ except Exception as exc:
1332
+ if not _is_navigation_cut(exc):
1333
+ raise
1334
+ return self._read_cut_as_users_step("password box", exc)
1307
1335
 
1308
1336
  def _personal_login_box(self, page: Any, url: str) -> bool:
1309
1337
  """A publisher account form can be on an article, login page or SSO host.
@@ -125,6 +125,7 @@ class UserRequestsMixin:
125
125
  return
126
126
  from ..browser.foreground import show
127
127
 
128
+ show(page, self.config)
128
129
  wait = getattr(result, "_login_wait", None)
129
130
  if wait is not None and getattr(result, "_login_attention", ""):
130
131
  wait.take_over()
@@ -132,7 +133,6 @@ class UserRequestsMixin:
132
133
  verification_wait = getattr(result, "_verification_wait", None)
133
134
  if verification_wait is not None:
134
135
  verification_wait.take_over()
135
- show(page, self.config)
136
136
  except (watchdog.BrowserUnresponsive, UserMarkedNoEntitlement):
137
137
  raise
138
138
  except Exception as exc:
@@ -125,6 +125,7 @@ class UserWaitMixin:
125
125
  except Exception:
126
126
  reporter = None
127
127
  shown = "" # "verification" | "login" | "unknown"
128
+ verification_tab = None
128
129
  try:
129
130
  while time.time() < deadline:
130
131
  self._check_user_decision(result, page)
@@ -154,7 +155,8 @@ class UserWaitMixin:
154
155
  if (urlparse(str(candidate.url or "")).hostname or "").lower() == suspect_host:
155
156
  self._raise_on_publisher_access_blocked(candidate)
156
157
  try:
157
- if self._is_challenge_page(candidate):
158
+ if (self._is_challenge_page(candidate)
159
+ or (candidate is verification_tab and self._challenge_continues(candidate))):
158
160
  state, tab = "verification", candidate
159
161
  break
160
162
  if self._pdf_step_needs_login(candidate):
@@ -191,6 +193,7 @@ class UserWaitMixin:
191
193
  captured["suspect_block"] = None
192
194
  return False
193
195
  if state == "verification":
196
+ verification_tab = tab
194
197
  self._raise_on_publisher_access_blocked(tab)
195
198
  result._attention_page = tab
196
199
  activity.observe(tab)
@@ -437,8 +440,9 @@ class UserWaitMixin:
437
440
  if deadline is None:
438
441
  if getattr(result, "_verification_attention", False):
439
442
  progress_reporter.clear_attention(key)
440
- if (progress_reporter.read_state() or {}).get("stage") == "waiting_verification":
441
- progress_reporter.report_stage("checking_access", current=result.doi)
443
+ progress = progress_reporter.read_state() or {}
444
+ if progress.get("stage") == "waiting_verification":
445
+ progress_reporter.update(stage="checking_access", phase="安全验证等待已结束,正在检查页面")
442
446
  result._verification_attention = False
443
447
  elif time.time() < getattr(result, "_verification_notify_at", 0):
444
448
  return
@@ -470,8 +474,7 @@ class UserWaitMixin:
470
474
  shell = self._challenge_shell(page)
471
475
  if not shell:
472
476
  self._raise_on_publisher_access_blocked(page)
473
- if (shell or self._is_challenge_page(page)
474
- or (waited and challenges.continues_manual_challenge(self._title(page)))):
477
+ if shell or self._is_challenge_page(page) or (waited and self._challenge_continues(page)):
475
478
  if not waited:
476
479
  deadline = self._wait_deadline(result, deadline)
477
480
  started, phase_before = time.time(), self._phase(result, "verification")
@@ -511,6 +514,12 @@ class UserWaitMixin:
511
514
  if wait_ms <= 0:
512
515
  break
513
516
  _observe_preview(page) # the verification page, for anyone checking in
517
+ remaining = watchdog.operation_remaining()
518
+ if remaining is not None and wait_ms >= remaining * 1000:
519
+ # No room for another polling interval. A scheduled
520
+ # delay running into the deadline is not a driver hang.
521
+ raise watchdog.BrowserBudgetExhausted(
522
+ "article page budget exhausted before next verification poll")
514
523
  page.wait_for_timeout(wait_ms)
515
524
  continue
516
525
  if waited:
@@ -520,8 +529,7 @@ class UserWaitMixin:
520
529
  self._event(result, "challenge_resolved", getattr(page, "url", ""))
521
530
  return True
522
531
  self._raise_on_publisher_access_blocked(page)
523
- passed = not (self._is_challenge_page(page)
524
- or (waited and challenges.continues_manual_challenge(self._title(page))))
532
+ passed = not (self._is_challenge_page(page) or (waited and self._challenge_continues(page)))
525
533
  if passed:
526
534
  result.state = state_before
527
535
  else:
@@ -549,6 +557,12 @@ class UserWaitMixin:
549
557
  if getattr(result, "_attention_page", None) is page:
550
558
  result._attention_page = None
551
559
 
560
+ def _challenge_continues(self, page: Any) -> bool:
561
+ # Only after a recognized challenge: the outer page can change title
562
+ # before its second, user-operated prompt is gone.
563
+ return (challenges.continues_manual_challenge(self._title(page))
564
+ or challenge_interaction.has_visible_recaptcha(page))
565
+
552
566
  def _challenge_shell(self, page: Any) -> bool:
553
567
  """Read only URL/title while a verification interstitial is active."""
554
568
  try:
@@ -465,9 +465,9 @@ def _try_browser_batch_download(
465
465
  config: dict[str, Any],
466
466
  profile: Any | None,
467
467
  ) -> dict[str, Any] | None:
468
- """Try single-DOI download via PublisherBatchDownloader + Camoufox.
468
+ """Try single-DOI download via PublisherBatchDownloader in the download browser.
469
469
 
470
- Uses the Camoufox state machine: navigate → SSO login → capture PDF → verify.
470
+ Uses the browser state machine: navigate → SSO login → capture PDF → verify.
471
471
  This is the most capable built-in path — handles Cloudflare, SSO redirects,
472
472
  and publisher-specific PDF extraction.
473
473
  """
@@ -482,8 +482,8 @@ def _try_browser_batch_download(
482
482
 
483
483
  try:
484
484
  from ..browser.backend import launch_persistent_context # noqa: F401
485
- # The configured browser: an ego-only install has no camoufox package
486
- # (2026-11-01: the default-backend check skipped every ego download).
485
+ # The configured browser, not the default one (2026-11-01: the
486
+ # default-backend check skipped every ego download).
487
487
  from ..browser.engine import is_available as _browser_backend_available
488
488
  if not _browser_backend_available(config):
489
489
  log.info(" [Institutional] no browser backend available, skipping browser download")
@@ -519,24 +519,30 @@ def _try_browser_batch_download(
519
519
 
520
520
  from ..browser import watchdog
521
521
 
522
+ from ..browser.backend import supports
523
+ from ..browser.batch_session import active_batch
524
+
522
525
  supplements_mode = str(config.get("supplements") or "")
526
+ batch = active_batch.get() if supports("batch_window", config) else None
523
527
  try:
524
- context = downloader._launch_context()
528
+ context = batch.open(downloader) if batch is not None else downloader._launch_context()
525
529
  try:
526
530
  if supplements_mode == "only":
527
531
  result = DownloadResult(doi=doi, status="failed", state="supplements_only",
528
532
  reason="supplements_only", article_url=downloader._article_url(doi))
529
533
  else:
530
- result = downloader.fetch_one(context, record, run_dir)
534
+ result = downloader.fetch_one(batch.page if batch is not None else context, record, run_dir)
531
535
  if _browser_closed_at_start(result):
532
536
  # The browser closed under the item's first page: the previous
533
537
  # item's browser was still releasing the profile. Once more.
534
538
  try:
535
- context.close()
539
+ (batch.close if batch is not None else context.close)()
536
540
  except Exception:
537
541
  pass
538
- context = downloader._launch_context(relaunch="the browser closed at the first page")
539
- result = downloader.fetch_one(context, record, run_dir)
542
+ relaunch = "the browser closed at the first page"
543
+ context = (batch.open(downloader, relaunch=relaunch) if batch is not None
544
+ else downloader._launch_context(relaunch=relaunch))
545
+ result = downloader.fetch_one(batch.page if batch is not None else context, record, run_dir)
540
546
  if watchdog.fired and not result.ok:
541
547
  # The browser call never returned and the driver was stopped:
542
548
  # whatever the engine reported after that is a consequence.
@@ -571,10 +577,14 @@ def _try_browser_batch_download(
571
577
  downloader._drop_snapshot_pictures(result)
572
578
  _note_supplements(result, written)
573
579
  finally:
574
- try:
575
- context.close()
576
- except Exception:
577
- pass
580
+ if batch is not None:
581
+ if not watchdog.fired:
582
+ batch.finish_item()
583
+ else:
584
+ try:
585
+ context.close()
586
+ except Exception:
587
+ pass
578
588
  except Exception as e:
579
589
  log.info(" [Institutional] Browser batch download error: %s", type(e).__name__)
580
590
  if isinstance(e, watchdog.BrowserOperationTimeout):
@@ -18,7 +18,7 @@ _READ_ACTIVITY = """token => {
18
18
  if (!state || state.token !== token) {
19
19
  if (state) state.dispose();
20
20
  state = {token, count: 0};
21
- // Camoufox also marks script events trusted. Require native input
21
+ // Some automation marks script events trusted. Require native input
22
22
  // metadata as well; submit/change alone cannot establish takeover.
23
23
  const events = ['input', 'keydown', 'pointerdown'];
24
24
  const record = event => {
@@ -3,6 +3,8 @@ from __future__ import annotations
3
3
 
4
4
  import asyncio
5
5
  from contextlib import suppress
6
+ from concurrent.futures import Executor
7
+ from contextvars import copy_context
6
8
  import threading
7
9
  from typing import Callable, Any
8
10
 
@@ -11,16 +13,22 @@ from . import progress_reporter
11
13
  STAGE_PREFIX = "carsi.stage:"
12
14
 
13
15
 
14
- async def run_with_progress(context: Any, identifier: str, operation: Callable[[], str]) -> str:
16
+ async def run_with_progress(context: Any, identifier: str, operation: Callable[[], str],
17
+ *, executor: Executor | None = None) -> str:
15
18
  """Stream fixed stages while the blocking operation runs off the event loop.
16
19
 
17
20
  The injected MCP context owns the caller's progress token (or sends nothing
18
21
  for an older client). Neither a global progress file nor GUI prose is read.
19
22
  """
20
- if context is None:
21
- return await asyncio.to_thread(operation)
22
-
23
23
  loop = asyncio.get_running_loop()
24
+
25
+ async def run() -> str:
26
+ if executor is None:
27
+ return await asyncio.to_thread(operation)
28
+ return await loop.run_in_executor(executor, copy_context().run, operation)
29
+
30
+ if context is None:
31
+ return await run()
24
32
  queue: asyncio.Queue[str | None] = asyncio.Queue(maxsize=64)
25
33
  active = threading.Event()
26
34
  active.set()
@@ -64,7 +72,7 @@ async def run_with_progress(context: Any, identifier: str, operation: Callable[[
64
72
  cancelled = False
65
73
  try:
66
74
  with progress_reporter.listen_for_stages(identifier, observe):
67
- return await asyncio.to_thread(operation)
75
+ return await run()
68
76
  except asyncio.CancelledError:
69
77
  cancelled = True
70
78
  raise
@@ -238,7 +238,7 @@ def fetch_with_browser(
238
238
  *,
239
239
  stream: bool = False,
240
240
  ) -> requests.Response | None:
241
- """Fetch URL using Camoufox to bypass Cloudflare challenges."""
241
+ """Fetch URL in the shared browser to pass Cloudflare challenges."""
242
242
  from .browser.engine import solve_url, is_available
243
243
  if not is_available(config):
244
244
  return None