@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
@@ -0,0 +1,660 @@
1
+ /**
2
+ * Paper_read 工具:按结构读一篇论文,而不是把整份 Markdown 丢给模型。
3
+ *
4
+ * 分工与前两个工具一致 —— 这里只负责 schema、指认与把宿主结果摆成稳定形状;
5
+ * 真正的读盘(块列表 / 译文 / 划线 / 边注 / 原页图)经 `deps.read` 交回宿主侧。
6
+ *
7
+ * 切片(sectionRange / findSection / blockRange / sliceText / clampText)在
8
+ * `slicing.js` —— 那是块模型的能力,宿主与工具都从那里取,工具模块不必持有它。
9
+ */
10
+
11
+ import { identifyDocument, identityRecordOf } from './tool-identity.js'
12
+ import { BIBLIOGRAPHY_SCHEMA, METADATA_SOURCES_SCHEMA } from './paper-metadata.js'
13
+ import { toolContract } from './tool-contract.js'
14
+ import { validateReadRequest } from './slicing.js'
15
+
16
+ /** 笔记 / 划线 / 边注一次最多回多少条。 */
17
+ export const MAX_ENTRIES = 200
18
+
19
+ /** 批量章节树:每篇默认多少字符、上限多少。章节树是骨架,不是正文,但 12 篇也不该无上限地塞。 */
20
+ export const OUTLINE_DEFAULT_CHARS = 8000
21
+ export const OUTLINE_MAX_CHARS = 32000
22
+
23
+ export const ACTIONS = Object.freeze(['outline', 'section', 'blocks', 'notes', 'translation', 'page', 'meta', 'search', 'audit'])
24
+
25
+ const ACTION_TEXT = Object.freeze({
26
+ outline: '章节树(带块 id 与页码范围)',
27
+ section: '按章节读正文',
28
+ blocks: '按块 id 或块序号区间读正文',
29
+ notes: '读已有的划线、笔记与边注线程',
30
+ translation: '读译文(逐块中文)',
31
+ page: '把原始页面渲染成图片',
32
+ meta: '看这篇的元数据与解析状态',
33
+ search: '跨篇检索正文(不传 paper;命中带 blockId,可直接接 blocks 与 Paper_annotate)',
34
+ audit: '只读检查空节、重复标题和块 id;不自动修改解析结果',
35
+ })
36
+
37
+ const MARK_SCHEMA = {
38
+ type: 'object',
39
+ additionalProperties: false,
40
+ properties: {
41
+ blockId: { type: 'string' },
42
+ quote: { type: 'string' },
43
+ color: { type: 'string' },
44
+ note: { type: 'string' },
45
+ gloss: { type: 'string' },
46
+ anchor: { type: 'string' },
47
+ createdAt: { type: 'string' },
48
+ },
49
+ required: ['blockId'],
50
+ }
51
+
52
+ const THREAD_SCHEMA = {
53
+ type: 'object',
54
+ additionalProperties: false,
55
+ properties: {
56
+ id: { type: 'string' },
57
+ blockId: { type: 'string' },
58
+ quote: { type: 'string' },
59
+ question: { type: 'string' },
60
+ answer: { type: 'string' },
61
+ status: { type: 'string' },
62
+ orphan: { type: 'boolean', description: '原段落已不在当前解析结果中;保留此条笔记供核对。' },
63
+ createdAt: { type: 'string' },
64
+ },
65
+ required: ['blockId'],
66
+ }
67
+
68
+ const PAPER_SCHEMA = {
69
+ type: 'object',
70
+ additionalProperties: false,
71
+ properties: {
72
+ paper: { type: 'string' },
73
+ documentId: { type: 'string' },
74
+ title: { type: 'string' },
75
+ authors: { type: 'array', items: { type: 'string' } },
76
+ authorsEtal: { type: 'boolean', description: '已知作者名单不完整。' },
77
+ year: { type: 'string' },
78
+ markdownPath: { type: 'string' },
79
+ sourceDir: { type: 'string', description: '这篇论文在用户工作文件夹中的来源目录,可关联配套资料。' },
80
+ sourcePdfPath: { type: 'string', description: '导入时的工作文件夹 PDF;与 documentId 指向同一份论文内容,文件可能已被用户移动。' },
81
+ bibliography: BIBLIOGRAPHY_SCHEMA,
82
+ metadataSources: METADATA_SOURCES_SCHEMA,
83
+ blocks: { type: 'number' },
84
+ tags: { type: 'array', items: { type: 'string' } },
85
+ starred: { type: 'boolean' },
86
+ outline: { type: 'object', additionalProperties: false, properties: {
87
+ version: { type: 'number' }, budget: { type: 'number' }, truncated: { type: 'boolean' }, updatedAt: { type: 'string' },
88
+ } },
89
+ },
90
+ required: ['paper', 'documentId'],
91
+ }
92
+
93
+ const OUTPUT_SCHEMA = {
94
+ type: 'object',
95
+ additionalProperties: false,
96
+ properties: {
97
+ ok: { type: 'boolean', description: '这次读取是否成功。' },
98
+ action: { type: 'string', description: '执行的是哪个动作。' },
99
+ notice: { type: 'string', description: '一句话说明拿到了什么;省略或截断会写在这里。' },
100
+ paper: PAPER_SCHEMA,
101
+ text: { type: 'string', description: '正文(章节或块区间),超过上限时截断并在 notice 里说明。' },
102
+ blockIds: { type: 'array', items: { type: 'string' }, description: '这次返回覆盖的块 id。' },
103
+ pageFrom: { type: 'number', description: '起始页码。' },
104
+ pageTo: { type: 'number', description: '结束页码。' },
105
+ marks: { type: 'array', items: MARK_SCHEMA, description: '划线/笔记。' },
106
+ threads: { type: 'array', items: THREAD_SCHEMA, description: '边注提问线程。' },
107
+ translation: {
108
+ type: 'array',
109
+ items: {
110
+ type: 'object',
111
+ additionalProperties: false,
112
+ properties: { blockId: { type: 'string' }, zh: { type: 'string' } },
113
+ required: ['blockId'],
114
+ },
115
+ description: '逐块译文。',
116
+ },
117
+ hits: {
118
+ type: 'array',
119
+ items: {
120
+ type: 'object',
121
+ additionalProperties: false,
122
+ properties: {
123
+ paper: { type: 'string' },
124
+ documentId: { type: 'string' },
125
+ blockId: { type: 'string' },
126
+ paperRank: { type: 'number', description: '这篇论文在本次结果里的相关度排名(1 最相关);同一篇的条目共享它。' },
127
+ score: { type: 'number', description: '本次查询的段落相关度分数;默认使用 BM25 与块种类权重,不用于跨查询比较。' },
128
+ matched: { type: 'string', description: '部分命中时给出「命中词数/总词数」,例如 2/3。没有这个字段 = 全部查询词都命中(精确)。' },
129
+ snippet: { type: 'string' },
130
+ section: { type: 'object', additionalProperties: false, properties: { blockId: { type: 'string' }, title: { type: 'string' } } },
131
+ },
132
+ required: ['paper', 'documentId', 'blockId'],
133
+ },
134
+ description: 'search 动作的命中段落,按相关度排序;blockId 可直接用于 blocks 与 Paper_annotate。',
135
+ },
136
+ failures: { type: 'array', items: { type: 'string' }, description: 'search 里没指认到的论文或未参与检索的篇目。' },
137
+ path: { type: 'string', description: 'page 动作落盘的图片路径。' },
138
+ url: { type: 'string', description: '原页图的访问地址。' },
139
+ image: {
140
+ type: 'object',
141
+ additionalProperties: false,
142
+ properties: {
143
+ attachmentId: { type: 'string' },
144
+ mediaType: { type: 'string' },
145
+ bytes: { type: 'number' },
146
+ width: { type: 'number' },
147
+ height: { type: 'number' },
148
+ },
149
+ required: ['attachmentId', 'mediaType', 'bytes', 'width', 'height'],
150
+ description: '当前模型收图时,原页会作为图片块一并返回(这里是对它的引用)。',
151
+ },
152
+ outlines: {
153
+ type: 'array',
154
+ items: {
155
+ type: 'object',
156
+ additionalProperties: false,
157
+ properties: {
158
+ paper: { type: 'string' },
159
+ documentId: { type: 'string' },
160
+ text: { type: 'string', description: '章节树文本;这篇没有目录时是空串。' },
161
+ sections: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
162
+ blockId: { type: 'string' }, title: { type: 'string' }, chars: { type: 'number' }, path: { type: 'string' },
163
+ } } },
164
+ truncated: { type: 'boolean' },
165
+ offset: { type: 'number' }, nextOffset: { type: 'number' }, totalChars: { type: 'number' },
166
+ },
167
+ required: ['paper', 'documentId'],
168
+ },
169
+ description: 'outline 批量(papers)时每篇的章节树;单篇仍走 text。',
170
+ },
171
+ truncated: { type: 'boolean', description: '正文是否被上限截断;search 时表示这一页之后还有命中。' },
172
+ total: { type: 'number', description: 'search 动作:这次查询在范围内一共命中多少处(不受分页影响)。' },
173
+ offset: { type: 'number', description: '本页起始偏移;正文与目录按字符计,搜索、笔记和译文按条目计。' },
174
+ nextOffset: { type: 'number', description: '保留相同参数,用此 offset 继续读取。' },
175
+ totalChars: { type: 'number' },
176
+ readPages: { type: 'array', items: { type: 'number' }, description: '可用 action="page" 继续核对的原页,paper 保持不变。' },
177
+ staleTranslationCount: { type: 'number', description: '所选范围内已确认与当前原文不符、未作为当前译文返回的块数。' },
178
+ sections: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
179
+ blockId: { type: 'string' }, title: { type: 'string' }, chars: { type: 'number' }, path: { type: 'string' },
180
+ } } },
181
+ issues: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
182
+ code: { type: 'string' }, blockId: { type: 'string' }, title: { type: 'string' },
183
+ // `DISPLACED_BLOCKS` 用:数组顺序在本节区间里、阅读顺序上却属于别的节的块 id。
184
+ // 只报 id 不报正文 —— 体检结果要能被直接转成 `blocks` / `Paper_annotate` 的地址。
185
+ blocks: { type: 'array', items: { type: 'string' } },
186
+ } } },
187
+ candidates: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
188
+ blockId: { type: 'string' }, title: { type: 'string' }, ordinal: { type: 'number' },
189
+ } } },
190
+ // 空节时给出「正文可能在哪」的证据:块 id + 它现在归属的节标题 + 重合的实词。
191
+ evidence: { type: 'object', additionalProperties: false, properties: {
192
+ blockId: { type: 'string' }, sectionTitle: { type: 'string' }, words: { type: 'array', items: { type: 'string' } },
193
+ } },
194
+ engine: {
195
+ type: 'string',
196
+ description: 'search 动作:这次由谁回答 —— index(倒排索引,快)或 scan(扫描回退,慢但永远是对的)。',
197
+ },
198
+ },
199
+ required: ['ok', 'action', 'notice'],
200
+ }
201
+
202
+ function textOf(value) {
203
+ return typeof value === 'string' ? value : ''
204
+ }
205
+
206
+ function messageOf(error) {
207
+ if (error instanceof Error && error.message !== '') return error.message
208
+ const text = textOf(error)
209
+ return text === '' ? '未知错误' : text
210
+ }
211
+
212
+ /** 批量章节树的每篇字符上限:非法值回默认,超过上限就压到上限。 */
213
+ function clampOutlineChars(value) {
214
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 1) return OUTLINE_DEFAULT_CHARS
215
+ return Math.min(Math.floor(value), OUTLINE_MAX_CHARS)
216
+ }
217
+
218
+ function definedFields(source) {
219
+ const result = {}
220
+ for (const [key, value] of Object.entries(source)) {
221
+ if (value !== undefined) result[key] = value
222
+ }
223
+ return result
224
+ }
225
+
226
+ function entryPage(rows, args) {
227
+ const offset = args?.offset ?? 0
228
+ const limit = args?.limit ?? MAX_ENTRIES
229
+ if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1) throw new Error('offset 必须是非负整数,limit 必须是正整数。')
230
+ const items = rows.slice(offset, offset + Math.min(limit, MAX_ENTRIES))
231
+ const next = offset + items.length
232
+ return { items, total: rows.length, offset, ...(next < rows.length ? { nextOffset: next, truncated: true } : {}) }
233
+ }
234
+
235
+
236
+ export function createReadTool(deps = {}) {
237
+ async function papers() {
238
+ if (typeof deps.papers !== 'function') return []
239
+ const list = await deps.papers()
240
+ return Array.isArray(list) ? list : []
241
+ }
242
+
243
+ async function resolve(reference) {
244
+ const list = await papers()
245
+ const hit = identifyDocument(list.map(identityRecordOf).filter(record => record !== null), reference)
246
+ return { list, hit }
247
+ }
248
+
249
+ /**
250
+ * search 的范围指认:点名的论文指认成 id;collection 交给宿主按名字解析(这里没有库);
251
+ * 两边都没有就是全库。
252
+ */
253
+ async function searchScope(args) {
254
+ const references = [
255
+ ...(Array.isArray(args?.papers) ? args.papers : []),
256
+ textOf(args?.paper),
257
+ ].filter(value => typeof value === 'string' && value.trim() !== '')
258
+ if (references.length === 0) return { documentIds: [], failures: [] }
259
+ const records = (await papers()).map(identityRecordOf).filter(record => record !== null)
260
+ const documentIds = []
261
+ const failures = []
262
+ for (const value of references) {
263
+ const hit = identifyDocument(records, value)
264
+ if (hit.document === undefined) failures.push(hit.error)
265
+ else documentIds.push(hit.document.id)
266
+ }
267
+ return { documentIds: [...new Set(documentIds)], failures }
268
+ }
269
+
270
+ const fail = (action, notice, code) => definedFields({ ok: false, action, notice, code })
271
+
272
+ return toolContract({
273
+ name: 'Paper_read',
274
+ description: [
275
+ '按结构读一篇论文:章节树、某一节的正文、块区间、已有划线笔记与边注、译文、原始页面图。',
276
+ 'action=outline 可传 papers 一次要几篇的骨架(写「这一类整体理解」时省掉逐篇往返)。',
277
+ 'paper 接受 64 位 id、PDF 文件名(可省 .pdf)、Markdown 路径或标题片段。',
278
+ 'action=search 例外:不传 paper,跨篇检索正文(范围取 paper/papers、collection,或省略即全库),命中带 blockId。',
279
+ '检索结果按相关度排(不是文档顺序),跨篇时前几条分散在不同的论文上;"词组" 用引号括起来。',
280
+ '只读,不改任何东西;正文超过 32 KB 会截断并说明。读完可以用 Paper_annotate 把结论写回对应段落。',
281
+ ].join('\n'),
282
+ parameters: {
283
+ type: 'object',
284
+ properties: {
285
+ action: {
286
+ type: 'string',
287
+ enum: [...ACTIONS],
288
+ description: ACTIONS.map(name => name + '(' + ACTION_TEXT[name] + ')').join(';'),
289
+ },
290
+ paper: { type: 'string', description: '读哪一篇:id、PDF 文件名、Markdown 路径或标题片段。' },
291
+ section: { type: 'string', description: 'section / translation 用:章节标题、#序号,或该节的块 id(可直接抄 [b:id])。同名章节请用 candidates 中的 blockId;省略则取整篇。' },
292
+ from: { type: 'number', description: 'blocks 用:起始块序号(1 起,含)。' },
293
+ to: { type: 'number', description: 'blocks 用:结束块序号(含)。' },
294
+ blockId: { type: 'string', description: 'blocks 用:稳定块 id,支持裸 id、b: 前缀、[b:id] 或完整 <!-- b:id --> 标记,均可带反引号;默认读一个块。' },
295
+ span: { type: 'number', description: 'blocks + blockId 用:连续读取的块数。' },
296
+ fromBlock: { type: 'string', description: 'blocks 用:起始块 id(含)。' },
297
+ toBlock: { type: 'string', description: 'blocks 用:结束块 id(含)。' },
298
+ scope: { type: 'string', enum: ['self', 'with-children'], description: 'section / translation:默认 with-children;self 只读当前标题直接所属的正文。' },
299
+ order: { type: 'string', enum: ['score', 'paper'], description: 'search:默认 score 按段落分数排;paper 按论文相关度分组,每篇内部按分数排。' },
300
+ page: { type: 'number', description: 'page 用:页码(1 起)。' },
301
+ width: { type: 'number', description: 'page 用:渲染宽度(像素,默认 1200,上限 4096)。' },
302
+ status: { type: 'string', enum: ['unread', 'reading', 'read'], description: 'search 用:只在某个阅读状态的论文里搜 —— 「还没读的论文里哪些提到 X」用它答,决定下一篇读什么。' },
303
+ trashed: { type: 'boolean', description: 'search 用:true = 只在回收站里搜。给了 status 或 tags 时默认排除回收站。' },
304
+ query: { type: 'string', description: 'search 用:关键词;自动处理标点、英文问句常词与常见词形(如 forget / forgetting、temporal / temporality)。默认同一段里全部命中;零命中时只返回覆盖多数关键词的部分命中。"..." 内是必须出现的连续片段,也可用于代码或公式(如 "std::vector<int>"),保留未配对的尖括号与运算符。成对的排版标记会折叠;要按字面搜成对 HTML/XML,在双引号内用反引号包住片段(如 "`<b>retrieval</b>`")。含数字的连字符或点号术语(如 GPT-4、0.05)按连续写法匹配,数字或版本标识不能在降级时省略。中文按子串;不自动推断同义词或跨语言含义,零命中后可换关键词或读 outline / section。' },
305
+ collection: { type: 'string', description: 'search 用:只在某个集合里搜(短名或「父 / 子」全路径,含子集合)。' },
306
+ tags: { type: 'array', items: { type: 'string' }, description: 'search 用:只在这些标签的论文里搜(多个标签是「同时都有」);list 的 tag 是单选,这里是多选。' },
307
+ papers: { type: 'array', items: { type: 'string' }, description: '多篇:search 用它限定检索范围;outline 用它一次要几篇的章节树(写法同 paper)。' },
308
+ limit: { type: 'number', description: 'search:每页默认 20,上限 50;notes / translation:默认与上限均为 200。' },
309
+ offset: { type: 'number', description: '从 0 起:section / blocks / outline 按字符偏移(多篇 outline 只读首页,须用单篇 paper 续读);search / notes / translation 按条目偏移。截断后保留原参数、用返回的 nextOffset 继续。' },
310
+ snippetChars: { type: 'number', description: 'search 用:每段片段多少字符,默认 90,上限 2000。要整段就调大。' },
311
+ maxChars: { type: 'number', description: 'outline 批量时每篇章节树最多多少字符,默认 ' + OUTLINE_DEFAULT_CHARS + ',上限 ' + OUTLINE_MAX_CHARS + '。' },
312
+ chars: { type: 'boolean', description: 'outline 默认返回 sections 章节列表;true 额外附每节字符数(含子节)。' },
313
+ },
314
+ required: ['action'],
315
+ },
316
+ output: {
317
+ schema: OUTPUT_SCHEMA,
318
+ // 图片块与文本块并排:模型收图时能直接看页面,不收图时这里只出文本,
319
+ // 由 path 给出落盘位置(两种情形同一份返回值,不靠调用方挑分支)。
320
+ render: (_args, value) => value.image === undefined
321
+ ? [{ type: 'text', text: value.notice }]
322
+ : [{ type: 'text', text: value.notice }, { type: 'image', attachment: value.image }],
323
+ },
324
+
325
+ async execute(args, exec) {
326
+ const action = textOf(args?.action).trim()
327
+ if (!ACTIONS.includes(action)) return fail(action, '不认识的 action。可用的是:' + ACTIONS.join('、') + '。')
328
+ const invalid = validateReadRequest({ ...args, action })
329
+ if (invalid) return fail(action, invalid.notice, invalid.code)
330
+
331
+ // search 是唯一不指认"一篇"的动作:它问的是「哪些篇里有这段话」,所以先于 paper 校验。
332
+ if (action === 'search') {
333
+ const query = textOf(args?.query).trim()
334
+ if (query === '') return fail(action, 'search 需要 query:要搜的词;多个词之间是「同一段里都出现」。')
335
+ if (typeof deps.search !== 'function') return fail(action, '这个宿主没有提供跨篇检索能力。')
336
+ const scope = await searchScope(args)
337
+ if (scope.documentIds.length === 0 && scope.failures.length > 0) return fail(action, scope.failures[0])
338
+ let result
339
+ try {
340
+ result = await deps.search({
341
+ query,
342
+ documentIds: scope.documentIds,
343
+ collection: textOf(args?.collection),
344
+ // 阅读状态与标签与「范围」正交:范围决定候选池,这两个再筛一层。
345
+ status: textOf(args?.status),
346
+ tags: Array.isArray(args?.tags) ? args.tags : undefined,
347
+ trashed: typeof args?.trashed === 'boolean' ? args.trashed : undefined,
348
+ limit: args?.limit,
349
+ offset: args?.offset,
350
+ snippetChars: args?.snippetChars,
351
+ order: args?.order,
352
+ })
353
+ } catch (error) {
354
+ return fail(action, '检索失败:' + messageOf(error))
355
+ }
356
+ const rows = (Array.isArray(result?.hits) ? result.hits : []).map(hit => definedFields({
357
+ paper: textOf(hit?.paper),
358
+ documentId: textOf(hit?.documentId),
359
+ blockId: textOf(hit?.blockId),
360
+ paperRank: Number.isFinite(hit?.paperRank) ? hit.paperRank : undefined,
361
+ score: Number.isFinite(hit?.score) ? hit.score : undefined,
362
+ matched: textOf(hit?.matched) || undefined,
363
+ snippet: textOf(hit?.snippet) || undefined,
364
+ section: hit?.section,
365
+ })).filter(row => row.paper !== '' && row.documentId !== '' && row.blockId !== '')
366
+ const failures = [
367
+ ...scope.failures,
368
+ ...(Array.isArray(result?.failures) ? result.failures.map(String) : []),
369
+ ]
370
+ return definedFields({
371
+ ok: result?.ok !== false,
372
+ action,
373
+ notice: textOf(result?.notice) || (rows.length === 0 ? '没有命中。' : '命中 ' + rows.length + ' 段。'),
374
+ hits: rows.length > 0 ? rows : undefined,
375
+ failures: failures.length > 0 ? failures : undefined,
376
+ total: Number.isFinite(result?.matched) ? result.matched : undefined,
377
+ offset: Number.isFinite(result?.offset) ? result.offset : undefined,
378
+ nextOffset: Number.isFinite(result?.nextOffset) ? result.nextOffset : undefined,
379
+ engine: textOf(result?.engine) || undefined,
380
+ code: result?.code,
381
+ truncated: result?.truncated === true ? true : undefined,
382
+ })
383
+ }
384
+
385
+ // outline 支持一次要几篇:写「这一类整体理解」要扫一整个集合的骨架,
386
+ // 逐篇调用等于把 N 次往返摊在模型身上。批量分支先于单篇校验。
387
+ if (action === 'outline') {
388
+ const references = [
389
+ ...(Array.isArray(args?.papers) ? args.papers : []),
390
+ textOf(args?.paper),
391
+ ].filter(value => typeof value === 'string' && value.trim() !== '')
392
+ if (references.length === 0) return fail(action, '需要 paper 或 papers:id、PDF 文件名、Markdown 路径或标题片段都行。')
393
+ const continuation = args?.offset ?? 0
394
+ const singleReference = textOf(args?.paper).trim() !== '' && (!Array.isArray(args?.papers) || args.papers.length === 0)
395
+ if (continuation !== 0 && !singleReference) return fail(action, '批量目录只读首页,每篇游标彼此独立;请用单篇 paper 与该篇的 nextOffset 续读,不要把一篇的游标用于整个批次。', 'INVALID_OFFSET')
396
+ if (typeof deps.read !== 'function') return fail(action, '这个宿主没有提供阅读能力。')
397
+ const list = await papers()
398
+ // 同一份 identityRecordOf:这里是**第四**处手拼记录,漏掉它的后果是
399
+ // 「meta 认文件夹名、outline 不认」—— 同一个工具里两条动作互相矛盾。
400
+ const records = list.map(identityRecordOf).filter(record => record !== null)
401
+ const wanted = []
402
+ const failures = []
403
+ for (const value of references) {
404
+ const hit = identifyDocument(records, value)
405
+ if (hit.document === undefined) failures.push(hit.error)
406
+ else if (!wanted.includes(hit.document.id)) wanted.push(hit.document.id)
407
+ }
408
+ if (failures.length > 0) return { ...fail(action, failures[0] ?? '没有找到要读的论文。', 'PAPER_NOT_FOUND'), failures }
409
+ if (wanted.length === 0) return fail(action, '没有找到要读的论文。', 'PAPER_NOT_FOUND')
410
+
411
+ const maxChars = clampOutlineChars(args?.maxChars)
412
+ const offset = args?.offset ?? 0
413
+ if (!Number.isSafeInteger(offset) || offset < 0) return fail(action, 'offset 必须是从 0 起的整数。', 'INVALID_OFFSET')
414
+ const rows = []
415
+ let failureCode
416
+ for (const documentId of wanted) {
417
+ const record = list.find(entry => (entry.id ?? entry.documentId) === documentId)
418
+ const name = textOf(record?.pdfName) || documentId
419
+ let outcome
420
+ try {
421
+ outcome = await deps.read({ action: 'outline', documentId, chars: args?.chars === true, sessionId: exec?.agent?.session?.id })
422
+ } catch (error) {
423
+ // 一篇读不出来不该让整批失败:与 search 同一条口径。
424
+ failures.push(name + ':' + messageOf(error))
425
+ continue
426
+ }
427
+ if (outcome?.ok === false) { failureCode = outcome.code; failures.push(name + ':' + (textOf(outcome.notice) || '读不出章节树')); continue }
428
+ const full = textOf(outcome?.text)
429
+ // 按字符截断(不是字节):章节树是给人/模型看的骨架,字符边界才是它自己的单位。
430
+ if (offset > full.length || (offset > 0 && /[\uDC00-\uDFFF]/.test(full[offset] ?? '') && /[\uD800-\uDBFF]/.test(full[offset - 1]))) {
431
+ failureCode = 'INVALID_OFFSET'
432
+ failures.push(name + ':offset 无效,请使用上次的 nextOffset。')
433
+ continue
434
+ }
435
+ let stop = offset
436
+ let count = 0
437
+ for (const char of full.slice(offset)) {
438
+ if (count++ >= maxChars) break
439
+ stop += char.length
440
+ }
441
+ const text = full.slice(offset, stop)
442
+ const end = offset + text.length
443
+ rows.push(definedFields({
444
+ paper: name,
445
+ documentId,
446
+ text,
447
+ offset, totalChars: full.length,
448
+ truncated: end < full.length || outcome?.truncated === true ? true : undefined,
449
+ nextOffset: end < full.length ? end : undefined,
450
+ ...(Array.isArray(outcome?.sections) ? { sections: outcome.sections.filter(section => {
451
+ const at = full.indexOf('[b:' + section.blockId + ' ..')
452
+ return at >= offset && at < end
453
+ }) } : {}),
454
+ }))
455
+ }
456
+
457
+ // 单篇仍然走原来的 text 与原来的回执:只问一篇时不该让调用方去翻数组,
458
+ // 也不该让「这篇还没有章节树」这条既有提示变样。
459
+ if (rows.length === 1 && failures.length === 0) {
460
+ const only = rows[0]
461
+ const single = list.find(entry => (entry.id ?? entry.documentId) === only.documentId)
462
+ return definedFields({
463
+ ok: true,
464
+ action,
465
+ paper: definedFields({
466
+ paper: textOf(single?.pdfName) || only.documentId,
467
+ documentId: only.documentId,
468
+ title: textOf(single?.title) || undefined,
469
+ authors: Array.isArray(single?.authors) && single.authors.length > 0 ? single.authors.map(String) : undefined,
470
+ year: textOf(single?.year) || undefined,
471
+ markdownPath: textOf(single?.markdownPath) || undefined,
472
+ sourceDir: textOf(single?.sourceDir) || undefined,
473
+ sourcePdfPath: textOf(single?.sourcePdfPath) || undefined,
474
+ }),
475
+ notice: only.nextOffset !== undefined ? '章节树本页如下;使用 offset=' + only.nextOffset + ' 继续。' : (only.text ?? '') === ''
476
+ ? '这篇还没有章节树(可能在解析中或没有 content.json)。'
477
+ : '章节树如下;块 id 可直接用于 section 与 Paper_annotate。',
478
+ text: only.text,
479
+ truncated: only.truncated,
480
+ offset: only.offset, totalChars: only.totalChars, nextOffset: only.nextOffset,
481
+ sections: only.sections,
482
+ })
483
+ }
484
+ if (rows.length === 0) return definedFields({ ok: false, action, code: failureCode, notice: failures[0] ?? '没有读到任何章节树。', failures })
485
+ const empty = rows.filter(row => (row.text ?? '') === '').length
486
+ return definedFields({
487
+ ok: failures.length === 0,
488
+ action,
489
+ notice: rows.length + ' 篇的章节树'
490
+ + (empty > 0 ? '(' + empty + ' 篇没有目录)' : '')
491
+ + (failures.length > 0 ? ',' + failures.length + ' 篇失败' : '') + '。',
492
+ outlines: rows,
493
+ failures: failures.length > 0 ? failures : undefined,
494
+ })
495
+ }
496
+
497
+ const reference = textOf(args?.paper).trim()
498
+ if (reference === '') return fail(action, '需要 paper:id、PDF 文件名、Markdown 路径或标题片段都行。')
499
+
500
+ // 指认只管交给 identifyDocument:它已经把 id / 篇名 / 主名 / 路径 / 标题全部试过,
501
+ // 这里再按路径兜一层是同一件事的第二种写法(且永远走不到)。
502
+ const { list, hit } = await resolve(reference)
503
+ if (hit.document === undefined) return fail(action, hit.error, hit.code)
504
+ const documentId = hit.document.id
505
+ const record = list.find(entry => (entry.id ?? entry.documentId) === documentId)
506
+ const paper = definedFields({
507
+ paper: textOf(record?.pdfName) || documentId,
508
+ documentId,
509
+ title: textOf(record?.title) || undefined,
510
+ authors: Array.isArray(record?.authors) && record.authors.length > 0 ? record.authors.map(String) : undefined,
511
+ year: textOf(record?.year) || undefined,
512
+ markdownPath: textOf(record?.markdownPath) || undefined,
513
+ // 用户工作区里那篇论文的文件夹:配套的 Source/ 与 Thought.md 都按它定位。
514
+ sourceDir: textOf(record?.sourceDir) || undefined,
515
+ sourcePdfPath: textOf(record?.sourcePdfPath) || undefined,
516
+ })
517
+
518
+ if (action === 'meta') {
519
+ const result = typeof deps.read === 'function' ? await deps.read({ action, documentId }) : {}
520
+ if (result?.ok === false) return fail(action, result.notice, result.code)
521
+ return definedFields({ ok: true, action, notice: '论文信息如下。', paper: { ...paper, ...result?.metadata } })
522
+ }
523
+
524
+ if (typeof deps.read !== 'function') return fail(action, '这个宿主没有提供阅读能力。')
525
+ let outcome
526
+ try {
527
+ outcome = await deps.read({
528
+ action,
529
+ documentId,
530
+ sessionId: exec?.agent?.session?.id,
531
+ // 原页图要不要以图片块返回,取决于**这次调用**的模型路由,所以 agent 得透下去。
532
+ agent: exec?.agent,
533
+ section: args?.section === undefined ? undefined : textOf(args.section),
534
+ offset: args?.offset,
535
+ scope: args?.scope,
536
+ blockId: args?.blockId,
537
+ span: args?.span,
538
+ fromBlock: args?.fromBlock,
539
+ toBlock: args?.toBlock,
540
+ from: args?.from,
541
+ to: args?.to,
542
+ page: args?.page,
543
+ width: args?.width,
544
+ })
545
+ } catch (error) {
546
+ return fail(action, '读取失败:' + messageOf(error))
547
+ }
548
+ if (outcome === null || typeof outcome !== 'object') return fail(action, '读取没有返回结果。')
549
+ if (outcome.ok === false) return definedFields({ ok: false, action, code: outcome.code, notice: textOf(outcome.notice) || '读取失败。',
550
+ candidates: outcome.candidates, readPages: outcome.readPages, pageFrom: outcome.pageFrom, pageTo: outcome.pageTo,
551
+ // 空节的「正文可能在上一节」证据:机器可读地给出块 id 与那一节的标题,
552
+ // 调用方不必去解析 notice 里的中文句子。
553
+ evidence: outcome.evidence,
554
+ })
555
+
556
+ const base = { ok: true, action, paper: outcome.paper ?? paper }
557
+
558
+ if (action === 'audit') {
559
+ const page = entryPage(outcome.issues ?? [], args)
560
+ return definedFields({ ...base, notice: textOf(outcome.notice) || '只读体检完成;重复标题可能是合法结构,请按块 id 区分。', issues: page.items,
561
+ total: page.total, offset: page.offset, nextOffset: page.nextOffset, truncated: page.truncated })
562
+ }
563
+
564
+ if (action === 'section' || action === 'blocks') {
565
+ const text = textOf(outcome.text)
566
+ return definedFields({
567
+ ...base,
568
+ notice: text === ''
569
+ ? (textOf(outcome.notice) || '这一段没有正文。')
570
+ : (textOf(outcome.notice) || '正文如下。') + (outcome.truncated === true ? '这一段较长,已截断;保留原参数,使用 offset=' + outcome.nextOffset + ' 继续读取。' : ''),
571
+ text,
572
+ blockIds: Array.isArray(outcome.blockIds) ? outcome.blockIds : undefined,
573
+ pageFrom: Number.isFinite(outcome.pageFrom) ? outcome.pageFrom : undefined,
574
+ pageTo: Number.isFinite(outcome.pageTo) ? outcome.pageTo : undefined,
575
+ truncated: outcome.truncated === true ? true : undefined,
576
+ offset: outcome.offset,
577
+ nextOffset: outcome.nextOffset,
578
+ totalChars: outcome.totalChars,
579
+ readPages: outcome.readPages,
580
+ })
581
+ }
582
+
583
+ if (action === 'notes') {
584
+ const all = [
585
+ ...(Array.isArray(outcome.marks) ? outcome.marks : []).map(mark => ({ mark })),
586
+ ...(Array.isArray(outcome.threads) ? outcome.threads : []).map(thread => ({ thread })),
587
+ ]
588
+ const page = entryPage(all, args)
589
+ const marks = page.items.filter(row => row.mark).map(row => row.mark).map(mark => definedFields({
590
+ blockId: textOf(mark?.blockId),
591
+ quote: textOf(mark?.quote) || undefined,
592
+ color: textOf(mark?.color) || undefined,
593
+ note: textOf(mark?.note) || undefined,
594
+ gloss: textOf(mark?.gloss) || undefined,
595
+ anchor: textOf(mark?.anchor) || undefined,
596
+ createdAt: textOf(mark?.createdAt) || undefined,
597
+ }))
598
+ const threads = page.items.filter(row => row.thread).map(row => row.thread).map(thread => definedFields({
599
+ id: textOf(thread?.id) || undefined,
600
+ blockId: textOf(thread?.blockId),
601
+ quote: textOf(thread?.quote) || undefined,
602
+ question: textOf(thread?.question) || undefined,
603
+ answer: textOf(thread?.answer) || undefined,
604
+ status: textOf(thread?.status) || undefined,
605
+ orphan: thread?.orphan === true ? true : undefined,
606
+ createdAt: textOf(thread?.createdAt) || undefined,
607
+ }))
608
+ return definedFields({
609
+ ...base,
610
+ notice: page.total === 0 ? '这篇还没有划线、笔记或边注。'
611
+ : page.items.length === 0 ? 'offset 已越过全部 ' + page.total + ' 条笔记;用 offset=0 从头读。'
612
+ : '划线 ' + marks.length + ' 条、边注 ' + threads.length + ' 条。' + (page.nextOffset === undefined ? '' : '用 offset=' + page.nextOffset + ' 继续。'),
613
+ marks: marks.length > 0 ? marks : undefined,
614
+ threads: threads.length > 0 ? threads : undefined,
615
+ total: page.total, offset: page.offset, nextOffset: page.nextOffset, truncated: page.truncated,
616
+ })
617
+ }
618
+
619
+ if (action === 'translation') {
620
+ const all = (Array.isArray(outcome.translation) ? outcome.translation : [])
621
+ .filter(row => textOf(row?.zh) !== '')
622
+ .map(row => ({ blockId: textOf(row.blockId), zh: textOf(row.zh) }))
623
+ const page = entryPage(all, args)
624
+ const rows = page.items
625
+ return definedFields({
626
+ ...base,
627
+ notice: (outcome.notice ? textOf(outcome.notice) + ' ' : '') + (page.total === 0
628
+ ? (outcome.staleTranslationCount > 0 ? '当前范围没有可用译文。' : '这一段还没有译文(可能没翻译,或翻译进行中)。')
629
+ : rows.length === 0 ? 'offset 已越过全部 ' + page.total + ' 块译文;用 offset=0 从头读。'
630
+ : '译文 ' + rows.length + ' 块。' + (page.nextOffset === undefined ? '' : '用 offset=' + page.nextOffset + ' 继续。')),
631
+ translation: rows.length > 0 ? rows : undefined,
632
+ staleTranslationCount: outcome.staleTranslationCount,
633
+ total: page.total, offset: page.offset, nextOffset: page.nextOffset, truncated: page.truncated,
634
+ })
635
+ }
636
+
637
+ // page
638
+ const path = textOf(outcome.path)
639
+ const source = outcome.image ?? {}
640
+ const image = textOf(source.attachmentId) === '' ? undefined : {
641
+ attachmentId: textOf(source.attachmentId),
642
+ mediaType: textOf(source.mediaType),
643
+ bytes: Number.isFinite(source.bytes) ? source.bytes : 0,
644
+ width: Number.isFinite(source.width) ? source.width : 0,
645
+ height: Number.isFinite(source.height) ? source.height : 0,
646
+ }
647
+ return definedFields({
648
+ ...base,
649
+ ok: path !== '' || image !== undefined,
650
+ notice: image !== undefined
651
+ ? '原页图片就在上面。'
652
+ : path === ''
653
+ ? (textOf(outcome.notice) || '这篇文章渲染不出页面图。')
654
+ : '原页已渲染到 ' + path + ';当前模型不收图片,可按路径自行查看。',
655
+ path: path === '' ? undefined : path,
656
+ image,
657
+ })
658
+ },
659
+ })
660
+ }