papersearch 0.5.11 → 0.5.13

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 (62) hide show
  1. package/README.en.md +3 -3
  2. package/README.md +3 -3
  3. package/carsi/paper_search_carsi/adapters/bmj/__init__.py +58 -1
  4. package/carsi/paper_search_carsi/assets/api_keys.json +16 -16
  5. package/carsi/paper_search_carsi/assets/capsule_en.json +3 -3
  6. package/carsi/paper_search_carsi/browser/challenge_interaction.py +20 -6
  7. package/carsi/paper_search_carsi/download_diagnostics.py +1 -0
  8. package/carsi/paper_search_carsi/engine/batch_institution.py +14 -4
  9. package/carsi/paper_search_carsi/engine/batch_login.py +13 -0
  10. package/carsi/paper_search_carsi/engine/bridge.py +9 -0
  11. package/carsi/paper_search_carsi/login_routes.py +62 -0
  12. package/dist/capabilities/metadata-search/handler.d.ts +10 -2
  13. package/dist/capabilities/metadata-search/handler.d.ts.map +1 -1
  14. package/dist/capabilities/metadata-search/handler.js +104 -73
  15. package/dist/capabilities/metadata-search/handler.js.map +1 -1
  16. package/dist/capabilities/metadata-search/schemas.d.ts +18 -7
  17. package/dist/capabilities/metadata-search/schemas.d.ts.map +1 -1
  18. package/dist/capabilities/metadata-search/schemas.js +10 -4
  19. package/dist/capabilities/metadata-search/schemas.js.map +1 -1
  20. package/dist/capabilities/metadata-search/tools.d.ts +18 -2
  21. package/dist/capabilities/metadata-search/tools.d.ts.map +1 -1
  22. package/dist/capabilities/metadata-search/tools.js +11 -5
  23. package/dist/capabilities/metadata-search/tools.js.map +1 -1
  24. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +2 -2
  25. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  26. package/dist/capabilities/pdf-discovery/batch.d.ts +6 -3
  27. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  28. package/dist/capabilities/pdf-discovery/batch.js +37 -18
  29. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  30. package/dist/capabilities/pdf-discovery/batchPapers.d.ts +15 -1
  31. package/dist/capabilities/pdf-discovery/batchPapers.d.ts.map +1 -1
  32. package/dist/capabilities/pdf-discovery/batchPapers.js +39 -3
  33. package/dist/capabilities/pdf-discovery/batchPapers.js.map +1 -1
  34. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +1 -1
  35. package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
  36. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
  37. package/dist/capabilities/pdf-discovery/handler.js +2 -2
  38. package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
  39. package/dist/capabilities/pdf-discovery/outputLayout.d.ts +24 -10
  40. package/dist/capabilities/pdf-discovery/outputLayout.d.ts.map +1 -1
  41. package/dist/capabilities/pdf-discovery/outputLayout.js +102 -15
  42. package/dist/capabilities/pdf-discovery/outputLayout.js.map +1 -1
  43. package/dist/cli.js +3 -0
  44. package/dist/cli.js.map +1 -1
  45. package/dist/infrastructure/http/ErrorHandler.d.ts +3 -1
  46. package/dist/infrastructure/http/ErrorHandler.d.ts.map +1 -1
  47. package/dist/infrastructure/http/ErrorHandler.js +5 -3
  48. package/dist/infrastructure/http/ErrorHandler.js.map +1 -1
  49. package/dist/management/reports/index.d.ts +2 -0
  50. package/dist/management/reports/index.d.ts.map +1 -1
  51. package/dist/management/reports/index.js +10 -4
  52. package/dist/management/reports/index.js.map +1 -1
  53. package/dist/management/skills/autoSync.d.ts +11 -0
  54. package/dist/management/skills/autoSync.d.ts.map +1 -1
  55. package/dist/management/skills/autoSync.js +75 -12
  56. package/dist/management/skills/autoSync.js.map +1 -1
  57. package/package.json +5 -1
  58. package/skills/paper-search/SKILL.md +5 -1
  59. package/skills/paper-search/references/browser-download.md +3 -2
  60. package/skills/paper-search/references/capability-routing.md +9 -1
  61. package/skills/paper-search/references/management-layer.md +2 -0
  62. package/skills/paper-search/references/publisher-support.md +1 -1
package/README.en.md CHANGED
@@ -105,7 +105,7 @@ Once set up, mention the PaperSearch Skill and say what you want to search for,
105
105
  <p align="center"><img src="assets/results.en.webp" width="840" alt="Results: the chat lists the 6 papers saved and how many supplementary files each has; the download folder holds one folder per paper, supplementary files in supplements/"></p>
106
106
 
107
107
  - Search results, snippets, journal metrics and citations come back in the conversation.
108
- - Each download gets its own `YYYYMMDD-HHmmss_PaperSearchDownload` folder inside your download folder: main texts alone lie directly in it; with supplementary files each paper has a folder, its supplementary files in supplements/. You are told why any paper was not obtained.
108
+ - Each download gets its own `YYYYMMDD-HHmmss_PaperSearchDownload` folder inside your download folder: PDFs lie directly in it; a paper whose supplementary files were saved gets a folder of its own, its files in supplements/. You are told why any paper was not obtained.
109
109
 
110
110
  ## Optional setup
111
111
 
@@ -171,13 +171,14 @@ paper-search carsi status --format text # check that it is ready
171
171
 
172
172
  Keys fall into four groups by what they are for. Get the key you need (an email needs no sign-up) and enter it any of the ways in [Quick start step 3](#3-add-api-keys-when-you-need-them).
173
173
 
174
- #### Journal metrics, full-text snippets and free full texts (recommended)
174
+ #### Recommended
175
175
 
176
176
  | Feature | Key | Where to get it |
177
177
  |---|---|---|
178
178
  | Look up impact factors and quartiles | `EASYSCHOLAR_KEY` | [EasyScholar](https://www.easyscholar.cc/) ([guide](https://docs.qq.com/aio/DTUxwZ3hUckVtZVJN), in Chinese) |
179
179
  | Search full-text snippets | `SEMANTIC_SCHOLAR_API_KEY` | [Semantic Scholar](https://www.semanticscholar.org/product/api) ([guide](https://docs.qq.com/aio/DTW9RdFVHc2hJUmpx), in Chinese) |
180
180
  | Find free full texts when downloading | `PAPER_SEARCH_UNPAYWALL_EMAIL` | No sign-up ([Unpaywall: about](https://unpaywall.org/products/api)) |
181
+ | Search papers, check that DOIs are real | `CROSSREF_MAILTO` | No sign-up ([Crossref: about](https://www.crossref.org/documentation/retrieve-metadata/rest-api/tips-for-using-the-crossref-rest-api/)) |
181
182
 
182
183
  #### Subscribed full texts (optional)
183
184
 
@@ -199,7 +200,6 @@ Keys fall into four groups by what they are for. Get the key you need (an email
199
200
 
200
201
  | Source | Key | Where to get it |
201
202
  |---|---|---|
202
- | Crossref (search papers, check that DOIs are real) | `CROSSREF_MAILTO` | No sign-up ([about](https://www.crossref.org/documentation/retrieve-metadata/rest-api/tips-for-using-the-crossref-rest-api/)) |
203
203
  | PubMed | `PUBMED_API_KEY` | [NCBI](https://ncbiinsights.ncbi.nlm.nih.gov/2017/11/02/new-api-keys-for-the-e-utilities/) |
204
204
  | OpenAlex (all citing papers past 10,000) | `OPENALEX_API_KEY` | [OpenAlex](https://openalex.org/settings/api) |
205
205
  | CORE | `CORE_API_KEY` | [CORE](https://core.ac.uk/services/api) |
package/README.md CHANGED
@@ -105,7 +105,7 @@ AI 会先问你要不要装 PaperSearch 的命令行程序,你同意后装好
105
105
  <p align="center"><img src="assets/results.webp" width="840" alt="拿到结果:对话里列出下好的 6 篇和各自的补充材料数量;带补充材料时下载文件夹里每篇一个文件夹,补充材料在 supplements/ 里"></p>
106
106
 
107
107
  - 检索、正文片段、期刊指标和引文,直接在对话里列给你。
108
- - 每次下载在下载文件夹里新建一个 `年月日-时分秒_PaperSearchDownload` 文件夹:只下正文时 PDF 直接放在里面,带补充材料时每篇一个文件夹,补充材料在 supplements/ 里;没拿到的篇目告诉你原因。
108
+ - 每次下载在下载文件夹里新建一个 `年月日-时分秒_PaperSearchDownload` 文件夹:PDF 直接放在里面,取到了补充材料的论文才单独一个文件夹,补充材料在 supplements/ 里;没拿到的篇目告诉你原因。
109
109
 
110
110
  ## 可选配置
111
111
 
@@ -171,13 +171,14 @@ paper-search carsi status --format text # 查看是否装好
171
171
 
172
172
  按用途分四类,需要哪类就申请对应的 key(邮箱直接填,不用申请),再用[快速开始第 3 步](#3-按需填-api-key)里的任一方式填入。
173
173
 
174
- #### 查期刊、搜正文、找免费全文(推荐配置)
174
+ #### 推荐配置
175
175
 
176
176
  | 功能 | 要填的 key | 去哪里申请 |
177
177
  |---|---|---|
178
178
  | 查影响因子和分区 | `EASYSCHOLAR_KEY` | [EasyScholar](https://www.easyscholar.cc/)([申请教程](https://docs.qq.com/aio/DTUxwZ3hUckVtZVJN)) |
179
179
  | 搜正文片段 | `SEMANTIC_SCHOLAR_API_KEY` | [Semantic Scholar](https://www.semanticscholar.org/product/api)([申请教程](https://docs.qq.com/aio/DTW9RdFVHc2hJUmpx)) |
180
180
  | 下载时找免费全文 | `PAPER_SEARCH_UNPAYWALL_EMAIL` | 不用申请([Unpaywall 说明](https://unpaywall.org/products/api)) |
181
+ | 检索论文、核对 DOI 是否真实 | `CROSSREF_MAILTO` | 不用申请([Crossref 说明](https://www.crossref.org/documentation/retrieve-metadata/rest-api/tips-for-using-the-crossref-rest-api/)) |
181
182
 
182
183
  #### 下载订阅全文(非必须)
183
184
 
@@ -199,7 +200,6 @@ paper-search carsi status --format text # 查看是否装好
199
200
 
200
201
  | 来源 | 要填的 key | 去哪里申请 |
201
202
  |---|---|---|
202
- | Crossref(检索论文、核对 DOI 是否真实) | `CROSSREF_MAILTO` | 不用申请([说明](https://www.crossref.org/documentation/retrieve-metadata/rest-api/tips-for-using-the-crossref-rest-api/)) |
203
203
  | PubMed | `PUBMED_API_KEY` | [NCBI](https://ncbiinsights.ncbi.nlm.nih.gov/2017/11/02/new-api-keys-for-the-e-utilities/) |
204
204
  | OpenAlex(被引超过 1 万篇时列全) | `OPENALEX_API_KEY` | [OpenAlex](https://openalex.org/settings/api) |
205
205
  | CORE | `CORE_API_KEY` | [CORE](https://core.ac.uk/services/api) |
@@ -3,20 +3,77 @@
3
3
  Without access the article page offers the article for sale ("Buy this
4
4
  article", an offer of the shared access rule). The institution login is HighWire's "Log in via Institution", a
5
5
  Shibboleth discovery page on the journal's own host (``/login/shibboleth``).
6
+
7
+ Supplementary files are linked in the full text, in ``div.supplementary-material``:
8
+ ``/content/<journal>/<volume>/<issue>/<page>/DC<n>/embed/inline-supplementary-material-<m>.<ext>``
9
+ for the article at ``/content/<volume>/<issue>/<page>`` (BJSM, BMJ Open, 2026-11-11).
6
10
  """
7
11
  from __future__ import annotations
8
12
 
13
+ import re
9
14
  from typing import Any
10
15
  from urllib.parse import urljoin, urlparse
11
16
 
17
+ from ...browser.driver import is_driver_error
12
18
  from ...engine.batch_common import open_page
13
- from ..base import PublisherAdapter, register
19
+ from ..base import PublisherAdapter, SupplementLink, register
20
+
21
+ # The full text's body: its sections or paragraphs (the page wraps it in .highwire-markup, 2026-11-11).
22
+ _FULL_TEXT = ".article.fulltext-view .section, .article.fulltext-view p"
23
+ _SUPPLEMENT_ROWS_JS = """() => ({
24
+ fullText: !!document.querySelector('""" + _FULL_TEXT + """'),
25
+ rows: [...document.querySelectorAll('a[href]')].map(a => ({
26
+ href: a.href,
27
+ label: (a.closest('.supplementary-material')?.textContent || a.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 240),
28
+ supplement: !!a.closest('.supplementary-material'),
29
+ })),
30
+ })"""
31
+ _DC_FILE = re.compile(r"/content/[^/]+/(?P<article>.+)/DC\d+/embed/[^/]+\.[A-Za-z0-9]{1,8}")
32
+ _ARTICLE = re.compile(r"/content/(?P<article>.+?)(?:\.(?:full|abstract|long|full-text))?/?")
33
+
34
+
35
+ def supplement_links_from_page(data: Any, page_url: str) -> list[SupplementLink] | None:
36
+ """The article's supplementary files, or None while its full text is not shown:
37
+ an abstract page lists none, which says nothing about the article."""
38
+ if not isinstance(data, dict) or not data.get("fullText"):
39
+ return None
40
+ page = urlparse(page_url)
41
+ host = (page.hostname or "").lower()
42
+ article = _ARTICLE.fullmatch(page.path)
43
+ links: list[SupplementLink] = []
44
+ for row in data.get("rows") or []:
45
+ if not isinstance(row, dict):
46
+ continue
47
+ target = urlparse(str(row.get("href") or ""))
48
+ found = _DC_FILE.fullmatch(target.path)
49
+ if (target.scheme != "https" or (target.hostname or "").lower() != host or not host.endswith("bmj.com")
50
+ or not found):
51
+ continue
52
+ # This article's files only: its own path, or at least its supplementary-material block.
53
+ if article and found.group("article") != article.group("article"):
54
+ continue
55
+ if not article and not row.get("supplement"):
56
+ continue
57
+ url = target._replace(query="", fragment="").geturl()
58
+ if url not in {link.url for link in links}:
59
+ links.append(SupplementLink(url, str(row.get("label") or "")))
60
+ return links
14
61
 
15
62
 
16
63
  @register
17
64
  class BMJAdapter(PublisherAdapter):
18
65
  publisher = "bmj"
19
66
 
67
+ def supplement_links(self, page: Any, doi: str) -> list[SupplementLink] | None:
68
+ if not (urlparse(str(getattr(page, "url", "") or "")).hostname or "").lower().endswith("bmj.com"):
69
+ return None
70
+ try: # the full text renders after the page has loaded
71
+ page.wait_for_selector(_FULL_TEXT, timeout=10_000)
72
+ except Exception as exc:
73
+ if not is_driver_error(exc, "TimeoutError"):
74
+ raise
75
+ return supplement_links_from_page(page.evaluate(_SUPPLEMENT_ROWS_JS), str(page.url))
76
+
20
77
  def open_institution_entry(self, page: Any, result: Any) -> bool | None:
21
78
  """HighWire's "Log in via Institution"; the login menu also holds
22
79
  personal and society logins, which are never used."""
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "groups": [
3
3
  {
4
- "title": "查期刊、搜正文、找免费全文(推荐配置)",
4
+ "title": "推荐配置",
5
5
  "services": [
6
6
  {
7
7
  "id": "easyscholar",
@@ -45,6 +45,21 @@
45
45
  "kind": "email"
46
46
  }
47
47
  ]
48
+ },
49
+ {
50
+ "id": "crossref",
51
+ "name": "Crossref",
52
+ "use": "检索论文、核对 DOI 是否真实",
53
+ "note": "填你常用的邮箱就行,不用注册",
54
+ "url": "https://www.crossref.org/documentation/retrieve-metadata/rest-api/tips-for-using-the-crossref-rest-api/",
55
+ "signup_label": "说明",
56
+ "keys": [
57
+ {
58
+ "key": "CROSSREF_MAILTO",
59
+ "label": "email",
60
+ "kind": "email"
61
+ }
62
+ ]
48
63
  }
49
64
  ]
50
65
  },
@@ -109,21 +124,6 @@
109
124
  {
110
125
  "title": "检索更快、更稳定(非必须)",
111
126
  "services": [
112
- {
113
- "id": "crossref",
114
- "name": "Crossref",
115
- "use": "检索论文、核对 DOI 是否真实",
116
- "note": "填你常用的邮箱就行,不用注册",
117
- "url": "https://www.crossref.org/documentation/retrieve-metadata/rest-api/tips-for-using-the-crossref-rest-api/",
118
- "signup_label": "说明",
119
- "keys": [
120
- {
121
- "key": "CROSSREF_MAILTO",
122
- "label": "email",
123
- "kind": "email"
124
- }
125
- ]
126
- },
127
127
  {
128
128
  "id": "pubmed",
129
129
  "name": "PubMed",
@@ -175,7 +175,6 @@
175
175
  "等学校登录超时": "School login timed out",
176
176
  "网站人机验证拦截": "Blocked by bot check",
177
177
  "网站拦截了当前网络": "Site blocked network",
178
- "网站暂不支持附录": "Supp. not supported here",
179
178
  "认证入口未注册": "Login entry unregistered",
180
179
  "需要学校登录": "School login needed",
181
180
  "页面处理超时": "Page timed out",
@@ -275,12 +274,13 @@
275
274
  "被拒绝:Unpaywall 不接受这个邮箱,请填你自己常用的邮箱": "Rejected by Unpaywall: use your own email",
276
275
  "可以用:已走 Crossref 优先通道": "Works: Crossref polite pool",
277
276
  "Crossref 没有认这个邮箱,仍走普通通道": "Crossref didn't take it: public pool",
278
- "查期刊、搜正文、找免费全文(推荐配置)": "Journals, snippets, free texts (recommended)",
277
+ "推荐配置": "Recommended",
279
278
  "下载订阅全文(非必须)": "Subscribed texts (optional)",
280
279
  "检索更快、更稳定(非必须)": "Faster, steady search (optional)",
281
280
  "下载时找免费全文": "Finds free full texts",
282
281
  "检索论文、核对 DOI 是否真实": "Search papers; check DOIs are real",
283
- "填你常用的邮箱就行,不用注册": "Your usual email will do; no sign-up"
282
+ "填你常用的邮箱就行,不用注册": "Your usual email will do; no sign-up",
283
+ "网站暂不支持自动下载附录": "No supp. rule; get by hand"
284
284
  },
285
285
  "patterns": [
286
286
  [
@@ -72,15 +72,25 @@ _NAVIGATED = ("frame was detached", "frame has been detached", "element is not a
72
72
  "execution context was destroyed")
73
73
 
74
74
 
75
+ # The longest one read of a verification page may take. After its checkbox the page
76
+ # can hang between two documents: one read waited 48 s and the article's page budget
77
+ # ran out before the page it led to opened (BMJ on Windows, 2026-11-11).
78
+ READ_LIMIT_SEC = 5
79
+
80
+
75
81
  def is_image_verification(page: Any) -> bool:
76
82
  """Image puzzles expose controls but may have no readable instructions."""
77
83
  from .driver import Error
84
+ from .watchdog import CallAbandoned, call_limit
78
85
 
79
86
  try:
80
- return page.evaluate("""() => document.title.trim().toLowerCase() === 'human verification'
81
- && !document.querySelector('meta[name="citation_doi"]')
82
- && [...document.querySelectorAll('button, [role="button"], canvas, iframe')].some(el =>
83
- el.getClientRects().length > 0)""") is True
87
+ with call_limit(READ_LIMIT_SEC):
88
+ return page.evaluate("""() => document.title.trim().toLowerCase() === 'human verification'
89
+ && !document.querySelector('meta[name="citation_doi"]')
90
+ && [...document.querySelectorAll('button, [role="button"], canvas, iframe')].some(el =>
91
+ el.getClientRects().length > 0)""") is True
92
+ except CallAbandoned:
93
+ return False # between two documents: the next check reads the one that opens
84
94
  except Error as exc:
85
95
  # A passed verification navigates while it is being read (Wiley and
86
96
  # ScienceDirect on Chrome, 2026-11-07): no puzzle on a page that is gone.
@@ -101,6 +111,7 @@ def needs_manual_verification(page: Any) -> bool:
101
111
  def has_visible_recaptcha(page: Any) -> bool:
102
112
  """Detect a reCAPTCHA prompt that remains after the outer page changes."""
103
113
  from .driver import Error
114
+ from .watchdog import CallAbandoned, call_limit
104
115
 
105
116
  for frame in page.frames:
106
117
  parsed = urlsplit(str(frame.url or ""))
@@ -109,8 +120,11 @@ def has_visible_recaptcha(page: Any) -> bool:
109
120
  or not parsed.path.startswith(("/recaptcha/api2/", "/recaptcha/enterprise/"))):
110
121
  continue
111
122
  try:
112
- if frame.frame_element().is_visible():
113
- return True
123
+ with call_limit(READ_LIMIT_SEC):
124
+ if frame.frame_element().is_visible():
125
+ return True
126
+ except CallAbandoned:
127
+ continue # the frame is going away with its page (``READ_LIMIT_SEC``)
114
128
  except Error as exc:
115
129
  if not any(text in str(exc).lower() for text in (
116
130
  "frame was detached", "frame has been detached", "element is not attached",
@@ -37,6 +37,7 @@ pdf_captured saved_pending_verification route_failed access_ready
37
37
  """.split())
38
38
  _EVENTS = frozenset("""
39
39
  aps_institution_entry_missing article_access_ready article_open browser_closed login_only_done
40
+ carsi_school_list_unconfirmed
40
41
  auth_wall_after_article_load auth_wall_after_pdf_attempt browser_capture_detach_error
41
42
  browser_capture_disable_error browser_pdf_response_captured browser_pdf_response_error
42
43
  browser_response_continue_error browser_response_discard_error challenge_manual_wait
@@ -370,13 +370,16 @@ class InstitutionMixin:
370
370
  return
371
371
  heading = page.get_by_role("heading", level=1, name=self._CARSI_OPTION).first
372
372
  if heading.is_visible() is not True or self._is_challenge_page(page):
373
+ self._school_list_unconfirmed(result, url, "no CARSI heading, or a verification page")
373
374
  return
374
375
  rows = listing.locator(":scope > li")
375
376
  entries = page.evaluate(self._ENTRIES_JS, self._FEDERATION_SCHOOL_LIST + " > li > a[href]")
376
- if (not entries or len(entries) != rows.count()
377
- or listing.evaluate("""el => !!el.closest('[aria-busy=true]') ||
378
- !!el.closest('section')?.querySelector('input:not([type=hidden]), [aria-busy=true], [rel=next]')""",
379
- timeout=800)):
377
+ busy = listing.evaluate("""el => el.closest('[aria-busy=true]') ? 'busy' :
378
+ (el.closest('section')?.querySelector('input:not([type=hidden]), [aria-busy=true], [rel=next]')?.outerHTML || '').slice(0, 120)""",
379
+ timeout=800)
380
+ if not entries or len(entries) != rows.count() or busy:
381
+ self._school_list_unconfirmed(
382
+ result, url, f"{len(entries or [])} links, {rows.count()} rows" + (f", {busy}" if busy else ""))
380
383
  return
381
384
  # Even a partial name match is enough to leave the choice open for the user.
382
385
  entity_id = self._entity_id()
@@ -391,6 +394,13 @@ class InstitutionMixin:
391
394
  raise
392
395
  self._event(result, "institution_step_interrupted", type(exc).__name__)
393
396
 
397
+ def _school_list_unconfirmed(self, result: DownloadResult, url: str, why: str) -> None:
398
+ """Why a shown CARSI school list could not settle the school's absence, once per page:
399
+ the school was left to choose by hand and the wait ran out (Science, 2026-11-11)."""
400
+ if not any(e["state"] == "carsi_school_list_unconfirmed" and str(e.get("detail", "")).endswith(f"@ {url}")
401
+ for e in result.events):
402
+ self._event(result, "carsi_school_list_unconfirmed", f"{why} @ {url}")
403
+
394
404
  def _close_blank_overlay(self, page: Any, result: DownloadResult) -> None:
395
405
  try:
396
406
  closed = page.evaluate(self._BLANK_OVERLAY_JS)
@@ -281,6 +281,15 @@ class LoginMixin:
281
281
  if self._institution_pdf_entitlement_missing(page):
282
282
  return False
283
283
  result.state = "sso_required"
284
+ if manual_selection:
285
+ from .. import login_routes
286
+ earlier = login_routes.missing_since(getattr(self.profile, "name", ""), login_routes.school_key(self.config))
287
+ if earlier:
288
+ # An earlier article of this publisher found no route for the school:
289
+ # nothing to wait for here (Science, BMJ; the user, 2026-11-11).
290
+ result.reason = "institution_federation_unavailable"
291
+ self._event(result, result.reason, f"no route for the school at this publisher earlier ({earlier})")
292
+ return False
284
293
  self._event(result, "sso_start", page.url)
285
294
  self._dismiss_cookie_banners(page, result)
286
295
  sites_opened = sum(e["state"] == "login_page_opened" for e in result.events)
@@ -353,6 +362,10 @@ class LoginMixin:
353
362
  if time.time() >= deadline:
354
363
  break
355
364
  time.sleep(1) # each pass checks the page again: a step done goes on within a second
365
+ if manual_selection and self.institution_query and not getattr(result, "_institution_not_listed", False):
366
+ # A CARSI school list without the school ends the wait whatever this pass
367
+ # would do next (Science, 2026-11-11: the list stood a whole page wait).
368
+ self._check_carsi_school_links(page, result, str(getattr(page, "url", "") or ""))
356
369
  if getattr(result, "_institution_not_listed", False):
357
370
  # The publisher's institution search has no entry for the school.
358
371
  result.reason = "institution_federation_unavailable"
@@ -73,6 +73,13 @@ def _remember_blocked_journal(doi: str, identity: dict[str, Any]) -> None:
73
73
  blocked_journals.remember(doi, identity)
74
74
 
75
75
 
76
+ def _remember_missing_route(publisher: str, config: dict[str, Any], doi: str) -> None:
77
+ """The publisher has no login route for the configured school (``login_routes``)."""
78
+ from .. import login_routes
79
+
80
+ login_routes.remember(publisher, login_routes.school_key(config), doi)
81
+
82
+
76
83
  def _failure_reason_code(result: Any) -> str:
77
84
  """The reason a failed browser result is reported under (a key of ``_FAILURE_KINDS``)."""
78
85
  # Denial must be the terminal state, not a stale reason left on a
@@ -361,6 +368,8 @@ def _try_builtin_institutional(
361
368
  "action": primary["action"], "source_failures": failures}
362
369
  if primary["error_type"] == "access_blocked":
363
370
  _remember_blocked_journal(doi, identity)
371
+ if primary["error_type"] == "institution_federation_unavailable" and manual_carsi:
372
+ _remember_missing_route(publisher_name, config, doi)
364
373
  if "reason_code" in primary:
365
374
  result["reason_code"] = primary["reason_code"]
366
375
  artifacts = primary.get("artifacts") or next(
@@ -0,0 +1,62 @@
1
+ """Publishers without a login route for the configured school, for half an hour.
2
+
3
+ When a publisher's institution list has no entry for the school (Science's CARSI
4
+ list without it; BMJ's federation list without CARSI), every other article there
5
+ waits the same login out. The publisher and the school are written to
6
+ ``<data dir>/login_routes.json``: a later article of that publisher still opens
7
+ and takes an open PDF, but ends at once where it would sign in (the user,
8
+ 2026-11-11). Another school is another key; entries older than ``KEEP_SEC`` are
9
+ dropped when the file is read, so a later batch tries again.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import time
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from .entitlements import _data_dir, _read_json, _write_json
18
+
19
+ KEEP_SEC = 30 * 60
20
+
21
+
22
+ def ledger_path() -> Path:
23
+ return _data_dir() / "login_routes.json"
24
+
25
+
26
+ def school_key(config: dict[str, Any]) -> str:
27
+ """The configured school: its entityID, else its CARSI name; "" without one."""
28
+ for field in ("idp_entity_id", "carsi_idp_name", "carsi_idp_name_en"):
29
+ value = " ".join(str(config.get(field) or "").split())
30
+ if value:
31
+ return value.lower()
32
+ return ""
33
+
34
+
35
+ def _key(publisher: str, school: str) -> str:
36
+ publisher = " ".join(str(publisher or "").lower().split())
37
+ return f"{publisher}|{school}" if publisher and school else ""
38
+
39
+
40
+ def _recent(now: float) -> dict[str, dict[str, Any]]:
41
+ data = _read_json(ledger_path())
42
+ return {key: entry for key, entry in data.items()
43
+ if isinstance(entry, dict) and isinstance(entry.get("at"), (int, float)) and now - KEEP_SEC < entry["at"] <= now}
44
+
45
+
46
+ def missing_since(publisher: str, school: str, now: float | None = None) -> str:
47
+ """The DOI that found no route for this school at this publisher in the last ``KEEP_SEC``, or ""."""
48
+ key = _key(publisher, school)
49
+ entry = _recent(time.time() if now is None else now).get(key) if key else None
50
+ return str(entry.get("doi") or "") if entry else ""
51
+
52
+
53
+ def remember(publisher: str, school: str, doi: str, now: float | None = None) -> bool:
54
+ """Write the publisher as having no route for the school; False without either."""
55
+ key = _key(publisher, school)
56
+ if not key:
57
+ return False
58
+ now = time.time() if now is None else now
59
+ data = _recent(now)
60
+ data[key] = {"at": now, "doi": doi}
61
+ _write_json(ledger_path(), data)
62
+ return True
@@ -11,9 +11,17 @@ export declare function handleSearchPapers(args: any, searchers: Searchers): Pro
11
11
  text: string;
12
12
  }[];
13
13
  }>;
14
+ /**
15
+ * ``get_paper_by_doi``: one DOI (``doi``) or many (``dois``) in one call. The answer
16
+ * has one shape whatever the platform (user, 2026-11-11): every paper in ``papers``;
17
+ * ``not_found`` for DOIs the sources answered for without the paper, ``lookup_failed``
18
+ * for DOIs no source could answer for; ``warnings`` for sources that failed. One DOI
19
+ * also gets its ``doi`` and per-source ``source_results``, ``errors``, ``failed_sources``.
20
+ */
14
21
  export declare function handleGetPaperByDoi(args: {
15
- doi: string;
16
- platform: string;
22
+ doi?: string;
23
+ dois?: string[];
24
+ platform?: string;
17
25
  }, searchers: Searchers): Promise<{
18
26
  content: {
19
27
  type: "text";
@@ -1 +1 @@
1
- {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../src/capabilities/metadata-search/handler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAwCzD,wBAAsB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,SAAS;;;;;GAkB1F;AAED,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,SAAS;;;;;GAiDvE;AAED,wBAAsB,mBAAmB,CAAC,IAAI,EAAE;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,CAAA;CAAE,EAAE,SAAS,EAAE,SAAS;;;;;GA6FtG"}
1
+ {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../../src/capabilities/metadata-search/handler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yBAAyB,CAAC;AAwCzD,wBAAsB,mBAAmB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,SAAS;;;;;GAkB1F;AAED,wBAAsB,kBAAkB,CAAC,IAAI,EAAE,GAAG,EAAE,SAAS,EAAE,SAAS;;;;;GAiDvE;AAuFD;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CAAC,IAAI,EAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,EAAE,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,SAAS,EAAE,SAAS;;;;;GAoCzH"}