papersearch 0.5.13 → 0.5.14

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.
@@ -190,7 +190,7 @@
190
190
  "机构下载": "School download",
191
191
  "学校登录页最多等": "Wait for school login",
192
192
  "其他页面最多等": "Wait for other pages",
193
- "验证提醒前最多等": "Wait before check alert",
193
+ "提醒你操作前最多等": "Wait before asking you",
194
194
  "每家出版社每小时最多": "Per publisher per hour",
195
195
  "秒": "s",
196
196
  "篇": "papers",
@@ -5,6 +5,7 @@ engine owns waiting and decides whether verification has actually ended.
5
5
  """
6
6
  from __future__ import annotations
7
7
 
8
+ import re
8
9
  import time
9
10
  from collections.abc import Callable
10
11
  from typing import Any, Literal
@@ -100,12 +101,93 @@ def is_image_verification(page: Any) -> bool:
100
101
 
101
102
 
102
103
  def needs_manual_verification(page: Any) -> bool:
103
- """A puzzle or reCAPTCHA on an already recognised verification page.
104
+ """A puzzle, reCAPTCHA or another provider's widget on an already recognised
105
+ verification page.
104
106
 
105
107
  Reading a checked box or a response token cannot prove that the enclosing
106
- page's confirmation was submitted. Leave both actions to the user.
108
+ page's confirmation was submitted. Leave these actions to the user.
107
109
  """
108
- return is_image_verification(page) or has_visible_recaptcha(page)
110
+ return (is_image_verification(page) or has_visible_recaptcha(page)
111
+ or bool(verification_widget(page, manual_only=True)))
112
+
113
+
114
+ # Verification widgets the program never operates (the user, 2026-11-11): a page
115
+ # showing one is a verification for the user. Frames by their address, read without
116
+ # a browser call; elements by the providers' fixed names; AWS WAF, whose puzzle has
117
+ # no fixed element, by its script. Turnstile is Cloudflare's own check, whose box the
118
+ # program clicks (``click_checkbox``). Not a verification page: an article (citation
119
+ # metadata), whose comment or newsletter form may carry a widget, and a long page,
120
+ # where a widget is one form among others (a publisher's personal sign-in).
121
+ _WIDGET_FRAMES: tuple[tuple[str, Callable[[str], bool]], ...] = (
122
+ ("reCAPTCHA", re.compile(r"^https://(?:www\.)?(?:google\.com|recaptcha\.net)/recaptcha/"
123
+ r"(?:api2|enterprise)/(?:anchor|bframe)").search),
124
+ ("hCaptcha", re.compile(r"^https://(?:[a-z0-9-]+\.)*hcaptcha\.com/captcha/").search),
125
+ ("DataDome", re.compile(r"^https://(?:[a-z0-9-]+\.)*captcha-delivery\.com/").search),
126
+ ("Arkose", re.compile(r"^https://(?:[a-z0-9-]+\.)*(?:arkoselabs\.com|funcaptcha\.com)/").search),
127
+ ("Tencent", re.compile(r"^https://(?:turing\.captcha\.qcloud\.com|t\.captcha\.qq\.com|"
128
+ r"ssl\.captcha\.qq\.com)/").search),
129
+ ("Turnstile", lambda url: is_turnstile_frame(url)),
130
+ )
131
+ _WIDGET_ELEMENTS = (
132
+ ("GeeTest", ".geetest_holder, .geetest_panel, .geetest_box, .geetest_captcha"),
133
+ ("Aliyun", "[id^='aliyunCaptcha-'], #nc_1_wrapper"),
134
+ ("Tencent", "#tcaptcha_iframe, #tcaptcha_transform"),
135
+ ("PerimeterX", "#px-captcha"),
136
+ )
137
+ # Longer than this, the page is more than a verification interstitial.
138
+ _WIDGET_PAGE_TEXT = 2500
139
+ _WIDGET_PAGE_JS = r"""([groups, longest]) => {
140
+ if (document.querySelector('meta[name="citation_doi"], meta[name="citation_title"]')) return '#page';
141
+ if ((document.body?.innerText || '').trim().length > longest) return '#page';
142
+ const shown = el => { const r = el.getBoundingClientRect(), s = getComputedStyle(el);
143
+ return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; };
144
+ for (const [name, selector] of groups)
145
+ if ([...document.querySelectorAll(selector)].some(shown)) return name;
146
+ if ([...document.scripts].some(s => /^https:\/\/[^/]*\.captcha\.awswaf\.com\//.test(s.src || ''))) return 'AWS WAF';
147
+ return '';
148
+ }"""
149
+
150
+
151
+ def verification_widget(page: Any, *, manual_only: bool = False) -> str:
152
+ """The provider of a visible verification widget making up ``page``, or "".
153
+ ``manual_only``: leave out Turnstile, which the program may click itself."""
154
+ from .driver import Error
155
+ from .watchdog import CallAbandoned, call_limit
156
+
157
+ try:
158
+ with call_limit(READ_LIMIT_SEC):
159
+ found = page.evaluate(_WIDGET_PAGE_JS, [[list(group) for group in _WIDGET_ELEMENTS], _WIDGET_PAGE_TEXT])
160
+ except CallAbandoned:
161
+ return ""
162
+ except Error as exc:
163
+ if any(text in str(exc).lower() for text in _NAVIGATED):
164
+ return "" # the page went on: the next check reads the new one
165
+ raise
166
+ found = found if isinstance(found, str) else ""
167
+ if found == "#page":
168
+ return ""
169
+ if found:
170
+ return found
171
+ frames = getattr(page, "frames", ())
172
+ frames = frames if isinstance(frames, (list, tuple)) else ()
173
+ for name, matches in _WIDGET_FRAMES:
174
+ if manual_only and name == "Turnstile":
175
+ continue
176
+ for frame in frames:
177
+ url = str(getattr(frame, "url", "") or "")
178
+ # reCAPTCHA v3's badge is a frame too, on ordinary pages.
179
+ if not matches(url) or "size=invisible" in url:
180
+ continue
181
+ try:
182
+ with call_limit(READ_LIMIT_SEC):
183
+ if frame.frame_element().is_visible() is True:
184
+ return name
185
+ except CallAbandoned:
186
+ continue
187
+ except Error as exc:
188
+ if not any(text in str(exc).lower() for text in _NAVIGATED):
189
+ raise
190
+ return ""
109
191
 
110
192
 
111
193
  def has_visible_recaptcha(page: Any) -> bool:
@@ -37,7 +37,7 @@ pdf_captured saved_pending_verification route_failed access_ready
37
37
  """.split())
38
38
  _EVENTS = frozenset("""
39
39
  aps_institution_entry_missing article_access_ready article_open browser_closed login_only_done
40
- carsi_school_list_unconfirmed
40
+ carsi_school_list_unconfirmed unknown_page_attention unknown_page_check_error
41
41
  auth_wall_after_article_load auth_wall_after_pdf_attempt browser_capture_detach_error
42
42
  browser_capture_disable_error browser_pdf_response_captured browser_pdf_response_error
43
43
  browser_response_continue_error browser_response_discard_error challenge_manual_wait
@@ -106,11 +106,68 @@ class UserRequestsMixin:
106
106
  activity = getattr(result, "_page_activity", None)
107
107
  owned = activity is None or activity.closed
108
108
  if owned:
109
+ from ..browser import watchdog
110
+
109
111
  result._page_activity = activity = PageActivity(result.doi, self.config)
112
+ watched = activity
113
+ watched.on_idle = lambda: watchdog.run_soon(lambda: self._remind_on_unknown_page(watched, result))
110
114
  if page is not None:
111
115
  activity.observe(page)
112
116
  return activity, owned
113
117
 
118
+ UNKNOWN_PAGE_NOTICE = "页面可能需要你处理,请查看浏览器窗口"
119
+ # Something to click on a short page that is not an article or a PDF: a prompt the
120
+ # program does not know (an unrecognised verification). The longest such page.
121
+ _UNKNOWN_PAGE_TEXT = 2000
122
+ _UNKNOWN_PAGE_CONTROL_JS = r"""(longest) => {
123
+ if (document.contentType === 'application/pdf'
124
+ || document.querySelector('meta[name="citation_doi"], meta[name="citation_title"]')) return '';
125
+ if ((document.body?.innerText || '').trim().length > longest) return '';
126
+ const shown = el => { const r = el.getBoundingClientRect(), s = getComputedStyle(el);
127
+ return r.width >= 12 && r.height >= 12 && s.visibility !== 'hidden' && s.display !== 'none'; };
128
+ const control = [...document.querySelectorAll(
129
+ 'input[type=checkbox], [role=checkbox], iframe, canvas, button, [role=button], input[type=submit]')]
130
+ .find(el => shown(el) && (el.tagName !== 'IFRAME' || el.getBoundingClientRect().height >= 30));
131
+ if (!control) return '';
132
+ const kind = control.getAttribute('role') || control.tagName.toLowerCase();
133
+ const label = (control.innerText || control.value || control.getAttribute('aria-label') || control.title || '').trim();
134
+ return (kind + (label ? ' "' + label.slice(0, 40) + '"' : '')).slice(0, 80);
135
+ }"""
136
+
137
+ def _remind_on_unknown_page(self, activity: PageActivity, result: DownloadResult) -> None:
138
+ """On the browser thread, after ``browser_stall_notify_after`` seconds without
139
+ progress: a page the program does not know, short and with something to click,
140
+ asks the user to look (an unrecognised verification; the user, 2026-11-11).
141
+ Recognised verification and the school's login remind the user themselves; an
142
+ article, a PDF or a long page asks nothing, and the program's own steps count as
143
+ progress (2026-11-06). A reminder is optional: a failed look never ends the article."""
144
+ from ..browser import watchdog
145
+
146
+ if activity.closed or not activity.stalled():
147
+ return
148
+ page = activity.page
149
+ if page is None or progress_reporter.has_attention(current=result.doi, excluding=activity.key):
150
+ return
151
+ try:
152
+ if page.is_closed() or self._is_challenge_page(page) or self._users_login_step(page):
153
+ return
154
+ url = str(getattr(page, "url", "") or "")
155
+ with watchdog.call_limit(5):
156
+ control = page.evaluate(self._UNKNOWN_PAGE_CONTROL_JS, self._UNKNOWN_PAGE_TEXT)
157
+ except watchdog.CallAbandoned:
158
+ return
159
+ except (watchdog.BrowserUnresponsive, UserMarkedNoEntitlement):
160
+ raise
161
+ except Exception as exc:
162
+ if exc is watchdog.interrupted:
163
+ raise # the window's skip or stop: it ends the article, not this look
164
+ first = str(exc).splitlines()[0][:160] if str(exc) else ""
165
+ self._event(result, "unknown_page_check_error", f"{type(exc).__name__}: {first}")
166
+ return
167
+ if isinstance(control, str) and control:
168
+ self._event(result, "unknown_page_attention", f"{control} @ {url[:160]}")
169
+ activity.remind(self.UNKNOWN_PAGE_NOTICE)
170
+
114
171
  def _show_download_browser(self, page: Any, result: DownloadResult) -> None:
115
172
  """Focus the existing task page only after the user requests it."""
116
173
  from ..browser import watchdog
@@ -425,6 +425,10 @@ class UserWaitMixin:
425
425
  if activity is not None:
426
426
  activity.automatic_for(automatic_end - now)
427
427
  if challenge_interaction.needs_manual_verification(page):
428
+ widget = challenge_interaction.verification_widget(page, manual_only=True)
429
+ if widget and not attempt.get("widget"):
430
+ attempt["widget"] = widget # whose widget the user is asked to complete
431
+ self._event(result, "challenge_observation", f"manual widget: {widget}")
428
432
  return False
429
433
  if ((attempt["attempts"] >= 3 and now >= attempt["retry_at"])
430
434
  or (attempt.get("unavailable") and now >= attempt["handoff_at"])):
@@ -607,4 +611,12 @@ class UserWaitMixin:
607
611
  title = self._title(page)
608
612
  return (challenges.has_challenge_text(title, self._body_text(page, 1_200))
609
613
  or (challenges.continues_manual_challenge(title)
610
- and challenge_interaction.is_image_verification(page)))
614
+ and challenge_interaction.is_image_verification(page))
615
+ or self._verification_widget_page(page))
616
+
617
+ def _verification_widget_page(self, page: Any) -> bool:
618
+ """Another provider's verification widget makes up the page (reCAPTCHA, hCaptcha,
619
+ sliders; ``challenge_interaction.verification_widget``). Not on the school's own
620
+ sign-in, where a captcha is part of the login the user does."""
621
+ host = (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower()
622
+ return not self._is_idp_host(host) and bool(challenge_interaction.verification_widget(page))
@@ -1,5 +1,9 @@
1
1
  """Track idle owned pages without treating missing progress as a user action.
2
2
 
3
+ A quiet interval is handed to the downloader (``on_idle``): it looks at the page on
4
+ the browser thread and reminds the user (``remind``) only for a page it does not know
5
+ with something to click on it (the user, 2026-11-11). Silence alone asks nothing.
6
+
3
7
  Main-document requests, navigation, a loaded document, a workflow step or
4
8
  received file bytes refresh the timer. An in-flight navigation gets only the
5
9
  existing page wait budget; polling and unrelated background traffic do not.
@@ -28,6 +32,11 @@ class PageActivity:
28
32
  self._lock = threading.RLock()
29
33
  self._doi = doi
30
34
  self._reported = False
35
+ self.key = f"page-unknown:{id(self)}:{doi}"
36
+ self._shown = False
37
+ # Called with the lock held once a quiet interval has passed, from any thread
38
+ # and without a browser call: it may only schedule work (``watchdog.run_soon``).
39
+ self.on_idle: Any = None
31
40
  self._transfers = 0
32
41
  self._automatic_until = 0.0
33
42
  self.closed = False
@@ -46,6 +55,9 @@ class PageActivity:
46
55
 
47
56
  def _clear(self) -> None:
48
57
  self._reported = False
58
+ if self._shown:
59
+ progress_reporter.clear_attention(self.key)
60
+ self._shown = False
49
61
 
50
62
  def automatic_for(self, seconds: float) -> None:
51
63
  """Defer idle diagnostics until the caller's existing automatic deadline.
@@ -64,7 +76,7 @@ class PageActivity:
64
76
  with self._lock:
65
77
  if self.closed:
66
78
  return
67
- if progress_reporter.has_attention(current=self._doi):
79
+ if progress_reporter.has_attention(current=self._doi, excluding=self.key):
68
80
  # School login and other explicit requests have priority. Start
69
81
  # a fresh quiet interval when they finish rather than duplicating them.
70
82
  self._last_progress = self._clock()
@@ -79,6 +91,23 @@ class PageActivity:
79
91
  logging.getLogger(__name__).info("page_idle: no observed progress for %.0f seconds",
80
92
  self._clock() - self._last_progress)
81
93
  self._reported = True
94
+ if self.on_idle is not None:
95
+ self.on_idle()
96
+
97
+ def stalled(self) -> bool:
98
+ """Still quiet for the whole interval: the downloader checks again before reminding."""
99
+ with self._lock:
100
+ return (not self.closed and not self._transfers and self._clock() >= self._automatic_until
101
+ and not self._navigation_loading() and self._clock() - self._last_progress >= self.after)
102
+
103
+ def remind(self, message: str) -> None:
104
+ """Ask the user to look at the page; the downloader calls it after inspecting the
105
+ page. Progress, another reminder for this paper or the article's end clears it."""
106
+ with self._lock:
107
+ if self.closed or self._shown:
108
+ return
109
+ progress_reporter.set_attention(self.key, message, current=self._doi, phase="需要你操作")
110
+ self._shown = True
82
111
 
83
112
  def _navigation_loading(self) -> bool:
84
113
  pending = self._navigations.get(id(self.page))
@@ -23,7 +23,7 @@ class Field:
23
23
  FIELDS = (
24
24
  Field("login", "学校登录页最多等", "browser_login_timeout", 180, 30, 1800, "秒", "wait"),
25
25
  Field("page", "其他页面最多等", "browser_page_wait_timeout", 60, 10, 600, "秒", "wait"),
26
- Field("stalled", "验证提醒前最多等", "browser_stall_notify_after", 30, 1, 600, "秒", "wait"),
26
+ Field("stalled", "提醒你操作前最多等", "browser_stall_notify_after", 30, 1, 600, "秒", "wait"),
27
27
  Field("hourly", "每家出版社每小时最多", "publisher_hourly_limit", 100, 0, 1000, "篇", "download"),
28
28
  )
29
29
 
@@ -18,7 +18,7 @@ export const CARSI_DOWNLOAD_TIMEOUT_MS = 1_200_000;
18
18
  export const CARSI_CLEANUP_TIMEOUT_MS = 5_000;
19
19
  const CARSI_BACKEND_SOURCE = "carsi";
20
20
  // MCP clientInfo is informational only; keep in step with package.json on release.
21
- const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.5.13";
21
+ const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.5.14";
22
22
  const NO_BATCH_SUPPORT = {
23
23
  downloadFields: false,
24
24
  supplementsField: false,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "papersearch",
3
- "version": "0.5.13",
3
+ "version": "0.5.14",
4
4
  "description": "PaperSearch: an agent-friendly command for searching and downloading academic papers from multiple sources.",
5
5
  "main": "dist/cli.js",
6
6
  "type": "module",
@@ -4,7 +4,7 @@ description: |
4
4
  用本机 paper-search 命令做文献工作:检索论文、核对 DOI/PMID、搜正文片段(找方法和结果的原文)、查期刊影响因子与分区、查施引和参考文献、下载全文和补充材料。
5
5
  用户要找文献、查期刊、下载论文,或说“请开始配置”时使用;英文请求(literature search、journal metrics、paper download、start setup)同样适用。
6
6
  metadata:
7
- version: "0.5.13"
7
+ version: "0.5.14"
8
8
  ---
9
9
 
10
10
  # 文献检索与下载(paper-search)
@@ -20,9 +20,9 @@
20
20
  - 机构下载一次一篇,开放渠道同时查后面的篇目。遇到学校登录或验证时停在这一篇;出现人工处理提示后,提醒用户到下载浏览器操作。等待时限:停在学校登录页(以及没配置学校、要用户自己选学校的页面)最多 3 分钟(后端配置 `browser_login_timeout`,秒);停在其他页面(人机验证、出版社页面、选机构页、取 PDF 时等待处理)连续超过 1 分钟就结束这一篇(`browser_page_wait_timeout`)。两项都能在进度窗口右上角的设置(齿轮)里改,从下一篇起生效。学校统一认证登录一次后,其余篇目通常自动通过。一篇等满时限后(日志写“这一篇等你登录或验证已到时限”),后面每篇只等 60 秒;用户在登录框输入时照常等。
21
21
  - 每个出版社每小时最多打开 100 篇(后端配置 `publisher_hourly_limit`,0 为不限)。到上限时批量等到可以继续再下这一篇(日志写明时间);单篇返回 `rate_limited`,稍后再试。
22
22
  - 出版社网站拦截了当前网络(`access_blocked`,如 Cloudflare 拦截页)时这一篇结束;同一期刊 30 分钟内的其他文章直接跳过(`journal_blocked_earlier`),其他期刊照常继续。告诉用户可能是当前网络被网站防护拦截,也可能是下载过多被暂停:可换网络或稍后再试,后者请联系学校图书馆。
23
- - 后端会先短暂等待自动验证,每次验证等待对可识别的 Turnstile 复选框最多尝试点击 3 次,两次至少间隔 3 秒;程序提示人工处理时,再提醒用户到下载浏览器接管,不因 `checking_access` 就要求用户操作。学校登录、二次验证和复杂验证码由用户完成;学校认证页的信息发送同意和使用条款、出版社登录途中的条款确认页由后端代点同意(每篇各最多两次,仍停在那一页时才提醒用户)。不索取账号、密码或验证码,agent 不另开浏览器代操作。
23
+ - 后端会先短暂等待自动验证,每次验证等待对可识别的 Turnstile 复选框最多尝试点击 3 次,两次至少间隔 3 秒;程序提示人工处理时,再提醒用户到下载浏览器接管,不因 `checking_access` 就要求用户操作。学校登录、二次验证和复杂验证码由用户完成(reCAPTCHA、hCaptcha、滑块等验证页,程序认出后直接交给用户);学校认证页的信息发送同意和使用条款、出版社登录途中的条款确认页由后端代点同意(每篇各最多两次,仍停在那一页时才提醒用户)。不索取账号、密码或验证码,agent 不另开浏览器代操作。
24
24
  - 在专用人工登录页输入、选择或点击控件,或点击胶囊接管登录后,暂停剩余学校登录预算;输入间停顿不算离开,离开该人工步骤后恢复计时。无人操作仍按原限时结束。不要询问用户的账号密码。用户在登录页中途停下(比如去拿手机验证码)时继续等,按原来的时限算,不重新发起登录。
25
- - 学校登录提醒依赖当前可见的账号、密码、二次验证码、二维码,或后端没能代点的同意步骤;学校域名和空闲时间不作为人工操作证据。胶囊“验证提醒前最多等”仍保存到 `browser_stall_notify_after`(默认 30 秒,1–600);可见验证控件无法自动操作时,按该值与剩余预算一半的较早者交接。控件仍在加载、已勾选处理中或尚未出现时继续自动观察。未派发点击不消耗最多 3 次输入额度;失败原因见 `challenge_observation`。明确网站封禁和预算耗尽仍结束当前路径,不保证所有验证码自动通过。
25
+ - 学校登录提醒依赖当前可见的账号、密码、二次验证码、二维码,或后端没能代点的同意步骤;学校域名和空闲时间不作为人工操作证据。胶囊“提醒你操作前最多等”仍保存到 `browser_stall_notify_after`(默认 30 秒,1–600);可见验证控件无法自动操作时,按该值与剩余预算一半的较早者交接。控件仍在加载、已勾选处理中或尚未出现时继续自动观察。未派发点击不消耗最多 3 次输入额度;失败原因见 `challenge_observation`。明确网站封禁和预算耗尽仍结束当前路径,不保证所有验证码自动通过。程序认不出的页面停住达到这个时长、页面上又有可点的控件时,也会提醒“页面可能需要你处理”,同样请用户到下载浏览器看一眼。
26
26
  - 通用 Human Verification 图片验证页会等待 Begin 之后的后续步骤。用户在专用验证页操作或通过胶囊接管后,人工阶段暂停剩余验证及文章等待预算;成功离开验证后继续自动流程。未操作时仍按原时限结束,外层任务资源限制不变。
27
27
  - 阶段以本次调用的结构化通知为准(命令写在 stderr,stdout 只有最终 JSON);不凭等待时间猜阶段。
28
28
  - PDF 在新标签页打开不等于已保存;以命令的最终结果为准,网页地址不是本地文件。