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
@@ -50,6 +50,11 @@ def _sent_as_attachment(headers: dict[str, str]) -> bool:
50
50
  return headers.get("content-disposition", "").strip().lower().startswith("attachment")
51
51
 
52
52
 
53
+ # A PDF control's link that opens a new tab opens in this one, whose PDF responses are watched.
54
+ _SAME_TAB_JS = """el => { const a = el.closest('a[target]');
55
+ if (a && (a.getAttribute('target') || '').toLowerCase() === '_blank') a.setAttribute('target', '_self'); }"""
56
+
57
+
53
58
  # A PDF larger than this is read in pieces (Fetch.takeResponseBodyAsStream), the step's time
54
59
  # going on while pieces arrive: read whole in one call it was cut at the step's minute, and the
55
60
  # page's own copy then fetched in its place took the tab down (Cell, 108 MB, 2026-11-18).
@@ -95,6 +100,18 @@ class CaptureMixin:
95
100
  captured["login_wall"] = True
96
101
  return True
97
102
 
103
+ def _paywall_answered_before_login(self, result: DownloadResult) -> bool:
104
+ """This capture, the PDF tried first before the school's login (access not known, ``_pdf_first``), had a PDF
105
+ address answer 403/429 with the article's own page (``pdf_step_article_page``): the site's other addresses
106
+ answer the same until the login, which comes next, then every address is tried again. Wiley's Angewandte
107
+ (10.1002/anie.202516998, Windows 2026-11-24): epdf, pdfdirect and pdf each answered its paywall page in about
108
+ 20 s and the PDF step's page budget ran out before the login, 原因不明 · 页面处理超时; the next paper of the
109
+ journal went through the login and was saved."""
110
+ if not getattr(result, "_pdf_first", False) or self._school_login_done():
111
+ return False
112
+ started = max((i for i, e in enumerate(result.events) if e.get("state") == "pdf_capture_started"), default=-1)
113
+ return any(e.get("state") == "pdf_step_article_page" for e in result.events[started + 1:])
114
+
98
115
  def _probe_pdf_while_waiting(self, page: Any, result: DownloadResult, *, after_login: bool) -> bool:
99
116
  """While the login waits: this article's PDF from an open tab or fetched
100
117
  with the browser's session (``_probe_pdf``); found, the item ends with it
@@ -120,32 +137,57 @@ class CaptureMixin:
120
137
  # PDF attempts that came back as a web page (``_record_pdf_attempt``).
121
138
  _WEB_PAGE_OUTCOMES = frozenset({"html page", "paywall"})
122
139
 
123
- def _pdf_sent_to_article_after_login(self, page: Any, result: DownloadResult, since: int) -> bool:
124
- """After this item's school login the PDF attempts from ``since`` on were
125
- sent to the article's own web page, with no PDF, login, verification or
126
- block. Missing entitlement additionally requires the page's denial,
127
- purchase offer or abstract-only evidence. A redirect alone can also
128
- happen on a freely readable article and does not prove missing access."""
140
+ def _pdf_sent_to_article(self, page: Any, result: DownloadResult, since: int) -> list[dict[str, Any]]:
141
+ """The PDF attempts from ``since`` on that were sent to the article's own web page:
142
+ redirected there, or the PDF address showing that page (the adapter's
143
+ ``pdf_address_shows_article_page``, or its 403/429 answer printing the article's
144
+ title, ``pdf_step_article_page``). [] unless every attempt came back as a web page
145
+ or nothing, and the tab is on no login or verification page. JAMA's ``/articlepdf/``
146
+ answered with ``/fullarticle/`` (10.1001/jama.2025.19316), jacc.org's ``/doi/pdf/``
147
+ with the article's page and a 403 (10.1016/j.jcmg.2025.09.021; Windows 2026-11-23)."""
129
148
  def plain(url: Any) -> str:
130
149
  parsed = urlparse(str(url or ""))
131
150
  return f"{parsed.hostname}{parsed.path}".lower().rstrip("/")
132
151
 
152
+ answered = {plain(str(e.get("detail") or "").split(" | ", 1)[0].split(" ", 1)[-1])
153
+ for e in result.events if e.get("state") == "pdf_step_article_page"}
133
154
  attempts = result.pdf_attempts[since:]
134
155
  sent_back = [a for a in attempts if a.get("outcome") in self._WEB_PAGE_OUTCOMES
135
- and plain(a.get("final_url")) != plain(a.get("url"))
156
+ and (plain(a.get("final_url")) != plain(a.get("url")) or self.adapter.pdf_address_shows_article_page
157
+ or plain(a.get("final_url")) in answered)
136
158
  and self._is_success_article_url(str(a.get("final_url") or ""))]
137
159
  url = str(getattr(page, "url", "") or "")
138
- if (not sent_back or not self._school_login_done()
160
+ if (not sent_back
139
161
  or any(a.get("outcome") not in self._WEB_PAGE_OUTCOMES | {"no pdf"} for a in attempts)
140
162
  or self._is_auth_page(url) or self._is_challenge_page(page)):
163
+ return []
164
+ return sent_back
165
+
166
+ def _pdf_sent_to_article_after_login(self, page: Any, result: DownloadResult, since: int) -> bool:
167
+ """After this item's school login, or with the school's session shown on the
168
+ page (signed in by an earlier item), the PDF attempts from ``since`` on were
169
+ sent to the article's own web page (``_pdf_sent_to_article``). Missing
170
+ entitlement additionally requires the page's denial, purchase offer or
171
+ abstract-only evidence. A redirect alone can also happen on a freely
172
+ readable article and does not prove missing access.
173
+ NEJM Catalyst (10.1056/cat.24.0478, Windows 2026-11-23): "Welcome: <school>"
174
+ in the header, "Get Access" over the abstract, the PDF address answering
175
+ with that page; it ended as pdf_not_captured, the school never switched."""
176
+ sent_back = self._pdf_sent_to_article(page, result, since)
177
+ if not sent_back:
141
178
  return False
142
- evidence = self._no_access_after_login(page, result)
179
+ signed_in = self._school_login_done()
180
+ session = not signed_in and self._institution_session(page) == "ours"
181
+ if not (signed_in or session):
182
+ return False
183
+ evidence = self._no_access_after_login(page, result, session_shown=session)
143
184
  if not evidence:
144
185
  return False
145
186
  last = sent_back[-1]
146
187
  result.reason = "institution_pdf_entitlement_missing"
147
188
  self._event(result, "no_access_after_login",
148
- f"PDF after the school login sent to the article's web page: {str(last.get('url'))[:120]} -> "
189
+ f"PDF {'with the school signed in' if session else 'after the school login'} sent to the "
190
+ f"article's web page: {str(last.get('url'))[:120]} -> "
149
191
  f"{str(last.get('final_url'))[:160]} | {evidence[:160]}")
150
192
  self._snapshot(page, result, "not subscribed")
151
193
  return True
@@ -304,6 +346,88 @@ class CaptureMixin:
304
346
  f"after {time.time() - started:.1f} s at {str(getattr(page, 'url', ''))[:160]}")
305
347
  return True
306
348
 
349
+ # Anything on the page naming a PDF: a citation PDF address, a link's or control's address,
350
+ # title or label, the page's text.
351
+ _NAMES_A_PDF_JS = """() => !!document.querySelector('meta[name$="pdf_url" i]')
352
+ || [...document.querySelectorAll('a, button, [role="button"]')].some(el => /pdf/i.test(
353
+ [el.getAttribute('href'), el.getAttribute('title'), el.getAttribute('aria-label')].join(' ')))
354
+ || /pdf/i.test(document.body ? document.body.innerText || '' : '')"""
355
+
356
+ def _page_offers_no_pdf(self, page: Any) -> bool:
357
+ """Nothing on the article's page names a PDF (``_NAMES_A_PDF_JS``): the site gives this
358
+ article as a web page only. CAA Reviews' open reviews have no PDF at all, and were reported
359
+ as "PDF not captured" with no reason (2026-11-24). A page that names one and gave none
360
+ is not this."""
361
+ try:
362
+ return page.evaluate(self._NAMES_A_PDF_JS) is False
363
+ except Exception as exc:
364
+ if not _is_browser_error(exc):
365
+ raise
366
+ return False
367
+
368
+ # A box the reader ticks to agree to the site's terms before its download links work, on the
369
+ # article's own page. ufn.ru (Physics-Uspekhi, 2026-11-25): "By downloading this file I agree
370
+ # with the terms of use" beside an unticked box; until it is ticked the site's script takes the
371
+ # PDF link's address away and greys it (ufn.js: copyright-agree, data-ehref), and the click on it
372
+ # gave nothing. The user asked for such boxes to be ticked for them, in the shared rules
373
+ # (2026-11-25), as the publisher's terms form on the way to the school is accepted (2026-11-08).
374
+ # Its words (its labels, else the nearest enclosing text up to 4 levels, at most 600 characters)
375
+ # agree to terms, conditions, a licence or copyright and speak of the download, the PDF or the
376
+ # full text, or the page has a download control held back (disabled, greyed, a link with no
377
+ # address). Never a box in a form with a password, nor one about newsletters, offers, cookies,
378
+ # privacy, staying signed in or an account.
379
+ _DOWNLOAD_TERMS_JS = r"""() => {
380
+ const shown = el => !!el && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden';
381
+ const words = el => (el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim();
382
+ const AGREE = /\b(?:agree|accept)\b|同意|接受/i;
383
+ const TERMS = /\bterms\b|\bconditions\b|copyright|\blicen[cs]e\b|条款|协议|版权|许可/i;
384
+ const DOWNLOAD = /download|\bpdf\b|full[ -]?text|下载|全文/i;
385
+ const NOT = /newsletter|subscri|marketing|promot|\boffers?\b|cookie|privacy|remember me|keep me|signed in|sign ?up|regist|account|password|订阅|营销|推广|隐私|记住|注册|账号|账户|密码/i;
386
+ const held = [...document.querySelectorAll('a, button, [role="button"]')].some(el => shown(el)
387
+ && DOWNLOAD.test(`${words(el)} ${el.getAttribute('class') || ''} ${el.getAttribute('aria-label') || ''}`)
388
+ && (el.disabled || el.getAttribute('aria-disabled') === 'true' || /\bdisabled\b/i.test(el.getAttribute('class') || '')
389
+ || (el.tagName === 'A' && !el.hasAttribute('href'))));
390
+ for (const box of document.querySelectorAll('input[type="checkbox"]')) {
391
+ if (box.checked || box.disabled) continue;
392
+ const labels = [...(box.labels || [])].filter(shown);
393
+ if (!shown(box) && !labels.length) continue;
394
+ const form = box.closest('form');
395
+ if (form && form.querySelector('input[type="password"]')) continue;
396
+ let text = labels.map(words).join(' ');
397
+ for (let el = box.parentElement, up = 0; el && up < 4 && !text; el = el.parentElement, up++) text = words(el);
398
+ if (!text || text.length > 600 || !AGREE.test(text) || !TERMS.test(text) || NOT.test(text)) continue;
399
+ if (!DOWNLOAD.test(text) && !held) continue;
400
+ document.querySelectorAll('[data-papersearch-download-terms]')
401
+ .forEach(el => el.removeAttribute('data-papersearch-download-terms'));
402
+ (shown(box) ? box : labels[0]).setAttribute('data-papersearch-download-terms', '1');
403
+ return text.slice(0, 200);
404
+ }
405
+ return '';
406
+ }"""
407
+
408
+ def _agree_to_download_terms(self, page: Any, result: DownloadResult) -> bool:
409
+ """Tick the site's box agreeing to its terms that holds back its download links
410
+ (``_DOWNLOAD_TERMS_JS``), on the article's own page, never a school's or a federation's;
411
+ True when ticked. The links are read after it, once the site's script has given them their
412
+ addresses."""
413
+ url = str(getattr(page, "url", "") or "")
414
+ if (not url.startswith("http") or self._is_idp_host(urlparse(url).netloc)
415
+ or self._school_or_federation_page(url.split("#", 1)[0], result, include_publisher_chooser=False)):
416
+ return False
417
+ try:
418
+ terms = page.evaluate(self._DOWNLOAD_TERMS_JS)
419
+ except Exception as exc:
420
+ if not _is_browser_error(exc):
421
+ raise
422
+ return False
423
+ if not terms or not isinstance(terms, str) or not self._click_control(
424
+ page, page.locator('[data-papersearch-download-terms="1"]').first, result, "agree to the download terms",
425
+ timeout_ms=3_000):
426
+ return False
427
+ self._event(result, "download_terms_agreed", f"{terms[:160]} @ {url[:160]}")
428
+ settle(page, 1_000)
429
+ return True
430
+
307
431
  def _nothing_tried_evidence(self, page: Any, doi: str) -> str:
308
432
  """The page and its access verdict, and the PDF addresses it offered."""
309
433
  try:
@@ -409,25 +533,38 @@ class CaptureMixin:
409
533
  fetched after the PDF, in the bridge, with the browser's session, or with the session
410
534
  kept here once the browser can no longer be asked then (``_fulltext_session``).
411
535
  ``target``: an address to read in a tab of its own instead (the article page again,
412
- once the school's login came later)."""
536
+ once the school's login came later). The address the adapter names for the full text
537
+ is opened only when the page the browser is on does not show it already."""
413
538
  if not self.config.get("fulltext") or getattr(result, "_fulltext_read", None):
414
539
  return
415
540
 
416
- target = self.adapter.fulltext_page_url(doi, str(getattr(page, "url", "") or "")) or target
541
+ named = self.adapter.fulltext_page_url(doi, str(getattr(page, "url", "") or ""))
542
+ target = named or target
417
543
  tab = None
418
544
  # The window says the Markdown's page is being read, then goes back to the part it was on.
419
545
  before = progress_reporter.current_part()
420
546
  progress_reporter.update(part="markdown", page_reading=True)
421
547
  try:
422
548
  with watchdog.operation(self.FULLTEXT_READ_SEC, "fulltext_page"):
549
+ if named and self._fulltext_shown_here(page):
550
+ # The article page shows its full text already: read here, not at the other
551
+ # address, which may serve less (MDPI, 2026-11-22: for 6 of 80 articles the
552
+ # article page was a full one by its size, the address with a query the abstract alone).
553
+ target = ""
554
+ gone = None
423
555
  if target:
424
556
  # The full text is another page than the article's (Thieme): a tab of its own.
425
557
  from .batch_common import open_page
426
558
 
427
559
  tab = page.context.new_page()
428
- open_page(tab, target, timeout_ms=30_000)
429
- read, why = self._read_fulltext_page(tab or page, doi, result)
430
- if read is None and why.startswith("fulltext_not_shown") and not self._pdf_only(why):
560
+ gone = self._page_not_found(open_page(tab, target, timeout_ms=30_000))
561
+ if gone:
562
+ # No such page: the article has no full text there (J-STAGE's articles with their
563
+ # PDF alone, whose full-text address is a 404), not a page to wait 15 s on.
564
+ read, why = None, f"fulltext_not_shown: {urlparse(target).hostname or ''} answered {gone}"
565
+ else:
566
+ read, why = self._read_fulltext_page(tab or page, doi, result)
567
+ if read is None and not gone and why.startswith("fulltext_not_shown") and not self._pdf_only(why):
431
568
  # No full text on the page: a paywall or a denial there is no access, not a
432
569
  # page without its text (pnas.org's "Get full access to this article",
433
570
  # said 文章页没有正文, 2026-11-17). The shared rules, as the access check reads them.
@@ -459,6 +596,19 @@ class CaptureMixin:
459
596
  self._event(result, "fulltext_page_read",
460
597
  f"{len(read['html'])} chars, {len(read['image_urls'])} images{prepared}{general}")
461
598
 
599
+ def _fulltext_shown_here(self, page: Any) -> bool:
600
+ """Whether the page shows the full text now, by the adapter's own rule: one look, no
601
+ wait; False when the browser cannot say."""
602
+ shown_js = getattr(self.adapter, "fulltext_shown_js", None)
603
+ if not shown_js:
604
+ return False
605
+ try:
606
+ return page.evaluate(shown_js) is True
607
+ except Exception as exc:
608
+ if not _is_browser_error(exc):
609
+ raise
610
+ return False
611
+
462
612
  # The longest wait for the page to load again before the second read.
463
613
  FULLTEXT_REREAD_SETTLE_MS = 5_000
464
614
 
@@ -511,6 +661,13 @@ class CaptureMixin:
511
661
  raise
512
662
  return ""
513
663
 
664
+ @staticmethod
665
+ def _page_not_found(response: Any) -> int | None:
666
+ """The status of a page that does not exist (404, 410), from its navigation's response;
667
+ None for any other, or when there is no response to ask."""
668
+ status = getattr(response, "status", None)
669
+ return status if isinstance(status, int) and status in (404, 410) else None
670
+
514
671
  @staticmethod
515
672
  def _pdf_only(why: str) -> bool:
516
673
  """The page is the PDF, or sends the reader to it for the text (``fulltext_page.PDF_ONLY``)."""
@@ -602,7 +759,9 @@ class CaptureMixin:
602
759
  ``"ip_blocked"`` if a publisher IP-block signal (403/429 or block page)
603
760
  was observed during capture, else ``None``.
604
761
  """
762
+
605
763
  self._event(result, "pdf_capture_started")
764
+ self._agree_to_download_terms(page, result)
606
765
  self._remember_listed_supplements(page, doi, result)
607
766
  captured: dict[str, Any] = {"bytes": None, "url": "", "deferred_url": "", "block_reason": None, "receiving": False,
608
767
  "suspect_block": None, "closed": False, "readers": set()}
@@ -1043,7 +1202,21 @@ class CaptureMixin:
1043
1202
  if not captured["bytes"] and self._pdf_step_hit_wall(page, result):
1044
1203
  return None, "", None
1045
1204
  if not captured["bytes"]:
1046
- if self._uses_article_pdf_validation() and not self._wait_for_challenge(page, result):
1205
+ if self._is_challenge_page(page) or self._challenge_shell(page):
1206
+ # The PDF link itself opened a verification page: the same
1207
+ # wait as anywhere else. It gets nothing? Then stop the
1208
+ # capture as at a login wall, so the article's school
1209
+ # login runs and the PDF is asked for again with the
1210
+ # session, instead of waiting on the user here (the PDF
1211
+ # address itself answers empty to Bright Data, 2026-11-25).
1212
+ if not self._wait_for_challenge(page, result, hand_over_only=True):
1213
+ if captured is not None:
1214
+ captured["login_wall"] = True
1215
+ return None, "", None
1216
+ if not captured["bytes"]:
1217
+ return None, "", captured["block_reason"]
1218
+ if (not captured["bytes"] and self._uses_article_pdf_validation()
1219
+ and not self._wait_for_challenge(page, result)):
1047
1220
  return None, "", captured["block_reason"]
1048
1221
  if entitlement_denied():
1049
1222
  return None, "", None
@@ -1083,6 +1256,12 @@ class CaptureMixin:
1083
1256
  continue
1084
1257
  if entitlement_denied():
1085
1258
  return None, "", None
1259
+ if self._paywall_answered_before_login(result):
1260
+ # The school's login first, then every address again (_paywall_answered_before_login).
1261
+ self._event(result, "pdf_candidates_after_login",
1262
+ f"{len(candidates) - candidates.index(pdf_url)} left: a PDF address answered with the "
1263
+ f"article's own page; the school's login first")
1264
+ return None, "", None
1086
1265
  self._raise_on_publisher_content_error(page)
1087
1266
  self._event(result, "pdf_candidate", pdf_url)
1088
1267
  begin("url", pdf_url, time.time())
@@ -1095,6 +1274,11 @@ class CaptureMixin:
1095
1274
  if captured.get("login_wall"):
1096
1275
  return None, "", None
1097
1276
  if self._is_challenge_page(page):
1277
+ # The same wait as everywhere else; nothing came? The
1278
+ # article's school login runs and the PDF is asked for
1279
+ # again with the session.
1280
+ if not self._wait_for_challenge(page, result, hand_over_only=True):
1281
+ captured["login_wall"] = True
1098
1282
  return None, final_url, captured["block_reason"]
1099
1283
  continue
1100
1284
  try:
@@ -1396,12 +1580,14 @@ class CaptureMixin:
1396
1580
  page, result, lambda href: self._article_pdf_link(href, keys, str(getattr(page, "url", "") or "")),
1397
1581
  "current-doi-pdf-link", drop_download=self.adapter.keeps_pdf_out_of_downloads):
1398
1582
  return True
1583
+ # A title or label naming PDF only on a control: Bioethics Open Research's "XML & PDF
1584
+ # downloads (all versions)" is the title of a counter in a list, clicked as the PDF (2026-11-24).
1399
1585
  selectors = (
1400
1586
  "a.xpl-btn-pdf",
1401
1587
  ".xpl-btn-pdf",
1402
1588
  "a.stats-document-lh-action-downloadPdf_3",
1403
- "[title*='PDF']",
1404
- "[aria-label*='PDF']",
1589
+ "a[title*='PDF'], button[title*='PDF'], [role='button'][title*='PDF']",
1590
+ "a[aria-label*='PDF'], button[aria-label*='PDF'], [role='button'][aria-label*='PDF']",
1405
1591
  "button:has-text('PDF')",
1406
1592
  "a:has-text('PDF')",
1407
1593
  )
@@ -1428,6 +1614,14 @@ class CaptureMixin:
1428
1614
  or re.search(r"\b(?:supplement(?:ary|al)?|supporting information|disclosure form)\b", text, re.I)):
1429
1615
  continue
1430
1616
  detail = {"selector": selector, "text": text[:200], "href": href[:300]}
1617
+ # In the tab whose PDF responses are watched, as ScienceDirect's: a
1618
+ # target=_blank link's PDF in a tab of its own is lost (IJOR's
1619
+ # Squarespace "PDF" button, 2026-11-25).
1620
+ try:
1621
+ control.evaluate(_SAME_TAB_JS, timeout=2_000)
1622
+ except Exception as exc:
1623
+ if not _is_browser_error(exc):
1624
+ raise
1431
1625
  if not self._click_control(page, control, result, f"pdf control: {selector}"):
1432
1626
  continue # nothing was clicked (script_click_failed)
1433
1627
  self._event(result, "pdf_button_clicked", json.dumps(detail, ensure_ascii=False))
@@ -1491,6 +1685,9 @@ class CaptureMixin:
1491
1685
  text: textOf(target).slice(0, 200),
1492
1686
  href: ((target.href || target.getAttribute('href') || target.getAttribute('formaction') || '') + '').slice(0, 300)
1493
1687
  };
1688
+ // In this tab, whose PDF responses are watched (_SAME_TAB_JS).
1689
+ const link = target.closest('a[target]');
1690
+ if (link && (link.getAttribute('target') || '').toLowerCase() === '_blank') link.setAttribute('target', '_self');
1494
1691
  target.click();
1495
1692
  return detail;
1496
1693
  }
@@ -347,6 +347,9 @@ class DownloadResult:
347
347
  fulltext_page: dict[str, Any] = field(default_factory=dict)
348
348
  #: Where a login that waited on the user ended (``_login_wait_page``).
349
349
  login_wait_page: str = ""
350
+ #: The kind of the last verification page this item waited on (a key of
351
+ #: ``browser.challenge.kinds.LABELS``), for the record (``_note_challenge_type``).
352
+ challenge_type: str = ""
350
353
  #: How the browser of this item started: who held its profile, the wait for
351
354
  #: it, the launch's seconds, a relaunch (``_launch_context``).
352
355
  browser_start: dict[str, Any] = field(default_factory=dict)
@@ -84,12 +84,12 @@ class DiagnosticsMixin:
84
84
  # choosing the school the page is not waiting for the user (JBJS on
85
85
  # OpenAthens, 2026-11-06: five remembered-school clicks in 25 s, no
86
86
  # main-frame navigation, and a "no progress" reminder in between).
87
- "sso_entry_clicked", "openathens_entry", "seamlessaccess_chooser_opened",
87
+ "sso_entry_clicked", "sso_entry_opened", "openathens_entry", "seamlessaccess_chooser_opened",
88
88
  "auto_remembered_entry", "institution_selected", "auto_institution_search",
89
89
  "institution_search_submitted", "institution_search_retyped",
90
90
  "institution_list_submitted", "institution_continue",
91
91
  "login_round_trip_returned", "redirect_page_passed",
92
- "publisher_terms_accepted", "idp_confirmation_accepted", "personal_account_offer_skipped",
92
+ "publisher_terms_accepted", "download_terms_agreed", "idp_confirmation_accepted", "personal_account_offer_skipped",
93
93
  }:
94
94
  activity.progress()
95
95
  # Only publish fixed phase text; event details can contain signed URLs.
@@ -103,6 +103,7 @@ class DiagnosticsMixin:
103
103
  "idp_confirmation_required": ("请在浏览器里确认学校认证页的提示(信息发送同意、使用条款或二次验证)", "waiting_login"),
104
104
  "idp_confirmation_accepted": ("已确认学校认证页的提示", "checking_access"),
105
105
  "publisher_terms_accepted": ("已同意出版社的条款", "checking_access"),
106
+ "download_terms_agreed": ("已勾选同意网站的下载条款", "fetching_pdf"),
106
107
  "login_attempt_started": ("正在尝试机构登录", "checking_access"),
107
108
  "login_retry_wait": ("机构登录暂未完成,准备重试", "checking_access"),
108
109
  "login_navigation_interrupted": ("登录跳转中断,检查是否可重试", "checking_access"),
@@ -204,6 +205,20 @@ class DiagnosticsMixin:
204
205
  if result is not None and took > self.LONG_WAIT_SEC:
205
206
  self._event(result, "wait", f"{what}: {took:.0f} s, ended: {why}")
206
207
 
208
+ def _note_challenge_type(self, page: Any, result: DownloadResult, *, title_and_url_only: bool = False) -> None:
209
+ """Which kind of verification the page is (``browser.challenge.kinds``), in the
210
+ record: an event when it is first seen or changes (a reCAPTCHA box that asks its
211
+ picture puzzle), and ``result.challenge_type``, which the failure record and the
212
+ CLI's summary name (the user, 2026-11-25). Only read, never acted on."""
213
+ from ..browser.challenge import kinds
214
+
215
+ kind = kinds.identify(page, title_and_url_only=title_and_url_only)
216
+ if kind == "other" and result.challenge_type:
217
+ return # a later look that tells less keeps what an earlier one told
218
+ if kind != result.challenge_type:
219
+ result.challenge_type = kind
220
+ self._event(result, "challenge_type", f"{kind}: {kinds.LABELS[kind]}")
221
+
207
222
  def _write_diagnostic(self, page: Any, result: DownloadResult, run_dir: Path) -> None:
208
223
  diag_dir = run_dir / "diagnostics" / safe_name(result.doi)
209
224
  diag_dir.mkdir(parents=True, exist_ok=True)
@@ -249,14 +264,19 @@ class DiagnosticsMixin:
249
264
  result.diagnostic_path = str(packet_path)
250
265
 
251
266
  def _denial_line(self, page: Any) -> str:
252
- """The page's denial (access_rules.denial_evidence) for the diagnostic, and
253
- why it is the school's: ``denial line: "<the page's words>" (after this
254
- item's school login)``."""
267
+ """The page's denial (access_rules.denial_evidence), else its offer, for the
268
+ diagnostic, and why it is the school's: ``denial line: "<the page's words>"
269
+ (after this item's school login)``."""
255
270
  try:
256
271
  snap = self._access_snapshot(page)
257
272
  except Exception:
258
273
  return "" # a probe for the diagnostic; the failure is reported either way
259
274
  evidence, named = access_rules.denial_evidence(snap.url, snap.lines, snap.probe)
275
+ if not evidence:
276
+ # An offer decided, the school signed in (``_no_access_after_login``: NEJM Catalyst's
277
+ # "Get Access", Taylor & Francis's "Purchase options"): its words, not "nothing saved".
278
+ offer = access_rules.offer_evidence(snap.lines, snap.probe, gate=False)
279
+ evidence = f'offer: "{offer}"' if offer else ""
260
280
  if not evidence:
261
281
  return ""
262
282
  try: