papersearch 0.6.1 → 0.6.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 (48) hide show
  1. package/README.en.md +9 -2
  2. package/README.md +9 -2
  3. package/dist/capabilities/pdf-discovery/batch.d.ts +6 -0
  4. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  5. package/dist/capabilities/pdf-discovery/batch.js +20 -5
  6. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  7. package/dist/capabilities/pdf-discovery/school/SchoolMcpClient.d.ts +7 -0
  8. package/dist/capabilities/pdf-discovery/school/SchoolMcpClient.d.ts.map +1 -1
  9. package/dist/capabilities/pdf-discovery/school/SchoolMcpClient.js +35 -1
  10. package/dist/capabilities/pdf-discovery/school/SchoolMcpClient.js.map +1 -1
  11. package/dist/capabilities/pdf-discovery/school/SchoolReadiness.d.ts +2 -0
  12. package/dist/capabilities/pdf-discovery/school/SchoolReadiness.d.ts.map +1 -1
  13. package/dist/capabilities/pdf-discovery/school/SchoolReadiness.js +3 -0
  14. package/dist/capabilities/pdf-discovery/school/SchoolReadiness.js.map +1 -1
  15. package/dist/capabilities/pdf-discovery/school/types.d.ts +7 -0
  16. package/dist/capabilities/pdf-discovery/school/types.d.ts.map +1 -1
  17. package/dist/infrastructure/pdf/PdfIdentity.d.ts +4 -2
  18. package/dist/infrastructure/pdf/PdfIdentity.d.ts.map +1 -1
  19. package/dist/infrastructure/pdf/PdfIdentity.js +66 -12
  20. package/dist/infrastructure/pdf/PdfIdentity.js.map +1 -1
  21. package/dist/management/school/autoUpdate.d.ts.map +1 -1
  22. package/dist/management/school/autoUpdate.js +2 -0
  23. package/dist/management/school/autoUpdate.js.map +1 -1
  24. package/dist/management/school/cliProgress.d.ts.map +1 -1
  25. package/dist/management/school/cliProgress.js +1 -0
  26. package/dist/management/school/cliProgress.js.map +1 -1
  27. package/package.json +1 -1
  28. package/school/paper_search_school/assets/capsule_en.json +26 -1
  29. package/school/paper_search_school/browser/batch_session.py +21 -0
  30. package/school/paper_search_school/engine/batch.py +2 -0
  31. package/school/paper_search_school/engine/batch_institution.py +114 -1
  32. package/school/paper_search_school/engine/batch_login.py +27 -2
  33. package/school/paper_search_school/engine/bridge.py +3 -0
  34. package/school/paper_search_school/engine/pdf_guard.py +66 -8
  35. package/school/paper_search_school/federations/builtin/incommon.json +11 -0
  36. package/school/paper_search_school/federations/builtin/infed.json +11 -0
  37. package/school/paper_search_school/federations/builtin/liaf.json +11 -0
  38. package/school/paper_search_school/federations/builtin/omren.json +11 -0
  39. package/school/paper_search_school/federations/builtin/pkifed.json +11 -0
  40. package/school/paper_search_school/federations/builtin/tigerfed.json +11 -0
  41. package/school/paper_search_school/federations/builtin/yetkim.json +11 -0
  42. package/school/paper_search_school/federations/schools.py +53 -12
  43. package/school/paper_search_school/progress_reporter.py +15 -3
  44. package/school/paper_search_school/progress_view.py +31 -0
  45. package/school/paper_search_school/server.py +15 -1
  46. package/skills/paper-search/SKILL.md +2 -1
  47. package/skills/paper-search/references/federation-support.md +19 -3
  48. package/skills/paper-search/references/school-setup.md +2 -2
@@ -577,7 +577,10 @@ class LoginMixin:
577
577
  # Shibboleth's attribute-release and terms-of-use forms, whatever the language.
578
578
  _IDP_CONFIRMATION_JS = """() => document.querySelector('[name="_eventId_TermsRejected"]') ? 'terms-of-use'
579
579
  : document.querySelector('[name="_shib_idp_consentOptions"], [name="_shib_idp_consentIds"]') ? 'attribute-release' : ''"""
580
- _IDP_ERROR_RE = re.compile(r"未知错误|系统错误|服务异常|认证失败|出错了|\b5\d{4}\b.{0,20}错误|an unexpected error|error code|system error", re.I)
580
+ # Shibboleth's "Message Security Error": the identity provider could not trust the
581
+ # publisher's request (a school's IdP to Elsevier, 2026-11-12).
582
+ _IDP_ERROR_RE = re.compile(r"未知错误|系统错误|服务异常|认证失败|出错了|\b5\d{4}\b.{0,20}错误|an unexpected error|error code|system error"
583
+ r"|message security error", re.I)
581
584
 
582
585
  # A publisher's own terms form on the way to the school: SIAM's SAML consent
583
586
  # ("I have read and agree to the Terms and Conditions and Privacy Policy.",
@@ -730,7 +733,7 @@ class LoginMixin:
730
733
  r"|sorry, you have been blocked|no institutions found|not registered for use with this service"
731
734
  r"|application you have accessed is not registered|may not be enabled for this type of authentication"
732
735
  r"|can't find your institution|access to this resource has been restricted by your organization|oa-ap-4032"
733
- r"|不支持的请求|does not have access to this resource"
736
+ r"|不支持的请求|does not have access to this resource|message security error|reported an idp error"
734
737
  r"|temporarily unavailable|verify you are human|are you a robot|checking your browser|正在进行安全验证", re.I)
735
738
 
736
739
  def _login_block_reason(self, page: Any) -> str:
@@ -743,6 +746,8 @@ class LoginMixin:
743
746
  def _block_evidence_for(self, code: str, page: Any) -> str:
744
747
  if code == "login_page_closed":
745
748
  return "the browser window was closed"
749
+ if code == "idp_login_error" and self._on_browser_error_page(page):
750
+ return f"the school's login server could not be reached: {self._school_unreachable}"
746
751
  if code == "institution_pdf_entitlement_missing":
747
752
  line = self._denial_line(page)
748
753
  if line:
@@ -758,9 +763,18 @@ class LoginMixin:
758
763
  return f'{url.hostname or ""}: "{quoted[:200]}"'
759
764
  return f"{url.hostname or ''}{url.path[:80]} | {self._title(page)[:80]} ({type(self.adapter).__name__} rule)"
760
765
 
766
+ def _on_browser_error_page(self, page: Any) -> bool:
767
+ """The browser's own error page after a navigation to the school's login
768
+ server failed (``_follow_login_route``): nobody can sign in there."""
769
+ return bool(getattr(self, "_school_unreachable", "")) and str(getattr(page, "url", "") or "").startswith(
770
+ "chrome-error://")
771
+
761
772
  def _login_block_check(self, page: Any) -> str:
762
773
  if page.is_closed() is True:
763
774
  return "login_page_closed" # the user closed the window
775
+ if self._on_browser_error_page(page):
776
+ # Two schools' login servers did not answer from abroad (2026-11-12).
777
+ return "idp_login_error"
764
778
  try:
765
779
  parsed_idp = urlparse(str(getattr(page, "url", "") or ""))
766
780
  if self._is_idp_host(parsed_idp.netloc):
@@ -803,6 +817,10 @@ class LoginMixin:
803
817
  return override
804
818
  if "unsupported request" in haystack and "not registered for use with this service" in haystack:
805
819
  return "institution_not_registered"
820
+ # A publisher's Shibboleth saying the school's identity provider answered with
821
+ # an error ("SAML response reported an IdP error ... AuthnFailed", 2026-11-12).
822
+ if "saml response reported an idp error" in haystack:
823
+ return "idp_login_error"
806
824
  # The same Shibboleth page in Chinese: "Web登陆服务 - 不支持的请求" on the
807
825
  # school's IdP, the school has not enabled this publisher (JAMA, 2026-11-07).
808
826
  if "不支持的请求" in haystack and self._is_idp_host(urlparse(current_url).netloc):
@@ -833,9 +851,16 @@ class LoginMixin:
833
851
  # school has not enabled (2026-11-02). A page there that is no login form, no
834
852
  # SAML hand-over and no "please wait" page, unchanged this long, ends the item.
835
853
  SCHOOL_SITE_STAY_SEC = 12
854
+ # A username-first page (Okta's "identifier" field, no password box yet: a
855
+ # school's login was taken for its portal and ended, 2026-11-12) is a login;
856
+ # a portal's search box is not.
836
857
  _SCHOOL_PAGE_STATE_JS = r"""() => ({
837
858
  ready: document.readyState === 'complete',
838
859
  login: !!document.querySelector('input[type="password"], input[autocomplete="one-time-code"]')
860
+ || [...document.querySelectorAll('input')].some(el => el.getClientRects().length > 0 && !el.disabled
861
+ && !el.readOnly && ['text', 'email'].includes(el.type) && (el.type === 'email'
862
+ || /username|email/i.test(el.autocomplete || '')
863
+ || /user|login|identifier|account|email|netid|学号|工号|账号|帐号/i.test(`${el.name} ${el.id}`)))
839
864
  || /扫码|二维码|QR ?code|验证码|verification code/i.test((document.body && document.body.innerText || '').slice(0, 4000)),
840
865
  handover: !!document.querySelector('input[name="SAMLResponse"], input[name="SAMLRequest"], input[name="RelayState"]')
841
866
  || /^\s*(?:loading|please wait|redirecting|正在跳转|跳转中|请稍候|处理中)/i.test(document.title || '')})"""
@@ -565,6 +565,9 @@ def _try_browser_batch_download(
565
565
  # The browser call never returned and the driver was stopped:
566
566
  # whatever the engine reported after that is a consequence.
567
567
  result.reason = result.state = watchdog.failure_code()
568
+ if batch is not None:
569
+ # What a wait of the batch keeps the publisher's session alive with.
570
+ batch.article_url = (result.final_url or result.article_url) if result.ok else ""
568
571
  if supplements_mode in ("with", "only"):
569
572
  if result.state in ("browser_unresponsive", "browser_operation_timeout"):
570
573
  result.supplements = [{"status": "skipped", "reason": result.state,
@@ -11,7 +11,8 @@ misread letters, reading order) does not matter, and the evidence is weighed:
11
11
 
12
12
  - strong: the whole title, exactly (letters only, at least 50 of them),
13
13
  standing as a title (an exact match inside a longer line counts one level lower);
14
- - single: the target DOI; the title with a few misread letters; a shorter title.
14
+ - single: the target DOI; the title with a few misread letters; a shorter title; a title
15
+ too short to count alone ("Reply") on its own line right next to the target DOI's line.
15
16
 
16
17
  Strong evidence, or two single pieces, verify the PDF; one single piece verifies
17
18
  it while the pages print no other DOI. Other DOIs and no evidence at all:
@@ -20,9 +21,14 @@ another article. A title's numbers must always be exact. An attachment
20
21
  (correction, retraction, briefing, letter to the editor), each known by its own
21
22
  heading line, are not the article, unless the notice is itself the requested
22
23
  item: its title says so, or the pages name it (its DOI in the header, or its
23
- whole title and its DOI) and print no other DOI. A scan without a text layer is
24
+ whole title and its DOI) and print no other DOI. A DOI the pages label as the article
25
+ a notice is about ("DOI of original article:", "Correction to:") is no other DOI for
26
+ the notice itself (a letter that names the article it discusses); when that label
27
+ points at the requested DOI, the PDF is a notice about it. A scan without a text layer is
24
28
  ``"source"`` when the URL it came from names the DOI (``assess`` with ``source``;
25
- the frontend passes it, the engine does not).
29
+ the frontend passes it, the engine does not); so is a page that prints no DOI at all and is
30
+ no notice or attachment, for an item named like a section rather than an article (a
31
+ one-page "Journal Club" note, "Issue Information").
26
32
 
27
33
  ``classify`` gives ``"match"`` (verified), ``"other"`` (another article),
28
34
  ``"unknown"`` (no decision: no text layer, or nothing printed) or ``"invalid"``
@@ -66,6 +72,14 @@ _NOTICE = re.compile(
66
72
  r"|:[ \t]*(?:correction|erratum|corrigendum|retraction|expression of concern)[ \t]*$", re.I | re.M)
67
73
  # A requested item whose title says it is a notice ("…: Erratum", "Reply to …").
68
74
  _NOTICE_TITLE = re.compile(r"\b(?:erratum|corrigendum|correction|retraction|retracted|withdrawn|expression of concern|reply to|letter)\b", re.I)
75
+ # A label for the article a notice is about, followed by its DOI ("DOI of original article:
76
+ # https://doi.org/…" under an Elsevier letter or reply, 2026-11-12; "Correction to: Nature
77
+ # https://doi.org/…"; "The original article can be found online at …").
78
+ _ABOUT_LABEL = re.compile(
79
+ r"\b(?:doi\s+of\s+(?:the\s+)?original\s+article|(?:the\s+)?original\s+article(?:\s+can\s+be\s+found\s+online\s+at|\s+is\s+available\s+(?:online\s+)?at)?"
80
+ r"|(?:correction|erratum|corrigendum|addendum)\s+to|retraction\s+(?:note\s+|notice\s+)?(?:to|of)|comment(?:ary)?\s+on"
81
+ r"|(?:in\s+)?(?:reply|response)\s+to|see\s+the\s+article|refers\s+to|linked\s+article)\s*:?", re.I)
82
+ _ABOUT_REACH = 200 # how far after its label the DOI of the article a notice is about may be
69
83
  # A DOI may break right after its prefix ("https://doi.org/10.1016/" then "S0140-…", The Lancet).
70
84
  _DOI_IN_TEXT = re.compile(r"10\.\d{4,9}/(?:[ \t]*\n[ \t]*)?[^\s\"<>]+")
71
85
  _LETTER = re.compile(r"[a-zЀ-ӿ一-鿿]")
@@ -162,6 +176,19 @@ def _title_evidence(text: str, chars: str, at: list[int], title: str) -> str | N
162
176
  return "single" if end > 0 and _numbers_match(window(end, len(key) + errors), plain) else None
163
177
 
164
178
 
179
+ def _short_title_beside_doi(text: str, target: str, title: str) -> bool:
180
+ """A title too short to count alone ("Reply") on its own line within two lines of the
181
+ target DOI's line (Wiley letters: "DOI 10.1002/…" then "Reply", 2026-11-12)."""
182
+ key = _letters(normalize_doi_text(_plain_title(title)))[0]
183
+ if not key or _weight(key) >= SHORT_TITLE:
184
+ return False
185
+ lines = text.split("\n")
186
+ for i, line in enumerate(lines):
187
+ if _doi_named(line, target) and any(_letters(near)[0] == key for near in lines[max(0, i - 2):i] + lines[i + 1:i + 3]):
188
+ return True
189
+ return False
190
+
191
+
165
192
  def _target_doi(identifier: str) -> str:
166
193
  return re.sub(r"^(?:https?://(?:dx\.)?doi\.org/|doi:\s*)", "", (identifier or "").strip().lower())
167
194
 
@@ -184,12 +211,30 @@ def _doi_named(pages: str, target: str) -> bool:
184
211
  return re.search(rf"(?<![0-9.]){head}{pattern(suffix)}(?![0-9a-z_/-]|\.[0-9a-z])", pages) is not None
185
212
 
186
213
 
214
+ def _clean_doi(match: re.Match[str]) -> str:
215
+ return re.sub(r"[.,;:)\]]+$", "", re.sub(r"\s+", "", match.group(0)))
216
+
217
+
218
+ def _same_article(doi: str, target: str) -> bool:
219
+ """``doi`` is the target, or a piece, an extension, a misprint or an older prefix of it."""
220
+ own, own_suffix = _bare(target), _bare(_suffix(target))
221
+ return (own.startswith(_bare(doi)) or _bare(doi).startswith(own)
222
+ or (len(own_suffix) >= SHARED_SUFFIX and _bare(_suffix(doi)) == own_suffix))
223
+
224
+
187
225
  def _other_dois(pages: str, target: str) -> list[str]:
188
226
  """DOIs printed that are not the target, nor a piece, an extension, a misprint or an older prefix of it."""
189
- own, own_suffix = _bare(target), _bare(_suffix(target))
190
- found = [re.sub(r"[.,;:)\]]+$", "", re.sub(r"\s+", "", m.group(0))) for m in _DOI_IN_TEXT.finditer(pages)]
191
- return [doi for doi in found if not own.startswith(_bare(doi)) and not _bare(doi).startswith(own)
192
- and not (len(own_suffix) >= SHARED_SUFFIX and _bare(_suffix(doi)) == own_suffix)]
227
+ return [doi for doi in map(_clean_doi, _DOI_IN_TEXT.finditer(pages)) if not _same_article(doi, target)]
228
+
229
+
230
+ def _about_dois(pages: str) -> list[str]:
231
+ """DOIs the pages label as the article a notice is about: the first DOI after each label."""
232
+ found = []
233
+ for label in _ABOUT_LABEL.finditer(pages):
234
+ doi = _DOI_IN_TEXT.search(pages, label.end(), label.end() + _ABOUT_REACH)
235
+ if doi:
236
+ found.append(_clean_doi(doi))
237
+ return found
193
238
 
194
239
 
195
240
  def _title_before(text: str, title: str) -> bool:
@@ -225,7 +270,13 @@ def evidence(first_pages: str, identifier: str, title: str = "") -> dict | None:
225
270
  chars, at = _letters(front)
226
271
  doi = _doi_named(front, target)
227
272
  found = _title_evidence(front, chars, at, title) if (title or "").strip() else None
273
+ if found is None and doi and _short_title_beside_doi(front, target, title or ""):
274
+ found = "single"
228
275
  others = _other_dois(front, target)
276
+ about = _about_dois(front)
277
+ if not any(_same_article(doi, target) for doi in about):
278
+ # The article a notice discusses is not another article on these pages.
279
+ others = [doi for doi in others if doi not in about]
229
280
  # A notice is itself the requested item when the pages name it (its DOI in the
230
281
  # header, Neurology; its whole title and its DOI, a letter under a "Letter to the
231
282
  # editor" heading) and print no other DOI. A notice about an article prints its
@@ -271,7 +322,14 @@ def assess(first_pages: str, identifier: str, title: str = "", source: str = "")
271
322
  return "mismatch"
272
323
  scan = (sum(char.isalpha() for char in first_pages or "") < SCAN_MAX_LETTERS
273
324
  and not (found and (found["not_article"] or found["other_dois"])))
274
- return "source" if source and scan and _source_names_doi(source, _target_doi(identifier)) else "unverified"
325
+ # Pages that print no DOI at all and are no notice or attachment, for an item named
326
+ # like a section rather than an article (under CLOSE_TITLE letters: Wiley's "Journal
327
+ # Club" and "Issue Information", 2026-11-12): the URL is the evidence, as for a scan.
328
+ # An article's title not printed is a reason for doubt (an issue's front matter at
329
+ # the article's address).
330
+ short = _weight(_letters(normalize_doi_text(_plain_title(title)))[0]) < CLOSE_TITLE
331
+ no_doi = bool(found) and short and not (found["not_article"] or found["doi"] or found["other_dois"] or found["title"])
332
+ return "source" if source and (scan or no_doi) and _source_names_doi(source, _target_doi(identifier)) else "unverified"
275
333
 
276
334
 
277
335
  def first_pages_text(body: bytes) -> str | None:
@@ -0,0 +1,11 @@
1
+ {
2
+ "code": "incommon",
3
+ "name": "InCommon",
4
+ "country": "US",
5
+ "registration_authorities": ["https://incommon.org"],
6
+ "chooser_labels": ["InCommon Federation"],
7
+ "chooser_pattern": "\\bInCommon\\b",
8
+ "discovery_hosts": [],
9
+ "service_domains": ["incommon.org", "incommonfederation.org"],
10
+ "metadata_url": "https://mdq.incommon.org/entities/exports/edugain"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "code": "infed",
3
+ "name": "INFED",
4
+ "country": "IN",
5
+ "registration_authorities": ["http://inflibnet.ac.in"],
6
+ "chooser_labels": ["INFLIBNET Access Management Federation (INFED)"],
7
+ "chooser_pattern": "\\bINFED\\b|\\bINFLIBNET\\s+Access\\s+Management\\s+Federation\\b",
8
+ "discovery_hosts": [],
9
+ "service_domains": ["inflibnet.ac.in"],
10
+ "metadata_url": "https://parichay.inflibnet.ac.in/metadata/edugain.xml"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "code": "liaf",
3
+ "name": "LIAF",
4
+ "country": "LK",
5
+ "registration_authorities": ["https://liaf.ac.lk"],
6
+ "chooser_labels": ["LEARN Identity Access Federation (LIAF)"],
7
+ "chooser_pattern": "\\bLIAF\\b|\\bLEARN\\s+Identity\\s+(?:and\\s+)?Access\\s+Federation\\b",
8
+ "discovery_hosts": [],
9
+ "service_domains": ["liaf.ac.lk"],
10
+ "metadata_url": "https://fr.ac.lk/signedmetadata/LIAF_to_edugain.xml"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "code": "omren",
3
+ "name": "OMREN",
4
+ "country": "OM",
5
+ "registration_authorities": ["http://www.omren.om"],
6
+ "chooser_labels": ["OMREN Identity Federation"],
7
+ "chooser_pattern": "\\bOMREN\\b",
8
+ "discovery_hosts": [],
9
+ "service_domains": ["fed.omren.om", "federation.omren.om"],
10
+ "metadata_url": "https://fed.omren.om/OMREN_export.xml"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "code": "pkifed",
3
+ "name": "PKIFED",
4
+ "country": "PK",
5
+ "registration_authorities": ["https://pkifed.pk"],
6
+ "chooser_labels": ["Pakistan Identity Federation (PKIFED)"],
7
+ "chooser_pattern": "\\bPKIFED\\b|\\bPakistan\\s+Identity\\s+Federation\\b",
8
+ "discovery_hosts": [],
9
+ "service_domains": ["pkifed.pk"],
10
+ "metadata_url": "https://rr.pern.edu.pk/rr3/signedmetadata/federation/PKIFED_eduGAIN/metadata.xml"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "code": "tigerfed",
3
+ "name": "TIGERfed",
4
+ "country": "BD",
5
+ "registration_authorities": ["https://tigerfed.net.bd"],
6
+ "chooser_labels": ["TIGERfed"],
7
+ "chooser_pattern": "\\bTIGERfed\\b",
8
+ "discovery_hosts": [],
9
+ "service_domains": ["tigerfed.net.bd"],
10
+ "metadata_url": "https://fedmanager.tigerfed.net.bd/edugain-export-metadata.xml"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "code": "yetkim",
3
+ "name": "YETKİM",
4
+ "country": "TR",
5
+ "registration_authorities": ["https://yetkim.org.tr/"],
6
+ "chooser_labels": ["YETKİM Identity Federation"],
7
+ "chooser_pattern": "\\bYETK[İI]M\\b",
8
+ "discovery_hosts": [],
9
+ "service_domains": ["yetkim.org.tr"],
10
+ "metadata_url": "http://md.yetkim.org.tr/yetkim-upstream.xml"
11
+ }
@@ -155,8 +155,10 @@ def institutional_configured(config: dict[str, Any]) -> bool:
155
155
  # --------------------------------------------------------------------------- finding
156
156
 
157
157
  def _key(text: str) -> str:
158
- """Case, spaces, hyphens, punctuation and a leading "The" do not count."""
159
- return re.sub(r"[\W_]+", "", re.sub(r"^the\s+", "", str(text or "").casefold().strip()))
158
+ """Case, spaces, hyphens, punctuation and a leading "The" do not count; "&"
159
+ is "and" (a school listed as "Science & Technology", 2026-11-12)."""
160
+ text = re.sub(r"^the\s+", "", str(text or "").casefold().strip())
161
+ return re.sub(r"[\W_]+", "", text.replace("&", " and "))
160
162
 
161
163
 
162
164
  def _host(text: str) -> str:
@@ -180,13 +182,11 @@ class _Found:
180
182
  self.rows[school.entity_id] = (school, exact)
181
183
 
182
184
  def _primary(self) -> None:
183
- """A school also listed in a secondary route (OpenAthens) under the same
184
- domain or name signs in through its federation: that entry goes."""
185
+ """A school also listed in a secondary route (OpenAthens) signs in through
186
+ its federation: that entry goes (``_same_school``)."""
185
187
  primary = [s for s, _ in self.rows.values() if not _secondary(s)]
186
- domains = {d for s in primary for d in s.scopes}
187
- names = {_key(s.name_en) for s in primary}
188
188
  for entity, (school, _) in list(self.rows.items()):
189
- if _secondary(school) and (set(school.scopes) & domains or _key(school.name_en) in names):
189
+ if _secondary(school) and any(_same_school(school, p) for p in primary):
190
190
  del self.rows[entity]
191
191
 
192
192
  def decide(self) -> tuple[School | None, list[School]]:
@@ -203,6 +203,20 @@ class _Found:
203
203
  return None, sorted(partial, key=lambda s: (len(s.name), s.name))
204
204
 
205
205
 
206
+ def _same_school(other: School, school: School) -> bool:
207
+ """``other`` is ``school`` listed again: under its domain or a host of it (its
208
+ library's), or under its name, an abbreviation in brackets aside, with a domain
209
+ of the same country (2026-11-12: two countries' universities share a name)."""
210
+ if any(o == d or o.endswith("." + d) for o in other.scopes for d in school.scopes):
211
+ return True
212
+ name = _key(_BRACKET.sub(" ", other.name_en))
213
+ if not name or name != _key(_BRACKET.sub(" ", school.name_en)):
214
+ return False
215
+ if not (other.scopes and school.scopes):
216
+ return True
217
+ return bool({d.rsplit(".", 1)[-1] for d in other.scopes} & {d.rsplit(".", 1)[-1] for d in school.scopes})
218
+
219
+
206
220
  def _secondary(school: School) -> bool:
207
221
  federation = by_code(school.federation)
208
222
  return bool(federation and federation.secondary)
@@ -213,24 +227,50 @@ _RETIRED = re.compile(r"\bdo not use\b|\btest\b|\blegacy\b", re.I)
213
227
 
214
228
 
215
229
  _PARTS = re.compile(r"\s+[-\u2013\u2014]\s+")
216
- _BRACKETED = re.compile(r"^(.*?)\s*\(([^()]+)\)\s*$")
230
+ _BRACKET = re.compile(r"\(([^()]+)\)")
231
+ # Chinese, Japanese and Korean writing, beside a name in Latin letters.
232
+ _CJK = re.compile(r"[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af][\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af\s・·]*")
217
233
 
218
234
 
219
235
  def _names(titles: Iterable[str]) -> list[str]:
220
236
  """The names a school is listed under, and their parts: "NHU - National
221
237
  Harbour University" (an abbreviation before the name), "北大学 (Kita
222
- University) – OpenAthens" (a second name in brackets, the route after a dash)."""
238
+ University) – OpenAthens" (a second name in brackets, the route after a dash),
239
+ "National Harbour Bay University (NHBU) 海灣大學" (brackets inside, and a name in
240
+ another script beside the English one: OpenAthens in Taiwan, 2026-11-12)."""
223
241
  names = [str(t).strip() for t in titles if str(t or "").strip()]
224
242
  found = list(names)
225
243
  for name in names:
226
244
  for part in _PARTS.split(name):
227
- bracketed = _BRACKETED.match(part.strip())
228
- found += [part.strip(), *([bracketed.group(1).strip(), bracketed.group(2).strip()] if bracketed else [])]
245
+ part = part.strip()
246
+ outside = re.sub(r"\s+", " ", _BRACKET.sub(" ", part)).strip()
247
+ found += [part, outside, *(m.strip() for m in _BRACKET.findall(part))]
248
+ if _CJK.search(outside) and re.search(r"[A-Za-z]{2}", _CJK.sub(" ", outside)):
249
+ found += [m.strip() for m in _CJK.findall(outside)] + [re.sub(r"\s+", " ", _CJK.sub(" ", outside)).strip()]
229
250
  return list(dict.fromkeys(n for n in found if n))
230
251
 
231
252
 
253
+ def _words(text: str) -> list[str]:
254
+ """The words of a name, as ``_key`` compares them."""
255
+ words = [w for w in re.split(r"[\W_]+", str(text or "").casefold().replace("&", " and ")) if w]
256
+ return words[1:] if words[:1] == ["the"] else words
257
+
258
+
259
+ def _listed_inside(text: str, listed_names: Iterable[str]) -> bool:
260
+ """A listed name of two words or more found word for word in what was given:
261
+ a school listed shorter than its full name ("Kita Bay" for "Kita Bay
262
+ University", 2026-11-12), only ever asked about."""
263
+ given = _words(text)
264
+ for name in listed_names:
265
+ part = _words(name)
266
+ if len(part) >= 2 and any(given[i:i + len(part)] == part for i in range(len(given) - len(part) + 1)):
267
+ return True
268
+ return False
269
+
270
+
232
271
  def _matches(given: Iterable[str], listed_names: Iterable[str], scopes: Iterable[str], entity: str) -> tuple[bool, bool]:
233
272
  """(exact, partial) for what was given against one listed school."""
273
+ listed_names = list(listed_names)
234
274
  keys = {_key(n) for n in listed_names} - {""}
235
275
  hosts = {s.lower() for s in scopes if s}
236
276
  exact = partial = False
@@ -240,7 +280,8 @@ def _matches(given: Iterable[str], listed_names: Iterable[str], scopes: Iterable
240
280
  continue
241
281
  if text == entity or key in keys or host in hosts:
242
282
  exact = True
243
- elif any(key in k for k in keys) or any(host and host in h for h in hosts):
283
+ elif (any(key in k for k in keys) or any(host and host in h for h in hosts)
284
+ or _listed_inside(text, listed_names)):
244
285
  partial = True
245
286
  return exact, partial and not exact
246
287
 
@@ -558,7 +558,9 @@ def tracked_download(current: str, output_dir: Any = None, batch: BatchContext |
558
558
  ``content`` (main / supplements / both) is shown as a small label.
559
559
  ``outcome["paused"]`` (a phase text) means the article has not run yet and
560
560
  the batch tries it again later (publisher's hourly limit): nothing is
561
- counted and the window stays open.
561
+ counted and the window stays open; ``outcome["hourly_wait"]`` (publisher,
562
+ limit, until) keeps the window saying so until then, whatever the batch's
563
+ other lane reports meanwhile. The next article clears it.
562
564
  """
563
565
  if batch is None:
564
566
  start_task("机构 PDF 下载", total=1, current=current, phase="进入机构访问")
@@ -568,6 +570,8 @@ def tracked_download(current: str, output_dir: Any = None, batch: BatchContext |
568
570
  current=current, stage="starting", channel="",
569
571
  phase=f"第 {batch.index}/{batch.total} 篇:进入机构访问" if batch.total > 1 else "进入机构访问")
570
572
  _notify_stage("starting", current)
573
+ with _LOCK:
574
+ _STATE.pop("hourly_wait", None) # this article runs: no longer held by the hourly limit
571
575
  update(content=content if content in ("main", "supplements", "both") else "main")
572
576
  if output_dir:
573
577
  set_output_dir(output_dir)
@@ -578,7 +582,8 @@ def tracked_download(current: str, output_dir: Any = None, batch: BatchContext |
578
582
  if outcome.get("paused") and batch is not None:
579
583
  with _LOCK:
580
584
  if _STATE:
581
- _STATE.update(awaiting_next=True, phase=str(outcome["paused"]))
585
+ _STATE.update(awaiting_next=True, phase=str(outcome["paused"]),
586
+ **({"hourly_wait": outcome["hourly_wait"]} if outcome.get("hourly_wait") else {}))
582
587
  _write_state()
583
588
  else:
584
589
  _finish_download(outcome, current, batch, content)
@@ -840,12 +845,19 @@ def read_snapshot() -> tuple[dict[str, Any] | None, str]:
840
845
  return None, "invalid_state"
841
846
  if state.get("status") == "running" and state.get("awaiting_next") is True:
842
847
  # Between batch items no process owns the task; only time ends the wait.
848
+ allowed = BATCH_WAIT_STALE_SECONDS
843
849
  try:
844
850
  ts = datetime.fromisoformat(str(state.get("updated_at")))
845
851
  waited = (datetime.now(ts.tzinfo) - ts).total_seconds()
852
+ # Held by the hourly limit the user set: the wait lasts until its time (up
853
+ # to an hour; read as stopped after 30 minutes, Windows 2026-11-13).
854
+ hold = state.get("hourly_wait")
855
+ until = hold.get("until") if isinstance(hold, dict) else None
856
+ if isinstance(until, (int, float)) and not isinstance(until, bool):
857
+ allowed = max(allowed, until - ts.timestamp() + BATCH_WAIT_STALE_SECONDS)
846
858
  except Exception:
847
859
  waited = 0.0
848
- if waited > BATCH_WAIT_STALE_SECONDS:
860
+ if waited > allowed:
849
861
  return {**state, "status": "interrupted", "stage": "interrupted", "awaiting_next": False,
850
862
  "phase": "批量下载已停止,结果未确认", "attention": {}}, "available"
851
863
  return state, "available"
@@ -10,6 +10,7 @@ from __future__ import annotations
10
10
  import os
11
11
  import re
12
12
  import sys
13
+ import time
13
14
  from datetime import datetime
14
15
  from typing import Any
15
16
 
@@ -283,6 +284,24 @@ def paper_lists(listed: Any, state: dict[str, Any] | None) -> dict[str, Any]:
283
284
  return {"ok": first_open(saved), "failed": missing, "left": first_open(left)}
284
285
 
285
286
 
287
+ # The longest publisher name the hourly-limit notice keeps on one line, in zh and en,
288
+ # with a limit of 1000 and 23:59 (measured in the capsule: "Copernicus", 2026-11-12).
289
+ HOLD_NAME_MAX = 10
290
+
291
+
292
+ def _hourly_hold(state: dict[str, Any], now: float) -> tuple[str, int | None, str] | None:
293
+ """The hourly limit the user set per publisher holding the school's downloads:
294
+ (publisher, limit, "HH:MM" it goes on), until that time (2026-11-12)."""
295
+ raw = state.get("hourly_wait")
296
+ if not isinstance(raw, dict):
297
+ return None
298
+ until, limit = raw.get("until"), raw.get("limit")
299
+ if not isinstance(until, (int, float)) or isinstance(until, bool) or until <= now:
300
+ return None
301
+ limit = limit if isinstance(limit, int) and not isinstance(limit, bool) and limit > 0 else None
302
+ return str(raw.get("publisher") or ""), limit, time.strftime("%H:%M", time.localtime(until))
303
+
304
+
286
305
  def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
287
306
  """Everything the capsule shows for one snapshot of the progress file.
288
307
 
@@ -364,6 +383,18 @@ def view(state: dict[str, Any] | None, now: float) -> dict[str, Any]:
364
383
  notice = str(raw.get("text") or "")
365
384
  except (TypeError, ValueError):
366
385
  pass
386
+ # Held by the hourly limit the user set: the capsule and the card say so, and that
387
+ # it is the user's setting, not the publisher's (2026-11-12).
388
+ hold = _hourly_hold(state, now) if running and not attention else None
389
+ if hold:
390
+ name, limit, resume = hold
391
+ part, publisher = "已达每小时上限", f"{resume} 继续"
392
+ # One line on the card in either language: a longer publisher name (or a site's
393
+ # host) is left out; the status line above already says what holds.
394
+ name = name if len(name) <= HOLD_NAME_MAX else ""
395
+ notice = (f"{name} 已达设置的每小时 {limit} 篇,{resume} 继续" if name and limit
396
+ else f"已达设置的每小时 {limit} 篇,{resume} 继续" if limit
397
+ else f"已达设置的每小时上限,{resume} 继续")
367
398
 
368
399
  return {
369
400
  "mode": mode, "tone": tone, "headline": headline,
@@ -123,9 +123,13 @@ def school_download(
123
123
  if result.get("error_type") == "access_blocked":
124
124
  outcome["failure_phase"] = "网站已阻止当前访问,未取得 PDF"
125
125
  if result.get("error_type") == "rate_limited":
126
- resume = time.strftime("%H:%M", time.localtime(time.time() + int(result.get("retry_after_sec") or 0)))
126
+ until = time.time() + int(result.get("retry_after_sec") or 0)
127
+ resume = time.strftime("%H:%M", time.localtime(until))
127
128
  outcome["paused"] = outcome["failure_phase"] = (
128
129
  f"{result.get('publisher')} 一小时内已打开 {result.get('limit')} 篇(每小时上限),{resume} 继续这一篇")
130
+ # The window says so until then, beside the other lane's lines (2026-11-12).
131
+ outcome["hourly_wait"] = {"publisher": str(result.get("publisher") or ""),
132
+ "limit": result.get("limit"), "until": until}
129
133
  if result.get("error_type") == "paywall" or result.get("action") == "login_required":
130
134
  result["agent_hint"] = (
131
135
  "此论文需要机构登录。请让用户在弹出的下载浏览器窗口里完成登录或人工验证后重试;"
@@ -201,6 +205,16 @@ async def school_close_batch_browser() -> str:
201
205
  return json.dumps({"closed": True})
202
206
 
203
207
 
208
+ @mcp_app.tool()
209
+ async def school_keep_session() -> str:
210
+ """While a serial batch waits (the publisher's hourly limit the user set), load the
211
+ last paper's article page again in the batch's window, so the publisher's
212
+ institutional session does not lapse. Opens no browser; does nothing after a paper
213
+ that did not save its PDF. Answers {"kept": true} or {"kept": false, "reason": ...}."""
214
+ result = await asyncio.get_running_loop().run_in_executor(_batch_worker, _batch_browser.keep_session)
215
+ return json.dumps(result)
216
+
217
+
204
218
  @mcp_app.tool()
205
219
  def school_batch_progress(
206
220
  batch_id: str,
@@ -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.6.1"
7
+ version: "0.6.2"
8
8
  ---
9
9
 
10
10
  # 文献检索与下载(paper-search)
@@ -13,6 +13,7 @@ metadata:
13
13
 
14
14
  ## 回复用户
15
15
 
16
+ - 用用户提问的语言回复。本 Skill 用中文写成,引号里的问法只表达意思,按用户的语言说;命令输出和程序提示里的中文说明,翻成用户的语言再转述。论文标题、正文原句、DOI、期刊名、命令和文件路径保持原样。
16
17
  - 只说结果和下一步,几句话说完;安装、配置的汇报不用表格。
17
18
  - 命令输出里的安装路径、版本号、依赖数、哈希、配置细节不复述,用户问起或排障时再说。
18
19
  - 只做用户要的事和本 Skill 写明的步骤,不额外跑测试、查包信息或翻找文件。
@@ -1,6 +1,6 @@
1
1
  # 学校订阅下载:各学术身份联盟支持情况
2
2
 
3
- 本表说明学校订阅下载能经哪些学术身份联盟登录(截至 2026-11-11)。“支持”是说:用户说出学校名称,程序能查出学校所属的联盟,并在出版社网站上自动选好联盟和学校,走到学校的登录页。登录之后能否下到全文,取决于学校的订阅,以及出版社是否给这所学校开通了学校账号登录。
3
+ 本表说明学校订阅下载能经哪些学术身份联盟登录(截至 2026-11-12)。“支持”是说:用户说出学校名称,程序能查出学校所属的联盟,并在出版社网站上自动选好联盟和学校,走到学校的登录页。登录之后能否下到全文,取决于学校的订阅,以及出版社是否给这所学校开通了学校账号登录。
4
4
 
5
5
  各国的学术身份联盟通过 eduGAIN 互联,出版社借此认可各国学校的账号;OpenAthens 是跨国的机构登录服务,没有加入本国联盟的学校不少经它登录。
6
6
 
@@ -21,11 +21,27 @@
21
21
  | 日本 | GakuNin(学認) | 学術認証フェデレーション(Academic Access Management Federation in Japan) | 约 170 | ✓ | 东京大学、大阪大学、东北大学、庆应义塾大学、早稻田大学 |
22
22
  | 韩国 | KAFE | Korean Access Federation | 27 | ✓ | KAIST、延世大学、浦项工科大学、成均馆大学 |
23
23
  | 马来西亚 | SIFULAN | SIFULAN Malaysian Access Federation | 约 150 | ✓ | 马来西亚理科大学、博特拉大学 |
24
- | 跨地区 | OpenAthens | OpenAthens 机构登录服务 | — | ✓ | 马来亚大学、朱拉隆功大学、菲律宾大学 Diliman、名古屋大学、台湾大学 |
24
+ | 印度 | INFED | INFLIBNET Access Management Federation | 约 390 | ✓ | 印度理工学院德里分校 |
25
+ | 土耳其 | YETKİM | YETKİM Identity Federation | 约 170 | ✓ | 哈杰泰佩大学、中东技术大学、海峡大学、伊斯坦布尔大学 |
26
+ | 斯里兰卡 | LIAF | LEARN Identity Access Federation | 31 | ✓ | 科伦坡大学 |
27
+ | 孟加拉 | TIGERfed | Trust, Identity and Group management for Education and Research Federation | 30 | ✓ | 孟加拉工程技术大学 |
28
+ | 巴基斯坦 | PKIFED | Pakistan Identity Federation | 8 | ✓ | COMSATS 大学伊斯兰堡分校、巴基斯坦国立科技大学、真纳大学 |
29
+ | 阿曼 | OMREN | OMREN Identity Federation | 约 30 | ○ | — |
30
+ | 跨地区 | OpenAthens | OpenAthens 机构登录服务 | — | ✓ | 马来亚大学、朱拉隆功大学、菲律宾大学 Diliman、名古屋大学、台湾大学、阳明交通大学、台湾师范大学 |
25
31
 
26
32
  - 联盟内学校数取自 eduGAIN 登记的身份提供方数量,一所学校可能登记不止一个。
27
33
  - OpenAthens 不是某个国家的联盟,是跨国的机构登录服务;学校同时有本国联盟入口时,程序优先用联盟的。
34
+ - 台湾没有加入 eduGAIN 的联盟,台湾的学校经 OpenAthens 登录;没有接入 OpenAthens 的台湾学校暂时无法使用。
35
+ - 巴基斯坦有一百多所学校经 PERN 全国共用入口登录,联盟名单里只有它们的域名:按校名查不到时,用学校官网域名配置。
36
+ - 阿曼 OMREN 交给 eduGAIN 的学校名单目前已过期,阿曼的学校暂时查不到;名单恢复后无需改动即可使用。
37
+ - 学校登录服务器连不上,或学校认证服务器拒绝出版社的登录请求时,程序立即结束并说明“学校登录系统出错”;这类情况要由学校处理。
38
+
39
+ ## 美洲
40
+
41
+ | 地区 | 联盟 | 全称 | 联盟内学校数 | 状态 | 已实测的学校 |
42
+ | --- | --- | --- | --- | --- | --- |
43
+ | 美国 | InCommon | InCommon Federation | 约 590 | ✓ | 斯坦福大学、麻省理工学院、耶鲁大学、普林斯顿大学、哥伦比亚大学、加州大学伯克利分校、加州大学洛杉矶分校、加州大学旧金山分校、密歇根大学、宾夕法尼亚大学、杜克大学、华盛顿大学、纽约大学、康奈尔大学、约翰斯·霍普金斯大学 |
28
44
 
29
45
  ## 计划中
30
46
 
31
- 美国(InCommon)、英国(UK federation)、澳大利亚(AAF)、欧洲各国联盟,之后是 eduGAIN 里的其他国家。
47
+ 英国(UK federation)、澳大利亚(AAF)、欧洲各国联盟,之后是 eduGAIN 里的其他国家。
@@ -53,8 +53,8 @@ paper-search school login --doi <学校订阅的一篇文章的 DOI>
53
53
  paper-search-school setup --institution "用户说的校名" [--also-name "学校的英文正式名称"]
54
54
  ```
55
55
 
56
- - 目前支持中国内地和澳门(CARSI)、香港(HKAF)、新加坡(SGAF)、日本(GakuNin)、韩国(KAFE)、马来西亚(SIFULAN)的学术身份联盟,以及只经 OpenAthens 登录的学校。`--institution` 可以是校名(任何语言)、学校域名或 entityID;后端在各联盟的学校名单里查,确定是哪一所才保存,并保存它所属的联盟。
57
- - 联盟名单里的校名是当地语言和英文(中国内地、澳门有中文,日本有日文,香港、韩国、新加坡、马来西亚多只有英文)。用户说的校名不是这两种时,加 `--also-name` 给出学校的英文正式名称;不确定英文名就不加。
56
+ - 目前支持中国内地和澳门(CARSI)、香港(HKAF)、新加坡(SGAF)、日本(GakuNin)、韩国(KAFE)、马来西亚(SIFULAN)、印度(INFED)、土耳其(YETKİM)、斯里兰卡(LIAF)、孟加拉(TIGERfed)、巴基斯坦(PKIFED)、阿曼(OMREN)、美国(InCommon)的学术身份联盟,以及只经 OpenAthens 登录的学校。`--institution` 可以是校名(任何语言)、学校域名或 entityID;后端在各联盟的学校名单里查,确定是哪一所才保存,并保存它所属的联盟。
57
+ - 联盟名单里的校名是当地语言和英文(中国内地、澳门有中文,日本有日文,土耳其有土耳其文,香港、韩国、新加坡、马来西亚、南亚和美国多只有英文)。用户说的校名不是这两种时,加 `--also-name` 给出学校的英文正式名称;不确定英文名就不加。
58
58
  - 返回 `school_ambiguous` 时,把 `candidates`(含学校名、联盟、域名)列给用户选,再用所选学校的 `entity_id` 作为 `--institution` 重新运行;只有一个候选也要问,那是名字不完全一致的学校。`school_not_found` 时请用户换成学校正式名称、英文名或学校域名,仍找不到就按回复里的 `reasons` 如实说明:这所学校可能没有接入学术身份联盟或 OpenAthens,学校订阅下载无法为它登录;`federation_not_supported` 是找到了学校但它所属的联盟还不支持,如实告诉用户;`school_list_unavailable` 是名单取不到,稍后重试。
59
59
  - `--carsi --institution` 只在 CARSI 名单里查(错误码 `carsi_school_*`);查 CARSI 名单:`paper-search-school setup --list-carsi-schools 关键词`。
60
60
  - `setup --check` 的 `school` 项为 `missing` 时,说明只存了学校名,按提示重新运行上面的命令。