papersearch 0.8.0 → 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 (101) hide show
  1. package/NOTICE +1 -1
  2. package/README.fr.md +5 -8
  3. package/README.ja.md +5 -8
  4. package/README.ko.md +5 -8
  5. package/README.md +148 -151
  6. package/README.zh-Hant.md +5 -8
  7. package/README.zh.md +265 -0
  8. package/dist/capabilities/download/batch/batch.d.ts +4 -0
  9. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  10. package/dist/capabilities/download/batch/batch.js +714 -198
  11. package/dist/capabilities/download/batch/batch.js.map +1 -1
  12. package/dist/capabilities/download/batch/windowPlan.d.ts +96 -0
  13. package/dist/capabilities/download/batch/windowPlan.d.ts.map +1 -0
  14. package/dist/capabilities/download/batch/windowPlan.js +196 -0
  15. package/dist/capabilities/download/batch/windowPlan.js.map +1 -0
  16. package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
  17. package/dist/capabilities/download/content/markdown/step.js +4 -1
  18. package/dist/capabilities/download/content/markdown/step.js.map +1 -1
  19. package/dist/capabilities/download/content/pdf/open/tiers/scihub.d.ts.map +1 -1
  20. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js +3 -1
  21. package/dist/capabilities/download/content/pdf/open/tiers/scihub.js.map +1 -1
  22. package/dist/infrastructure/http/hostGate.d.ts +24 -0
  23. package/dist/infrastructure/http/hostGate.d.ts.map +1 -0
  24. package/dist/infrastructure/http/hostGate.js +72 -0
  25. package/dist/infrastructure/http/hostGate.js.map +1 -0
  26. package/dist/infrastructure/pdf/PdfDownload.d.ts +1 -0
  27. package/dist/infrastructure/pdf/PdfDownload.d.ts.map +1 -1
  28. package/dist/infrastructure/pdf/PdfDownload.js +6 -1
  29. package/dist/infrastructure/pdf/PdfDownload.js.map +1 -1
  30. package/dist/infrastructure/runlog/RunLedger.d.ts +7 -0
  31. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  32. package/dist/infrastructure/runlog/RunLedger.js +17 -4
  33. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  34. package/dist/infrastructure/school/SchoolMcpClient.d.ts +12 -2
  35. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  36. package/dist/infrastructure/school/SchoolMcpClient.js +122 -11
  37. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  38. package/dist/infrastructure/school/SchoolReadiness.d.ts +7 -0
  39. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  40. package/dist/infrastructure/school/SchoolReadiness.js +8 -0
  41. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  42. package/dist/infrastructure/school/index.d.ts +1 -1
  43. package/dist/infrastructure/school/index.d.ts.map +1 -1
  44. package/dist/infrastructure/school/types.d.ts +31 -1
  45. package/dist/infrastructure/school/types.d.ts.map +1 -1
  46. package/dist/infrastructure/school/types.js.map +1 -1
  47. package/dist/infrastructure/security/SecurityUtils.d.ts.map +1 -1
  48. package/dist/infrastructure/security/SecurityUtils.js +6 -2
  49. package/dist/infrastructure/security/SecurityUtils.js.map +1 -1
  50. package/dist/management/failures/index.d.ts.map +1 -1
  51. package/dist/management/failures/index.js +5 -2
  52. package/dist/management/failures/index.js.map +1 -1
  53. package/dist/management/school/autoUpdate.d.ts.map +1 -1
  54. package/dist/management/school/autoUpdate.js +9 -1
  55. package/dist/management/school/autoUpdate.js.map +1 -1
  56. package/dist/management/school/cliProgress.d.ts.map +1 -1
  57. package/dist/management/school/cliProgress.js +3 -1
  58. package/dist/management/school/cliProgress.js.map +1 -1
  59. package/package.json +2 -2
  60. package/school/paper_search_school/adapters/base.py +3 -0
  61. package/school/paper_search_school/adapters/optica/__init__.py +50 -4
  62. package/school/paper_search_school/adapters/platforms/atypon/__init__.py +4 -3
  63. package/school/paper_search_school/adapters/platforms/figshare/__init__.py +23 -4
  64. package/school/paper_search_school/assets/capsule.html +380 -41
  65. package/school/paper_search_school/assets/capsule_en.json +72 -4
  66. package/school/paper_search_school/assets/capsule_fr.json +72 -4
  67. package/school/paper_search_school/assets/capsule_ja.json +72 -4
  68. package/school/paper_search_school/assets/capsule_ko.json +72 -4
  69. package/school/paper_search_school/assets/capsule_zh-Hant.json +66 -3
  70. package/school/paper_search_school/browser/backend.py +125 -4
  71. package/school/paper_search_school/browser/batch_session.py +188 -7
  72. package/school/paper_search_school/browser/challenge/continuation.py +19 -1
  73. package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +38 -10
  74. package/school/paper_search_school/browser/challenge/pro.py +24 -0
  75. package/school/paper_search_school/browser/challenge/services/solver.py +24 -4
  76. package/school/paper_search_school/browser/engine.py +4 -1
  77. package/school/paper_search_school/browser/user_turn.py +126 -0
  78. package/school/paper_search_school/browser/watchdog.py +213 -60
  79. package/school/paper_search_school/config.py +5 -0
  80. package/school/paper_search_school/engine/batch.py +9 -7
  81. package/school/paper_search_school/engine/batch_access.py +27 -7
  82. package/school/paper_search_school/engine/batch_capture.py +45 -13
  83. package/school/paper_search_school/engine/batch_institution.py +14 -0
  84. package/school/paper_search_school/engine/batch_login.py +177 -22
  85. package/school/paper_search_school/engine/batch_user.py +48 -3
  86. package/school/paper_search_school/engine/batch_waits.py +42 -2
  87. package/school/paper_search_school/engine/bridge.py +1 -2
  88. package/school/paper_search_school/engine/fulltext_page.py +10 -1
  89. package/school/paper_search_school/engine/supplements.py +7 -1
  90. package/school/paper_search_school/entitlements.py +28 -0
  91. package/school/paper_search_school/progress_capsule.py +33 -5
  92. package/school/paper_search_school/progress_reporter.py +189 -6
  93. package/school/paper_search_school/progress_view.py +142 -48
  94. package/school/paper_search_school/rate_limit.py +24 -1
  95. package/school/paper_search_school/school_login.py +170 -8
  96. package/school/paper_search_school/server.py +164 -19
  97. package/school/paper_search_school/user_settings.py +33 -4
  98. package/skills/paper-search/SKILL.md +1 -1
  99. package/skills/paper-search/references/browser-download.md +2 -2
  100. package/LICENSE-paper-search-mcp-nodejs +0 -24
  101. package/README.en.md +0 -268
@@ -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:
@@ -86,6 +86,11 @@ DEFAULT_CONFIG: dict[str, Any] = {
86
86
  "publisher_hourly_limit_now": False,
87
87
  # 失败后自动重试:原因不明的批量最后再试一次,被网站拦截的 10 分钟后再试一次;默认关(用户 2026-11-24)。
88
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,
89
94
  # 验证码识别服务(用户 2026-11-25 定):见 browser/challenge/services/solver.py。
90
95
  # 没权限时换下一所学校 (school_switch.py; user, 2026-11-21): on unless turned off.
91
96
  "school_switch": True,
@@ -224,12 +224,13 @@ class PublisherBatchDownloader(
224
224
  own_page = [final_url] if final_url and self.adapter.is_article_page_url(final_url) else []
225
225
  candidates = self.adapter.supplements_page_urls(doi) or [self._article_url(doi)]
226
226
  incomplete = ""
227
- listed = list(getattr(result, "_listed_supplements", None) or [])
228
- if listed:
229
- # Read on the article page before its PDF: no second load.
230
- links = listed
227
+ listed = getattr(result, "_listed_supplements", None)
228
+ if listed is not None:
229
+ # Read on the article page before its PDF: no second load (none when it
230
+ # listed none: Optica's articles without any, 8 to 27 s each, 2026-11-26).
231
+ links = list(listed)
231
232
  self._event(result, "supplements_listed_on_article", str(len(links)))
232
- for url in ([] if listed else dict.fromkeys(own_page + candidates)):
233
+ for url in ([] if listed is not None else dict.fromkeys(own_page + candidates)):
233
234
  open_page(page, url, timeout_ms=60_000)
234
235
  if self._challenge_shell(page) or self._is_challenge_page(page):
235
236
  if not self._wait_for_challenge(page, result):
@@ -267,8 +268,9 @@ class PublisherBatchDownloader(
267
268
  return [{"status": "failed", "reason": incomplete, "url": "", "label": ""}]
268
269
  self._event(result, "supplements_found", str(len(links)))
269
270
  progress_reporter.update(supplements_total=len(links))
270
- if self.config.get("fulltext"):
271
- # --fulltext on a visit for the attachments alone: the article page it opened.
271
+ if self.config.get("fulltext") and listed is None:
272
+ # --fulltext on a visit for the attachments alone: the article page it opened (none
273
+ # was when the files were read before the PDF: a blank tab is no page to read).
272
274
  self._remember_fulltext_page(page, doi, result)
273
275
  files = []
274
276
  if links:
@@ -35,7 +35,15 @@ from .batch_common import (
35
35
  # each paper written 待适配.
36
36
  _IP_BLOCKED = re.compile(r"\byour ip(?: address)?(?: [0-9a-f.:]+)? (?:has been|is) blocked\b"
37
37
  r"|\bthe ip address (?:of )?[0-9a-f.:]+ has not been recogni[sz]ed to access\b"
38
- r"|访问请求可能对网站造成安全威胁")
38
+ r"|访问请求可能对网站造成安全威胁"
39
+ # A throttle, any site's words for it (Optica, 2026-11-26: "This IP address is subject to a
40
+ # downloading timeout based on heavy usage. Please try again in a few minutes."): by the address,
41
+ r"|\b(?:this|your) ip(?: address)?(?: [0-9a-f.:]+)? (?:has been |is |was )?(?:temporarily )?"
42
+ r"(?:subject to|limited|throttled|rate[- ]limited|restricted|suspended|banned)\b"
43
+ # or by the use, with the time to come back,
44
+ r"|\b(?:heavy|excessive|unusually high|unusual)\s+(?:usage|use|downloading|downloads|requests|traffic"
45
+ r"|activity)\b[^.!?]{0,100}[.!?]?\s*(?:please\s+)?(?:try again|come back|retry)\s+(?:later|in\b|after\b)"
46
+ r"|(?:访问|请求|下载)(?:过于|太|过度)频繁", re.I)
39
47
  _GATEWAY_ERROR_MARKERS = (
40
48
  "upstream connect error or disconnect/reset before headers",
41
49
  "502 bad gateway", "503 service unavailable", "503 service temporarily unavailable",
@@ -175,12 +183,24 @@ class AccessMixin:
175
183
  and "you are unable to access" in text)
176
184
 
177
185
  @staticmethod
178
- def _ip_blocked_text(text: str) -> bool:
179
- """The publisher's own page for a blocked address, under its usual title (Science,
180
- 2026-11-16: "Your IP 69.63.193.18 has been blocked."): no login can open it. Read
181
- from the article page's text the access check reads anyway (``_access_snapshot``)."""
182
- # Its start, and its end: Taylor & Francis writes it after the site's whole header.
183
- return bool(_IP_BLOCKED.search(" ".join((text[:4000] + "\n" + text[-2000:]).lower().split())))
186
+ def _ip_blocked_words(text: str) -> str:
187
+ """The publisher's own words that it blocks or throttles this address, under its usual
188
+ title (Science, 2026-11-16: "Your IP 69.63.193.18 has been blocked."; Optica, 2026-11-26:
189
+ "This IP address is subject to a downloading timeout based on heavy usage. Please try
190
+ again in a few minutes."): no login opens it, and the site's other addresses answer the
191
+ same; "" for any other page. Read from the page's text: the article page's, which the
192
+ access check reads anyway (``_access_snapshot``), and the page a PDF attempt ended on."""
193
+ # Its start, and its end: Taylor & Francis writes it after the site's whole header, Optica before its footer.
194
+ window = " ".join((str(text or "")[:4000] + "\n" + str(text or "")[-2000:]).split())
195
+ found = _IP_BLOCKED.search(window)
196
+ if found:
197
+ return window[max(0, found.start() - 60):found.end() + 80]
198
+ # A bare 429 page ("Too Many Requests"), not an article that names the status.
199
+ return window[:200] if len(window) <= 1500 and "too many requests" in window.lower() else ""
200
+
201
+ @classmethod
202
+ def _ip_blocked_text(cls, text: str) -> bool:
203
+ return bool(cls._ip_blocked_words(text))
184
204
 
185
205
  def _raise_on_publisher_access_blocked(self, page: Any) -> None:
186
206
  if self._publisher_access_blocked(page):
@@ -61,8 +61,12 @@ _SAME_TAB_JS = """el => { const a = el.closest('a[target]');
61
61
  # A PDF over this, or one whose size is not given, is read in pieces, the PDF step's time going on
62
62
  # while they arrive: IEEE's getPDF.jsp sent a 31.8 MB PDF and a 37 MB one without a size, read in one
63
63
  # call in 46 and 57 s of the step's 60 (2026-11-18; 32 MB before).
64
- STREAM_PDF_BYTES = 8 * 1024 * 1024
65
- STREAM_PIECE_BYTES = 4 * 1024 * 1024
64
+ # Over 2 MB since 2026-11-26 (8 before), in pieces of 256 KB (4 MB before): Optica's 4 MB pieces came in 41 and 44 s
65
+ # at about 100 KB/s and the third went past STREAM_STALL_SEC (two reviews of tens of MB lost after five minutes); a
66
+ # small piece comes back every few seconds on a slow line, so only a real stop ends the read, and the window shows
67
+ # the file's size and how far it has come (progress_reporter.Transfer).
68
+ STREAM_PDF_BYTES = 2 * 1024 * 1024
69
+ STREAM_PIECE_BYTES = 256 * 1024
66
70
  # How long a piece may take before the read counts as stalled.
67
71
  STREAM_STALL_SEC = 45
68
72
 
@@ -503,21 +507,24 @@ class CaptureMixin:
503
507
  except Exception:
504
508
  pass
505
509
 
506
- # Figshare links: their files are found by its own API in the attachment step.
507
- _FIGSHARE_LINKED_JS = "() => !!document.querySelector('a[href*=\"figshare.com\"]')"
508
-
509
510
  def _remember_listed_supplements(self, page: Any, doi: str, result: DownloadResult) -> None:
510
511
  """The files the article page lists, read before the PDF takes its tab: the
511
512
  attachment step then need not load the page again (AHA's page took more
512
513
  than that step's 60 s once, 2026-11-08). Only from an adapter that reads
513
- them without leaving the page, and not beside Figshare links."""
514
+ them without leaving the page (its ``listed_supplement_links``: the files, [] when
515
+ the page lists none, None when it cannot say), and not beside Figshare
516
+ resources, whose files Figshare's API gives in the attachment step (Optica's are
517
+ linked as doi.org/10.6084/m9.figshare.<id>, 2026-11-26)."""
514
518
  read = getattr(self.adapter, "listed_supplement_links", None)
515
- if read is None or getattr(result, "_listed_supplements", None):
519
+ if read is None or getattr(result, "_listed_supplements", None) is not None:
516
520
  return
517
521
  try:
518
522
  links = read(page, doi)
519
- if links and not page.evaluate(self._FIGSHARE_LINKED_JS):
520
- result._listed_supplements = list(links)
523
+ if links is not None:
524
+ from ..adapters.platforms.figshare import resources_linked
525
+
526
+ if not resources_linked(page):
527
+ result._listed_supplements = list(links)
521
528
  except Exception as exc:
522
529
  if not _is_browser_error(exc):
523
530
  raise
@@ -722,15 +729,16 @@ class CaptureMixin:
722
729
  self._remember_fulltext_page(page, doi, result, target=str(result.final_url or self._article_url(doi)))
723
730
 
724
731
  def _read_paused_pdf(self, cdp_session: Any, request_id: str, result: DownloadResult,
725
- captured: dict[str, Any]) -> bytes:
732
+ captured: dict[str, Any], size: int = 0) -> bytes:
726
733
  """A large paused PDF response, read in pieces: while they arrive, the PDF step's time
727
- goes on (``watchdog.extend_operation``); a piece that takes STREAM_STALL_SEC ends it."""
734
+ goes on (``watchdog.extend_operation``); a piece that takes STREAM_STALL_SEC ends it.
735
+ ``size``: its stated length, shown with what has come on the window's card."""
728
736
  captured["receiving"] = True
729
737
  handle = ""
730
738
  pieces: list[bytes] = []
731
739
  started = time.monotonic()
732
740
  try:
733
- with transfer(result):
741
+ with transfer(result), progress_reporter.Transfer("pdf", size) as arriving:
734
742
  handle = cdp_session.send("Fetch.takeResponseBodyAsStream", {"requestId": request_id})["stream"]
735
743
  while True:
736
744
  watchdog.extend_operation(STREAM_STALL_SEC)
@@ -739,6 +747,7 @@ class CaptureMixin:
739
747
  if data:
740
748
  # CDP's plain stream chunks are UTF-8 text, not Latin-1 bytes.
741
749
  pieces.append(base64.b64decode(data) if piece.get("base64Encoded") else data.encode("utf-8"))
750
+ arriving.add(len(pieces[-1]))
742
751
  if piece.get("eof"):
743
752
  break
744
753
  body = b"".join(pieces)
@@ -913,7 +922,7 @@ class CaptureMixin:
913
922
  size = _content_length(headers)
914
923
  if not size or size > STREAM_PDF_BYTES:
915
924
  try:
916
- body = self._read_paused_pdf(cdp_session, request_id, result, captured)
925
+ body = self._read_paused_pdf(cdp_session, request_id, result, captured, size)
917
926
  finally:
918
927
  # Its body taken, the request cannot go on as it was: answered empty,
919
928
  # the tab stays on the article page (as for an attachment below).
@@ -1456,6 +1465,8 @@ class CaptureMixin:
1456
1465
  self._note_download_limit(page, result)
1457
1466
  if outcome != "pdf ok" and not any(s["why"] == "pdf attempt failed" for s in result.snapshots):
1458
1467
  self._snapshot(page, result, "pdf attempt failed")
1468
+ if outcome != "pdf ok":
1469
+ self._note_blocked_page(page, result, captured)
1459
1470
  except Exception as exc: # the record never ends the capture
1460
1471
  self._event(result, "pdf_attempt_record_error", f"{type(exc).__name__}: {str(exc)[:160]}")
1461
1472
 
@@ -1469,6 +1480,27 @@ class CaptureMixin:
1469
1480
  r"download limit|(?:exceeded|reached)\b.{0,60}\bdownloads?\b|too many (?:pdf )?downloads"
1470
1481
  r"|下载.{0,8}(?:达到|超过|超出).{0,4}(?:上限|限额|限制)", re.I | re.S)
1471
1482
 
1483
+ def _note_blocked_page(self, page: Any, result: DownloadResult, captured: dict[str, Any]) -> None:
1484
+ """A PDF attempt that ended on the site's own page blocking or throttling this address
1485
+ (``_ip_blocked_words``; Optica, 2026-11-26: twelve articles in a row each tried the
1486
+ page's other PDF addresses, all answering the same, until the step's minute ran out, and
1487
+ ended as 页面或浏览器卡住): the step ends as blocked, its other addresses not asked for,
1488
+ and the batch waits on the site (three in a row) instead of going on into it."""
1489
+ if captured.get("bytes") or captured.get("block_reason"):
1490
+ return
1491
+ from ..browser import watchdog
1492
+ try:
1493
+ words = self._ip_blocked_words(self._body_text(page, 20_000))
1494
+ except Exception as exc:
1495
+ if exc is watchdog.interrupted:
1496
+ raise # the window's skip or stop
1497
+ return # a look for the record: the attempt is recorded either way
1498
+ if not words:
1499
+ return
1500
+ captured["block_reason"] = "ip_blocked"
1501
+ host = urlparse(str(getattr(page, "url", "") or "")).hostname or ""
1502
+ self._event(result, "ip_blocked_page", f'{host}: "{words[:200]}"')
1503
+
1472
1504
  def _note_download_limit(self, page: Any, result: DownloadResult) -> None:
1473
1505
  """A PDF attempt that got no PDF, with a dialog over the page saying the downloads
1474
1506
  are used up (ScienceDirect's "You have reached the daily bulk download limit" after
@@ -1680,6 +1680,9 @@ class InstitutionMixin:
1680
1680
  school's OpenAthens sign-in went on to its university system's login host,
1681
1681
  where the school's name was typed into a field)."""
1682
1682
  self._school_side_hosts: set[str] = set()
1683
+ # Shared login services (Microsoft, Google, Okta) the school's own login server sent this item to: its
1684
+ # login page there too (school_login.note_shared_login; user, 2026-11-28).
1685
+ self._shared_from_school: set[str] = set()
1683
1686
  self._route_hosts: set[str] = set()
1684
1687
  self._publisher_hosts: set[str] = set()
1685
1688
  self._route_away = False
@@ -1707,11 +1710,22 @@ class InstitutionMixin:
1707
1710
  page.remove_listener("request", requested)
1708
1711
  page.remove_listener("requestfailed", failed)
1709
1712
  self._school_side_hosts = set()
1713
+ self._shared_from_school = set() # this item's only: never another school's, or another paper's
1710
1714
  self._school_unreachable = ""
1711
1715
 
1712
1716
  return stop
1713
1717
 
1714
1718
  def _note_route_hop(self, url: str, result: DownloadResult) -> None:
1719
+ from .. import school_login
1720
+
1721
+ if school_login.shared_login_host(url) and getattr(self, "_route_last_host", ""):
1722
+ pro = school_login.module()
1723
+ entity = str(self.config.get("idp_entity_id") or "").strip()
1724
+ also = school_login.pro_login_hosts(pro, entity) if pro is not None else ()
1725
+ before = set(self._shared_from_school)
1726
+ school_login.note_shared_login(self._route_last_host, url, self.config, also, self._shared_from_school)
1727
+ for host in self._shared_from_school - before:
1728
+ self._event(result, "school_shared_login", f"{host} after {self._route_last_host}")
1715
1729
  kind = self._route_hop(url)
1716
1730
  if not kind:
1717
1731
  return