papersearch 0.7.3 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/NOTICE +8 -37
  2. package/README.fr.md +265 -0
  3. package/README.ja.md +265 -0
  4. package/README.ko.md +265 -0
  5. package/README.md +149 -148
  6. package/README.zh-Hant.md +265 -0
  7. package/README.zh.md +265 -0
  8. package/dist/capabilities/download/batch/batch.d.ts +20 -1
  9. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  10. package/dist/capabilities/download/batch/batch.js +1057 -208
  11. package/dist/capabilities/download/batch/batch.js.map +1 -1
  12. package/dist/capabilities/download/batch/batchFolder.d.ts.map +1 -1
  13. package/dist/capabilities/download/batch/batchFolder.js +3 -2
  14. package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
  15. package/dist/capabilities/download/batch/networkLoss.d.ts +11 -2
  16. package/dist/capabilities/download/batch/networkLoss.d.ts.map +1 -1
  17. package/dist/capabilities/download/batch/networkLoss.js +24 -3
  18. package/dist/capabilities/download/batch/networkLoss.js.map +1 -1
  19. package/dist/capabilities/download/batch/resume.d.ts +7 -0
  20. package/dist/capabilities/download/batch/resume.d.ts.map +1 -1
  21. package/dist/capabilities/download/batch/resume.js +50 -9
  22. package/dist/capabilities/download/batch/resume.js.map +1 -1
  23. package/dist/capabilities/download/batch/windowPlan.d.ts +96 -0
  24. package/dist/capabilities/download/batch/windowPlan.d.ts.map +1 -0
  25. package/dist/capabilities/download/batch/windowPlan.js +196 -0
  26. package/dist/capabilities/download/batch/windowPlan.js.map +1 -0
  27. package/dist/capabilities/download/content/markdown/pro.d.ts +6 -0
  28. package/dist/capabilities/download/content/markdown/pro.d.ts.map +1 -1
  29. package/dist/capabilities/download/content/markdown/pro.js.map +1 -1
  30. package/dist/capabilities/download/content/markdown/shortfall.d.ts +8 -5
  31. package/dist/capabilities/download/content/markdown/shortfall.d.ts.map +1 -1
  32. package/dist/capabilities/download/content/markdown/shortfall.js +22 -10
  33. package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
  34. package/dist/capabilities/download/content/markdown/step.d.ts +9 -0
  35. package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
  36. package/dist/capabilities/download/content/markdown/step.js +46 -3
  37. package/dist/capabilities/download/content/markdown/step.js.map +1 -1
  38. package/dist/capabilities/download/content/markdown/types.d.ts +10 -1
  39. package/dist/capabilities/download/content/markdown/types.d.ts.map +1 -1
  40. package/dist/capabilities/download/content/pdf/open/tiers/scihub.d.ts.map +1 -1
  41. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js +3 -1
  42. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js.map +1 -1
  43. package/dist/capabilities/download/handler.d.ts.map +1 -1
  44. package/dist/capabilities/download/handler.js +13 -5
  45. package/dist/capabilities/download/handler.js.map +1 -1
  46. package/dist/capabilities/download/outputLayout.d.ts.map +1 -1
  47. package/dist/capabilities/download/outputLayout.js +3 -1
  48. package/dist/capabilities/download/outputLayout.js.map +1 -1
  49. package/dist/capabilities/download/tools.js +2 -2
  50. package/dist/capabilities/download/tools.js.map +1 -1
  51. package/dist/capabilities/download/types.d.ts +9 -1
  52. package/dist/capabilities/download/types.d.ts.map +1 -1
  53. package/dist/cli.js +3 -1
  54. package/dist/cli.js.map +1 -1
  55. package/dist/infrastructure/http/hostGate.d.ts +24 -0
  56. package/dist/infrastructure/http/hostGate.d.ts.map +1 -0
  57. package/dist/infrastructure/http/hostGate.js +72 -0
  58. package/dist/infrastructure/http/hostGate.js.map +1 -0
  59. package/dist/infrastructure/pdf/PdfDownload.d.ts +1 -0
  60. package/dist/infrastructure/pdf/PdfDownload.d.ts.map +1 -1
  61. package/dist/infrastructure/pdf/PdfDownload.js +6 -1
  62. package/dist/infrastructure/pdf/PdfDownload.js.map +1 -1
  63. package/dist/infrastructure/runlog/RunLedger.d.ts +14 -0
  64. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  65. package/dist/infrastructure/runlog/RunLedger.js +30 -4
  66. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  67. package/dist/infrastructure/runlog/failureClass.d.ts +2 -1
  68. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  69. package/dist/infrastructure/runlog/failureClass.js +27 -4
  70. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  71. package/dist/infrastructure/school/SchoolAttempt.d.ts +11 -0
  72. package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
  73. package/dist/infrastructure/school/SchoolAttempt.js +48 -5
  74. package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
  75. package/dist/infrastructure/school/SchoolMcpClient.d.ts +13 -2
  76. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  77. package/dist/infrastructure/school/SchoolMcpClient.js +138 -15
  78. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  79. package/dist/infrastructure/school/SchoolProgress.d.ts +2 -0
  80. package/dist/infrastructure/school/SchoolProgress.d.ts.map +1 -1
  81. package/dist/infrastructure/school/SchoolProgress.js +2 -0
  82. package/dist/infrastructure/school/SchoolProgress.js.map +1 -1
  83. package/dist/infrastructure/school/SchoolReadiness.d.ts +9 -0
  84. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  85. package/dist/infrastructure/school/SchoolReadiness.js +10 -0
  86. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  87. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  88. package/dist/infrastructure/school/SchoolResultNormalizer.js +4 -0
  89. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  90. package/dist/infrastructure/school/index.d.ts +2 -2
  91. package/dist/infrastructure/school/index.d.ts.map +1 -1
  92. package/dist/infrastructure/school/index.js +1 -1
  93. package/dist/infrastructure/school/index.js.map +1 -1
  94. package/dist/infrastructure/school/types.d.ts +73 -1
  95. package/dist/infrastructure/school/types.d.ts.map +1 -1
  96. package/dist/infrastructure/school/types.js.map +1 -1
  97. package/dist/infrastructure/security/SecurityUtils.d.ts.map +1 -1
  98. package/dist/infrastructure/security/SecurityUtils.js +6 -2
  99. package/dist/infrastructure/security/SecurityUtils.js.map +1 -1
  100. package/dist/management/failures/index.d.ts +23 -0
  101. package/dist/management/failures/index.d.ts.map +1 -1
  102. package/dist/management/failures/index.js +68 -20
  103. package/dist/management/failures/index.js.map +1 -1
  104. package/dist/management/school/autoUpdate.d.ts.map +1 -1
  105. package/dist/management/school/autoUpdate.js +9 -1
  106. package/dist/management/school/autoUpdate.js.map +1 -1
  107. package/dist/management/school/cliProgress.d.ts.map +1 -1
  108. package/dist/management/school/cliProgress.js +3 -1
  109. package/dist/management/school/cliProgress.js.map +1 -1
  110. package/package.json +8 -3
  111. package/school/NOTICE +3 -2
  112. package/school/paper_search_school/adapters/__init__.py +2 -0
  113. package/school/paper_search_school/adapters/aps/__init__.py +3 -6
  114. package/school/paper_search_school/adapters/base.py +19 -2
  115. package/school/paper_search_school/adapters/copernicus/__init__.py +2 -7
  116. package/school/paper_search_school/adapters/elsevier/__init__.py +50 -1
  117. package/school/paper_search_school/adapters/frontiers/__init__.py +41 -2
  118. package/school/paper_search_school/adapters/ieee/__init__.py +6 -4
  119. package/school/paper_search_school/adapters/iop/__init__.py +8 -0
  120. package/school/paper_search_school/adapters/jama/__init__.py +8 -0
  121. package/school/paper_search_school/adapters/lww/__init__.py +14 -6
  122. package/school/paper_search_school/adapters/mdpi/__init__.py +12 -7
  123. package/school/paper_search_school/adapters/neurology/__init__.py +5 -2
  124. package/school/paper_search_school/adapters/optica/__init__.py +52 -13
  125. package/school/paper_search_school/adapters/oup/__init__.py +7 -4
  126. package/school/paper_search_school/adapters/platforms/__init__.py +4 -1
  127. package/school/paper_search_school/adapters/platforms/atypon/__init__.py +12 -3
  128. package/school/paper_search_school/adapters/platforms/figshare/__init__.py +23 -4
  129. package/school/paper_search_school/adapters/platforms/jstage/__init__.py +64 -0
  130. package/school/paper_search_school/adapters/taylor_francis/__init__.py +0 -3
  131. package/school/paper_search_school/adapters/thieme/__init__.py +2 -9
  132. package/school/paper_search_school/api_keys.py +63 -13
  133. package/school/paper_search_school/assets/api_keys.json +14 -0
  134. package/school/paper_search_school/assets/capsule.html +526 -147
  135. package/school/paper_search_school/assets/capsule_en.json +140 -49
  136. package/school/paper_search_school/assets/capsule_fr.json +141 -50
  137. package/school/paper_search_school/assets/capsule_ja.json +140 -49
  138. package/school/paper_search_school/assets/capsule_ko.json +140 -49
  139. package/school/paper_search_school/assets/capsule_zh-Hant.json +134 -48
  140. package/school/paper_search_school/browser/backend.py +125 -4
  141. package/school/paper_search_school/browser/batch_session.py +189 -8
  142. package/school/paper_search_school/browser/challenge/__init__.py +12 -9
  143. package/school/paper_search_school/browser/challenge/continuation.py +83 -0
  144. package/school/paper_search_school/browser/challenge/handlers/__init__.py +1 -0
  145. package/school/paper_search_school/browser/challenge/handlers/aws_waf.py +260 -0
  146. package/school/paper_search_school/browser/challenge/handlers/recaptcha_hcaptcha.py +167 -0
  147. package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +128 -0
  148. package/school/paper_search_school/browser/challenge/handlers/turnstile.py +174 -0
  149. package/school/paper_search_school/browser/challenge/kinds.py +203 -0
  150. package/school/paper_search_school/browser/challenge/local/__init__.py +1 -0
  151. package/school/paper_search_school/browser/challenge/{interaction.py → local/interaction.py} +94 -13
  152. package/school/paper_search_school/browser/challenge/{pointer.py → local/pointer.py} +2 -2
  153. package/school/paper_search_school/browser/challenge/local/prompt.py +283 -0
  154. package/school/paper_search_school/browser/challenge/local/submission.py +33 -0
  155. package/school/paper_search_school/browser/challenge/pro.py +24 -0
  156. package/school/paper_search_school/browser/challenge/services/__init__.py +1 -0
  157. package/school/paper_search_school/browser/challenge/services/solver.py +292 -0
  158. package/school/paper_search_school/browser/engine.py +4 -1
  159. package/school/paper_search_school/browser/user_turn.py +126 -0
  160. package/school/paper_search_school/browser/watchdog.py +213 -60
  161. package/school/paper_search_school/cli_config.py +10 -5
  162. package/school/paper_search_school/config.py +16 -10
  163. package/school/paper_search_school/download_diagnostics.py +7 -2
  164. package/school/paper_search_school/engine/access_rules.py +12 -3
  165. package/school/paper_search_school/engine/batch.py +52 -18
  166. package/school/paper_search_school/engine/batch_access.py +62 -16
  167. package/school/paper_search_school/engine/batch_capture.py +260 -31
  168. package/school/paper_search_school/engine/batch_common.py +3 -0
  169. package/school/paper_search_school/engine/batch_diagnostics.py +25 -5
  170. package/school/paper_search_school/engine/batch_institution.py +52 -3
  171. package/school/paper_search_school/engine/batch_login.py +398 -36
  172. package/school/paper_search_school/engine/batch_pdf_urls.py +38 -7
  173. package/school/paper_search_school/engine/batch_user.py +48 -3
  174. package/school/paper_search_school/engine/batch_waits.py +221 -14
  175. package/school/paper_search_school/engine/bridge.py +29 -6
  176. package/school/paper_search_school/engine/fulltext_page.py +55 -8
  177. package/school/paper_search_school/engine/router.py +16 -1
  178. package/school/paper_search_school/engine/supplements.py +7 -1
  179. package/school/paper_search_school/entitlements.py +29 -1
  180. package/school/paper_search_school/pdf_utils.py +25 -16
  181. package/school/paper_search_school/progress_capsule.py +69 -11
  182. package/school/paper_search_school/progress_reporter.py +243 -11
  183. package/school/paper_search_school/progress_view.py +205 -91
  184. package/school/paper_search_school/publishers/builtin/iop.json +2 -1
  185. package/school/paper_search_school/publishers/builtin/neurology.json +4 -2
  186. package/school/paper_search_school/publishers/site.py +12 -4
  187. package/school/paper_search_school/rate_limit.py +24 -1
  188. package/school/paper_search_school/school_login.py +170 -8
  189. package/school/paper_search_school/school_test.py +1 -1
  190. package/school/paper_search_school/server.py +179 -23
  191. package/school/paper_search_school/user_settings.py +46 -4
  192. package/school/pyproject.toml +1 -0
  193. package/skills/paper-search/SKILL.md +107 -107
  194. package/skills/paper-search/references/browser-download.md +102 -99
  195. package/skills/paper-search/references/capability-routing.md +89 -89
  196. package/skills/paper-search/references/cli-contract.md +78 -78
  197. package/skills/paper-search/references/federation-support.md +172 -172
  198. package/skills/paper-search/references/management-layer.md +78 -78
  199. package/skills/paper-search/references/publisher-support.md +38 -38
  200. package/skills/paper-search/references/school-setup.md +56 -55
  201. package/skills/paper-search/references/setup.md +20 -20
  202. package/skills/paper-search/references/troubleshooting.md +12 -12
  203. package/README.en.md +0 -264
  204. package/school/paper_search_school/browser/challenge/prompt.py +0 -154
@@ -318,8 +318,12 @@ def resolve_backend(config: dict[str, Any] | None = None) -> str:
318
318
  # batch_window: a serial batch keeps one browser window and tab from paper
319
319
  # to paper (browser/batch_session.py); without it every paper opens and
320
320
  # closes its own browser, as before.
321
+ # parallel_windows: a batch downloads several papers at once, each in a
322
+ # window of its own of the one browser, the other windows' drivers coming in
323
+ # on its remote-debugging port (并行下载, user 2026-11-29); without it a
324
+ # batch downloads one paper after another whatever the settings say.
321
325
  BACKEND_CAPABILITIES: dict[str, frozenset[str]] = {
322
- BACKEND_CHROME: frozenset({"batch_window"}),
326
+ BACKEND_CHROME: frozenset({"batch_window", "parallel_windows"}),
323
327
  # The user's own running browser: one tab per paper until a batch there
324
328
  # has been tried.
325
329
  BACKEND_EGO: frozenset(),
@@ -460,7 +464,7 @@ def _relay_failure(log_path: Path, start: int) -> str:
460
464
  return lines[-1][:200] if lines else "no log"
461
465
 
462
466
 
463
- def _scope_to_own_tabs(context: Any) -> set:
467
+ def _scope_to_own_tabs(context: Any, existing: bool = False) -> set:
464
468
  """Make ``context`` show only the tabs this package opened (and their popups).
465
469
 
466
470
  The user's own tabs live in the same browser context. Every place that
@@ -469,7 +473,7 @@ def _scope_to_own_tabs(context: Any) -> set:
469
473
  returns this same object, so its class is swapped for a subclass whose
470
474
  ``pages`` and ``on("page")`` see only owned tabs.
471
475
  """
472
- owned: set = set()
476
+ owned: set = set(base_pages(context) if existing else ())
473
477
  base = type(context)
474
478
 
475
479
  def track(page: Any) -> None:
@@ -505,9 +509,116 @@ def _scope_to_own_tabs(context: Any) -> set:
505
509
  })
506
510
  context.__class__ = scoped
507
511
  context.new_page = new_page # type: ignore[method-assign]
512
+ context.paper_search_owned = owned
508
513
  return owned
509
514
 
510
515
 
516
+ def base_pages(context: Any) -> list:
517
+ """Every page of ``context``, its tabs scoped to ours or not (``_scope_to_own_tabs``)."""
518
+ for cls in type(context).__mro__:
519
+ if cls.__name__ != "EgoScopedContext" and "pages" in vars(cls):
520
+ return list(vars(cls)["pages"].fget(context))
521
+ return list(context.pages)
522
+
523
+
524
+ # ---------------------------------------------------------------------------
525
+ # 并行下载 (user, 2026-11-29): one Chrome, a window and a driver of its own for each paper downloading at once
526
+ # ---------------------------------------------------------------------------
527
+ #: Config keys the batch's first window launches Chrome with when its papers run at once (batch_session.py): a
528
+ #: remote-debugging port on 127.0.0.1 for the other windows' drivers, and the downloads' folder every driver shares.
529
+ PARALLEL_DOWNLOADS_KEY = "browser_parallel_downloads"
530
+ WINDOW_CONNECT_TIMEOUT_MS = 30_000
531
+ _ENDPOINT_WAIT_SEC = 10.0
532
+
533
+
534
+ def devtools_endpoint(user_data_dir: str | Path, since: float = 0.0) -> str:
535
+ """The remote-debugging address the batch's Chrome wrote into its profile (DevToolsActivePort), once it is newer
536
+ than ``since``; waits up to a few seconds after a launch. "" when there is none."""
537
+ path = chrome_profile_dir(user_data_dir) / "DevToolsActivePort"
538
+ until = time.monotonic() + _ENDPOINT_WAIT_SEC
539
+ while True:
540
+ try:
541
+ if path.stat().st_mtime >= since - 1:
542
+ port = path.read_text().split()[0]
543
+ if port.isdigit():
544
+ return f"http://127.0.0.1:{port}"
545
+ except (OSError, IndexError):
546
+ pass
547
+ if time.monotonic() >= until:
548
+ return ""
549
+ time.sleep(0.1)
550
+
551
+
552
+ def _target_of(context: Any, page: Any) -> str:
553
+ """A page's DevTools target id ("" when it cannot be read)."""
554
+ try:
555
+ session = context.new_cdp_session(page)
556
+ try:
557
+ return str(session.send("Target.getTargetInfo")["targetInfo"]["targetId"])
558
+ finally:
559
+ session.detach()
560
+ except Exception:
561
+ return ""
562
+
563
+
564
+ def open_window_page(context: Any, session: Any, timeout_sec: float = 15.0) -> Any:
565
+ """A page in a window of its own, behind the window the user is in (a background tab would be slowed down by
566
+ Chrome: sliders, verification pictures and Cloudflare's check misbehave there; user, 2026-11-29). Found among the
567
+ context's pages by its target id: other windows' drivers open pages at the same time."""
568
+ before = {id(page) for page in base_pages(context)}
569
+ target = str(session.send("Target.createTarget", {"url": "about:blank", "newWindow": True, "background": True})["targetId"])
570
+ until = time.monotonic() + timeout_sec
571
+ while time.monotonic() < until:
572
+ for page in base_pages(context):
573
+ if id(page) not in before and _target_of(context, page) == target:
574
+ return page
575
+ before.add(id(page))
576
+ try:
577
+ context.wait_for_event("page", timeout=500)
578
+ except Exception:
579
+ pass
580
+ raise RuntimeError("the new window's page did not come")
581
+
582
+
583
+ def _windows_of_their_own(context: Any, owned: set) -> None:
584
+ """``context.new_page()`` opens a window of its own and counts it as ours (``open_window_page``)."""
585
+ session = context.browser.new_browser_cdp_session() if context.browser is not None else None
586
+ open_page = context.new_page
587
+
588
+ def new_page(*args: Any, **kwargs: Any) -> Any:
589
+ if args or kwargs or session is None:
590
+ page = open_page(*args, **kwargs)
591
+ else:
592
+ page = open_window_page(context, session)
593
+ owned.add(page)
594
+ return page
595
+
596
+ context.new_page = new_page # type: ignore[method-assign]
597
+ context.paper_search_session = session
598
+
599
+
600
+ def connect_window(endpoint: str, downloads: str) -> tuple[Any, Any]:
601
+ """Another window's driver on the batch's Chrome (``endpoint``, the first window's remote-debugging address):
602
+ (its driver, the browser's context as this driver sees it, scoped to the pages it opens; ``new_page`` opens a
603
+ window of its own). Every driver's downloads go to ``downloads`` (batch_session.shared_downloads): Chrome keeps one
604
+ folder for the profile, set by the driver that connected last. The driver stays connected until the batch ends:
605
+ one leaving resets the profile's downloads for every window."""
606
+ from patchright.sync_api import sync_playwright
607
+
608
+ pw = sync_playwright().start()
609
+ try:
610
+ browser = pw.chromium.connect_over_cdp(endpoint, timeout=WINDOW_CONNECT_TIMEOUT_MS)
611
+ context = browser.contexts[0]
612
+ owned = _scope_to_own_tabs(context)
613
+ browser.new_browser_cdp_session().send("Browser.setDownloadBehavior", {
614
+ "behavior": "allowAndName", "downloadPath": downloads, "eventsEnabled": True})
615
+ _windows_of_their_own(context, owned)
616
+ except Exception:
617
+ pw.stop()
618
+ raise
619
+ return pw, context
620
+
621
+
511
622
  def _launch_ego_persistent(config: dict[str, Any] | None) -> Any:
512
623
  """The running ego's own context (the user's logins), scoped to our tabs."""
513
624
  pw, browser = _connect_ego(config)
@@ -702,9 +813,15 @@ def _chrome_options(headless: bool, proxy: Any, args: list[str] | None,
702
813
  switches.append(f"--lang={language}")
703
814
  if language and not any(arg.startswith("--accept-lang=") for arg in switches):
704
815
  switches.append(f"--accept-lang={accept_languages(language)}")
816
+ downloads = str((config or {}).get(PARALLEL_DOWNLOADS_KEY) or "")
817
+ if downloads and not any(arg.startswith("--remote-debugging-port") for arg in switches):
818
+ # 并行下载: the other windows' drivers come in on 127.0.0.1 (a port Chrome chooses).
819
+ switches.append("--remote-debugging-port=0")
705
820
  opts: dict[str, Any] = {"executable_path": str(executable), "headless": headless, "args": switches,
706
821
  # Without it the driver adds --no-sandbox, and Chrome shows a warning bar.
707
822
  "chromium_sandbox": True}
823
+ if downloads:
824
+ opts["downloads_path"] = downloads
708
825
  if proxy:
709
826
  opts["proxy"] = proxy
710
827
  if not headless:
@@ -760,7 +877,11 @@ def _chrome_persistent(user_data_dir: str, *, headless: bool, proxy: Any, args:
760
877
  proxy = _proxy_from_config(config)
761
878
  context = _launch_chrome_persistent(profile, headless, proxy, args, config)
762
879
  _keep_session_cookies(context, profile, config)
763
- if not headless:
880
+ if (config or {}).get(PARALLEL_DOWNLOADS_KEY):
881
+ # 并行下载: this driver sees the other windows' pages too; it keeps to its own, and opens windows, not tabs.
882
+ owned = _scope_to_own_tabs(context, existing=True)
883
+ _windows_of_their_own(context, owned)
884
+ elif not headless:
764
885
  _open_tabs_in_background(context)
765
886
  _reuse_startup_page(context)
766
887
  return context
@@ -1,9 +1,20 @@
1
1
  """One browser window and tab kept for a serial MCP batch, on its Playwright
2
2
  worker thread. Used when the backend declares ``batch_window``
3
- (browser/backend.py); only plain Playwright calls, no backend of its own."""
3
+ (browser/backend.py); only plain Playwright calls, no backend of its own.
4
+
5
+ 并行下载 (user, 2026-11-29): a batch downloading several papers at once has a
6
+ window for each, in the one Chrome (one profile, one school login), each driven
7
+ by a driver of its own on a thread of its own (``BatchThread``). The first
8
+ window launches Chrome as a serial batch does, with a remote-debugging port on
9
+ 127.0.0.1 and a downloads' folder every driver shares (``shared_downloads``);
10
+ the others connect to it (``backend.connect_window``) and open a window of
11
+ their own. A window's driver sees only the pages it opened."""
4
12
  import queue
13
+ import shutil
14
+ import tempfile
5
15
  import threading
6
16
  import time
17
+ from pathlib import Path
7
18
  from concurrent.futures import Executor, Future
8
19
  from contextvars import ContextVar
9
20
  from urllib.parse import urlsplit
@@ -24,20 +35,43 @@ IDLE_POLL_SEC = 0.05
24
35
 
25
36
 
26
37
  class BatchBrowser:
27
- def __init__(self):
38
+ def __init__(self, window=0, first=None):
28
39
  self.context = None
29
40
  self.page = None
30
41
  self.info = None
31
42
  self.id = ""
32
43
  #: The publisher's article page of the last paper, when that paper saved its PDF.
33
44
  self.article_url = ""
45
+ #: 并行下载: this window's number (0, the first, launches Chrome) and the first window (for the others).
46
+ self.window = window
47
+ self.first = self if first is None else first
48
+ #: The first window: its batch runs papers at once (Chrome launched for other windows to connect to).
49
+ self.parallel = False
50
+ self.endpoint = ""
51
+ self.downloads = ""
52
+ self.ready = threading.Event()
53
+ self._driver = None # another window's own driver, connected until the batch ends
54
+ self._joined = "" # the first window's Chrome (its remote-debugging address) this one is connected to
34
55
 
35
56
  def open(self, downloader, *, relaunch=""):
36
- if self.context is not None and not self.context.pages:
57
+ if self.window:
58
+ return self._open_another(downloader)
59
+ # Its window closed: a browser one after another opens again; the other windows' Chrome, still there, stays.
60
+ if self.context is not None and not self.context.pages and not (self.parallel and _connected(self.context)):
37
61
  self.close()
38
62
  if self.context is None:
63
+ if self.parallel:
64
+ self.downloads = self.downloads or tempfile.mkdtemp(prefix="papersearch-downloads-")
65
+ shared_downloads(self.downloads)
66
+ downloader.config[_backend().PARALLEL_DOWNLOADS_KEY] = self.downloads
67
+ started = time.time()
39
68
  self.context = downloader._launch_context(relaunch=relaunch)
40
69
  self.info = downloader.browser
70
+ if self.parallel:
71
+ from ..engine.batch_common import _resolve_profile_dir
72
+
73
+ self.endpoint = _backend().devtools_endpoint(_resolve_profile_dir(downloader.config, None), started)
74
+ self.ready.set()
41
75
  else:
42
76
  downloader.browser = self.info
43
77
  ensure_enabled(self.context, downloader.config)
@@ -45,6 +79,31 @@ class BatchBrowser:
45
79
  self.page = self.context.new_page()
46
80
  return self.context
47
81
 
82
+ def _open_another(self, downloader):
83
+ """A window after the first: its driver connected to the first window's Chrome, its page a window of its own.
84
+ Waits for the first window's Chrome while it starts."""
85
+ first = self.first
86
+ if not first.ready.wait(WINDOW_READY_SEC) or not first.endpoint or first.context is None:
87
+ raise RuntimeError("the batch's first window has no browser to join")
88
+ # Gone, or the first window started Chrome again (another school, its last sign-in forgotten): this one's
89
+ # Chrome closed with it. A paper going on with it failed at once as 浏览器被关闭 (user's Mac, 2026-11-29).
90
+ if self.context is not None and (not _connected(self.context) or self._joined != first.endpoint):
91
+ self.disconnect()
92
+ if self.context is None:
93
+ from . import watchdog
94
+
95
+ watchdog.install()
96
+ self._driver, self.context = _backend().connect_window(first.endpoint, first.downloads)
97
+ self._joined = first.endpoint
98
+ from .challenge.local.interaction import prepare_context
99
+
100
+ prepare_context(self.context)
101
+ downloader.browser = first.info
102
+ downloader._browser_start = {"window": self.window}
103
+ if self.page is None or self.page.is_closed():
104
+ self.page = self.context.new_page()
105
+ return self.context
106
+
48
107
  def keep_session(self):
49
108
  """While the batch waits (the hourly limit the user set): the last paper's
50
109
  article page, loaded again in the batch's tab, so the publisher's institutional
@@ -81,17 +140,30 @@ class BatchBrowser:
81
140
  tab goes on answering. Patchright sends every request of a tab with an init script
82
141
  through this process first, and a sync driver hears it only during a call of its
83
142
  own: with no paper running, the school's login page did not move after 登录
84
- (Windows, 2026-11-18)."""
85
- page = self.page
86
- if self.context is None or page is None:
143
+ (Windows, 2026-11-18).
144
+
145
+ A window with no page answers through its context: in a batch whose papers run at
146
+ once, a window whose paper is done and whose pages are closed keeps its driver until
147
+ the batch ends, and that driver hears the requests of every window opened after it
148
+ first. Sleeping instead, it held them: Wiley's papers in the windows opened after the
149
+ other publishers' windows fell idle never loaded (Windows, 2026-11-30: a new window's
150
+ Wiley article did not load in 60 s, and loaded in 0.3 s with the idle window answering)."""
151
+ page, context = self.page, self.context
152
+ if context is None:
87
153
  time.sleep(IDLE_PASS_MS / 1000)
88
154
  return
155
+ from patchright.sync_api import TimeoutError as Waited
156
+
89
157
  from . import watchdog
90
158
 
91
159
  try:
92
- if not page.is_closed():
160
+ if page is not None and not page.is_closed():
93
161
  page.wait_for_timeout(IDLE_PASS_MS)
94
162
  return
163
+ context.wait_for_event("close", timeout=IDLE_PASS_MS)
164
+ return
165
+ except Waited:
166
+ return # its time answering is over
95
167
  except Exception:
96
168
  pass # the next paper finds the browser as it is and says so
97
169
  finally:
@@ -106,13 +178,122 @@ class BatchBrowser:
106
178
  page.close()
107
179
 
108
180
  def close(self):
181
+ if self.window:
182
+ # Its pages only: its driver stays until the batch ends (``disconnect``), Chrome keeps the profile's
183
+ # downloads where the drivers share them only while every driver that set it is there.
184
+ for page in list(getattr(self.context, "pages", []) or []):
185
+ try:
186
+ if not page.is_closed():
187
+ page.close()
188
+ except Exception:
189
+ pass
190
+ self.page = None
191
+ return
109
192
  context, self.context, self.page, self.info = self.context, None, None, None
193
+ self.ready.clear()
194
+ self.endpoint = ""
110
195
  if context is not None:
111
196
  context.close()
112
197
 
198
+ def disconnect(self):
199
+ """Another window's driver leaves (the batch's end, or Chrome gone): its pages closed first."""
200
+ driver, self._driver = self._driver, None
201
+ try:
202
+ self.close()
203
+ finally:
204
+ self.context = self.page = None
205
+ if driver is not None:
206
+ try:
207
+ driver.stop()
208
+ except Exception:
209
+ pass
210
+
113
211
 
114
212
  active_batch: ContextVar[BatchBrowser | None] = ContextVar("active_browser_batch", default=None)
115
213
 
214
+ #: How long a window after the first waits for the first one's Chrome to start.
215
+ WINDOW_READY_SEC = 180
216
+
217
+
218
+ def _backend():
219
+ from . import backend
220
+
221
+ return backend
222
+
223
+
224
+ def _connected(context) -> bool:
225
+ try:
226
+ browser = context.browser
227
+ return browser is None or browser.is_connected()
228
+ except Exception:
229
+ return False
230
+
231
+
232
+ # The downloads' folders of the batches whose windows share one (``shared_downloads``).
233
+ _SHARED: list[Path] = []
234
+ _SHARED_LOCK = threading.Lock()
235
+
236
+
237
+ def shared_downloads(folder) -> None:
238
+ """Every window's downloads arrive in ``folder`` (Chrome keeps one downloads' folder for the profile): a driver
239
+ whose own folder lacks a download takes it from there by its name (Playwright names each by its id). Without
240
+ this a window's PDF was saved empty (Mac, 2026-11-29: the second driver's connection took the profile's
241
+ downloads to its own folder)."""
242
+ with _SHARED_LOCK:
243
+ if Path(folder) not in _SHARED:
244
+ _SHARED.append(Path(folder))
245
+ _share_downloads()
246
+
247
+
248
+ def forget_downloads(folder) -> None:
249
+ """The batch is over: its folder goes."""
250
+ with _SHARED_LOCK:
251
+ if Path(folder) in _SHARED:
252
+ _SHARED.remove(Path(folder))
253
+ shutil.rmtree(folder, ignore_errors=True)
254
+
255
+
256
+ def _shared_copy(found) -> Path | None:
257
+ """Where a finished download is when not at ``found`` (its driver's own folder): a shared folder's file of its
258
+ name; None when it is where its driver put it."""
259
+ try:
260
+ here = Path(found)
261
+ if here.is_file() and here.stat().st_size:
262
+ return None
263
+ except (OSError, TypeError, ValueError):
264
+ return None
265
+ with _SHARED_LOCK:
266
+ folders = list(_SHARED)
267
+ for folder in folders:
268
+ candidate = folder / here.name
269
+ if candidate.is_file():
270
+ return candidate
271
+ return None
272
+
273
+
274
+ def _share_downloads() -> None:
275
+ from patchright.sync_api._generated import Download
276
+
277
+ if getattr(Download, "_papersearch_shared", False):
278
+ return
279
+ original_path, original_save = Download.path, Download.save_as
280
+
281
+ def path(self):
282
+ found = original_path(self)
283
+ return _shared_copy(found) or found
284
+
285
+ def save_as(self, target):
286
+ shared = _shared_copy(original_path(self)) # waits for the download to finish, as Playwright's does
287
+ if shared is None:
288
+ return original_save(self, target)
289
+ Path(target).parent.mkdir(parents=True, exist_ok=True)
290
+ shutil.copyfile(shared, target)
291
+ return None
292
+
293
+ Download.path = path
294
+ Download.save_as = save_as
295
+ Download._papersearch_shared = True
296
+
116
297
 
117
298
  class BatchThread(Executor):
118
299
  """The batch's one browser thread: runs its jobs in order, and with none waiting calls
@@ -177,7 +358,7 @@ def _settle(page, site: str) -> str:
177
358
  after KEEP_SESSION_SETTLE_SECONDS, "verification" or "signin" (another site: the
178
359
  publisher's sign-in, a school's login). A check's checkbox is clicked as in a
179
360
  download (at most three times, three seconds apart)."""
180
- from .challenge.interaction import click_checkbox
361
+ from .challenge.local.interaction import click_checkbox
181
362
  until = time.monotonic() + KEEP_SESSION_SETTLE_SECONDS
182
363
  clicks, next_click = 0, 0.0
183
364
  page.wait_for_timeout(2000) # a redirect the page makes once loaded
@@ -1,13 +1,16 @@
1
- """Verification handling: avoid it, recognise it, press its widget, hand over the rest.
1
+ """Publisher verification: detection, local controls, image services and handlers.
2
2
 
3
+ local/: native browser controls; interaction owns Cloudflare/Turnstile clicks,
4
+ pointer owns movement/presses, prompt owns other checkboxes and outer submit.
5
+ services/: server requests and decoded image answers, with no browser actions.
6
+ handlers/: aws_waf, recaptcha_hcaptcha and text_captcha extract puzzles and
7
+ apply the service answers in the same browser.
8
+ continuation: bounded dispatch into the handlers.
3
9
  detection: verification evidence predicates, with no browser or task state.
4
- interaction: one bounded press on an observed Turnstile widget, and its event record.
5
- pointer: the pointer path and the hold before that press.
6
- prompt: the other providers' own confirmation controls, one press each.
7
- warmup: the site root visit before its first article, so the session starts on
8
- the site rather than on a deep article URL.
10
+ warmup: visit a site root before its first article.
11
+ kinds: which kind of verification a page is (reCAPTCHA v2, hCaptcha's puzzle, ...), for
12
+ the record only.
9
13
 
10
- The engine owns waiting and decides whether verification ended; nothing here
11
- answers a puzzle or reads a response token.
14
+ The engine owns waiting and decides whether the publisher has allowed access.
15
+ No response tokens are read or injected.
12
16
  """
13
- from __future__ import annotations
@@ -0,0 +1,83 @@
1
+ """Continue a publisher verification in the same browser with a typed service task."""
2
+ from __future__ import annotations
3
+
4
+ import time
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from .services import solver
9
+ from . import pro
10
+
11
+
12
+ class Expired(Exception):
13
+ """The existing verification deadline has elapsed."""
14
+
15
+
16
+ @dataclass
17
+ class Limits:
18
+ deadline: float
19
+ budget: solver.Budget
20
+ checkpoint: Any = None
21
+ cleanup: Any = None
22
+
23
+ def remaining(self) -> float:
24
+ if self.checkpoint:
25
+ self.checkpoint()
26
+ left = self.deadline - time.monotonic()
27
+ if left <= 0:
28
+ raise Expired
29
+ return left
30
+
31
+ def sleep(self, seconds: float) -> None:
32
+ until = time.monotonic() + seconds
33
+ while time.monotonic() < until:
34
+ time.sleep(min(0.2, self.remaining(), max(0, until - time.monotonic())))
35
+ self.remaining()
36
+
37
+
38
+ def resume(page: Any, config: dict, *, kind: str, limits: Limits, observation: Any) -> bool:
39
+ """True means return to the outer page check, never that the site passed.
40
+
41
+ This dispatcher is entered only for publisher pages. The engine checks the
42
+ IdP boundary before local actions and before every service continuation.
43
+ """
44
+ note = observation
45
+ extension = pro.verification()
46
+ handler = extension.HANDLERS.get(kind) if extension is not None else None
47
+ if not callable(handler) and kind not in {"awswaf", "recaptcha", "hcaptcha", "image_code", "turnstile"}:
48
+ note(f"service unsupported: {kind}; no handler")
49
+ return False
50
+ if not solver.configured(config):
51
+ note("service not configured")
52
+ return False
53
+ try:
54
+ limits.remaining()
55
+ if callable(handler):
56
+ try:
57
+ result = handler(page, config, kind=kind, limits=limits, observation=note)
58
+ if not isinstance(result, bool):
59
+ raise TypeError('invalid Pro handler result')
60
+ return result
61
+ except Expired:
62
+ raise
63
+ except Exception as exc:
64
+ limits.remaining() # Cancellation and expiry remain authoritative.
65
+ pro.log.warning("PaperSearch Pro verification handler failed (%s); using public handler",
66
+ type(exc).__name__)
67
+ if kind not in {"awswaf", "recaptcha", "hcaptcha", "image_code", "turnstile"}:
68
+ note(f"service unsupported: {kind}; no public fallback")
69
+ return False
70
+ if kind == "turnstile":
71
+ from .handlers import turnstile
72
+ return turnstile.solve(page, config, limits=limits, observation=note)
73
+ if kind == "awswaf":
74
+ from .handlers import aws_waf
75
+ return aws_waf.solve(page, config, observation=note, limits=limits)
76
+ if kind == "image_code":
77
+ from .handlers import text_captcha
78
+ return text_captcha.solve(page, config, limits=limits, observation=note)
79
+ from .handlers import recaptcha_hcaptcha
80
+ return recaptcha_hcaptcha.solve(page, config, kind=kind, limits=limits, observation=note)
81
+ except Expired:
82
+ note("service deadline exhausted")
83
+ return False
@@ -0,0 +1 @@
1
+ """Read each supported puzzle and apply service answers in the same browser."""