papersearch 0.7.3 → 0.8.0

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 (170) hide show
  1. package/LICENSE-paper-search-mcp-nodejs +24 -0
  2. package/NOTICE +8 -37
  3. package/README.en.md +7 -3
  4. package/README.fr.md +268 -0
  5. package/README.ja.md +268 -0
  6. package/README.ko.md +268 -0
  7. package/README.md +7 -3
  8. package/README.zh-Hant.md +268 -0
  9. package/dist/capabilities/download/batch/batch.d.ts +16 -1
  10. package/dist/capabilities/download/batch/batch.d.ts.map +1 -1
  11. package/dist/capabilities/download/batch/batch.js +389 -56
  12. package/dist/capabilities/download/batch/batch.js.map +1 -1
  13. package/dist/capabilities/download/batch/batchFolder.d.ts.map +1 -1
  14. package/dist/capabilities/download/batch/batchFolder.js +3 -2
  15. package/dist/capabilities/download/batch/batchFolder.js.map +1 -1
  16. package/dist/capabilities/download/batch/networkLoss.d.ts +11 -2
  17. package/dist/capabilities/download/batch/networkLoss.d.ts.map +1 -1
  18. package/dist/capabilities/download/batch/networkLoss.js +24 -3
  19. package/dist/capabilities/download/batch/networkLoss.js.map +1 -1
  20. package/dist/capabilities/download/batch/resume.d.ts +7 -0
  21. package/dist/capabilities/download/batch/resume.d.ts.map +1 -1
  22. package/dist/capabilities/download/batch/resume.js +50 -9
  23. package/dist/capabilities/download/batch/resume.js.map +1 -1
  24. package/dist/capabilities/download/content/markdown/pro.d.ts +6 -0
  25. package/dist/capabilities/download/content/markdown/pro.d.ts.map +1 -1
  26. package/dist/capabilities/download/content/markdown/pro.js.map +1 -1
  27. package/dist/capabilities/download/content/markdown/shortfall.d.ts +8 -5
  28. package/dist/capabilities/download/content/markdown/shortfall.d.ts.map +1 -1
  29. package/dist/capabilities/download/content/markdown/shortfall.js +22 -10
  30. package/dist/capabilities/download/content/markdown/shortfall.js.map +1 -1
  31. package/dist/capabilities/download/content/markdown/step.d.ts +9 -0
  32. package/dist/capabilities/download/content/markdown/step.d.ts.map +1 -1
  33. package/dist/capabilities/download/content/markdown/step.js +42 -2
  34. package/dist/capabilities/download/content/markdown/step.js.map +1 -1
  35. package/dist/capabilities/download/content/markdown/types.d.ts +10 -1
  36. package/dist/capabilities/download/content/markdown/types.d.ts.map +1 -1
  37. package/dist/capabilities/download/handler.d.ts.map +1 -1
  38. package/dist/capabilities/download/handler.js +13 -5
  39. package/dist/capabilities/download/handler.js.map +1 -1
  40. package/dist/capabilities/download/outputLayout.d.ts.map +1 -1
  41. package/dist/capabilities/download/outputLayout.js +3 -1
  42. package/dist/capabilities/download/outputLayout.js.map +1 -1
  43. package/dist/capabilities/download/tools.js +2 -2
  44. package/dist/capabilities/download/tools.js.map +1 -1
  45. package/dist/capabilities/download/types.d.ts +9 -1
  46. package/dist/capabilities/download/types.d.ts.map +1 -1
  47. package/dist/cli.js +3 -1
  48. package/dist/cli.js.map +1 -1
  49. package/dist/infrastructure/runlog/RunLedger.d.ts +7 -0
  50. package/dist/infrastructure/runlog/RunLedger.d.ts.map +1 -1
  51. package/dist/infrastructure/runlog/RunLedger.js +13 -0
  52. package/dist/infrastructure/runlog/RunLedger.js.map +1 -1
  53. package/dist/infrastructure/runlog/failureClass.d.ts +2 -1
  54. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  55. package/dist/infrastructure/runlog/failureClass.js +27 -4
  56. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  57. package/dist/infrastructure/school/SchoolAttempt.d.ts +11 -0
  58. package/dist/infrastructure/school/SchoolAttempt.d.ts.map +1 -1
  59. package/dist/infrastructure/school/SchoolAttempt.js +48 -5
  60. package/dist/infrastructure/school/SchoolAttempt.js.map +1 -1
  61. package/dist/infrastructure/school/SchoolMcpClient.d.ts +1 -0
  62. package/dist/infrastructure/school/SchoolMcpClient.d.ts.map +1 -1
  63. package/dist/infrastructure/school/SchoolMcpClient.js +18 -6
  64. package/dist/infrastructure/school/SchoolMcpClient.js.map +1 -1
  65. package/dist/infrastructure/school/SchoolProgress.d.ts +2 -0
  66. package/dist/infrastructure/school/SchoolProgress.d.ts.map +1 -1
  67. package/dist/infrastructure/school/SchoolProgress.js +2 -0
  68. package/dist/infrastructure/school/SchoolProgress.js.map +1 -1
  69. package/dist/infrastructure/school/SchoolReadiness.d.ts +2 -0
  70. package/dist/infrastructure/school/SchoolReadiness.d.ts.map +1 -1
  71. package/dist/infrastructure/school/SchoolReadiness.js +2 -0
  72. package/dist/infrastructure/school/SchoolReadiness.js.map +1 -1
  73. package/dist/infrastructure/school/SchoolResultNormalizer.d.ts.map +1 -1
  74. package/dist/infrastructure/school/SchoolResultNormalizer.js +4 -0
  75. package/dist/infrastructure/school/SchoolResultNormalizer.js.map +1 -1
  76. package/dist/infrastructure/school/index.d.ts +2 -2
  77. package/dist/infrastructure/school/index.d.ts.map +1 -1
  78. package/dist/infrastructure/school/index.js +1 -1
  79. package/dist/infrastructure/school/index.js.map +1 -1
  80. package/dist/infrastructure/school/types.d.ts +42 -0
  81. package/dist/infrastructure/school/types.d.ts.map +1 -1
  82. package/dist/infrastructure/school/types.js.map +1 -1
  83. package/dist/management/failures/index.d.ts +23 -0
  84. package/dist/management/failures/index.d.ts.map +1 -1
  85. package/dist/management/failures/index.js +63 -18
  86. package/dist/management/failures/index.js.map +1 -1
  87. package/package.json +7 -2
  88. package/school/NOTICE +3 -2
  89. package/school/paper_search_school/adapters/__init__.py +2 -0
  90. package/school/paper_search_school/adapters/aps/__init__.py +3 -6
  91. package/school/paper_search_school/adapters/base.py +16 -2
  92. package/school/paper_search_school/adapters/copernicus/__init__.py +2 -7
  93. package/school/paper_search_school/adapters/elsevier/__init__.py +50 -1
  94. package/school/paper_search_school/adapters/frontiers/__init__.py +41 -2
  95. package/school/paper_search_school/adapters/ieee/__init__.py +6 -4
  96. package/school/paper_search_school/adapters/iop/__init__.py +8 -0
  97. package/school/paper_search_school/adapters/jama/__init__.py +8 -0
  98. package/school/paper_search_school/adapters/lww/__init__.py +14 -6
  99. package/school/paper_search_school/adapters/mdpi/__init__.py +12 -7
  100. package/school/paper_search_school/adapters/neurology/__init__.py +5 -2
  101. package/school/paper_search_school/adapters/optica/__init__.py +2 -9
  102. package/school/paper_search_school/adapters/oup/__init__.py +7 -4
  103. package/school/paper_search_school/adapters/platforms/__init__.py +4 -1
  104. package/school/paper_search_school/adapters/platforms/atypon/__init__.py +8 -0
  105. package/school/paper_search_school/adapters/platforms/jstage/__init__.py +64 -0
  106. package/school/paper_search_school/adapters/taylor_francis/__init__.py +0 -3
  107. package/school/paper_search_school/adapters/thieme/__init__.py +2 -9
  108. package/school/paper_search_school/api_keys.py +63 -13
  109. package/school/paper_search_school/assets/api_keys.json +14 -0
  110. package/school/paper_search_school/assets/capsule.html +156 -116
  111. package/school/paper_search_school/assets/capsule_en.json +69 -46
  112. package/school/paper_search_school/assets/capsule_fr.json +70 -47
  113. package/school/paper_search_school/assets/capsule_ja.json +69 -46
  114. package/school/paper_search_school/assets/capsule_ko.json +69 -46
  115. package/school/paper_search_school/assets/capsule_zh-Hant.json +68 -45
  116. package/school/paper_search_school/browser/batch_session.py +1 -1
  117. package/school/paper_search_school/browser/challenge/__init__.py +12 -9
  118. package/school/paper_search_school/browser/challenge/continuation.py +65 -0
  119. package/school/paper_search_school/browser/challenge/handlers/__init__.py +1 -0
  120. package/school/paper_search_school/browser/challenge/handlers/aws_waf.py +260 -0
  121. package/school/paper_search_school/browser/challenge/handlers/recaptcha_hcaptcha.py +167 -0
  122. package/school/paper_search_school/browser/challenge/handlers/text_captcha.py +100 -0
  123. package/school/paper_search_school/browser/challenge/handlers/turnstile.py +174 -0
  124. package/school/paper_search_school/browser/challenge/kinds.py +203 -0
  125. package/school/paper_search_school/browser/challenge/local/__init__.py +1 -0
  126. package/school/paper_search_school/browser/challenge/{interaction.py → local/interaction.py} +94 -13
  127. package/school/paper_search_school/browser/challenge/{pointer.py → local/pointer.py} +2 -2
  128. package/school/paper_search_school/browser/challenge/local/prompt.py +283 -0
  129. package/school/paper_search_school/browser/challenge/local/submission.py +33 -0
  130. package/school/paper_search_school/browser/challenge/services/__init__.py +1 -0
  131. package/school/paper_search_school/browser/challenge/services/solver.py +272 -0
  132. package/school/paper_search_school/cli_config.py +10 -5
  133. package/school/paper_search_school/config.py +11 -10
  134. package/school/paper_search_school/download_diagnostics.py +7 -2
  135. package/school/paper_search_school/engine/access_rules.py +12 -3
  136. package/school/paper_search_school/engine/batch.py +43 -11
  137. package/school/paper_search_school/engine/batch_access.py +38 -12
  138. package/school/paper_search_school/engine/batch_capture.py +215 -18
  139. package/school/paper_search_school/engine/batch_common.py +3 -0
  140. package/school/paper_search_school/engine/batch_diagnostics.py +25 -5
  141. package/school/paper_search_school/engine/batch_institution.py +38 -3
  142. package/school/paper_search_school/engine/batch_login.py +223 -16
  143. package/school/paper_search_school/engine/batch_pdf_urls.py +38 -7
  144. package/school/paper_search_school/engine/batch_waits.py +179 -12
  145. package/school/paper_search_school/engine/bridge.py +28 -4
  146. package/school/paper_search_school/engine/fulltext_page.py +45 -7
  147. package/school/paper_search_school/engine/router.py +16 -1
  148. package/school/paper_search_school/entitlements.py +1 -1
  149. package/school/paper_search_school/pdf_utils.py +25 -16
  150. package/school/paper_search_school/progress_capsule.py +36 -6
  151. package/school/paper_search_school/progress_reporter.py +54 -5
  152. package/school/paper_search_school/progress_view.py +63 -43
  153. package/school/paper_search_school/publishers/builtin/iop.json +2 -1
  154. package/school/paper_search_school/publishers/builtin/neurology.json +4 -2
  155. package/school/paper_search_school/publishers/site.py +12 -4
  156. package/school/paper_search_school/school_test.py +1 -1
  157. package/school/paper_search_school/server.py +17 -6
  158. package/school/paper_search_school/user_settings.py +13 -0
  159. package/school/pyproject.toml +1 -0
  160. package/skills/paper-search/SKILL.md +107 -107
  161. package/skills/paper-search/references/browser-download.md +102 -99
  162. package/skills/paper-search/references/capability-routing.md +89 -89
  163. package/skills/paper-search/references/cli-contract.md +78 -78
  164. package/skills/paper-search/references/federation-support.md +172 -172
  165. package/skills/paper-search/references/management-layer.md +78 -78
  166. package/skills/paper-search/references/publisher-support.md +38 -38
  167. package/skills/paper-search/references/school-setup.md +56 -55
  168. package/skills/paper-search/references/setup.md +20 -20
  169. package/skills/paper-search/references/troubleshooting.md +12 -12
  170. package/school/paper_search_school/browser/challenge/prompt.py +0 -154
@@ -3,12 +3,12 @@ import { randomUUID } from "node:crypto";
3
3
  import { RunLedger } from "../../../infrastructure/runlog/RunLedger.js";
4
4
  import { classifyFailureCode, FAILURE_CLASS_NAMES, } from "../../../infrastructure/runlog/failureClass.js";
5
5
  import { createDefaultDownloadTiers, downloadWithFallback, } from "../content/pdf/OpenAccessFallbackService.js";
6
- import { schoolAttemptDetails, schoolShortReason } from "../../../infrastructure/school/index.js";
6
+ import { blockedBySite, schoolAttemptDetails, schoolShortReason } from "../../../infrastructure/school/index.js";
7
7
  import { journalOfDoi, takeNext } from "./journalKey.js";
8
8
  import { downloadSupplementsOnly, filesPastNetworkLoss } from "../content/supplements/fetch.js";
9
9
  import { supplementShortfall } from "../content/supplements/shortfall.js";
10
10
  import { fulltextPageVisit } from "../content/markdown/pageVisit.js";
11
- import { fulltextAlone, fulltextForItem, markdownBeside, markdownPastNetworkLoss } from "../content/markdown/step.js";
11
+ import { figuresMissing, figuresOnceMore, fulltextAlone, fulltextForItem, markdownBeside, markdownPastNetworkLoss } from "../content/markdown/step.js";
12
12
  import { markdownDoubt, markdownMissing } from "../content/markdown/shortfall.js";
13
13
  import { batchPaper, failure, reportBatchResults, stoppedItem } from "./batchSummary.js";
14
14
  import { loadMarkdownPro, markdownBlocked } from "../content/markdown/pro.js";
@@ -85,6 +85,23 @@ const SCHOOL_SIGN_IN_PAGE = "school_login";
85
85
  /** How often a batch waiting for the user to go on with held publishers asks its window. */
86
86
  const HOLD_POLL_MS = 3_000;
87
87
  const HOLD_WAIT_PHASE = "其他篇目已完成,等你回来点“登录并继续”";
88
+ /**
89
+ * How long a publisher's papers wait after its site blocked one of them (被网站拦截: its human verification not passed,
90
+ * its block page): the batch goes on with the other publishers meanwhile, then tries them once more (user, 2026-11-23).
91
+ * Ten minutes: JAMA's first block in the publisher sweep had cleared within five (the re-check interval the user set for
92
+ * a blocked journal, 2026-11-16), its second held for the 47 minutes the batch went on hitting it; with one retry only,
93
+ * twice that interval. Shorter than the half hour after which a publisher's school session lapsed unused (Wiley,
94
+ * 2026-11-12), so nothing is loaded from the blocking site to keep it.
95
+ */
96
+ export const BLOCKED_PAUSE_MS = 10 * 60_000;
97
+ /**
98
+ * Without 失败后自动重试: a publisher's papers its site blocks in a row before its others are given up for the batch
99
+ * (user, 2026-11-24: Wiley's one verification not passed, paper 85, gave its other 40 up untried). Each one blocked
100
+ * fails on its own; one not blocked starts the count again.
101
+ */
102
+ export const BLOCKED_IN_ROW = 3;
103
+ /** A time of day as the batch's lines say it ("01:05"). */
104
+ const clockTime = (at) => new Date(at).toTimeString().slice(0, 5);
88
105
  const AWAY_NOTICE = "[批量] 这一篇等你登录或验证已到时限;后面的篇目遇到登录或验证只等 60 秒,你在登录页开始输入就照常等";
89
106
  /**
90
107
  * Entitled access waited on the user (school login, verification) until its
@@ -93,7 +110,7 @@ const AWAY_NOTICE = "[批量] 这一篇等你登录或验证已到时限;后
93
110
  function waitedOutOnUser(result) {
94
111
  return (result.status !== "ok" &&
95
112
  result.attempts.some((attempt) => attempt.stage === "entitled_access" &&
96
- (attempt.code === "login_timeout" || attempt.code === "download_timeout")));
113
+ (attempt.code === "login_timeout" || attempt.code === "download_timeout" || attempt.code === "captcha_required")));
97
114
  }
98
115
  /**
99
116
  * The seconds the backend asked this article to wait, and whose limit it is: the publisher's
@@ -213,12 +230,33 @@ function unexplainedFailure(result) {
213
230
  const school = [...result.attempts].reverse().find((attempt) => attempt.stage === "entitled_access");
214
231
  return school?.status === "error" && classifyFailureCode(school.code) === "unexplained";
215
232
  }
233
+ /**
234
+ * 被网站拦截 at the school's stage (blockedBySite): the publisher's site blocked the network or its human verification was
235
+ * not passed. Its publisher's papers wait (``BLOCKED_PAUSE_MS``); none goes to the end's retry or other schools.
236
+ */
237
+ function siteBlocked(result) {
238
+ if (!result || result.status === "ok" || stoppedByUser(result))
239
+ return false;
240
+ const school = [...result.attempts].reverse().find((attempt) => attempt.stage === "entitled_access");
241
+ return school?.status === "error" && blockedBySite(school.code);
242
+ }
216
243
  /** The other saved schools a batch's papers without access go to at its end: none for a batch given its school. */
217
244
  async function schoolsAfterDefault(backend, options) {
218
245
  if (options.school?.trim() || !backend?.schoolSwitch)
219
246
  return [];
220
247
  return (await backend.schoolSwitch().catch(() => undefined))?.schools.slice(1) ?? [];
221
248
  }
249
+ /**
250
+ * 失败后自动重试 (the settings' 等待和提醒 page; user, 2026-11-24: off by default, whoever wants it turns it on): 原因不明
251
+ * tried once more at the batch's end, a publisher whose site blocked it paused and tried once more after BLOCKED_PAUSE_MS.
252
+ * Off, or a backend that does not say: 原因不明 fails at once, and a blocking site's publisher is given up for the batch
253
+ * (接着下 goes on with it). Neither 没权限时换下一所学校 (its own switch) nor a lapsed school login (登录并继续) is one.
254
+ */
255
+ async function retrySetting(backend) {
256
+ if (!backend?.schoolSwitch)
257
+ return false;
258
+ return (await backend.schoolSwitch().catch(() => undefined))?.retry === true;
259
+ }
222
260
  /**
223
261
  * 没权限时换下一所学校 at a batch's end (PaperSearch Pro; user, 2026-11-22): the papers still without access go to each
224
262
  * other saved school in turn, all of them with one before the next, so that the school's login is switched once, not at
@@ -280,6 +318,21 @@ function recorded(request, ledger, item) {
280
318
  ? { ...request, onStage: (record) => ledger.stage(item, record), recordsDir: ledger.records, diagnosticsDir: ledger.diagnostics }
281
319
  : request;
282
320
  }
321
+ /**
322
+ * A batch's end (user, 2026-11-23): the papers whose Markdown was saved without figures that did not download get
323
+ * those figures once more (figuresOnceMore); still missing, the Markdown stays saved with them marked in it. Each
324
+ * paper's record waits for this, to say how it ended.
325
+ */
326
+ async function figuresAtTheEnd(papers, log, ledger) {
327
+ if (!papers.length)
328
+ return;
329
+ log(`[批量] Markdown 缺图的 ${papers.length} 篇再取一次图片`);
330
+ ledger?.phase(`Markdown 缺图的 ${papers.length} 篇再取一次图片`);
331
+ for (const { result, request } of papers)
332
+ await figuresOnceMore(result, request);
333
+ const still = papers.filter(({ result }) => figuresMissing(result)).length;
334
+ log(`[批量] 再取图片:${papers.length - still} 篇补齐` + (still ? `,${still} 篇仍缺图(Markdown 已保存,缺的图在文中标明)` : ""));
335
+ }
283
336
  function openLedger(mode, batchId, options, log) {
284
337
  const ledger = RunLedger.open({
285
338
  kind: "download_batch",
@@ -330,7 +383,7 @@ function summary(mode, batchId, items, extra = {}) {
330
383
  };
331
384
  }
332
385
  /** Download a list serially; one batch id ties it to one progress window. */
333
- export async function downloadBatch(searchers, options, backend, log = (line) => process.stderr.write(`${line}\n`), createTiers = createDefaultDownloadTiers, pause = wait, online = networkReachable) {
386
+ export async function downloadBatch(searchers, options, backend, log = (line) => process.stderr.write(`${line}\n`), createTiers = createDefaultDownloadTiers, pause = wait, online = networkReachable, now = Date.now) {
334
387
  options = { ...options, savePath: resolveDownloadPath(options.savePath) };
335
388
  // The batch's own folder keeps its records beside its papers (user, 2026-11-17).
336
389
  const { folderRecord: _given, ...asked } = options;
@@ -369,7 +422,7 @@ export async function downloadBatch(searchers, options, backend, log = (line) =>
369
422
  ? downloadSerialBatch(options, backend, log, searchers, createTiers, pause, online)
370
423
  : options.mode === "per_item"
371
424
  ? downloadPerItem(searchers, options, backend, log, createTiers, pause, online)
372
- : downloadTwoPhase(searchers, options, backend, log, createTiers, options.mode === "entitled_only" ? "entitled_only" : "two_phase", pause, online));
425
+ : downloadTwoPhase(searchers, options, backend, log, createTiers, options.mode === "entitled_only" ? "entitled_only" : "two_phase", pause, online, now));
373
426
  await reportBatchResults(result, backend, startedAt, options.savePath);
374
427
  return result;
375
428
  };
@@ -432,8 +485,8 @@ export async function downloadBatch(searchers, options, backend, log = (line) =>
432
485
  (missed ? `。附录未下全 ${missed} 篇:${[...shortfalls].map(([reason, n]) => `${reason} ${n}`).join("、")}` : "") +
433
486
  (incomplete ? `。Markdown 未生成 ${incomplete} 篇:${[...noMarkdown].map(([reason, n]) => `${reason} ${n}`).join("、")}` : "") +
434
487
  (doubtful ? `。Markdown 可能不全 ${doubtful} 篇(已保存,请核对):${[...doubts].map(([reason, n]) => `${reason} ${n}`).join("、")}` : ""));
435
- // What is left goes on later with one word (user, 2026-11-15).
436
- if ((result.failed || missed || incomplete) && result.runLog) {
488
+ // What is left goes on later with one word (user, 2026-11-15): a Markdown's missing figures too.
489
+ if ((result.failed || missed || incomplete || result.items.some(figuresMissing)) && result.runLog) {
437
490
  log("[批量] 没下全的篇目:回来后对 AI 说“接着下”即可补(download_batch 的 resume: \"latest\",同一套环境变量)");
438
491
  }
439
492
  folderRecord?.refresh();
@@ -458,6 +511,9 @@ async function downloadSerialBatch(options, backend, log, searchers, createTiers
458
511
  let succeeded = 0;
459
512
  let failed = 0;
460
513
  let away = false;
514
+ /** Papers whose Markdown lacks figures, recorded after their second try at the end (figuresAtTheEnd). */
515
+ const figuresLater = [];
516
+ let stopped = false;
461
517
  for (const [offset, item] of options.items.entries()) {
462
518
  const batch = { id: batchId, index: offset + 1, total, done: offset, succeeded, failed };
463
519
  const request = { ...itemOptions(item, options), batch, ...(away ? { shortUserWait: true } : {}) };
@@ -489,10 +545,14 @@ async function downloadSerialBatch(options, backend, log, searchers, createTiers
489
545
  succeeded += 1;
490
546
  else
491
547
  failed += 1;
492
- ledger?.item(entry, result);
493
548
  items.push(itemResult(result, offset + 1, request));
549
+ if (figuresMissing(result))
550
+ figuresLater.push({ offset, entry, request, ...(item.mainPath ? { mainPath: item.mainPath } : {}) });
551
+ else
552
+ ledger?.item(entry, result);
494
553
  papers.set(offset, batchPaper(request, items[items.length - 1], undefined, content, item.mainPath));
495
554
  if (stoppedByUser(result)) {
555
+ stopped = true;
496
556
  for (const [rest, item] of options.items.entries()) {
497
557
  if (rest <= offset)
498
558
  continue;
@@ -508,6 +568,14 @@ async function downloadSerialBatch(options, backend, log, searchers, createTiers
508
568
  }
509
569
  await papers.send();
510
570
  }
571
+ // Markdown saved without some figures: those once more, unless the user stopped the batch (user, 2026-11-23).
572
+ if (!stopped) {
573
+ await figuresAtTheEnd(figuresLater.map(({ offset, entry, request }) => ({ result: items[offset], request: recorded(request, ledger, entry) })), log, ledger);
574
+ }
575
+ for (const { offset, entry, request, mainPath } of figuresLater) {
576
+ ledger?.item(entry, items[offset]);
577
+ papers.set(offset, batchPaper(request, items[offset], undefined, content, mainPath));
578
+ }
511
579
  await papers.send(true);
512
580
  ledger?.close();
513
581
  return summary(options.mode ?? "two_phase", batchId, items, {
@@ -531,10 +599,35 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
531
599
  // school at a time (``laterSchools``, user 2026-11-22).
532
600
  let turns;
533
601
  const otherSchools = () => (turns ??= schoolsAfterDefault(backend, options));
602
+ let retryOn;
603
+ const retrying = () => (retryOn ??= retrySetting(backend));
534
604
  const waiting = new Map();
535
605
  const schoolsTried = new Map();
536
606
  /** Papers failed for a reason not known, waiting for their one more try at the end (user, 2026-11-22). */
537
607
  const unexplainedYet = new Map();
608
+ // The papers held for a later try are in the window's ring beside those done (user, 2026-11-23), told when they change.
609
+ const dois = (entries) => [...entries.values()].map((entry) => entry.doi ?? "").filter(Boolean);
610
+ const later = () => ({ noAccess: waiting.size, unexplained: unexplainedYet.size, blocked: 0, login: 0,
611
+ papers: { noAccess: dois(waiting), unexplained: dois(unexplainedYet), blocked: [], login: [] } });
612
+ let laterSaid = JSON.stringify(later());
613
+ /** The window told of them, and at the switch to another school, its name; none once every paper is done. */
614
+ const reportLater = async (school) => {
615
+ const counts = later();
616
+ if (!backend?.reportBatchProgress || succeeded + failed >= total || !school && JSON.stringify(counts) === laterSaid)
617
+ return;
618
+ laterSaid = JSON.stringify(counts);
619
+ await backend.reportBatchProgress({ id: batchId, total, done: succeeded + failed, succeeded, failed, current: "",
620
+ finished: false, later: counts, ...(school ? { switchTo: school.name } : {}), laterOnly: true }).catch(() => false);
621
+ };
622
+ /** Papers whose Markdown lacks figures, recorded after their second try at the end (figuresAtTheEnd). */
623
+ const figuresLater = new Map();
624
+ /** A finished paper into the run's records, unless its Markdown's figures wait for the end. */
625
+ const record = (offset, entry) => {
626
+ if (figuresMissing(items[offset]))
627
+ figuresLater.set(offset, entry);
628
+ else
629
+ ledger?.item(entry, items[offset]);
630
+ };
538
631
  let stopped = false;
539
632
  for (const [offset, item] of options.items.entries()) {
540
633
  const index = offset + 1;
@@ -560,13 +653,15 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
560
653
  waiting.set(offset, entry);
561
654
  papers.set(offset, batchPaper(request, finished, "school", content));
562
655
  await papers.send();
656
+ await reportLater();
563
657
  continue;
564
658
  }
565
- if (unexplainedFailure(finished)) {
659
+ if (unexplainedFailure(finished) && await retrying()) {
566
660
  // Not finished: once more at the end, with this school.
567
661
  unexplainedYet.set(offset, entry);
568
662
  papers.set(offset, batchPaper(request, finished, "school", content));
569
663
  await papers.send();
664
+ await reportLater();
570
665
  continue;
571
666
  }
572
667
  if (result.status === "ok")
@@ -575,7 +670,7 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
575
670
  failed += 1;
576
671
  // The window's end when the last paper is finished, not the last in the list (some wait for the end).
577
672
  await reportBatchItem({ ...request, batch: { ...batch, index: batch.done + 1 } }, finished, backend);
578
- ledger?.item(entry, finished);
673
+ record(offset, entry);
579
674
  papers.set(offset, batchPaper(request, finished, undefined, content));
580
675
  if (publisherBlocked(result))
581
676
  log(blockedNotice(request.doi || request.paperId));
@@ -597,6 +692,7 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
597
692
  }
598
693
  /** A paper's school stage once more (another saved school when given), its files and Markdown when it comes. */
599
694
  const again = async (offset, entry, school) => {
695
+ await reportLater();
600
696
  const request = { ...itemOptions(options.items[offset], options), ...(school ? { school: school.entityId } : {}) };
601
697
  const batch = { id: batchId, index: offset + 1, total, done: succeeded + failed, succeeded, failed };
602
698
  log(school ? `[批量] 换${school.name}:${request.doi || request.paperId}` : `[批量] 再试一次:${request.doi || request.paperId}`);
@@ -625,7 +721,7 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
625
721
  else
626
722
  failed += 1;
627
723
  await reportBatchItem({ ...request, batch }, items[offset], backend);
628
- ledger?.item(entry, items[offset]);
724
+ record(offset, entry);
629
725
  papers.set(offset, batchPaper(request, items[offset], undefined, content));
630
726
  await papers.send();
631
727
  };
@@ -651,6 +747,7 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
651
747
  await laterSchools(await otherSchools(), () => [...waiting.keys()], async (school, count) => {
652
748
  log(`[批量] 没权限的 ${count} 篇换${school.name}再试`);
653
749
  ledger?.phase(`没权限的 ${count} 篇换${school.name}再试`);
750
+ await reportLater(school);
654
751
  }, async (offset, school) => {
655
752
  const entry = waiting.get(offset);
656
753
  const finished = await again(offset, entry, school);
@@ -666,6 +763,14 @@ async function downloadPerItem(searchers, options, backend, log, createTiers, pa
666
763
  // Without access with every school (or the batch stopped first): failed.
667
764
  for (const [offset, entry] of waiting)
668
765
  await finish(offset, entry);
766
+ // Markdown saved without some figures: those once more, unless the user stopped the batch (user, 2026-11-23).
767
+ if (!stopped) {
768
+ await figuresAtTheEnd([...figuresLater].map(([offset, entry]) => ({ result: items[offset], request: recorded(itemOptions(options.items[offset], options), ledger, entry) })), log, ledger);
769
+ }
770
+ for (const [offset, entry] of figuresLater) {
771
+ ledger?.item(entry, items[offset]);
772
+ papers.set(offset, batchPaper(itemOptions(options.items[offset], options), items[offset], undefined, content));
773
+ }
669
774
  await papers.send(true);
670
775
  ledger?.close();
671
776
  return summary("per_item", batchId, items, {
@@ -681,7 +786,7 @@ function laneError(stage, error) {
681
786
  message: error instanceof Error ? `${error.name}: ${error.message}` : String(error) }],
682
787
  };
683
788
  }
684
- async function downloadTwoPhase(searchers, options, backend, log, createTiers, mode = "two_phase", pause = wait, online = networkReachable) {
789
+ async function downloadTwoPhase(searchers, options, backend, log, createTiers, mode = "two_phase", pause = wait, online = networkReachable, now = Date.now) {
685
790
  const batchId = randomUUID();
686
791
  const total = options.items.length;
687
792
  const ledger = openLedger(mode, batchId, options, log);
@@ -691,10 +796,17 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
691
796
  const content = options.content ?? "main";
692
797
  const papers = new PaperList(backend, batchId, options.savePath, requests.map((request) => batchPaper(request, undefined, mode === "entitled_only" ? "school" : "open", content)));
693
798
  const recordedOffsets = new Set();
799
+ /** Papers whose Markdown lacks figures: recorded after their second try at the end (figuresAtTheEnd). */
800
+ const figuresLater = new Set();
801
+ let figuresTried = false;
694
802
  /** An item goes to the run record once, when it has settled. */
695
803
  const record = (offset) => {
696
804
  if (recordedOffsets.has(offset))
697
805
  return;
806
+ if (!figuresTried && figuresMissing(results[offset])) {
807
+ figuresLater.add(offset);
808
+ return;
809
+ }
698
810
  recordedOffsets.add(offset);
699
811
  ledger?.item(entries[offset], results[offset]);
700
812
  };
@@ -743,11 +855,11 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
743
855
  const reportProgress = (current) => {
744
856
  if (!openProgress)
745
857
  return reports;
746
- const update = {
858
+ const update = withLater({
747
859
  id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current, finished: false,
748
860
  ...(openRunning ? { phase: `${OPEN_CHANNEL}:已查 ${checked}/${total} 篇,找到 ${openFound} 篇`, channel: OPEN_CHANNEL } : {}),
749
861
  ...(missed.length ? { lanes: lanes() } : {}),
750
- };
862
+ });
751
863
  reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
752
864
  return reports;
753
865
  };
@@ -761,8 +873,8 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
761
873
  const watch = { log, pause, online, notice: (phase) => {
762
874
  if (!backend?.reportBatchProgress || !(openProgress || missed.length))
763
875
  return reports;
764
- const update = { id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
765
- finished: false, phase };
876
+ const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
877
+ finished: false, phase });
766
878
  reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
767
879
  return reports;
768
880
  } };
@@ -863,7 +975,8 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
863
975
  }
864
976
  // Its page stopped at the school's own sign-in page: held with its publisher, its Markdown
865
977
  // fetched again when the user goes on (the files it got stand).
866
- if (pageWait === SCHOOL_SIGN_IN_PAGE && wentThrough(offset) && !stoppedByUser(item) && await canHold()) {
978
+ if (pageWait === SCHOOL_SIGN_IN_PAGE && wentThrough(offset) && !stoppedByUser(item) && await canHold()
979
+ && !heldAgain(offset)) {
867
980
  item.attempts.length = markdownFrom;
868
981
  delete item.markdown;
869
982
  finishing.add(offset);
@@ -901,6 +1014,12 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
901
1014
  const viaSchool = new Set();
902
1015
  /** Each held publisher's papers, open-access ones still to be finished among them. */
903
1016
  const held = new Map();
1017
+ /**
1018
+ * The papers that held their publisher. Gone on with by 登录并继续 and stopped at the school's sign-in page again, such
1019
+ * a paper fails and its publisher's other papers go on, not held a second time (Windows, 2026-11-24: Nature Digest, a
1020
+ * site with only its subscribers' sign-in, held Springer Nature's 73 other papers again after each 登录并继续).
1021
+ */
1022
+ const heldBy = new Set();
904
1023
  /** Where each paper's wait on a school login ended, as the backend said (trace.loginWaitPage). */
905
1024
  const waitEnded = new Map();
906
1025
  const prefixOf = (offset) => (/^10\.\d{4,9}\//.exec(requests[offset].doi.toLowerCase()) ?? [""])[0];
@@ -926,15 +1045,26 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
926
1045
  const canHold = async () => (holdOk ??= await backend?.holdSupported?.().catch(() => false) ?? false);
927
1046
  /** Each DOI prefix's publisher as the school's stages named it ("Science"); the last one named. */
928
1047
  const publishers = new Map();
929
- const heldList = () => [...held.entries()].map(([key, offsets]) => ({
1048
+ // A publisher whose site blocks the batch (被网站拦截: its human verification not passed, its block page): its papers
1049
+ // wait in ``held`` too, the others go on, and they are tried once more after BLOCKED_PAUSE_MS, without the user; blocked
1050
+ // again then, the publisher is given up for this batch (user, 2026-11-23: JAMA blocked after about 15 papers, and 21
1051
+ // of 28 each waited out its verification, at the end again with the retry of 原因不明 and with the next school).
1052
+ /** Each held publisher whose site blocked the batch: when its papers are tried again. */
1053
+ const blockedUntil = new Map();
1054
+ /** Publishers whose papers went on after their pause: blocked again, the batch gives them up. */
1055
+ const triedAgain = new Set();
1056
+ /** Publishers given up: their papers not tried yet end as 被网站拦截, untried; no visit of the batch's end goes to them. */
1057
+ const givenUp = new Set();
1058
+ /** The held publishers waiting for the user (登录并继续), not those blocked. */
1059
+ const heldList = () => [...held.entries()].filter(([key]) => !blockedUntil.has(key)).map(([key, offsets]) => ({
930
1060
  key, name: publishers.get(key) ?? key, count: offsets.length,
931
1061
  }));
932
1062
  /** The window's line and button for the held publishers (none: cleared). */
933
1063
  const reportHeld = (waiting = false) => {
934
1064
  if (!backend?.reportBatchProgress || !holdOk)
935
1065
  return reports;
936
- const update = { id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
937
- finished: false, held: heldList(), ...(waiting ? { phase: HOLD_WAIT_PHASE, heldWait: true } : { lanes: lanes() }) };
1066
+ const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
1067
+ finished: false, held: heldList(), ...(waiting ? { phase: HOLD_WAIT_PHASE, heldWait: true } : { lanes: lanes() }) });
938
1068
  reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
939
1069
  return reports;
940
1070
  };
@@ -946,13 +1076,98 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
946
1076
  return;
947
1077
  }
948
1078
  held.set(key, [offset]);
1079
+ heldBy.add(offset);
949
1080
  log(`[批量] ${key} 的文章前面经学校登录下到了,这一篇停在学校登录页没有完成登录:` +
950
1081
  "这家出版社的篇目先暂停,其他照常下载;回来后在进度窗口点“登录并继续”");
951
1082
  ledger?.phase(`暂停 ${key}:学校登录中途失效`);
952
1083
  void reportHeld();
953
1084
  };
954
- /** The user pressed 登录并继续 (or 终止) in the window: held papers go on first. */
1085
+ /** ``offset`` held its publisher before and stopped at the school's sign-in page again after 登录并继续: not held again. */
1086
+ const heldAgain = (offset) => {
1087
+ if (!heldBy.has(offset))
1088
+ return false;
1089
+ log(`[批量] ${id(offset)} 点“登录并继续”后仍停在学校登录页:这一篇记为失败,${publisherOf(offset)} 的其他篇目接着下载`);
1090
+ return true;
1091
+ };
1092
+ /** The window's line while blocked publishers' papers wait: when they are tried again, how many. */
1093
+ const reportBlocked = () => {
1094
+ if (!backend?.reportBatchProgress || !blockedUntil.size)
1095
+ return reports;
1096
+ const until = Math.min(...blockedUntil.values());
1097
+ const count = [...blockedUntil.keys()].reduce((sum, key) => sum + (held.get(key)?.length ?? 0), 0);
1098
+ if (!count)
1099
+ return reports;
1100
+ const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
1101
+ finished: false, phase: `被网站拦截,${clockTime(until)} 再试暂停的 ${count} 篇` });
1102
+ reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
1103
+ return reports;
1104
+ };
1105
+ /**
1106
+ * ``key``'s site blocked the batch (``why``): the publisher's papers wait, the others go on. ``offset``, the paper it
1107
+ * blocked, waits with them; none when the paper was saved and only its files were refused as too many requests.
1108
+ */
1109
+ const pauseBlocked = (key, why, offset) => {
1110
+ const until = now() + BLOCKED_PAUSE_MS;
1111
+ held.set(key, [...(held.get(key) ?? []), ...(offset === undefined ? [] : [offset])]);
1112
+ blockedUntil.set(key, until);
1113
+ log(`[批量] ${key} 的网站拦截了访问(${why}):这家出版社的篇目先暂停,${clockTime(until)} 再试一次,其他照常下载`);
1114
+ ledger?.phase(`暂停 ${key}:被网站拦截`);
1115
+ void reportBlocked();
1116
+ };
1117
+ /** Pauses with none of their publisher's papers left to wait (its files refused on its last paper): not waited out. */
1118
+ const dropEmptyPauses = () => {
1119
+ for (const key of [...blockedUntil.keys()]) {
1120
+ if (held.get(key)?.length)
1121
+ continue;
1122
+ blockedUntil.delete(key);
1123
+ held.delete(key);
1124
+ }
1125
+ };
1126
+ /** ``offset``'s publisher's site blocked it again after the pause, or at the batch's end: given up for this batch. */
1127
+ const giveUp = (offset) => {
1128
+ const key = publisherOf(offset);
1129
+ if (givenUp.has(key))
1130
+ return;
1131
+ givenUp.add(key);
1132
+ log(`[批量] ${key} 的网站${triedAgain.has(key) ? "暂停后仍" : ""}拦截了访问(${id(offset)}):这家出版社余下的篇目本批不再试` +
1133
+ "(没试的记为被网站拦截,原因不明的不再重试,没权限的不再换学校);过一阵说“接着下”再补");
1134
+ ledger?.phase(`不再试 ${key}:仍被网站拦截`);
1135
+ };
1136
+ /** Without 失败后自动重试: each publisher's papers blocked in a row (BLOCKED_IN_ROW of them give it up). */
1137
+ const blockedInRow = new Map();
1138
+ const blockedOnce = (offset) => {
1139
+ const key = publisherOf(offset);
1140
+ const count = (blockedInRow.get(key) ?? 0) + 1;
1141
+ blockedInRow.set(key, count);
1142
+ if (count >= BLOCKED_IN_ROW)
1143
+ giveUp(offset);
1144
+ else
1145
+ log(`[批量] ${key} 的网站拦截了 ${id(offset)}(连续第 ${count} 篇):这一篇记为失败,这家出版社的其他篇目接着试`);
1146
+ };
1147
+ /** Blocked publishers whose pause is over: their papers go first, once more. */
1148
+ const releaseBlocked = () => {
1149
+ let released = 0;
1150
+ for (const [key, until] of blockedUntil) {
1151
+ if (now() < until)
1152
+ continue;
1153
+ const offsets = held.get(key) ?? [];
1154
+ blockedUntil.delete(key);
1155
+ held.delete(key);
1156
+ // A pause nothing waited in (only a paper's files were refused) is no try: its next block pauses again.
1157
+ if (!offsets.length)
1158
+ continue;
1159
+ triedAgain.add(key);
1160
+ queue.unshift(...offsets);
1161
+ released += offsets.length;
1162
+ log(`[批量] ${key} 已暂停 ${BLOCKED_PAUSE_MS / 60_000} 分钟:暂停的 ${offsets.length} 篇再试一次`);
1163
+ ledger?.phase(`再试 ${key} 暂停的 ${offsets.length} 篇`);
1164
+ }
1165
+ if (released)
1166
+ notify();
1167
+ };
1168
+ /** The user pressed 登录并继续 (or 终止) in the window: held papers go on first. Blocked ones whose pause is over too. */
955
1169
  const takeRequests = () => {
1170
+ releaseBlocked();
956
1171
  const asked = backend?.takeBatchRequests?.(batchId);
957
1172
  if (!asked)
958
1173
  return;
@@ -960,6 +1175,8 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
960
1175
  stopped = true;
961
1176
  let resumed = 0;
962
1177
  for (const key of asked.resume) {
1178
+ if (blockedUntil.has(key))
1179
+ continue;
963
1180
  const offsets = held.get(key) ?? [];
964
1181
  held.delete(key);
965
1182
  queue.unshift(...offsets);
@@ -972,22 +1189,32 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
972
1189
  notify();
973
1190
  }
974
1191
  };
1192
+ /** A paper its publisher's pause left untried: its school stage says so (``code``), or, its PDF from open access standing, its files. */
1193
+ const untried = (offset, code, files = code) => {
1194
+ const item = results[offset];
1195
+ if (finishing.has(offset)) {
1196
+ // Its PDF stands; its browser's part waited.
1197
+ if (wantsFiles)
1198
+ item.supplements = [{ status: "skipped", label: "", reason: files }];
1199
+ }
1200
+ else {
1201
+ const stage = { stage: "entitled_access", status: "error", ...schoolAttemptDetails(code) };
1202
+ results[offset] = itemResult({ ...item, status: "error", attempts: [...item.attempts, stage] }, offset + 1, requests[offset]);
1203
+ // The run record says it too, as `paper-search failures` reads it: there such a paper had no school stage, "没有走到
1204
+ // 机构下载" beside the batch's 被网站拦截 (BMJ, 2026-11-23: 1 + 47 against 48).
1205
+ ledger?.stage(entries[offset], { ...stage, startedAt: new Date().toISOString(), durationMs: 0,
1206
+ trace: { publisher: publisherOf(offset) } });
1207
+ }
1208
+ };
975
1209
  /** The held papers end as paused (the batch stopped): returns them, no longer held. */
976
1210
  const markPaused = () => {
977
1211
  const paused = [...held.values()].flat();
978
- for (const offset of paused) {
979
- const item = results[offset];
980
- if (finishing.has(offset)) {
981
- // Its PDF stands; its browser's part waited for the login.
982
- if (wantsFiles)
983
- item.supplements = [{ status: "skipped", label: "", reason: "batch_stopped" }];
984
- }
985
- else {
986
- results[offset] = itemResult({ ...item, status: "error", attempts: [...item.attempts,
987
- { stage: "entitled_access", status: "error", ...schoolAttemptDetails("login_paused") }] }, offset + 1, requests[offset]);
988
- }
1212
+ for (const [key, offsets] of held) {
1213
+ for (const offset of offsets)
1214
+ untried(offset, blockedUntil.has(key) ? "blocked_paused" : "login_paused", "batch_stopped");
989
1215
  }
990
1216
  held.clear();
1217
+ blockedUntil.clear();
991
1218
  return paused;
992
1219
  };
993
1220
  /**
@@ -1013,12 +1240,44 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1013
1240
  // one school before the next (``laterSchools``, user 2026-11-22).
1014
1241
  let turns;
1015
1242
  const otherSchools = () => (turns ??= schoolsAfterDefault(backend, options));
1243
+ // 失败后自动重试 (retrySetting): asked once, when the first paper might be tried again.
1244
+ let retryOn;
1245
+ const retrying = () => (retryOn ??= retrySetting(backend));
1016
1246
  /** Papers without access with the schools tried so far, waiting for the next one. */
1017
1247
  const withoutAccessYet = new Set();
1018
1248
  /** Papers failed for a reason not known, waiting for their one more try at the end. */
1019
1249
  const unexplainedYet = new Set();
1020
1250
  /** Each waiting paper's schools tried, the default one counted. */
1021
1251
  const schoolsTried = new Map();
1252
+ // The papers held for a later try, by why, are in the window's ring beside those done, not in 剩余 unsaid (user,
1253
+ // 2026-11-23): every report to it says them, and one of its own does before a paper's school visit when they changed.
1254
+ /** The papers held for a later try now. */
1255
+ const later = () => {
1256
+ const waiting = (blocked) => [...held].filter(([key]) => blockedUntil.has(key) === blocked).flatMap(([, offsets]) => offsets);
1257
+ const until = [...blockedUntil].filter(([key]) => held.get(key)?.length).map(([, at]) => at);
1258
+ const dois = (offsets) => [...offsets].map((offset) => requests[offset].doi).filter(Boolean);
1259
+ const blocked = waiting(true), login = waiting(false);
1260
+ return { noAccess: withoutAccessYet.size, unexplained: unexplainedYet.size, blocked: blocked.length, login: login.length,
1261
+ ...(until.length ? { blockedAt: Math.min(...until) } : {}),
1262
+ papers: { noAccess: dois(withoutAccessYet), unexplained: dois(unexplainedYet), blocked: dois(blocked), login: dois(login) } };
1263
+ };
1264
+ /** What the window was last told of them. */
1265
+ let laterSaid = JSON.stringify(later());
1266
+ /** A report to the window with them (``later``). */
1267
+ const withLater = (update) => {
1268
+ const counts = later();
1269
+ laterSaid = JSON.stringify(counts);
1270
+ return { ...update, later: counts };
1271
+ };
1272
+ /** The window told of papers held for a later try, or back from it, when no report has said so; none once all are done. */
1273
+ const reportLater = () => {
1274
+ if (!backend?.reportBatchProgress || JSON.stringify(later()) === laterSaid || settledOk() + failed >= total)
1275
+ return reports;
1276
+ const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
1277
+ finished: false, laterOnly: true });
1278
+ reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
1279
+ return reports;
1280
+ };
1022
1281
  // One journal's papers one after another when the backend says so (more than one school taking part, user
1023
1282
  // 2026-11-21; kept with the switch at the end, user 2026-11-22). Asked until the backend has run a paper and can say.
1024
1283
  let groupJournals;
@@ -1039,6 +1298,19 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1039
1298
  held.get(publisherOf(offset)).push(offset);
1040
1299
  continue;
1041
1300
  }
1301
+ if (givenUp.has(publisherOf(offset))) {
1302
+ // Its publisher's site still blocks after the pause: not tried, 被网站拦截.
1303
+ untried(offset, "blocked_paused");
1304
+ if (finishing.delete(offset))
1305
+ openSettled += 1;
1306
+ else
1307
+ failed += 1;
1308
+ record(offset);
1309
+ settle(offset);
1310
+ await sendPapers();
1311
+ continue;
1312
+ }
1313
+ await reportLater();
1042
1314
  if (finishing.has(offset)) {
1043
1315
  await finishOpenItem(offset);
1044
1316
  if (stopped)
@@ -1083,11 +1355,17 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1083
1355
  }, offset + 1, request);
1084
1356
  const school = result.attempts.find((attempt) => attempt.stage === "entitled_access");
1085
1357
  const holding = result.status !== "ok" && wentThrough(offset) && school?.code === LOGIN_LAPSED_CODE
1086
- && waitEnded.get(offset) === SCHOOL_SIGN_IN_PAGE && !stoppedByUser(result) && await canHold();
1358
+ && waitEnded.get(offset) === SCHOOL_SIGN_IN_PAGE && !stoppedByUser(result) && await canHold() && !heldAgain(offset);
1359
+ // Its publisher's site blocked it: it waits with the publisher's other papers, once (BLOCKED_PAUSE_MS).
1360
+ const blocked = !holding && siteBlocked(result);
1361
+ const pausing = blocked && !triedAgain.has(publisherOf(offset)) && await retrying();
1362
+ if (!blocked)
1363
+ blockedInRow.delete(publisherOf(offset));
1087
1364
  // Its Markdown now, from the page this visit saved, or the open sources (only these
1088
- // while its school login is in doubt).
1089
- if (wantsMarkdown && !stoppedByUser(result)) {
1090
- await markdownPastNetworkLoss(results[offset], recorded({ ...request, batch }, ledger, entries[offset]), searchers, holding ? undefined : pageVisit(backend, { ...request, batch, ...(away ? { shortUserWait: true } : {}) }, log, pause), watch);
1365
+ // while its school login is in doubt or its site blocks); a paused paper's when it is tried again.
1366
+ if (wantsMarkdown && !stoppedByUser(result) && !pausing) {
1367
+ await markdownPastNetworkLoss(results[offset], recorded({ ...request, batch }, ledger, entries[offset]), searchers, holding || blocked ? undefined
1368
+ : pageVisit(backend, { ...request, batch, ...(away ? { shortUserWait: true } : {}) }, log, pause), watch);
1091
1369
  }
1092
1370
  if (result.status === "ok") {
1093
1371
  succeeded += 1;
@@ -1095,15 +1373,39 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1095
1373
  settle(offset);
1096
1374
  if (school?.status === "ok")
1097
1375
  cameThrough(offset);
1376
+ // Saved, its files refused as too many requests (BMJ Open's, 2026-11-23, the paper before gut.bmj.com's check):
1377
+ // the publisher's other papers wait all the same.
1378
+ const key = publisherOf(offset);
1379
+ if (result.supplements?.some((file) => file.reason === "http_429") && !blockedUntil.has(key) && !triedAgain.has(key)) {
1380
+ // Without 失败后自动重试: no pause; one of BLOCKED_IN_ROW in a row (blockedOnce).
1381
+ if (await retrying())
1382
+ pauseBlocked(key, `${id(offset)} 的附录:请求太多`);
1383
+ else
1384
+ blockedOnce(offset);
1385
+ }
1098
1386
  }
1099
1387
  else if (holding) {
1100
1388
  hold(offset);
1101
1389
  }
1390
+ else if (pausing) {
1391
+ pauseBlocked(publisherOf(offset), `${id(offset)}:人机验证没过或拦截页`, offset);
1392
+ }
1393
+ else if (blocked) {
1394
+ // Blocked again after its pause: this one fails 被网站拦截, its publisher's others are not tried. Without 失败后自动
1395
+ // 重试: this one fails, its publisher's others go on until BLOCKED_IN_ROW in a row (blockedOnce).
1396
+ if (triedAgain.has(publisherOf(offset)))
1397
+ giveUp(offset);
1398
+ else
1399
+ blockedOnce(offset);
1400
+ failed += 1;
1401
+ record(offset);
1402
+ settle(offset);
1403
+ }
1102
1404
  else if (withoutAccess(result) && !stoppedByUser(result) && (await otherSchools()).length) {
1103
1405
  withoutAccessYet.add(offset);
1104
1406
  settle(offset, "school");
1105
1407
  }
1106
- else if (unexplainedFailure(result)) {
1408
+ else if (unexplainedFailure(result) && await retrying()) {
1107
1409
  unexplainedYet.add(offset);
1108
1410
  settle(offset, "school");
1109
1411
  }
@@ -1112,12 +1414,11 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1112
1414
  record(offset);
1113
1415
  settle(offset);
1114
1416
  }
1115
- // The window's line, not for a paper that waits for the end (it would close the batch early when last).
1116
- if (!withoutAccessYet.has(offset) && !unexplainedYet.has(offset)) {
1417
+ // The window's line, not for a paper that waits for the end or its publisher's pause (it would close the batch
1418
+ // early when last).
1419
+ if (!withoutAccessYet.has(offset) && !unexplainedYet.has(offset) && !pausing) {
1117
1420
  await reportBatchItem({ ...request, batch: { ...batch, index: batch.done + 1 } }, result, backend);
1118
1421
  }
1119
- if (publisherBlocked(result))
1120
- log(blockedNotice(id(offset)));
1121
1422
  if (stoppedByUser(result)) {
1122
1423
  stopped = true;
1123
1424
  return;
@@ -1147,21 +1448,32 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1147
1448
  // The held publishers wait for the user as long as it takes (user, 2026-11-15): the
1148
1449
  // window shows 登录并继续 and 终止. 登录并继续 downloads them, the school's login asking
1149
1450
  // the user where it lapsed; held again, the wait starts over. 终止 ends them as paused.
1451
+ // Those blocked by their site wait out their pause and go on by themselves (user, 2026-11-23).
1452
+ dropEmptyPauses();
1150
1453
  if (held.size && !stopped) {
1151
- const waiting = [...held.values()].reduce((sum, offsets) => sum + offsets.length, 0);
1152
- log(`[批量] 其他篇目已完成,暂停的 ${waiting} 篇等你回来:在进度窗口点“登录并继续”,或点“终止”结束`);
1153
- ledger?.phase(`等你回来:暂停的 ${waiting} 篇`);
1454
+ const waiting = heldList().reduce((sum, publisher) => sum + publisher.count, 0);
1455
+ if (waiting) {
1456
+ log(`[批量] 其他篇目已完成,暂停的 ${waiting} 篇等你回来:在进度窗口点“登录并继续”,或点“终止”结束`);
1457
+ ledger?.phase(`等你回来:暂停的 ${waiting} 篇`);
1458
+ }
1459
+ const blockedWaiting = [...blockedUntil.keys()].reduce((sum, key) => sum + (held.get(key)?.length ?? 0), 0);
1460
+ if (blockedWaiting) {
1461
+ log(`[批量] 其他篇目已完成,被网站拦截暂停的 ${blockedWaiting} 篇 ${clockTime(Math.min(...blockedUntil.values()))} 再试一次`);
1462
+ ledger?.phase(`等网站解除拦截:暂停的 ${blockedWaiting} 篇`);
1463
+ }
1154
1464
  }
1155
1465
  while (held.size && !stopped) {
1156
- await reportHeld(true);
1466
+ await (heldList().length ? reportHeld(true) : reportBlocked());
1157
1467
  await pause(HOLD_POLL_MS);
1158
1468
  takeRequests();
1159
1469
  if (queue.length && !stopped) {
1160
1470
  await entitledLane();
1161
1471
  }
1472
+ dropEmptyPauses();
1162
1473
  }
1163
1474
  /** A paper's school stage once more, with another saved school when given; merged into its result. */
1164
1475
  const visitAgain = async (offset, school) => {
1476
+ await reportLater();
1165
1477
  const request = { ...requests[offset], ...(school ? { school: school.entityId } : {}) };
1166
1478
  const done = settledOk() + failed;
1167
1479
  const batch = { id: batchId, index: done + 1, total, done, succeeded: settledOk(), failed };
@@ -1189,22 +1501,29 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1189
1501
  }
1190
1502
  if (stoppedByUser(result))
1191
1503
  stopped = true;
1192
- if (publisherBlocked(result))
1193
- log(blockedNotice(id(offset)));
1504
+ // Its publisher's site blocks the batch's end too: no more visits go there (no pause at the end).
1505
+ if (siteBlocked(result))
1506
+ giveUp(offset);
1194
1507
  return item;
1195
1508
  };
1509
+ /** Not visited again at the batch's end: its publisher's site still blocks (``giveUp``). */
1510
+ const visitable = (offset) => !givenUp.has(publisherOf(offset));
1196
1511
  /** The window's line for a paper finished at the end (the counts before it, as ``reportBatchItem`` takes them). */
1197
1512
  const reportSettled = async (offset) => {
1198
1513
  const done = settledOk() + failed;
1199
1514
  await reportBatchItem({ ...requests[offset], batch: { id: batchId, index: done + 1, total, done, succeeded: settledOk(), failed } }, results[offset], backend);
1200
1515
  };
1201
- // 原因不明 once more, the default school still signed in, before any other school (user, 2026-11-22).
1202
- if (unexplainedYet.size && !stopped) {
1203
- log(`[批量] 原因不明的 ${unexplainedYet.size} 篇再试一次`);
1204
- ledger?.phase(`原因不明的 ${unexplainedYet.size} 篇再试一次`);
1205
- for (const offset of [...unexplainedYet]) {
1516
+ // 原因不明 once more, the default school still signed in, before any other school (user, 2026-11-22). Not where the
1517
+ // site still blocks: those end as they were.
1518
+ const unexplainedAgain = [...unexplainedYet].filter(visitable);
1519
+ if (unexplainedAgain.length && !stopped) {
1520
+ log(`[批量] 原因不明的 ${unexplainedAgain.length} 篇再试一次`);
1521
+ ledger?.phase(`原因不明的 ${unexplainedAgain.length} 篇再试一次`);
1522
+ for (const offset of unexplainedAgain) {
1206
1523
  if (stopped)
1207
1524
  break;
1525
+ if (!visitable(offset))
1526
+ continue;
1208
1527
  const item = await visitAgain(offset);
1209
1528
  unexplainedYet.delete(offset);
1210
1529
  if (!stopped && item.status !== "ok" && withoutAccess(item) && (await otherSchools()).length) {
@@ -1228,8 +1547,11 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1228
1547
  record(offset);
1229
1548
  }
1230
1549
  unexplainedYet.clear();
1231
- // The papers without access go to the other saved schools, one school at a time.
1550
+ // The papers without access go to the other saved schools, one school at a time; not where the site still blocks
1551
+ // (they end without access, with the schools tried so far).
1232
1552
  const withSchool = async (offset, school) => {
1553
+ if (!visitable(offset))
1554
+ return;
1233
1555
  const item = await visitAgain(offset, school);
1234
1556
  schoolsTried.set(offset, (schoolsTried.get(offset) ?? 1) + 1);
1235
1557
  if (!stopped && withoutAccess(item)) {
@@ -1248,13 +1570,14 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1248
1570
  await sendPapers();
1249
1571
  };
1250
1572
  if (withoutAccessYet.size && !stopped) {
1251
- await laterSchools(await otherSchools(), () => [...withoutAccessYet], async (school, count) => {
1573
+ await laterSchools(await otherSchools(), () => [...withoutAccessYet].filter(visitable), async (school, count) => {
1252
1574
  log(`[批量] 没权限的 ${count} 篇换${school.name}再试`);
1253
1575
  ledger?.phase(`没权限的 ${count} 篇换${school.name}再试`);
1254
1576
  if (!backend?.reportBatchProgress)
1255
1577
  return;
1256
- const update = { id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
1257
- finished: false, phase: `没权限,换${school.name}` };
1578
+ // The card names the school a moment (switchTo), in place of a line saying so.
1579
+ const update = withLater({ id: batchId, total, done: settledOk() + failed, succeeded: settledOk(), failed, current: "",
1580
+ finished: false, switchTo: school.name, laterOnly: true });
1258
1581
  reports = reports.then(() => backend.reportBatchProgress(update)).catch(() => false);
1259
1582
  await reports;
1260
1583
  }, withSchool, () => stopped);
@@ -1266,6 +1589,16 @@ async function downloadTwoPhase(searchers, options, backend, log, createTiers, m
1266
1589
  record(offset);
1267
1590
  }
1268
1591
  withoutAccessYet.clear();
1592
+ // Markdown saved without some figures: those once more, unless the user stopped the batch (user, 2026-11-23);
1593
+ // recorded before a stop's own marks on the papers not recorded yet.
1594
+ figuresTried = true;
1595
+ if (!stopped) {
1596
+ await figuresAtTheEnd([...figuresLater].map((offset) => ({ result: results[offset], request: recorded(requests[offset], ledger, entries[offset]) })), log, ledger);
1597
+ }
1598
+ for (const offset of figuresLater) {
1599
+ record(offset);
1600
+ settle(offset);
1601
+ }
1269
1602
  await reports;
1270
1603
  // Stopped in the window: the items neither lane reached end as not downloaded, the held as paused.
1271
1604
  if (stopped) {