papersearch 0.7.3 → 0.8.1

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 (204) hide show
  1. package/NOTICE +8 -37
  2. package/README.fr.md +265 -0
  3. package/README.ja.md +265 -0
  4. package/README.ko.md +265 -0
  5. package/README.md +149 -148
  6. package/README.zh-Hant.md +265 -0
  7. package/README.zh.md +265 -0
  8. package/dist/capabilities/download/batch/batch.d.ts +20 -1
  9. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  10. package/dist/capabilities/download/batch/batch.js +1057 -208
  11. package/dist/capabilities/download/batch/batch.js.map +1 -1
  12. package/dist/capabilities/download/batch/batchFolder.d.ts.map +1 -1
  13. package/dist/capabilities/download/batch/batchFolder.js +3 -2
  14. package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
  15. package/dist/capabilities/download/batch/networkLoss.d.ts +11 -2
  16. package/dist/capabilities/download/batch/networkLoss.d.ts.map +1 -1
  17. package/dist/capabilities/download/batch/networkLoss.js +24 -3
  18. package/dist/capabilities/download/batch/networkLoss.js.map +1 -1
  19. package/dist/capabilities/download/batch/resume.d.ts +7 -0
  20. package/dist/capabilities/download/batch/resume.d.ts.map +1 -1
  21. package/dist/capabilities/download/batch/resume.js +50 -9
  22. package/dist/capabilities/download/batch/resume.js.map +1 -1
  23. package/dist/capabilities/download/batch/windowPlan.d.ts +96 -0
  24. package/dist/capabilities/download/batch/windowPlan.d.ts.map +1 -0
  25. package/dist/capabilities/download/batch/windowPlan.js +196 -0
  26. package/dist/capabilities/download/batch/windowPlan.js.map +1 -0
  27. package/dist/capabilities/download/content/markdown/pro.d.ts +6 -0
  28. package/dist/capabilities/download/content/markdown/pro.d.ts.map +1 -1
  29. package/dist/capabilities/download/content/markdown/pro.js.map +1 -1
  30. package/dist/capabilities/download/content/markdown/shortfall.d.ts +8 -5
  31. package/dist/capabilities/download/content/markdown/shortfall.d.ts.map +1 -1
  32. package/dist/capabilities/download/content/markdown/shortfall.js +22 -10
  33. package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
  34. package/dist/capabilities/download/content/markdown/step.d.ts +9 -0
  35. package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
  36. package/dist/capabilities/download/content/markdown/step.js +46 -3
  37. package/dist/capabilities/download/content/markdown/step.js.map +1 -1
  38. package/dist/capabilities/download/content/markdown/types.d.ts +10 -1
  39. package/dist/capabilities/download/content/markdown/types.d.ts.map +1 -1
  40. package/dist/capabilities/download/content/pdf/open/tiers/scihub.d.ts.map +1 -1
  41. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js +3 -1
  42. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js.map +1 -1
  43. package/dist/capabilities/download/handler.d.ts.map +1 -1
  44. package/dist/capabilities/download/handler.js +13 -5
  45. package/dist/capabilities/download/handler.js.map +1 -1
  46. package/dist/capabilities/download/outputLayout.d.ts.map +1 -1
  47. package/dist/capabilities/download/outputLayout.js +3 -1
  48. package/dist/capabilities/download/outputLayout.js.map +1 -1
  49. package/dist/capabilities/download/tools.js +2 -2
  50. package/dist/capabilities/download/tools.js.map +1 -1
  51. package/dist/capabilities/download/types.d.ts +9 -1
  52. package/dist/capabilities/download/types.d.ts.map +1 -1
  53. package/dist/cli.js +3 -1
  54. package/dist/cli.js.map +1 -1
  55. package/dist/infrastructure/http/hostGate.d.ts +24 -0
  56. package/dist/infrastructure/http/hostGate.d.ts.map +1 -0
  57. package/dist/infrastructure/http/hostGate.js +72 -0
  58. package/dist/infrastructure/http/hostGate.js.map +1 -0
  59. package/dist/infrastructure/pdf/PdfDownload.d.ts +1 -0
  60. package/dist/infrastructure/pdf/PdfDownload.d.ts.map +1 -1
  61. package/dist/infrastructure/pdf/PdfDownload.js +6 -1
  62. package/dist/infrastructure/pdf/PdfDownload.js.map +1 -1
  63. package/dist/infrastructure/runlog/RunLedger.d.ts +14 -0
  64. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  65. package/dist/infrastructure/runlog/RunLedger.js +30 -4
  66. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  67. package/dist/infrastructure/runlog/failureClass.d.ts +2 -1
  68. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  69. package/dist/infrastructure/runlog/failureClass.js +27 -4
  70. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  71. package/dist/infrastructure/school/SchoolAttempt.d.ts +11 -0
  72. package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
  73. package/dist/infrastructure/school/SchoolAttempt.js +48 -5
  74. package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
  75. package/dist/infrastructure/school/SchoolMcpClient.d.ts +13 -2
  76. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  77. package/dist/infrastructure/school/SchoolMcpClient.js +138 -15
  78. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  79. package/dist/infrastructure/school/SchoolProgress.d.ts +2 -0
  80. package/dist/infrastructure/school/SchoolProgress.d.ts.map +1 -1
  81. package/dist/infrastructure/school/SchoolProgress.js +2 -0
  82. package/dist/infrastructure/school/SchoolProgress.js.map +1 -1
  83. package/dist/infrastructure/school/SchoolReadiness.d.ts +9 -0
  84. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  85. package/dist/infrastructure/school/SchoolReadiness.js +10 -0
  86. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  87. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  88. package/dist/infrastructure/school/SchoolResultNormalizer.js +4 -0
  89. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  90. package/dist/infrastructure/school/index.d.ts +2 -2
  91. package/dist/infrastructure/school/index.d.ts.map +1 -1
  92. package/dist/infrastructure/school/index.js +1 -1
  93. package/dist/infrastructure/school/index.js.map +1 -1
  94. package/dist/infrastructure/school/types.d.ts +73 -1
  95. package/dist/infrastructure/school/types.d.ts.map +1 -1
  96. package/dist/infrastructure/school/types.js.map +1 -1
  97. package/dist/infrastructure/security/SecurityUtils.d.ts.map +1 -1
  98. package/dist/infrastructure/security/SecurityUtils.js +6 -2
  99. package/dist/infrastructure/security/SecurityUtils.js.map +1 -1
  100. package/dist/management/failures/index.d.ts +23 -0
  101. package/dist/management/failures/index.d.ts.map +1 -1
  102. package/dist/management/failures/index.js +68 -20
  103. package/dist/management/failures/index.js.map +1 -1
  104. package/dist/management/school/autoUpdate.d.ts.map +1 -1
  105. package/dist/management/school/autoUpdate.js +9 -1
  106. package/dist/management/school/autoUpdate.js.map +1 -1
  107. package/dist/management/school/cliProgress.d.ts.map +1 -1
  108. package/dist/management/school/cliProgress.js +3 -1
  109. package/dist/management/school/cliProgress.js.map +1 -1
  110. package/package.json +8 -3
  111. package/school/NOTICE +3 -2
  112. package/school/paper_search_school/adapters/__init__.py +2 -0
  113. package/school/paper_search_school/adapters/aps/__init__.py +3 -6
  114. package/school/paper_search_school/adapters/base.py +19 -2
  115. package/school/paper_search_school/adapters/copernicus/__init__.py +2 -7
  116. package/school/paper_search_school/adapters/elsevier/__init__.py +50 -1
  117. package/school/paper_search_school/adapters/frontiers/__init__.py +41 -2
  118. package/school/paper_search_school/adapters/ieee/__init__.py +6 -4
  119. package/school/paper_search_school/adapters/iop/__init__.py +8 -0
  120. package/school/paper_search_school/adapters/jama/__init__.py +8 -0
  121. package/school/paper_search_school/adapters/lww/__init__.py +14 -6
  122. package/school/paper_search_school/adapters/mdpi/__init__.py +12 -7
  123. package/school/paper_search_school/adapters/neurology/__init__.py +5 -2
  124. package/school/paper_search_school/adapters/optica/__init__.py +52 -13
  125. package/school/paper_search_school/adapters/oup/__init__.py +7 -4
  126. package/school/paper_search_school/adapters/platforms/__init__.py +4 -1
  127. package/school/paper_search_school/adapters/platforms/atypon/__init__.py +12 -3
  128. package/school/paper_search_school/adapters/platforms/figshare/__init__.py +23 -4
  129. package/school/paper_search_school/adapters/platforms/jstage/__init__.py +64 -0
  130. package/school/paper_search_school/adapters/taylor_francis/__init__.py +0 -3
  131. package/school/paper_search_school/adapters/thieme/__init__.py +2 -9
  132. package/school/paper_search_school/api_keys.py +63 -13
  133. package/school/paper_search_school/assets/api_keys.json +14 -0
  134. package/school/paper_search_school/assets/capsule.html +526 -147
  135. package/school/paper_search_school/assets/capsule_en.json +140 -49
  136. package/school/paper_search_school/assets/capsule_fr.json +141 -50
  137. package/school/paper_search_school/assets/capsule_ja.json +140 -49
  138. package/school/paper_search_school/assets/capsule_ko.json +140 -49
  139. package/school/paper_search_school/assets/capsule_zh-Hant.json +134 -48
  140. package/school/paper_search_school/browser/backend.py +125 -4
  141. package/school/paper_search_school/browser/batch_session.py +189 -8
  142. package/school/paper_search_school/browser/challenge/__init__.py +12 -9
  143. package/school/paper_search_school/browser/challenge/continuation.py +83 -0
  144. package/school/paper_search_school/browser/challenge/handlers/__init__.py +1 -0
  145. package/school/paper_search_school/browser/challenge/handlers/aws_waf.py +260 -0
  146. package/school/paper_search_school/browser/challenge/handlers/recaptcha_hcaptcha.py +167 -0
  147. package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +128 -0
  148. package/school/paper_search_school/browser/challenge/handlers/turnstile.py +174 -0
  149. package/school/paper_search_school/browser/challenge/kinds.py +203 -0
  150. package/school/paper_search_school/browser/challenge/local/__init__.py +1 -0
  151. package/school/paper_search_school/browser/challenge/{interaction.py → local/interaction.py} +94 -13
  152. package/school/paper_search_school/browser/challenge/{pointer.py → local/pointer.py} +2 -2
  153. package/school/paper_search_school/browser/challenge/local/prompt.py +283 -0
  154. package/school/paper_search_school/browser/challenge/local/submission.py +33 -0
  155. package/school/paper_search_school/browser/challenge/pro.py +24 -0
  156. package/school/paper_search_school/browser/challenge/services/__init__.py +1 -0
  157. package/school/paper_search_school/browser/challenge/services/solver.py +292 -0
  158. package/school/paper_search_school/browser/engine.py +4 -1
  159. package/school/paper_search_school/browser/user_turn.py +126 -0
  160. package/school/paper_search_school/browser/watchdog.py +213 -60
  161. package/school/paper_search_school/cli_config.py +10 -5
  162. package/school/paper_search_school/config.py +16 -10
  163. package/school/paper_search_school/download_diagnostics.py +7 -2
  164. package/school/paper_search_school/engine/access_rules.py +12 -3
  165. package/school/paper_search_school/engine/batch.py +52 -18
  166. package/school/paper_search_school/engine/batch_access.py +62 -16
  167. package/school/paper_search_school/engine/batch_capture.py +260 -31
  168. package/school/paper_search_school/engine/batch_common.py +3 -0
  169. package/school/paper_search_school/engine/batch_diagnostics.py +25 -5
  170. package/school/paper_search_school/engine/batch_institution.py +52 -3
  171. package/school/paper_search_school/engine/batch_login.py +398 -36
  172. package/school/paper_search_school/engine/batch_pdf_urls.py +38 -7
  173. package/school/paper_search_school/engine/batch_user.py +48 -3
  174. package/school/paper_search_school/engine/batch_waits.py +221 -14
  175. package/school/paper_search_school/engine/bridge.py +29 -6
  176. package/school/paper_search_school/engine/fulltext_page.py +55 -8
  177. package/school/paper_search_school/engine/router.py +16 -1
  178. package/school/paper_search_school/engine/supplements.py +7 -1
  179. package/school/paper_search_school/entitlements.py +29 -1
  180. package/school/paper_search_school/pdf_utils.py +25 -16
  181. package/school/paper_search_school/progress_capsule.py +69 -11
  182. package/school/paper_search_school/progress_reporter.py +243 -11
  183. package/school/paper_search_school/progress_view.py +205 -91
  184. package/school/paper_search_school/publishers/builtin/iop.json +2 -1
  185. package/school/paper_search_school/publishers/builtin/neurology.json +4 -2
  186. package/school/paper_search_school/publishers/site.py +12 -4
  187. package/school/paper_search_school/rate_limit.py +24 -1
  188. package/school/paper_search_school/school_login.py +170 -8
  189. package/school/paper_search_school/school_test.py +1 -1
  190. package/school/paper_search_school/server.py +179 -23
  191. package/school/paper_search_school/user_settings.py +46 -4
  192. package/school/pyproject.toml +1 -0
  193. package/skills/paper-search/SKILL.md +107 -107
  194. package/skills/paper-search/references/browser-download.md +102 -99
  195. package/skills/paper-search/references/capability-routing.md +89 -89
  196. package/skills/paper-search/references/cli-contract.md +78 -78
  197. package/skills/paper-search/references/federation-support.md +172 -172
  198. package/skills/paper-search/references/management-layer.md +78 -78
  199. package/skills/paper-search/references/publisher-support.md +38 -38
  200. package/skills/paper-search/references/school-setup.md +56 -55
  201. package/skills/paper-search/references/setup.md +20 -20
  202. package/skills/paper-search/references/troubleshooting.md +12 -12
  203. package/README.en.md +0 -264
  204. package/school/paper_search_school/browser/challenge/prompt.py +0 -154
@@ -9,7 +9,8 @@ from fnmatch import fnmatch
9
9
  from typing import Any
10
10
  from urllib.parse import unquote, urlparse
11
11
 
12
- from .router import build_pdf_candidates, extract_elsevier_pii, is_pdf_candidate_url, is_supplementary_url, is_springer_article_pdf_url
12
+ from .router import (OJS_VIEW_PATH, PLATFORM_FILE_PATH, build_pdf_candidates, extract_elsevier_pii, is_pdf_candidate_url,
13
+ is_supplementary_url, is_springer_article_pdf_url)
13
14
  from .batch_common import PaperRecord, _REFERENCE_AREA, _is_browser_error
14
15
 
15
16
 
@@ -24,22 +25,45 @@ _NOT_PDF_LINK = re.compile(
24
25
  r"|password|/ads?/|doubleclick|addtoany", re.I)
25
26
  # A path that serves a PDF: a .pdf file or a PDF view (Wiley /doi/pdf|epdf|pdfdirect/,
26
27
  # ScienceDirect /pdfft, RSC /articlepdf/, Elsevier journals' /action/showPdf, IEEE's
27
- # stamp.jsp and stampPDF, Optica's viewmedia.cfm, PLOS's /article/file).
28
+ # stamp.jsp and stampPDF, Optica's viewmedia.cfm, PLOS's /article/file), or a platform's file
29
+ # (router.PLATFORM_FILE_PATH: an Open Journal Systems galley, bepress's viewcontent.cgi).
28
30
  _PDF_PATH = re.compile(
29
31
  r"\.pdf$|/(?:pdf|epdf|pdfdirect|pdfft|articlepdf|stamppdf)(?:/|$)|/action/showpdf$|/stamp/stamp\.jsp$"
30
- r"|viewmedia\.cfm$|/article/file$", re.I)
32
+ r"|viewmedia\.cfm$|/article/file$|" + PLATFORM_FILE_PATH.pattern, re.I)
31
33
  # Article views that are not an article id ("/article/123/fulltext").
32
34
  _VIEWS = frozenset({"fulltext", "abstract", "full", "abs", "html", "pdf", "epdf", "summary", "info", "references"})
33
- # The page's citation metadata and its visible links outside the references, in one round trip.
35
+ # The page's citation metadata and its visible links outside the references, in one round trip. A form with a
36
+ # control shown counts as a link to its address (with its own fields when it is sent by GET): Brepols's PDF button is
37
+ # a link to "#" in <form action="/deliver/fulltext/.../<article>.pdf">, sent by the page's script; the click gave no
38
+ # PDF and its address was never tried (Centaurus, Windows 2026-11-24). Its address still has to pass as this
39
+ # article's PDF (_article_pdf_link).
40
+ # A page without citation_doi names its DOI elsewhere: bepress Digital Commons in bepress_citation_doi (with
41
+ # its PDF in bepress_citation_pdf_url, Osgoode Hall Law Journal), Tellus B's site in DC.Identifier (its
42
+ # citation_pdf_url never tried, 2026-11-24). Those are read only when the citation_ names are missing.
34
43
  _PAGE_PDF_LINKS_JS = """() => {
35
44
  const shown = el => el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden';
36
- const meta = name => [...document.querySelectorAll('meta[name="' + name + '"]')]
45
+ const meta = name => [...document.querySelectorAll('meta[name="' + name + '" i]')]
37
46
  .map(el => (el.content || '').trim()).filter(Boolean);
47
+ const first = (...lists) => lists.find(list => list.length) || [];
48
+ const doiLike = values => values.map(value => value.replace(/^(?:https?:\\/\\/(?:dx\\.)?doi\\.org\\/|doi:\\s*)/i, ''))
49
+ .filter(value => /^10\\.\\d{4,9}\\/\\S+$/.test(value));
38
50
  const absolute = value => { try { return new URL(value, location.href).href; } catch (_) { return ''; } };
39
51
  const links = [...document.querySelectorAll('a[href]')]
40
52
  .filter(a => shown(a) && !a.closest(REFERENCES)).map(a => a.href).filter(href => /^https?:/i.test(href));
41
- return {dois: meta('citation_doi'), pdfs: meta('citation_pdf_url').map(absolute).filter(Boolean),
42
- links: [...new Set(links)].slice(0, 800)};
53
+ const forms = [...document.querySelectorAll('form[action]')]
54
+ .filter(f => !f.closest(REFERENCES) && [...f.querySelectorAll('a, button, input[type=submit], [role=button]')].some(shown))
55
+ .map(f => {
56
+ let target;
57
+ try { target = new URL(f.getAttribute('action'), location.href); } catch (_) { return ''; }
58
+ if ((f.getAttribute('method') || 'get').toLowerCase() === 'get') {
59
+ for (const [name, value] of new FormData(f)) if (typeof value === 'string') target.searchParams.append(name, value);
60
+ }
61
+ return target.href;
62
+ }).filter(href => /^https?:/i.test(href));
63
+ return {dois: first(meta('citation_doi'), meta('bepress_citation_doi'), doiLike(meta('DC.Identifier.DOI')),
64
+ doiLike(meta('DC.Identifier'))),
65
+ pdfs: first(meta('citation_pdf_url'), meta('bepress_citation_pdf_url')).map(absolute).filter(Boolean),
66
+ links: [...new Set([...links, ...forms])].slice(0, 800)};
43
67
  }""".replace("REFERENCES", repr(_REFERENCE_AREA))
44
68
 
45
69
 
@@ -83,6 +107,13 @@ class PdfUrlsMixin:
83
107
  ids = [part for part in segments if re.fullmatch(r"\d{5,}", part)]
84
108
  if ids:
85
109
  keys.append(ids[-1])
110
+ # On an Open Journal Systems article or galley page, that article's galley files: its
111
+ # "PDF" opens /article/view/<article>/<galley>, a page around the PDF whose Download is
112
+ # /article/download/<article>/<galley>/<file>; the article number was too short to name it
113
+ # (AJPR's 442) or a name (JSIHS), and that Download was never tried (2026-11-24).
114
+ ojs = OJS_VIEW_PATH.search(urlparse(page_url or "").path.lower())
115
+ if ojs:
116
+ keys.append(f"/article/download/{ojs.group(1)}/")
86
117
  return [key for key in dict.fromkeys(keys) if key]
87
118
 
88
119
  def _citation_pdf_urls(self, page: Any, doi: str, found: dict | None = None) -> list[str]:
@@ -69,7 +69,12 @@ class UserRequestsMixin:
69
69
  publisher = str(getattr(getattr(self, "profile", None), "name", "") or "")
70
70
  since = getattr(self, "_item_started", 0.0)
71
71
  scheduled: set[str] = set()
72
- if sys.platform == "darwin":
72
+ from ..browser import user_turn
73
+
74
+ # A window after the first (并行下载) joined the first's Chrome: its driver sees none of its processes; the
75
+ # first window's stand for all of them.
76
+ joined = bool(user_turn.window())
77
+ if sys.platform == "darwin" and not joined:
73
78
  from ..browser.foreground import mac_browser_pid
74
79
 
75
80
  try:
@@ -78,7 +83,7 @@ class UserRequestsMixin:
78
83
  self._event(result, "browser_focus_unavailable", type(exc).__name__)
79
84
  pid = 0
80
85
  progress_reporter.update(browser_pid=pid)
81
- elif os.name == "nt":
86
+ elif os.name == "nt" and not joined:
82
87
  # The window raises the browser itself, as on macOS: a request left for this
83
88
  # article's watch was lost once the watch had ended (Windows, 2026-11-16).
84
89
  from ..browser.foreground import browser_pids
@@ -90,7 +95,11 @@ class UserRequestsMixin:
90
95
  pids = []
91
96
  progress_reporter.update(browser_pids=pids)
92
97
 
98
+ # This article's browser thread: what the watch asks for runs there (a batch's windows each have theirs).
99
+ owner = threading.get_ident()
100
+
93
101
  def watch() -> None:
102
+ watchdog.adopt(owner)
94
103
  while not stop.wait(1.0):
95
104
  activity.check()
96
105
  try:
@@ -114,6 +123,41 @@ class UserRequestsMixin:
114
123
  threading.Thread(target=watch, name="user-requests", daemon=True).start()
115
124
  return stop
116
125
 
126
+ def _take_user_turn(self, page: Any, result: DownloadResult) -> float | None:
127
+ """并行下载 (user, 2026-11-29): this window's turn to ask for the user (browser/user_turn.py), before the
128
+ school's login or a verification handed to the user. Waits while another window has it, its page answering
129
+ and the user's buttons read; the article's waits on the user start after it (their deadlines move on by the
130
+ time waited). An absent user's wait run out meanwhile makes this one's short. None: no turns taken (not a
131
+ batch of windows at once); else the seconds waited."""
132
+ from ..browser import user_turn
133
+
134
+ if not user_turn.active():
135
+ return None
136
+ since = time.monotonic()
137
+
138
+ def pump() -> None:
139
+ self._check_user_decision(result, page)
140
+ page.wait_for_timeout(int(user_turn.POLL_SEC * 1000))
141
+
142
+ if user_turn.holder() not in (None, user_turn.window()):
143
+ self._event(result, "user_turn_wait", "another window is asking for you first")
144
+ waited = user_turn.acquire(pump)
145
+ if waited >= 1:
146
+ self._event(result, "user_turn", f"its turn after {waited:.0f} s")
147
+ for attribute in ("_user_wait_deadline", "_school_login_deadline"):
148
+ if isinstance(getattr(result, attribute, None), (int, float)):
149
+ setattr(result, attribute, getattr(result, attribute) + waited)
150
+ if user_turn.expired_since(since) and not self._user_away:
151
+ self.config["user_wait"] = "short"
152
+ self._event(result, "user_seems_away", "another window's wait on you ran out meanwhile")
153
+ return waited
154
+
155
+ def _give_user_turn(self) -> None:
156
+ """The step that took this window's turn ended (``_take_user_turn``)."""
157
+ from ..browser import user_turn
158
+
159
+ user_turn.release()
160
+
117
161
  def _observe_page_activity(self, page: Any, result: DownloadResult) -> tuple[PageActivity, bool]:
118
162
  activity = getattr(result, "_page_activity", None)
119
163
  owned = activity is None or activity.closed
@@ -122,7 +166,8 @@ class UserRequestsMixin:
122
166
 
123
167
  result._page_activity = activity = PageActivity(result.doi, self.config)
124
168
  watched = activity
125
- watched.on_idle = lambda: watchdog.run_soon(lambda: self._remind_on_unknown_page(watched, result))
169
+ owner = threading.get_ident() # its reminder runs on this article's browser thread, from any thread
170
+ watched.on_idle = lambda: watchdog.run_soon(lambda: self._remind_on_unknown_page(watched, result), thread=owner)
126
171
  if page is not None:
127
172
  activity.observe(page)
128
173
  return activity, owned
@@ -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:
@@ -125,6 +126,7 @@ class UserWaitMixin:
125
126
  automatic: dict[str, Any] = {}
126
127
  interaction = ExitStack()
127
128
  manual = False
129
+ turn = False # this window's turn to ask for the user (并行下载), once its wait needs the user
128
130
  state = ""
129
131
  reporter = None
130
132
  attention_key = f"pdf-step:{id(self)}:{result.doi}"
@@ -221,6 +223,13 @@ class UserWaitMixin:
221
223
  page.wait_for_timeout(min(1000, max(0, (deadline - time.time()) * 1000)))
222
224
  continue
223
225
  activity.automatic_for(0)
226
+ if state in ("verification", "login") and not turn:
227
+ # Another window asking for the user first: this one waits for its turn, its time after it.
228
+ with watchdog.pause_operation():
229
+ waited = self._take_user_turn(tab, result)
230
+ if waited is not None:
231
+ turn = True
232
+ deadline += waited
224
233
  if state == "verification":
225
234
  self._verification_attention(result, deadline)
226
235
  result._attention_page = tab
@@ -268,12 +277,16 @@ class UserWaitMixin:
268
277
  self._event(result, "ip_blocked_response", f"{suspect} | no PDF after waiting ({shown or 'nothing shown'})")
269
278
  return False
270
279
  finally:
280
+ if automatic.get("service_cleanup") is not None:
281
+ automatic["service_cleanup"].close()
271
282
  self._verification_attention(result, None)
272
283
  activity.automatic_for(0)
273
284
  result._attention_page = None
274
285
  if activity_owned:
275
286
  activity.close()
276
287
  interaction.close()
288
+ if turn:
289
+ self._give_user_turn()
277
290
  if shown and reporter is not None:
278
291
  try:
279
292
  reporter.clear_attention(attention_key)
@@ -362,7 +375,9 @@ class UserWaitMixin:
362
375
  # "your IP address has been blocked automatically".
363
376
  if "ip address" in text and "block" in text:
364
377
  return True
365
- return False
378
+ # The site's words for a blocked or throttled address in the page's visible text, which may
379
+ # come after a long header (Optica's, 2026-11-26: 41 KB into its 200 answer to the PDF address).
380
+ return self._ip_blocked_text(self._visible_text_excerpt(body_or_text, 20_000))
366
381
 
367
382
  @property
368
383
  def _user_away(self) -> bool:
@@ -400,10 +415,14 @@ class UserWaitMixin:
400
415
  return min(bounds)
401
416
 
402
417
  def _wait_ran_out(self, result: DownloadResult) -> None:
403
- """A wait on the user ended unanswered: the article reports a timeout."""
418
+ """A wait on the user ended unanswered: the article reports a timeout (and a window waiting for its turn
419
+ to ask for the user knows the user seems away)."""
404
420
  if not getattr(result, "_user_wait_expired", False):
405
421
  result._user_wait_expired = True
406
422
  self._event(result, "user_wait_expired", "short wait" if self._user_away else "")
423
+ from ..browser import user_turn
424
+
425
+ user_turn.note_expired()
407
426
 
408
427
  def _automatic_challenge_step(self, page: Any, result: DownloadResult,
409
428
  attempt: dict[str, Any], deadline: float) -> bool:
@@ -412,6 +431,9 @@ class UserWaitMixin:
412
431
  An absent/loading widget stays automatic, including late arrivals. A
413
432
  visible widget we cannot operate hands off within the existing budget.
414
433
  """
434
+ host = (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower()
435
+ if self._is_idp_host(host):
436
+ return False
415
437
  now = time.time()
416
438
  if not attempt:
417
439
  attempt.update(started=now, attempts=0, retry_at=now + 2)
@@ -430,17 +452,31 @@ class UserWaitMixin:
430
452
  activity = getattr(result, "_page_activity", None)
431
453
  if activity is not None:
432
454
  activity.automatic_for(automatic_end - now)
455
+ if self._forward_checked_challenge(page, result, attempt, automatic_end):
456
+ return True
457
+ from ..browser.challenge.handlers import text_captcha
458
+ if text_captcha.find(page):
459
+ return self._continue_challenge(page, result, attempt, automatic_end, "image_code")
433
460
  if challenge_interaction.needs_manual_verification(page):
434
461
  widget = challenge_interaction.verification_widget(page, manual_only=True)
435
462
  if widget and not attempt.get("widget"):
436
463
  attempt["widget"] = widget # whose widget the user is asked to complete
437
464
  self._event(result, "challenge_observation", f"manual widget: {widget}")
438
- if self._press_confirm_control(page, result, attempt, deadline):
465
+ kind = challenge_interaction.challenge_kind(page)
466
+ if kind != "awswaf" and self._press_confirm_control(page, result, attempt, deadline):
439
467
  return True
440
- return False
468
+ return self._continue_challenge(page, result, attempt, automatic_end, kind)
469
+ if now >= attempt["handoff_at"] and challenge_interaction.challenge_kind(page) == "turnstile":
470
+ return self._continue_challenge(page, result, attempt, automatic_end, "turnstile")
441
471
  if ((attempt["attempts"] >= 2 and now >= attempt["retry_at"])
442
472
  or (attempt.get("unavailable") and now >= attempt["handoff_at"])):
443
- return False
473
+ return self._continue_challenge(page, result, attempt, automatic_end,
474
+ challenge_interaction.challenge_kind(page))
475
+ if attempt.get("managed") and now >= attempt["handoff_at"]:
476
+ # With no visible control there is no human action to request. Record
477
+ # unsupported service continuation once, then retain the fixed wait.
478
+ self._continue_challenge(page, result, attempt, automatic_end,
479
+ challenge_interaction.challenge_kind(page))
444
480
  if now >= automatic_end:
445
481
  # No observed user action: the caller ends at its original bound.
446
482
  return True
@@ -494,6 +530,27 @@ class UserWaitMixin:
494
530
  "widget events: " + " -> ".join(names[-6:]))
495
531
  return True
496
532
 
533
+ def _continue_challenge(self, page: Any, result: DownloadResult, attempt: dict,
534
+ deadline: float, kind: str) -> bool:
535
+ """One bounded service continuation per verification wait and provider."""
536
+ from ..browser.challenge.continuation import Limits, resume
537
+
538
+ tried = attempt.setdefault("service_tried", set())
539
+ if kind in tried:
540
+ return False
541
+ tried.add(kind)
542
+ def checkpoint() -> None:
543
+ self._check_user_decision(result, page)
544
+ host = (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower()
545
+ if self._is_idp_host(host):
546
+ from ..browser.challenge.continuation import Expired
547
+ raise Expired
548
+ limits = Limits(time.monotonic() + max(0, deadline - time.time()),
549
+ self._captcha_budget, checkpoint,
550
+ attempt.setdefault("service_cleanup", ExitStack()))
551
+ return resume(page, self.config, kind=kind, limits=limits,
552
+ observation=lambda note: self._event(result, "challenge_observation", note))
553
+
497
554
  def _recover_stuck_widget(self, page: Any, result: DownloadResult, attempt: dict[str, Any]) -> bool:
498
555
  """A widget that reported failure or expired gets one fresh page.
499
556
 
@@ -534,7 +591,7 @@ class UserWaitMixin:
534
591
  ``True`` keeps the automatic wait going; the page's own change still
535
592
  decides whether verification ended.
536
593
  """
537
- from ..browser.challenge import prompt as prompt_control
594
+ from ..browser.challenge.local import prompt as prompt_control
538
595
 
539
596
  if not prompt_control.enabled() or attempt.get("confirmed"):
540
597
  return False
@@ -546,16 +603,129 @@ class UserWaitMixin:
546
603
  if budget <= 0.5:
547
604
  return False
548
605
  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)
606
+ # A provider's widget is on the page but its control is not rendered yet:
607
+ # keep looking for a little while before handing the page out. Not past the
608
+ # time the user is to be asked (``handoff_at``, browser_stall_notify_after),
609
+ # and not once the page has moved on: looking up to 15 s regardless kept a
610
+ # page that let the reader through in 0.2 s on screen as a verification and
611
+ # asked the user to complete it, and every reminder came late (Windows, real
612
+ # Chrome, 2026-11-25; since fdebe5b5).
613
+ widget = self._verification_widget_page(page)
614
+ try_until = min(deadline, time.time() + prompt_control.PRESS_LIMIT_SEC
615
+ + (prompt_control.AWAIT_LIMIT_SEC if widget else 0.0))
616
+ if remaining is not None:
617
+ try_until = min(try_until, time.time() + max(0.0, remaining))
618
+ # The first look as before; looking again only until the user is to be asked.
619
+ look_again_until = try_until
620
+ if widget and attempt.get("handoff_at"):
621
+ look_again_until = min(try_until, float(attempt["handoff_at"]))
622
+ outcome = "absent"
623
+ first = True
624
+ while True:
625
+ if not first and not (self._challenge_shell(page) or self._is_challenge_page(page)):
626
+ # Let through meanwhile: the wait sees the page and ends without asking anyone.
627
+ self._event(result, "challenge_observation", "confirmation control: page moved on")
628
+ return True
629
+ room = try_until - time.time()
630
+ if room <= 0.5:
631
+ break
632
+ outcome = prompt_control.click_confirm_control(
633
+ page, timeout_ms=int(min(prompt_control.PRESS_LIMIT_SEC, room) * 1000),
634
+ checkpoint=lambda: self._check_user_decision(result, page),
635
+ observation=reasons.append)
636
+ first = False
637
+ if (outcome == "clicked" or not widget
638
+ or time.time() + prompt_control.AWAIT_STEP_SEC >= look_again_until):
639
+ break
640
+ page.wait_for_timeout(int(prompt_control.AWAIT_STEP_SEC * 1000))
553
641
  detail = f"confirmation control: {outcome}"
554
642
  if reasons:
555
643
  detail += f" ({', '.join(dict.fromkeys(reasons))})"
556
644
  self._event(result, "challenge_observation", detail)
645
+ if outcome == "clicked":
646
+ self._await_check_then_forward(page, result, attempt, deadline, prompt_control)
557
647
  return outcome == "clicked"
558
648
 
649
+ def _await_check_then_forward(self, page: Any, result: DownloadResult, attempt: dict[str, Any],
650
+ deadline: float, prompt_control: Any) -> None:
651
+ """After the box is pressed: wait for it to read checked, then press the page's own
652
+ forward button once (JAMA's "Take me to my Content", which must be pressed within a
653
+ minute of checking or the token expires while the wait goes on)."""
654
+ reasons: list[str] = []
655
+ checked = prompt_control.confirm_checked(page)
656
+ refresh_left = prompt_control.REFRESH_LIMIT
657
+ rounds = prompt_control.REFRESH_LIMIT + 1
658
+ for round_index in range(rounds):
659
+ if checked or self._check_user_decision(result, page):
660
+ break
661
+ if prompt_control.expired(page) and refresh_left > 0:
662
+ refresh_left -= 1
663
+ if prompt_control.press_refresh(page, timeout_ms=2500, observation=reasons.append):
664
+ self._event(result, "challenge_observation",
665
+ f"interstitial expired: refreshed ({refresh_left} left)")
666
+ page.wait_for_timeout(1500)
667
+ continue
668
+ if round_index and not attempt.get("repressed"):
669
+ attempt["repressed"] = True
670
+ prompt_control.click_confirm_control(
671
+ page, timeout_ms=2000,
672
+ checkpoint=lambda: self._check_user_decision(result, page),
673
+ observation=reasons.append)
674
+ budget_end = min(deadline, time.time() + prompt_control.CHECKED_LIMIT_SEC)
675
+ while time.time() < budget_end:
676
+ if self._check_user_decision(result, page):
677
+ break
678
+ if prompt_control.confirm_checked(page):
679
+ checked = True
680
+ break
681
+ from ..browser.challenge.handlers.recaptcha_hcaptcha import has_grid
682
+ if has_grid(page):
683
+ self._event(result, "challenge_observation", "picture grid appeared; continue with service")
684
+ return
685
+ page.wait_for_timeout(400)
686
+ if checked:
687
+ break
688
+ detail = f"confirmation checked: {checked}"
689
+ if reasons:
690
+ detail += f" ({', '.join(dict.fromkeys(reasons))})"
691
+ self._event(result, "challenge_observation", detail)
692
+ if not checked:
693
+ return
694
+ self._forward_checked_challenge(page, result, attempt, deadline)
695
+
696
+ def _forward_checked_challenge(self, page: Any, result: DownloadResult,
697
+ attempt: dict[str, Any], deadline: float) -> bool:
698
+ """Observe delayed acknowledgements even after image solving handed back.
699
+
700
+ This is also called in manual wait: a user-completed widget gets the same
701
+ outer submission. A successful press is remembered only for this wait.
702
+ """
703
+ from ..browser.challenge.local import prompt as prompt_control
704
+ host = (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower()
705
+ if self._is_idp_host(host) or not prompt_control.confirm_checked(page):
706
+ return False
707
+ if attempt.get("forwarded"):
708
+ return True
709
+ if time.time() >= deadline or self._check_user_decision(result, page):
710
+ return False
711
+ remaining = watchdog.operation_remaining()
712
+ room = deadline - time.time()
713
+ if remaining is not None:
714
+ room = min(room, remaining)
715
+ if room <= 0:
716
+ return False
717
+ reasons: list[str] = []
718
+ outcome = prompt_control.press_forward(
719
+ page, timeout_ms=max(1, int(min(prompt_control.FORWARD_LIMIT_SEC, room) * 1000)),
720
+ observation=reasons.append)
721
+ if outcome == "pressed":
722
+ attempt["forwarded"] = True
723
+ if outcome != attempt.get("forward_outcome"):
724
+ self._event(result, "challenge_observation",
725
+ f"forward control: {outcome} ({'; '.join(reasons)})")
726
+ attempt["forward_outcome"] = outcome
727
+ return True # checked is acknowledgement; the enclosing wait checks access
728
+
559
729
  def _verification_attention(self, result: DownloadResult, deadline: float | None) -> None:
560
730
  from .. import progress_reporter
561
731
  key = f"verification:{id(self)}:{result.doi}"
@@ -577,11 +747,13 @@ class UserWaitMixin:
577
747
  progress_reporter.update_attention_deadline(key, deadline)
578
748
 
579
749
  def _wait_for_challenge(self, page: Any, result: DownloadResult, *, deadline: float | None = None,
580
- until: Callable[[], bool] | None = None) -> bool:
750
+ until: Callable[[], bool] | None = None, hand_over_only: bool = False) -> bool:
581
751
  """Wait while a verification page is up, until ``_wait_deadline``. ``until``: the
582
752
  wait ends, as passed, once it says what it waits for has arrived though the page
583
753
  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)."""
754
+ a moment...": two articles failed with the PDF in hand, 2026-11-21).
755
+ ``hand_over_only``: the PDF step's verification ends, not passed, where the wait on
756
+ the user would begin; its caller signs in at the article and asks for the PDF again."""
585
757
  interaction = ExitStack()
586
758
  activity, activity_owned = self._observe_page_activity(page, result)
587
759
  automatic: dict[str, Any] = {}
@@ -590,6 +762,7 @@ class UserWaitMixin:
590
762
  started, phase_before = time.time(), ""
591
763
  verification_wait = None
592
764
  verification_deadline = None
765
+ turn = False # this window's turn to ask for the user (并行下载)
593
766
  try:
594
767
  waited = False
595
768
  state_before = result.state
@@ -609,6 +782,7 @@ class UserWaitMixin:
609
782
  if not waited:
610
783
  deadline = self._wait_deadline(result, deadline)
611
784
  started, phase_before = time.time(), self._phase(result, "verification")
785
+ self._note_challenge_type(page, result, title_and_url_only=bool(shell))
612
786
  waited = True
613
787
  result.state = "challenge_or_viewer_timeout"
614
788
  if verification_wait is not None:
@@ -621,14 +795,42 @@ class UserWaitMixin:
621
795
  if time.time() >= deadline:
622
796
  break
623
797
  result._attention_page = page
624
- auto_pending = not manual and self._automatic_challenge_step(page, result, automatic, deadline)
798
+ auto_pending = (self._forward_checked_challenge(page, result, automatic, deadline)
799
+ if manual else self._automatic_challenge_step(page, result, automatic, deadline))
625
800
  if not auto_pending:
626
801
  activity.automatic_for(0)
627
802
  activity.check()
803
+ if not auto_pending and not manual and not automatic.get("school_reloaded") and self._is_idp_host(
804
+ (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower()):
805
+ # The school's own page, its check (Cloudflare's) not passed by the program's steps: loaded
806
+ # once more and its steps tried again before the user is asked (user, 2026-11-28).
807
+ if automatic.get("service_cleanup") is not None:
808
+ automatic["service_cleanup"].close()
809
+ automatic.clear()
810
+ automatic["school_reloaded"] = True
811
+ self._event(result, "challenge_observation", "school page reloaded once for its check")
812
+ try:
813
+ page.reload(wait_until="domcontentloaded", timeout=15_000)
814
+ except (watchdog.BrowserUnresponsive, watchdog.CallAbandoned):
815
+ raise
816
+ except Exception as exc: # noqa: BLE001 - a reload that fails leaves the wait as it was
817
+ self._event(result, "challenge_observation", f"reload failed: {type(exc).__name__}")
818
+ continue
819
+ if not auto_pending and not manual and hand_over_only:
820
+ # Not passed by the program's own steps (the captcha service's
821
+ # included): no wait on the user in the PDF step (ba77bb4e; the
822
+ # parameter went with Bright Data in ead266c9, its callers kept it).
823
+ self._note_challenge_type(page, result)
824
+ return False
628
825
  if not auto_pending and not manual:
629
826
  result._attention_page = page
630
827
  interaction.enter_context(watchdog.pause_operation())
631
828
  manual = True
829
+ # Another window asking for the user first: this one waits for its turn, its time after it.
830
+ turn_waited = self._take_user_turn(page, result)
831
+ if turn_waited is not None:
832
+ turn = True
833
+ deadline += turn_waited
632
834
  from .login_wait import LoginWait
633
835
  verification_deadline = deadline
634
836
  verification_wait = result._verification_wait = LoginWait(
@@ -665,9 +867,12 @@ class UserWaitMixin:
665
867
  if passed:
666
868
  result.state = state_before
667
869
  else:
870
+ self._note_challenge_type(page, result)
668
871
  self._wait_ran_out(result)
669
872
  return passed
670
873
  finally:
874
+ if automatic.get("service_cleanup") is not None:
875
+ automatic["service_cleanup"].close()
671
876
  self._verification_attention(result, None)
672
877
  activity.automatic_for(0)
673
878
  if verification_wait is not None:
@@ -680,6 +885,8 @@ class UserWaitMixin:
680
885
  result._user_wait_deadline += excluded
681
886
  result._verification_wait = None
682
887
  interaction.close()
888
+ if turn:
889
+ self._give_user_turn()
683
890
  if waited:
684
891
  self._phase(result, phase_before or "open")
685
892
  self._note_wait(result, "verification", started, "passed" if result.state != "challenge_or_viewer_timeout"
@@ -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.
@@ -80,6 +83,9 @@ _FAILURE_KINDS = {
80
83
  # The site's page shows no way to any school's login (an open-access site, one with personal
81
84
  # accounts only): no school login was started (user, 2026-11-18).
82
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", ""),
83
89
  **{code: (code, "review_browser") for code in _LOGIN_FAILURE_CODES},
84
90
  }
85
91
 
@@ -127,7 +133,13 @@ def _failure_reason_code(result: Any) -> str:
127
133
  # A timeout is the user's only where the user had a step to take
128
134
  # (ADR 0012); a wait that ended on the publisher's pages means the
129
135
  # program never reached the login.
130
- 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"
131
143
  elif reason_code == "sso_required" and getattr(result, "_user_wait_expired", False):
132
144
  reason_code = "login_timeout" # the login waited on the user until its time was up
133
145
  if getattr(result, "_download_limit", "") and reason_code in _PDF_NOT_ARRIVED:
@@ -319,6 +331,7 @@ def _try_builtin_institutional(
319
331
  # Without a profile there is no site to build one for.
320
332
  return _failure(doi, "doi_not_resolved") if profile else _unsupported_publisher(doi)
321
333
 
334
+ from ..adapters.base import adapter_class_for as _adapter_class_for
322
335
  from ..publishers.profiles import infer_publisher_profile_from_url, journal_platform
323
336
  hosted = (infer_publisher_profile_from_url(resolved_url, profiles=profiles)
324
337
  if profiles is not None else infer_publisher_profile_from_url(resolved_url))
@@ -330,6 +343,12 @@ def _try_builtin_institutional(
330
343
  # Academic, 2026-11-14). A journal listed in _JOURNAL_PLATFORMS keeps its entry.
331
344
  log.info(" [Institutional] DOI resolves to %s's site: its rules, not %s's", hosted.name, profile.name)
332
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
333
352
  if not profile:
334
353
  # No profile names the site: the publisher driver with the shared rules
335
354
  # only, on the site the DOI resolves to.
@@ -375,13 +394,12 @@ def _try_builtin_institutional(
375
394
  from .. import rate_limit
376
395
  rate_key = publisher_name or (urlparse(resolved_url).hostname or "")
377
396
  limit = int(config.get("publisher_hourly_limit", rate_limit.DEFAULT_LIMIT) or 0)
378
- wait = rate_limit.wait_seconds(rate_key, limit)
397
+ wait = rate_limit.take(rate_key, limit)
379
398
  if wait:
380
399
  log.info(" [Institutional] %s: %d articles this hour, a new hour in %d s", rate_key, limit, wait)
381
400
  return {"success": False, "identifier": doi, "doi": doi, "source": "institutional:rate_limit",
382
401
  "error_type": "rate_limited", "reason": "publisher_hourly_limit", "action": "wait",
383
402
  "retry_after_sec": wait, "publisher": rate_key, "limit": limit}
384
- rate_limit.record(rate_key)
385
403
 
386
404
  def accept(result: dict[str, Any] | None, source: str) -> bool:
387
405
  if not result:
@@ -437,8 +455,8 @@ def _try_builtin_institutional(
437
455
  primary = next((f for code in ("source_exception", "unsupported_platform", "article_not_yet_published",
438
456
  "generic_institution_entry_missing", "publisher_institution_entry_missing",
439
457
  "no_institution_entry",
440
- "publisher_content_error", "access_blocked", *_LOGIN_FAILURE_CODES,
441
- "download_timeout")
458
+ "publisher_content_error", "access_blocked", "captcha_required",
459
+ *_LOGIN_FAILURE_CODES, "download_timeout")
442
460
  for f in failures if f["error_type"] == code), denial or failures[-1])
443
461
  result = {"success": False, "identifier": doi, "doi": doi, "source": "institutional",
444
462
  "error_type": primary["error_type"], "reason": primary["reason"],
@@ -1005,6 +1023,11 @@ def _browser_artifacts(result: Any, profile: Any) -> dict[str, str]:
1005
1023
  wait_page = str(getattr(result, "login_wait_page", "") or "")
1006
1024
  if wait_page in LOGIN_WAIT_PAGES:
1007
1025
  artifacts["login_wait_page"] = wait_page
1026
+ # The kind of verification the item last waited on: a fixed word (``kinds.LABELS``).
1027
+ from ..browser.challenge.kinds import LABELS as CHALLENGE_TYPES
1028
+ challenge_type = str(getattr(result, "challenge_type", "") or "")
1029
+ if challenge_type in CHALLENGE_TYPES:
1030
+ artifacts["challenge_type"] = challenge_type
1008
1031
  # The school's site the login stopped on: a host name only, for the message.
1009
1032
  host = str(getattr(result, "_stopped_host", "") or "").lower()
1010
1033
  if state == "idp_no_return_to_publisher" and re.fullmatch(r"[a-z0-9-]+(?:\.[a-z0-9-]+)+", host) and len(host) <= 253: