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
@@ -0,0 +1,126 @@
1
+ """One window at a time asks for the user (并行下载, user 2026-11-29).
2
+
3
+ A batch downloading several papers at once runs each in a window of its own in the one download browser
4
+ (``batch_session.BatchBrowser``). The school's login and a verification the user has to complete come up in one of
5
+ them only: a window that needs the user while another one does waits for its turn, its page answering meanwhile, and
6
+ the other windows go on with their papers. Its time to wait for the user starts when its turn comes, not before.
7
+
8
+ Turns are taken only in a batch whose windows run at once (``start``); a paper on its own, or a batch one paper after
9
+ another, takes none and waits for nobody.
10
+
11
+ A turn is the window's from the step that may ask the user (the school's login, a verification handed to the user)
12
+ to that step's end, nested steps counted (``acquire``/``release``), and never past its paper (``release_all``). A turn
13
+ whose wait on the user ran out unanswered says so (``note_expired``): a window whose turn came after it was waiting
14
+ for an absent user too, and waits for the user only briefly (the batch's ``user_wait`` "short").
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import threading
19
+ import time
20
+ from contextvars import ContextVar
21
+ from typing import Callable
22
+
23
+ _cond = threading.Condition()
24
+ _holder: int | None = None
25
+ _depth = 0
26
+ _parallel = False
27
+ _expired_at = 0.0
28
+ _window: ContextVar[int | None] = ContextVar("papersearch_batch_window", default=None)
29
+ #: How often a window waiting for its turn lets its page answer (its pump).
30
+ POLL_SEC = 0.25
31
+
32
+
33
+ def start(parallel: bool) -> None:
34
+ """A batch begins (server.py): its windows take turns when it runs several at once."""
35
+ global _parallel, _holder, _depth
36
+ with _cond:
37
+ _parallel = bool(parallel)
38
+ _holder, _depth = None, 0
39
+ _cond.notify_all()
40
+
41
+
42
+ def bind(window: int | None):
43
+ """The window the current download runs in (server.py, on the window's own thread); returns the token to reset."""
44
+ return _window.set(window)
45
+
46
+
47
+ def unbind(token) -> None:
48
+ _window.reset(token)
49
+
50
+
51
+ def window() -> int | None:
52
+ """The window of the current download in a batch whose windows run at once; None otherwise."""
53
+ found = _window.get()
54
+ return found if _parallel and found is not None else None
55
+
56
+
57
+ def active() -> bool:
58
+ """Whether the current download takes turns with other windows."""
59
+ return window() is not None
60
+
61
+
62
+ def acquire(pump: Callable[[], None] | None = None) -> float:
63
+ """The current window's turn to ask for the user: at once when no other window has it (or this one already
64
+ does, a step within a step), else once the other's ends, ``pump`` called meanwhile (its page answering, the
65
+ user's buttons read). Returns the seconds waited."""
66
+ global _holder, _depth
67
+ me = window()
68
+ if me is None:
69
+ return 0.0
70
+ started = time.monotonic()
71
+ while True:
72
+ with _cond:
73
+ if _holder is None or _holder == me:
74
+ _holder = me
75
+ _depth += 1
76
+ return time.monotonic() - started
77
+ if pump is None:
78
+ _cond.wait(POLL_SEC)
79
+ continue
80
+ pump()
81
+
82
+
83
+ def release() -> None:
84
+ """The current window's step that asked for the user ended: its turn ends with its outermost one."""
85
+ global _holder, _depth
86
+ me = window()
87
+ if me is None:
88
+ return
89
+ with _cond:
90
+ if _holder != me:
91
+ return
92
+ _depth -= 1
93
+ if _depth <= 0:
94
+ _holder, _depth = None, 0
95
+ _cond.notify_all()
96
+
97
+
98
+ def release_all() -> None:
99
+ """The current window's paper ended: whatever turn it held ends with it."""
100
+ global _holder, _depth
101
+ me = window()
102
+ if me is None:
103
+ return
104
+ with _cond:
105
+ if _holder == me:
106
+ _holder, _depth = None, 0
107
+ _cond.notify_all()
108
+
109
+
110
+ def holder() -> int | None:
111
+ """The window whose turn it is, or None."""
112
+ with _cond:
113
+ return _holder
114
+
115
+
116
+ def note_expired() -> None:
117
+ """A wait on the user ran out unanswered: the user seems away."""
118
+ global _expired_at
119
+ with _cond:
120
+ _expired_at = time.monotonic()
121
+
122
+
123
+ def expired_since(since: float) -> bool:
124
+ """Whether a wait on the user ran out after ``since`` (time.monotonic())."""
125
+ with _cond:
126
+ return _expired_at > since
@@ -16,12 +16,25 @@ thread: :func:`interrupt` ends the item at once (the running call is cancelled
16
16
  and every later call raises the given exception until :func:`clear_interrupt`),
17
17
  and :func:`run_soon` runs work, such as handling a problem report, on the
18
18
  browser thread before its next call.
19
+
20
+ Each browser thread has its own: a batch downloading several papers at once runs
21
+ one browser thread per window (并行下载, user 2026-11-29), and a skip, a slow call
22
+ or work queued for one paper stays with its window. A thread a browser thread
23
+ starts for its paper (the window's requests) says whose it is (:func:`adopt`).
24
+ ``fired`` is the process's: a call that never returns ends the backend. In a window
25
+ of a batch whose papers run at once (:func:`in_window`) it is that window's: its
26
+ paper ends as ``browser_unresponsive`` and the other windows' papers go on; the
27
+ client takes the batch's next papers to a new backend once they are done. Ending
28
+ them all, or stopping the watch after the first, left another window's stuck call
29
+ waiting for the 20-minute item timeout (Windows, 2026-11-30).
19
30
  """
20
31
  from __future__ import annotations
21
32
 
22
33
  import asyncio
23
34
  import logging
35
+ import sys
24
36
  import threading
37
+ import types
25
38
  import time
26
39
  import traceback
27
40
  from contextlib import contextmanager
@@ -45,24 +58,99 @@ _abandoned: set[int] = set()
45
58
  _local = threading.local()
46
59
  _installed = False
47
60
  # A browser call longer than this is reported to ``on_slow_call(name, seconds,
48
- # ended, caller)``, set by the downloader for the article it runs: a Playwright
49
- # default timeout of 30 s otherwise passes without a trace (Sage, 2026-11-02).
61
+ # ended, caller)``, set by the downloader for the article it runs (its thread's,
62
+ # _ThreadState): a Playwright default timeout of 30 s otherwise passes without a
63
+ # trace (Sage, 2026-11-02).
50
64
  SLOW_CALL_SEC = 10
51
- on_slow_call: Any = None
52
- # The browser calls since the article's previous step (``take_period``): a long
53
- # silence then says whether it was spent in the browser, and on what.
54
- _period: dict[str, Any] = {"calls": 0, "seconds": 0.0, "slowest": "", "slowest_sec": 0.0}
65
+ fired: dict[str, Any] | None = None
66
+
67
+
68
+ class _ThreadState:
69
+ """One browser thread's: its paper's skip or stop (``interrupted``), the callback for its slow calls
70
+ (``on_slow_call``), its calls since the paper's previous step (``period``, :func:`take_period`), the work queued
71
+ for it (:func:`run_soon`)."""
72
+
73
+ def __init__(self) -> None:
74
+ self.interrupted: BaseException | None = None
75
+ self.on_slow_call: Any = None
76
+ self.period: dict[str, Any] = _new_period()
77
+ self.soon: list[Any] = []
78
+ self.running_soon = False
79
+ #: A window's paper in a batch whose papers run at once (:func:`in_window`), and what ended its calls.
80
+ self.window = False
81
+ self.fired: dict[str, Any] | None = None
82
+
83
+
84
+ def _new_period() -> dict[str, Any]:
85
+ return {"calls": 0, "seconds": 0.0, "slowest": "", "slowest_sec": 0.0}
86
+
87
+
88
+ _states: dict[int, _ThreadState] = {}
89
+ # A window's calls already cancelled (check): each once.
90
+ _window_cancelled: set[int] = set()
91
+
92
+
93
+ def _thread() -> int:
94
+ """The browser thread the caller works for: its own, or the one that adopted it."""
95
+ return getattr(_local, "owner", None) or threading.get_ident()
96
+
97
+
98
+ def _state(thread: int | None = None) -> _ThreadState:
99
+ key = _thread() if thread is None else thread
100
+ found = _states.get(key)
101
+ if found is None:
102
+ found = _states.setdefault(key, _ThreadState())
103
+ return found
104
+
105
+
106
+ def adopt(thread: int) -> None:
107
+ """This thread works for the browser thread ``thread`` (a paper's watch of the window's requests): its
108
+ :func:`interrupt`, :func:`run_soon` and ``interrupted`` are that thread's."""
109
+ _local.owner = thread
55
110
 
56
111
 
57
112
  def take_period() -> dict[str, Any]:
58
113
  """The browser calls since the last time asked (count, seconds, the slowest), and start again."""
59
- global _period
60
- taken, _period = _period, {"calls": 0, "seconds": 0.0, "slowest": "", "slowest_sec": 0.0}
114
+ state = _state()
115
+ taken, state.period = state.period, _new_period()
61
116
  return taken
62
- fired: dict[str, Any] | None = None
63
- interrupted: BaseException | None = None
64
- _soon: list[Any] = []
65
- _running_soon = False
117
+
118
+
119
+ def _thread_attribute(name: str, default: Any) -> property:
120
+ """A module attribute that is the calling thread's ``name`` (its _ThreadState); deleting it puts back ``default()``."""
121
+ def get(self: Any) -> Any:
122
+ return getattr(_state(), name)
123
+
124
+ def put(self: Any, value: Any) -> None:
125
+ setattr(_state(), name, value)
126
+
127
+ def reset(self: Any) -> None:
128
+ setattr(_state(), name, default())
129
+
130
+ return property(get, put, reset)
131
+
132
+
133
+ class _Module(types.ModuleType):
134
+ """``interrupted``, ``on_slow_call`` and the queued work and call counts (``_soon``, ``_running_soon``, ``_period``),
135
+ read and set as module attributes, are the calling thread's."""
136
+
137
+ interrupted = _thread_attribute("interrupted", lambda: None)
138
+ on_slow_call = _thread_attribute("on_slow_call", lambda: None)
139
+ _soon = _thread_attribute("soon", list)
140
+ _running_soon = _thread_attribute("running_soon", lambda: False)
141
+ _period = _thread_attribute("period", _new_period)
142
+
143
+ @property
144
+ def fired(self) -> dict[str, Any] | None:
145
+ """What ended the browser calls: the process's, else the calling thread's window's (:func:`in_window`)."""
146
+ return _fired_of()
147
+
148
+ @fired.setter
149
+ def fired(self, value: dict[str, Any] | None) -> None:
150
+ globals()["fired"] = value
151
+
152
+
153
+ sys.modules[__name__].__class__ = _Module
66
154
 
67
155
 
68
156
  class BrowserUnresponsive(Exception):
@@ -178,14 +266,33 @@ def pause_operation():
178
266
  _local.budgets = stack
179
267
 
180
268
 
269
+ def in_window(on: bool) -> bool:
270
+ """The calling thread begins a window's paper of a batch whose papers run at once (``on``), or another paper
271
+ (server.py). Returns whether a call of the last paper in this window ran past its time: that page is not the next
272
+ paper's (its call may still be waiting)."""
273
+ state = _state(threading.get_ident())
274
+ ended = state.fired is not None
275
+ state.window, state.fired = bool(on), None
276
+ return ended
277
+
278
+
279
+ def _fired_of(state: _ThreadState | None = None) -> dict[str, Any] | None:
280
+ """What ended the calling thread's browser calls: the process's, else its window's."""
281
+ if fired is not None:
282
+ return fired
283
+ return (_state() if state is None else state).fired
284
+
285
+
181
286
  def failure_code() -> str:
182
- return "browser_operation_timeout" if fired and fired.get("operation") else "browser_unresponsive"
287
+ ended = _fired_of()
288
+ return "browser_operation_timeout" if ended and ended.get("operation") else "browser_unresponsive"
183
289
 
184
290
 
185
- def _timeout_error() -> BrowserUnresponsive:
186
- if fired and fired.get("operation"):
187
- return BrowserOperationTimeout(f"{fired['operation']} exceeded its page budget during {fired['call']}")
188
- return BrowserUnresponsive(f"browser unresponsive since {fired['call']}")
291
+ def _timeout_error(ended: dict[str, Any] | None = None) -> BrowserUnresponsive:
292
+ ended = ended or _fired_of()
293
+ if ended and ended.get("operation"):
294
+ return BrowserOperationTimeout(f"{ended['operation']} exceeded its page budget during {ended['call']}")
295
+ return BrowserUnresponsive(f"browser unresponsive since {ended['call']}")
189
296
 
190
297
 
191
298
  def install(limit_sec: float = LIMIT_SEC) -> None:
@@ -198,15 +305,17 @@ def install(limit_sec: float = LIMIT_SEC) -> None:
198
305
  def timing(original: Any) -> Any:
199
306
  def timed_sync(self: Any, coro: Any) -> Any:
200
307
  name = getattr(coro, "__qualname__", "") or type(coro).__name__
201
- if fired is not None:
308
+ state = _state(threading.get_ident())
309
+ ended_by = _fired_of(state)
310
+ if ended_by is not None:
202
311
  coro.close()
203
- raise _timeout_error()
204
- if interrupted is not None:
312
+ raise _timeout_error(ended_by)
313
+ if state.interrupted is not None:
205
314
  coro.close()
206
- raise interrupted
207
- if _soon and not _running_soon:
315
+ raise state.interrupted
316
+ if state.soon and not state.running_soon:
208
317
  try:
209
- _run_soon_calls()
318
+ _run_soon_calls(state)
210
319
  except BaseException:
211
320
  coro.close()
212
321
  raise
@@ -222,7 +331,7 @@ def install(limit_sec: float = LIMIT_SEC) -> None:
222
331
  raise BrowserBudgetExhausted(f"{label} exhausted its page budget before {name}")
223
332
  _call_deadlines[key] = (deadline, label)
224
333
  _inflight[key] = (started, name, traceback.format_stack(limit=8)[:-1],
225
- getattr(self, "_loop", None), coro, _greenlet())
334
+ getattr(self, "_loop", None), coro, _greenlet(), threading.get_ident())
226
335
  ended = "returned"
227
336
  try:
228
337
  return original(self, coro)
@@ -230,10 +339,10 @@ def install(limit_sec: float = LIMIT_SEC) -> None:
230
339
  ended = "cancelled"
231
340
  if key in _abandoned:
232
341
  raise CallAbandoned(name) from None
233
- if fired is not None:
234
- raise _timeout_error() from None
235
- if interrupted is not None:
236
- raise interrupted from None
342
+ if _fired_of(state) is not None:
343
+ raise _timeout_error(_fired_of(state)) from None
344
+ if state.interrupted is not None:
345
+ raise state.interrupted from None
237
346
  raise
238
347
  except BaseException as exc:
239
348
  ended = type(exc).__name__
@@ -242,13 +351,15 @@ def install(limit_sec: float = LIMIT_SEC) -> None:
242
351
  _inflight.pop(key, None)
243
352
  _call_deadlines.pop(key, None)
244
353
  _abandoned.discard(key)
354
+ _window_cancelled.discard(key)
245
355
  elapsed = time.monotonic() - started
246
- _period["calls"] += 1
247
- _period["seconds"] += elapsed
248
- if elapsed > _period["slowest_sec"]:
249
- _period["slowest"], _period["slowest_sec"] = name, elapsed
250
- if elapsed > SLOW_CALL_SEC and on_slow_call is not None:
251
- _report_slow(name, elapsed, ended)
356
+ period = state.period
357
+ period["calls"] += 1
358
+ period["seconds"] += elapsed
359
+ if elapsed > period["slowest_sec"]:
360
+ period["slowest"], period["slowest_sec"] = name, elapsed
361
+ if elapsed > SLOW_CALL_SEC and state.on_slow_call is not None:
362
+ _report_slow(state.on_slow_call, name, elapsed, ended)
252
363
  return timed_sync
253
364
 
254
365
  for base in sync_bases():
@@ -257,7 +368,7 @@ def install(limit_sec: float = LIMIT_SEC) -> None:
257
368
  threading.Thread(target=_watch, args=(limit_sec,), name="browser-watchdog", daemon=True).start()
258
369
 
259
370
 
260
- def _report_slow(name: str, seconds: float, ended: str) -> None:
371
+ def _report_slow(on_slow_call: Any, name: str, seconds: float, ended: str) -> None:
261
372
  """Tell ``on_slow_call`` about a long call, with the engine's line that made it."""
262
373
  frames = [f for f in traceback.extract_stack(limit=16)
263
374
  if "paper_search_school" in f.filename and not f.filename.endswith("watchdog.py")]
@@ -273,8 +384,43 @@ def _watch(limit_sec: float) -> None:
273
384
  time.sleep(0.25)
274
385
 
275
386
 
387
+ def _what_ended(key: int, entry: tuple, deadlines: dict, now: float, limit_sec: float) -> dict[str, Any]:
388
+ started, name = entry[:2]
389
+ ended: dict[str, Any] = {"call": name, "seconds": int(now - started)}
390
+ deadline = deadlines.get(key)
391
+ if deadline and deadline[0] <= now and deadline[0] <= started + limit_sec:
392
+ ended["operation"] = deadline[1]
393
+ return ended
394
+
395
+
396
+ def _window_of(entry: tuple) -> _ThreadState | None:
397
+ """The state of the window whose call ``entry`` is (in_window), or None."""
398
+ state = _states.get(entry[6]) if len(entry) > 6 else None
399
+ return state if state is not None and state.window else None
400
+
401
+
402
+ def _end_window(state: _ThreadState, key: int, entry: tuple, deadlines: dict, now: float, limit_sec: float) -> None:
403
+ """A window's call past its time: that window's paper ends (its calls cancelled, its later calls raise), the
404
+ other windows go on."""
405
+ if state.fired is None:
406
+ state.fired = ended = _what_ended(key, entry, deadlines, now, limit_sec)
407
+ code = "browser_operation_timeout" if ended.get("operation") else "browser_unresponsive"
408
+ log.warning("%s (one window): %s waited %ss; operation=%s; caller:\n%s", code, ended["call"],
409
+ ended["seconds"], ended.get("operation", ""), "".join(entry[2]))
410
+ from ..log import dump_stacks
411
+
412
+ dump_stacks(f"{code} (one window): {ended['call']} waited {ended['seconds']}s")
413
+ for other_key, other in list(_inflight.items()):
414
+ if len(other) > 6 and other[6] == entry[6] and other_key not in _window_cancelled:
415
+ _window_cancelled.add(other_key)
416
+ loop, coro = other[3], other[4]
417
+ if loop is not None and not loop.is_closed():
418
+ loop.call_soon_threadsafe(_cancel, coro)
419
+
420
+
276
421
  def check(limit_sec: float) -> bool:
277
- """Cancel a call that has run past ``limit_sec``; True once fired."""
422
+ """Cancel a call that has run past ``limit_sec``; True once fired for the process. A window's call
423
+ (:func:`in_window`) ends that window's paper only, and the watch goes on."""
278
424
  global fired
279
425
  if fired is not None:
280
426
  return True
@@ -285,12 +431,18 @@ def check(limit_sec: float) -> bool:
285
431
  or (key in deadlines and now >= deadlines[key][0] + OPERATION_GRACE_SEC)]
286
432
  if not overdue:
287
433
  return False
288
- key, entry = min(overdue, key=lambda pair: pair[1][0])
289
- started, name, stack, loop, coro, _ = entry
290
- fired = {"call": name, "seconds": int(now - started)}
291
- deadline = deadlines.get(key)
292
- if deadline and deadline[0] <= now and deadline[0] <= started + limit_sec:
293
- fired["operation"] = deadline[1]
434
+ rest = []
435
+ for key, entry in sorted(overdue, key=lambda pair: pair[1][0]):
436
+ window = _window_of(entry)
437
+ if window is not None:
438
+ _end_window(window, key, entry, deadlines, now, limit_sec)
439
+ else:
440
+ rest.append((key, entry))
441
+ if not rest:
442
+ return False
443
+ key, entry = rest[0]
444
+ started, name, stack, loop, coro = entry[:5]
445
+ fired = _what_ended(key, entry, deadlines, now, limit_sec)
294
446
  log.warning("%s: %s waited %ss; operation=%s; caller:\n%s", failure_code(), name,
295
447
  fired["seconds"], fired.get("operation", ""), "".join(stack))
296
448
  # Every thread's stack, for the cause of the hang (still unknown, 2026-11-01).
@@ -302,34 +454,35 @@ def check(limit_sec: float) -> bool:
302
454
  return True
303
455
 
304
456
 
305
- def interrupt(exc: BaseException) -> None:
306
- """End the item at once: cancel the running browser call; it and every later
307
- call raise ``exc`` until :func:`clear_interrupt`."""
308
- global interrupted
309
- interrupted = exc
310
- for _, _, _, loop, coro, _ in list(_inflight.values()):
311
- if loop is not None and not loop.is_closed():
457
+ def interrupt(exc: BaseException, thread: int | None = None) -> None:
458
+ """End the item of the browser thread at once (the caller's, or ``thread``): cancel
459
+ its running browser call; it and every later call of that thread raise ``exc``
460
+ until :func:`clear_interrupt`. Another window's paper goes on."""
461
+ key = _thread() if thread is None else thread
462
+ _state(key).interrupted = exc
463
+ for entry in list(_inflight.values()):
464
+ loop, coro, owner = entry[3], entry[4], entry[6]
465
+ if owner == key and loop is not None and not loop.is_closed():
312
466
  loop.call_soon_threadsafe(_cancel, coro)
313
467
 
314
468
 
315
469
  def clear_interrupt() -> None:
316
- global interrupted
317
- interrupted = None
470
+ _state().interrupted = None
318
471
 
319
472
 
320
- def run_soon(work: Any) -> None:
321
- """Run ``work()`` on the browser thread before its next browser call."""
322
- _soon.append(work)
473
+ def run_soon(work: Any, thread: int | None = None) -> None:
474
+ """Run ``work()`` on the browser thread (the caller's, or ``thread``) before its next browser call."""
475
+ _state(thread).soon.append(work)
323
476
 
324
477
 
325
- def _run_soon_calls() -> None:
326
- global _running_soon
327
- _running_soon = True
478
+ def _run_soon_calls(state: _ThreadState | None = None) -> None:
479
+ state = _state() if state is None else state
480
+ state.running_soon = True
328
481
  try:
329
- while _soon:
330
- _soon.pop(0)()
482
+ while state.soon:
483
+ state.soon.pop(0)()
331
484
  finally:
332
- _running_soon = False
485
+ state.running_soon = False
333
486
 
334
487
 
335
488
  def _cancel(coro: Any) -> None:
@@ -38,13 +38,18 @@ def update(changes: dict[str, str | None]) -> None:
38
38
  data.pop(key, None)
39
39
  else:
40
40
  data[key] = value
41
- target = config_path()
41
+ write_private_json(config_path(), data)
42
+
43
+
44
+ def write_private_json(target: Path, data: dict) -> None:
45
+ """Atomically replace a local JSON file that can contain credentials."""
42
46
  target.parent.mkdir(parents=True, exist_ok=True)
43
- with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=target.parent, delete=False) as fh:
44
- temporary = Path(fh.name)
45
- json.dump(data, fh, ensure_ascii=False, indent=2)
46
- fh.write("\n")
47
+ fh = tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=target.parent, delete=False)
48
+ temporary = Path(fh.name)
47
49
  try:
50
+ with fh:
51
+ json.dump(data, fh, ensure_ascii=False, indent=2)
52
+ fh.write("\n")
48
53
  os.chmod(temporary, 0o600)
49
54
  temporary.replace(target)
50
55
  finally:
@@ -84,6 +84,14 @@ DEFAULT_CONFIG: dict[str, Any] = {
84
84
  "publisher_hourly_limit": 100,
85
85
  # 改了上面的上限时,正在等上限的篇目是否立即按新上限接着下;false = 这一小时过后再按新上限。
86
86
  "publisher_hourly_limit_now": False,
87
+ # 失败后自动重试:原因不明的批量最后再试一次,被网站拦截的 10 分钟后再试一次;默认关(用户 2026-11-24)。
88
+ "batch_retry_failed": False,
89
+ # 同时下载(设置窗口“下载”页;用户 2026-11-29):默认串行;并行时同时下几家出版社(不同出版社)、每家同时几篇(同一出版社),
90
+ # 各至少 1、不设上限(user_settings.py)。
91
+ "batch_parallel": False,
92
+ "batch_parallel_publishers": 1,
93
+ "batch_parallel_per_publisher": 1,
94
+ # 验证码识别服务(用户 2026-11-25 定):见 browser/challenge/services/solver.py。
87
95
  # 没权限时换下一所学校 (school_switch.py; user, 2026-11-21): on unless turned off.
88
96
  "school_switch": True,
89
97
  # 灰色源竞速浏览器的独立无头开关(只影响 sci-hub 竞速,机构登录仍有可见窗口)。
@@ -131,7 +139,7 @@ def _from_before_rename(existing: dict[str, Any]) -> dict[str, Any]:
131
139
  return existing
132
140
 
133
141
 
134
- def load_config() -> dict[str, Any]:
142
+ def load_config(*, strict: bool = False) -> dict[str, Any]:
135
143
  config = DEFAULT_CONFIG.copy()
136
144
  if CONFIG_FILE.exists():
137
145
  try:
@@ -139,8 +147,11 @@ def load_config() -> dict[str, Any]:
139
147
  existing = json.load(fh)
140
148
  if isinstance(existing, dict):
141
149
  config.update(_from_before_rename(existing))
150
+ elif strict:
151
+ raise ValueError("School backend configuration must be a JSON object")
142
152
  except Exception:
143
- pass
153
+ if strict:
154
+ raise
144
155
  for key, value in DEFAULT_CONFIG.items():
145
156
  config.setdefault(key, value)
146
157
  for key in _RETIRED_KEYS:
@@ -149,14 +160,9 @@ def load_config() -> dict[str, Any]:
149
160
 
150
161
 
151
162
  def save_config(config: dict[str, Any]) -> None:
152
- DATA_DIR.mkdir(parents=True, exist_ok=True)
153
- with CONFIG_FILE.open("w", encoding="utf-8") as fh:
154
- json.dump(config, fh, indent=2, ensure_ascii=False)
155
- try:
156
- # Readable by the user only: it may hold a school's account (school_login.py).
157
- CONFIG_FILE.chmod(0o600)
158
- except OSError:
159
- pass
163
+ from .cli_config import write_private_json
164
+
165
+ write_private_json(CONFIG_FILE.resolve(), config)
160
166
 
161
167
 
162
168
  _VALIDATION_RULES: dict[str, tuple[type, Any, Any]] = {
@@ -29,6 +29,7 @@ unsupported_platform unsupported_publisher user_skipped user_marked_no_entitleme
29
29
  article_not_yet_published doi_not_resolved doi_not_registered network_unavailable
30
30
  institution_federation_unavailable browser_unresponsive browser_operation_timeout login_not_reached idp_no_return_to_publisher
31
31
  generic_institution_entry_missing no_institution_entry browser_closed browser_connection_lost
32
+ pdf_not_offered
32
33
  """.split())
33
34
  _STATES = _FAILURES | _STATUSES | frozenset("""
34
35
  started article_loaded article_loaded_after_sso pdf_response_captured
@@ -58,9 +59,9 @@ pdf_capture_started pdf_navigation_error pdf_saved pdf_state_candidate post_logi
58
59
  post_login_hold_article_access post_login_hold_auth_wall post_login_hold_login_page
59
60
  post_run_hold publisher_access_blocked publisher_content_error publisher_unreachable publisher_login_menu_opened
60
61
  publisher_pdf_link_unverified publisher_session_save_failed publisher_session_saved
61
- publisher_terms_accepted personal_account_offer_skipped personal_account_offer_left
62
+ publisher_terms_accepted download_terms_agreed personal_account_offer_skipped personal_account_offer_left
62
63
  record_article_return record_article_return_error seamlessaccess_chooser_opened
63
- shared_cookies_exported shared_cookies_loaded sso_entry_clicked sso_entry_error sso_start
64
+ shared_cookies_exported shared_cookies_loaded sso_entry_clicked sso_entry_opened sso_entry_error sso_start challenge_type
64
65
  access_unknown_pdf_first access_unknown_pdf_failed pdf_step_login_required login_round_trip_returned
65
66
  pdf_probe pdf_probe_captured pdf_probe_refused no_access_after_login pdf_found_while_waiting
66
67
  login_entry_missing login_entry_controls access_menu_opened access_menu_entry_refused access_menu_error
@@ -161,6 +162,10 @@ def serialize_download_result(result, *, phase=None, full_text=None,
161
162
  "final_url_role": _url_role(_get(result, "final_url")),
162
163
  "pdf_url_role": _url_role(_get(result, "pdf_url")),
163
164
  }
165
+ from .browser.challenge.kinds import LABELS as CHALLENGE_TYPES
166
+ challenge_type = _get(result, "challenge_type")
167
+ if type(challenge_type) is str and challenge_type in CHALLENGE_TYPES:
168
+ packet["challenge_type"] = challenge_type
164
169
  if phase is not None:
165
170
  packet["phase"] = _choice(phase, {"primary", "retry"}, "unknown")
166
171
  if doi and type(artifact_name) is str and artifact_name == re.sub(r"[^\w\-.]", "_", doi) + ".pdf":
@@ -201,6 +201,12 @@ OPEN_SIGNS_JS = r"""() => {
201
201
  if (/(?:^|\s)license(?:\s|$)/i.test(link.getAttribute('rel')) && CC.test(link.href) && !link.closest(NOT))
202
202
  return `licence link: ${short(link.href)}`;
203
203
  }
204
+ // A licence badge named for what it is, without rel="license": F1000's open research platforms'
205
+ // <a aria-label="Creative Commons License CC-BY" href="https://creativecommons.org/licenses/">
206
+ // (Bioethics Open Research, taken for a closed page and sent to the school's login, 2026-11-24).
207
+ for (const a of document.querySelectorAll('a[href][aria-label*="creative commons licen" i]')) {
208
+ if (CC.test(a.href) && !a.closest(NOT)) return `licence link: ${short(a.href)}`;
209
+ }
204
210
  for (const script of [...document.querySelectorAll('script[type="application/ld+json"]')].slice(0, 8)) {
205
211
  let data;
206
212
  try { data = JSON.parse((script.textContent || '').slice(0, 200000)); } catch (_) { continue; }
@@ -270,13 +276,16 @@ _OFFER_PHRASE = re.compile(
270
276
  # read this": RSC and Oxford Academic "You do not currently have access to this
271
277
  # content/article.", ScienceDirect "<school> does not subscribe to this content
272
278
  # on ScienceDirect.", Sage "Access via <school> is not available as they do not
273
- # subscribe to Sage Journals content.". A whole line: help copy and
274
- # conditionals around it are not a denial.
279
+ # subscribe to Sage Journals content.", nature.com "Access to this article via <institution>
280
+ # is not available." (its name in <strong> with no spaces around it, so the line reads
281
+ # "via<name>is not available"; Nature Cities, Windows 2026-11-24). A whole line: help copy
282
+ # and conditionals around it are not a denial.
275
283
  _DENIAL_LINE = re.compile(
276
284
  r"(?:(?:(?P<who>you|your (?:institution|organi[sz]ation))|(?P<name>[^.!?:\"“”]{2,120}?))\s+(?:do|does)\s+not"
277
285
  r"\s+(?:currently\s+)?(?:have access to|subscribe to)\s+(?:this|the)\s+"
278
286
  r"(?:article|content|pdf|full text|journal|book|chapter)(?:\s+on\s+[^.!?]{2,40})?"
279
- r"|access via (?P<via>[^.!?]{2,120}?) is not available as they do not subscribe to [^.!?]{2,80}"
287
+ r"|access (?:to this (?:article|content|chapter|book|pdf|issue)\s+)?via\s*(?P<via>[^.!?]{2,120}?)\s*is not available"
288
+ r"(?:\s+as they do not subscribe to [^.!?]{2,80})?"
280
289
  r"|your (?:institution|organi[sz]ation) has not (?:subscribed to this content|purchased access to this article))\.?",
281
290
  re.I)
282
291
  _DENIAL_CONTEXT = re.compile(