papersearch 0.4.10 → 0.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/LICENSE +1 -1
  2. package/NOTICE +23 -0
  3. package/README.en.md +127 -225
  4. package/README.md +127 -225
  5. package/assets/carsi-flow.en.png +0 -0
  6. package/assets/carsi-flow.png +0 -0
  7. package/assets/overview.en.png +0 -0
  8. package/assets/overview.png +0 -0
  9. package/carsi/README.md +1 -1
  10. package/carsi/paper_search_carsi/adapters/iop/__init__.py +8 -2
  11. package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +23 -0
  12. package/carsi/paper_search_carsi/assets/capsule.html +25 -8
  13. package/carsi/paper_search_carsi/browser/watchdog.py +53 -4
  14. package/carsi/paper_search_carsi/download_diagnostics.py +2 -1
  15. package/carsi/paper_search_carsi/engine/batch.py +8 -2
  16. package/carsi/paper_search_carsi/engine/batch_capture.py +41 -11
  17. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +3 -0
  18. package/carsi/paper_search_carsi/engine/batch_institution.py +32 -22
  19. package/carsi/paper_search_carsi/engine/batch_login.py +121 -16
  20. package/carsi/paper_search_carsi/engine/supplements.py +36 -2
  21. package/carsi/paper_search_carsi/progress_capsule.py +6 -2
  22. package/carsi/paper_search_carsi/progress_reporter.py +30 -13
  23. package/carsi/paper_search_carsi/progress_view.py +28 -12
  24. package/carsi/paper_search_carsi/server.py +7 -1
  25. package/dist/capabilities/journal-metrics/JournalMetricsService.d.ts.map +1 -1
  26. package/dist/capabilities/journal-metrics/JournalMetricsService.js +2 -1
  27. package/dist/capabilities/journal-metrics/JournalMetricsService.js.map +1 -1
  28. package/dist/capabilities/pdf-discovery/batch.d.ts +2 -0
  29. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  30. package/dist/capabilities/pdf-discovery/batch.js +45 -10
  31. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  32. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +7 -1
  33. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -1
  34. package/dist/capabilities/pdf-discovery/batchSummary.js +24 -0
  35. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -1
  36. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  37. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +4 -0
  38. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  39. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +3 -0
  40. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  41. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +29 -4
  42. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  43. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +2 -0
  44. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  45. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +2 -0
  46. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  47. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +12 -0
  48. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  49. package/dist/capabilities/pdf-discovery/tiers/publisherApi.d.ts.map +1 -1
  50. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js +2 -1
  51. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js.map +1 -1
  52. package/dist/cli.js +18 -7
  53. package/dist/cli.js.map +1 -1
  54. package/dist/config/ConfigService.d.ts.map +1 -1
  55. package/dist/config/ConfigService.js +28 -2
  56. package/dist/config/ConfigService.js.map +1 -1
  57. package/dist/config/apiKeySignup.d.ts +13 -0
  58. package/dist/config/apiKeySignup.d.ts.map +1 -0
  59. package/dist/config/apiKeySignup.js +32 -0
  60. package/dist/config/apiKeySignup.js.map +1 -0
  61. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  62. package/dist/infrastructure/runlog/failureClass.js +4 -0
  63. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  64. package/dist/management/capability-profile/index.d.ts +7 -0
  65. package/dist/management/capability-profile/index.d.ts.map +1 -1
  66. package/dist/management/capability-profile/index.js +7 -0
  67. package/dist/management/capability-profile/index.js.map +1 -1
  68. package/dist/management/carsi/installer.js +5 -5
  69. package/dist/management/carsi/installer.js.map +1 -1
  70. package/dist/management/diagnostics/index.d.ts.map +1 -1
  71. package/dist/management/diagnostics/index.js +4 -1
  72. package/dist/management/diagnostics/index.js.map +1 -1
  73. package/dist/management/failures/exportReport.js +3 -3
  74. package/dist/management/reports/index.d.ts.map +1 -1
  75. package/dist/management/reports/index.js +6 -1
  76. package/dist/management/reports/index.js.map +1 -1
  77. package/dist/platforms/SemanticScholarSearcher.d.ts.map +1 -1
  78. package/dist/platforms/SemanticScholarSearcher.js +2 -1
  79. package/dist/platforms/SemanticScholarSearcher.js.map +1 -1
  80. package/package.json +3 -2
  81. package/skills/paper-search/SKILL.md +5 -5
  82. package/skills/paper-search/references/browser-download.md +6 -5
  83. package/skills/paper-search/references/capability-routing.md +3 -3
  84. package/skills/paper-search/references/carsi-setup.md +1 -1
  85. package/skills/paper-search/references/cli-contract.md +2 -2
  86. package/skills/paper-search/references/management-layer.md +1 -1
  87. package/skills/paper-search/references/publisher-support.md +2 -0
  88. package/skills/paper-search/references/troubleshooting.md +1 -2
@@ -33,8 +33,10 @@ log = logging.getLogger(__name__)
33
33
  # timeout); waits for the user are made of short calls.
34
34
  LIMIT_SEC = 90
35
35
 
36
- _inflight: dict[int, tuple[float, str, list[str], Any, Any]] = {}
36
+ _inflight: dict[int, tuple[float, str, list[str], Any, Any, Any]] = {}
37
37
  _call_deadlines: dict[int, tuple[float, str]] = {}
38
+ # Calls dropped by :func:`abandon`: they end in :class:`CallAbandoned`.
39
+ _abandoned: set[int] = set()
38
40
  _local = threading.local()
39
41
  _installed = False
40
42
  # A browser call longer than this is reported to ``on_slow_call(name, seconds,
@@ -70,6 +72,50 @@ class BrowserBudgetExhausted(BrowserOperationTimeout):
70
72
  """No time remained to send another call; the driver did not stall."""
71
73
 
72
74
 
75
+ class CallAbandoned(Exception):
76
+ """A call whose answer is no longer wanted (:func:`abandon`)."""
77
+
78
+
79
+ def _greenlet() -> Any:
80
+ """The greenlet making a call: the driver runs each event handler in its own."""
81
+ try:
82
+ from greenlet import getcurrent
83
+ except ImportError:
84
+ return None
85
+ return getcurrent()
86
+
87
+
88
+ @contextmanager
89
+ def owned_by(owners: set):
90
+ """Mark the calls this greenlet makes meanwhile as ``owners``' (see :func:`abandon`)."""
91
+ me = _greenlet()
92
+ owners.add(me)
93
+ try:
94
+ yield
95
+ finally:
96
+ owners.discard(me)
97
+
98
+
99
+ def abandon(owners: set) -> int:
100
+ """Cancel the running calls of these greenlets without ending the browser: their
101
+ answer is no longer wanted. A response read in an event handler that never
102
+ returned was otherwise timed out 90 s later, and the article running then
103
+ (JAMA after AIAA's blocked PDF, 2026-11-08) ended as browser_unresponsive.
104
+ Returns how many were cancelled."""
105
+ count = 0
106
+ for key, entry in list(_inflight.items()):
107
+ if entry[5] is None or entry[5] not in owners:
108
+ continue
109
+ _abandoned.add(key)
110
+ _inflight.pop(key, None)
111
+ _call_deadlines.pop(key, None)
112
+ loop, coro = entry[3], entry[4]
113
+ if loop is not None and not loop.is_closed():
114
+ loop.call_soon_threadsafe(_cancel, coro)
115
+ count += 1
116
+ return count
117
+
118
+
73
119
  @contextmanager
74
120
  def operation(seconds: float, label: str):
75
121
  """One monotonic deadline shared by all calls and retries in this scope."""
@@ -148,12 +194,14 @@ def install(limit_sec: float = LIMIT_SEC) -> None:
148
194
  raise BrowserBudgetExhausted(f"{label} exhausted its page budget before {name}")
149
195
  _call_deadlines[key] = (deadline, label)
150
196
  _inflight[key] = (started, name, traceback.format_stack(limit=8)[:-1],
151
- getattr(self, "_loop", None), coro)
197
+ getattr(self, "_loop", None), coro, _greenlet())
152
198
  ended = "returned"
153
199
  try:
154
200
  return original(self, coro)
155
201
  except asyncio.CancelledError:
156
202
  ended = "cancelled"
203
+ if key in _abandoned:
204
+ raise CallAbandoned(name) from None
157
205
  if fired is not None:
158
206
  raise _timeout_error() from None
159
207
  if interrupted is not None:
@@ -165,6 +213,7 @@ def install(limit_sec: float = LIMIT_SEC) -> None:
165
213
  finally:
166
214
  _inflight.pop(key, None)
167
215
  _call_deadlines.pop(key, None)
216
+ _abandoned.discard(key)
168
217
  elapsed = time.monotonic() - started
169
218
  _period["calls"] += 1
170
219
  _period["seconds"] += elapsed
@@ -209,7 +258,7 @@ def check(limit_sec: float) -> bool:
209
258
  if not overdue:
210
259
  return False
211
260
  key, entry = min(overdue, key=lambda pair: pair[1][0])
212
- started, name, stack, loop, coro = entry
261
+ started, name, stack, loop, coro, _ = entry
213
262
  fired = {"call": name, "seconds": int(now - started)}
214
263
  deadline = deadlines.get(key)
215
264
  if deadline and deadline[0] <= now and deadline[0] <= started + limit_sec:
@@ -230,7 +279,7 @@ def interrupt(exc: BaseException) -> None:
230
279
  call raise ``exc`` until :func:`clear_interrupt`."""
231
280
  global interrupted
232
281
  interrupted = exc
233
- for _, _, _, loop, coro in list(_inflight.values()):
282
+ for _, _, _, loop, coro, _ in list(_inflight.values()):
234
283
  if loop is not None and not loop.is_closed():
235
284
  loop.call_soon_threadsafe(_cancel, coro)
236
285
 
@@ -43,7 +43,7 @@ challenge_or_viewer_timeout challenge_resolved challenge_wait cookie_banner_dism
43
43
  advertisement_closed pdf_step_article_page institution_choice_returned_article institution_choice_stopped
44
44
  cookie_inject_failed download_capture_error elsevier_institution_entry_error
45
45
  institution_continue institution_continue_error institution_entry_unresolved institution_federation_selected
46
- institution_search_error institution_search_retyped institution_session_other idp_confirmation_required
46
+ institution_search_error institution_search_retyped institution_session_other idp_confirmation_accepted idp_confirmation_required
47
47
  institution_required institution_search institution_search_submitted
48
48
  institution_select_error institution_selected institution_selection_required
49
49
  institution_session_return_article institution_session_return_error
@@ -56,6 +56,7 @@ pdf_capture_started pdf_navigation_error pdf_saved pdf_state_candidate post_logi
56
56
  post_login_hold_article_access post_login_hold_auth_wall post_login_hold_login_page
57
57
  post_run_hold publisher_access_blocked publisher_content_error publisher_unreachable publisher_login_menu_opened
58
58
  publisher_pdf_link_unverified publisher_session_save_failed publisher_session_saved
59
+ publisher_terms_accepted
59
60
  record_article_return record_article_return_error seamlessaccess_chooser_opened
60
61
  shared_cookies_exported shared_cookies_loaded sso_entry_clicked sso_entry_error sso_start
61
62
  access_unknown_pdf_first access_unknown_pdf_failed pdf_step_login_required login_round_trip_returned
@@ -289,7 +289,10 @@ class PublisherBatchDownloader(
289
289
  if not _is_browser_error(exc):
290
290
  raise
291
291
  self._event(result, "supplements_failed", f"{type(exc).__name__}: {str(exc)[:160]}")
292
- return [{"status": "failed", "reason": type(exc).__name__, "url": "", "label": ""}]
292
+ # The site did not answer, not the error's class name ("Error": pubs.acs.org
293
+ # closed the connection on every try, Windows 2026-11-07).
294
+ reason = "publisher_unreachable" if _is_network_failure(exc) else type(exc).__name__
295
+ return [{"status": "failed", "reason": reason, "url": "", "label": ""}]
293
296
  finally:
294
297
  user_watch.set()
295
298
  watchdog.clear_interrupt()
@@ -311,7 +314,10 @@ class PublisherBatchDownloader(
311
314
  own = self.adapter.supplement_links(page, doi)
312
315
  external = external_links(page, doi)
313
316
  if own is None and external is None:
314
- return None
317
+ from ..adapters.platforms.silverchair import declares_no_supplements
318
+
319
+ # No rule found files, but the page itself may say there are none.
320
+ return [] if declares_no_supplements(page, doi) else None
315
321
  return list(dict.fromkeys([*(own or []), *(external or [])]))
316
322
  except Exception as exc:
317
323
  if (attempt == 2 or not _is_browser_error(exc)
@@ -150,7 +150,7 @@ class CaptureMixin:
150
150
  getattr(self, "_fallback_pdf", None))
151
151
  self._capture_doi = (doi or "").lower()
152
152
  self._expected_title = self._citation_title(page) or getattr(self, "_record_title", "")
153
- self._show_title()
153
+ self._show_title(page)
154
154
  try:
155
155
  try:
156
156
  tabs = [tab for tab in list(page.context.pages) if not tab.is_closed()]
@@ -208,7 +208,7 @@ class CaptureMixin:
208
208
  self._phase(result, "pdf")
209
209
  self._capture_doi = (doi or "").lower()
210
210
  self._expected_title = self._citation_title(page) or getattr(self, "_record_title", "")
211
- self._show_title()
211
+ self._show_title(page)
212
212
  self._fallback_pdf = None
213
213
  tried_before = len(result.pdf_attempts)
214
214
  try:
@@ -311,9 +311,22 @@ class CaptureMixin:
311
311
  return ""
312
312
  return " ".join(value.split()) if isinstance(value, str) else ""
313
313
 
314
- def _show_title(self) -> None:
315
- """The article's title in the progress window, once its page names it."""
316
- title = getattr(self, "_expected_title", "")
314
+ @staticmethod
315
+ def _dublin_core_title(page: Any) -> str:
316
+ """The article page's Dublin Core title (dc.Title), which Atypon sites such
317
+ as SIAM give without a citation_title (2026-11-08). For display only."""
318
+ try:
319
+ value = page.evaluate(
320
+ "() => (document.querySelector('meta[name=\"dc.title\" i]') || {}).content || ''")
321
+ except Exception:
322
+ return ""
323
+ return " ".join(value.split()) if isinstance(value, str) else ""
324
+
325
+ def _show_title(self, page: Any = None) -> None:
326
+ """The article's title in the progress window, once its page names it: the
327
+ title the identity check uses, else the page's Dublin Core title (only shown,
328
+ never checked against: the capsule showed the DOI instead, 2026-11-08)."""
329
+ title = getattr(self, "_expected_title", "") or (self._dublin_core_title(page) if page is not None else "")
317
330
  if not title or title == getattr(self, "_shown_title", ""):
318
331
  return
319
332
  self._shown_title = title
@@ -333,7 +346,7 @@ class CaptureMixin:
333
346
  """
334
347
  self._event(result, "pdf_capture_started")
335
348
  captured: dict[str, Any] = {"bytes": None, "url": "", "deferred_url": "", "block_reason": None,
336
- "suspect_block": None}
349
+ "suspect_block": None, "closed": False, "readers": set()}
337
350
  cdp_session = None
338
351
  native_redirects: dict[str, list[Any]] = {}
339
352
  cdn_redirects: dict[str, list[Any]] = {}
@@ -387,7 +400,9 @@ class CaptureMixin:
387
400
  url = event.get("request", {}).get("url", "")
388
401
  response = SimpleNamespace(url=url, status=200, headers={}, history=history)
389
402
  urls = self._response_urls(response)
390
- if (self.adapter.is_pdf_cdn_url(url, doi)
403
+ # Kept by address too: Chrome can answer the final PDF under another
404
+ # request id. The bound PDF's own file on its CDN is one (RSC, 2026-11-07).
405
+ if ((self.adapter.is_pdf_cdn_url(url, doi) or self._bound_pdf_copy(url, response, doi, article_options))
391
406
  and self._response_matches_article(response, doi, **article_options)):
392
407
  cdn_redirects[url] = list(history)
393
408
  if (any(hop in rejected_pdf_urls for hop in urls)
@@ -408,11 +423,16 @@ class CaptureMixin:
408
423
  for header in event.get("responseHeaders", [])
409
424
  }
410
425
  url = event.get("request", {}).get("url", "")
426
+ history = native_redirects.get(event.get("networkId", ""), []) or cdn_redirects.get(url, [])
411
427
  if (self.adapter.discards_unbound_pdfs
412
428
  and "application/pdf" in headers.get("content-type", "").lower()
413
429
  and (url in rejected_pdf_urls or self._is_supplementary_url(url)
414
430
  or self._is_supplementary_url(headers.get("content-disposition", ""))
415
- or not self._article_pdf_url_matches(url, doi, **article_options))):
431
+ or not (self._article_pdf_url_matches(url, doi, **article_options)
432
+ # The bound PDF's own file on the host its address redirects
433
+ # to (RSC's article-pdf -> rscj.silverchair-cdn.com, 2026-11-07).
434
+ or self._bound_pdf_copy(url, SimpleNamespace(url=url, history=history),
435
+ doi, article_options)))):
416
436
  rejected_pdf_urls.add(url)
417
437
  return
418
438
  if ("application/pdf" in headers.get("content-type", "").lower()
@@ -437,7 +457,6 @@ class CaptureMixin:
437
457
  # response.body(). Apply the same article/attachment guards
438
458
  # before reading the response through CDP instead.
439
459
  if self._uses_article_pdf_validation():
440
- history = native_redirects.get(event.get("networkId", ""), []) or cdn_redirects.get(url, [])
441
460
  response = SimpleNamespace(
442
461
  url=url, headers=headers,
443
462
  status=event.get("responseStatusCode", 0), history=history,
@@ -496,6 +515,12 @@ class CaptureMixin:
496
515
  self._event(result, "browser_response_continue_error", type(exc).__name__)
497
516
 
498
517
  def on_response(response: Any) -> None:
518
+ # A response handled after this capture is over reads nothing: a body
519
+ # read that never returned there (after AIAA's blocked PDF) stopped the
520
+ # watchdog for the whole process, and the next article with it
521
+ # (Chicago, browser_unresponsive, 2026-11-07).
522
+ if captured["closed"]:
523
+ return
499
524
  # The tab's own document answers, for the attempt's record.
500
525
  try:
501
526
  request = getattr(response, "request", None)
@@ -539,7 +564,8 @@ class CaptureMixin:
539
564
  if self._uses_article_pdf_validation() else True)
540
565
  if relevant:
541
566
  try:
542
- snippet = response.text()[:8192] if hasattr(response, "text") else response.body()
567
+ with watchdog.owned_by(captured["readers"]):
568
+ snippet = response.text()[:8192] if hasattr(response, "text") else response.body()
543
569
  except Exception:
544
570
  snippet = ""
545
571
  text = self._visible_text_excerpt(snippet)
@@ -577,7 +603,7 @@ class CaptureMixin:
577
603
  if self._should_defer_response_body(url):
578
604
  captured["deferred_url"] = url
579
605
  return
580
- with transfer(result):
606
+ with transfer(result), watchdog.owned_by(captured["readers"]):
581
607
  body = response.body()
582
608
  # Body-level block-page detection (some block pages are 200
583
609
  # with an HTML "IP Address Blocked" body).
@@ -819,6 +845,10 @@ class CaptureMixin:
819
845
  if block_reason and not captured["block_reason"]:
820
846
  captured["block_reason"] = block_reason
821
847
  finally:
848
+ captured["closed"] = True
849
+ # A response still being read is not wanted any more (see watchdog.abandon).
850
+ if watchdog.abandon(captured["readers"]):
851
+ self._event(result, "pdf_response_read_abandoned", "capture ended")
822
852
  finish()
823
853
  if cdp_session is not None:
824
854
  try:
@@ -89,6 +89,7 @@ class DiagnosticsMixin:
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",
92
93
  }:
93
94
  activity.progress()
94
95
  # Only publish fixed phase text; event details can contain signed URLs.
@@ -100,6 +101,8 @@ class DiagnosticsMixin:
100
101
  "institution_entry_unresolved": ("官方机构入口尚未确认 CARSI", "checking_access"),
101
102
  "login_state": ("检查机构登录页面", "checking_access"),
102
103
  "idp_confirmation_required": ("请在浏览器里确认学校认证页的提示(信息发送同意、使用条款或二次验证)", "waiting_login"),
104
+ "idp_confirmation_accepted": ("已确认学校认证页的提示", "checking_access"),
105
+ "publisher_terms_accepted": ("已同意出版社的条款", "checking_access"),
103
106
  "login_attempt_started": ("正在尝试机构登录", "checking_access"),
104
107
  "login_retry_wait": ("机构登录暂未完成,准备重试", "checking_access"),
105
108
  "login_navigation_interrupted": ("登录跳转中断,检查是否可重试", "checking_access"),
@@ -663,9 +663,11 @@ class InstitutionMixin:
663
663
  # school failed the article, 2026-11-01): the page has gone on.
664
664
  return True
665
665
 
666
+ # The school's name may follow "for" with no space: RSNA writes
667
+ # "for<em>Example University</em>" (2026-11-07).
666
668
  _NO_INSTITUTION_SEARCH_RESULTS = re.compile(
667
- r"^(?:no (?:institutions?|results?|matches) found(?:[.!]?$|\s+for\b)"
668
- r"|we couldn['’]t find any results? for\b)", re.I)
669
+ r"^(?:no (?:institutions?|results?|matches) found(?:[.!]?$|\s+for)"
670
+ r"|we couldn['’]t find any results? for)", re.I)
669
671
  _INSTITUTION_LIST_LINK = re.compile(r"^(?:select|choose) (?:your|an) institution from (?:a|the) list$", re.I)
670
672
 
671
673
  def _handle_institution_search_miss(self, page: Any, result: DownloadResult, url: str) -> bool:
@@ -680,27 +682,35 @@ class InstitutionMixin:
680
682
  if notice.is_visible() is not True:
681
683
  return False # no candidate yet does not establish an empty result
682
684
  message = notice.inner_text(timeout=800)
683
- named = re.split(r"\bfor\b", message, maxsplit=1, flags=re.I)[1:]
684
- for selector in self._institution_search_selectors(page):
685
- box = page.locator(selector).first
686
- if box.is_visible() is not True:
687
- continue
688
- typed = str(box.input_value(timeout=800) or "").strip()
689
- if f"{typed} @ {url}" not in queries:
690
- continue
691
- if named and self._canonical_school_name(named[0]) != self._canonical_school_name(typed):
692
- continue # the reply names a different query
693
- listing = page.get_by_role("link", name=self._INSTITUTION_LIST_LINK).filter(visible=True).first
694
- if listing.is_visible() is True:
695
- href = listing.get_attribute("href", timeout=800)
696
- if (href and self._manual_institution_target_allowed(urljoin(url, href))
697
- and self._click_control(page, listing, result, "open institution list")):
698
- self._event(result, "auto_institution_list_opened", url)
699
- return True
700
- return False # there is another route; don't call the school missing
701
- self._event(result, "auto_institution_not_found", f"{message[:120]} @ {url}")
702
- result._institution_not_listed = True
685
+ named = re.split(r"\bfor", message, maxsplit=1, flags=re.I)[1:]
686
+ ours = {q.rsplit(" @ ", 1)[0] for q in queries if q.endswith(f" @ {url}")}
687
+ typed = [str(box.input_value(timeout=800) or "").strip()
688
+ for box in (page.locator(selector).first for selector in self._institution_search_selectors(page))
689
+ if box.is_visible() is True]
690
+ if any(typed) and not any(value in ours for value in typed):
691
+ return False # the box holds another query now: the reply is not about ours
692
+ if named:
693
+ # The reply names the query it answers. RSNA's box, once it held the
694
+ # name, had lost the placeholder it was found by, and the miss went
695
+ # unseen until the page wait ran out (2026-11-08).
696
+ if not any(self._canonical_school_name(named[0]) == self._canonical_school_name(q) for q in ours):
697
+ return False # the reply names a different query
698
+ elif not any(value in ours for value in typed):
703
699
  return False
700
+ listing = page.get_by_role("link", name=self._INSTITUTION_LIST_LINK).filter(visible=True).first
701
+ if listing.is_visible() is True:
702
+ href = listing.get_attribute("href", timeout=800)
703
+ if (href and self._manual_institution_target_allowed(urljoin(url, href))
704
+ and self._click_control(page, listing, result, "open institution list")):
705
+ self._event(result, "auto_institution_list_opened", url)
706
+ return True
707
+ if not any(e["state"] == "auto_institution_list_refused" and e.get("detail", "").endswith(url)
708
+ for e in result.events):
709
+ self._event(result, "auto_institution_list_refused", f"{str(href)[:160]} @ {url}")
710
+ return False # there is another route; don't call the school missing
711
+ self._event(result, "auto_institution_not_found", f"{message[:120]} @ {url}")
712
+ result._institution_not_listed = True
713
+ return False
704
714
  except Exception as exc:
705
715
  if not _is_browser_error(exc):
706
716
  raise
@@ -422,8 +422,9 @@ class LoginMixin:
422
422
  self._event(result, "login_state", marker)
423
423
  last_state = marker
424
424
  confirmation = self._idp_confirmation(page)
425
- if confirmation:
426
- # The user decides: the engine never agrees on their behalf.
425
+ if confirmation and confirmation not in self.IDP_ACCEPTED_CONFIRMATIONS:
426
+ # A second factor (Duo) is the user's; the agreements are
427
+ # accepted below (_accept_idp_confirmation).
427
428
  self._event(result, "idp_confirmation_required", confirmation)
428
429
  page_since = time.time()
429
430
  elif self._user_away:
@@ -439,6 +440,8 @@ class LoginMixin:
439
440
  continue
440
441
  if self._return_from_login_site(page, result):
441
442
  continue
443
+ if self._accept_publisher_terms(page, result) or self._accept_idp_confirmation(page, result):
444
+ continue
442
445
  if manual_selection:
443
446
  if self._is_challenge_page(page):
444
447
  if not self._wait_for_challenge(page, result, deadline=deadline):
@@ -563,6 +566,91 @@ class LoginMixin:
563
566
  : document.querySelector('[name="_shib_idp_consentOptions"], [name="_shib_idp_consentIds"]') ? 'attribute-release' : ''"""
564
567
  _IDP_ERROR_RE = re.compile(r"未知错误|系统错误|服务异常|认证失败|出错了|\b5\d{4}\b.{0,20}错误|an unexpected error|error code|system error", re.I)
565
568
 
569
+ # A publisher's own terms form on the way to the school: SIAM's SAML consent
570
+ # ("I have read and agree to the Terms and Conditions and Privacy Policy.",
571
+ # Atypon's /action/saml2post) held the login until the page wait ran out
572
+ # (2026-11-07). The user asked to have such forms accepted (2026-11-08). Only
573
+ # on the publisher's site; the school's own: ``_accept_idp_confirmation``.
574
+ _PUBLISHER_TERMS_JS = r"""() => {
575
+ const visible = el => !!el && el.getClientRects().length > 0;
576
+ for (const form of document.querySelectorAll('form')) {
577
+ if (!visible(form)) continue;
578
+ const text = (form.innerText || '').replace(/\s+/g, ' ').trim();
579
+ if (text.length > 300 || !/^I (?:have read and )?(?:agree|accept) to the ?Terms\b/i.test(text)) continue;
580
+ const yes = [...form.querySelectorAll('input[type=submit], button[type=submit], button:not([type])')]
581
+ .find(el => visible(el) && !/^\s*(?:no|cancel|decline)\b/i.test(el.value || el.innerText || ''));
582
+ if (!yes) continue;
583
+ yes.setAttribute('data-papersearch-terms', '1');
584
+ return text.slice(0, 120);
585
+ }
586
+ return '';
587
+ }"""
588
+ PUBLISHER_TERMS_TRIES = 2
589
+
590
+ def _accept_publisher_terms(self, page: Any, result: DownloadResult) -> bool:
591
+ """Agree to a publisher's terms form shown during the login; True when clicked."""
592
+ url = str(getattr(page, "url", "") or "")
593
+ if (not self._on_publisher_host(url) or self._is_idp_host(urlparse(url).netloc)
594
+ or sum(e["state"] == "publisher_terms_accepted" for e in result.events) >= self.PUBLISHER_TERMS_TRIES):
595
+ return False
596
+ try:
597
+ terms = page.evaluate(self._PUBLISHER_TERMS_JS)
598
+ except Exception as exc:
599
+ if not _is_browser_error(exc):
600
+ raise
601
+ return False
602
+ if not terms or not self._click_control(page, page.locator('[data-papersearch-terms="1"]').first,
603
+ result, "accept the publisher's terms"):
604
+ return False
605
+ self._event(result, "publisher_terms_accepted", f"{terms} @ {url[:160]}")
606
+ settle(page, 2_000)
607
+ return True
608
+
609
+ # The school's IdP asking to agree before it goes on (Shibboleth's attribute
610
+ # release and terms of use): accepted for the user too, as they asked
611
+ # (2026-11-08). The release keeps the choices the school preselected; the
612
+ # terms' own "I accept" box is ticked. A second factor (Duo) stays the user's,
613
+ # and so does a confirmation still shown after two accepts in one article.
614
+ IDP_ACCEPTED_CONFIRMATIONS = ("attribute-release", "terms-of-use")
615
+ IDP_CONFIRMATION_TRIES = 2
616
+ _IDP_ACCEPT_JS = r"""(kind) => {
617
+ const visible = el => !!el && el.getClientRects().length > 0;
618
+ const proceed = [...document.querySelectorAll('[name="_eventId_proceed"]')].find(visible);
619
+ if (!proceed) return false;
620
+ if (kind === 'terms-of-use' && proceed.form)
621
+ for (const box of proceed.form.querySelectorAll('input[type=checkbox][name="_shib_idp_consentIds"]'))
622
+ if (!box.checked && visible(box)) box.setAttribute('data-papersearch-idp', 'tick');
623
+ proceed.setAttribute('data-papersearch-idp', 'proceed');
624
+ return true;
625
+ }"""
626
+
627
+ def _accept_idp_confirmation(self, page: Any, result: DownloadResult) -> bool:
628
+ """Agree to the school's attribute release or terms of use; True when clicked.
629
+ Otherwise the user is told once that the page waits for them."""
630
+ kind = self._idp_confirmation(page)
631
+ if kind not in self.IDP_ACCEPTED_CONFIRMATIONS:
632
+ return False
633
+ url = str(getattr(page, "url", "") or "").split("?", 1)[0]
634
+ if sum(e["state"] == "idp_confirmation_accepted" for e in result.events) < self.IDP_CONFIRMATION_TRIES:
635
+ try:
636
+ ready = page.evaluate(self._IDP_ACCEPT_JS, kind)
637
+ except Exception as exc:
638
+ if not _is_browser_error(exc):
639
+ raise
640
+ ready = False
641
+ if ready:
642
+ for box in page.locator('[data-papersearch-idp="tick"]').all():
643
+ self._click_control(page, box, result, "tick the school's terms of use")
644
+ if self._click_control(page, page.locator('[data-papersearch-idp="proceed"]').first,
645
+ result, "accept the school's confirmation"):
646
+ self._event(result, "idp_confirmation_accepted", f"{kind} @ {url[:160]}")
647
+ settle(page, 2_000)
648
+ return True
649
+ if getattr(result, "_idp_confirmation_left", "") != kind:
650
+ result._idp_confirmation_left = kind
651
+ self._event(result, "idp_confirmation_required", kind)
652
+ return False
653
+
566
654
  def _idp_confirmation(self, page: Any) -> str:
567
655
  """What the school's IdP asks the user to agree to, if anything: Shibboleth's
568
656
  attribute release or terms of use, or a Duo second factor."""
@@ -628,6 +716,7 @@ class LoginMixin:
628
716
  r"|sorry, you have been blocked|no institutions found|not registered for use with this service"
629
717
  r"|application you have accessed is not registered|may not be enabled for this type of authentication"
630
718
  r"|can't find your institution|access to this resource has been restricted by your organization|oa-ap-4032"
719
+ r"|不支持的请求|does not have access to this resource"
631
720
  r"|temporarily unavailable|verify you are human|are you a robot|checking your browser|正在进行安全验证", re.I)
632
721
 
633
722
  def _login_block_reason(self, page: Any) -> str:
@@ -641,7 +730,9 @@ class LoginMixin:
641
730
  if code == "login_page_closed":
642
731
  return "the browser window was closed"
643
732
  if code == "institution_pdf_entitlement_missing":
644
- return self._denial_line(page)
733
+ line = self._denial_line(page)
734
+ if line:
735
+ return line
645
736
  lists = self._federation_list_lacks_carsi(page) if code == "institution_federation_unavailable" else ""
646
737
  if lists:
647
738
  return f"the federation list has no CARSI entry ({lists})"[:240]
@@ -698,6 +789,15 @@ class LoginMixin:
698
789
  return override
699
790
  if "unsupported request" in haystack and "not registered for use with this service" in haystack:
700
791
  return "institution_not_registered"
792
+ # The same Shibboleth page in Chinese: "Web登陆服务 - 不支持的请求" on the
793
+ # school's IdP, the school has not enabled this publisher (JAMA, 2026-11-07).
794
+ if "不支持的请求" in haystack and self._is_idp_host(urlparse(current_url).netloc):
795
+ return "institution_not_registered"
796
+ # LibLynx (De Gruyter's chooser) after the school was chosen: "<school> does
797
+ # not have access to this resource", the publisher denies the school (2026-11-07).
798
+ if ("does not have access to this resource" in haystack
799
+ and any(name.lower() in haystack for name in self._institution_names() if name)):
800
+ return "institution_pdf_entitlement_missing"
701
801
  if "application you have accessed is not registered" in haystack:
702
802
  return "institution_not_registered"
703
803
  if "your institution may not be enabled for this type of authentication" in haystack:
@@ -884,22 +984,27 @@ class LoginMixin:
884
984
 
885
985
  # Controls that open a site's access menu or login panel instead of a page:
886
986
  # "GET ACCESS" and "Login / Register" on ascelibrary.org (2026-11-02), "Access
887
- # options", "Sign in". A link to a login page is not one of them.
987
+ # options", "Sign in". A link to a login page is not one of them. An access
988
+ # menu comes first: SIAM's "Register / Sign In", earlier on the page than its
989
+ # "Get Access", went to its personal account sign-in (2026-11-08).
888
990
  _ACCESS_MENU_JS = r"""() => {
889
991
  const shown = el => el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden';
890
- const MENU = /^(?:get access|access options|(?:log ?in|sign ?in)(?: ?\/ ?register)?|register ?\/ ?(?:log ?in|sign ?in))$/i;
992
+ const MENUS = [/^(?:get access|access options)$/i,
993
+ /^(?:(?:log ?in|sign ?in)(?: ?\/ ?register)?|register ?\/ ?(?:log ?in|sign ?in))$/i];
891
994
  const TOGGLES = ['aria-haspopup', 'aria-expanded', 'aria-controls', 'data-toggle', 'data-bs-toggle', 'data-target'];
892
- for (const el of document.querySelectorAll('button, [role="button"], a')) {
893
- if (!shown(el) || el.closest('form')) continue;
894
- const label = (el.innerText || el.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim();
895
- // A screen-reader hint can be part of innerText ("Sign In Open Menu").
896
- const menuLabel = label.replace(/\s+open menu$/i, '');
897
- if (!MENU.test(menuLabel)) continue;
898
- const href = (el.getAttribute('href') || '').trim();
899
- if (el.tagName === 'A' && href && !href.startsWith('#') && !/^javascript:/i.test(href)
900
- && !TOGGLES.some(name => el.hasAttribute(name))) continue;
901
- el.click();
902
- return label;
995
+ for (const MENU of MENUS) {
996
+ for (const el of document.querySelectorAll('button, [role="button"], a')) {
997
+ if (!shown(el) || el.closest('form')) continue;
998
+ const label = (el.innerText || el.getAttribute('aria-label') || '').replace(/\s+/g, ' ').trim();
999
+ // A screen-reader hint can be part of innerText ("Sign In Open Menu").
1000
+ const menuLabel = label.replace(/\s+open menu$/i, '');
1001
+ if (!MENU.test(menuLabel)) continue;
1002
+ const href = (el.getAttribute('href') || '').trim();
1003
+ if (el.tagName === 'A' && href && !href.startsWith('#') && !/^javascript:/i.test(href)
1004
+ && !TOGGLES.some(name => el.hasAttribute(name))) continue;
1005
+ el.click();
1006
+ return label;
1007
+ }
903
1008
  }
904
1009
  return '';
905
1010
  }"""
@@ -117,6 +117,35 @@ def _get(request: Any, url: str, entry: dict[str, Any], sleep) -> Any:
117
117
  return request.get(url, timeout=REQUEST_TIMEOUT_MS)
118
118
 
119
119
 
120
+ # Response headers that name what answered instead of the file (a CDN's or a
121
+ # firewall's challenge, a login service), kept for the record.
122
+ _PAGE_HEADERS = ("server", "x-amzn-waf-action", "cf-mitigated", "location")
123
+
124
+
125
+ def _page_evidence(response: Any) -> dict[str, Any]:
126
+ """What a page received instead of a file was: its status, final address
127
+ (no query), title and telling headers. Figshare's download address answered a
128
+ page and nothing said which (AIP, Royal Society, AACR; 2026-11-08)."""
129
+ evidence: dict[str, Any] = {"http_status": getattr(response, "status", None)}
130
+ url = str(getattr(response, "url", "") or "")
131
+ if url:
132
+ evidence["final_url"] = url.split("?", 1)[0][:300]
133
+ headers = getattr(response, "headers", None) or {}
134
+ named = {key: str(headers.get(key))[:120] for key in _PAGE_HEADERS if headers.get(key)}
135
+ if named:
136
+ evidence["page_headers"] = named
137
+ try:
138
+ text = response.body()[:65536].decode("utf-8", "replace")
139
+ except Exception:
140
+ return evidence
141
+ title = re.search(r"<title[^>]*>(.*?)</title>", text, re.I | re.S)
142
+ if title:
143
+ from html import unescape
144
+
145
+ evidence["page_title"] = " ".join(unescape(title.group(1)).split())[:160]
146
+ return evidence
147
+
148
+
120
149
  def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi: str, *,
121
150
  clock=time.monotonic, sleep=time.sleep,
122
151
  manifest_dir: Path | None = None,
@@ -171,8 +200,13 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
171
200
  elif length > MAX_FILE_BYTES:
172
201
  entry.update(status="skipped", reason="too_large", size=length)
173
202
  elif "text/html" in content_type.lower():
174
- # A login wall or landing page instead of the file.
175
- entry.update(status="failed", reason="html_page")
203
+ # A login wall or landing page instead of the file: which one, for the record.
204
+ # A firewall's human verification page is told apart (Figshare's AWS WAF,
205
+ # 2026-11-08): the site stopped the request, the file may well exist.
206
+ evidence = _page_evidence(response)
207
+ headers = evidence.get("page_headers") or {}
208
+ challenged = "challenge" in (headers.get("x-amzn-waf-action"), headers.get("cf-mitigated"))
209
+ entry.update(status="failed", reason="verification_page" if challenged else "html_page", **evidence)
176
210
  else:
177
211
  name = _file_name(link.url, str(response.headers.get("content-disposition", "") or ""), taken,
178
212
  link.label, content_type)
@@ -177,11 +177,15 @@ class Api:
177
177
  from .entitlements import SHOW_BROWSER, request_action
178
178
 
179
179
  if action == SHOW_BROWSER:
180
+ # Asked for from a reminder, or from the paper on the card at any
181
+ # time while it has a browser (user request, 2026-11-08).
180
182
  state = read_state() or {}
181
- if (state.get("status") != "running" or not state.get("attention")
183
+ if (state.get("status") != "running"
182
184
  or str(state.get("current") or "") != current
183
185
  or str(state.get("run_id") or "") != run_id):
184
- return "当前没有等待处理的下载浏览器"
186
+ return "当前没有正在下载的浏览器"
187
+ if not state.get("attention") and state.get("channel"):
188
+ return "这一篇在查开放来源,没有打开浏览器"
185
189
  if sys.platform == "darwin":
186
190
  from .browser.foreground import activate_mac
187
191