@li-canghai/dsh-paper 0.0.0-stage → 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 (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -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 +2607 -0
  19. package/lib/client.js +9569 -0
  20. package/lib/code-source.js +68 -0
  21. package/lib/concurrency-gate.js +91 -0
  22. package/lib/context.js +233 -0
  23. package/lib/csl/SOURCES.md +10 -0
  24. package/lib/csl/gb-t-7714.csl +441 -0
  25. package/lib/csl/ieee.csl +520 -0
  26. package/lib/csl/locales-zh-CN.xml +438 -0
  27. package/lib/csl/nature.csl +190 -0
  28. package/lib/discussion.js +400 -0
  29. package/lib/documents.js +67 -0
  30. package/lib/export.js +848 -0
  31. package/lib/file-lock.js +177 -0
  32. package/lib/gloss.js +181 -0
  33. package/lib/glossary.js +279 -0
  34. package/lib/index.js +3862 -0
  35. package/lib/inline-html.js +53 -0
  36. package/lib/install-dependency.js +120 -0
  37. package/lib/item-ops.js +83 -0
  38. package/lib/job-facade.js +58 -0
  39. package/lib/json-store.js +54 -0
  40. package/lib/library-model.js +132 -0
  41. package/lib/library-service.js +180 -0
  42. package/lib/library-tool.js +982 -0
  43. package/lib/library.js +814 -0
  44. package/lib/markdown-assets.js +138 -0
  45. package/lib/markdown-literals.js +93 -0
  46. package/lib/metadata-enrichment.js +516 -0
  47. package/lib/metadata-fetch.js +146 -0
  48. package/lib/metadata-node.js +158 -0
  49. package/lib/metadata-proxy.ps1 +35 -0
  50. package/lib/mineru-config.js +95 -0
  51. package/lib/mineru-sdk-helper.py +123 -0
  52. package/lib/mineru-sdk.js +182 -0
  53. package/lib/mineru.js +268 -0
  54. package/lib/mirror-export.js +240 -0
  55. package/lib/outline.js +296 -0
  56. package/lib/page-image-helper.py +294 -0
  57. package/lib/page-image.js +454 -0
  58. package/lib/paper-metadata.js +242 -0
  59. package/lib/parse-export.js +631 -0
  60. package/lib/pdf-analysis-tool.js +750 -0
  61. package/lib/pdf-metadata-helper.py +75 -0
  62. package/lib/pdf-metadata.js +141 -0
  63. package/lib/pdf-page.js +183 -0
  64. package/lib/pdf-scan.js +134 -0
  65. package/lib/pdf-text.js +68 -0
  66. package/lib/picker.js +305 -0
  67. package/lib/portable.js +379 -0
  68. package/lib/purge.js +170 -0
  69. package/lib/read-tool.js +660 -0
  70. package/lib/reader-store.js +497 -0
  71. package/lib/reading-order.js +207 -0
  72. package/lib/rename-document.js +480 -0
  73. package/lib/rename.js +372 -0
  74. package/lib/renderer-status.js +161 -0
  75. package/lib/resolver.js +1152 -0
  76. package/lib/result-archive.js +157 -0
  77. package/lib/revisions.js +330 -0
  78. package/lib/search-database.js +62 -0
  79. package/lib/search-index.js +601 -0
  80. package/lib/search-scan.js +185 -0
  81. package/lib/search-source.js +23 -0
  82. package/lib/search-terms.js +539 -0
  83. package/lib/section-audit.js +209 -0
  84. package/lib/selection-message.js +332 -0
  85. package/lib/serial-tail.js +21 -0
  86. package/lib/slicing.js +425 -0
  87. package/lib/source-resolver.js +581 -0
  88. package/lib/stem-repair.js +189 -0
  89. package/lib/storage.js +562 -0
  90. package/lib/store-paths.js +253 -0
  91. package/lib/table-gfm.js +236 -0
  92. package/lib/tasks.js +270 -0
  93. package/lib/tex-align.js +509 -0
  94. package/lib/tex-blocks.js +653 -0
  95. package/lib/tex-fetch.js +455 -0
  96. package/lib/tex-figures.js +140 -0
  97. package/lib/tex-inline.js +166 -0
  98. package/lib/tex-merge.js +279 -0
  99. package/lib/tex-pipeline.js +242 -0
  100. package/lib/tex-prepare.js +746 -0
  101. package/lib/tex-tables.js +210 -0
  102. package/lib/text-similarity.js +85 -0
  103. package/lib/tool-contract.js +86 -0
  104. package/lib/tool-host.js +1058 -0
  105. package/lib/tool-identity.js +214 -0
  106. package/lib/translatable-text.js +48 -0
  107. package/lib/translate-prompts.js +709 -0
  108. package/lib/translate-queue.js +418 -0
  109. package/lib/translate-task.js +158 -0
  110. package/lib/translate.js +909 -0
  111. package/lib/update-check.js +438 -0
  112. package/lib/update-contracts.js +75 -0
  113. package/lib/usage.js +282 -0
  114. package/package.json +55 -4
@@ -0,0 +1,750 @@
1
+ /**
2
+ * Paper_analysis 工具:把用户给出的论文来源变成「直接可读的结果」或「可追踪的解析任务」。
3
+ *
4
+ * 不 import 任何同目录协作者(source-resolver / tasks / job-facade)与宿主的 defineTool:它们全部经 deps 注入。
5
+ * 并行的另一条分支同时在写这些文件,加载期 import 会把「对方还没写完」变成「本工具加载失败」。宿主
6
+ * register() 消费的就是返回的对象字面量。
7
+ */
8
+
9
+ import { basename, dirname, resolve } from 'node:path'
10
+ import { toolContract } from './tool-contract.js'
11
+
12
+ /** 轮询上限:一篇永远排不上队的论文不能让后台任务一直挂着等下去。 */
13
+ export const MAX_POLL_ROUNDS = 600
14
+
15
+ /** 轮询间隔默认值;测试用 deps.pollMs 压到 1–5ms,免得一条用例跑十分钟。 */
16
+ export const DEFAULT_POLL_MS = 1000
17
+
18
+ /** wait_ms 的上限。再长就该交给 job_output,而不是让一次工具调用占住整轮。 */
19
+ export const MAX_WAIT_MS = 120 * 1000
20
+
21
+ /** 工具自身的超时预算:比 MAX_WAIT_MS 宽 30 秒,留给排队、快照与返回序列化。 */
22
+ export const TOOL_TIMEOUT_MS = MAX_WAIT_MS + 30 * 1000
23
+
24
+ /** 终态集合与 storage.js 的 TERMINAL_JOB_STATUSES 对齐:只有这四种算「这篇有结论了」。 */
25
+ const TERMINAL_JOB_STATUSES = new Set(['ready', 'failed', 'interrupted', 'retried'])
26
+
27
+ /** 文档 id 是 PDF 内容的 sha256 十六进制串。用来挡住把任意字符串当 id 传给 repository 的调用。 */
28
+ const DOCUMENT_ID_PATTERN = /^[0-9a-f]{64}$/i
29
+
30
+ /** 大纲预算兜底值:与 storage.js 的 DEFAULT_SETTINGS.outlineBudgetBytes 同值,只处理「调用方没传」。
31
+ * 真实部署应由外部把配置值经 deps.outlineBudgetBytes 传进来,别让这里成为第二处默认值来源。 */
32
+ const FALLBACK_OUTLINE_BUDGET_BYTES = 32 * 1024
33
+
34
+ const TOOL_DESCRIPTION = [
35
+ '把论文解析成 Markdown 全文与章节树。source 每行一个,可一次传多篇:本地 PDF 绝对路径、',
36
+ '装 PDF 的文件夹、http(s) 直链、arXiv 编号(1706.03762)、DOI。',
37
+ 'library 默认 true,解析结果入库并长期可取;library=false 走独立解析,不写文献库、',
38
+ '只把 Markdown 放到 PDF 旁边(只接受本地 PDF 路径)。',
39
+ '有结果时给出每篇的篇名、documentId 与章节树(outlineText),用 Paper_read 继续读正文;还没解析过就先回 jobId。',
40
+ '第一次解析要跑远端流水线(分钟级):想一次拿到结果就把 wait_ms 设大(上限 120000),',
41
+ '等不到再用 job_output 继续等。解析结果已存在的论文直接同步返回。',
42
+ '在 run_code 中调用时,外层预算也须覆盖等待时间。调用中断不撤销已入队解析;按中断回执的 jobId 查询,避免重复提交。',
43
+ ].join('\n')
44
+
45
+ const SOURCE_DESCRIPTION = [
46
+ '论文来源,一行一个(可混用):本地 PDF 绝对路径(C:\\papers\\a.pdf)、装 PDF 的文件夹(D:\\papers)、',
47
+ 'http(s) 直链(https://arxiv.org/pdf/1706.03762)、arXiv 编号(1706.03762)、DOI(10.1038/s41586-023-06600-9)。',
48
+ '已入库论文可传完整的 64 位 documentId(大小写均可);路径和编号可带成对引号。',
49
+ 'library=false 时只接受本地 PDF 绝对路径。',
50
+ ].join('\n')
51
+
52
+ /** schema 里声明的顶层字段与 papers 元素字段;测试照它逐字段核对 execute 的返回值。
53
+ * 这是**裸 JSON Schema**:宿主 register() 直接把它交给 assertSupportedJsonSchema,必填只能写成对象级
54
+ * 字符串数组。defineTool 那套「逐属性 required: true」的参数 DSL 在这里会被拒
55
+ * (required is not supported on type "boolean"),整个插件随之加载失败。 */
56
+ const OUTPUT_SCHEMA = {
57
+ type: 'object',
58
+ additionalProperties: false,
59
+ properties: {
60
+ ok: { type: 'boolean', description: '是否至少有一篇论文进入了处理流程或拿到了结果。' },
61
+ mode: { type: 'string', enum: ['result', 'queued'], description: 'result 表示结果已给出;queued 表示在后台解析。' },
62
+ notice: { type: 'string', description: '一句话说明这次调用发生了什么。' },
63
+ taskId: { type: 'string', description: '后台解析任务的编号。' },
64
+ jobId: { type: 'string', description: '宿主后台任务的编号,用 job_output 查询。' },
65
+ jobUnavailableReason: { type: 'string', description: '没有 jobId 的原因;进度需要自行重试查询。' },
66
+ papers: {
67
+ type: 'array',
68
+ items: {
69
+ type: 'object',
70
+ additionalProperties: false,
71
+ properties: {
72
+ pdfName: { type: 'string' },
73
+ pdfPath: { type: 'string' },
74
+ sourceType: { type: 'string' },
75
+ status: { type: 'string', enum: ['ready', 'queued', 'running', 'failed'] },
76
+ documentId: { type: 'string' },
77
+ markdownPath: { type: 'string' },
78
+ sourceDir: { type: 'string' },
79
+ outlineText: { type: 'string' },
80
+ title: { type: 'string' },
81
+ error: { type: 'string' },
82
+ },
83
+ required: ['pdfName', 'pdfPath', 'sourceType', 'status'],
84
+ },
85
+ },
86
+ failures: { type: 'array', items: { type: 'string' } },
87
+ },
88
+ required: ['ok', 'mode', 'notice', 'papers'],
89
+ }
90
+
91
+ function readText(value) {
92
+ return typeof value === 'string' ? value : ''
93
+ }
94
+
95
+ /** 失败项既可能是 Error、给人看的字符串,也可能是 source-resolver 的 { input, error }。
96
+ * 一律折成非空的一句话:对普通对象直接 String() 只会得到 [object Object]。 */
97
+ function messageOf(error) {
98
+ if (error instanceof Error && error.message !== '') return error.message
99
+ const text = readText(error)
100
+ if (text !== '') return text
101
+ if (error !== null && typeof error === 'object') {
102
+ for (const field of ['error', 'message', 'input']) {
103
+ const value = error[field]
104
+ if (value instanceof Error && value.message !== '') return value.message
105
+ const nested = readText(value)
106
+ if (nested !== '') return nested
107
+ }
108
+ } else if (error !== undefined && error !== null) {
109
+ const rendered = String(error)
110
+ if (rendered !== '') return rendered
111
+ }
112
+ return '未知错误'
113
+ }
114
+
115
+ /** 丢掉值为 undefined 的键:宿主按 additionalProperties: false 校验输出,写明 undefined 的键同样是多余字段。 */
116
+ function definedFields(source) {
117
+ const result = {}
118
+ for (const [key, value] of Object.entries(source)) {
119
+ if (value !== undefined) result[key] = value
120
+ }
121
+ return result
122
+ }
123
+
124
+ /** 把 state.jobs 里的原始状态折成 schema 允许的四种之一。 */
125
+ function normalizeStatus(raw) {
126
+ if (raw === 'ready' || raw === 'running' || raw === 'queued') return raw
127
+ // interrupted / retried / 未知值对模型而言都是「这一篇没有可用结果」,按 failed 报。
128
+ return 'failed'
129
+ }
130
+
131
+ /** 独立解析(parse-export)的条目状态 → 输出 schema 允许的四种之一。 */
132
+ const STANDALONE_STATUS = new Map([
133
+ ['pending', 'queued'], ['queued', 'queued'], ['running', 'running'],
134
+ ['failed', 'failed'], ['interrupted', 'failed'],
135
+ ])
136
+
137
+ /** 独立解析里「这一篇已有结论」的两种状态。 */
138
+ const SETTLED_STANDALONE = new Set(['ready', 'failed'])
139
+
140
+ /**
141
+ * `wait_ms` 收口:非数字、负数一律当 0(模型偶尔写成字符串,报参数错不如按 0 走),
142
+ * 超过 {@link MAX_WAIT_MS} 按上限算 —— 再长就该交给 `job_output`,别让一次调用占住整轮。
143
+ *
144
+ * @param {unknown} value 原始参数
145
+ * @returns {number} 实际等待毫秒数
146
+ */
147
+ export function readWaitMs(value) {
148
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return 0
149
+ return Math.min(Math.floor(value), MAX_WAIT_MS)
150
+ }
151
+
152
+ /** state.jobs 的原始状态 → 写进任务输出行的中文。未知状态原样带出,别把它伪装成已知值。 */
153
+ const JOB_STATUS_TEXT = new Map([
154
+ ['ready', '已完成'], ['running', '解析中'], ['queued', '排队中'],
155
+ ['failed', '解析失败'], ['interrupted', '已中断'], ['retried', '已重试'],
156
+ ])
157
+
158
+ const sleep = ms => new Promise(resolve => { setTimeout(resolve, ms) })
159
+
160
+ /** 在 state.jobs 里找某一篇论文最新的解析任务。readyResult 写下的记录不带 kind(「结果已存在、直接复用」的
161
+ * 命中),这里把 kind 缺失也当成候选:只认 kind === 'parse' 的话那类记录永远匹配不到,轮询会一路拖到上限。 */
162
+ function findLatestParseJob(jobs, documentId) {
163
+ let latest
164
+ for (const job of Object.values(jobs ?? {})) {
165
+ if (job === null || typeof job !== 'object') continue
166
+ if (job.documentId !== documentId) continue
167
+ if (job.kind !== undefined && job.kind !== 'parse') continue
168
+ if (latest === undefined || String(job.createdAt ?? '') > String(latest.createdAt ?? '')) latest = job
169
+ }
170
+ return latest
171
+ }
172
+
173
+ export function createPdfAnalysisTool(deps) {
174
+ const publicMessage = typeof deps.publicMessage === 'function' ? deps.publicMessage : value => value
175
+ const pollMs = Number.isFinite(deps?.pollMs) && deps.pollMs >= 0 ? deps.pollMs : DEFAULT_POLL_MS
176
+ const maxPollRounds = Number.isInteger(deps?.maxPollRounds) && deps.maxPollRounds > 0
177
+ ? deps.maxPollRounds
178
+ : MAX_POLL_ROUNDS
179
+ const outlineBudgetBytes = Number.isFinite(deps?.outlineBudgetBytes)
180
+ ? deps.outlineBudgetBytes
181
+ : FALLBACK_OUTLINE_BUDGET_BYTES
182
+
183
+ function warn(message) {
184
+ try {
185
+ deps?.logger?.warn?.(message)
186
+ } catch {
187
+ // 日志通道坏掉不该让工具失败:这里已经是最外层的一行了。
188
+ }
189
+ }
190
+
191
+ /** 按 64 位文档 id 找回 PDF 路径,供来源解析器把「用户直接写了文档 id」翻译成路径。
192
+ * 查不到返回 undefined(由调用方决定怎么报),不抛:这里不是失败路径的判断者。
193
+ *
194
+ * 🔴 **热层查不到要问冷归档**:长期没用的论文会被 `compact()` 挪进 `archive/`,那之后
195
+ * `state.documents` 里就没有它了 —— 只查热层等于「文献库列表里点得到、按 id 调工具却说
196
+ * 库里没有这篇」。`resolver.reparse` 本来就支持 `archivedDocument`,判断不能挡在它前面。
197
+ * 仓储实现没有这个方法(测试替身、老装配)时照旧只查热层。 */
198
+ async function lookupDocument(id) {
199
+ const key = readText(id)
200
+ if (!DOCUMENT_ID_PATTERN.test(key)) return undefined
201
+ try {
202
+ const state = await deps.repository.snapshot()
203
+ const hot = state?.documents?.[key]
204
+ const document = hot ?? await deps.repository?.archivedDocument?.(key)
205
+ const pdfPath = readText(document?.pdfPath) || readText(document?.path)
206
+ return pdfPath === '' ? undefined : { pdfPath }
207
+ } catch (error) {
208
+ warn(`[dsh-paper] 按文档 id 查询 PDF 路径失败:${messageOf(error)}`)
209
+ return undefined
210
+ }
211
+ }
212
+
213
+ /** 取章节树。reader 缺失、Markdown 被删、大纲构建失败都只说明「这篇没有大纲」,不该让整次调用失败
214
+ * ——模型拿到 markdownPath 仍然能自己读文件。 */
215
+ async function readUsable(document, documentId) {
216
+ if (typeof deps.reader?.usableDocument !== 'function') return undefined
217
+ try {
218
+ return await deps.reader.usableDocument(document ?? { id: documentId }, outlineBudgetBytes)
219
+ } catch (error) {
220
+ warn(`[dsh-paper] 读取章节树失败:${messageOf(error)}`)
221
+ return undefined
222
+ }
223
+ }
224
+
225
+ /** result 档:把每篇的 markdownPath 与章节树补进已经构造好的 papers 条目。 */
226
+ async function fillResults(accepted) {
227
+ for (const entry of accepted) {
228
+ const usable = await readUsable(entry.document, entry.paper.documentId)
229
+ const markdownPath = readText(usable?.markdownPath)
230
+ || readText(entry.document?.markdownPath)
231
+ || readText(entry.job?.markdownPath)
232
+ if (markdownPath !== '') entry.paper.markdownPath = markdownPath
233
+ // 复用已有记录时 sourceDir 来自记录本身(本次这条路可能是重指文件夹的回填,也可能只读)。
234
+ const sourceDir = readText(entry.document?.sourceDir)
235
+ if (sourceDir !== '') entry.paper.sourceDir = sourceDir
236
+ const outlineText = readText(usable?.outlineText)
237
+ if (outlineText !== '') entry.paper.outlineText = outlineText
238
+ }
239
+ }
240
+
241
+ function summarize(papers) {
242
+ const ready = papers.filter(paper => paper.status === 'ready')
243
+ const lines = [`成功 ${ready.length} 篇,失败 ${papers.length - ready.length} 篇`]
244
+ for (const paper of papers) {
245
+ const tail = paper.status === 'ready'
246
+ ? (paper.documentId ? '已就绪,可用 Paper_read 继续阅读' : (paper.markdownPath ?? '解析已完成'))
247
+ : publicMessage(paper.error ?? '解析没有产出结果')
248
+ lines.push(`- ${paper.pdfName} → ${tail}`)
249
+ }
250
+ return lines.join('\n')
251
+ }
252
+
253
+ function outcomeOf(papers) {
254
+ const failed = papers.filter(paper => paper.status !== 'ready')
255
+ if (failed.length === 0) {
256
+ return { status: 'completed', detail: `已完成 ${papers.length} 篇解析`, result: summarize(papers) }
257
+ }
258
+ return { status: 'failed', detail: `${failed.length} 篇解析失败`, result: summarize(papers) }
259
+ }
260
+
261
+ /** 宿主契约:run 必须**同步**返回 hooks,所以这里先把轮询 Promise 起出来,再连同同步的 cancel 交出去。取消只置
262
+ * 标志,不反向去停已经提交的解析——那些解析由 state.jobs 独立管理,别处的会话可能正依赖同一份结果。 */
263
+ function createRun(jobHandle, tracked, papers) {
264
+ let cancelled = false
265
+ let cancelReason
266
+
267
+ function callJob(method, payload) {
268
+ const fn = jobHandle?.[method]
269
+ if (typeof fn !== 'function') return
270
+ try {
271
+ fn.call(jobHandle, typeof payload === 'string' ? publicMessage(payload) : payload)
272
+ } catch (error) {
273
+ warn(`[dsh-paper] 写入后台任务进度失败:${messageOf(error)}`)
274
+ }
275
+ }
276
+
277
+ const cancelledOutcome = () => ({ status: 'killed', detail: publicMessage(readText(cancelReason) || '已取消') })
278
+
279
+ function reportProgress() {
280
+ const ready = tracked.filter(entry => entry.paper.status === 'ready').length
281
+ callJob('updateProgress', `已就绪 ${ready}/${tracked.length} 篇`)
282
+ }
283
+
284
+ /** 状态没变就不写行:轮询每轮都 append 同一句会把宿主任务的输出环刷成噪音。 */
285
+ function applyState(state) {
286
+ for (const entry of tracked) {
287
+ const job = findLatestParseJob(state.jobs, entry.paper.documentId)
288
+ if (job === undefined) continue
289
+ const raw = readText(job.status) || 'queued'
290
+ if (raw === entry.rawStatus) continue
291
+ entry.rawStatus = raw
292
+ entry.paper.status = normalizeStatus(raw)
293
+ if (entry.paper.status === 'ready') {
294
+ // 只从 state 取路径:reader 要读整篇 Markdown 才能建大纲,而这里只缺一个路径。
295
+ const markdownPath = readText(state.documents?.[entry.paper.documentId]?.markdownPath)
296
+ if (markdownPath !== '') entry.paper.markdownPath = markdownPath
297
+ }
298
+ callJob('append', `- ${entry.paper.pdfName}:${JOB_STATUS_TEXT.get(raw) ?? raw}`)
299
+ }
300
+ }
301
+
302
+ const done = (async () => {
303
+ let readFailureLogged = false
304
+ for (let round = 1; round <= maxPollRounds; round += 1) {
305
+ await sleep(pollMs)
306
+ if (cancelled) return cancelledOutcome()
307
+
308
+ let state
309
+ try {
310
+ state = await deps.repository.snapshot()
311
+ } catch (error) {
312
+ // 读不到状态不等于解析失败:记一行就够(每轮都记会把环刷满),下一轮再试,轮次上限照样兜底。
313
+ if (!readFailureLogged) {
314
+ readFailureLogged = true
315
+ callJob('append', `读取解析状态失败:${messageOf(error)}`)
316
+ }
317
+ }
318
+ if (state !== undefined) applyState(state)
319
+ if (cancelled) return cancelledOutcome()
320
+
321
+ reportProgress()
322
+ if (tracked.every(entry => TERMINAL_JOB_STATUSES.has(entry.rawStatus))) {
323
+ return outcomeOf(papers)
324
+ }
325
+ }
326
+ // 到点还没结论:可能是排队排不上,也可能是状态被别处改写。报 failed 而不是无限等。
327
+ return { status: 'failed', detail: '等待解析超时', result: summarize(papers) }
328
+ })()
329
+
330
+ return {
331
+ cancel(reason) {
332
+ // 同步且幂等:重复取消不改写已记录的理由,也不抛。
333
+ if (cancelled) return
334
+ cancelled = true
335
+ if (readText(reason) !== '') cancelReason = reason
336
+ },
337
+ done,
338
+ }
339
+ }
340
+
341
+ /**
342
+ * 在调用内等一段时间:`step` 每次返回「是否已经全部有结论」。
343
+ *
344
+ * 到点就返回,不抛:等不到结果是常态(论文要跑分钟级流水线),调用方据此退回 queued。
345
+ */
346
+ async function waitUntil(step, deadline, signal) {
347
+ for (;;) {
348
+ if (signal?.aborted) return
349
+ if (await step()) return
350
+ const remaining = deadline - Date.now()
351
+ if (remaining <= 0) return
352
+ await sleep(Math.max(1, Math.min(pollMs, remaining)))
353
+ }
354
+ }
355
+
356
+ /** 从 state 刷新每篇的状态与 Markdown 路径;读不到状态就什么都不动,让等待继续到点。 */
357
+ async function refreshAccepted(accepted) {
358
+ let state
359
+ try {
360
+ state = await deps.repository.snapshot()
361
+ } catch (error) {
362
+ warn(`[dsh-paper] 等待解析时读状态失败:${messageOf(error)}`)
363
+ return
364
+ }
365
+ for (const entry of accepted) {
366
+ const job = findLatestParseJob(state.jobs, entry.paper.documentId)
367
+ const raw = readText(job?.status) || entry.rawStatus
368
+ entry.rawStatus = raw
369
+ entry.paper.status = normalizeStatus(raw)
370
+ if (entry.paper.status === 'ready') {
371
+ const markdownPath = readText(state.documents?.[entry.paper.documentId]?.markdownPath)
372
+ if (markdownPath !== '') entry.paper.markdownPath = markdownPath
373
+ }
374
+ }
375
+ }
376
+
377
+ /** 独立解析的条目状态:清单里有就按条目报,已导出(从清单删掉、进了 done)就算 ready。 */
378
+ function applyStandalone(traced) {
379
+ const listed = typeof deps.parseExport?.list === 'function' ? deps.parseExport.list() : { items: [], done: [] }
380
+ const live = new Map((Array.isArray(listed.items) ? listed.items : []).map(item => [item.id, item]))
381
+ const finished = new Map((Array.isArray(listed.done) ? listed.done : []).map(entry => [entry.id, entry]))
382
+ for (const entry of traced) {
383
+ const done = finished.get(entry.id)
384
+ if (done !== undefined) {
385
+ entry.paper.status = 'ready'
386
+ const markdownPath = readText(done.markdown)
387
+ if (markdownPath !== '') entry.paper.markdownPath = markdownPath
388
+ continue
389
+ }
390
+ const item = live.get(entry.id)
391
+ if (item === undefined) {
392
+ // 既不在清单也没有产物:条目被别处删掉了,这一篇没有结论。
393
+ entry.paper.status = 'failed'
394
+ if (entry.paper.error === undefined) entry.paper.error = '解析条目已从清单消失,且没有产物'
395
+ continue
396
+ }
397
+ entry.paper.status = STANDALONE_STATUS.get(item.status) ?? 'queued'
398
+ const markdownPath = readText(item.markdown)
399
+ if (markdownPath !== '') entry.paper.markdownPath = markdownPath
400
+ const error = readText(item.error)
401
+ if (entry.paper.status === 'failed' && error !== '') entry.paper.error = error
402
+ }
403
+ }
404
+
405
+ /** 独立解析的后台任务:存在的意义只是让 wait_ms 之后还能用 job_output 继续等。 */
406
+ function createStandaloneRun(jobHandle, traced) {
407
+ let cancelled = false
408
+ let cancelReason
409
+
410
+ function callJob(method, payload) {
411
+ const fn = jobHandle?.[method]
412
+ if (typeof fn !== 'function') return
413
+ try {
414
+ fn.call(jobHandle, typeof payload === 'string' ? publicMessage(payload) : payload)
415
+ } catch (error) {
416
+ warn(`[dsh-paper] 写入后台任务进度失败:${messageOf(error)}`)
417
+ }
418
+ }
419
+
420
+ const settled = () => traced.every(entry => SETTLED_STANDALONE.has(entry.paper.status))
421
+
422
+ const done = (async () => {
423
+ for (let round = 1; round <= maxPollRounds; round += 1) {
424
+ await sleep(pollMs)
425
+ if (cancelled) return { status: 'killed', detail: publicMessage(readText(cancelReason) || '已取消') }
426
+ applyStandalone(traced)
427
+ const papers = traced.map(entry => entry.paper)
428
+ callJob('updateProgress', `已就绪 ${papers.filter(paper => paper.status === 'ready').length}/${papers.length} 篇`)
429
+ if (settled()) return outcomeOf(papers)
430
+ }
431
+ return { status: 'failed', detail: '等待解析超时', result: summarize(traced.map(entry => entry.paper)) }
432
+ })()
433
+
434
+ return {
435
+ cancel(reason) {
436
+ if (cancelled) return
437
+ cancelled = true
438
+ if (readText(reason) !== '') cancelReason = reason
439
+ },
440
+ done,
441
+ }
442
+ }
443
+
444
+ /**
445
+ * `library=false`:走右栏「解析」那条独立通路。
446
+ *
447
+ * 与文献库那条路的区别是结构性的:不产生 `documentId`、不写状态记录、不改文献库;
448
+ * 产物是 PDF 旁边同名的 `.md`(parse-export 的 `mirrorMarkdown` 落地)。
449
+ */
450
+ async function runStandalone(args, { sessionId, requestedTitle, waitMs, signal }) {
451
+ const service = deps.parseExport
452
+ if (service === undefined || service === null) {
453
+ return { ok: false, mode: 'queued', papers: [], notice: '这个宿主没有独立解析服务;把 library 设为 true 走文献库那条路。' }
454
+ }
455
+ if (typeof deps.inspectPdf !== 'function') {
456
+ return { ok: false, mode: 'queued', papers: [], notice: '独立解析缺少 PDF 检查能力,无法校验路径。' }
457
+ }
458
+
459
+ const lines = readText(args?.source).split(/\r\n|\r|\n/).map(line => line.trim()).filter(line => line !== '')
460
+ if (lines.length === 0) {
461
+ return { ok: false, mode: 'queued', papers: [], notice: '没有给出 PDF 路径:library=false 时 source 只接受本地 PDF 绝对路径。' }
462
+ }
463
+
464
+ const failures = []
465
+ const paths = []
466
+ for (const line of lines) {
467
+ try {
468
+ paths.push((await deps.inspectPdf(line)).path)
469
+ } catch (error) {
470
+ failures.push(`${line}:${messageOf(error)}`)
471
+ }
472
+ }
473
+ if (paths.length === 0) {
474
+ return definedFields({
475
+ ok: false,
476
+ mode: 'queued',
477
+ papers: [],
478
+ failures,
479
+ notice: `没有可解析的 PDF:${failures[0] ?? '路径无效'}。library=false 只接受本地 PDF 绝对路径。`,
480
+ })
481
+ }
482
+
483
+ await service.start()
484
+ await service.add(paths)
485
+ // add 会跳过「已在清单里」的路径,所以清单才是条目的唯一可信来源:按路径回查。
486
+ const items = service.items instanceof Map ? [...service.items.values()] : []
487
+ const byPath = new Map(items.map(item => [readText(item.pdfPath).toLowerCase(), item]))
488
+ const traced = []
489
+ const papers = []
490
+ for (const path of paths) {
491
+ const item = byPath.get(path.toLowerCase())
492
+ if (item === undefined) {
493
+ failures.push(`${path}:没能排进解析清单`)
494
+ continue
495
+ }
496
+ const paper = { pdfPath: item.pdfPath, pdfName: item.pdfName, sourceType: 'file', status: 'queued' }
497
+ papers.push(paper)
498
+ traced.push({ id: item.id, paper })
499
+ }
500
+ // 逐条点火:`startRun('')` 会连用户自己在面板上排着、还没点「开始解析」的那批一起烧掉。
501
+ for (const entry of traced) {
502
+ const item = byPath.get(readText(entry.paper.pdfPath).toLowerCase())
503
+ if (item?.status === 'pending') await service.startRun(item.id)
504
+ }
505
+ if (traced.length === 0) {
506
+ return definedFields({ ok: false, mode: 'queued', papers, failures, notice: '没有条目进入独立解析队列。' })
507
+ }
508
+
509
+ const settle = () => {
510
+ applyStandalone(traced)
511
+ return traced.every(entry => SETTLED_STANDALONE.has(entry.paper.status))
512
+ }
513
+ if (waitMs > 0) await waitUntil(settle, Date.now() + waitMs, signal)
514
+ settle()
515
+
516
+ if (papers.every(paper => paper.status === 'ready')) {
517
+ return definedFields({
518
+ ok: true,
519
+ mode: 'result',
520
+ papers,
521
+ failures,
522
+ notice: `这 ${papers.length} 篇已解析完成,Markdown 就在 PDF 旁边。`,
523
+ })
524
+ }
525
+
526
+ let jobId
527
+ let jobUnavailableReason
528
+ const facade = deps.jobFacade
529
+ const label = requestedTitle === '' ? `独立解析 ${papers.length} 篇` : requestedTitle
530
+ if (facade !== undefined && facade !== null && facade.available !== false && typeof facade.start === 'function') {
531
+ try {
532
+ const started = await facade.start({ label, owner: sessionId, run: jobHandle => createStandaloneRun(jobHandle, traced) })
533
+ if (started?.jobId !== undefined && started.jobId !== null) jobId = String(started.jobId)
534
+ else jobUnavailableReason = readText(started?.reason) || '没有后台任务服务'
535
+ } catch (error) {
536
+ jobUnavailableReason = messageOf(error)
537
+ }
538
+ } else {
539
+ jobUnavailableReason = '没有后台任务服务'
540
+ }
541
+
542
+ const parts = [`已提交 ${papers.length} 篇独立解析(不写文献库)`]
543
+ if (jobId !== undefined) parts.push(`后台任务 ${jobId},用 job_output 等结果`)
544
+ else parts.push(`无法跟踪进度:${jobUnavailableReason ?? '未知原因'};稍后用同一批路径再调一次即可接上`)
545
+ return definedFields({ ok: true, mode: 'queued', papers, jobId, jobUnavailableReason, notice: `${parts.join(';')}。`, failures })
546
+ }
547
+
548
+ return toolContract({
549
+ name: 'Paper_analysis',
550
+ description: TOOL_DESCRIPTION,
551
+ // parameters 是**编译后**的 JSON Schema(object 根),不是 defineTool 的参数 DSL:宿主把它原样
552
+ // 交给模型与网关,写成 { source: {…} } 会被当成未知关键字 source 而拒掉。
553
+ parameters: {
554
+ type: 'object',
555
+ properties: {
556
+ source: { type: 'string', description: SOURCE_DESCRIPTION },
557
+ library: {
558
+ type: 'boolean',
559
+ description: '是否入库,默认 true。false = 独立解析:不写文献库、不产生 documentId,只把 Markdown 与图片放到 PDF 旁边。',
560
+ },
561
+ wait_ms: {
562
+ type: 'number',
563
+ description: '可选:最多等多久拿结果(毫秒,0–120000,默认 0 表示不等)。等到就返回可用结果,等不到返回 jobId。',
564
+ },
565
+ title: { type: 'string', description: '可选:给这批论文一个易读的名字。' },
566
+ },
567
+ required: ['source'],
568
+ },
569
+ output: {
570
+ schema: OUTPUT_SCHEMA,
571
+ render: (_args, value) => [{ type: 'text', text: value.notice }],
572
+ },
573
+ // wait_ms 上限 120s,工具预算要比它宽:宿主若按默认预算掐断,等满 120s 的那次调用会被判超时。
574
+ timeoutMs: TOOL_TIMEOUT_MS,
575
+
576
+ async execute(args, exec) {
577
+ const sessionId = exec?.agent?.session?.id
578
+ // 没有会话就没有 cwd。这里不退回 process.cwd():那是宿主的目录,不是用户的项目目录,
579
+ // 相对路径按它解析会得到一个看似合理却错的答案;交给来源解析器按自己的默认处理。
580
+ const cwd = sessionId === undefined ? undefined : deps.sessionCwds?.get?.(sessionId)
581
+ const requestedTitle = readText(args?.title).trim()
582
+ const waitMs = readWaitMs(args?.wait_ms)
583
+ // 两条路的落点完全不同(写不写文献库、有没有 documentId),在解析 source 之前就分叉。
584
+ if (args?.library === false) return await runStandalone(args, { sessionId, requestedTitle, waitMs, signal: exec?.signal })
585
+
586
+ let items = []
587
+ let failures = []
588
+ try {
589
+ const resolved = await deps.resolveSource(args?.source, { cwd, tmpRoot: deps.tmpRoot, lookupDocument })
590
+ items = Array.isArray(resolved?.items) ? resolved.items : []
591
+ failures = (Array.isArray(resolved?.failures) ? resolved.failures : []).map(messageOf)
592
+ } catch (error) {
593
+ // 认不出来的写法是输入问题,不是程序故障。异常冒到宿主只会换来一次工具崩溃,
594
+ // 模型拿不到「换一种写法」这条能执行的提示。
595
+ const reason = messageOf(error)
596
+ return definedFields({
597
+ ok: false,
598
+ mode: 'queued',
599
+ papers: [],
600
+ notice: `没能识别 source:${reason}。可以写本地 PDF 绝对路径、文件夹、http(s) 链接、arXiv 编号或 DOI。`,
601
+ failures: [reason],
602
+ })
603
+ }
604
+
605
+ const papers = []
606
+ /** 与 papers 里是同一批对象引用:后面在 result 档直接补字段,不再重建数组。 */
607
+ const accepted = []
608
+ for (const [index, item] of items.entries()) {
609
+ const pdfPath = readText(item?.pdfPath)
610
+ const sourceType = readText(item?.sourceType) || 'unknown'
611
+ // 「原件在用户哪个目录」只有本地来源才有这个事实:arxiv/doi/url 的 pdfPath 是下载缓存,
612
+ // library 是 runtime 副本 —— 拿它们的 dirname 当 sourceDir 等于伪造一个用户目录。
613
+ const sourceDir = sourceType === 'folder' || sourceType === 'local' ? dirname(resolve(pdfPath)) : ''
614
+ const paper = {
615
+ pdfPath,
616
+ pdfName: readText(item?.pdfName) || basename(pdfPath) || `第 ${index + 1} 篇`,
617
+ sourceType,
618
+ status: 'queued',
619
+ }
620
+ if (sourceDir !== '') paper.sourceDir = sourceDir
621
+ const paperTitle = readText(item?.title)
622
+ if (paperTitle !== '') paper.title = paperTitle
623
+
624
+ if (pdfPath === '') {
625
+ papers.push({ ...paper, status: 'failed', error: '来源没有给出可用的 PDF 路径' })
626
+ continue
627
+ }
628
+
629
+ try {
630
+ // 🔴 目录元数据(arXiv/DOI 的标题、作者、年份)在**这里**交给 resolver:
631
+ // item 上本来就是 source-resolver 采好的,但过去没往下传,于是入库那一刻就丢了,
632
+ // 改名只能退回去猜 PDF 自己的 Info dict —— 而 arXiv 的 LaTeX 产物那里是空的。
633
+ const catalog = { ...item?.metadata, title: readText(item?.title), authors: item?.metadata?.authors, year: item?.metadata?.year }
634
+ // 只有真拿到目录元数据时才挂这个键:空对象传下去会让任务记录平白多个空字段,
635
+ // 也会让"这条记录有哪些键"不再能表达"拿到了什么"。
636
+ const hasCatalog = catalog.title !== '' ||
637
+ (Array.isArray(catalog.authors) && catalog.authors.length > 0) ||
638
+ (typeof catalog.year === 'string' && catalog.year !== '')
639
+ const added = await deps.resolver.add(pdfPath, sessionId, {
640
+ deferCompaction: true,
641
+ ...(hasCatalog ? { metadata: catalog } : {}),
642
+ })
643
+ const job = added?.job
644
+ if (job?.documentId !== undefined && job.documentId !== null) paper.documentId = String(job.documentId)
645
+ paper.status = normalizeStatus(job?.status)
646
+ papers.push(paper)
647
+ // 初始 rawStatus 取 add 当时的状态:轮询第一轮若还是同一个状态,就不该写一行重复的进度。
648
+ accepted.push({ paper, job, document: added?.document, rawStatus: readText(job?.status) || 'queued' })
649
+ } catch (error) {
650
+ // 逐篇隔离:整目录扫描里一篇坏 PDF 不该让其余论文白扫一遍。
651
+ papers.push({ ...paper, status: 'failed', error: messageOf(error) })
652
+ }
653
+ }
654
+
655
+ // wait_ms > 0:先在调用内等一段,等到就按 result 直接给结果,等不到再退回 queued + jobId。
656
+ if (waitMs > 0 && !papers.every(paper => paper.status === 'ready')) {
657
+ await waitUntil(async () => {
658
+ await refreshAccepted(accepted)
659
+ return accepted.every(entry => TERMINAL_JOB_STATUSES.has(entry.rawStatus))
660
+ }, Date.now() + waitMs, exec?.signal)
661
+ }
662
+
663
+ // D84:判据是「结果是否已存在」,不是「用户传了几篇」。第一次解析一篇也走 queued。
664
+ const mode = papers.length > 0 && papers.every(paper => paper.status === 'ready') ? 'result' : 'queued'
665
+
666
+ if (mode === 'result') {
667
+ await fillResults(accepted)
668
+ return definedFields({
669
+ ok: true,
670
+ mode: 'result',
671
+ papers,
672
+ notice: `这 ${papers.length} 篇论文已有解析结果,篇名、论文 id 与章节树见 papers;用 Paper_read 继续阅读。`,
673
+ failures,
674
+ })
675
+ }
676
+
677
+ const tracked = accepted.filter(entry => entry.paper.documentId !== undefined)
678
+ if (tracked.length === 0) {
679
+ const reason = failures[0]
680
+ ?? papers.find(paper => paper.error !== undefined)?.error
681
+ ?? '来源里没有可用的 PDF'
682
+ return definedFields({
683
+ ok: false,
684
+ mode: 'queued',
685
+ papers,
686
+ notice: `没有论文进入解析队列:${reason}`,
687
+ failures,
688
+ })
689
+ }
690
+
691
+ const label = requestedTitle === '' ? `解析 ${papers.length} 篇论文` : requestedTitle
692
+ const taskItems = tracked.map(entry => ({
693
+ key: entry.paper.documentId,
694
+ label: entry.paper.pdfName,
695
+ documentId: entry.paper.documentId,
696
+ pdfPath: entry.paper.pdfPath,
697
+ }))
698
+
699
+ let taskId
700
+ let taskNote
701
+ if (typeof deps.tasks?.createTask === 'function') {
702
+ try {
703
+ const task = await deps.tasks.createTask({ kind: 'pdf-analysis', sessionId, label, items: taskItems })
704
+ if (task?.id !== undefined && task.id !== null) taskId = String(task.id)
705
+ } catch (error) {
706
+ taskNote = messageOf(error)
707
+ }
708
+ } else {
709
+ // 任务清单只是给人看的登记簿,缺它不影响解析本身,所以不失败、只降级说明。
710
+ taskNote = '宿主没有提供任务清单服务'
711
+ }
712
+
713
+ let jobId
714
+ let jobUnavailableReason
715
+ const facade = deps.jobFacade
716
+ if (facade !== undefined && facade !== null && facade.available !== false && typeof facade.start === 'function') {
717
+ try {
718
+ const started = await facade.start({
719
+ label,
720
+ owner: sessionId,
721
+ run: jobHandle => createRun(jobHandle, tracked, papers),
722
+ })
723
+ if (started?.jobId !== undefined && started.jobId !== null) jobId = String(started.jobId)
724
+ else jobUnavailableReason = readText(started?.reason) || '没有后台任务服务'
725
+ } catch (error) {
726
+ jobUnavailableReason = messageOf(error)
727
+ }
728
+ } else {
729
+ jobUnavailableReason = '没有后台任务服务'
730
+ }
731
+
732
+ const parts = [`已提交 ${tracked.length} 篇论文解析`]
733
+ if (taskId !== undefined) parts.push(`任务编号 ${taskId}`)
734
+ if (jobId !== undefined) parts.push(`后台任务 ${jobId},进度与结果用 job_output 查询`)
735
+ else if (jobUnavailableReason !== undefined) parts.push(`无法跟踪进度:${jobUnavailableReason}`)
736
+ if (taskNote !== undefined) parts.push(`任务清单未登记:${taskNote}`)
737
+
738
+ return definedFields({
739
+ ok: true,
740
+ mode: 'queued',
741
+ papers,
742
+ taskId,
743
+ jobId,
744
+ jobUnavailableReason,
745
+ notice: `${parts.join(';')}。`,
746
+ failures,
747
+ })
748
+ },
749
+ })
750
+ }