papersearch 0.7.1 → 0.7.3

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 (126) hide show
  1. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  2. package/dist/capabilities/download/batch/batch.js +306 -12
  3. package/dist/capabilities/download/batch/batch.js.map +1 -1
  4. package/dist/capabilities/download/batch/batchFolder.js +1 -1
  5. package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
  6. package/dist/capabilities/download/batch/batchSummary.d.ts.map +1 -1
  7. package/dist/capabilities/download/batch/batchSummary.js +17 -8
  8. package/dist/capabilities/download/batch/batchSummary.js.map +1 -1
  9. package/dist/capabilities/download/batch/journalKey.d.ts +12 -0
  10. package/dist/capabilities/download/batch/journalKey.d.ts.map +1 -0
  11. package/dist/capabilities/download/batch/journalKey.js +30 -0
  12. package/dist/capabilities/download/batch/journalKey.js.map +1 -0
  13. package/dist/capabilities/download/batch/networkLoss.d.ts +1 -1
  14. package/dist/capabilities/download/batch/networkLoss.js +1 -1
  15. package/dist/capabilities/download/content/markdown/shortfall.js +5 -5
  16. package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
  17. package/dist/capabilities/download/content/pdf/DownloadTier.d.ts +4 -0
  18. package/dist/capabilities/download/content/pdf/DownloadTier.d.ts.map +1 -1
  19. package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.d.ts.map +1 -1
  20. package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.js +2 -0
  21. package/dist/capabilities/download/content/pdf/OpenAccessFallbackService.js.map +1 -1
  22. package/dist/capabilities/download/content/pdf/school.js +2 -0
  23. package/dist/capabilities/download/content/pdf/school.js.map +1 -1
  24. package/dist/capabilities/download/types.d.ts +4 -0
  25. package/dist/capabilities/download/types.d.ts.map +1 -1
  26. package/dist/cli.js +32 -9
  27. package/dist/cli.js.map +1 -1
  28. package/dist/infrastructure/runlog/failureClass.d.ts +16 -9
  29. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  30. package/dist/infrastructure/runlog/failureClass.js +64 -54
  31. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  32. package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
  33. package/dist/infrastructure/school/SchoolAttempt.js +61 -56
  34. package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
  35. package/dist/infrastructure/school/SchoolMcpClient.d.ts +9 -1
  36. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  37. package/dist/infrastructure/school/SchoolMcpClient.js +31 -1
  38. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  39. package/dist/infrastructure/school/SchoolReadiness.d.ts +2 -0
  40. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  41. package/dist/infrastructure/school/SchoolReadiness.js +3 -0
  42. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  43. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  44. package/dist/infrastructure/school/SchoolResultNormalizer.js +5 -0
  45. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  46. package/dist/infrastructure/school/index.d.ts +1 -1
  47. package/dist/infrastructure/school/index.d.ts.map +1 -1
  48. package/dist/infrastructure/school/types.d.ts +19 -0
  49. package/dist/infrastructure/school/types.d.ts.map +1 -1
  50. package/dist/management/failures/index.d.ts +5 -2
  51. package/dist/management/failures/index.d.ts.map +1 -1
  52. package/dist/management/failures/index.js +21 -4
  53. package/dist/management/failures/index.js.map +1 -1
  54. package/dist/management/pro/activate.d.ts +36 -0
  55. package/dist/management/pro/activate.d.ts.map +1 -0
  56. package/dist/management/pro/activate.js +122 -0
  57. package/dist/management/pro/activate.js.map +1 -0
  58. package/dist/management/pro/install.d.ts +15 -0
  59. package/dist/management/pro/install.d.ts.map +1 -1
  60. package/dist/management/pro/install.js +39 -12
  61. package/dist/management/pro/install.js.map +1 -1
  62. package/dist/management/reports/index.d.ts +6 -0
  63. package/dist/management/reports/index.d.ts.map +1 -1
  64. package/dist/management/reports/index.js +6 -0
  65. package/dist/management/reports/index.js.map +1 -1
  66. package/dist/management/school/autoUpdate.d.ts.map +1 -1
  67. package/dist/management/school/autoUpdate.js +1 -0
  68. package/dist/management/school/autoUpdate.js.map +1 -1
  69. package/dist/management/school/cliProgress.d.ts.map +1 -1
  70. package/dist/management/school/cliProgress.js +1 -0
  71. package/dist/management/school/cliProgress.js.map +1 -1
  72. package/dist/management/school/settingsWindow.d.ts +1 -0
  73. package/dist/management/school/settingsWindow.d.ts.map +1 -1
  74. package/dist/management/school/settingsWindow.js +2 -0
  75. package/dist/management/school/settingsWindow.js.map +1 -1
  76. package/dist/management/updates/selfUpdate.d.ts +86 -0
  77. package/dist/management/updates/selfUpdate.d.ts.map +1 -0
  78. package/dist/management/updates/selfUpdate.js +194 -0
  79. package/dist/management/updates/selfUpdate.js.map +1 -0
  80. package/package.json +1 -1
  81. package/school/paper_search_school/adapters/annual_reviews/__init__.py +1 -0
  82. package/school/paper_search_school/adapters/base.py +4 -0
  83. package/school/paper_search_school/adapters/ieee/__init__.py +1 -0
  84. package/school/paper_search_school/adapters/oup/__init__.py +20 -0
  85. package/school/paper_search_school/adapters/sage/__init__.py +4 -1
  86. package/school/paper_search_school/adapters/taylor_francis/__init__.py +3 -0
  87. package/school/paper_search_school/adapters/thieme/__init__.py +4 -2
  88. package/school/paper_search_school/assets/capsule.html +1044 -243
  89. package/school/paper_search_school/assets/capsule_en.json +320 -74
  90. package/school/paper_search_school/assets/capsule_fr.json +1309 -0
  91. package/school/paper_search_school/assets/capsule_ja.json +1309 -0
  92. package/school/paper_search_school/assets/capsule_ko.json +1309 -0
  93. package/school/paper_search_school/assets/capsule_zh-Hant.json +2436 -0
  94. package/school/paper_search_school/cli.py +15 -1
  95. package/school/paper_search_school/cold_start.py +82 -9
  96. package/school/paper_search_school/config.py +2 -0
  97. package/school/paper_search_school/download_diagnostics.py +4 -4
  98. package/school/paper_search_school/engine/access_rules.py +3 -2
  99. package/school/paper_search_school/engine/batch.py +12 -4
  100. package/school/paper_search_school/engine/batch_access.py +21 -9
  101. package/school/paper_search_school/engine/batch_capture.py +36 -2
  102. package/school/paper_search_school/engine/batch_diagnostics.py +1 -1
  103. package/school/paper_search_school/engine/batch_institution.py +171 -29
  104. package/school/paper_search_school/engine/batch_login.py +65 -1
  105. package/school/paper_search_school/engine/batch_waits.py +22 -8
  106. package/school/paper_search_school/engine/bridge.py +27 -3
  107. package/school/paper_search_school/engine/router.py +2 -1
  108. package/school/paper_search_school/i18n.py +46 -22
  109. package/school/paper_search_school/orchestrator.py +90 -12
  110. package/school/paper_search_school/pro_status.py +54 -63
  111. package/school/paper_search_school/progress_capsule.py +180 -24
  112. package/school/paper_search_school/progress_reporter.py +68 -13
  113. package/school/paper_search_school/progress_view.py +4 -3
  114. package/school/paper_search_school/publishers/builtin/sage.json +4 -2
  115. package/school/paper_search_school/publishers/builtin/thieme.json +3 -1
  116. package/school/paper_search_school/school_login.py +18 -4
  117. package/school/paper_search_school/school_switch.py +84 -0
  118. package/school/paper_search_school/school_test.py +335 -0
  119. package/school/paper_search_school/server.py +21 -3
  120. package/school/paper_search_school/updates.py +222 -0
  121. package/school/paper_search_school/user_settings.py +8 -3
  122. package/skills/paper-search/SKILL.md +1 -1
  123. package/skills/paper-search/references/browser-download.md +7 -9
  124. package/skills/paper-search/references/cli-contract.md +1 -1
  125. package/skills/paper-search/references/publisher-support.md +2 -2
  126. package/skills/paper-search/references/school-setup.md +1 -1
@@ -1,8 +1,10 @@
1
- """The progress window in English: ``assets/capsule_en.json`` maps each Chinese
2
- text it can show (its own, the download's prompts and phases, PaperSearch's
3
- failure reasons) to a short English one. The page translates what it shows with
4
- it; the system notifications use it here. A text the table does not know stays
5
- as it is."""
1
+ """The progress window in other languages than its own simplified Chinese: ``assets/capsule_en.json`` maps each
2
+ Chinese text it can show (its own, the download's prompts and phases, PaperSearch's failure reasons) to a short
3
+ English one; ``assets/capsule_zh-Hant.json`` (made from it by ``school/tools/zh_hant_table.py``, user 2026-11-21)
4
+ says each in Traditional Chinese, and turns any other text character by character; ``capsule_ja.json``,
5
+ ``capsule_ko.json`` and ``capsule_fr.json`` say them in Japanese, Korean and French (user, 2026-11-21), a text they
6
+ do not know in English. The page translates what it shows with them; the system notifications use them here. In
7
+ English a text the table does not know stays as it is."""
6
8
  from __future__ import annotations
7
9
 
8
10
  import json
@@ -10,42 +12,64 @@ import re
10
12
  from functools import lru_cache
11
13
  from pathlib import Path
12
14
 
13
- TABLE = Path(__file__).resolve().parent / "assets" / "capsule_en.json"
14
- LANGUAGES = ("zh", "en")
15
+ ASSETS = Path(__file__).resolve().parent / "assets"
16
+ #: Each language's table; Chinese (zh, simplified) is the windows' own.
17
+ TABLES = {"en": ASSETS / "capsule_en.json", "zh-Hant": ASSETS / "capsule_zh-Hant.json",
18
+ "ja": ASSETS / "capsule_ja.json", "ko": ASSETS / "capsule_ko.json", "fr": ASSETS / "capsule_fr.json"}
19
+ TABLE = TABLES["en"]
20
+ LANGUAGES = ("zh", "zh-Hant", "en", "ja", "ko", "fr")
15
21
  _HAN = re.compile(r"[\u4e00-\u9fff]")
16
22
  _BRACKETS = re.compile(r"^(.+?)((.+))$")
23
+ _LISTED = re.compile(r"^([^:]+):(.+)$")
17
24
 
18
25
 
19
- @lru_cache(maxsize=1)
20
- def table() -> dict:
21
- return json.loads(TABLE.read_text(encoding="utf-8"))
26
+ @lru_cache(maxsize=None)
27
+ def table(lang: str = "en") -> dict:
28
+ return json.loads(TABLES[lang].read_text(encoding="utf-8"))
22
29
 
23
30
 
24
- @lru_cache(maxsize=1)
25
- def _patterns() -> list[tuple[re.Pattern, str]]:
26
- # The table's replacements are written for JavaScript ($1); Python's are \g<1>.
27
- return [(re.compile(source), re.sub(r"\$(\d)", r"\\g<\1>", target)) for source, target in table()["patterns"]]
31
+ @lru_cache(maxsize=None)
32
+ def _patterns(lang: str = "en") -> list[tuple[re.Pattern, str]]:
33
+ return [(re.compile(source), target) for source, target in table(lang)["patterns"]]
28
34
 
29
35
 
30
- def _one(text: str) -> str:
36
+ def _part(text: str, lang: str) -> str:
37
+ return _one(text, lang) if _HAN.search(text) else text
38
+
39
+
40
+ def _one(text: str, lang: str = "en") -> str:
31
41
  core = text.strip()
32
42
  if not core or not _HAN.search(core):
33
43
  return text
34
- exact = table()["exact"].get(core)
44
+ exact = table(lang)["exact"].get(core)
35
45
  if exact is None:
36
- for pattern, target in _patterns():
37
- if pattern.search(core):
38
- exact = pattern.sub(target, core)
46
+ for pattern, target in _patterns(lang):
47
+ found = pattern.search(core)
48
+ if found:
49
+ # What it names is said too where it is a text of the table; a name keeps its words (as the page does).
50
+ said = re.sub(r"\$(\d)", lambda m: _part(found.group(int(m.group(1))) or "", lang), target)
51
+ exact = core[:found.start()] + said + core[found.end():]
39
52
  break
53
+ if exact is None and lang == "zh-Hant":
54
+ # Not a text of the table: its characters (a name keeps its words).
55
+ chars = table(lang)["chars"]
56
+ exact = "".join(chars.get(c, c) for c in core)
40
57
  parts = _BRACKETS.match(core) if exact is None else None
41
58
  if parts:
42
59
  # "开放下载 18(出版社 API 3、预印本 1)": the text and what its brackets list, each on its own.
43
- exact = f"{_one(parts[1])} ({', '.join(_one(item) for item in parts[2].split('、'))})"
60
+ exact = f"{_one(parts[1], lang)} ({', '.join(_one(item, lang) for item in parts[2].split('、'))})"
61
+ listed = _LISTED.match(core) if exact is None else None
62
+ if listed and _one(listed[1], lang) != listed[1]:
63
+ # "读取失败:TimeoutError": a known word, then what it says, each on its own (as the page does).
64
+ exact = f"{_one(listed[1], lang)}: {', '.join(_one(item, lang) for item in listed[2].split(','))}"
65
+ if exact is None and lang not in ("en", "zh-Hant"):
66
+ # Japanese, Korean, French: what their table does not know, in English rather than in Chinese.
67
+ return _one(text, "en")
44
68
  return text if exact is None else text.replace(core, exact)
45
69
 
46
70
 
47
71
  def translate(text: str, lang: str) -> str:
48
72
  """``text`` in ``lang``; its " · " parts one by one, as the page does."""
49
- if lang != "en" or not text:
73
+ if lang not in TABLES or not text:
50
74
  return text
51
- return " · ".join(_one(part) for part in text.split(" · "))
75
+ return " · ".join(_one(part, lang) for part in text.split(" · "))
@@ -45,9 +45,13 @@ def download_institutional(
45
45
  login_wait: int | None = None,
46
46
  fulltext: bool | str | None = None,
47
47
  school: str | None = None,
48
+ fresh: bool = False,
48
49
  ) -> dict[str, Any]:
49
50
  """Download one DOI through institutional access only.
50
51
 
52
+ ``fresh`` (the settings' 测试登录, school_test.py): neither from the cache nor into it: the download itself is
53
+ what is tested.
54
+
51
55
  ``login_only`` (``login``): the download's own steps up to the article's
52
56
  access, then stop: no PDF, nothing cached. ``login_wait``: seconds to wait
53
57
  on the school's login page instead of the setting.
@@ -97,6 +101,8 @@ def download_institutional(
97
101
  extra["login_wait"] = login_wait
98
102
  if school and school.strip():
99
103
  extra["school"] = school.strip()
104
+ if fresh:
105
+ extra["fresh"] = True
100
106
  return _download_impl(doi, output_dir, **extra)
101
107
  finally:
102
108
  with _INFLIGHT_LOCK:
@@ -107,16 +113,21 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
107
113
  supplements: str | None = None, user_wait: str | None = None,
108
114
  diagnostics_dir: str | None = None, title: str | None = None,
109
115
  login_only: bool = False, login_wait: int | None = None,
110
- fulltext: str | None = None, school: str | None = None) -> dict[str, Any]:
116
+ fulltext: str | None = None, school: str | None = None, fresh: bool = False) -> dict[str, Any]:
111
117
  config = load_config()
112
- if school:
113
- # Another saved school for this download alone, as the user asked; the config's own
114
- # school is not changed (user, 2026-11-17).
115
- from .schools.saved import use_for_download
118
+ from . import school_switch
119
+ from .schools import saved as saved_schools
116
120
 
117
- problem = use_for_download(config, school)
121
+ # Another saved school for this download alone (the user asked, or a batch's 没权限 tried with it at its end); the
122
+ # config's own school is not changed (user, 2026-11-17).
123
+ other_school = ""
124
+ if school:
125
+ problem = saved_schools.use_for_download(config, school)
118
126
  if problem:
119
127
  return fail(doi, problem, error_type=problem, action="review_school")
128
+ if not saved_schools.is_current(load_config(), saved_schools.current(config) or {}):
129
+ other_school = school_switch.name(saved_schools.current(config) or {})
130
+ config[school_switch.MARKS_OFF] = True
120
131
  if fulltext:
121
132
  # The article's full-text page is saved while on it (engine/fulltext_page.py).
122
133
  # A main text already cached is not fetched again, so neither is its page.
@@ -146,7 +157,7 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
146
157
  config["diagnostics_dir"] = str(Path(diagnostics_dir).resolve())
147
158
  output_path = target_dir / f"{safe_filename(doi)}.pdf"
148
159
 
149
- cached = None if login_only else cache_get(doi, config)
160
+ cached = None if login_only or fresh else cache_get(doi, config)
150
161
  if cached and cached.get("success"):
151
162
  cached_file = Path(str(cached.get("file") or ""))
152
163
  if cached_file.exists() and is_pdf_file(cached_file):
@@ -161,12 +172,77 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
161
172
  return cached
162
173
 
163
174
  log.info(f"paper-search-school - {doi}")
175
+ # Another school than the one the browser last signed in with: that sign-in forgotten first; a test
176
+ # (``fresh``) always starts signed out, so that the account is what it tries (user, 2026-11-21).
177
+ from .cold_start import before_sign_in, signed_in_school
178
+ from .progress_reporter import batch_id
164
179
 
165
- try:
166
- result = try_institutional(doi, output_path, config)
167
- except Exception as exc:
168
- log.info(f" [Institutional] route exception: {type(exc).__name__}")
169
- return fail(doi, "institutional route raised", error_type="source_exception", action="review_logs")
180
+ # 没权限时换下一所学校 (school_switch.py): the schools to try in turn, the default one first. One alone: the switch
181
+ # off, a school named for this download, the test of one, a sign-in only, a paper of a batch (it switches once, at
182
+ # its end, for all its papers without access: user, 2026-11-22).
183
+ turns = (school_switch.schools(config) if school_switch.enabled(config) and not school and not fresh
184
+ and not login_only and not batch_id() else [])
185
+ turn = 0
186
+ entry_turn = 0
187
+ while True:
188
+ entity = str(config.get("idp_entity_id") or "").strip()
189
+ if not fresh and entity and signed_in_school() not in ("", entity):
190
+ # The batch's own browser, open from the article before, holds the profile: the default school's article
191
+ # after one another school got kept that school's sign-in beside its own, each article waiting 10 s for the
192
+ # profile in vain (Windows, 2026-11-22: Bone signed in with the default school, the other school's Wiley sign-in still
193
+ # there). Closed first, as for a switch.
194
+ from .browser.batch_session import active_batch
195
+
196
+ batch = active_batch.get()
197
+ if batch is not None:
198
+ batch.close()
199
+ signed = before_sign_in(config, always=fresh)
200
+ if signed == "busy" and not fresh:
201
+ log.info(" [Institutional] the download browser is open: the last school's sign-in kept")
202
+ if signed == "cleared":
203
+ log.info(" [Institutional] the browser's sign-in with another school forgotten")
204
+ elif signed == "busy" and fresh:
205
+ return fail(doi, "the download browser is open", error_type="browser_busy", action="close_browser")
206
+
207
+ try:
208
+ result = try_institutional(doi, output_path, config)
209
+ except Exception as exc:
210
+ log.info(f" [Institutional] route exception: {type(exc).__name__}")
211
+ return fail(doi, "institutional route raised", error_type="source_exception", action="review_logs")
212
+ # The school's entries by one name: the next one, with this school, when the one chosen did not do.
213
+ if school_switch.entry_did_not_do(result) and entry_turn + 1 < int(result.get("same_name_entries") or 0):
214
+ entry_turn += 1
215
+ config["institution_entry_turn"] = entry_turn
216
+ log.info(f" [Institutional] the school's entry {entry_turn} of {result['same_name_entries']} did not do; "
217
+ f"the next one")
218
+ continue
219
+ entry_turn = 0
220
+ config.pop("institution_entry_turn", None)
221
+ if turn + 1 >= len(turns) or not school_switch.no_access(result):
222
+ break
223
+ # Signed in, no access: the next school, its sign-in after this one's is forgotten (the batch's browser closed
224
+ # first to let go of it; one that will not let go ends the turns: the next would try this school's session).
225
+ turn += 1
226
+ following = turns[turn]
227
+ log.info(f" [Institutional] no access with {school_switch.name(turns[turn - 1])}; next: {school_switch.name(following)}")
228
+ from . import progress_reporter
229
+ from .browser.batch_session import active_batch
230
+
231
+ progress_reporter.update(stage="switching_school", phase=f"没权限,换{school_switch.name(following)}")
232
+ batch = active_batch.get()
233
+ if batch is not None:
234
+ batch.close()
235
+ saved_schools.apply(config, following)
236
+ config[school_switch.MARKS_OFF] = True
237
+ if before_sign_in(config) == "busy":
238
+ log.info(" [Institutional] the browser kept the last school's sign-in; no other school tried")
239
+ turn -= 1
240
+ break
241
+ if result and result.get("success") and (turn or other_school):
242
+ # Not the default school's: the results say whose.
243
+ result["school"] = school_switch.name(turns[turn]) if turn else other_school
244
+ elif turns and turn and school_switch.no_access(result):
245
+ result["schools_tried"] = turn + 1 # the lists say "N 所学校都没有权限"
170
246
  # An article that re-checked a blocked journal's site: open again unless blocked again.
171
247
  from . import blocked_journals
172
248
  blocked_journals.recheck_ended(doi, blocked=bool(result) and result.get("error_type") == "access_blocked")
@@ -193,5 +269,7 @@ def _download_impl(doi: str, output_dir: str | Path | None, *,
193
269
  result.setdefault("doi", doi)
194
270
  result["file"] = str(file_path)
195
271
  result.setdefault("size_kb", round(file_path.stat().st_size / 1024, 1))
272
+ if fresh:
273
+ return result
196
274
  cache_set(doi, result, config)
197
275
  return result
@@ -6,6 +6,7 @@ from __future__ import annotations
6
6
 
7
7
  import json
8
8
  import os
9
+ import re
9
10
  from pathlib import Path
10
11
  from typing import Any, Mapping
11
12
  from urllib.parse import quote
@@ -47,7 +48,7 @@ def status(env: Mapping[str, str] | None = None) -> dict[str, Any]:
47
48
  command line counts) and whether Pro is free now (pro/access.json, which Pro keeps)."""
48
49
  path = entry(env)
49
50
  if not path.is_file():
50
- return {"installed": False, "version": ""}
51
+ return {"installed": False, "version": "", "activation": activation(env)}
51
52
  manifest = _read(path.parent / "pro.json")
52
53
  sites = manifest.get("sites")
53
54
  stats = _read(data_home(env) / "pro" / "stats.json")
@@ -62,9 +63,28 @@ def status(env: Mapping[str, str] | None = None) -> dict[str, Any]:
62
63
  "complete": min(converted, _count(stats.get("complete"))),
63
64
  "access": {"mode": access.get("mode") if access.get("mode") in ("free", "key") else "free",
64
65
  "until": _day(until)},
66
+ "activation": activation(env),
65
67
  }
66
68
 
67
69
 
70
+ _DAY = re.compile(r"^\d{4}-\d{2}-\d{2}$")
71
+
72
+
73
+ def activation(env: Mapping[str, str] | None = None) -> dict[str, str]:
74
+ """Whether this computer is activated (user, 2026-11-21), from ``pro/activation.json``, which
75
+ ``paper-search pro activate`` keeps (src/management/pro/activate.ts): none, active or expired,
76
+ the code's last four characters and the day it ends. The code itself is not handed on."""
77
+ record = _read(data_home(env) / "pro" / "activation.json")
78
+ code = record.get("code")
79
+ if not isinstance(code, str) or not code:
80
+ return {"state": "none", "tail": "", "until": ""}
81
+ until = record.get("until") if isinstance(record.get("until"), str) and _DAY.match(record["until"]) else ""
82
+ import time
83
+
84
+ expired = bool(until) and until < time.strftime("%Y-%m-%d", time.localtime())
85
+ return {"state": "expired" if expired else "active", "tail": code[-4:], "until": until}
86
+
87
+
68
88
  def _day(ms: Any) -> str:
69
89
  """A free setting's end ("2027-03-01"), from Pro's milliseconds; "" for none."""
70
90
  import time
@@ -74,64 +94,11 @@ def _day(ms: Any) -> str:
74
94
  return time.strftime("%Y-%m-%d", time.localtime(ms / 1000))
75
95
 
76
96
 
77
- class ProCheck:
78
- """The Markdown page's 检查更新: ``paper-search pro check`` in the background (user, 2026-11-19);
79
- the page asks for ``state()`` until it is done: the newest version and whether it is newer."""
80
-
81
- def __init__(self, command_of=None, run=None):
82
- import threading
83
-
84
- from .api_keys import paper_search_command
85
-
86
- self._command_of = command_of or paper_search_command
87
- self._run_command = run
88
- self._lock = threading.Lock()
89
- self._state: dict[str, Any] = {"state": "idle"}
90
-
91
- def state(self) -> dict[str, Any]:
92
- with self._lock:
93
- return dict(self._state)
94
-
95
- def start(self) -> dict[str, Any]:
96
- import threading
97
-
98
- with self._lock:
99
- if self._state.get("state") == "running":
100
- return dict(self._state)
101
- self._state = {"state": "running"}
102
- threading.Thread(target=self._check, name="pro-check", daemon=True).start()
103
- return {"state": "running"}
104
-
105
- def _check(self) -> None:
106
- import subprocess
107
-
108
- command = self._command_of()
109
- answer: dict[str, Any] = {}
110
- if command is None:
111
- answer = {"ok": False, "message": "找不到 paper-search 命令"}
112
- else:
113
- env = {**os.environ, "PAPER_SEARCH_SKILL_AUTO_UPDATE": "false", "PAPER_SEARCH_UPDATE_NOTIFY": "false"}
114
- try:
115
- run = self._run_command or (lambda argv: subprocess.run(
116
- argv, capture_output=True, encoding="utf-8", errors="replace", env=env, timeout=60).stdout)
117
- lines = [line for line in str(run([*command, "pro", "check"]) or "").splitlines() if line.strip()]
118
- answer = json.loads(lines[-1]) if lines else {}
119
- except Exception:
120
- answer = {}
121
- with self._lock:
122
- if isinstance(answer, dict) and answer.get("ok") is True:
123
- self._state = {"state": "done", "latest": str(answer.get("latest") or ""),
124
- "update": answer.get("update") is True}
125
- else:
126
- message = answer.get("message") if isinstance(answer, dict) else ""
127
- self._state = {"state": "failed", "message": str(message or "检查更新出错")}
128
-
129
-
130
97
  class ProInstall:
131
98
  """The settings window's 安装: ``paper-search pro install --progress`` in the background, its
132
99
  progress lines read as they come; the page asks for ``state()`` until it is done or failed."""
133
100
 
134
- def __init__(self, command_of=None, popen=None):
101
+ def __init__(self, command_of=None, popen=None, run=None):
135
102
  import subprocess
136
103
  import threading
137
104
 
@@ -139,6 +106,7 @@ class ProInstall:
139
106
 
140
107
  self._command_of = command_of or paper_search_command
141
108
  self._popen = popen or subprocess.Popen
109
+ self._run_command = run or subprocess.run
142
110
  self._lock = threading.Lock()
143
111
  self._state: dict[str, Any] = {"state": "idle"}
144
112
 
@@ -150,25 +118,47 @@ class ProInstall:
150
118
  with self._lock:
151
119
  self._state = state
152
120
 
153
- def start(self) -> dict[str, Any]:
121
+ def start(self, code: str | None = None) -> dict[str, Any]:
122
+ """安装, or with the code typed on Pro's page 激活并安装: ``paper-search pro activate`` first
123
+ (user, 2026-11-21), the code handed on standard input; the install only once it is active."""
154
124
  import threading
155
125
 
156
126
  with self._lock:
157
127
  if self._state.get("state") == "running":
158
128
  return dict(self._state)
159
- self._state = started = {"state": "running", "done": 0, "total": 0}
160
- threading.Thread(target=self._run, name="pro-install", daemon=True).start()
129
+ activating = code is not None
130
+ self._state = started = ({"state": "running", "step": "activate"} if activating
131
+ else {"state": "running", "step": "install", "done": 0, "total": 0})
132
+ threading.Thread(target=self._run, args=(code,), name="pro-install", daemon=True).start()
161
133
  return dict(started)
162
134
 
163
- def _run(self) -> None:
135
+ def _activate(self, command: list[str], env: dict[str, str], code: str) -> bool:
136
+ try:
137
+ run = self._run_command([*command, "pro", "activate"], input=code, capture_output=True, encoding="utf-8",
138
+ errors="replace", env=env, timeout=60)
139
+ lines = [line for line in (run.stdout or "").splitlines() if line.strip()]
140
+ answer = json.loads(lines[-1]) if lines else {}
141
+ except Exception:
142
+ answer = {}
143
+ if isinstance(answer, dict) and answer.get("ok") is True:
144
+ return True
145
+ message = answer.get("message") or answer.get("error") if isinstance(answer, dict) else ""
146
+ self._set(state="failed", step="activate", message=str(message or "激活出错"))
147
+ return False
148
+
149
+ def _run(self, code: str | None = None) -> None:
164
150
  import subprocess
165
151
 
166
152
  command = self._command_of()
167
153
  if command is None:
168
- self._set(state="failed", message="找不到 paper-search 命令")
154
+ self._set(state="failed", step="activate" if code is not None else "install", message="找不到 paper-search 命令")
169
155
  return
170
156
  # An install must not also update the Skill or check for a new version.
171
157
  env = {**os.environ, "PAPER_SEARCH_SKILL_AUTO_UPDATE": "false", "PAPER_SEARCH_UPDATE_NOTIFY": "false"}
158
+ if code is not None:
159
+ if not self._activate(command, env, code):
160
+ return
161
+ self._set(state="running", step="install", done=0, total=0)
172
162
  last: dict[str, Any] = {}
173
163
  try:
174
164
  process = self._popen([*command, "pro", "install", "--progress"], stdout=subprocess.PIPE,
@@ -179,14 +169,15 @@ class ProInstall:
179
169
  except ValueError:
180
170
  continue
181
171
  if isinstance(message, dict) and message.get("event") == "progress":
182
- self._set(state="running", done=int(message.get("done") or 0), total=int(message.get("total") or 0))
172
+ self._set(state="running", step="install", done=int(message.get("done") or 0),
173
+ total=int(message.get("total") or 0))
183
174
  elif isinstance(message, dict):
184
175
  last = message
185
176
  process.wait(timeout=60)
186
177
  except Exception:
187
- self._set(state="failed", message="安装出错")
178
+ self._set(state="failed", step="install", message="安装出错")
188
179
  return
189
180
  if last.get("ok") is True:
190
181
  self._set(state="done", version=str(last.get("version") or ""))
191
182
  else:
192
- self._set(state="failed", message=str(last.get("message") or last.get("error") or "安装出错"))
183
+ self._set(state="failed", step="install", message=str(last.get("message") or last.get("error") or "安装出错"))