papersearch 0.7.2 → 0.8.0

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 (177) hide show
  1. package/LICENSE-paper-search-mcp-nodejs +24 -0
  2. package/NOTICE +8 -37
  3. package/README.en.md +7 -3
  4. package/README.fr.md +268 -0
  5. package/README.ja.md +268 -0
  6. package/README.ko.md +268 -0
  7. package/README.md +7 -3
  8. package/README.zh-Hant.md +268 -0
  9. package/dist/capabilities/download/batch/batch.d.ts +16 -1
  10. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  11. package/dist/capabilities/download/batch/batch.js +669 -53
  12. package/dist/capabilities/download/batch/batch.js.map +1 -1
  13. package/dist/capabilities/download/batch/batchFolder.d.ts.map +1 -1
  14. package/dist/capabilities/download/batch/batchFolder.js +4 -3
  15. package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
  16. package/dist/capabilities/download/batch/batchSummary.js +1 -1
  17. package/dist/capabilities/download/batch/batchSummary.js.map +1 -1
  18. package/dist/capabilities/download/batch/networkLoss.d.ts +12 -3
  19. package/dist/capabilities/download/batch/networkLoss.d.ts.map +1 -1
  20. package/dist/capabilities/download/batch/networkLoss.js +25 -4
  21. package/dist/capabilities/download/batch/networkLoss.js.map +1 -1
  22. package/dist/capabilities/download/batch/resume.d.ts +7 -0
  23. package/dist/capabilities/download/batch/resume.d.ts.map +1 -1
  24. package/dist/capabilities/download/batch/resume.js +50 -9
  25. package/dist/capabilities/download/batch/resume.js.map +1 -1
  26. package/dist/capabilities/download/content/markdown/pro.d.ts +6 -0
  27. package/dist/capabilities/download/content/markdown/pro.d.ts.map +1 -1
  28. package/dist/capabilities/download/content/markdown/pro.js.map +1 -1
  29. package/dist/capabilities/download/content/markdown/shortfall.d.ts +8 -5
  30. package/dist/capabilities/download/content/markdown/shortfall.d.ts.map +1 -1
  31. package/dist/capabilities/download/content/markdown/shortfall.js +27 -15
  32. package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
  33. package/dist/capabilities/download/content/markdown/step.d.ts +9 -0
  34. package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
  35. package/dist/capabilities/download/content/markdown/step.js +42 -2
  36. package/dist/capabilities/download/content/markdown/step.js.map +1 -1
  37. package/dist/capabilities/download/content/markdown/types.d.ts +10 -1
  38. package/dist/capabilities/download/content/markdown/types.d.ts.map +1 -1
  39. package/dist/capabilities/download/handler.d.ts.map +1 -1
  40. package/dist/capabilities/download/handler.js +13 -5
  41. package/dist/capabilities/download/handler.js.map +1 -1
  42. package/dist/capabilities/download/outputLayout.d.ts.map +1 -1
  43. package/dist/capabilities/download/outputLayout.js +3 -1
  44. package/dist/capabilities/download/outputLayout.js.map +1 -1
  45. package/dist/capabilities/download/tools.js +2 -2
  46. package/dist/capabilities/download/tools.js.map +1 -1
  47. package/dist/capabilities/download/types.d.ts +9 -1
  48. package/dist/capabilities/download/types.d.ts.map +1 -1
  49. package/dist/cli.js +3 -1
  50. package/dist/cli.js.map +1 -1
  51. package/dist/infrastructure/runlog/RunLedger.d.ts +7 -0
  52. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  53. package/dist/infrastructure/runlog/RunLedger.js +13 -0
  54. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  55. package/dist/infrastructure/runlog/failureClass.d.ts +17 -9
  56. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  57. package/dist/infrastructure/runlog/failureClass.js +89 -56
  58. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  59. package/dist/infrastructure/school/SchoolAttempt.d.ts +11 -0
  60. package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
  61. package/dist/infrastructure/school/SchoolAttempt.js +107 -59
  62. package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
  63. package/dist/infrastructure/school/SchoolMcpClient.d.ts +7 -2
  64. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  65. package/dist/infrastructure/school/SchoolMcpClient.js +30 -7
  66. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  67. package/dist/infrastructure/school/SchoolProgress.d.ts +2 -0
  68. package/dist/infrastructure/school/SchoolProgress.d.ts.map +1 -1
  69. package/dist/infrastructure/school/SchoolProgress.js +2 -0
  70. package/dist/infrastructure/school/SchoolProgress.js.map +1 -1
  71. package/dist/infrastructure/school/SchoolReadiness.d.ts +2 -0
  72. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  73. package/dist/infrastructure/school/SchoolReadiness.js +2 -0
  74. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  75. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  76. package/dist/infrastructure/school/SchoolResultNormalizer.js +4 -0
  77. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  78. package/dist/infrastructure/school/index.d.ts +2 -2
  79. package/dist/infrastructure/school/index.d.ts.map +1 -1
  80. package/dist/infrastructure/school/index.js +1 -1
  81. package/dist/infrastructure/school/index.js.map +1 -1
  82. package/dist/infrastructure/school/types.d.ts +52 -3
  83. package/dist/infrastructure/school/types.d.ts.map +1 -1
  84. package/dist/infrastructure/school/types.js.map +1 -1
  85. package/dist/management/failures/index.d.ts +28 -2
  86. package/dist/management/failures/index.d.ts.map +1 -1
  87. package/dist/management/failures/index.js +83 -21
  88. package/dist/management/failures/index.js.map +1 -1
  89. package/package.json +7 -2
  90. package/school/NOTICE +3 -2
  91. package/school/paper_search_school/adapters/__init__.py +2 -0
  92. package/school/paper_search_school/adapters/aps/__init__.py +3 -6
  93. package/school/paper_search_school/adapters/base.py +18 -0
  94. package/school/paper_search_school/adapters/copernicus/__init__.py +2 -7
  95. package/school/paper_search_school/adapters/elsevier/__init__.py +50 -1
  96. package/school/paper_search_school/adapters/frontiers/__init__.py +41 -2
  97. package/school/paper_search_school/adapters/ieee/__init__.py +6 -4
  98. package/school/paper_search_school/adapters/iop/__init__.py +8 -0
  99. package/school/paper_search_school/adapters/jama/__init__.py +8 -0
  100. package/school/paper_search_school/adapters/lww/__init__.py +14 -6
  101. package/school/paper_search_school/adapters/mdpi/__init__.py +12 -7
  102. package/school/paper_search_school/adapters/neurology/__init__.py +5 -2
  103. package/school/paper_search_school/adapters/optica/__init__.py +2 -9
  104. package/school/paper_search_school/adapters/oup/__init__.py +27 -4
  105. package/school/paper_search_school/adapters/platforms/__init__.py +4 -1
  106. package/school/paper_search_school/adapters/platforms/atypon/__init__.py +8 -0
  107. package/school/paper_search_school/adapters/platforms/jstage/__init__.py +64 -0
  108. package/school/paper_search_school/adapters/sage/__init__.py +4 -1
  109. package/school/paper_search_school/adapters/thieme/__init__.py +6 -11
  110. package/school/paper_search_school/api_keys.py +63 -13
  111. package/school/paper_search_school/assets/api_keys.json +14 -0
  112. package/school/paper_search_school/assets/capsule.html +274 -158
  113. package/school/paper_search_school/assets/capsule_en.json +99 -98
  114. package/school/paper_search_school/assets/capsule_fr.json +100 -99
  115. package/school/paper_search_school/assets/capsule_ja.json +99 -98
  116. package/school/paper_search_school/assets/capsule_ko.json +99 -98
  117. package/school/paper_search_school/assets/capsule_zh-Hant.json +94 -97
  118. package/school/paper_search_school/browser/batch_session.py +1 -1
  119. package/school/paper_search_school/browser/challenge/__init__.py +12 -9
  120. package/school/paper_search_school/browser/challenge/continuation.py +65 -0
  121. package/school/paper_search_school/browser/challenge/handlers/__init__.py +1 -0
  122. package/school/paper_search_school/browser/challenge/handlers/aws_waf.py +260 -0
  123. package/school/paper_search_school/browser/challenge/handlers/recaptcha_hcaptcha.py +167 -0
  124. package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +100 -0
  125. package/school/paper_search_school/browser/challenge/handlers/turnstile.py +174 -0
  126. package/school/paper_search_school/browser/challenge/kinds.py +203 -0
  127. package/school/paper_search_school/browser/challenge/local/__init__.py +1 -0
  128. package/school/paper_search_school/browser/challenge/{interaction.py → local/interaction.py} +94 -13
  129. package/school/paper_search_school/browser/challenge/{pointer.py → local/pointer.py} +2 -2
  130. package/school/paper_search_school/browser/challenge/local/prompt.py +283 -0
  131. package/school/paper_search_school/browser/challenge/local/submission.py +33 -0
  132. package/school/paper_search_school/browser/challenge/services/__init__.py +1 -0
  133. package/school/paper_search_school/browser/challenge/services/solver.py +272 -0
  134. package/school/paper_search_school/cli_config.py +10 -5
  135. package/school/paper_search_school/cold_start.py +22 -11
  136. package/school/paper_search_school/config.py +11 -10
  137. package/school/paper_search_school/download_diagnostics.py +7 -2
  138. package/school/paper_search_school/engine/access_rules.py +15 -5
  139. package/school/paper_search_school/engine/batch.py +55 -15
  140. package/school/paper_search_school/engine/batch_access.py +59 -21
  141. package/school/paper_search_school/engine/batch_capture.py +215 -18
  142. package/school/paper_search_school/engine/batch_common.py +3 -0
  143. package/school/paper_search_school/engine/batch_diagnostics.py +25 -5
  144. package/school/paper_search_school/engine/batch_institution.py +168 -32
  145. package/school/paper_search_school/engine/batch_login.py +223 -16
  146. package/school/paper_search_school/engine/batch_pdf_urls.py +38 -7
  147. package/school/paper_search_school/engine/batch_waits.py +179 -12
  148. package/school/paper_search_school/engine/bridge.py +44 -7
  149. package/school/paper_search_school/engine/fulltext_page.py +45 -7
  150. package/school/paper_search_school/engine/router.py +18 -2
  151. package/school/paper_search_school/entitlements.py +1 -1
  152. package/school/paper_search_school/orchestrator.py +44 -18
  153. package/school/paper_search_school/pdf_utils.py +25 -16
  154. package/school/paper_search_school/progress_capsule.py +36 -6
  155. package/school/paper_search_school/progress_reporter.py +71 -13
  156. package/school/paper_search_school/progress_view.py +64 -44
  157. package/school/paper_search_school/publishers/builtin/iop.json +2 -1
  158. package/school/paper_search_school/publishers/builtin/neurology.json +4 -2
  159. package/school/paper_search_school/publishers/builtin/sage.json +4 -2
  160. package/school/paper_search_school/publishers/builtin/thieme.json +3 -1
  161. package/school/paper_search_school/publishers/site.py +12 -4
  162. package/school/paper_search_school/school_switch.py +34 -52
  163. package/school/paper_search_school/school_test.py +1 -1
  164. package/school/paper_search_school/server.py +24 -11
  165. package/school/paper_search_school/user_settings.py +13 -0
  166. package/school/pyproject.toml +1 -0
  167. package/skills/paper-search/SKILL.md +107 -107
  168. package/skills/paper-search/references/browser-download.md +102 -101
  169. package/skills/paper-search/references/capability-routing.md +89 -89
  170. package/skills/paper-search/references/cli-contract.md +78 -78
  171. package/skills/paper-search/references/federation-support.md +172 -172
  172. package/skills/paper-search/references/management-layer.md +78 -78
  173. package/skills/paper-search/references/publisher-support.md +38 -38
  174. package/skills/paper-search/references/school-setup.md +56 -55
  175. package/skills/paper-search/references/setup.md +20 -20
  176. package/skills/paper-search/references/troubleshooting.md +12 -12
  177. package/school/paper_search_school/browser/challenge/prompt.py +0 -154
@@ -14,7 +14,8 @@ from urllib.parse import urlparse
14
14
 
15
15
  from ..entitlements import UserMarkedNoEntitlement
16
16
  from ..browser import watchdog
17
- from ..browser.challenge import detection as challenges, interaction as challenge_interaction
17
+ from ..browser.challenge import detection as challenges
18
+ from ..browser.challenge.local import interaction as challenge_interaction
18
19
  from .batch_common import (AWAY_WAIT_SEC, DownloadResult, _IP_BLOCK_STATUS_CODES, _observe_preview)
19
20
 
20
21
  class UserWaitMixin:
@@ -268,6 +269,8 @@ class UserWaitMixin:
268
269
  self._event(result, "ip_blocked_response", f"{suspect} | no PDF after waiting ({shown or 'nothing shown'})")
269
270
  return False
270
271
  finally:
272
+ if automatic.get("service_cleanup") is not None:
273
+ automatic["service_cleanup"].close()
271
274
  self._verification_attention(result, None)
272
275
  activity.automatic_for(0)
273
276
  result._attention_page = None
@@ -412,6 +415,9 @@ class UserWaitMixin:
412
415
  An absent/loading widget stays automatic, including late arrivals. A
413
416
  visible widget we cannot operate hands off within the existing budget.
414
417
  """
418
+ host = (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower()
419
+ if self._is_idp_host(host):
420
+ return False
415
421
  now = time.time()
416
422
  if not attempt:
417
423
  attempt.update(started=now, attempts=0, retry_at=now + 2)
@@ -430,17 +436,31 @@ class UserWaitMixin:
430
436
  activity = getattr(result, "_page_activity", None)
431
437
  if activity is not None:
432
438
  activity.automatic_for(automatic_end - now)
439
+ if self._forward_checked_challenge(page, result, attempt, automatic_end):
440
+ return True
441
+ from ..browser.challenge.handlers import text_captcha
442
+ if text_captcha.find(page):
443
+ return self._continue_challenge(page, result, attempt, automatic_end, "image_code")
433
444
  if challenge_interaction.needs_manual_verification(page):
434
445
  widget = challenge_interaction.verification_widget(page, manual_only=True)
435
446
  if widget and not attempt.get("widget"):
436
447
  attempt["widget"] = widget # whose widget the user is asked to complete
437
448
  self._event(result, "challenge_observation", f"manual widget: {widget}")
438
- if self._press_confirm_control(page, result, attempt, deadline):
449
+ kind = challenge_interaction.challenge_kind(page)
450
+ if kind != "awswaf" and self._press_confirm_control(page, result, attempt, deadline):
439
451
  return True
440
- return False
452
+ return self._continue_challenge(page, result, attempt, automatic_end, kind)
453
+ if now >= attempt["handoff_at"] and challenge_interaction.challenge_kind(page) == "turnstile":
454
+ return self._continue_challenge(page, result, attempt, automatic_end, "turnstile")
441
455
  if ((attempt["attempts"] >= 2 and now >= attempt["retry_at"])
442
456
  or (attempt.get("unavailable") and now >= attempt["handoff_at"])):
443
- return False
457
+ return self._continue_challenge(page, result, attempt, automatic_end,
458
+ challenge_interaction.challenge_kind(page))
459
+ if attempt.get("managed") and now >= attempt["handoff_at"]:
460
+ # With no visible control there is no human action to request. Record
461
+ # unsupported service continuation once, then retain the fixed wait.
462
+ self._continue_challenge(page, result, attempt, automatic_end,
463
+ challenge_interaction.challenge_kind(page))
444
464
  if now >= automatic_end:
445
465
  # No observed user action: the caller ends at its original bound.
446
466
  return True
@@ -494,6 +514,27 @@ class UserWaitMixin:
494
514
  "widget events: " + " -> ".join(names[-6:]))
495
515
  return True
496
516
 
517
+ def _continue_challenge(self, page: Any, result: DownloadResult, attempt: dict,
518
+ deadline: float, kind: str) -> bool:
519
+ """One bounded service continuation per verification wait and provider."""
520
+ from ..browser.challenge.continuation import Limits, resume
521
+
522
+ tried = attempt.setdefault("service_tried", set())
523
+ if kind in tried:
524
+ return False
525
+ tried.add(kind)
526
+ def checkpoint() -> None:
527
+ self._check_user_decision(result, page)
528
+ host = (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower()
529
+ if self._is_idp_host(host):
530
+ from ..browser.challenge.continuation import Expired
531
+ raise Expired
532
+ limits = Limits(time.monotonic() + max(0, deadline - time.time()),
533
+ self._captcha_budget, checkpoint,
534
+ attempt.setdefault("service_cleanup", ExitStack()))
535
+ return resume(page, self.config, kind=kind, limits=limits,
536
+ observation=lambda note: self._event(result, "challenge_observation", note))
537
+
497
538
  def _recover_stuck_widget(self, page: Any, result: DownloadResult, attempt: dict[str, Any]) -> bool:
498
539
  """A widget that reported failure or expired gets one fresh page.
499
540
 
@@ -534,7 +575,7 @@ class UserWaitMixin:
534
575
  ``True`` keeps the automatic wait going; the page's own change still
535
576
  decides whether verification ended.
536
577
  """
537
- from ..browser.challenge import prompt as prompt_control
578
+ from ..browser.challenge.local import prompt as prompt_control
538
579
 
539
580
  if not prompt_control.enabled() or attempt.get("confirmed"):
540
581
  return False
@@ -546,16 +587,129 @@ class UserWaitMixin:
546
587
  if budget <= 0.5:
547
588
  return False
548
589
  reasons: list[str] = []
549
- outcome = prompt_control.click_confirm_control(
550
- page, timeout_ms=int(min(prompt_control.PRESS_LIMIT_SEC, budget) * 1000),
551
- checkpoint=lambda: self._check_user_decision(result, page),
552
- observation=reasons.append)
590
+ # A provider's widget is on the page but its control is not rendered yet:
591
+ # keep looking for a little while before handing the page out. Not past the
592
+ # time the user is to be asked (``handoff_at``, browser_stall_notify_after),
593
+ # and not once the page has moved on: looking up to 15 s regardless kept a
594
+ # page that let the reader through in 0.2 s on screen as a verification and
595
+ # asked the user to complete it, and every reminder came late (Windows, real
596
+ # Chrome, 2026-11-25; since fdebe5b5).
597
+ widget = self._verification_widget_page(page)
598
+ try_until = min(deadline, time.time() + prompt_control.PRESS_LIMIT_SEC
599
+ + (prompt_control.AWAIT_LIMIT_SEC if widget else 0.0))
600
+ if remaining is not None:
601
+ try_until = min(try_until, time.time() + max(0.0, remaining))
602
+ # The first look as before; looking again only until the user is to be asked.
603
+ look_again_until = try_until
604
+ if widget and attempt.get("handoff_at"):
605
+ look_again_until = min(try_until, float(attempt["handoff_at"]))
606
+ outcome = "absent"
607
+ first = True
608
+ while True:
609
+ if not first and not (self._challenge_shell(page) or self._is_challenge_page(page)):
610
+ # Let through meanwhile: the wait sees the page and ends without asking anyone.
611
+ self._event(result, "challenge_observation", "confirmation control: page moved on")
612
+ return True
613
+ room = try_until - time.time()
614
+ if room <= 0.5:
615
+ break
616
+ outcome = prompt_control.click_confirm_control(
617
+ page, timeout_ms=int(min(prompt_control.PRESS_LIMIT_SEC, room) * 1000),
618
+ checkpoint=lambda: self._check_user_decision(result, page),
619
+ observation=reasons.append)
620
+ first = False
621
+ if (outcome == "clicked" or not widget
622
+ or time.time() + prompt_control.AWAIT_STEP_SEC >= look_again_until):
623
+ break
624
+ page.wait_for_timeout(int(prompt_control.AWAIT_STEP_SEC * 1000))
553
625
  detail = f"confirmation control: {outcome}"
554
626
  if reasons:
555
627
  detail += f" ({', '.join(dict.fromkeys(reasons))})"
556
628
  self._event(result, "challenge_observation", detail)
629
+ if outcome == "clicked":
630
+ self._await_check_then_forward(page, result, attempt, deadline, prompt_control)
557
631
  return outcome == "clicked"
558
632
 
633
+ def _await_check_then_forward(self, page: Any, result: DownloadResult, attempt: dict[str, Any],
634
+ deadline: float, prompt_control: Any) -> None:
635
+ """After the box is pressed: wait for it to read checked, then press the page's own
636
+ forward button once (JAMA's "Take me to my Content", which must be pressed within a
637
+ minute of checking or the token expires while the wait goes on)."""
638
+ reasons: list[str] = []
639
+ checked = prompt_control.confirm_checked(page)
640
+ refresh_left = prompt_control.REFRESH_LIMIT
641
+ rounds = prompt_control.REFRESH_LIMIT + 1
642
+ for round_index in range(rounds):
643
+ if checked or self._check_user_decision(result, page):
644
+ break
645
+ if prompt_control.expired(page) and refresh_left > 0:
646
+ refresh_left -= 1
647
+ if prompt_control.press_refresh(page, timeout_ms=2500, observation=reasons.append):
648
+ self._event(result, "challenge_observation",
649
+ f"interstitial expired: refreshed ({refresh_left} left)")
650
+ page.wait_for_timeout(1500)
651
+ continue
652
+ if round_index and not attempt.get("repressed"):
653
+ attempt["repressed"] = True
654
+ prompt_control.click_confirm_control(
655
+ page, timeout_ms=2000,
656
+ checkpoint=lambda: self._check_user_decision(result, page),
657
+ observation=reasons.append)
658
+ budget_end = min(deadline, time.time() + prompt_control.CHECKED_LIMIT_SEC)
659
+ while time.time() < budget_end:
660
+ if self._check_user_decision(result, page):
661
+ break
662
+ if prompt_control.confirm_checked(page):
663
+ checked = True
664
+ break
665
+ from ..browser.challenge.handlers.recaptcha_hcaptcha import has_grid
666
+ if has_grid(page):
667
+ self._event(result, "challenge_observation", "picture grid appeared; continue with service")
668
+ return
669
+ page.wait_for_timeout(400)
670
+ if checked:
671
+ break
672
+ detail = f"confirmation checked: {checked}"
673
+ if reasons:
674
+ detail += f" ({', '.join(dict.fromkeys(reasons))})"
675
+ self._event(result, "challenge_observation", detail)
676
+ if not checked:
677
+ return
678
+ self._forward_checked_challenge(page, result, attempt, deadline)
679
+
680
+ def _forward_checked_challenge(self, page: Any, result: DownloadResult,
681
+ attempt: dict[str, Any], deadline: float) -> bool:
682
+ """Observe delayed acknowledgements even after image solving handed back.
683
+
684
+ This is also called in manual wait: a user-completed widget gets the same
685
+ outer submission. A successful press is remembered only for this wait.
686
+ """
687
+ from ..browser.challenge.local import prompt as prompt_control
688
+ host = (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower()
689
+ if self._is_idp_host(host) or not prompt_control.confirm_checked(page):
690
+ return False
691
+ if attempt.get("forwarded"):
692
+ return True
693
+ if time.time() >= deadline or self._check_user_decision(result, page):
694
+ return False
695
+ remaining = watchdog.operation_remaining()
696
+ room = deadline - time.time()
697
+ if remaining is not None:
698
+ room = min(room, remaining)
699
+ if room <= 0:
700
+ return False
701
+ reasons: list[str] = []
702
+ outcome = prompt_control.press_forward(
703
+ page, timeout_ms=max(1, int(min(prompt_control.FORWARD_LIMIT_SEC, room) * 1000)),
704
+ observation=reasons.append)
705
+ if outcome == "pressed":
706
+ attempt["forwarded"] = True
707
+ if outcome != attempt.get("forward_outcome"):
708
+ self._event(result, "challenge_observation",
709
+ f"forward control: {outcome} ({'; '.join(reasons)})")
710
+ attempt["forward_outcome"] = outcome
711
+ return True # checked is acknowledgement; the enclosing wait checks access
712
+
559
713
  def _verification_attention(self, result: DownloadResult, deadline: float | None) -> None:
560
714
  from .. import progress_reporter
561
715
  key = f"verification:{id(self)}:{result.doi}"
@@ -577,11 +731,13 @@ class UserWaitMixin:
577
731
  progress_reporter.update_attention_deadline(key, deadline)
578
732
 
579
733
  def _wait_for_challenge(self, page: Any, result: DownloadResult, *, deadline: float | None = None,
580
- until: Callable[[], bool] | None = None) -> bool:
734
+ until: Callable[[], bool] | None = None, hand_over_only: bool = False) -> bool:
581
735
  """Wait while a verification page is up, until ``_wait_deadline``. ``until``: the
582
736
  wait ends, as passed, once it says what it waits for has arrived though the page
583
737
  is still up (the PDF's answer, captured while ScienceDirect's tab stayed on "Just
584
- a moment...": two articles failed with the PDF in hand, 2026-11-21)."""
738
+ a moment...": two articles failed with the PDF in hand, 2026-11-21).
739
+ ``hand_over_only``: the PDF step's verification ends, not passed, where the wait on
740
+ the user would begin; its caller signs in at the article and asks for the PDF again."""
585
741
  interaction = ExitStack()
586
742
  activity, activity_owned = self._observe_page_activity(page, result)
587
743
  automatic: dict[str, Any] = {}
@@ -609,6 +765,7 @@ class UserWaitMixin:
609
765
  if not waited:
610
766
  deadline = self._wait_deadline(result, deadline)
611
767
  started, phase_before = time.time(), self._phase(result, "verification")
768
+ self._note_challenge_type(page, result, title_and_url_only=bool(shell))
612
769
  waited = True
613
770
  result.state = "challenge_or_viewer_timeout"
614
771
  if verification_wait is not None:
@@ -621,10 +778,17 @@ class UserWaitMixin:
621
778
  if time.time() >= deadline:
622
779
  break
623
780
  result._attention_page = page
624
- auto_pending = not manual and self._automatic_challenge_step(page, result, automatic, deadline)
781
+ auto_pending = (self._forward_checked_challenge(page, result, automatic, deadline)
782
+ if manual else self._automatic_challenge_step(page, result, automatic, deadline))
625
783
  if not auto_pending:
626
784
  activity.automatic_for(0)
627
785
  activity.check()
786
+ if not auto_pending and not manual and hand_over_only:
787
+ # Not passed by the program's own steps (the captcha service's
788
+ # included): no wait on the user in the PDF step (ba77bb4e; the
789
+ # parameter went with Bright Data in ead266c9, its callers kept it).
790
+ self._note_challenge_type(page, result)
791
+ return False
628
792
  if not auto_pending and not manual:
629
793
  result._attention_page = page
630
794
  interaction.enter_context(watchdog.pause_operation())
@@ -665,9 +829,12 @@ class UserWaitMixin:
665
829
  if passed:
666
830
  result.state = state_before
667
831
  else:
832
+ self._note_challenge_type(page, result)
668
833
  self._wait_ran_out(result)
669
834
  return passed
670
835
  finally:
836
+ if automatic.get("service_cleanup") is not None:
837
+ automatic["service_cleanup"].close()
671
838
  self._verification_attention(result, None)
672
839
  activity.automatic_for(0)
673
840
  if verification_wait is not None:
@@ -48,7 +48,10 @@ _FAILURE_KINDS = {
48
48
  "publisher_unreachable": ("publisher_unreachable", "review_publisher_error"),
49
49
  "sso_required": ("paywall", "login_required"),
50
50
  "institution_pdf_entitlement_missing": ("paywall", "review_entitlement"),
51
- "challenge_or_viewer_timeout": ("download_timeout", "review_browser"),
51
+ # The site's human verification stayed up until the wait ran out: not passed, the site's block
52
+ # (被网站拦截), not a page that hung (JAMA's crawl-prevention reCAPTCHA, gut.bmj.com's Cloudflare
53
+ # check after ten articles in a row; reported as download_timeout, 原因不明, until 2026-11-23).
54
+ "challenge_or_viewer_timeout": ("captcha_required", "review_access"),
52
55
  "ip_blocked": ("access_blocked", "review_access"),
53
56
  "unexpected_error": ("source_exception", ""),
54
57
  # The user closed the download browser (or it quit) before the article was done.
@@ -74,9 +77,15 @@ _FAILURE_KINDS = {
74
77
  "doi_not_registered": ("doi_not_registered", "review_publisher_error"),
75
78
  # A site without a publisher profile: the shared rules found no institution entry.
76
79
  "generic_institution_entry_missing": ("generic_institution_entry_missing", "review_publisher_profiles"),
80
+ # A publisher with rules of its own: its article page showed no login entry the rules found
81
+ # (reported as download_failed until 2026-11-22, "原因不明"; Thieme's Thrombosis and Haemostasis).
82
+ "publisher_institution_entry_missing": ("publisher_institution_entry_missing", "review_browser"),
77
83
  # The site's page shows no way to any school's login (an open-access site, one with personal
78
84
  # accounts only): no school login was started (user, 2026-11-18).
79
85
  "no_institution_entry": ("no_institution_entry", ""),
86
+ # An article open to all whose page names no PDF anywhere: its site gives it as a web page only
87
+ # (CAA Reviews, 2026-11-24; 原因不明 · 没取到 PDF before).
88
+ "pdf_not_offered": ("pdf_not_offered", ""),
80
89
  **{code: (code, "review_browser") for code in _LOGIN_FAILURE_CODES},
81
90
  }
82
91
 
@@ -124,7 +133,13 @@ def _failure_reason_code(result: Any) -> str:
124
133
  # A timeout is the user's only where the user had a step to take
125
134
  # (ADR 0012); a wait that ended on the publisher's pages means the
126
135
  # program never reached the login.
127
- reason_code = "login_timeout" if wait_page in ("school_login", "school_choice") else "login_not_reached"
136
+ if wait_page == "institution_chooser":
137
+ # The chooser opened and never named the school: had it been there,
138
+ # the program would have picked it (Glasgow Caledonian, 2026-11-24).
139
+ # No route at this publisher, not a wait the user missed.
140
+ reason_code = "institution_federation_unavailable"
141
+ else:
142
+ reason_code = "login_timeout" if wait_page in ("school_login", "school_choice") else "login_not_reached"
128
143
  elif reason_code == "sso_required" and getattr(result, "_user_wait_expired", False):
129
144
  reason_code = "login_timeout" # the login waited on the user until its time was up
130
145
  if getattr(result, "_download_limit", "") and reason_code in _PDF_NOT_ARRIVED:
@@ -316,6 +331,7 @@ def _try_builtin_institutional(
316
331
  # Without a profile there is no site to build one for.
317
332
  return _failure(doi, "doi_not_resolved") if profile else _unsupported_publisher(doi)
318
333
 
334
+ from ..adapters.base import adapter_class_for as _adapter_class_for
319
335
  from ..publishers.profiles import infer_publisher_profile_from_url, journal_platform
320
336
  hosted = (infer_publisher_profile_from_url(resolved_url, profiles=profiles)
321
337
  if profiles is not None else infer_publisher_profile_from_url(resolved_url))
@@ -327,6 +343,12 @@ def _try_builtin_institutional(
327
343
  # Academic, 2026-11-14). A journal listed in _JOURNAL_PLATFORMS keeps its entry.
328
344
  log.info(" [Institutional] DOI resolves to %s's site: its rules, not %s's", hosted.name, profile.name)
329
345
  profile = hosted
346
+ elif hosted is None and _adapter_class_for(profile).covers_site(resolved_url) is False:
347
+ # Another site under the publisher's DOI prefix that its rules were not written for
348
+ # (the AMA Journal of Ethics beside JAMA Network, 2026-11-23): the shared rules of a
349
+ # site without a profile, below.
350
+ log.info(" [Institutional] DOI resolves to a site %s's rules do not cover", profile.name)
351
+ profile = None
330
352
  if not profile:
331
353
  # No profile names the site: the publisher driver with the shared rules
332
354
  # only, on the site the DOI resolves to.
@@ -352,7 +374,9 @@ def _try_builtin_institutional(
352
374
  remembered = entitlements.decision_for(doi, publisher_name, identity=identity)
353
375
  except Exception:
354
376
  remembered = None
355
- if remembered and remembered.get("decision") == "skip":
377
+ # The user's marks were made with the default school: another one's visit is not skipped by them (没权限时换下一所学校).
378
+ from .. import school_switch
379
+ if remembered and remembered.get("decision") == "skip" and not config.get(school_switch.MARKS_OFF):
356
380
  log.info(" [Institutional] Skipped: %s marked as no access", remembered.get("key"))
357
381
  return {"success": False, "identifier": doi, "doi": doi, "source": "institutional:entitlement_memory",
358
382
  "error_type": "no_entitlement", "reason": "user_marked_no_entitlement",
@@ -397,6 +421,8 @@ def _try_builtin_institutional(
397
421
  failure["supplements"] = result["supplements"]
398
422
  if isinstance(result.get("fulltext_page"), dict):
399
423
  failure["fulltext_page"] = result["fulltext_page"]
424
+ if isinstance(result.get("same_name_entries"), int):
425
+ failure["same_name_entries"] = result["same_name_entries"]
400
426
  if failure["error_type"] in _LOGIN_FAILURE_CODES:
401
427
  failure.update(reason=failure["error_type"], action="review_browser")
402
428
  if (result.get("error_type") == "paywall"
@@ -428,13 +454,16 @@ def _try_builtin_institutional(
428
454
  denial = next((f for f in failures if f.get("reason_code") ==
429
455
  "institution_pdf_entitlement_missing"), None)
430
456
  primary = next((f for code in ("source_exception", "unsupported_platform", "article_not_yet_published",
431
- "generic_institution_entry_missing", "no_institution_entry",
432
- "publisher_content_error", "access_blocked", *_LOGIN_FAILURE_CODES,
433
- "download_timeout")
457
+ "generic_institution_entry_missing", "publisher_institution_entry_missing",
458
+ "no_institution_entry",
459
+ "publisher_content_error", "access_blocked", "captcha_required",
460
+ *_LOGIN_FAILURE_CODES, "download_timeout")
434
461
  for f in failures if f["error_type"] == code), denial or failures[-1])
435
462
  result = {"success": False, "identifier": doi, "doi": doi, "source": "institutional",
436
463
  "error_type": primary["error_type"], "reason": primary["reason"],
437
- "action": primary["action"], "source_failures": failures}
464
+ "action": primary["action"], "source_failures": failures,
465
+ **({"same_name_entries": entries} if (entries := max((f.get("same_name_entries") or 0
466
+ for f in failures), default=0)) > 1 else {})}
438
467
  if primary["error_type"] == "access_blocked":
439
468
  _remember_blocked_journal(doi, identity)
440
469
  if (primary["error_type"] == "institution_federation_unavailable" and manual_school
@@ -823,6 +852,9 @@ def _try_browser_batch_download(
823
852
  failure = {"success": False, "identifier": doi, "source": "institutional:browser",
824
853
  "error_type": error_type, "reason": error_type, "action": action,
825
854
  "artifacts": _browser_artifacts(result, profile)}
855
+ if int(getattr(result, "_same_name_entries", 0) or 0) > 1:
856
+ # The school's entries by one name, one chosen this time: the orchestrator takes the next if it did not do.
857
+ failure["same_name_entries"] = int(result._same_name_entries)
826
858
  if supplements_mode in ("with", "only"):
827
859
  failure["supplements"] = result.supplements
828
860
  if getattr(result, "fulltext_page", None) and reason_code != "institution_pdf_entitlement_missing" \
@@ -992,6 +1024,11 @@ def _browser_artifacts(result: Any, profile: Any) -> dict[str, str]:
992
1024
  wait_page = str(getattr(result, "login_wait_page", "") or "")
993
1025
  if wait_page in LOGIN_WAIT_PAGES:
994
1026
  artifacts["login_wait_page"] = wait_page
1027
+ # The kind of verification the item last waited on: a fixed word (``kinds.LABELS``).
1028
+ from ..browser.challenge.kinds import LABELS as CHALLENGE_TYPES
1029
+ challenge_type = str(getattr(result, "challenge_type", "") or "")
1030
+ if challenge_type in CHALLENGE_TYPES:
1031
+ artifacts["challenge_type"] = challenge_type
995
1032
  # The school's site the login stopped on: a host name only, for the message.
996
1033
  host = str(getattr(result, "_stopped_host", "") or "").lower()
997
1034
  if state == "idp_no_return_to_publisher" and re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)+", host) and len(host) <= 253:
@@ -62,6 +62,27 @@ _PAGE_DOI_JS = """() => {
62
62
  }"""
63
63
 
64
64
 
65
+ def paragraph_text_js(paragraphs: str, outside: str, threshold: str, *, root: str = "") -> str:
66
+ """A ``fulltext_shown_js`` that counts the article's paragraph text: the elements
67
+ ``paragraphs`` selects (inside the first ``root`` when one is given: no full text without
68
+ it), those inside ``outside`` aside, their text's length compared with ``threshold``
69
+ ("> 500", ">= 200": each adapter's own). The selectors are written in single quotes."""
70
+ if not re.fullmatch(r">=? \d+", threshold):
71
+ raise ValueError(f"threshold is a comparison with a number: {threshold!r}")
72
+ if any("'" in selector or "\\" in selector for selector in (paragraphs, outside, root)):
73
+ raise ValueError("a selector with a quote or a backslash")
74
+ lines = ["() => {"]
75
+ scope = "document"
76
+ if root:
77
+ lines += [f" const root = document.querySelector('{root}');", " if (!root) return false;"]
78
+ scope = "root"
79
+ lines.append(f" const text = [...{scope}.querySelectorAll('{paragraphs}')]")
80
+ if outside:
81
+ lines.append(f" .filter((p) => !p.closest('{outside}'))")
82
+ lines += [" .reduce((total, p) => total + (p.textContent || '').length, 0);", f" return text {threshold};", "}"]
83
+ return "\n".join(lines)
84
+
85
+
65
86
  # For an adapter's ``fulltext_prepare_js`` on a MathJax page that keeps no MathML in the
66
87
  # DOM (ScienceDirect's MathJax 4, Wiley's lazy MathJax 4.1, 2026-11-14): each formula's
67
88
  # source written onto its element as data-original-mathml, which PaperSearch reads. A
@@ -92,6 +113,16 @@ MATHJAX_SOURCES_JS = r"""async () => {
92
113
  }"""
93
114
 
94
115
 
116
+ def _names_doi(named: str, doi: str) -> bool:
117
+ """Whether the DOI a page names (``_PAGE_DOI_JS``) is this one, or the page names none. A
118
+ DOI written as the end of a sentence is the same DOI: the AMA Journal of Ethics writes
119
+ "10.1001/amajethics.2025.884." in its citation_doi too, and its pages were taken for another
120
+ article's (other_article, 2026-11-22)."""
121
+ named = normalize_doi(named).lower()
122
+ wanted = (normalize_doi(doi) or "").lower()
123
+ return not named or named == wanted or named.rstrip(".") == wanted.rstrip(".")
124
+
125
+
95
126
  def page_dir(output_dir: Path, doi: str) -> Path:
96
127
  return Path(output_dir) / (re.sub(r"[^A-Za-z0-9._-]+", "_", doi) + "_fulltext_page")
97
128
 
@@ -192,8 +223,7 @@ def read_page(page: Any, doi: str, adapter: Any, *, sample: bool = False) -> tup
192
223
  shown_js = _SAMPLE_SHOWN_JS if general else own
193
224
  if not wait_stable(page):
194
225
  return None, "page_not_stable"
195
- named = normalize_doi(str(page.evaluate(_PAGE_DOI_JS) or "")).lower()
196
- if named and named != (normalize_doi(doi) or "").lower():
226
+ if not _names_doi(str(page.evaluate(_PAGE_DOI_JS) or ""), doi):
197
227
  return None, "other_article"
198
228
  if not sample:
199
229
  pdf_only = str(page.evaluate(_PDF_ONLY_JS) or "")
@@ -321,11 +351,19 @@ def save_page(read: dict[str, Any], output_dir: Path, doi: str, request: Any, *,
321
351
  failed.append({"url": url, "reason": "not_an_image"})
322
352
  continue
323
353
  body = bytearray()
324
- for chunk in response.chunks():
325
- body.extend(chunk)
326
- if total + len(body) > MAX_BYTES or clock() > deadline:
327
- break
328
- else:
354
+ try:
355
+ whole = True
356
+ for chunk in response.chunks():
357
+ body.extend(chunk)
358
+ if total + len(body) > MAX_BYTES or clock() > deadline:
359
+ whole = False
360
+ break
361
+ except Exception as exc:
362
+ # A read that fails part way (PLOS's image host timing out, 2026-11-23) is recorded like
363
+ # one that could not start: this figure is missing, the page and the PDF go on.
364
+ failed.append({"url": url, "reason": type(exc).__name__})
365
+ continue
366
+ if whole:
329
367
  if not body:
330
368
  failed.append({"url": url, "reason": "empty"})
331
369
  continue
@@ -18,6 +18,20 @@ from ..publishers.profiles import PublisherProfile
18
18
 
19
19
  PDF_LINK_TEXT_MARKERS = ("pdf", "download pdf", "full text pdf", "view pdf")
20
20
  PDF_URL_MARKERS = (".pdf", "/pdf", "/epdf", "/pdfdirect", "/pdfft", "download=true")
21
+ # Open Journal Systems' galley file: /<journal>/article/download/<article>/<galley>[/<file>],
22
+ # an address with no "pdf" in it. Its citation_pdf_url and the galley's Download link are this
23
+ # address; the article's "View PDF" (/article/view/<article>/<galley>) is a page around the PDF
24
+ # (Via Medica's Reports of Practical Oncology and Radiotherapy: the click ended on that page and
25
+ # nothing was tried after it, 2026-11-23). The article part can be the article's name instead of
26
+ # its number (Fringe Global's JSIHS: /article/download/ai-and-edge-analytics-.../239/1341, 2026-11-24).
27
+ GALLEY_DOWNLOAD_PATH = re.compile(r"/article/download/[^/]+/\d+(?:/\d+)?/?$")
28
+ # An Open Journal Systems article page or its galley's page: /article/view/<article>[/<galley>].
29
+ OJS_VIEW_PATH = re.compile(r"/article/view/([^/]+)(?:/\d+)?/?$")
30
+ # bepress Digital Commons' file: /cgi/viewcontent.cgi?article=<n>&context=<journal>, its
31
+ # bepress_citation_pdf_url (Osgoode Hall Law Journal: not taken as a PDF address, 2026-11-24).
32
+ VIEWCONTENT_PATH = re.compile(r"/cgi/viewcontent\.cgi$")
33
+ # Platform paths that serve the article's file with no "pdf" in them.
34
+ PLATFORM_FILE_PATH = re.compile(f"{GALLEY_DOWNLOAD_PATH.pattern}|{VIEWCONTENT_PATH.pattern}")
21
35
  PDF_JS_DEFAULT_URL_RE = re.compile(
22
36
  r"PDFViewerApplicationOptions\.set\(\s*['\"]defaultUrl['\"]\s*,\s*['\"]([^'\"]+)['\"]",
23
37
  flags=re.IGNORECASE,
@@ -209,13 +223,15 @@ def is_pdf_candidate_url(profile: PublisherProfile, url: str) -> bool:
209
223
  if verdict is not None:
210
224
  return verdict
211
225
  lower = url.lower()
212
- return lower.endswith(".pdf") or any(marker.lower() in lower for marker in profile.pdf_url_markers)
226
+ return (lower.endswith(".pdf") or any(marker.lower() in lower for marker in profile.pdf_url_markers)
227
+ or bool(PLATFORM_FILE_PATH.search(urlparse(url).path)))
213
228
 
214
229
 
215
230
  def is_thieme_article_pdf_url(url: str, doi: str = "") -> bool:
216
231
  """Exclude account/reset URLs that merely carry a PDF return address."""
217
232
  parsed = urlparse(url.strip())
218
- match = re.fullmatch(r"/products/ejournals/pdf/(10\.1055/[^/]+)\.pdf",
233
+ # Any DOI: Thieme's own 10.1055 and those of the journals it took over (Schattauer's 10.1160).
234
+ match = re.fullmatch(r"/products/ejournals/pdf/(10\.\d{4,9}/[^/]+)\.pdf",
219
235
  unquote(parsed.path).lower())
220
236
  return (parsed.scheme == "https" and not parsed.username and not parsed.password
221
237
  and parsed.netloc.lower() in {"www.thieme-connect.de", "thieme-connect.de",
@@ -211,7 +211,7 @@ def resume_path() -> Path:
211
211
 
212
212
 
213
213
  def request_resume(key: str, batch_id: str) -> None:
214
- """The user asked the batch to go on with a publisher it holds (a DOI prefix)."""
214
+ """The user asked the batch to go on with a publisher it holds (its key: its name, else its DOI prefix)."""
215
215
  data = _read_json(resume_path())
216
216
  keys = list(data.get("keys") or []) if data.get("batch_id") == batch_id else []
217
217
  if key not in keys: