papersearch 0.4.9 → 0.4.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/LICENSE +1 -1
  2. package/NOTICE +23 -0
  3. package/README.en.md +136 -247
  4. package/README.md +136 -247
  5. package/assets/carsi-flow.en.png +0 -0
  6. package/assets/carsi-flow.png +0 -0
  7. package/assets/overview.en.png +0 -0
  8. package/assets/overview.png +0 -0
  9. package/assets/progress-capsule.en.png +0 -0
  10. package/assets/progress-capsule.png +0 -0
  11. package/carsi/README.md +6 -7
  12. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
  13. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
  14. package/carsi/paper_search_carsi/adapters/iop/__init__.py +8 -2
  15. package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
  16. package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
  17. package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
  18. package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
  19. package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +23 -0
  20. package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
  21. package/carsi/paper_search_carsi/assets/capsule.html +134 -18
  22. package/carsi/paper_search_carsi/browser/backend.py +269 -233
  23. package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
  24. package/carsi/paper_search_carsi/browser/challenge_interaction.py +28 -9
  25. package/carsi/paper_search_carsi/browser/cookies.py +8 -8
  26. package/carsi/paper_search_carsi/browser/driver.py +29 -0
  27. package/carsi/paper_search_carsi/browser/engine.py +17 -23
  28. package/carsi/paper_search_carsi/browser/foreground.py +21 -15
  29. package/carsi/paper_search_carsi/browser/login.py +12 -18
  30. package/carsi/paper_search_carsi/browser/preview.py +31 -12
  31. package/carsi/paper_search_carsi/browser/profiles.py +16 -23
  32. package/carsi/paper_search_carsi/browser/watchdog.py +113 -58
  33. package/carsi/paper_search_carsi/cli.py +22 -7
  34. package/carsi/paper_search_carsi/cold_start.py +65 -51
  35. package/carsi/paper_search_carsi/config.py +6 -4
  36. package/carsi/paper_search_carsi/download_diagnostics.py +2 -1
  37. package/carsi/paper_search_carsi/engine/batch.py +17 -7
  38. package/carsi/paper_search_carsi/engine/batch_capture.py +97 -31
  39. package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
  40. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +3 -0
  41. package/carsi/paper_search_carsi/engine/batch_institution.py +132 -13
  42. package/carsi/paper_search_carsi/engine/batch_login.py +151 -18
  43. package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
  44. package/carsi/paper_search_carsi/engine/batch_waits.py +21 -7
  45. package/carsi/paper_search_carsi/engine/bridge.py +23 -13
  46. package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
  47. package/carsi/paper_search_carsi/engine/supplements.py +36 -2
  48. package/carsi/paper_search_carsi/mcp_progress.py +13 -5
  49. package/carsi/paper_search_carsi/network.py +1 -1
  50. package/carsi/paper_search_carsi/progress_capsule.py +6 -2
  51. package/carsi/paper_search_carsi/progress_reporter.py +107 -9
  52. package/carsi/paper_search_carsi/progress_view.py +78 -1
  53. package/carsi/paper_search_carsi/server.py +53 -10
  54. package/carsi/paper_search_carsi/session_broker.py +1 -1
  55. package/carsi/pyproject.toml +7 -7
  56. package/dist/capabilities/journal-metrics/JournalMetricsService.d.ts.map +1 -1
  57. package/dist/capabilities/journal-metrics/JournalMetricsService.js +2 -1
  58. package/dist/capabilities/journal-metrics/JournalMetricsService.js.map +1 -1
  59. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
  60. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
  61. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  62. package/dist/capabilities/pdf-discovery/batch.d.ts +2 -0
  63. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  64. package/dist/capabilities/pdf-discovery/batch.js +59 -14
  65. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  66. package/dist/capabilities/pdf-discovery/batchSummary.d.ts +28 -0
  67. package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
  68. package/dist/capabilities/pdf-discovery/batchSummary.js +155 -0
  69. package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
  70. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
  71. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  72. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +56 -1
  73. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  74. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +11 -4
  75. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
  76. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +114 -30
  77. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
  78. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +6 -0
  79. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
  80. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +12 -0
  81. package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
  82. package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
  83. package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
  84. package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
  85. package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
  86. package/dist/capabilities/pdf-discovery/carsi/types.d.ts +48 -0
  87. package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
  88. package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
  89. package/dist/capabilities/pdf-discovery/handler.js +11 -6
  90. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  91. package/dist/capabilities/pdf-discovery/tiers/publisherApi.d.ts.map +1 -1
  92. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js +2 -1
  93. package/dist/capabilities/pdf-discovery/tiers/publisherApi.js.map +1 -1
  94. package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
  95. package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
  96. package/dist/cli.js +30 -15
  97. package/dist/cli.js.map +1 -1
  98. package/dist/config/ConfigService.d.ts.map +1 -1
  99. package/dist/config/ConfigService.js +28 -2
  100. package/dist/config/ConfigService.js.map +1 -1
  101. package/dist/config/apiKeySignup.d.ts +13 -0
  102. package/dist/config/apiKeySignup.d.ts.map +1 -0
  103. package/dist/config/apiKeySignup.js +32 -0
  104. package/dist/config/apiKeySignup.js.map +1 -0
  105. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  106. package/dist/infrastructure/runlog/failureClass.js +4 -0
  107. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  108. package/dist/management/capability-profile/index.d.ts +7 -0
  109. package/dist/management/capability-profile/index.d.ts.map +1 -1
  110. package/dist/management/capability-profile/index.js +7 -0
  111. package/dist/management/capability-profile/index.js.map +1 -1
  112. package/dist/management/carsi/installer.d.ts +26 -14
  113. package/dist/management/carsi/installer.d.ts.map +1 -1
  114. package/dist/management/carsi/installer.js +118 -74
  115. package/dist/management/carsi/installer.js.map +1 -1
  116. package/dist/management/carsi/runtime.d.ts +12 -1
  117. package/dist/management/carsi/runtime.d.ts.map +1 -1
  118. package/dist/management/carsi/runtime.js +30 -1
  119. package/dist/management/carsi/runtime.js.map +1 -1
  120. package/dist/management/diagnostics/index.d.ts.map +1 -1
  121. package/dist/management/diagnostics/index.js +4 -1
  122. package/dist/management/diagnostics/index.js.map +1 -1
  123. package/dist/management/failures/exportReport.js +3 -3
  124. package/dist/management/reports/index.d.ts.map +1 -1
  125. package/dist/management/reports/index.js +6 -1
  126. package/dist/management/reports/index.js.map +1 -1
  127. package/dist/platforms/SemanticScholarSearcher.d.ts.map +1 -1
  128. package/dist/platforms/SemanticScholarSearcher.js +2 -1
  129. package/dist/platforms/SemanticScholarSearcher.js.map +1 -1
  130. package/package.json +3 -2
  131. package/skills/paper-search/SKILL.md +9 -9
  132. package/skills/paper-search/references/browser-download.md +7 -6
  133. package/skills/paper-search/references/capability-routing.md +3 -3
  134. package/skills/paper-search/references/carsi-setup.md +8 -7
  135. package/skills/paper-search/references/cli-contract.md +6 -6
  136. package/skills/paper-search/references/management-layer.md +3 -3
  137. package/skills/paper-search/references/publisher-support.md +2 -0
  138. package/skills/paper-search/references/troubleshooting.md +1 -2
  139. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
  140. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
  141. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
  142. package/carsi/paper_search_carsi/browser/background.py +0 -68
@@ -32,6 +32,7 @@ from .batch_common import (
32
32
  _REFERENCE_AREA,
33
33
  _IP_BLOCK_STATUS_CODES,
34
34
  _is_browser_error,
35
+ goto_retrying,
35
36
  )
36
37
 
37
38
 
@@ -149,7 +150,7 @@ class CaptureMixin:
149
150
  getattr(self, "_fallback_pdf", None))
150
151
  self._capture_doi = (doi or "").lower()
151
152
  self._expected_title = self._citation_title(page) or getattr(self, "_record_title", "")
152
- self._show_title()
153
+ self._show_title(page)
153
154
  try:
154
155
  try:
155
156
  tabs = [tab for tab in list(page.context.pages) if not tab.is_closed()]
@@ -207,7 +208,7 @@ class CaptureMixin:
207
208
  self._phase(result, "pdf")
208
209
  self._capture_doi = (doi or "").lower()
209
210
  self._expected_title = self._citation_title(page) or getattr(self, "_record_title", "")
210
- self._show_title()
211
+ self._show_title(page)
211
212
  self._fallback_pdf = None
212
213
  tried_before = len(result.pdf_attempts)
213
214
  try:
@@ -215,6 +216,9 @@ class CaptureMixin:
215
216
 
216
217
  with pause_preview(getattr(page, "context", None)):
217
218
  body, url, block = self._capture_pdf_channels(page, doi, result)
219
+ if (body is None and not block and len(result.pdf_attempts) == tried_before
220
+ and not result.reason and self._wait_for_pdf_candidates(page, doi, result)):
221
+ body, url, block = self._capture_pdf_channels(page, doi, result)
218
222
  if body is None and not block and self._fallback_pdf is not None:
219
223
  body, url = self._fallback_pdf
220
224
  self._event(result, "pdf_saved_unconfirmed", f"{url} | no DOI or title on the first pages")
@@ -226,6 +230,38 @@ class CaptureMixin:
226
230
  finally:
227
231
  self._fallback_pdf = None
228
232
 
233
+ @staticmethod
234
+ def _chromium_pdf_patterns(native: tuple[str, ...]) -> list[dict[str, str]]:
235
+ """Responses Chrome pauses during the PDF step: the adapter's PDF addresses,
236
+ and every document the tab opens wherever it is served. A PDF address can
237
+ redirect to a delivery host no adapter lists (JAMA's articlepdf to
238
+ Silverchair's watermark host, 2026-11-07); the checks on each paused
239
+ response decide, and other documents go on at once."""
240
+ return [*({"urlPattern": pattern, "requestStage": "Response"} for pattern in native),
241
+ {"urlPattern": "*", "resourceType": "Document", "requestStage": "Response"}]
242
+
243
+ PDF_CANDIDATE_WAIT_MS = 8_000
244
+
245
+ def _wait_for_pdf_candidates(self, page: Any, doi: str, result: DownloadResult) -> bool:
246
+ """A page that offered no PDF address may still be loading or about to move
247
+ on: Thieme right after the school login, on its token address before the
248
+ article (2026-11-02 on Firefox, 2026-11-07 on Chrome). Look again for a
249
+ while; True once it offers one."""
250
+ def offered() -> bool:
251
+ try:
252
+ return bool(self._pdf_candidates(page, doi))
253
+ except Exception as exc:
254
+ if not _is_browser_error(exc):
255
+ raise
256
+ return False # the page is moving on: look at it again
257
+
258
+ started = time.time()
259
+ if not pump_until(page, offered, self.PDF_CANDIDATE_WAIT_MS, step_ms=500):
260
+ return False
261
+ self._event(result, "pdf_candidates_appeared",
262
+ f"after {time.time() - started:.1f} s at {str(getattr(page, 'url', ''))[:160]}")
263
+ return True
264
+
229
265
  def _nothing_tried_evidence(self, page: Any, doi: str) -> str:
230
266
  """The page and its access verdict, and the PDF addresses it offered."""
231
267
  try:
@@ -275,9 +311,22 @@ class CaptureMixin:
275
311
  return ""
276
312
  return " ".join(value.split()) if isinstance(value, str) else ""
277
313
 
278
- def _show_title(self) -> None:
279
- """The article's title in the progress window, once its page names it."""
280
- 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 "")
281
330
  if not title or title == getattr(self, "_shown_title", ""):
282
331
  return
283
332
  self._shown_title = title
@@ -297,7 +346,7 @@ class CaptureMixin:
297
346
  """
298
347
  self._event(result, "pdf_capture_started")
299
348
  captured: dict[str, Any] = {"bytes": None, "url": "", "deferred_url": "", "block_reason": None,
300
- "suspect_block": None}
349
+ "suspect_block": None, "closed": False, "readers": set()}
301
350
  cdp_session = None
302
351
  native_redirects: dict[str, list[Any]] = {}
303
352
  cdn_redirects: dict[str, list[Any]] = {}
@@ -351,7 +400,9 @@ class CaptureMixin:
351
400
  url = event.get("request", {}).get("url", "")
352
401
  response = SimpleNamespace(url=url, status=200, headers={}, history=history)
353
402
  urls = self._response_urls(response)
354
- 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))
355
406
  and self._response_matches_article(response, doi, **article_options)):
356
407
  cdn_redirects[url] = list(history)
357
408
  if (any(hop in rejected_pdf_urls for hop in urls)
@@ -372,11 +423,16 @@ class CaptureMixin:
372
423
  for header in event.get("responseHeaders", [])
373
424
  }
374
425
  url = event.get("request", {}).get("url", "")
426
+ history = native_redirects.get(event.get("networkId", ""), []) or cdn_redirects.get(url, [])
375
427
  if (self.adapter.discards_unbound_pdfs
376
428
  and "application/pdf" in headers.get("content-type", "").lower()
377
429
  and (url in rejected_pdf_urls or self._is_supplementary_url(url)
378
430
  or self._is_supplementary_url(headers.get("content-disposition", ""))
379
- 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)))):
380
436
  rejected_pdf_urls.add(url)
381
437
  return
382
438
  if ("application/pdf" in headers.get("content-type", "").lower()
@@ -401,13 +457,16 @@ class CaptureMixin:
401
457
  # response.body(). Apply the same article/attachment guards
402
458
  # before reading the response through CDP instead.
403
459
  if self._uses_article_pdf_validation():
404
- history = native_redirects.get(event.get("networkId", ""), []) or cdn_redirects.get(url, [])
405
460
  response = SimpleNamespace(
406
461
  url=url, headers=headers,
407
462
  status=event.get("responseStatusCode", 0), history=history,
408
463
  )
409
464
  final_pdf = (self._article_pdf_url_matches(url, doi, **article_options)
410
- or self.adapter.is_pdf_cdn_url(url, doi))
465
+ or self.adapter.is_pdf_cdn_url(url, doi)
466
+ # The bound PDF's own file on the host its address redirects
467
+ # to, as _response_matches_article accepts it (JAMA's
468
+ # articlepdf -> Silverchair's watermarked copy, 2026-11-07).
469
+ or self._bound_pdf_copy(url, response, doi, article_options))
411
470
  if (len(history) > 20 or not final_pdf
412
471
  or not self._response_matches_article(response, doi, **article_options)):
413
472
  rejected_pdf_urls.update(self._response_urls(response))
@@ -456,6 +515,12 @@ class CaptureMixin:
456
515
  self._event(result, "browser_response_continue_error", type(exc).__name__)
457
516
 
458
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
459
524
  # The tab's own document answers, for the attempt's record.
460
525
  try:
461
526
  request = getattr(response, "request", None)
@@ -499,7 +564,8 @@ class CaptureMixin:
499
564
  if self._uses_article_pdf_validation() else True)
500
565
  if relevant:
501
566
  try:
502
- 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()
503
569
  except Exception:
504
570
  snippet = ""
505
571
  text = self._visible_text_excerpt(snippet)
@@ -537,7 +603,7 @@ class CaptureMixin:
537
603
  if self._should_defer_response_body(url):
538
604
  captured["deferred_url"] = url
539
605
  return
540
- with transfer(result):
606
+ with transfer(result), watchdog.owned_by(captured["readers"]):
541
607
  body = response.body()
542
608
  # Body-level block-page detection (some block pages are 200
543
609
  # with an HTML "IP Address Blocked" body).
@@ -557,8 +623,8 @@ class CaptureMixin:
557
623
  def on_request_failed(request: Any) -> None:
558
624
  # A request for a PDF address that ended without an answer: what the
559
625
  # browser said and after how long, for the record (Karger's PDF
560
- # navigation ended NS_ERROR_ABORT after 46 s, and whether the click's
561
- # own request had failed was not known, 2026-11-02).
626
+ # navigation ended aborted after 46 s, and whether the click's own
627
+ # request had failed was not known, 2026-11-02).
562
628
  try:
563
629
  url = str(request.url)
564
630
  if not self._is_pdf_candidate_url(url) or self._is_supplementary_url(url):
@@ -591,18 +657,14 @@ class CaptureMixin:
591
657
  try:
592
658
  native_pdf_patterns = ((self.adapter.metadata_pdf_patterns if metadata_pdf_urls else ())
593
659
  or self.adapter.native_pdf_patterns)
594
- if native_pdf_patterns:
595
- browser = getattr(page.context, "browser", None)
596
- if browser is not None and browser.browser_type.name == "chromium":
597
- cdp_session = page.context.new_cdp_session(page)
598
- if self._uses_article_pdf_validation():
599
- cdp_session.on("Network.requestWillBeSent", on_native_request)
600
- cdp_session.send("Network.enable")
601
- cdp_session.on("Fetch.requestPaused", on_paused_response)
602
- cdp_session.send("Fetch.enable", {"patterns": [
603
- {"urlPattern": pattern, "requestStage": "Response"}
604
- for pattern in native_pdf_patterns
605
- ]})
660
+ browser = getattr(page.context, "browser", None)
661
+ if browser is not None and browser.browser_type.name == "chromium":
662
+ cdp_session = page.context.new_cdp_session(page)
663
+ if self._uses_article_pdf_validation():
664
+ cdp_session.on("Network.requestWillBeSent", on_native_request)
665
+ cdp_session.send("Network.enable")
666
+ cdp_session.on("Fetch.requestPaused", on_paused_response)
667
+ cdp_session.send("Fetch.enable", {"patterns": self._chromium_pdf_patterns(native_pdf_patterns)})
606
668
  self._return_to_record_article_if_needed(page, result, doi)
607
669
  # A login can return directly to a PDF before these listeners were
608
670
  # installed. PDF.js has no article button or metadata to discover.
@@ -697,8 +759,8 @@ class CaptureMixin:
697
759
  return None, final_url, captured["block_reason"]
698
760
  continue
699
761
  try:
700
- response = page.goto(pdf_url, wait_until="commit", timeout=self.pdf_timeout_ms,
701
- **({"referer": article_page} if article_page.startswith("https://") else {}))
762
+ response = goto_retrying(page, pdf_url, timeout_ms=self.pdf_timeout_ms,
763
+ **({"referer": article_page} if article_page.startswith("https://") else {}))
702
764
  if not self._resolve_suspect_block(page, result, captured):
703
765
  return None, "", captured["block_reason"]
704
766
  if captured["block_reason"]:
@@ -783,6 +845,10 @@ class CaptureMixin:
783
845
  if block_reason and not captured["block_reason"]:
784
846
  captured["block_reason"] = block_reason
785
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")
786
852
  finish()
787
853
  if cdp_session is not None:
788
854
  try:
@@ -1142,7 +1208,7 @@ class CaptureMixin:
1142
1208
  try:
1143
1209
  with expect_download(timeout=self.pdf_timeout_ms) as download_info:
1144
1210
  try:
1145
- page.goto(pdf_url, wait_until="commit", timeout=self.pdf_timeout_ms)
1211
+ goto_retrying(page, pdf_url, timeout_ms=self.pdf_timeout_ms)
1146
1212
  except Exception as exc:
1147
1213
  if not self._is_download_navigation_abort(exc):
1148
1214
  raise
@@ -1343,7 +1409,7 @@ class CaptureMixin:
1343
1409
  deadline = time.time() + timeout_sec
1344
1410
  attempted.clear()
1345
1411
  continue
1346
- # Firefox/Camoufox can leave the native PDF.js shell visible while
1412
+ # Firefox can leave the native PDF.js shell visible while
1347
1413
  # the document is already available (or while its loading task is
1348
1414
  # idle). Read that document in the viewer's own realm before
1349
1415
  # falling back to a second HTTP request, which may lose the
@@ -1384,7 +1450,7 @@ class CaptureMixin:
1384
1450
  const documentUri = String(nativeDocument?.documentURI || "");
1385
1451
  const app = nativeWindow.PDFViewerApplication;
1386
1452
  // Older builds expose the resource:// viewer shell; Firefox 156
1387
- // (Camoufox) keeps the https PDF URL on a document whose
1453
+ // keeps the https PDF URL on a document whose
1388
1454
  // contentType is application/pdf.
1389
1455
  const isNativePdfViewer = nativeLocation.startsWith("resource://pdf.js/")
1390
1456
  || documentUri.startsWith("resource://pdf.js/")
@@ -16,6 +16,7 @@ from urllib.parse import urlencode
16
16
  import requests
17
17
 
18
18
  from ..browser import watchdog
19
+ from ..browser.driver import is_driver_error
19
20
  from ..browser.challenges import looks_like_challenge
20
21
 
21
22
 
@@ -129,9 +130,8 @@ def _observe_preview(page: Any) -> None:
129
130
 
130
131
 
131
132
  def _is_browser_error(exc: BaseException, name: str = "") -> bool:
132
- """A Playwright/Patchright error (optionally of class ``name``), not a program bug."""
133
- return (type(exc).__module__.startswith(("playwright.", "patchright."))
134
- and (not name or type(exc).__name__ == name))
133
+ """A driver error (optionally of class ``name``), not a program bug."""
134
+ return is_driver_error(exc, name)
135
135
 
136
136
 
137
137
  def page_title(page: Any) -> str:
@@ -158,11 +158,10 @@ def _is_navigation_cut(exc: BaseException) -> bool:
158
158
  return _is_browser_error(exc) and any(marker in str(exc) for marker in _NAVIGATION_CUT)
159
159
 
160
160
 
161
- # The publisher's site did not answer: Firefox's and Chromium's network errors,
162
- # and a page load that ran out of time. Not a program error (thieme-connect.de's
163
- # empty response and pubs.acs.org's 60 s loads, 2026-11-01).
164
- _NETWORK_FAILURE = ("NS_ERROR_NET_", "NS_ERROR_CONNECTION_REFUSED", "NS_ERROR_UNKNOWN_HOST",
165
- "NS_ERROR_PROXY_", "net::ERR_")
161
+ # The publisher's site did not answer: Chromium's network errors, and a page
162
+ # load that ran out of time. Not a program error (thieme-connect.de's empty
163
+ # response and pubs.acs.org's 60 s loads, 2026-11-01).
164
+ _NETWORK_FAILURE = ("net::ERR_",)
166
165
 
167
166
 
168
167
  def _is_network_failure(exc: BaseException) -> bool:
@@ -218,12 +217,54 @@ _DOCUMENT_STATE_JS = """() => [document.readyState,
218
217
  document.readyState === 'loading' && document.body ? document.body.textContent.length : 0]"""
219
218
 
220
219
 
220
+ # A connection the network dropped before the site answered: Chromium's codes for a
221
+ # closed, reset or timed-out connection, a failed proxy tunnel or name lookup, a
222
+ # broken protocol stream. A system proxy in front of doi.org dropped 1 of 6
223
+ # connections and 3 articles failed on it, each fine on the next try (Windows,
224
+ # 2026-11-07); such a navigation is tried again after these pauses.
225
+ _DROPPED_CONNECTION = (
226
+ "net::ERR_CONNECTION_CLOSED", "net::ERR_CONNECTION_RESET", "net::ERR_CONNECTION_TIMED_OUT",
227
+ "net::ERR_TIMED_OUT", "net::ERR_EMPTY_RESPONSE", "net::ERR_NETWORK_CHANGED",
228
+ "net::ERR_PROXY_CONNECTION_FAILED", "net::ERR_TUNNEL_CONNECTION_FAILED", "net::ERR_NAME_NOT_RESOLVED",
229
+ "net::ERR_SSL_PROTOCOL_ERROR", "net::ERR_HTTP2_PROTOCOL_ERROR", "net::ERR_QUIC_PROTOCOL_ERROR",
230
+ )
231
+ DROPPED_CONNECTION_RETRY_MS = (2_000, 5_000)
232
+
233
+
234
+ def goto_retrying(page: Any, url: str, *, timeout_ms: int, wait_until: str = "commit",
235
+ started: float | None = None, **kwargs: Any) -> Any:
236
+ """``page.goto``, again after a dropped connection while ``timeout_ms`` (counted
237
+ from ``started``, default now) allows. Every navigation of the download goes
238
+ through here: the article (``open_page``), its PDF, supplement tabs."""
239
+ started = time.monotonic() if started is None else started
240
+ dropped: BaseException | None = None
241
+ for attempt, pause_ms in enumerate((*DROPPED_CONNECTION_RETRY_MS, None)):
242
+ spent_ms = int((time.monotonic() - started) * 1000) if attempt else 0 # the first try: the whole budget
243
+ try:
244
+ return page.goto(url, wait_until=wait_until, timeout=max(1_000, timeout_ms - spent_ms), **kwargs)
245
+ except Exception as exc:
246
+ message = str(exc) if _is_browser_error(exc) else ""
247
+ if any(code in message for code in _DROPPED_CONNECTION):
248
+ dropped = exc
249
+ elif not (dropped and "net::ERR_ABORTED" in message):
250
+ raise
251
+ # After a dropped connection Chromium's error page reloads by itself and
252
+ # can cut the next try short (net::ERR_ABORTED): still the dropped
253
+ # connection, and reported as such (T&F through doi.org, Windows 2026-11-07).
254
+ spent_ms = int((time.monotonic() - started) * 1000)
255
+ if pause_ms is None or spent_ms + pause_ms >= timeout_ms:
256
+ raise dropped from (exc if exc is not dropped else None)
257
+ logger.info(" [Navigation] %s; trying again in %d s", message.splitlines()[0][:200], pause_ms // 1000)
258
+ page.wait_for_timeout(pause_ms)
259
+ raise AssertionError("unreachable")
260
+
261
+
221
262
  def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int = 15_000, **kwargs: Any) -> Any:
222
263
  """Go to ``url`` and on as soon as its document can be read: the navigation
223
- commits within ``timeout_ms``, then at most ``ready_ms`` until the document is
224
- parsed or its text stops growing; a verification page is left untouched at
225
- once. The caller checks the page state it needs (``settle``, the access rule,
226
- the verification wait). Returns the response."""
264
+ commits within ``timeout_ms`` (a dropped connection is tried again), then at
265
+ most ``ready_ms`` until the document is parsed or its text stops growing; a
266
+ verification page is left untouched at once. The caller checks the page state
267
+ it needs (``settle``, the access rule, the verification wait). Returns the response."""
227
268
  committed = False
228
269
 
229
270
  def navigated(frame: Any) -> None:
@@ -235,13 +276,12 @@ def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int =
235
276
  page.on("framenavigated", navigated)
236
277
  try:
237
278
  try:
238
- response = page.goto(url, wait_until="commit", timeout=timeout_ms, **kwargs)
279
+ response = goto_retrying(page, url, timeout_ms=timeout_ms, started=started, **kwargs)
239
280
  except Exception as exc:
240
281
  # A script redirect can replace the requested navigation before goto
241
- # returns (Firefox NS_ERROR_ABORT). Continue only after an observed
282
+ # returns (net::ERR_ABORTED). Continue only after an observed
242
283
  # top-level document commit; the caller still checks identity/access.
243
- if not _is_browser_error(exc) or not any(
244
- marker in str(exc) for marker in ("NS_ERROR_ABORT", "net::ERR_ABORTED")):
284
+ if not _is_browser_error(exc) or "net::ERR_ABORTED" not in str(exc):
245
285
  raise
246
286
  left = max(0, min(ready_ms, timeout_ms - int((time.monotonic() - started) * 1000)))
247
287
  if not committed and not pump_until(page, lambda: committed, left):
@@ -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"),
@@ -7,7 +7,7 @@ from __future__ import annotations
7
7
  import re
8
8
  import time
9
9
  from typing import Any
10
- from urllib.parse import parse_qs, unquote, urlencode, urlparse
10
+ from urllib.parse import parse_qs, unquote, urlencode, urljoin, urlparse
11
11
 
12
12
  from .batch_common import DownloadResult, _is_browser_error, logger, open_page, pump_until, settle
13
13
 
@@ -86,6 +86,12 @@ class InstitutionMixin:
86
86
  return True
87
87
  if self.institution_query and self._assist_configured_institution(page, result):
88
88
  return True
89
+ if self.institution_query and self._select_carsi_federation_link(page, result, here):
90
+ return True
91
+ if self.institution_query and not getattr(result, "_institution_not_listed", False):
92
+ self._check_carsi_school_links(page, result, here)
93
+ if getattr(result, "_institution_not_listed", False):
94
+ return False
89
95
  if self.adapter.prepare_institution_choice(page, result) is False:
90
96
  return False
91
97
  if self._open_seamlessaccess_chooser(page, result):
@@ -225,6 +231,8 @@ class InstitutionMixin:
225
231
  return null;
226
232
  }"""
227
233
  _CARSI_OPTION = re.compile(r"\bCARSI\b", re.I)
234
+ _FEDERATION_LINK_LIST = "ul.federation--list"
235
+ _FEDERATION_SCHOOL_LIST = "ul.federation--list-inner"
228
236
  # How long one pass waits for the school's option once the federation is chosen
229
237
  # (ACS answered after 35-50 s, 2026-11-02; the login loop asks again).
230
238
  LIST_WAIT_SEC = 15
@@ -325,6 +333,61 @@ class InstitutionMixin:
325
333
  result._federation_pages = getattr(result, "_federation_pages", set()) | {here}
326
334
  self._event(result, "institution_federation_selected", detail)
327
335
 
336
+ def _select_carsi_federation_link(self, page: Any, result: DownloadResult, url: str) -> bool:
337
+ if not self._on_publisher_host(url):
338
+ return False
339
+ listing = page.locator(self._FEDERATION_LINK_LIST).first
340
+ try:
341
+ if listing.is_visible() is not True:
342
+ return False
343
+ links = listing.get_by_role("link", name=self._CARSI_OPTION)
344
+ if links.count() != 1:
345
+ return False
346
+ href = links.first.get_attribute("href", timeout=800)
347
+ if not href or not self._manual_institution_target_allowed(urljoin(url, href)):
348
+ return False
349
+ here = self._federation_choice_page(page, result)
350
+ if here is None or not self._click_control(page, links.first, result, "choose CARSI federation"):
351
+ return False
352
+ except Exception as exc:
353
+ if not _is_browser_error(exc):
354
+ raise
355
+ self._event(result, "institution_step_interrupted", type(exc).__name__)
356
+ return False
357
+ self._federation_chosen(result, here, f"carsi: federation link @ {url}")
358
+ return True
359
+
360
+ def _check_carsi_school_links(self, page: Any, result: DownloadResult, url: str) -> None:
361
+ """Only a complete link directory can establish absence after choosing CARSI."""
362
+ if not self._on_publisher_host(url):
363
+ return
364
+ try:
365
+ listing = page.locator(self._FEDERATION_SCHOOL_LIST).first
366
+ if listing.is_visible() is not True:
367
+ return
368
+ heading = page.get_by_role("heading", level=1, name=self._CARSI_OPTION).first
369
+ if heading.is_visible() is not True or self._is_challenge_page(page):
370
+ return
371
+ rows = listing.locator(":scope > li")
372
+ entries = page.evaluate(self._ENTRIES_JS, self._FEDERATION_SCHOOL_LIST + " > li > a[href]")
373
+ if (not entries or len(entries) != rows.count()
374
+ or listing.evaluate("""el => !!el.closest('[aria-busy=true]') ||
375
+ !!el.closest('section')?.querySelector('input:not([type=hidden]), [aria-busy=true], [rel=next]')""",
376
+ timeout=800)):
377
+ return
378
+ # Even a partial name match is enough to leave the choice open for the user.
379
+ entity_id = self._entity_id()
380
+ names = {self._canonical_school_name(name) for name in self._institution_names()} - {""}
381
+ if any(self._institution_entry_score(entry, entity_id)
382
+ or self._canonical_school_name(entry["t"]) in names for entry in entries):
383
+ return
384
+ self._event(result, "auto_institution_not_found", f"{self.institution_query} (CARSI list, {len(entries)} schools) @ {url}")
385
+ result._institution_not_listed = True
386
+ except Exception as exc:
387
+ if not _is_browser_error(exc):
388
+ raise
389
+ self._event(result, "institution_step_interrupted", type(exc).__name__)
390
+
328
391
  def _close_blank_overlay(self, page: Any, result: DownloadResult) -> None:
329
392
  try:
330
393
  closed = page.evaluate(self._BLANK_OVERLAY_JS)
@@ -487,6 +550,11 @@ class InstitutionMixin:
487
550
  .filter(it => it.t && it.t.length <= 160);
488
551
  }"""
489
552
 
553
+ def _institution_entry_score(self, entry: dict, entity_id: str) -> int:
554
+ if self._carries_entity_id(str(entry.get("ids") or ""), entity_id):
555
+ return 4
556
+ return self._institution_match_score(entry.get("t", ""))
557
+
490
558
  def _click_unique_institution_entry(self, page: Any, result: DownloadResult, url: str) -> bool:
491
559
  """Click the single best visible entry for the configured school.
492
560
 
@@ -506,12 +574,7 @@ class InstitutionMixin:
506
574
  return False
507
575
  entity_id = self._entity_id()
508
576
 
509
- def score(item: dict) -> int:
510
- if self._carries_entity_id(str(item.get("ids") or ""), entity_id):
511
- return 4
512
- return self._institution_match_score(item.get("t", ""))
513
-
514
- scored = [(score(it), it) for it in items if isinstance(it, dict)]
577
+ scored = [(self._institution_entry_score(it, entity_id), it) for it in items if isinstance(it, dict)]
515
578
  top = max([score for score, _ in scored] or [0])
516
579
  best = [it for score, it in scored if score == top]
517
580
  same = (len(best) == 1 or top == 4
@@ -543,8 +606,8 @@ class InstitutionMixin:
543
606
  # leaves the option unselected even though no error is raised.
544
607
  # This is only the already matched institution, never a challenge
545
608
  # widget, credential field or another default choice.
546
- # Omit MouseEventInit.view: Camoufox rejects the evaluation
547
- # world's window as a Window, and the selection does not need it.
609
+ # Omit MouseEventInit.view: an isolated evaluation world's window
610
+ # can be rejected as a Window, and the selection does not need it.
548
611
  try:
549
612
  clicked = page.evaluate("""() => {
550
613
  const el = document.querySelector('[data-paper-search-entry]');
@@ -595,11 +658,65 @@ class InstitutionMixin:
595
658
  return False
596
659
  if not _is_browser_error(exc):
597
660
  raise
598
- # The wait was cut off by the navigation itself (Firefox's
599
- # NS_BINDING_ABORTED, a detached frame: an Atypon chooser going on to
600
- # the school failed the article, 2026-11-01): the page has gone on.
661
+ # The wait was cut off by the navigation itself (an aborted
662
+ # navigation, a detached frame: an Atypon chooser going on to the
663
+ # school failed the article, 2026-11-01): the page has gone on.
601
664
  return True
602
665
 
666
+ # The school's name may follow "for" with no space: RSNA writes
667
+ # "for<em>Example University</em>" (2026-11-07).
668
+ _NO_INSTITUTION_SEARCH_RESULTS = re.compile(
669
+ r"^(?:no (?:institutions?|results?|matches) found(?:[.!]?$|\s+for)"
670
+ r"|we couldn['’]t find any results? for)", re.I)
671
+ _INSTITUTION_LIST_LINK = re.compile(r"^(?:select|choose) (?:your|an) institution from (?:a|the) list$", re.I)
672
+
673
+ def _handle_institution_search_miss(self, page: Any, result: DownloadResult, url: str) -> bool:
674
+ """Use a visible negative result for our search, and try an offered list first."""
675
+ if (not (self._on_publisher_host(url) or self._is_federation_chooser(url))
676
+ or self._is_challenge_page(page)
677
+ or any(e["state"] == "auto_institution_list_opened" and e.get("detail") == url for e in result.events)):
678
+ return False
679
+ queries = {e.get("detail", "") for e in result.events if e["state"] == "auto_institution_search"}
680
+ try:
681
+ notice = page.get_by_text(self._NO_INSTITUTION_SEARCH_RESULTS).filter(visible=True).first
682
+ if notice.is_visible() is not True:
683
+ return False # no candidate yet does not establish an empty result
684
+ message = notice.inner_text(timeout=800)
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):
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
714
+ except Exception as exc:
715
+ if not _is_browser_error(exc):
716
+ raise
717
+ self._event(result, "institution_step_interrupted", type(exc).__name__)
718
+ return False
719
+
603
720
  def _assist_configured_institution(self, page: Any, result: DownloadResult) -> bool:
604
721
  """Pick the user's configured institution on the current page.
605
722
 
@@ -678,7 +795,9 @@ class InstitutionMixin:
678
795
  # 4. type the school into an empty institution search box (once per page);
679
796
  # never on a verification page, which the challenge wait takes first: a
680
797
  # search there found no school and ended the login (fixture, 2026-11-01).
681
- if not self._is_challenge_page(page) and once("institution_search"):
798
+ if not once("institution_search"):
799
+ return self._handle_institution_search_miss(page, result, url)
800
+ if not self._is_challenge_page(page):
682
801
  if self._assist_carsi_discovery(page, result):
683
802
  self._event(result, "auto_institution_search", f"carsi @ {url}")
684
803
  return True