papersearch 0.4.9 → 0.4.11

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 (142) hide show
  1. package/LICENSE +1 -1
  2. package/NOTICE +23 -0
  3. package/README.en.md +136 -247
  4. package/README.md +136 -247
  5. package/assets/carsi-flow.en.png +0 -0
  6. package/assets/carsi-flow.png +0 -0
  7. package/assets/overview.en.png +0 -0
  8. package/assets/overview.png +0 -0
  9. package/assets/progress-capsule.en.png +0 -0
  10. package/assets/progress-capsule.png +0 -0
  11. package/carsi/README.md +6 -7
  12. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
  13. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
  14. package/carsi/paper_search_carsi/adapters/iop/__init__.py +8 -2
  15. package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
  16. package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
  17. package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
  18. package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
  19. package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +23 -0
  20. package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
  21. package/carsi/paper_search_carsi/assets/capsule.html +134 -18
  22. package/carsi/paper_search_carsi/browser/backend.py +269 -233
  23. package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
  24. package/carsi/paper_search_carsi/browser/challenge_interaction.py +28 -9
  25. package/carsi/paper_search_carsi/browser/cookies.py +8 -8
  26. package/carsi/paper_search_carsi/browser/driver.py +29 -0
  27. package/carsi/paper_search_carsi/browser/engine.py +17 -23
  28. package/carsi/paper_search_carsi/browser/foreground.py +21 -15
  29. package/carsi/paper_search_carsi/browser/login.py +12 -18
  30. package/carsi/paper_search_carsi/browser/preview.py +31 -12
  31. package/carsi/paper_search_carsi/browser/profiles.py +16 -23
  32. package/carsi/paper_search_carsi/browser/watchdog.py +113 -58
  33. package/carsi/paper_search_carsi/cli.py +22 -7
  34. package/carsi/paper_search_carsi/cold_start.py +65 -51
  35. package/carsi/paper_search_carsi/config.py +6 -4
  36. package/carsi/paper_search_carsi/download_diagnostics.py +2 -1
  37. package/carsi/paper_search_carsi/engine/batch.py +17 -7
  38. package/carsi/paper_search_carsi/engine/batch_capture.py +97 -31
  39. package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
  40. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +3 -0
  41. package/carsi/paper_search_carsi/engine/batch_institution.py +132 -13
  42. package/carsi/paper_search_carsi/engine/batch_login.py +151 -18
  43. package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
  44. package/carsi/paper_search_carsi/engine/batch_waits.py +21 -7
  45. package/carsi/paper_search_carsi/engine/bridge.py +23 -13
  46. package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
  47. package/carsi/paper_search_carsi/engine/supplements.py +36 -2
  48. package/carsi/paper_search_carsi/mcp_progress.py +13 -5
  49. package/carsi/paper_search_carsi/network.py +1 -1
  50. package/carsi/paper_search_carsi/progress_capsule.py +6 -2
  51. package/carsi/paper_search_carsi/progress_reporter.py +107 -9
  52. package/carsi/paper_search_carsi/progress_view.py +78 -1
  53. package/carsi/paper_search_carsi/server.py +53 -10
  54. package/carsi/paper_search_carsi/session_broker.py +1 -1
  55. package/carsi/pyproject.toml +7 -7
  56. package/dist/capabilities/journal-metrics/JournalMetricsService.d.ts.map +1 -1
  57. package/dist/capabilities/journal-metrics/JournalMetricsService.js +2 -1
  58. package/dist/capabilities/journal-metrics/JournalMetricsService.js.map +1 -1
  59. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
  60. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
  61. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  62. package/dist/capabilities/pdf-discovery/batch.d.ts +2 -0
  63. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  64. package/dist/capabilities/pdf-discovery/batch.js +59 -14
  65. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  66. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +28 -0
  67. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
  68. package/dist/capabilities/pdf-discovery/batchSummary.js +155 -0
  69. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
  70. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
  71. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  72. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +56 -1
  73. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  74. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +11 -4
  75. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  76. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +114 -30
  77. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  78. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +6 -0
  79. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  80. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +12 -0
  81. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  82. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
  83. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  84. package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
  85. package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
  86. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +48 -0
  87. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  88. package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
  89. package/dist/capabilities/pdf-discovery/handler.js +11 -6
  90. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  91. package/dist/capabilities/pdf-discovery/tiers/publisherApi.d.ts.map +1 -1
  92. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js +2 -1
  93. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js.map +1 -1
  94. package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
  95. package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
  96. package/dist/cli.js +30 -15
  97. package/dist/cli.js.map +1 -1
  98. package/dist/config/ConfigService.d.ts.map +1 -1
  99. package/dist/config/ConfigService.js +28 -2
  100. package/dist/config/ConfigService.js.map +1 -1
  101. package/dist/config/apiKeySignup.d.ts +13 -0
  102. package/dist/config/apiKeySignup.d.ts.map +1 -0
  103. package/dist/config/apiKeySignup.js +32 -0
  104. package/dist/config/apiKeySignup.js.map +1 -0
  105. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  106. package/dist/infrastructure/runlog/failureClass.js +4 -0
  107. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  108. package/dist/management/capability-profile/index.d.ts +7 -0
  109. package/dist/management/capability-profile/index.d.ts.map +1 -1
  110. package/dist/management/capability-profile/index.js +7 -0
  111. package/dist/management/capability-profile/index.js.map +1 -1
  112. package/dist/management/carsi/installer.d.ts +26 -14
  113. package/dist/management/carsi/installer.d.ts.map +1 -1
  114. package/dist/management/carsi/installer.js +118 -74
  115. package/dist/management/carsi/installer.js.map +1 -1
  116. package/dist/management/carsi/runtime.d.ts +12 -1
  117. package/dist/management/carsi/runtime.d.ts.map +1 -1
  118. package/dist/management/carsi/runtime.js +30 -1
  119. package/dist/management/carsi/runtime.js.map +1 -1
  120. package/dist/management/diagnostics/index.d.ts.map +1 -1
  121. package/dist/management/diagnostics/index.js +4 -1
  122. package/dist/management/diagnostics/index.js.map +1 -1
  123. package/dist/management/failures/exportReport.js +3 -3
  124. package/dist/management/reports/index.d.ts.map +1 -1
  125. package/dist/management/reports/index.js +6 -1
  126. package/dist/management/reports/index.js.map +1 -1
  127. package/dist/platforms/SemanticScholarSearcher.d.ts.map +1 -1
  128. package/dist/platforms/SemanticScholarSearcher.js +2 -1
  129. package/dist/platforms/SemanticScholarSearcher.js.map +1 -1
  130. package/package.json +3 -2
  131. package/skills/paper-search/SKILL.md +9 -9
  132. package/skills/paper-search/references/browser-download.md +7 -6
  133. package/skills/paper-search/references/capability-routing.md +3 -3
  134. package/skills/paper-search/references/carsi-setup.md +8 -7
  135. package/skills/paper-search/references/cli-contract.md +6 -6
  136. package/skills/paper-search/references/management-layer.md +3 -3
  137. package/skills/paper-search/references/publisher-support.md +2 -0
  138. package/skills/paper-search/references/troubleshooting.md +1 -2
  139. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
  140. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
  141. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
  142. package/carsi/paper_search_carsi/browser/background.py +0 -68
@@ -422,8 +422,9 @@ class LoginMixin:
422
422
  self._event(result, "login_state", marker)
423
423
  last_state = marker
424
424
  confirmation = self._idp_confirmation(page)
425
- if confirmation:
426
- # The user decides: the engine never agrees on their behalf.
425
+ if confirmation and confirmation not in self.IDP_ACCEPTED_CONFIRMATIONS:
426
+ # A second factor (Duo) is the user's; the agreements are
427
+ # accepted below (_accept_idp_confirmation).
427
428
  self._event(result, "idp_confirmation_required", confirmation)
428
429
  page_since = time.time()
429
430
  elif self._user_away:
@@ -439,6 +440,8 @@ class LoginMixin:
439
440
  continue
440
441
  if self._return_from_login_site(page, result):
441
442
  continue
443
+ if self._accept_publisher_terms(page, result) or self._accept_idp_confirmation(page, result):
444
+ continue
442
445
  if manual_selection:
443
446
  if self._is_challenge_page(page):
444
447
  if not self._wait_for_challenge(page, result, deadline=deadline):
@@ -563,6 +566,91 @@ class LoginMixin:
563
566
  : document.querySelector('[name="_shib_idp_consentOptions"], [name="_shib_idp_consentIds"]') ? 'attribute-release' : ''"""
564
567
  _IDP_ERROR_RE = re.compile(r"未知错误|系统错误|服务异常|认证失败|出错了|\b5\d{4}\b.{0,20}错误|an unexpected error|error code|system error", re.I)
565
568
 
569
+ # A publisher's own terms form on the way to the school: SIAM's SAML consent
570
+ # ("I have read and agree to the Terms and Conditions and Privacy Policy.",
571
+ # Atypon's /action/saml2post) held the login until the page wait ran out
572
+ # (2026-11-07). The user asked to have such forms accepted (2026-11-08). Only
573
+ # on the publisher's site; the school's own: ``_accept_idp_confirmation``.
574
+ _PUBLISHER_TERMS_JS = r"""() => {
575
+ const visible = el => !!el && el.getClientRects().length > 0;
576
+ for (const form of document.querySelectorAll('form')) {
577
+ if (!visible(form)) continue;
578
+ const text = (form.innerText || '').replace(/\s+/g, ' ').trim();
579
+ if (text.length > 300 || !/^I (?:have read and )?(?:agree|accept) to the ?Terms\b/i.test(text)) continue;
580
+ const yes = [...form.querySelectorAll('input[type=submit], button[type=submit], button:not([type])')]
581
+ .find(el => visible(el) && !/^\s*(?:no|cancel|decline)\b/i.test(el.value || el.innerText || ''));
582
+ if (!yes) continue;
583
+ yes.setAttribute('data-papersearch-terms', '1');
584
+ return text.slice(0, 120);
585
+ }
586
+ return '';
587
+ }"""
588
+ PUBLISHER_TERMS_TRIES = 2
589
+
590
+ def _accept_publisher_terms(self, page: Any, result: DownloadResult) -> bool:
591
+ """Agree to a publisher's terms form shown during the login; True when clicked."""
592
+ url = str(getattr(page, "url", "") or "")
593
+ if (not self._on_publisher_host(url) or self._is_idp_host(urlparse(url).netloc)
594
+ or sum(e["state"] == "publisher_terms_accepted" for e in result.events) >= self.PUBLISHER_TERMS_TRIES):
595
+ return False
596
+ try:
597
+ terms = page.evaluate(self._PUBLISHER_TERMS_JS)
598
+ except Exception as exc:
599
+ if not _is_browser_error(exc):
600
+ raise
601
+ return False
602
+ if not terms or not self._click_control(page, page.locator('[data-papersearch-terms="1"]').first,
603
+ result, "accept the publisher's terms"):
604
+ return False
605
+ self._event(result, "publisher_terms_accepted", f"{terms} @ {url[:160]}")
606
+ settle(page, 2_000)
607
+ return True
608
+
609
+ # The school's IdP asking to agree before it goes on (Shibboleth's attribute
610
+ # release and terms of use): accepted for the user too, as they asked
611
+ # (2026-11-08). The release keeps the choices the school preselected; the
612
+ # terms' own "I accept" box is ticked. A second factor (Duo) stays the user's,
613
+ # and so does a confirmation still shown after two accepts in one article.
614
+ IDP_ACCEPTED_CONFIRMATIONS = ("attribute-release", "terms-of-use")
615
+ IDP_CONFIRMATION_TRIES = 2
616
+ _IDP_ACCEPT_JS = r"""(kind) => {
617
+ const visible = el => !!el && el.getClientRects().length > 0;
618
+ const proceed = [...document.querySelectorAll('[name="_eventId_proceed"]')].find(visible);
619
+ if (!proceed) return false;
620
+ if (kind === 'terms-of-use' && proceed.form)
621
+ for (const box of proceed.form.querySelectorAll('input[type=checkbox][name="_shib_idp_consentIds"]'))
622
+ if (!box.checked && visible(box)) box.setAttribute('data-papersearch-idp', 'tick');
623
+ proceed.setAttribute('data-papersearch-idp', 'proceed');
624
+ return true;
625
+ }"""
626
+
627
+ def _accept_idp_confirmation(self, page: Any, result: DownloadResult) -> bool:
628
+ """Agree to the school's attribute release or terms of use; True when clicked.
629
+ Otherwise the user is told once that the page waits for them."""
630
+ kind = self._idp_confirmation(page)
631
+ if kind not in self.IDP_ACCEPTED_CONFIRMATIONS:
632
+ return False
633
+ url = str(getattr(page, "url", "") or "").split("?", 1)[0]
634
+ if sum(e["state"] == "idp_confirmation_accepted" for e in result.events) < self.IDP_CONFIRMATION_TRIES:
635
+ try:
636
+ ready = page.evaluate(self._IDP_ACCEPT_JS, kind)
637
+ except Exception as exc:
638
+ if not _is_browser_error(exc):
639
+ raise
640
+ ready = False
641
+ if ready:
642
+ for box in page.locator('[data-papersearch-idp="tick"]').all():
643
+ self._click_control(page, box, result, "tick the school's terms of use")
644
+ if self._click_control(page, page.locator('[data-papersearch-idp="proceed"]').first,
645
+ result, "accept the school's confirmation"):
646
+ self._event(result, "idp_confirmation_accepted", f"{kind} @ {url[:160]}")
647
+ settle(page, 2_000)
648
+ return True
649
+ if getattr(result, "_idp_confirmation_left", "") != kind:
650
+ result._idp_confirmation_left = kind
651
+ self._event(result, "idp_confirmation_required", kind)
652
+ return False
653
+
566
654
  def _idp_confirmation(self, page: Any) -> str:
567
655
  """What the school's IdP asks the user to agree to, if anything: Shibboleth's
568
656
  attribute release or terms of use, or a Duo second factor."""
@@ -596,6 +684,12 @@ class LoginMixin:
596
684
  or any(self._CARSI_OPTION.search(label) for label in entries)):
597
685
  continue
598
686
  return f"{name}: {', '.join(label[:40] for label in entries[:6])}"
687
+ if self._on_publisher_host(str(getattr(page, "url", "") or "")):
688
+ listing = page.locator(self._FEDERATION_LINK_LIST).first
689
+ if listing.is_visible() is True:
690
+ entries = [label.strip() for label in listing.get_by_role("link").all_text_contents() if label.strip()]
691
+ if len(entries) >= 2 and not any(self._CARSI_OPTION.search(label) for label in entries):
692
+ return f"federation links: {', '.join(label[:40] for label in entries[:6])}"
599
693
  return ""
600
694
 
601
695
  def _openathens_lacks_school(self, page: Any) -> bool:
@@ -622,6 +716,7 @@ class LoginMixin:
622
716
  r"|sorry, you have been blocked|no institutions found|not registered for use with this service"
623
717
  r"|application you have accessed is not registered|may not be enabled for this type of authentication"
624
718
  r"|can't find your institution|access to this resource has been restricted by your organization|oa-ap-4032"
719
+ r"|不支持的请求|does not have access to this resource"
625
720
  r"|temporarily unavailable|verify you are human|are you a robot|checking your browser|正在进行安全验证", re.I)
626
721
 
627
722
  def _login_block_reason(self, page: Any) -> str:
@@ -635,7 +730,9 @@ class LoginMixin:
635
730
  if code == "login_page_closed":
636
731
  return "the browser window was closed"
637
732
  if code == "institution_pdf_entitlement_missing":
638
- return self._denial_line(page)
733
+ line = self._denial_line(page)
734
+ if line:
735
+ return line
639
736
  lists = self._federation_list_lacks_carsi(page) if code == "institution_federation_unavailable" else ""
640
737
  if lists:
641
738
  return f"the federation list has no CARSI entry ({lists})"[:240]
@@ -692,6 +789,15 @@ class LoginMixin:
692
789
  return override
693
790
  if "unsupported request" in haystack and "not registered for use with this service" in haystack:
694
791
  return "institution_not_registered"
792
+ # The same Shibboleth page in Chinese: "Web登陆服务 - 不支持的请求" on the
793
+ # school's IdP, the school has not enabled this publisher (JAMA, 2026-11-07).
794
+ if "不支持的请求" in haystack and self._is_idp_host(urlparse(current_url).netloc):
795
+ return "institution_not_registered"
796
+ # LibLynx (De Gruyter's chooser) after the school was chosen: "<school> does
797
+ # not have access to this resource", the publisher denies the school (2026-11-07).
798
+ if ("does not have access to this resource" in haystack
799
+ and any(name.lower() in haystack for name in self._institution_names() if name)):
800
+ return "institution_pdf_entitlement_missing"
695
801
  if "application you have accessed is not registered" in haystack:
696
802
  return "institution_not_registered"
697
803
  if "your institution may not be enabled for this type of authentication" in haystack:
@@ -878,22 +984,27 @@ class LoginMixin:
878
984
 
879
985
  # Controls that open a site's access menu or login panel instead of a page:
880
986
  # "GET ACCESS" and "Login / Register" on ascelibrary.org (2026-11-02), "Access
881
- # options", "Sign in". A link to a login page is not one of them.
987
+ # options", "Sign in". A link to a login page is not one of them. An access
988
+ # menu comes first: SIAM's "Register / Sign In", earlier on the page than its
989
+ # "Get Access", went to its personal account sign-in (2026-11-08).
882
990
  _ACCESS_MENU_JS = r"""() => {
883
991
  const shown = el => el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden';
884
- const MENU = /^(?:get access|access options|(?:log ?in|sign ?in)(?: ?\/ ?register)?|register ?\/ ?(?:log ?in|sign ?in))$/i;
992
+ const MENUS = [/^(?:get access|access options)$/i,
993
+ /^(?:(?:log ?in|sign ?in)(?: ?\/ ?register)?|register ?\/ ?(?:log ?in|sign ?in))$/i];
885
994
  const TOGGLES = ['aria-haspopup', 'aria-expanded', 'aria-controls', 'data-toggle', 'data-bs-toggle', 'data-target'];
886
- for (const el of document.querySelectorAll('button, [role="button"], a')) {
887
- if (!shown(el) || el.closest('form')) continue;
888
- const label = (el.innerText || el.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim();
889
- // A screen-reader hint can be part of innerText ("Sign In Open Menu").
890
- const menuLabel = label.replace(/\s+open menu$/i, '');
891
- if (!MENU.test(menuLabel)) continue;
892
- const href = (el.getAttribute('href') || '').trim();
893
- if (el.tagName === 'A' && href && !href.startsWith('#') && !/^javascript:/i.test(href)
894
- && !TOGGLES.some(name => el.hasAttribute(name))) continue;
895
- el.click();
896
- return label;
995
+ for (const MENU of MENUS) {
996
+ for (const el of document.querySelectorAll('button, [role="button"], a')) {
997
+ if (!shown(el) || el.closest('form')) continue;
998
+ const label = (el.innerText || el.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim();
999
+ // A screen-reader hint can be part of innerText ("Sign In Open Menu").
1000
+ const menuLabel = label.replace(/\s+open menu$/i, '');
1001
+ if (!MENU.test(menuLabel)) continue;
1002
+ const href = (el.getAttribute('href') || '').trim();
1003
+ if (el.tagName === 'A' && href && !href.startsWith('#') && !/^javascript:/i.test(href)
1004
+ && !TOGGLES.some(name => el.hasAttribute(name))) continue;
1005
+ el.click();
1006
+ return label;
1007
+ }
897
1008
  }
898
1009
  return '';
899
1010
  }"""
@@ -1265,6 +1376,23 @@ class LoginMixin:
1265
1376
  return True
1266
1377
  # Username-first and QR login pages may have no password box. Inspect
1267
1378
  # only visibility and labels; never collect input or QR contents.
1379
+ try:
1380
+ return self._idp_controls(page)
1381
+ except Exception as exc:
1382
+ if not _is_navigation_cut(exc):
1383
+ raise
1384
+ return self._read_cut_as_users_step("login controls", exc)
1385
+
1386
+ def _read_cut_as_users_step(self, what: str, exc: BaseException) -> bool:
1387
+ """A read cut off by the page navigating (Ovid right after the remembered
1388
+ school, on Chrome, 2026-11-07): this pass leaves the page to the user, as
1389
+ ``_has_visible_editable_input`` does, and the next pass reads the new page."""
1390
+ self._event(getattr(self, "_item_result", None), "page_read_interrupted",
1391
+ f"{what}, taken as the user's step: {type(exc).__name__}: {(str(exc).splitlines() or [''])[0][:160]}")
1392
+ return True
1393
+
1394
+ @staticmethod
1395
+ def _idp_controls(page: Any) -> bool:
1268
1396
  return page.evaluate("""() => {
1269
1397
  const visible = el => el.getClientRects().length > 0;
1270
1398
  const input = [...document.querySelectorAll('input')].some(el => visible(el)
@@ -1302,8 +1430,13 @@ class LoginMixin:
1302
1430
 
1303
1431
  def _school_password_box(self, page: Any, url: str) -> bool:
1304
1432
  """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))
1433
+ try:
1434
+ return bool(page.locator('input[type="password"]:visible, input[autocomplete="one-time-code"]:visible').count()
1435
+ and not self._personal_login_box(page, url))
1436
+ except Exception as exc:
1437
+ if not _is_navigation_cut(exc):
1438
+ raise
1439
+ return self._read_cut_as_users_step("password box", exc)
1307
1440
 
1308
1441
  def _personal_login_box(self, page: Any, url: str) -> bool:
1309
1442
  """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 => {
@@ -117,6 +117,35 @@ def _get(request: Any, url: str, entry: dict[str, Any], sleep) -> Any:
117
117
  return request.get(url, timeout=REQUEST_TIMEOUT_MS)
118
118
 
119
119
 
120
+ # Response headers that name what answered instead of the file (a CDN's or a
121
+ # firewall's challenge, a login service), kept for the record.
122
+ _PAGE_HEADERS = ("server", "x-amzn-waf-action", "cf-mitigated", "location")
123
+
124
+
125
+ def _page_evidence(response: Any) -> dict[str, Any]:
126
+ """What a page received instead of a file was: its status, final address
127
+ (no query), title and telling headers. Figshare's download address answered a
128
+ page and nothing said which (AIP, Royal Society, AACR; 2026-11-08)."""
129
+ evidence: dict[str, Any] = {"http_status": getattr(response, "status", None)}
130
+ url = str(getattr(response, "url", "") or "")
131
+ if url:
132
+ evidence["final_url"] = url.split("?", 1)[0][:300]
133
+ headers = getattr(response, "headers", None) or {}
134
+ named = {key: str(headers.get(key))[:120] for key in _PAGE_HEADERS if headers.get(key)}
135
+ if named:
136
+ evidence["page_headers"] = named
137
+ try:
138
+ text = response.body()[:65536].decode("utf-8", "replace")
139
+ except Exception:
140
+ return evidence
141
+ title = re.search(r"<title[^>]*>(.*?)</title>", text, re.I | re.S)
142
+ if title:
143
+ from html import unescape
144
+
145
+ evidence["page_title"] = " ".join(unescape(title.group(1)).split())[:160]
146
+ return evidence
147
+
148
+
120
149
  def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi: str, *,
121
150
  clock=time.monotonic, sleep=time.sleep,
122
151
  manifest_dir: Path | None = None,
@@ -171,8 +200,13 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
171
200
  elif length > MAX_FILE_BYTES:
172
201
  entry.update(status="skipped", reason="too_large", size=length)
173
202
  elif "text/html" in content_type.lower():
174
- # A login wall or landing page instead of the file.
175
- entry.update(status="failed", reason="html_page")
203
+ # A login wall or landing page instead of the file: which one, for the record.
204
+ # A firewall's human verification page is told apart (Figshare's AWS WAF,
205
+ # 2026-11-08): the site stopped the request, the file may well exist.
206
+ evidence = _page_evidence(response)
207
+ headers = evidence.get("page_headers") or {}
208
+ challenged = "challenge" in (headers.get("x-amzn-waf-action"), headers.get("cf-mitigated"))
209
+ entry.update(status="failed", reason="verification_page" if challenged else "html_page", **evidence)
176
210
  else:
177
211
  name = _file_name(link.url, str(response.headers.get("content-disposition", "") or ""), taken,
178
212
  link.label, content_type)
@@ -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
@@ -177,11 +177,15 @@ class Api:
177
177
  from .entitlements import SHOW_BROWSER, request_action
178
178
 
179
179
  if action == SHOW_BROWSER:
180
+ # Asked for from a reminder, or from the paper on the card at any
181
+ # time while it has a browser (user request, 2026-11-08).
180
182
  state = read_state() or {}
181
- if (state.get("status") != "running" or not state.get("attention")
183
+ if (state.get("status") != "running"
182
184
  or str(state.get("current") or "") != current
183
185
  or str(state.get("run_id") or "") != run_id):
184
- return "当前没有等待处理的下载浏览器"
186
+ return "当前没有正在下载的浏览器"
187
+ if not state.get("attention") and state.get("channel"):
188
+ return "这一篇在查开放来源,没有打开浏览器"
185
189
  if sys.platform == "darwin":
186
190
  from .browser.foreground import activate_mac
187
191