papersearch 0.5.1 → 0.5.2

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 (36) hide show
  1. package/README.en.md +8 -13
  2. package/README.md +8 -13
  3. package/carsi/paper_search_carsi/assets/api_keys.json +1 -1
  4. package/carsi/paper_search_carsi/assets/capsule_en.json +5 -0
  5. package/carsi/paper_search_carsi/browser/cookies.py +3 -206
  6. package/carsi/paper_search_carsi/cli.py +73 -37
  7. package/carsi/paper_search_carsi/config.py +24 -106
  8. package/carsi/paper_search_carsi/download_diagnostics.py +3 -3
  9. package/carsi/paper_search_carsi/engine/batch.py +15 -0
  10. package/carsi/paper_search_carsi/engine/batch_common.py +6 -0
  11. package/carsi/paper_search_carsi/engine/bridge.py +17 -4
  12. package/carsi/paper_search_carsi/orchestrator.py +19 -2
  13. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
  14. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +2 -0
  15. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  16. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
  17. package/dist/cli.js +19 -3
  18. package/dist/cli.js.map +1 -1
  19. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  20. package/dist/infrastructure/runlog/failureClass.js +1 -0
  21. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  22. package/dist/management/carsi/login.d.ts +28 -0
  23. package/dist/management/carsi/login.d.ts.map +1 -0
  24. package/dist/management/carsi/login.js +46 -0
  25. package/dist/management/carsi/login.js.map +1 -0
  26. package/dist/management/skills/nextSteps.d.ts.map +1 -1
  27. package/dist/management/skills/nextSteps.js +4 -3
  28. package/dist/management/skills/nextSteps.js.map +1 -1
  29. package/package.json +1 -1
  30. package/skills/paper-search/SKILL.md +11 -9
  31. package/skills/paper-search/references/browser-download.md +2 -1
  32. package/skills/paper-search/references/capability-routing.md +1 -1
  33. package/skills/paper-search/references/carsi-setup.md +14 -3
  34. package/skills/paper-search/references/cli-contract.md +1 -0
  35. package/skills/paper-search/references/publisher-support.md +1 -1
  36. package/carsi/paper_search_carsi/browser/login.py +0 -332
@@ -11,42 +11,12 @@ from typing import Any
11
11
  DATA_DIR = Path(os.environ.get("CARSI_DATA_DIR", str(Path.home() / ".local" / "share" / "paper-search-cli" / "carsi")))
12
12
  CONFIG_FILE = DATA_DIR / "config.json"
13
13
 
14
- DEFAULT_SCIHUB_DOMAINS = [
15
- # Direct PDF mirrors (no CAPTCHA, PDF via sci.bban.top iframe) — verified 2026-07
16
- # vg/al 现为 Turnstile 门/首页壳(2026-08-31 实测),保留用于人工点一次模式
17
- "https://sci-hub.vg",
18
- "https://sci-hub.al",
19
- "https://sci-hub.mk",
20
- # 2026-08-31 深夜直连实测新增:bz/mksa 稳定出文章页(iframe PDF,无验证墙)
21
- "https://sci-hub.bz",
22
- "https://sci-hub.mksa.top",
23
- # ALTCHA-protected (stable; used as manual-download hint)
24
- "https://sci-hub.ru",
25
- "https://sci-hub.ee",
26
- # Cloudflare-protected (requires a browser to pass the JS challenge)
27
- "https://sci-hub.st",
28
- # Reported intermittent (2026-06); kept but deprioritized
29
- "https://sci-hub.mksa.top",
30
- # Legacy (currently down, kept for future recovery)
31
- "https://sci-hub.se",
32
- "https://sci-hub.is",
33
- "https://sci-hub.41610.org",
34
- ]
35
-
36
14
  DEFAULT_CONFIG: dict[str, Any] = {
37
15
  "email": "paper-search-carsi@example.invalid",
38
16
  "output_dir": str(DATA_DIR / "papers"),
39
17
  "cache_dir": str(DATA_DIR / "cache"),
40
18
  "network_proxy": "",
41
19
  "proxy_pool": "", # 逗号分隔的代理列表;非空时批量下载按代理轮换出口 IP
42
- "download_strategy": "fastest", # fastest / grey_only(all 3 grey) / scihub_only(Sci-Hub only) / scihub_first / oa_first / legal_only
43
- "race_mode": "hedge", # hedge: score-ordered staggered cascade (fewer requests, less anti-bot heat) / full: flat parallel race
44
- "hedge_delay_seconds": 1.5, # hedged cascade: wait this long before widening to the next lane
45
- "batch_default_lanes": True, # batch downloads default to pretriage + channel-lane scheduling (fast HTTP -> grey -> institutional)
46
- "lane_s2_batch_min": 10, # minimum batch size to enrich OA URLs via the S2 batch endpoint (500 ids/request)
47
- "lane_mdpi_cdn": True, # fast lane: construct mdpi-res.com CDN URLs for 10.3390 DOIs (bypasses the bot-walled main site)
48
- "scihub_enabled": True,
49
- "scihub_domains": DEFAULT_SCIHUB_DOMAINS,
50
20
  "carsi_enabled": False,
51
21
  # The user's school. `setup --carsi --institution ...` saves the Chinese and English
52
22
  # names and the SAML entityID (https://idp.<school>/idp/shibboleth) from the CARSI
@@ -55,24 +25,6 @@ DEFAULT_CONFIG: dict[str, Any] = {
55
25
  "carsi_idp_name": "",
56
26
  "carsi_idp_name_en": "",
57
27
  "idp_entity_id": "",
58
- # 中文源开关(均为合法渠道):
59
- # ncpssd_enabled 国家哲学社会科学文献中心,人文社科免费全文
60
- # cn_journal_direct 中文期刊官网直链 PDF(DOI 落地到刊社网站时)
61
- "ncpssd_enabled": True,
62
- "cn_journal_direct": True,
63
- "core_api_key": "",
64
- "openalex_api_key": "",
65
- # Sciverse 语义检索(agentic-search):自然语言问题 → 可引用的证据片段。
66
- # 需要 https://sciverse.space/tokens 创建的 API Key;未配置时整条链路静默跳过。
67
- "sciverse_enabled": True,
68
- "sciverse_api_key": "",
69
- "sciverse_base_url": "https://api.sciverse.space",
70
- "sciverse_sub_queries": 0, # 查询改写数 0-4;调高召回更好但延迟更高
71
- "sciverse_timeout_seconds": 45,
72
- # 每次 search 额外跑一路结构化 meta-search(返回 DOI/unique_id,补语义片段的 DOI 缺口)。
73
- # 每次检索会因此多消耗一次 Sciverse 配额;配额紧张时设为 false。
74
- "sciverse_meta_search_enabled": True,
75
- "springer_api_key": "", # Springer Nature Full Text API (TDM) — entitlement follows the institution (ORCID-affiliated key, needs a Springer subscription with TDM rights)
76
28
  "connect_timeout": 15,
77
29
  "read_timeout": 30,
78
30
  "request_delay_min": 2.0,
@@ -80,11 +32,6 @@ DEFAULT_CONFIG: dict[str, Any] = {
80
32
  "fixed_request_delay_enabled": False,
81
33
  "json_probe_cache_seconds": 3600,
82
34
  "cache_ttl_hours": 168,
83
- "parallel_sources": True,
84
- "parallel_probes": True,
85
- "batch_workers": 10,
86
- "batch_stagger_seconds": 0.3,
87
- "min_pdf_size_bytes": 10000,
88
35
  "browser_headless": False,
89
36
  "browser_humanize": True,
90
37
  # 浏览器后端,二选一:chrome(默认,本机安装的 Google Chrome,经 Patchright 驱动)
@@ -95,11 +42,6 @@ DEFAULT_CONFIG: dict[str, Any] = {
95
42
  # 批量下载时每 N 篇回收一次浏览器上下文(cookie 内存交接,登录态不丢)。
96
43
  # 0 = 关闭。长批次(上千篇)建议 100-200,避免 Chrome 长会话内存漂移。
97
44
  "browser_restart_every": 0,
98
- # 批量下载成功后自动抓取附件/补充材料(SI)。默认关——大多数任务只要主 PDF。
99
- # 开启后成功论文会尝试抓取出版商补充材料,存为 {DOI}_SI{n}.{ext},并写 si_manifest.json。
100
- "fast_retry_wait_sec": 60,
101
- # 冷却重试期间的逐篇间隔(秒)。实测 15s/篇可 100% 绕开 Elsevier API 限流。
102
- "fast_retry_delay_sec": 15,
103
45
  # 任务启动时自动弹出悬浮进度条(独立进程,已有实例则不重复弹出)。
104
46
  "progress_bar_auto": True,
105
47
  # 需要登录学校或完成验证时,除了进度胶囊变色,再发一条系统通知;进度窗口的设置里可以关。
@@ -115,37 +57,32 @@ DEFAULT_CONFIG: dict[str, Any] = {
115
57
  "browser_stall_notify_after": 30,
116
58
  # 每个出版社每小时最多打开的文章数,防止学校因下载过多被出版社暂停访问;0 = 不限。
117
59
  "publisher_hourly_limit": 100,
118
- # Turnstile 交互门(如 sci-hub.vg):无头会话下无法点击,默认跳过并冷却。
119
- # scihub_browser_headless=false 时可开启人工点一次模式(点一次整批复用)。
120
- "scihub_turnstile_click": True,
121
- "turnstile_wait_sec": 180,
122
- # 机构级联并行 fetcher 数(各持独立登录会话)。默认 1 = 串行;2 可省约一半
123
- # Phase 2 时间,代价是同 IP 双浏览器会话。
124
- "institutional_workers": 1,
125
60
  # 灰色源竞速浏览器的独立无头开关(只影响 sci-hub 竞速,机构登录仍有可见窗口)。
126
61
  # true = 竞速全程零窗口、零任务栏闪烁;指纹安全性由 UA 清洗保证。
127
62
  "scihub_browser_headless": False,
128
- "scihub_browser_first": True, # false = pure-HTTP Sci-Hub lane (use when the PDF CDN challenges headless browsers but serves plain requests)
129
- "is_campus_network": False,
130
- "tor_proxy": os.environ.get("TOR_PROXY", ""),
131
- "tor_binary_path": "", # Explicit tor binary; empty falls back to the embedded install and then PATH. Pinning it stops lookup order from deciding which binary runs
132
- "tor_use_bridges": False,
133
- "use_tor_for_scihub": True,
134
- "google_scholar_limit": 5,
135
- "max_browser_workers": 1,
136
- "scihub_browser_workers": 3, # Number of Sci-Hub domains to race in parallel via browser
137
63
  "host_concurrency": {},
138
- "auto_rename": True,
139
- "zotero_api_key": "",
140
- "zotero_library_type": "user",
141
- "zotero_library_id": "",
142
- "flaresolverr_url": "http://127.0.0.1:8191/v1",
143
- "cookie_path": "",
144
64
  "chrome_profile_dir": "",
145
- "carsi_cookie_dir": "",
146
65
  }
147
66
 
148
67
 
68
+ # Settings of the project this backend grew out of (Sci-Hub, Sciverse, Zotero, Tor,
69
+ # parallel lanes, VPN and EZproxy routes, the old browser's) that no code reads any
70
+ # more: dropped from saved configs when they load, refused by `config set` (2026-11-09).
71
+ _RETIRED_KEYS = frozenset("""
72
+ download_strategy race_mode hedge_delay_seconds batch_default_lanes lane_s2_batch_min lane_mdpi_cdn
73
+ scihub_enabled scihub_domains ncpssd_enabled cn_journal_direct core_api_key openalex_api_key
74
+ sciverse_enabled sciverse_api_key sciverse_base_url sciverse_sub_queries sciverse_timeout_seconds sciverse_meta_search_enabled
75
+ springer_api_key parallel_sources parallel_probes batch_workers batch_stagger_seconds min_pdf_size_bytes
76
+ fast_retry_wait_sec fast_retry_delay_sec scihub_turnstile_click turnstile_wait_sec institutional_workers scihub_browser_first
77
+ is_campus_network tor_proxy tor_binary_path tor_use_bridges use_tor_for_scihub google_scholar_limit
78
+ max_browser_workers scihub_browser_workers auto_rename zotero_api_key zotero_library_type zotero_library_id
79
+ flaresolverr_url cookie_path carsi_cookie_dir
80
+ auto_relogin browser_auto_upgrade browser_executable cn_auto_login cn_databases_enabled cn_vip_fallback
81
+ ezproxy_enabled ezproxy_login_url institutional_allow_self_signed vpnsci_base_url vpnsci_cookie_file vpnsci_enabled
82
+ vpnsci_school
83
+ """.split())
84
+
85
+
149
86
  def load_config() -> dict[str, Any]:
150
87
  config = DEFAULT_CONFIG.copy()
151
88
  if CONFIG_FILE.exists():
@@ -158,6 +95,8 @@ def load_config() -> dict[str, Any]:
158
95
  pass
159
96
  for key, value in DEFAULT_CONFIG.items():
160
97
  config.setdefault(key, value)
98
+ for key in _RETIRED_KEYS:
99
+ config.pop(key, None)
161
100
  return config
162
101
 
163
102
 
@@ -176,20 +115,14 @@ _VALIDATION_RULES: dict[str, tuple[type, Any, Any]] = {
176
115
  "request_delay_max": (float, 0.0, 60.0),
177
116
  "json_probe_cache_seconds": (int, 0, 86400),
178
117
  "cache_ttl_hours": (int, 1, 8760),
179
- "batch_workers": (int, 1, 50),
180
- "batch_stagger_seconds": (float, 0.0, 10.0),
181
- "min_pdf_size_bytes": (int, 100, 1000000),
182
- "google_scholar_limit": (int, 1, 50),
183
- "sciverse_sub_queries": (int, 0, 4),
184
- "sciverse_timeout_seconds": (int, 5, 300),
185
118
  }
186
119
 
187
- _VALID_STRATEGIES = frozenset({"fastest", "scihub_first", "scihub_only", "grey_only", "oa_first", "legal_only"})
188
-
189
120
 
190
121
  def update_config(key: str, value: str) -> dict[str, Any]:
191
122
  import warnings as _warnings
192
123
 
124
+ if key in _RETIRED_KEYS:
125
+ raise ValueError(f"'{key}' is no longer used by this backend")
193
126
  config = load_config()
194
127
 
195
128
  # Validate: warn on unknown keys
@@ -200,17 +133,6 @@ def update_config(key: str, value: str) -> dict[str, Any]:
200
133
  stacklevel=2,
201
134
  )
202
135
 
203
- # Special handling for download_strategy
204
- if key == "download_strategy":
205
- value_lower = value.lower().strip()
206
- if value_lower not in _VALID_STRATEGIES:
207
- raise ValueError(
208
- f"Invalid download_strategy '{value}'. Valid options: {', '.join(sorted(_VALID_STRATEGIES))}"
209
- )
210
- config[key] = value_lower
211
- save_config(config)
212
- return config
213
-
214
136
  if key in config:
215
137
  old_type = type(config[key])
216
138
  if old_type == bool:
@@ -226,7 +148,7 @@ def update_config(key: str, value: str) -> dict[str, Any]:
226
148
  except ValueError:
227
149
  raise ValueError(f"Invalid float value for '{key}': '{value}'")
228
150
  elif old_type == list:
229
- # Try JSON parse for list values (e.g. scihub_domains)
151
+ # Try JSON parse for list values
230
152
  try:
231
153
  parsed = json.loads(value)
232
154
  if isinstance(parsed, list):
@@ -235,7 +157,7 @@ def update_config(key: str, value: str) -> dict[str, Any]:
235
157
  raise ValueError(f"Expected a JSON list for '{key}', got {type(parsed).__name__}")
236
158
  except json.JSONDecodeError:
237
159
  raise ValueError(
238
- f"Invalid list value for '{key}'. Use JSON format, e.g.: '[\"https://sci-hub.vg\",\"https://sci-hub.al\"]'"
160
+ f"Invalid list value for '{key}'. Use JSON format, e.g.: '[\"a\",\"b\"]'"
239
161
  )
240
162
  else:
241
163
  config[key] = value
@@ -252,12 +174,8 @@ def update_config(key: str, value: str) -> dict[str, Any]:
252
174
 
253
175
 
254
176
  SENSITIVE_KEYS = [
255
- "core_api_key",
256
- "zotero_api_key",
257
- "zotero_library_id",
258
177
  "elsevier_api_key",
259
178
  "elsevier_insttoken",
260
- "sciverse_api_key",
261
179
  ]
262
180
 
263
181
  # The list above is for names that do not advertise themselves. Everything else
@@ -28,15 +28,15 @@ profile_busy cancelled interrupted skipped_cached_attempt target_verified_reache
28
28
  unsupported_platform unsupported_publisher user_skipped user_marked_no_entitlement pdf_wrong_article
29
29
  article_not_yet_published
30
30
  institution_federation_unavailable browser_unresponsive browser_operation_timeout login_not_reached idp_no_return_to_publisher
31
- generic_institution_entry_missing
31
+ generic_institution_entry_missing browser_closed
32
32
  """.split())
33
33
  _STATES = _FAILURES | _STATUSES | frozenset("""
34
34
  started article_loaded article_loaded_after_sso pdf_response_captured
35
35
  opening_article waiting_login waiting_verification checking_access fetching_pdf
36
- pdf_captured saved_pending_verification route_failed
36
+ pdf_captured saved_pending_verification route_failed access_ready
37
37
  """.split())
38
38
  _EVENTS = frozenset("""
39
- aps_institution_entry_missing article_access_ready article_open
39
+ aps_institution_entry_missing article_access_ready article_open browser_closed login_only_done
40
40
  auth_wall_after_article_load auth_wall_after_pdf_attempt browser_capture_detach_error
41
41
  browser_capture_disable_error browser_pdf_response_captured browser_pdf_response_error
42
42
  browser_response_continue_error browser_response_discard_error challenge_manual_wait
@@ -51,6 +51,7 @@ from .batch_common import (
51
51
  goto_retrying,
52
52
  settle,
53
53
  _is_network_failure,
54
+ browser_closed,
54
55
  DownloadResult,
55
56
  EST_ISSN,
56
57
  IP_BLOCK_STOP_THRESHOLD,
@@ -482,6 +483,13 @@ class PublisherBatchDownloader(
482
483
  preparation = self._prepare_article(page, result, run_dir)
483
484
  if preparation is not None:
484
485
  return preparation
486
+ if self.config.get("login_only"):
487
+ # `login` (cli): the school's login and the article's access, then stop; no PDF.
488
+ result.signed_in = self._school_login_done()
489
+ result.state = "access_ready"
490
+ self._event(result, "login_only_done",
491
+ "signed in to the school" if result.signed_in else "access without the school's login")
492
+ return result
485
493
  self._snapshot(page, result, "article access checked")
486
494
  ip_block: str | None = None
487
495
  # Whether this capture comes after the school's login, and its first attempt.
@@ -663,6 +671,13 @@ class PublisherBatchDownloader(
663
671
  self._event(result, "publisher_unreachable", f"{str(exc).splitlines()[0][:300]} | {where}")
664
672
  self._write_diagnostic(page, result, run_dir)
665
673
  return result
674
+ if browser_closed(exc):
675
+ # The user closed the download browser, or it quit: said as such, not
676
+ # as an unexplained error (Elsevier at the school's login page, 2026-11-09).
677
+ result.reason = result.state = "browser_closed"
678
+ self._event(result, "browser_closed", f"{type(exc).__name__}: {str(exc)[:200]} | {where}")
679
+ self._write_diagnostic(page, result, run_dir)
680
+ return result
666
681
  result.reason = f"{type(exc).__name__}: {exc}"
667
682
  result.state = "unexpected_error"
668
683
  # The diagnostic normalizes reason to "unexpected_error"; keep the
@@ -134,6 +134,12 @@ def _is_browser_error(exc: BaseException, name: str = "") -> bool:
134
134
  return is_driver_error(exc, name)
135
135
 
136
136
 
137
+ def browser_closed(exc: BaseException) -> bool:
138
+ """The browser, its window or the page went away under a call (the driver's
139
+ TargetClosedError): the user closed the download browser, or it quit."""
140
+ return _is_browser_error(exc, "TargetClosedError") or "Target page, context or browser has been closed" in str(exc)
141
+
142
+
137
143
  def page_title(page: Any) -> str:
138
144
  """Read optional title text without consuming the whole page budget."""
139
145
  try:
@@ -45,6 +45,8 @@ _FAILURE_KINDS = {
45
45
  "challenge_or_viewer_timeout": ("download_timeout", "review_browser"),
46
46
  "ip_blocked": ("access_blocked", "review_access"),
47
47
  "unexpected_error": ("source_exception", ""),
48
+ # The user closed the download browser (or it quit) before the article was done.
49
+ "browser_closed": ("browser_closed", ""),
48
50
  "user_marked_no_entitlement": ("no_entitlement", "skipped_by_user"),
49
51
  "user_skipped": ("user_skipped", "skipped_by_user"),
50
52
  "batch_stopped": ("batch_stopped", "stopped_by_user"),
@@ -591,10 +593,14 @@ def _try_browser_batch_download(
591
593
  pass
592
594
  except Exception as e:
593
595
  log.info(" [Institutional] Browser batch download error: %s", type(e).__name__)
596
+ from .batch_common import browser_closed
597
+
594
598
  if isinstance(e, watchdog.BrowserOperationTimeout):
595
599
  state = "browser_operation_timeout"
596
600
  elif isinstance(e, watchdog.BrowserUnresponsive):
597
601
  state = "browser_unresponsive"
602
+ elif browser_closed(e):
603
+ state = "browser_closed"
598
604
  else:
599
605
  state = "unexpected_error"
600
606
  error_type, action = _FAILURE_KINDS[state]
@@ -604,6 +610,13 @@ def _try_browser_batch_download(
604
610
  "diagnostic": _write_exception_diagnostic(run_dir, doi, e, state=state, reason=error_type),
605
611
  "state": state}}
606
612
 
613
+ if getattr(result, "state", "") == "access_ready":
614
+ # `login`: the article opens in full; whether the school's login was part of it.
615
+ return {"success": True, "identifier": doi, "doi": doi,
616
+ "source": f"institutional:browser:{profile.name}",
617
+ "login": {"signed_in": bool(getattr(result, "signed_in", False))},
618
+ "artifacts": _browser_artifacts(result, profile)}
619
+
607
620
  if result.ok and result.pdf_path:
608
621
  src = Path(result.pdf_path)
609
622
  if src.exists():
@@ -639,11 +652,11 @@ def _try_browser_batch_download(
639
652
 
640
653
  def _browser_closed_at_start(result: Any) -> bool:
641
654
  """The item ended at its first navigation because the browser had closed
642
- (Playwright's TargetClosedError), before any other step."""
655
+ (Playwright's TargetClosedError), before any other step: the previous
656
+ item's browser was still letting go of the profile, not the user."""
643
657
  events = [e for e in getattr(result, "events", None) or () if e.get("state") != "browser_start"]
644
- return (getattr(result, "state", "") == "unexpected_error" and 2 <= len(events) <= 3
645
- and events[0].get("state") == "article_open" and events[1].get("state") == "unexpected_exception"
646
- and str(events[1].get("detail") or "").startswith("TargetClosedError"))
658
+ return (getattr(result, "state", "") == "browser_closed" and 2 <= len(events) <= 3
659
+ and events[0].get("state") == "article_open" and events[1].get("state") == "browser_closed")
647
660
 
648
661
 
649
662
  def _note_supplements(result: Any, written: int) -> None:
@@ -41,9 +41,15 @@ def download_institutional(
41
41
  user_wait: str | None = None,
42
42
  diagnostics_dir: str | None = None,
43
43
  title: str | None = None,
44
+ login_only: bool = False,
45
+ login_wait: int | None = None,
44
46
  ) -> dict[str, Any]:
45
47
  """Download one DOI through institutional access only.
46
48
 
49
+ ``login_only`` (``login``): the download's own steps up to the article's
50
+ access, then stop: no PDF, nothing cached. ``login_wait``: seconds to wait
51
+ on the school's login page instead of the setting.
52
+
47
53
  ``user_wait="short"``: the user seems away (an earlier article of the batch
48
54
  waited on them until its time was up); each wait on the user is short.
49
55
 
@@ -79,6 +85,10 @@ def download_institutional(
79
85
  extra["diagnostics_dir"] = diagnostics_dir
80
86
  if title:
81
87
  extra["title"] = title
88
+ if login_only:
89
+ extra["login_only"] = True
90
+ if login_wait:
91
+ extra["login_wait"] = login_wait
82
92
  return _download_impl(doi, output_dir, **extra)
83
93
  finally:
84
94
  with _INFLIGHT_LOCK:
@@ -87,8 +97,13 @@ def download_institutional(
87
97
 
88
98
  def _download_impl(doi: str, output_dir: str | Path | None, *,
89
99
  supplements: str | None = None, user_wait: str | None = None,
90
- diagnostics_dir: str | None = None, title: str | None = None) -> dict[str, Any]:
100
+ diagnostics_dir: str | None = None, title: str | None = None,
101
+ login_only: bool = False, login_wait: int | None = None) -> dict[str, Any]:
91
102
  config = load_config()
103
+ if login_only:
104
+ config["login_only"] = True
105
+ if login_wait:
106
+ config["browser_login_timeout"] = int(login_wait)
92
107
  if title:
93
108
  # The caller's title for the PDF identity check (bridge's PaperRecord).
94
109
  config["record_title"] = plain_title(title)
@@ -107,7 +122,7 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
107
122
  config["diagnostics_dir"] = str(Path(diagnostics_dir).resolve())
108
123
  output_path = target_dir / f"{safe_filename(doi)}.pdf"
109
124
 
110
- cached = cache_get(doi, config)
125
+ cached = None if login_only else cache_get(doi, config)
111
126
  if cached and cached.get("success"):
112
127
  cached_file = Path(str(cached.get("file") or ""))
113
128
  if cached_file.exists() and is_pdf_file(cached_file):
@@ -141,6 +156,8 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
141
156
  result.setdefault("doi", doi)
142
157
  result.setdefault("reason", "institutional download failed")
143
158
  return result
159
+ if login_only:
160
+ return result # the article's access, no PDF (bridge: access_ready)
144
161
 
145
162
  file_path = Path(str(result.get("file") or output_path))
146
163
  if not file_path.exists() or not is_pdf_file(file_path):
@@ -1 +1 @@
1
- {"version":3,"file":"CarsiAttempt.d.ts","sourceRoot":"","sources":["../../../../src/capabilities/pdf-discovery/carsi/CarsiAttempt.ts"],"names":[],"mappings":"AAkIA,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,SAAgC,GAAG,MAAM,CAE1G;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG;IACnF,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB,CAIA"}
1
+ {"version":3,"file":"CarsiAttempt.d.ts","sourceRoot":"","sources":["../../../../src/capabilities/pdf-discovery/carsi/CarsiAttempt.ts"],"names":[],"mappings":"AAoIA,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,EAAE,OAAO,SAAgC,GAAG,MAAM,CAE1G;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE;IAAE,WAAW,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG;IACnF,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;CACjB,CAIA"}
@@ -4,6 +4,7 @@ const MESSAGES = {
4
4
  login_timeout: "等待机构登录超时。请检查下载浏览器并完成登录后重试;超时不代表没有全文权限。",
5
5
  login_not_reached: "程序没能进入学校登录页(一直停在出版社页面),这不是没有权限;已记为原因不明,待排查。",
6
6
  login_page_closed: "机构登录页面已关闭。请重新打开下载浏览器后重试。",
7
+ browser_closed: "下载浏览器被关闭了,这一篇没有下完;需要时重新下载即可。",
7
8
  login_credentials_rejected: "机构登录凭证被拒绝。请在下载浏览器核查登录提示并手动处理;不自动重复提交。",
8
9
  login_retries_exhausted: "机构登录重试次数已用尽。请核查下载浏览器状态后再决定是否重试。",
9
10
  idp_login_error: "学校统一身份认证返回了错误页(例如“50000 未知错误”)。请稍后重试;若反复出现,请向学校图书馆确认该出版社的 CARSI 服务是否开通。",
@@ -50,6 +51,7 @@ const SHORT_REASONS = {
50
51
  login_timeout: "等学校登录超时",
51
52
  login_not_reached: "没进入学校登录页",
52
53
  login_page_closed: "登录页被关闭",
54
+ browser_closed: "下载浏览器被关闭了",
53
55
  login_credentials_rejected: "学校登录被拒绝",
54
56
  login_retries_exhausted: "登录重试已用尽",
55
57
  idp_login_error: "学校登录系统出错",
@@ -1 +1 @@
1
- {"version":3,"file":"CarsiAttempt.js","sourceRoot":"","sources":["../../../../src/capabilities/pdf-discovery/carsi/CarsiAttempt.ts"],"names":[],"mappings":"AAAA,uFAAuF;AACvF,MAAM,QAAQ,GAA2B;IACvC,cAAc,EACZ,sCAAsC;IACxC,aAAa,EACX,wCAAwC;IAC1C,iBAAiB,EACf,6CAA6C;IAC/C,iBAAiB,EAAE,0BAA0B;IAC7C,0BAA0B,EACxB,uCAAuC;IACzC,uBAAuB,EACrB,iCAAiC;IACnC,eAAe,EACb,yEAAyE;IAC3E,kBAAkB,EAChB,2CAA2C;IAC7C,0BAA0B,EACxB,mFAAmF;IACrF,oBAAoB,EAClB,uCAAuC;IACzC,YAAY,EACV,6BAA6B;IAC/B,aAAa,EACX,+BAA+B;IACjC,cAAc,EACZ,wEAAwE;IAC1E,kCAAkC,EAChC,2DAA2D;IAC7D,0BAA0B,EACxB,+CAA+C;IACjD,OAAO,EACL,2CAA2C;IAC7C,mBAAmB,EACjB,sEAAsE;IACxE,kBAAkB,EAChB,4BAA4B;IAC9B,gBAAgB,EAAE,4BAA4B;IAC9C,gBAAgB,EACd,kCAAkC;IACpC,OAAO,EACL,kCAAkC;IACpC,SAAS,EAAE,QAAQ;IACnB,YAAY,EACV,gDAAgD;IAClD,mBAAmB,EAAE,uBAAuB;IAC5C,SAAS,EAAE,iBAAiB;IAC5B,uBAAuB,EACrB,sDAAsD;IACxD,qBAAqB,EACnB,uDAAuD;IACzD,yBAAyB,EACvB,+DAA+D;IACjE,oBAAoB,EAClB,8CAA8C;IAChD,oBAAoB,EAClB,6EAA6E;IAC/E,yBAAyB,EACvB,iEAAiE;IACnE,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AC,CAAC,CAAC,OAAO,CAAC;AACpF,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,IAAY,EAAE,KAAgC;IAIhF,MAAM,SAAS,GAAG,MAAM,CAAC,MAAM,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,iBAAiB,CAAC;IAC3E,yFAAyF;IACzF,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,QAAQ,CAAC,SAAS,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,KAAK,EAAE,WAAW,IAAI,OAAO,CAAC,EAAE,CAAC;AAC5G,CAAC"}
@@ -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.1";
21
+ const PAPER_SEARCH_MCP_CLIENT_VERSION = "0.5.2";
22
22
  const NO_BATCH_SUPPORT = {
23
23
  downloadFields: false,
24
24
  supplementsField: false,
package/dist/cli.js CHANGED
@@ -25,6 +25,7 @@ import { InstallError, installCarsi, carsiStatus, renderStatusText, uninstallCar
25
25
  import { resolveDefaultCarsiProfileDir, takeDownloadLock } from "./capabilities/pdf-discovery/carsi/index.js";
26
26
  import { autoUpdateCarsi, withAutoUpdate } from "./management/carsi/autoUpdate.js";
27
27
  import { openSettingsWindow, settingsWindowEnv as windowEnv } from "./management/carsi/settingsWindow.js";
28
+ import { carsiLogin } from "./management/carsi/login.js";
28
29
  import { paperSearchCommand } from "./config/selfCommand.js";
29
30
  import { TESTABLE_KEYS, probeKeyFor, testApiKey } from "./config/apiKeyTest.js";
30
31
  import { hasScreen } from "./management/carsi/runtime.js";
@@ -82,6 +83,7 @@ Usage:
82
83
  paper-search failures [--run <id>|latest] [--since 2026-11-01] [--runs 5] [--doi <DOI>] [--export <file.zip>] [--all]
83
84
  paper-search carsi <install|status> [--browser chrome|ego] [--yes] [--force] [--skip-school]
84
85
  paper-search carsi update [--force]
86
+ paper-search carsi login --doi <DOI> [--max-wait <seconds>]
85
87
  paper-search carsi uninstall [--yes] [--remove-data]
86
88
  paper-search smoke --mock|--live
87
89
  paper-search skills <status|update|diff> [--targets agents,codex]
@@ -344,10 +346,14 @@ function carsiBackendForToolCall(tool, args) {
344
346
  return undefined;
345
347
  }
346
348
  // After an upgrade, the extension is updated before the backend first starts.
347
- return withCliCarsiProgress(withAutoUpdate(createCarsiBackend(), () => autoUpdateCarsi(createNodeHost(() => Promise.resolve("")), carsiContext(), () => {
349
+ return withCliCarsiProgress(withAutoUpdate(createCarsiBackend(), updateCarsiFirst));
350
+ }
351
+ /** After a PaperSearch upgrade: the extension brought up to it (autoUpdateCarsi), under the download lock. */
352
+ function updateCarsiFirst() {
353
+ return autoUpdateCarsi(createNodeHost(() => Promise.resolve("")), carsiContext(), () => {
348
354
  const lockPath = takeDownloadLock(resolveDefaultCarsiProfileDir());
349
355
  return () => unlinkSync(lockPath);
350
- })));
356
+ });
351
357
  }
352
358
  function withCliCarsiProgress(backend) {
353
359
  const withBatchSession = backend.withBatchSession?.bind(backend);
@@ -877,6 +883,16 @@ async function handleCarsiCommand(positionals, flags) {
877
883
  ? renderStatusText(status)
878
884
  : { ok: outcome.status !== "cancelled", outcome: outcome.status, ...status };
879
885
  }
886
+ if (sub === "login") {
887
+ // The backend's own steps of a download up to the article's access (no PDF).
888
+ await updateCarsiFirst();
889
+ return carsiLogin({
890
+ executable: getConfigValue("PAPER_SEARCH_CARSI_EXECUTABLE"),
891
+ doi: typeof flags.doi === "string" ? flags.doi : "",
892
+ ...(Number(flags.maxWait) > 0 ? { maxWait: Number(flags.maxWait) } : {}),
893
+ env: settingsWindowEnv(),
894
+ });
895
+ }
880
896
  if (sub === "status") {
881
897
  const status = await carsiStatus(host, context);
882
898
  return flags.format === "text" ? renderStatusText(status) : { ok: true, ...status };
@@ -906,7 +922,7 @@ async function handleCarsiCommand(positionals, flags) {
906
922
  }
907
923
  return {
908
924
  ok: false,
909
- error: "用法:paper-search carsi <install|status|update|uninstall>(见 paper-search --help)",
925
+ error: "用法:paper-search carsi <install|status|update|uninstall|login>(见 paper-search --help)",
910
926
  };
911
927
  }
912
928
  catch (error) {