@li-canghai/dsh-paper 0.0.0-stage → 0.8.1

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 (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -2
  3. package/cordis.patch.yml +4 -0
  4. package/lib/annotate-tool.js +334 -0
  5. package/lib/arxiv-id.js +74 -0
  6. package/lib/asset-routes.js +210 -0
  7. package/lib/bibliography-formats.js +126 -0
  8. package/lib/bibliography-import.js +105 -0
  9. package/lib/bibliography-service.js +43 -0
  10. package/lib/bibliography.js +42 -0
  11. package/lib/block-authors.js +292 -0
  12. package/lib/block-cache.js +39 -0
  13. package/lib/blocks-markdown.js +157 -0
  14. package/lib/blocks-reconcile.js +218 -0
  15. package/lib/blocks.js +1344 -0
  16. package/lib/citation-metadata.js +260 -0
  17. package/lib/citation-styles.js +120 -0
  18. package/lib/client-parts/01-pure-helpers.js +2762 -0
  19. package/lib/client-parts/02-author-year.js +95 -0
  20. package/lib/client.js +10381 -0
  21. package/lib/code-source.js +68 -0
  22. package/lib/concurrency-gate.js +91 -0
  23. package/lib/context.js +233 -0
  24. package/lib/csl/SOURCES.md +10 -0
  25. package/lib/csl/gb-t-7714.csl +441 -0
  26. package/lib/csl/ieee.csl +520 -0
  27. package/lib/csl/locales-zh-CN.xml +438 -0
  28. package/lib/csl/nature.csl +190 -0
  29. package/lib/discussion.js +400 -0
  30. package/lib/documents.js +67 -0
  31. package/lib/export.js +848 -0
  32. package/lib/file-lock.js +177 -0
  33. package/lib/gloss.js +181 -0
  34. package/lib/glossary.js +279 -0
  35. package/lib/index.js +3862 -0
  36. package/lib/inline-html.js +53 -0
  37. package/lib/install-dependency.js +120 -0
  38. package/lib/item-ops.js +83 -0
  39. package/lib/job-facade.js +58 -0
  40. package/lib/json-store.js +54 -0
  41. package/lib/library-model.js +132 -0
  42. package/lib/library-service.js +180 -0
  43. package/lib/library-tool.js +982 -0
  44. package/lib/library.js +814 -0
  45. package/lib/markdown-assets.js +138 -0
  46. package/lib/markdown-literals.js +93 -0
  47. package/lib/metadata-enrichment.js +516 -0
  48. package/lib/metadata-fetch.js +146 -0
  49. package/lib/metadata-node.js +158 -0
  50. package/lib/metadata-proxy.ps1 +35 -0
  51. package/lib/mineru-config.js +95 -0
  52. package/lib/mineru-sdk-helper.py +123 -0
  53. package/lib/mineru-sdk.js +182 -0
  54. package/lib/mineru.js +268 -0
  55. package/lib/mirror-export.js +240 -0
  56. package/lib/outline.js +296 -0
  57. package/lib/page-image-helper.py +308 -0
  58. package/lib/page-image.js +454 -0
  59. package/lib/paper-metadata.js +242 -0
  60. package/lib/parse-export.js +631 -0
  61. package/lib/pdf-analysis-tool.js +750 -0
  62. package/lib/pdf-metadata-helper.py +75 -0
  63. package/lib/pdf-metadata.js +141 -0
  64. package/lib/pdf-page.js +261 -0
  65. package/lib/pdf-scan.js +134 -0
  66. package/lib/pdf-text.js +68 -0
  67. package/lib/picker.js +305 -0
  68. package/lib/portable.js +379 -0
  69. package/lib/purge.js +170 -0
  70. package/lib/read-tool.js +660 -0
  71. package/lib/reader-store.js +497 -0
  72. package/lib/reading-order.js +207 -0
  73. package/lib/rename-document.js +480 -0
  74. package/lib/rename.js +372 -0
  75. package/lib/renderer-status.js +161 -0
  76. package/lib/resolver.js +1152 -0
  77. package/lib/result-archive.js +157 -0
  78. package/lib/revisions.js +330 -0
  79. package/lib/search-database.js +62 -0
  80. package/lib/search-index.js +601 -0
  81. package/lib/search-scan.js +185 -0
  82. package/lib/search-source.js +23 -0
  83. package/lib/search-terms.js +539 -0
  84. package/lib/section-audit.js +209 -0
  85. package/lib/selection-message.js +332 -0
  86. package/lib/serial-tail.js +21 -0
  87. package/lib/slicing.js +425 -0
  88. package/lib/source-resolver.js +581 -0
  89. package/lib/stem-repair.js +189 -0
  90. package/lib/storage.js +562 -0
  91. package/lib/store-paths.js +253 -0
  92. package/lib/table-gfm.js +236 -0
  93. package/lib/tasks.js +270 -0
  94. package/lib/tex-align.js +509 -0
  95. package/lib/tex-blocks.js +653 -0
  96. package/lib/tex-fetch.js +455 -0
  97. package/lib/tex-figures.js +140 -0
  98. package/lib/tex-inline.js +166 -0
  99. package/lib/tex-merge.js +279 -0
  100. package/lib/tex-pipeline.js +242 -0
  101. package/lib/tex-prepare.js +746 -0
  102. package/lib/tex-tables.js +210 -0
  103. package/lib/text-similarity.js +85 -0
  104. package/lib/tool-contract.js +86 -0
  105. package/lib/tool-host.js +1058 -0
  106. package/lib/tool-identity.js +214 -0
  107. package/lib/translatable-text.js +48 -0
  108. package/lib/translate-prompts.js +709 -0
  109. package/lib/translate-queue.js +418 -0
  110. package/lib/translate-task.js +158 -0
  111. package/lib/translate.js +909 -0
  112. package/lib/update-check.js +438 -0
  113. package/lib/update-contracts.js +75 -0
  114. package/lib/usage.js +282 -0
  115. package/package.json +55 -4
package/lib/slicing.js ADDED
@@ -0,0 +1,425 @@
1
+ /**
2
+ * 把论文的块列表切成「模型要读的那一段」。
3
+ *
4
+ * 独立成模块的理由是**归属**:切章节、按块取区间、按字节封顶,是块模型的能力,
5
+ * 不是"模型侧工具"的能力。过去它们住在 read-tool.js 里,宿主反而反过来 import 工具模块 ——
6
+ * 那是一次方向反了的依赖。现在两边都从这份实现取。
7
+ *
8
+ * 纯函数:只依赖块列表(blocks.js 的产物)与上限常量。
9
+ */
10
+
11
+ import { headingEntries, headingLevels, headingTitle, mathMarkdown, visibleHeadingIndexes } from './blocks.js'
12
+ import { codeSource } from './code-source.js'
13
+ import { plainInlineText } from './inline-html.js'
14
+ import { tableToGfm } from './table-gfm.js'
15
+
16
+ /** 一次返回的正文上限。再长模型也读不完,而且会把上下文一次性吃满。 */
17
+ export const MAX_TEXT_BYTES = 32 * 1024
18
+
19
+ function textOf(value) {
20
+ return typeof value === 'string' ? value : ''
21
+ }
22
+
23
+ /**
24
+ * 标题的**规范形**:先折掉行内 HTML,再折空白、转小写。
25
+ *
26
+ * 🔴 折标签绝不能少:MinerU 把不少标题切成了 `<sub>` 碎片(实测 26 处,
27
+ * `3<sub>.</sub>4 Difi<sub>cu</sub>lt<sub>y</sub> …`)。目录里显示的是折过的
28
+ * `3.4 Dificulty ladder …`,照抄回 `section()` 却匹配不上未折的原串 ——
29
+ * 读者明明看见那一行,工具却说「没有叫「3.4 Dificulty ladder」的章节」。
30
+ */
31
+ const normalize = value => plainInlineText(textOf(value)).normalize('NFKC').replace(/[‐‑‒–—−]/g, '-').replace(/\s+/g, ' ').trim().toLowerCase()
32
+ const literal = value => plainInlineText(textOf(value)).replace(/\s+/g, ' ').trim().toLowerCase()
33
+ const canonical = value => literal(value).normalize('NFC')
34
+
35
+ /**
36
+ * 图表脚注(`table_footnote` / `chart_footnote` / `image_footnote` → `block.footnote`)接在本块之后。
37
+ *
38
+ * caption 与 footnote 是两种东西:caption 是「表 1 各模型的准确率」,footnote 是
39
+ * 「单位为百分点 / * p<0.05」—— 少了它,表里的数字没有单位、星号没有含义。
40
+ * 同一句已经出现在本块渲染结果里就不重复印:MinerU 有时把脚注也塞进 caption。
41
+ *
42
+ * @param {string} rendered 本块已经渲染出的正文。
43
+ * @param {object} block 译文块。
44
+ * @returns {string} 带脚注的正文。
45
+ */
46
+ function withFootnote(rendered, block) {
47
+ const footnote = plainInlineText(textOf(block?.footnote)).trim()
48
+ if (footnote === '' || rendered.includes(footnote)) return rendered
49
+ return rendered + '\n\n' + footnote
50
+ }
51
+
52
+ /**
53
+ * 一个块渲染成 Markdown 的那一行/那一段。空块返回空串(调用方按行过滤掉)。
54
+ *
55
+ * @param {object} block 译文块。
56
+ * @param {{noise?: boolean}} [options] `noise` = 这个 heading 块是**被上游误标成标题的正文**:
57
+ * 不再印成 `## …`(那会让读者以为正文里还有一节叫 `Question:`),改成引用块 ——
58
+ * 内容照旧可读,只是不再冒充章节标题。
59
+ */
60
+ export function renderBlock(block, options) {
61
+ // 🔴 正文也要折掉行内 HTML(审查 F24 的同一根因,落在**读**这一侧):MinerU 把大量字母
62
+ // 标成上/下标,`We consider a set` 在盘上是 `W<sub>e cons</sub>id<sub>er a se</sub>t`。
63
+ // 阅读器与导出早就折了(inline-html.js / export.js),只有 `Paper_read` 把原串交给模型 ——
64
+ // 于是模型读到满屏标签,写综述时还会把它们抄进正文。折壳不删字(`<sub>g</sub>` → `g`),
65
+ // 代码围栏整段跳过;表格的块级标签不在这里折,由下面 table 分支的 tableToGfm 折成 GFM。
66
+ const text = plainInlineText(textOf(block?.sourceText))
67
+ const type = textOf(block?.type)
68
+ if (type === 'heading') {
69
+ // 🔴 标题也要折掉行内 HTML:MinerU 把不少标题切成了 `<sub>` 碎片,
70
+ // 照原样印出来就是一串 `3<sub>.</sub>4 Difi<sub>cu</sub>lt…`。
71
+ const title = headingTitle(block)
72
+ if (title === '') return ''
73
+ if (options?.noise === true) return '> ' + title
74
+ const level = Number.isInteger(block?.level) ? Math.min(Math.max(block.level, 1), 6) : 2
75
+ return '#'.repeat(level) + ' ' + title
76
+ }
77
+ // 代码块的正文在 `block.html`(MinerU 的 `code_body`),`sourceText` 只是 caption ——
78
+ // 只读 sourceText 会让 233 个没有 caption 的代码块整块消失(见 code-source.js)。
79
+ // caption 存在时照上游版式排在正文之前:它多半是 `Figure 19: Prompt for …` 这种说明行。
80
+ if (type === 'code') {
81
+ const body = codeSource(block?.html)
82
+ if (body === '') return text
83
+ return text === '' ? body : text + '\n\n' + body
84
+ }
85
+ // 公式的序列化只有一处(blocks.js 的 mathMarkdown):只包一层 $$、编号要留下。
86
+ if (type === 'math') return mathMarkdown(block)
87
+ // 🔴 `figure` 才是 splitBlocks 对 MinerU 的 image / chart 产出的**规范**类型,`image` 只出现在
88
+ // 手工构造的块与历史数据里。只认后者会让没有题注的图整块消失(sourceText 是 caption,空的),
89
+ // 审计再按「渲染为空」跳过它 —— 于是这一节里的图像证据既不在正文里、也不在「为什么空」里。
90
+ // 占位与页码都不依赖 caption:有没有题注是解析的运气,图在不在是本节的**事实**。
91
+ if (type === 'figure' || type === 'image') {
92
+ const caption = plainInlineText(textOf(block?.caption)).trim() || text
93
+ const page = Number.isSafeInteger(block?.page) && block.page >= 1 ? '(第 ' + block.page + ' 页)' : ''
94
+ return withFootnote((caption === '' ? '[图]' : '[图:' + caption + ']') + page, block)
95
+ }
96
+ if (type === 'table') {
97
+ // 🔴 `html` 是 MinerU 的 `table_body`,整段 `<table>…</table>`,不是可读文本。直接拼进正文
98
+ // 就是把 `</td></tr></table>` 灌进模型读的那一段(实测:读一节返回的正是这些标签)。
99
+ // GFM 才进得了正文,口径与阅读器(client.js 的 tableToGfm)、导出(export.js)、
100
+ // 翻译载荷(translatable-text.js)一致 —— 同一张表四处必须给出同一份文本。
101
+ // 转不出来(没有 <tr>、栅格宽 0)时退回 caption:宁可少一张表,不把标签当正文。
102
+ const gfm = tableToGfm(block?.html)
103
+ return withFootnote([text, gfm].filter(value => value !== '').join('\n\n') || '[表格]', block)
104
+ }
105
+ return text
106
+ }
107
+
108
+ /**
109
+ * 章节树里某一节的边界:从该标题起,到下一个同级或更高级标题之前。
110
+ *
111
+ * 🔴 边界的比较基准必须是**有效层级**(blocks.headingLevels),不能直接读 `block.level`:
112
+ * MinerU 把 `2` 与 `2.1` 都压成 `##`,照原始 `#` 数比较就会认为 `2.1` 与 `2` 同级,
113
+ * 于是读「第 2 节」只返回导语那一段、后面的 2.1–2.3 全被切掉 —— 而且不报错,静默半节。
114
+ * 目录(outline.js)与切片(这里)必须同一套层级,否则「目录里有子节、读出来没有」。
115
+ */
116
+ export function sectionRange(blocks, index, scope = 'with-children') {
117
+ const levels = headingLevels(blocks)
118
+ const level = levels.get(index) ?? 2
119
+ // 🔴 噪声标题(被上游标成标题的正文)**不能**当边界:它本来就在这一节里面,
120
+ // 层级是按「比前一条深一层」给的,拿来比较会把父节截成半截。实测 MemR3:
121
+ // `A.1 System prompt of the generate node` 的正文之后紧跟一个被标成标题的
122
+ // `SYSTEM PROMPT`,区间就断在它前面 —— 1723 字符的 prompt 正文与后面的 `A.2`
123
+ // 一起被切掉,读「A.1」只拿到 918 字符的导语。
124
+ // 边界集合与目录同口径:目录页(`Contents`)的页码清单属于它所在那一节的版面内容,
125
+ // 当边界会把 MemHarness 的 `Appendix` 切成 11 字符的标题行。
126
+ const boundary = new Set(visibleHeadingIndexes(blocks))
127
+ let end = blocks.length
128
+ for (let cursor = index + 1; cursor < blocks.length; cursor += 1) {
129
+ if (textOf(blocks[cursor]?.type) !== 'heading') continue
130
+ if (!boundary.has(cursor)) continue
131
+ if (scope === 'self' || (levels.get(cursor) ?? 2) <= level) { end = cursor; break }
132
+ }
133
+ return { from: index, to: end }
134
+ }
135
+
136
+ /**
137
+ * 块 id 的**规范形**:去掉一个前导 `b:`。
138
+ *
139
+ * 目录里印的是 `[b:p2-h1 .. b:p4-p7]`(那是**标记行**的写法),块 id 本身是裸的
140
+ * `p2-h1`。照目录抄来的地址不归一化,`section("b:p9-h1")` 会回「没有这一节」;
141
+ * `Paper_annotate` 更糟 —— 它照样返回 ok,笔记落成一条挂在没人读的 id 上的孤儿边注。
142
+ *
143
+ * @param {unknown} value 裸 id、`b:` 前缀、方括号或完整块标记,可带反引号;不完整包装原样保留。
144
+ * @returns {string}
145
+ */
146
+ export function normalizeBlockId(value) {
147
+ let text = textOf(value).trim()
148
+ const code = /^(`+)([^`\r\n]+)\1$/.exec(text)
149
+ if (code) text = code[2].trim()
150
+ const marker = /^<!--\s*b:([^\s<>]+)\s*-->$/.exec(text)
151
+ if (marker) return marker[1]
152
+ const bracketed = /^\[b:([^\s\[\]]+)\]$/.exec(text)
153
+ const id = bracketed ? bracketed[1] : text.startsWith('b:') ? text.slice(2).trim() : text
154
+ return id === '' ? textOf(value).trim() : id
155
+ }
156
+
157
+ /** 目录行给前置/后置页打的标记(`〔前置〕` / `〔后置〕`)。 */
158
+ const MATTER_MARK = /^〔(?:前置|后置)〕\s*/
159
+
160
+ /**
161
+ * 章节引用的规范形:剥掉目录里的装饰(前置/后置页标记、块 id 前缀、`#序号` 的井号)。
162
+ * 读者/模型是**照着目录抄**地址的,抄来的东西必须能直接用。
163
+ */
164
+ export function normalizeSectionReference(value) {
165
+ let text = textOf(value).trim()
166
+ if (MATTER_MARK.test(text)) text = text.replace(MATTER_MARK, '').trim()
167
+ const interval = /^\[b:([^\s\[\]]+)\s+\.\.\s+b:[^\s\[\]]+\]$/.exec(text)
168
+ if (interval) text = interval[1]
169
+ text = normalizeBlockId(text)
170
+ const ordinal = /^#(\d+)$/.exec(text)
171
+ return ordinal === null ? text : ordinal[1]
172
+ }
173
+
174
+ function escapeRegExp(text) {
175
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
176
+ }
177
+
178
+ /**
179
+ * 把模型给的「第几节 / 哪一节」折成一个块区间。
180
+ *
181
+ * 三种写法:1 起的章节序号、标题原文(空白与大小写不敏感)、或一个块 id;标题也可以
182
+ * 只写片段。找不到 / 命中多节时**不猜**,把候选交回去 —— 候选要带**能用来区分的东西**
183
+ * (序号 + 块 id),否则「命中 2 节」下面两行一模一样,等于什么都没说。
184
+ */
185
+ export function findSection(blocks, reference, scope = 'with-children') {
186
+ const raw = normalizeSectionReference(reference)
187
+ if (normalize(raw) === '') return { code: 'SECTION_REQUIRED', error: '没有给出章节:可以写标题、1 起的章节序号,或该节的块 id。' }
188
+ // 🔴 可定位的标题只取**进目录**的那些:目录页(`Contents`)与噪声标题都不在里面。
189
+ // 前者按标题取到只会回一页页码清单,后者回的是正文里的伪标题 —— 两者都让调用方
190
+ // 以为「这一节读到了」。实测 A-MEM 的 `section("Contents")` 回 ok=true + 810 字符。
191
+ const listed = visibleHeadingIndexes(blocks)
192
+ const listedSet = new Set(listed)
193
+ const headings = listed.filter(index => textOf(blocks[index]?.type) === 'heading')
194
+ const entries = headingEntries(blocks)
195
+ const titles = new Map(entries.map(entry => [entry.index, entry.title]))
196
+
197
+ const ordinal = Number(raw)
198
+ if (Number.isInteger(ordinal) && String(ordinal) === raw && ordinal >= 1) {
199
+ // 🔴 序号按**目录**数,不按全部 heading:被上游误标成标题的正文不进目录,
200
+ // 却仍占一个 heading 块位。按全部数会让 `#25` 之后整段错位
201
+ // (实测 2c3992d2:目录 36 行、heading 50 个,12 行对不上)。
202
+ if (ordinal > headings.length) return { code: 'SECTION_NOT_FOUND', error: '总共只有 ' + headings.length + ' 节,没有第 ' + ordinal + ' 节。先用 outline 看一眼章节树。' }
203
+ const index = headings[ordinal - 1]
204
+ return { ...sectionRange(blocks, index, scope), title: textOf(blocks[index]?.sourceText), index }
205
+ }
206
+
207
+ // 块 id 是**显式地址**,照给;但它可能是目录页或伪标题 —— 那种位置没有可读的正文可切,
208
+ // 如实说清楚比回一段页码清单或一句 caption 好。
209
+ const byId = blocks.findIndex(block => textOf(block?.id) === raw)
210
+ if (byId !== -1 && textOf(blocks[byId]?.type) === 'heading') {
211
+ if (!listedSet.has(byId)) {
212
+ return { code: 'NOT_A_SECTION', error: '块 ' + raw + ' 是「' + textOf(blocks[byId]?.sourceText)
213
+ + '」——这个标题不是章节(目录页或被上游误标成标题的正文),没有可读的正文可切。先用 outline 看一眼章节树。' }
214
+ }
215
+ return { ...sectionRange(blocks, byId, scope), title: textOf(blocks[byId]?.sourceText), index: byId }
216
+ }
217
+
218
+ // Preserve literal titles and paths before trying canonical text and compatibility aliases.
219
+ let exact = [], pathMatches = []
220
+ for (const form of [literal, canonical, normalize]) {
221
+ const key = form(raw)
222
+ const displayed = headings.filter(index => form(titles.get(index)) === key)
223
+ exact = displayed.length ? displayed : headings.filter(index => form(blocks[index]?.sourceText) === key)
224
+ pathMatches = entries.filter(entry => listedSet.has(entry.index) && entry.path?.some((_, start) => form(entry.path.slice(start).join(' / ')) === key))
225
+ if (exact.length > 0 || pathMatches.length > 0) break
226
+ }
227
+ if (exact.length === 1) return { ...sectionRange(blocks, exact[0], scope), title: textOf(blocks[exact[0]]?.sourceText), index: exact[0] }
228
+ if (pathMatches.length === 1) {
229
+ const index = pathMatches[0].index
230
+ return { ...sectionRange(blocks, index, scope), title: titles.get(index), index }
231
+ }
232
+
233
+ // 🔴 片段必须落在**词首且不切词**:裸 `includes` 会让 `section("IV")` 命中
234
+ // "sensitiv**ity**"(实测 MemConflict 因此回了 12216 字符的 4.4 节)—— 那篇根本没有
235
+ // 罗马数字章节,IV 没有合法含义,却拿到 ok=true 的错内容。
236
+ const cjk = '[\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\p{Script=Hangul}]'
237
+ const delimiter = '[^\\p{L}\\p{M}\\p{N}]'
238
+ let partial = pathMatches.length > 1 ? pathMatches.map(entry => entry.index) : []
239
+ if (partial.length === 0) {
240
+ for (const form of [literal, canonical, normalize]) {
241
+ const wanted = form(raw)
242
+ const boundary = new RegExp('(?:^|' + delimiter + '|(?<=' + cjk + '))' + escapeRegExp(wanted) + '(?=$|' + delimiter + '|' + cjk + ')', 'u')
243
+ partial = headings.filter(index => boundary.test(form(titles.get(index))) || boundary.test(form(blocks[index]?.sourceText)))
244
+ if (partial.length > 0) break
245
+ }
246
+ }
247
+ if (partial.length === 1) return { ...sectionRange(blocks, partial[0], scope), title: textOf(blocks[partial[0]]?.sourceText), index: partial[0] }
248
+ const candidates = (exact.length > 1 ? exact : partial)
249
+ if (candidates.length > 1) {
250
+ const shown = candidates.slice(0, 8)
251
+ // 候选里的 `#序号` 必须与目录同口径 —— 否则照抄候选行反而定位到别的一节。
252
+ const list = shown.map(index => {
253
+ const ordinalOf = listed.indexOf(index) + 1
254
+ const id = textOf(blocks[index]?.id)
255
+ return '- #' + ordinalOf + (id === '' ? '' : ' [b:' + id + ']') + ' ' + titles.get(index)
256
+ }).join('\n')
257
+ return {
258
+ code: 'AMBIGUOUS_SECTION',
259
+ candidates: candidates.map(index => ({ blockId: blocks[index].id, title: titles.get(index), ordinal: listed.indexOf(index) + 1 })),
260
+ error: '「' + raw + '」命中 ' + candidates.length + ' 节,请写全标题、#序号或块 id:\n' + list
261
+ + (candidates.length > shown.length ? '\n(只列前 ' + shown.length + ' 条)' : ''),
262
+ }
263
+ }
264
+ return { code: 'SECTION_NOT_FOUND', error: '没有叫「' + raw + '」的章节。先用 outline 看一眼章节树(也可以用 1 起的章节序号)。' }
265
+ }
266
+
267
+ /** Reject selectors for another action instead of silently expanding the requested content. */
268
+ export function validateReadRequest(request) {
269
+ const blockKeys = ['from', 'to', 'blockId', 'span', 'fromBlock', 'toBlock']
270
+ const invalid = [
271
+ ...(request.action === 'blocks' ? [] : blockKeys),
272
+ ...(['section', 'translation'].includes(request.action) ? [] : ['section', 'scope']),
273
+ ...(['outline', 'search'].includes(request.action) ? [] : ['papers']),
274
+ ].filter(key => request[key] !== undefined)
275
+ if (invalid.length > 0) return { ok: false, code: 'INVALID_ARGUMENTS',
276
+ notice: request.action + ' 不支持参数 ' + invalid.join(' / ') + '。' + (invalid.includes('papers')
277
+ ? '单篇动作请只传 paper;多篇请使用 outline 或 search。'
278
+ : '块区间请使用 action="blocks";章节请使用 action="section" 和 section;续读请使用返回的 nextOffset 作为 offset。') }
279
+ if (request.scope !== undefined && !['self', 'with-children'].includes(request.scope)) {
280
+ return { ok: false, code: 'INVALID_SCOPE', notice: 'scope 必须是 self / with-children。' }
281
+ }
282
+ if (request.scope === 'self' && request.section === undefined) return { ok: false, code: 'INVALID_ARGUMENTS', notice: 'scope="self" 需要 section:请指定当前标题的名称或块 id。读取全文请省略 scope。' }
283
+ }
284
+
285
+ /** Stable block addresses are inclusive. Unknown addresses never fall back to the whole paper. */
286
+ export function addressedRange(blocks, request) {
287
+ if (request.span !== undefined && request.blockId === undefined) return { code: 'INVALID_RANGE', error: 'span 必须与 blockId 一起使用。' }
288
+ const addressed = ['blockId', 'fromBlock', 'toBlock'].filter(key => request[key] !== undefined)
289
+ if (addressed.some(key => typeof request[key] !== 'string' || request[key].trim() === '')) return { code: 'BLOCK_REQUIRED', error: '块 id 不能为空。' }
290
+ if ((request.blockId !== undefined && (request.fromBlock !== undefined || request.toBlock !== undefined))
291
+ || (addressed.length > 0 && (request.from !== undefined || request.to !== undefined))) return { code: 'INVALID_RANGE', error: '请使用块 id 或块序号中的一种区间写法。' }
292
+ if (['from', 'to'].some(key => request[key] !== undefined && !Number.isFinite(request[key]))) return { code: 'INVALID_RANGE', error: 'from / to 必须是块序号;块 id 请传 blockId 或 fromBlock / toBlock。' }
293
+ const startId = normalizeBlockId(request.fromBlock ?? request.blockId)
294
+ const endId = normalizeBlockId(request.toBlock)
295
+ if (startId === '' && endId === '') {
296
+ if (request.from !== undefined && request.to !== undefined && request.to < request.from) return { code: 'INVALID_RANGE', error: 'to 不能小于 from。' }
297
+ return blockRange(blocks, request.from, request.to)
298
+ }
299
+ const from = startId === '' ? 0 : blocks.findIndex(block => block.id === startId)
300
+ const last = endId === '' ? undefined : blocks.findIndex(block => block.id === endId)
301
+ if (from < 0 || last === -1) return { code: 'BLOCK_NOT_FOUND', error: '块 id 不存在,请使用原始块 id。' }
302
+ const span = request.span ?? 1
303
+ if (!Number.isSafeInteger(span) || span < 1) return { code: 'INVALID_RANGE', error: 'span 必须是正整数。' }
304
+ const to = last === undefined ? Math.min(blocks.length, from + (request.blockId === undefined ? blocks.length : span)) : last + 1
305
+ if (to <= from) return { code: 'INVALID_RANGE', error: '结束块必须在起始块之后或与它相同。' }
306
+ return { from, to }
307
+ }
308
+
309
+ /**
310
+ * 把一串块下标渲染成一段正文,并记下每个块在正文里的字符区间。
311
+ *
312
+ * 抽出来是为了让「数组区间」与「阅读顺序的块列表」两条入口共用同一套渲染与分页逻辑 ——
313
+ * 两处各写一遍必然漂移(噪声标题的降级、代码块取 html 正文这些只在其中一处生效)。
314
+ *
315
+ * @param {object[]} blocks 块列表。
316
+ * @param {number[]} indexes 要渲染的块下标,顺序即输出顺序。
317
+ * @returns {{text: string, spans: Array<{block: object, from: number, to: number}>, total: number}}
318
+ */
319
+ function renderParts(blocks, indexes) {
320
+ const visible = new Set(visibleHeadingIndexes(blocks))
321
+ const spans = []
322
+ const parts = []
323
+ let total = 0
324
+ for (const index of indexes) {
325
+ const block = blocks[index]
326
+ const text = renderBlock(block, { noise: block?.type === 'heading' && !visible.has(index) })
327
+ if (text === '') continue
328
+ if (parts.length > 0) { parts.push('\n\n'); total += 2 }
329
+ spans.push({ block, from: total, to: total + text.length })
330
+ parts.push(text)
331
+ total += text.length
332
+ }
333
+ return { text: parts.join(''), spans, total }
334
+ }
335
+
336
+ /** 数组区间 → 块下标列表。 */
337
+ function indexesOf(from, to) {
338
+ const indexes = []
339
+ for (let index = from; index < to; index += 1) indexes.push(index)
340
+ return indexes
341
+ }
342
+
343
+ /** Offset counts UTF-16 characters in the rendered range; every page ends on a Unicode boundary. */
344
+ export function slicePage(blocks, from, to, offset = 0) {
345
+ return pageOfParts(renderParts(blocks, indexesOf(from, to)), offset)
346
+ }
347
+
348
+ /**
349
+ * 按**阅读顺序**的块列表切一页正文。与 {@link slicePage} 同口径,坐标换成阅读顺序。
350
+ *
351
+ * @param {object[]} blocks 块列表。
352
+ * @param {number[]} members 该节的块下标(来自 reading-order.sectionBlocks)。
353
+ * @param {number} [offset] 字符偏移。
354
+ */
355
+ export function sliceMembersPage(blocks, members, offset = 0) {
356
+ return pageOfParts(renderParts(blocks, Array.isArray(members) ? members : []), offset)
357
+ }
358
+
359
+ /** 渲染结果 → 一页(offset / 截断 / blockIds / 页码)。两条入口共用。 */
360
+ function pageOfParts({ text: full, spans, total }, offset) {
361
+ if (!Number.isSafeInteger(offset) || offset < 0) return { ok: false, code: 'INVALID_OFFSET', notice: 'offset 必须是从 0 起的整数。' }
362
+ if (offset > total || (offset > 0 && /[\uDC00-\uDFFF]/.test(full[offset] ?? '') && /[\uD800-\uDBFF]/.test(full[offset - 1]))) {
363
+ return { ok: false, code: 'INVALID_OFFSET', notice: 'offset 超出正文或落在 Unicode 字符中间,请使用上次的 nextOffset。' }
364
+ }
365
+ let used = 0
366
+ let end = offset
367
+ for (const char of full.slice(offset)) {
368
+ const size = Buffer.byteLength(char, 'utf8')
369
+ if (used + size > MAX_TEXT_BYTES) break
370
+ used += size
371
+ end += char.length
372
+ }
373
+ const covered = spans.filter(span => span.to > offset && span.from < end).map(span => span.block)
374
+ const pages = covered.map(block => block.page).filter(page => Number.isSafeInteger(page) && page > 0)
375
+ return {
376
+ ok: true, text: full.slice(offset, end), offset, totalChars: total,
377
+ truncated: end < total,
378
+ ...(end < total ? { nextOffset: end } : {}),
379
+ blockIds: covered.map(block => block.id),
380
+ pageFrom: pages.length > 0 ? Math.min(...pages) : undefined,
381
+ pageTo: pages.length > 0 ? Math.max(...pages) : undefined,
382
+ notice: '',
383
+ }
384
+ }
385
+
386
+ /** 按块序号(1 起、含两端)取区间,越界自动夹到合法范围。 */
387
+ export function blockRange(blocks, from, to) {
388
+ const total = blocks.length
389
+ const start = Number.isFinite(from) ? Math.min(Math.max(Math.floor(from), 1), total) : 1
390
+ const end = Number.isFinite(to) ? Math.min(Math.max(Math.floor(to), start), total) : total
391
+ return { from: start - 1, to: end }
392
+ }
393
+
394
+ /** 块下标列表 → 正文。块之间空一行,块 id 不外露(模型要 id 时用 blockIds 字段)。 */
395
+ export function sliceMembersText(blocks, members) {
396
+ // 噪声集合按**整个文档**算(层级与噪声都是全文性质),只对切出来的块生效。
397
+ const visible = new Set(visibleHeadingIndexes(blocks))
398
+ const out = []
399
+ for (const index of Array.isArray(members) ? members : []) {
400
+ const block = blocks[index]
401
+ const noise = block?.type === 'heading' && !visible.has(index)
402
+ const line = renderBlock(block, { noise })
403
+ if (line !== '') out.push(line)
404
+ }
405
+ return out.join('\n\n')
406
+ }
407
+
408
+ /** 区间 → 正文。{@link sliceMembersText} 的数组区间版。 */
409
+ export function sliceText(blocks, from, to) {
410
+ return sliceMembersText(blocks, indexesOf(from, to))
411
+ }
412
+
413
+ /** 按 UTF-8 字节上限截断,并如实标记截断。 */
414
+ export function clampText(text) {
415
+ if (Buffer.byteLength(text, 'utf8') <= MAX_TEXT_BYTES) return { text, truncated: false }
416
+ // 按字符退,退到装得下为止;避免把一个多字节字符砍成两半。
417
+ let cut = 0
418
+ let bytes = 0
419
+ for (const char of text) {
420
+ bytes += Buffer.byteLength(char, 'utf8')
421
+ if (bytes > MAX_TEXT_BYTES) break
422
+ cut += char.length
423
+ }
424
+ return { text: text.slice(0, cut), truncated: true }
425
+ }