@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.
- package/LICENSE +21 -0
- package/README.md +137 -2
- package/cordis.patch.yml +4 -0
- package/lib/annotate-tool.js +334 -0
- package/lib/arxiv-id.js +74 -0
- package/lib/asset-routes.js +210 -0
- package/lib/bibliography-formats.js +126 -0
- package/lib/bibliography-import.js +105 -0
- package/lib/bibliography-service.js +43 -0
- package/lib/bibliography.js +42 -0
- package/lib/block-authors.js +292 -0
- package/lib/block-cache.js +39 -0
- package/lib/blocks-markdown.js +157 -0
- package/lib/blocks-reconcile.js +218 -0
- package/lib/blocks.js +1344 -0
- package/lib/citation-metadata.js +260 -0
- package/lib/citation-styles.js +120 -0
- package/lib/client-parts/01-pure-helpers.js +2607 -0
- package/lib/client.js +9569 -0
- package/lib/code-source.js +68 -0
- package/lib/concurrency-gate.js +91 -0
- package/lib/context.js +233 -0
- package/lib/csl/SOURCES.md +10 -0
- package/lib/csl/gb-t-7714.csl +441 -0
- package/lib/csl/ieee.csl +520 -0
- package/lib/csl/locales-zh-CN.xml +438 -0
- package/lib/csl/nature.csl +190 -0
- package/lib/discussion.js +400 -0
- package/lib/documents.js +67 -0
- package/lib/export.js +848 -0
- package/lib/file-lock.js +177 -0
- package/lib/gloss.js +181 -0
- package/lib/glossary.js +279 -0
- package/lib/index.js +3862 -0
- package/lib/inline-html.js +53 -0
- package/lib/install-dependency.js +120 -0
- package/lib/item-ops.js +83 -0
- package/lib/job-facade.js +58 -0
- package/lib/json-store.js +54 -0
- package/lib/library-model.js +132 -0
- package/lib/library-service.js +180 -0
- package/lib/library-tool.js +982 -0
- package/lib/library.js +814 -0
- package/lib/markdown-assets.js +138 -0
- package/lib/markdown-literals.js +93 -0
- package/lib/metadata-enrichment.js +516 -0
- package/lib/metadata-fetch.js +146 -0
- package/lib/metadata-node.js +158 -0
- package/lib/metadata-proxy.ps1 +35 -0
- package/lib/mineru-config.js +95 -0
- package/lib/mineru-sdk-helper.py +123 -0
- package/lib/mineru-sdk.js +182 -0
- package/lib/mineru.js +268 -0
- package/lib/mirror-export.js +240 -0
- package/lib/outline.js +296 -0
- package/lib/page-image-helper.py +294 -0
- package/lib/page-image.js +454 -0
- package/lib/paper-metadata.js +242 -0
- package/lib/parse-export.js +631 -0
- package/lib/pdf-analysis-tool.js +750 -0
- package/lib/pdf-metadata-helper.py +75 -0
- package/lib/pdf-metadata.js +141 -0
- package/lib/pdf-page.js +183 -0
- package/lib/pdf-scan.js +134 -0
- package/lib/pdf-text.js +68 -0
- package/lib/picker.js +305 -0
- package/lib/portable.js +379 -0
- package/lib/purge.js +170 -0
- package/lib/read-tool.js +660 -0
- package/lib/reader-store.js +497 -0
- package/lib/reading-order.js +207 -0
- package/lib/rename-document.js +480 -0
- package/lib/rename.js +372 -0
- package/lib/renderer-status.js +161 -0
- package/lib/resolver.js +1152 -0
- package/lib/result-archive.js +157 -0
- package/lib/revisions.js +330 -0
- package/lib/search-database.js +62 -0
- package/lib/search-index.js +601 -0
- package/lib/search-scan.js +185 -0
- package/lib/search-source.js +23 -0
- package/lib/search-terms.js +539 -0
- package/lib/section-audit.js +209 -0
- package/lib/selection-message.js +332 -0
- package/lib/serial-tail.js +21 -0
- package/lib/slicing.js +425 -0
- package/lib/source-resolver.js +581 -0
- package/lib/stem-repair.js +189 -0
- package/lib/storage.js +562 -0
- package/lib/store-paths.js +253 -0
- package/lib/table-gfm.js +236 -0
- package/lib/tasks.js +270 -0
- package/lib/tex-align.js +509 -0
- package/lib/tex-blocks.js +653 -0
- package/lib/tex-fetch.js +455 -0
- package/lib/tex-figures.js +140 -0
- package/lib/tex-inline.js +166 -0
- package/lib/tex-merge.js +279 -0
- package/lib/tex-pipeline.js +242 -0
- package/lib/tex-prepare.js +746 -0
- package/lib/tex-tables.js +210 -0
- package/lib/text-similarity.js +85 -0
- package/lib/tool-contract.js +86 -0
- package/lib/tool-host.js +1058 -0
- package/lib/tool-identity.js +214 -0
- package/lib/translatable-text.js +48 -0
- package/lib/translate-prompts.js +709 -0
- package/lib/translate-queue.js +418 -0
- package/lib/translate-task.js +158 -0
- package/lib/translate.js +909 -0
- package/lib/update-check.js +438 -0
- package/lib/update-contracts.js +75 -0
- package/lib/usage.js +282 -0
- package/package.json +55 -4
package/lib/tool-host.js
ADDED
|
@@ -0,0 +1,1058 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工具的执行侧:把模型侧工具归一化后的请求,落到与界面同一套宿主能力上。
|
|
3
|
+
*
|
|
4
|
+
* 这四个函数曾经直接住在 index.js 的 apply 里,和 1200 行的 HTTP 分发挤在同一个文件;
|
|
5
|
+
* 现在它们有独立的落点,index.js 只负责把宿主能力作为 deps 递进来。
|
|
6
|
+
*
|
|
7
|
+
* 依赖一律经 deps 注入(与 pdf-analysis-tool / library-tool 同一分工):
|
|
8
|
+
* 这里不 new 仓库、不读配置、不持有状态,只把「一次工具调用」翻译成已有的写路径与读路径。
|
|
9
|
+
*
|
|
10
|
+
* - `exportFor` 导出(html / citation / notes):`/export` 路由与 Paper_library 共用
|
|
11
|
+
* - `runLibraryRequest` 文献库写入:与 `/item`、`libraryService.handle`、`renameDocument` 同源
|
|
12
|
+
* - `attachPageImage` 原页图 → 附件引用(模型收图时用)
|
|
13
|
+
* - `readPdf` 按结构读一篇:切章节 / 块区间 / 笔记 / 译文 / 原页图
|
|
14
|
+
* - `searchPapers` 跨篇全文检索:命中段落带 blockId,能直接接 blocks / Paper_annotate
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises'
|
|
18
|
+
import { headingEntries, headingTitle, visibleHeadingIndexes, withDocumentTitle } from './blocks.js'
|
|
19
|
+
import { randomUUID } from 'node:crypto'
|
|
20
|
+
import { basename, join } from 'node:path'
|
|
21
|
+
|
|
22
|
+
import { exportHtml, notesMarkdown } from './export.js'
|
|
23
|
+
import { applyItemAction } from './item-ops.js'
|
|
24
|
+
import { itemPathOf, READ_STATUSES, readItem, readLibrary, setCategoryHidden, setCategoryPinned, setViewHidden, setViewPinned, writeItem, writeLibrary } from './library.js'
|
|
25
|
+
import { createLibraryModel } from './library-model.js'
|
|
26
|
+
import { renderPageImages } from './page-image.js'
|
|
27
|
+
import { documentPaths, hydrateDocument, readDocumentManifest } from './portable.js'
|
|
28
|
+
import { MAX_STEM_CHARS } from './rename.js'
|
|
29
|
+
import { renameDocument } from './rename-document.js'
|
|
30
|
+
import { readManifest, rebuildIndex, runIndexedSearch, syncIndex } from './search-index.js'
|
|
31
|
+
import { pageOf, scanMatches } from './search-scan.js'
|
|
32
|
+
import {
|
|
33
|
+
clampSearchLimit, clampSearchOffset, clampSnippetChars, degradedMinHits, hasCjk, isPlainWord, parseQuery,
|
|
34
|
+
} from './search-terms.js'
|
|
35
|
+
import { addressedRange, findSection, renderBlock, sectionRange, sliceMembersPage, slicePage, validateReadRequest } from './slicing.js'
|
|
36
|
+
import { blockOwners, sectionBlocks } from './reading-order.js'
|
|
37
|
+
import { effectiveMetadata, updateMetadata, enrichMetadata, keepMetadata, metadataSourceRows } from './paper-metadata.js'
|
|
38
|
+
import { createBibliographyService } from './bibliography-service.js'
|
|
39
|
+
import { createMetadataResolver } from './metadata-enrichment.js'
|
|
40
|
+
import { buildOutline, outlineFileText, parseOutlineFile } from './outline.js'
|
|
41
|
+
import { outlineRevisionAt } from './revisions.js'
|
|
42
|
+
import { replaceStateFile } from './storage.js'
|
|
43
|
+
import { sectionStats, auditSections, contentKinds, previousSectionEvidence } from './section-audit.js'
|
|
44
|
+
import { readTranslation } from './translate.js'
|
|
45
|
+
import { translationPathOf } from './translate-task.js'
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* `blocks` 的区间跨进了别的章节时给一句提示。
|
|
49
|
+
*
|
|
50
|
+
* 返回空串表示没跨节(区间内除起点外没有可见标题),调用方据此决定要不要带 notice。
|
|
51
|
+
* 只报**第一处**越界:区间跨了 5 节时列 5 行没有意义,读者需要知道的是「你越界了」
|
|
52
|
+
* 与「越到哪儿」,剩下的用 outline 看。
|
|
53
|
+
*
|
|
54
|
+
* @param {object[]} blocks 块列表。
|
|
55
|
+
* @param {number} from 起始块下标(含)。
|
|
56
|
+
* @param {number} to 结束块下标(不含)。
|
|
57
|
+
* @returns {string}
|
|
58
|
+
*/
|
|
59
|
+
function crossSections(blocks, from, to) {
|
|
60
|
+
const listed = new Set(visibleHeadingIndexes(blocks))
|
|
61
|
+
for (let index = from + 1; index < to; index += 1) {
|
|
62
|
+
if (!listed.has(index)) continue
|
|
63
|
+
const title = headingTitle(blocks[index])
|
|
64
|
+
return '这个区间在块 ' + blocks[index].id + ' 处跨进了下一节「' + title
|
|
65
|
+
+ '」,后面的内容不属于起始块所在的节。只读本节请用 action="section" 并给出 section;'
|
|
66
|
+
+ '确实要按块号读就用 action="blocks" 继续(提示不裁剪内容)。'
|
|
67
|
+
}
|
|
68
|
+
return ''
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 一节的 `notice`:说清「这一节的内容是什么形态」。
|
|
73
|
+
*
|
|
74
|
+
* 🔴 过去只有两个分支 —— 含图 / 没有正文。正文是表格(`5f937bc5 5.2`、`afbb0b96 B.2`)
|
|
75
|
+
* 或代码的节因此既没有「没有正文」的报错、也没有任何提示,读出来只有一行 caption,
|
|
76
|
+
* 读者无法判断是解析丢了内容还是内容本来就不在文字里。
|
|
77
|
+
*
|
|
78
|
+
* 现在按 `contentKinds` 的实际构成给话。🔴 **只有真有图时才提 `readPages`** ——
|
|
79
|
+
* 那个字段由调用方按 `figures.length > 0` 决定带不带,表格 / 代码 / 公式节没有它,
|
|
80
|
+
* 文案里指向一个不存在的字段会让调用方去读 `undefined`。
|
|
81
|
+
*
|
|
82
|
+
* @param {{kinds: string[], hasText: boolean}} kinds 见 section-audit.contentKinds。
|
|
83
|
+
* @returns {string} 不需要提示时返回空串。
|
|
84
|
+
*/
|
|
85
|
+
function sectionNotice({ kinds, hasText }) {
|
|
86
|
+
const label = { table: '表格', code: '代码', figure: '图像', math: '公式' }
|
|
87
|
+
const assets = kinds.filter(kind => kind !== 'text').map(kind => label[kind] ?? kind)
|
|
88
|
+
const hasFigure = assets.includes('图像')
|
|
89
|
+
const toPage = hasFigure ? '按 readPages 查看原页。' : '用 action="page" 按页核对。'
|
|
90
|
+
if (!hasText) {
|
|
91
|
+
if (assets.length === 0) return ''
|
|
92
|
+
// 只有图时内容本来就在图里;表格与代码的正文由解析给出,这里只是提醒它不是散文。
|
|
93
|
+
const tail = hasFigure ? '图内内容不在下面的文字里;' : ''
|
|
94
|
+
return '这一节只有' + assets.join('、') + ',没有正文段落;' + tail + toPage
|
|
95
|
+
}
|
|
96
|
+
if (hasFigure) {
|
|
97
|
+
return '这一节含图像,下面的文字不包含图内内容;请用 Paper_read action="page",paper 保持不变,按 readPages 查看。'
|
|
98
|
+
}
|
|
99
|
+
return ''
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 错误折成一行给人看的话。与 index.js 的同名实现同口径(那边还要服务 HTTP 层)。 */
|
|
103
|
+
function errorText(error) {
|
|
104
|
+
return String(error?.message ?? error).slice(0, 500)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* 翻页复用对齐结果的时间窗。
|
|
109
|
+
*
|
|
110
|
+
* **只对翻页生效**(`offset > 0`):一次翻页与上一页是同一批结果,没必要再把全库哈希对一遍。
|
|
111
|
+
* 首页永不复用 —— 「改完一篇正文马上再搜」必须立刻看到新结果,那是最常见的动作,
|
|
112
|
+
* 不能用「最多晚 2 秒」去换 20 ms。
|
|
113
|
+
*
|
|
114
|
+
* 窗口内索引只可能「旧」、不会「错」:命中逐块按当前正文重新校验,对不上就整次退回扫描。
|
|
115
|
+
*/
|
|
116
|
+
const SYNC_REUSE_MS = 2000
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* @param {object} deps 宿主能力
|
|
120
|
+
* @param {object} deps.ctx 插件上下文(`ctx.get('attachments')` / `ctx.get('llm')` / logger)
|
|
121
|
+
* @param {string} deps.root 插件 runtime 根(`runtimeRoot(config)`)
|
|
122
|
+
* @param {object} deps.repository PaperRepository
|
|
123
|
+
* @param {object} deps.libraryService createLibraryService 的产物
|
|
124
|
+
* @param {(operation: Function) => Promise<unknown>} deps.serializeLibrary 库级写锁
|
|
125
|
+
* @param {string} deps.libraryFile library.json 的绝对路径
|
|
126
|
+
* @param {(id: string) => Promise<object|null>} deps.libraryDocumentOf 按 id 取原始记录
|
|
127
|
+
* @param {(sessionId: string, ids: string[]) => Promise<void>} deps.attachDocumentsToSession 把论文挂到会话
|
|
128
|
+
* @param {(state: object, id: string) => Promise<object|undefined>} deps.readerDocumentOf 热优先、冷兜底
|
|
129
|
+
* @param {(contentPath: string) => Promise<{blocks: object[], notice: string}>} deps.readerBlocksOf 块列表
|
|
130
|
+
* @param {(document: object, blocks: object[]) => Promise<object[]>} deps.readerMarksOf 划线视图
|
|
131
|
+
* @param {(document: object, blocks: object[]) => Promise<object[]>} deps.readerThreadsOf 边注视图
|
|
132
|
+
* @param {(document: object) => Promise<string>} deps.outlineTextOf 章节树文本
|
|
133
|
+
* @param {(document: object, blocks: object[]) => Promise<object>} deps.exportAssetsOf 导出用资源
|
|
134
|
+
* @param {(blocks: object[], translation: object|null) => object[]} deps.mergeReaderBlocks 合并译文
|
|
135
|
+
* @param {string} deps.pageImageCacheDir 原页图缓存根
|
|
136
|
+
* @param {string} [deps.mineruCommand] 原页渲染命令(缺省走渲染器内置)
|
|
137
|
+
* @param {(dirText: string) => Promise<object>} [deps.bindSourceDirs] 目录 → 记录的绑定(见 index.js)
|
|
138
|
+
* @param {(documentId: string, dir: string) => Promise<object>} [deps.setSourceDir] 记录 → 目录的显式改写(见 index.js)
|
|
139
|
+
* @param {() => Promise<object[]>} [deps.allDocuments] 热记录 + 冷归档(跨篇检索的候选池)
|
|
140
|
+
* @returns {{exportFor: Function, writeExportFile: Function, runLibraryRequest: Function, attachPageImage: Function, readPdf: Function}} 工具执行面
|
|
141
|
+
*/
|
|
142
|
+
export function createToolHost(deps = {}) {
|
|
143
|
+
const {
|
|
144
|
+
ctx, root, repository,
|
|
145
|
+
libraryService, serializeLibrary, libraryFile, libraryDocumentOf, attachDocumentsToSession,
|
|
146
|
+
readerDocumentOf, readerBlocksOf, readerMarksOf, readerThreadsOf, outlineTextOf, exportAssetsOf,
|
|
147
|
+
mergeReaderBlocks, pageImageCacheDir, mineruCommand, bindSourceDirs, setSourceDir, allDocuments,
|
|
148
|
+
} = deps
|
|
149
|
+
// 渲染器可注入(与 index.js 的 config.readPdfMetadata / config.sdkParse 同一手法):
|
|
150
|
+
// 不注入就用本模块 import 的那一个。**这条不只是为测试** —— 少了它,「deps 里的
|
|
151
|
+
// mineruCommand 有没有真的走到子进程」这层接缝就只能靠真起 uvx 才验得到。
|
|
152
|
+
const renderPages = typeof deps.renderPageImages === 'function' ? deps.renderPageImages : renderPageImages
|
|
153
|
+
const metadataResolver = deps.metadataResolver ?? createMetadataResolver()
|
|
154
|
+
let bibliographyService = deps.bibliographyService
|
|
155
|
+
const getBibliographyService = () => bibliographyService ??= createBibliographyService({ repository, allDocuments: deps.allDocuments, libraryService: deps.libraryService })
|
|
156
|
+
async function currentMetadata(id) {
|
|
157
|
+
const raw = (await repository.snapshot()).documents[id] ?? await repository.archivedDocument(id)
|
|
158
|
+
return raw ? effectiveMetadata(raw) : undefined
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
async function readBlocks(document) {
|
|
162
|
+
const result = await readerBlocksOf(documentPaths(hydrateDocument(document)).contentPath)
|
|
163
|
+
if ((result.blocks.find(block => block.type === 'heading')?.sourceText?.length ?? 0) <= 300) return result
|
|
164
|
+
const metadata = await readDocumentManifest(document, { validateArtifacts: false }) ?? document
|
|
165
|
+
return { ...result, blocks: withDocumentTitle(result.blocks, metadata.title ?? metadata.metadata?.title) }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* 导出(html / citation / notes)的唯一实现:/export 路由与 Paper_library 工具共用。
|
|
170
|
+
*
|
|
171
|
+
* 失败抛错,由两条调用方各自折算成自己的口径 —— 路由转 4xx,工具转 ok:false + 原因。
|
|
172
|
+
* 书目导出不要求正文;HTML 与笔记需要解析产物,并共用阅读器的块、译文与标注。
|
|
173
|
+
*
|
|
174
|
+
* @param {string} documentId 论文 id
|
|
175
|
+
* @param {string} action html / citation / notes
|
|
176
|
+
* @param {string} format citation 的标准书目格式或 CSL 样式别名
|
|
177
|
+
* @param {{style?: string, locale?: string, mode?: string}} options CSL 样式、语言与排版类型
|
|
178
|
+
* @returns {Promise<{format: string, text: string}>} 导出结果
|
|
179
|
+
*/
|
|
180
|
+
async function exportFor(documentId, action, format, options = {}) {
|
|
181
|
+
if (action === 'citation') return getBibliographyService().exportRecords([documentId], format ?? 'bibtex', options)
|
|
182
|
+
const state = await repository.snapshot()
|
|
183
|
+
const stored = await readerDocumentOf(state, documentId)
|
|
184
|
+
if (!stored) throw new Error('论文不存在')
|
|
185
|
+
const raw = await readDocumentManifest(stored).catch(() => undefined) ?? stored
|
|
186
|
+
const document = hydrateDocument(raw)
|
|
187
|
+
if (typeof document.markdownPath !== 'string' || document.markdownPath === '') {
|
|
188
|
+
throw new Error('这篇论文没有可用的 Markdown,无法导出')
|
|
189
|
+
}
|
|
190
|
+
const { blocks } = await readBlocks(document)
|
|
191
|
+
const path = translationPathOf(document)
|
|
192
|
+
const translation = path === '' ? null : await readTranslation(path)
|
|
193
|
+
const merged = mergeReaderBlocks(blocks, translation)
|
|
194
|
+
const title = typeof raw.pdfName === 'string' && raw.pdfName !== '' ? raw.pdfName : document.id.slice(0, 8)
|
|
195
|
+
if (action === 'notes') {
|
|
196
|
+
return {
|
|
197
|
+
format: 'markdown',
|
|
198
|
+
text: notesMarkdown({
|
|
199
|
+
document: { id: document.id, pdfName: title },
|
|
200
|
+
blocks: merged,
|
|
201
|
+
marks: await readerMarksOf(document, merged),
|
|
202
|
+
threads: await readerThreadsOf(document, merged),
|
|
203
|
+
outlineText: await outlineTextOf(document),
|
|
204
|
+
title,
|
|
205
|
+
}),
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
if (action !== 'html') throw new Error('导出操作必须是 html / citation / notes')
|
|
209
|
+
return {
|
|
210
|
+
format: 'html',
|
|
211
|
+
text: exportHtml({
|
|
212
|
+
document: { id: document.id, pdfName: title },
|
|
213
|
+
blocks: merged,
|
|
214
|
+
translation: merged,
|
|
215
|
+
marks: await readerMarksOf(document, merged),
|
|
216
|
+
threads: await readerThreadsOf(document, merged),
|
|
217
|
+
outlineText: await outlineTextOf(document),
|
|
218
|
+
assets: await exportAssetsOf(document, merged),
|
|
219
|
+
title,
|
|
220
|
+
}),
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Keep one export per paper and format; the public tool returns its download URL. */
|
|
225
|
+
async function writeExportFile(documentId, suffix, text) {
|
|
226
|
+
const dir = join(root, 'exports')
|
|
227
|
+
await mkdir(dir, { recursive: true })
|
|
228
|
+
const file = join(dir, documentId + suffix)
|
|
229
|
+
const temporary = file + '.' + randomUUID() + '.tmp'
|
|
230
|
+
try {
|
|
231
|
+
await writeFile(temporary, text, 'utf8')
|
|
232
|
+
await replaceStateFile(temporary, file)
|
|
233
|
+
} catch (error) { await rm(temporary, { force: true }); throw error }
|
|
234
|
+
return file
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Paper_library 的执行侧:把工具整理好的请求落到与界面**同一套**写路径上。
|
|
239
|
+
*
|
|
240
|
+
* 每个动作都复用路由已经在用的函数(libraryService.handle / setTrashed / renameDocument /
|
|
241
|
+
* attachDocumentsToSession / exportFor),所以工具与界面不可能对同一件事给出两种结果。
|
|
242
|
+
*
|
|
243
|
+
* @param {object} request 工具归一化后的请求
|
|
244
|
+
* @returns {Promise<{ok: boolean, notice: string, citation?: string, path?: string, failures?: string[]}>} 执行结果
|
|
245
|
+
*/
|
|
246
|
+
async function runLibraryRequest(request) {
|
|
247
|
+
if (['import', 'styles', 'style-install', 'style-select'].includes(request.action)) return getBibliographyService().run(request)
|
|
248
|
+
if (request.action === 'export') {
|
|
249
|
+
const outcome = await getBibliographyService().exportRecords(request.documentIds, request.format, { style: request.style, locale: request.locale, mode: request.citationMode })
|
|
250
|
+
const file = await writeExportFile(outcome.exportId, '.' + outcome.extension, outcome.text)
|
|
251
|
+
return { ok: true, notice: '已导出 ' + outcome.count + ' 条书目。', url: '/api/dsh-paper/export?file=' + encodeURIComponent(file.split(/[\\/]/).at(-1)) }
|
|
252
|
+
}
|
|
253
|
+
const action = request.action
|
|
254
|
+
const ids = Array.isArray(request.documentIds) ? request.documentIds : []
|
|
255
|
+
const failures = []
|
|
256
|
+
const sessionId = request.sessionId
|
|
257
|
+
if (['metadata', 'rename', 'citation', 'html', 'notes', 'rebind', 'unbind'].includes(action) && ids.length !== 1) return { ok: false, code: 'ONE_PAPER_REQUIRED', notice: '这个动作一次处理一篇论文。' }
|
|
258
|
+
|
|
259
|
+
if (action === 'metadata') {
|
|
260
|
+
if (ids.length !== 1) return { ok: false, code: 'ONE_PAPER_REQUIRED', notice: 'metadata 一次修改一篇论文。' }
|
|
261
|
+
if (request.enrich === true) {
|
|
262
|
+
if (request.fields !== undefined) throw new Error('enrich 与 fields 不可同时使用。')
|
|
263
|
+
const enrichment = await enrichMetadata(repository, ids[0], metadataResolver, request)
|
|
264
|
+
const count = Object.keys(enrichment.fields).length
|
|
265
|
+
// 显式标识与记录对不上时 resolve 只记 warnings、不拒绝:把这句带进回执,
|
|
266
|
+
// 免得模型把"能预览"读成"完全一致"。
|
|
267
|
+
const warned = Array.isArray(enrichment.warnings) && enrichment.warnings.length > 0
|
|
268
|
+
? ';注意:' + enrichment.warnings.join(';') : ''
|
|
269
|
+
const notice = (enrichment.status === 'candidates' ? '尚未确定论文标识。请核对 candidates,再用 identifier 预览;本次未写入。'
|
|
270
|
+
: enrichment.status === 'version-conflict' ? '出版年份或版本冲突,未自动合并;请核对 conflicts。'
|
|
271
|
+
: enrichment.dryRun ? '预览:可补全 ' + count + ' 个字段;已有值和显式清空的字段保留。传 dryRun=false 保存。'
|
|
272
|
+
: '已补全 ' + count + ' 个字段;已有值和显式清空的字段保留。') + warned
|
|
273
|
+
return { ok: true, enrichment, notice, ...(!enrichment.dryRun ? { metadata: await currentMetadata(ids[0]) } : {}) }
|
|
274
|
+
}
|
|
275
|
+
// 「这条冲突保持原样」(keptMetadata):记下本次来源值,下次补全在来源没变时不再报冲突。
|
|
276
|
+
if (request.keep !== undefined) {
|
|
277
|
+
if (!Array.isArray(request.keep)) throw new Error('keep 必须是书目字段名数组。')
|
|
278
|
+
const result = await keepMetadata(repository, ids[0], request.keep, metadataResolver, { identifier: request.identifier })
|
|
279
|
+
return { ok: result.kept.length > 0, kept: result.kept,
|
|
280
|
+
notice: result.kept.length > 0
|
|
281
|
+
? '已记下保留 ' + result.kept.join('、') + ';来源记录不变时,这些字段不再出现在补全冲突里。'
|
|
282
|
+
: '来源记录这次没有给出这些字段的值,没有可对照的「保留」可记。' }
|
|
283
|
+
}
|
|
284
|
+
if (request.identifier !== undefined) throw new Error('identifier 需要 enrich=true。')
|
|
285
|
+
const result = await serializeLibrary(() => updateMetadata(repository, ids[0], request.fields))
|
|
286
|
+
return { ok: true, notice: '书目元数据已保存。', bibliography: result.bibliography, metadata: await currentMetadata(ids[0]) }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
if (action === 'rebuild') {
|
|
290
|
+
if (!['outline', 'index'].includes(request.target)) return { ok: false, code: 'INVALID_TARGET', notice: 'target 必须是 outline / index。' }
|
|
291
|
+
const records = await allDocuments()
|
|
292
|
+
const selected = request.target === 'index' || ids.length === 0 ? records : records.filter(record => ids.includes(record.id))
|
|
293
|
+
const documents = selected.map(raw => hydrateDocument(raw)).filter(document => document.markdownPath)
|
|
294
|
+
const dryRun = request.dryRun !== false
|
|
295
|
+
const maintenance = { target: request.target, dryRun, count: documents.length }
|
|
296
|
+
if (dryRun) return { ok: true, notice: '预览:将重建 ' + documents.length + ' 篇论文的' + (request.target === 'index' ? '检索索引' : '章节树') + ';执行时传 dryRun=false。', maintenance }
|
|
297
|
+
if (request.target === 'index') {
|
|
298
|
+
await rebuildIndex({ root, documents: documents.map(document => ({ documentId: document.id,
|
|
299
|
+
markdownPath: document.markdownPath, contentPath: documentPaths(document).contentPath })) })
|
|
300
|
+
} else {
|
|
301
|
+
const budget = (await repository.snapshot()).settings.outlineBudgetBytes
|
|
302
|
+
for (const document of documents) {
|
|
303
|
+
const paths = documentPaths(document)
|
|
304
|
+
const temporary = paths.outlinePath + '.' + randomUUID() + '.tmp'
|
|
305
|
+
try {
|
|
306
|
+
const { blocks } = await readBlocks(document)
|
|
307
|
+
const outline = buildOutline(await readFile(paths.markdownPath, 'utf8'), budget, blocks)
|
|
308
|
+
// 重建出来的目录必须带**当前输入**的身份,否则它下次读起来还要再算一遍。
|
|
309
|
+
const revision = await outlineRevisionAt(paths)
|
|
310
|
+
await writeFile(temporary, outlineFileText(outline, budget, revision), 'utf8')
|
|
311
|
+
await replaceStateFile(temporary, paths.outlinePath)
|
|
312
|
+
} catch {
|
|
313
|
+
await rm(temporary, { force: true })
|
|
314
|
+
failures.push(document.id + ':章节树重建失败,原文件保留。')
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return { ok: failures.length === 0, notice: '重建完成:' + (documents.length - failures.length) + ' 篇。', maintenance, failures }
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// ---- 条目属性与回收站:读-改-写该篇的 item.json(与 /item 路由同一套) ----
|
|
322
|
+
if (['star', 'pin', 'status', 'tag', 'untag', 'trash', 'restore'].includes(action)) {
|
|
323
|
+
return serializeLibrary(async () => {
|
|
324
|
+
const labels = { star: '改了星标', pin: '改了置顶', status: '改了阅读状态', tag: '加了标签', untag: '移除了标签', trash: '移入了回收站', restore: '从回收站还原了' }
|
|
325
|
+
/** 失败回执里的动词:与上面的完成时文案分开,否则会拼出「无法移入了回收站」。 */
|
|
326
|
+
const verbs = { star: '改星标', pin: '改置顶', status: '改阅读状态', tag: '加标签', untag: '移除标签', trash: '移入回收站', restore: '从回收站还原' }
|
|
327
|
+
let applied = 0
|
|
328
|
+
/** 执行后的条目原样带回:调用方(Paper_library)据此更新回执,不必再整库重读。 */
|
|
329
|
+
const updated = []
|
|
330
|
+
for (const documentId of ids) {
|
|
331
|
+
const raw = await libraryDocumentOf(documentId)
|
|
332
|
+
const name = raw !== null && typeof raw.pdfName === 'string' && raw.pdfName !== '' ? raw.pdfName : documentId
|
|
333
|
+
if (raw === null) { failures.push(name + ':论文不存在'); continue }
|
|
334
|
+
const path = itemPathOf(root, raw)
|
|
335
|
+
// 🔴 条目文件是标记的唯一落点:定位不到就**没有这次写入**,必须报失败而不是静默成功
|
|
336
|
+
// (trash 静默成功最坏 —— 面板说已进回收站,实际什么都没写)。
|
|
337
|
+
if (path === '') { failures.push(name + ':没有条目位置(D127 之前的非 sidecar 记录),无法' + (verbs[action] ?? '保存标记')); continue }
|
|
338
|
+
try {
|
|
339
|
+
// 与 /item 路由同一份算法(lib/item-ops.js):两处不再各写一遍去重与校验。
|
|
340
|
+
const next = applyItemAction(await readItem(path), {
|
|
341
|
+
action,
|
|
342
|
+
starred: request.starred,
|
|
343
|
+
pinned: request.pinned,
|
|
344
|
+
status: request.status,
|
|
345
|
+
tag: request.tag,
|
|
346
|
+
})
|
|
347
|
+
const stored = await writeItem(path, next)
|
|
348
|
+
updated.push({ documentId, item: stored })
|
|
349
|
+
applied += 1
|
|
350
|
+
} catch (error) {
|
|
351
|
+
failures.push(name + ':' + errorText(error))
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
return {
|
|
355
|
+
ok: failures.length === 0,
|
|
356
|
+
notice: failures.length === 0
|
|
357
|
+
? '已为 ' + applied + ' 篇' + labels[action] + '。'
|
|
358
|
+
: applied + ' 篇' + labels[action] + ',' + failures.length + ' 篇失败:' + failures[0],
|
|
359
|
+
failures,
|
|
360
|
+
items: updated,
|
|
361
|
+
}
|
|
362
|
+
})
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// ---- 集合:全部经 libraryService.handle,与界面共用校验与写锁 ----
|
|
366
|
+
if (action.startsWith('collection-') || action === 'file' || action === 'unfile') {
|
|
367
|
+
// 工具侧的动作名 → libraryService 的动作名与载荷。整组移动与合并各有自己的语义:
|
|
368
|
+
// - collection-merge 并集(来源成员加进目标,再删来源),不搬走;
|
|
369
|
+
// - collection-move-items 默认「搬走」(从来源移除),keepInSource=true 才是只加入。
|
|
370
|
+
const collectionRequest = () => {
|
|
371
|
+
if (action === 'collection-add') return { action: 'collection-create', name: request.name, parentId: request.parentId ?? null }
|
|
372
|
+
if (action === 'collection-rename') return { action: 'collection-update', collectionId: request.collectionId, name: request.name }
|
|
373
|
+
if (action === 'collection-move') return { action: 'collection-update', collectionId: request.collectionId, parentId: request.parentId ?? null }
|
|
374
|
+
if (action === 'collection-remove') {
|
|
375
|
+
// trashItems 是面板删集合对话框里那个「同时把论文移入回收站」;后端早就支持,
|
|
376
|
+
// 只是工具侧一直没有把它透出去。要一并移入回收站时必须显式确认(服务侧会核 confirm)。
|
|
377
|
+
return request.trashItems === true
|
|
378
|
+
? { action: 'collection-remove', collectionId: request.collectionId, trashItems: true, confirm: true }
|
|
379
|
+
: { action: 'collection-remove', collectionId: request.collectionId }
|
|
380
|
+
}
|
|
381
|
+
if (action === 'collection-merge') return { action: 'collection-merge', collectionId: request.collectionId, sourceCollectionId: request.sourceCollectionId }
|
|
382
|
+
if (action === 'collection-move-items') {
|
|
383
|
+
return {
|
|
384
|
+
action: 'collection-move-items',
|
|
385
|
+
collectionId: request.collectionId,
|
|
386
|
+
sourceCollectionId: request.sourceCollectionId,
|
|
387
|
+
documentIds: ids,
|
|
388
|
+
keepInSource: request.keepInSource === true,
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
if (action === 'file') return { action: 'collection-add-items', collectionId: request.collectionId, documentIds: ids }
|
|
392
|
+
return { action: 'collection-remove-items', collectionId: request.collectionId, documentIds: ids }
|
|
393
|
+
}
|
|
394
|
+
try {
|
|
395
|
+
const result = await serializeLibrary(() => libraryService.handle(collectionRequest()))
|
|
396
|
+
const moved = Array.isArray(result?.succeeded) ? result.succeeded.length : ids.length
|
|
397
|
+
const trashed = Array.isArray(result?.succeeded) ? result.succeeded.length : 0
|
|
398
|
+
const notice = action === 'collection-merge'
|
|
399
|
+
? '已把「' + (request.from ?? '') + '」并入目标集合:新增 ' + (Number(result?.merged) || 0) + ' 篇,来源集合已删除。'
|
|
400
|
+
: action === 'collection-move-items'
|
|
401
|
+
? (request.keepInSource === true ? '已加入目标集合(保留在来源集合):' : '已整体移到目标集合(从来源移除):') + moved + ' 篇。'
|
|
402
|
+
: action === 'collection-remove' && request.trashItems === true
|
|
403
|
+
? '集合已删除,' + trashed + ' 篇论文移入了回收站。'
|
|
404
|
+
: (labelsOfCollection(action)) + (ids.length > 0 ? ':' + moved + ' 篇。' : '。')
|
|
405
|
+
// 集合成员变了:把新的库视图一并带回,调用方不必再读一次 library.json。
|
|
406
|
+
const failed = Array.isArray(result?.failures) ? result.failures.map(row => (typeof row === 'string' ? row : textOf(row?.documentId) + ':' + textOf(row?.error))) : []
|
|
407
|
+
// keepInSource 原样带回:工具侧兜底文案要按它分「保留在来源」与「从来源移除」两种说法。
|
|
408
|
+
return {
|
|
409
|
+
ok: failed.length === 0,
|
|
410
|
+
notice,
|
|
411
|
+
failures: failed.length > 0 ? [...failures, ...failed] : failures,
|
|
412
|
+
library: result?.library,
|
|
413
|
+
keepInSource: request.keepInSource === true,
|
|
414
|
+
merged: Number(result?.merged) || 0,
|
|
415
|
+
succeeded: result?.succeeded,
|
|
416
|
+
}
|
|
417
|
+
} catch (error) {
|
|
418
|
+
return { ok: false, notice: errorText(error), failures }
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// ---- 改名:与 /rename 的键入那条路同一个实现(撞名 409、超长 400 都收成一句话) ----
|
|
423
|
+
//
|
|
424
|
+
// 🔴 **每个 reason 都要有自己的回话**,不许落到一个默认分支说成功:改名是搬文件,
|
|
425
|
+
// 没执行却说成功等于让用户以为盘上已经改了。实测踩过的是 `not-found` —— 冷归档论文
|
|
426
|
+
// 在 state.documents 里没有条目,`renameDocument` 回 not-found,而这里只判了撞名/超长/
|
|
427
|
+
// 非法名,于是返回 `ok:true`「已更新显示名」,实际文件名一个字节都没动。
|
|
428
|
+
if (action === 'rename') {
|
|
429
|
+
const outcome = await renameDocument({ repository, documentId: ids[0], stem: request.name, logger: ctx.logger })
|
|
430
|
+
if (outcome.reason === 'occupied') return { ok: false, notice: '这个名字已经被同目录的另一篇论文占用,请换一个。', failures }
|
|
431
|
+
if (outcome.reason === 'name-too-long') return { ok: false, notice: '名字太长了(上限 ' + MAX_STEM_CHARS + ' 个字符),请缩短后再试。', failures }
|
|
432
|
+
if (outcome.reason === 'invalid-name') return { ok: false, notice: '名字不能为空,也不能只由文件名非法字符组成。', failures }
|
|
433
|
+
if (outcome.reason === 'invalid-id') return { ok: false, notice: '论文标识无效,改名没有执行。', failures }
|
|
434
|
+
if (outcome.reason === 'not-found') return { ok: false, notice: '这篇论文不在本机文献库里(记录可能已被移除),改名没有执行。', failures }
|
|
435
|
+
if (outcome.reason === 'no-name') return { ok: false, notice: '这篇论文的记录里没有文件名,改名没有执行。', failures }
|
|
436
|
+
if (outcome.reason === 'no-title') return { ok: false, notice: '没能从记录或 PDF 元数据里推出名字;请直接给出 name。', failures }
|
|
437
|
+
if (outcome.reason === 'manual') return { ok: false, notice: '这篇论文被手动改过名,自动改名不会覆盖它;要改就直接给出 name。', failures }
|
|
438
|
+
if (outcome.reason === 'no-files') return { ok: false, notice: '这篇论文的资产文件都不在磁盘上,改名没有执行。', failures }
|
|
439
|
+
if (outcome.renamed === true) return { ok: true, notice: '已改名为「' + outcome.to + '」。', failures }
|
|
440
|
+
// 剩下的就是 `same`:文件名本来就对。只有真的写了显示名才说「已更新」,否则如实说未改动。
|
|
441
|
+
return { ok: true, notice: outcome.titleUpdated === true ? '文件名本来就是这个名字,已更新显示名。' : '文件名本来就是这个名字,未做改动。', failures }
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// ---- 会话注入:复用 /selection 的判据(Markdown 必须非空)与 attachDocumentsToSession ----
|
|
445
|
+
if (action === 'inject' || action === 'uninject') {
|
|
446
|
+
if (typeof sessionId !== 'string' || sessionId === '') {
|
|
447
|
+
return { ok: false, notice: '没有会话上下文,无法注入。', failures }
|
|
448
|
+
}
|
|
449
|
+
const selected = action === 'inject'
|
|
450
|
+
const snapshot = await repository.snapshot()
|
|
451
|
+
const accepted = []
|
|
452
|
+
const resolved = new Map()
|
|
453
|
+
for (const documentId of ids) {
|
|
454
|
+
const raw = await readerDocumentOf(snapshot, documentId)
|
|
455
|
+
const document = raw ? hydrateDocument(raw) : null
|
|
456
|
+
if (!document) { failures.push(documentId + ':论文不在本机文献库'); continue }
|
|
457
|
+
if (selected) {
|
|
458
|
+
const markdown = await readFile(document.markdownPath, 'utf8').catch(() => '')
|
|
459
|
+
if (markdown.trim() === '') { failures.push(document.pdfName + ':Markdown 不存在或为空,不能注入'); continue }
|
|
460
|
+
}
|
|
461
|
+
accepted.push(documentId)
|
|
462
|
+
if (selected) resolved.set(documentId, raw)
|
|
463
|
+
}
|
|
464
|
+
if (accepted.length === 0) return { ok: false, notice: failures[0] ?? '没有可处理的论文', failures }
|
|
465
|
+
await repository.update(state => {
|
|
466
|
+
const current = state.selections[sessionId] ?? { desired: [], delivered: [] }
|
|
467
|
+
const desired = new Set(current.desired ?? [])
|
|
468
|
+
for (const documentId of accepted) {
|
|
469
|
+
if (selected && !state.documents[documentId]) state.documents[documentId] = resolved.get(documentId)
|
|
470
|
+
if (selected) desired.add(documentId)
|
|
471
|
+
else desired.delete(documentId)
|
|
472
|
+
}
|
|
473
|
+
state.selections[sessionId] = { ...current, desired: [...desired] }
|
|
474
|
+
})
|
|
475
|
+
if (selected) await attachDocumentsToSession(sessionId, accepted)
|
|
476
|
+
return {
|
|
477
|
+
ok: failures.length === 0,
|
|
478
|
+
notice: selected ? '已推进会话上下文:' + accepted.length + ' 篇,下一轮生效。' : '已取消注入:' + accepted.length + ' 篇,下一轮生效。',
|
|
479
|
+
failures,
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// ---- 导出:citation 直接回文本,notes / html 落盘回路径 ----
|
|
484
|
+
if (action === 'citation' || action === 'notes' || action === 'html') {
|
|
485
|
+
const documentId = ids[0]
|
|
486
|
+
if (documentId === undefined) return { ok: false, notice: '需要 paper:一次导出一篇。', failures }
|
|
487
|
+
try {
|
|
488
|
+
const outcome = await exportFor(documentId, action, request.format, { style: request.style, locale: request.locale, mode: request.citationMode })
|
|
489
|
+
if (action === 'citation') return { ok: true, notice: '已按 ' + outcome.format + ' 生成引用。', citation: outcome.text, failures }
|
|
490
|
+
await writeExportFile(documentId, action === 'html' ? '.html' : '.notes.md', outcome.text)
|
|
491
|
+
return { ok: true, notice: '已导出,可通过下载链接保存。', url: '/api/dsh-paper/export?documentId=' + encodeURIComponent(documentId) + '&action=' + action, failures }
|
|
492
|
+
} catch (error) {
|
|
493
|
+
return { ok: false, notice: errorText(error), failures }
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
// ---- 全局标签改名 / 合并:与面板「改名 / 合并标签」走同一个 libraryService 实现 ----
|
|
498
|
+
if (action === 'tag-rename') {
|
|
499
|
+
try {
|
|
500
|
+
const result = await serializeLibrary(() => libraryService.handle({ action: 'tags-rename', tag: request.tag, next: request.next }))
|
|
501
|
+
const changed = Array.isArray(result?.succeeded) ? result.succeeded.length : 0
|
|
502
|
+
const failed = Array.isArray(result?.failures) ? result.failures.map(row => (typeof row === 'string' ? row : textOf(row?.documentId) + ':' + textOf(row?.error))) : []
|
|
503
|
+
return {
|
|
504
|
+
ok: failed.length === 0,
|
|
505
|
+
notice: '把「' + request.tag + '」改成「' + request.next + '」:' + changed + ' 篇' + (failed.length > 0 ? ',' + failed.length + ' 篇失败' : '') + '。',
|
|
506
|
+
failures: failed.length > 0 ? [...failures, ...failed] : failures,
|
|
507
|
+
succeeded: result?.succeeded,
|
|
508
|
+
library: result?.library,
|
|
509
|
+
}
|
|
510
|
+
} catch (error) {
|
|
511
|
+
return { ok: false, notice: errorText(error), failures }
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// ---- 目录 → 记录:把工作区文件夹绑回库记录 ----
|
|
516
|
+
// 唯一实现由 index.js 持有(那里才有 scanFolder / inspectPdf / repository);
|
|
517
|
+
// 工具侧只把 dir 递过去,排版交给调用方。
|
|
518
|
+
if (action === 'bind') {
|
|
519
|
+
if (typeof bindSourceDirs !== 'function') return { ok: false, notice: '这个宿主没有提供目录绑定能力。', failures }
|
|
520
|
+
try {
|
|
521
|
+
return await bindSourceDirs(request.dir, { dryRun: request.dryRun === true })
|
|
522
|
+
} catch (error) {
|
|
523
|
+
return { ok: false, notice: errorText(error), failures }
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
// ---- 记录 → 目录:把一条记录的 sourceDir 显式指向某个文件夹,或清空 ----
|
|
528
|
+
// 内容哈希只在 bind 那条路上生效;PDF 换了版本(重新下载、出版社版换 arXiv 版)之后
|
|
529
|
+
// 旧记录再也匹配不上,而它身上还有划线、笔记与译文 —— 删掉重入的代价正是这一条存在的原因。
|
|
530
|
+
if (action === 'rebind' || action === 'unbind') {
|
|
531
|
+
if (typeof setSourceDir !== 'function') return { ok: false, notice: '这个宿主没有提供源目录改写能力。', failures }
|
|
532
|
+
const documentId = ids[0]
|
|
533
|
+
if (documentId === undefined) return { ok: false, notice: '需要 paper:一次改一篇的源目录。', failures }
|
|
534
|
+
try {
|
|
535
|
+
const outcome = await setSourceDir(documentId, action === 'unbind' ? '' : String(request.dir ?? ''))
|
|
536
|
+
return { ...outcome, failures }
|
|
537
|
+
} catch (error) {
|
|
538
|
+
return { ok: false, notice: errorText(error), failures }
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// ---- 界面偏好 ----
|
|
543
|
+
//
|
|
544
|
+
// 🔴 这三个动作改的是**同一个 library.json** —— 集合、保存搜索、标签颜色都住在里面。
|
|
545
|
+
// 绕过库级串行器、拿锁外的旧库整体替换,就会顺手删掉刚建好的集合(实测:sort 之后
|
|
546
|
+
// 集合数 1→0,两次都报成功)。所以它们与界面 /library、集合服务共用同一把锁。
|
|
547
|
+
if (action === 'sort') {
|
|
548
|
+
await serializeLibrary(() => repository.withNamedWrite('library', async () => {
|
|
549
|
+
const library = await readLibrary(libraryFile)
|
|
550
|
+
await writeLibrary(libraryFile, { ...library, sort: request.mode })
|
|
551
|
+
}))
|
|
552
|
+
return { ok: true, notice: '已把排序方式改为 ' + request.mode + '。' }
|
|
553
|
+
}
|
|
554
|
+
if (action === 'group-hide' || action === 'group-pin') {
|
|
555
|
+
const pin = action === 'group-pin'
|
|
556
|
+
const flag = pin ? request.pinned !== false : request.hidden !== false
|
|
557
|
+
const group = request.group.trim()
|
|
558
|
+
const isCategory = group.startsWith('c:')
|
|
559
|
+
const key = isCategory ? group.slice(2) : group
|
|
560
|
+
await serializeLibrary(() => repository.withNamedWrite('library', async () => {
|
|
561
|
+
const library = await readLibrary(libraryFile)
|
|
562
|
+
const next = pin
|
|
563
|
+
? (isCategory ? setCategoryPinned(library, key, flag) : setViewPinned(library, key, flag))
|
|
564
|
+
: (isCategory ? setCategoryHidden(library, key, flag) : setViewHidden(library, key, flag))
|
|
565
|
+
await writeLibrary(libraryFile, next)
|
|
566
|
+
}))
|
|
567
|
+
return { ok: true, notice: (pin ? '置顶' : '显示') + '设置已更新。' }
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
return { ok: false, notice: '不支持的动作:' + action, failures }
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** 集合动作的中文回执前缀。 */
|
|
574
|
+
function labelsOfCollection(action) {
|
|
575
|
+
return {
|
|
576
|
+
'collection-add': '已建集合',
|
|
577
|
+
'collection-rename': '集合已改名',
|
|
578
|
+
'collection-move': '集合已移动',
|
|
579
|
+
'collection-remove': '集合已删除(论文本体未动)',
|
|
580
|
+
file: '已归入集合',
|
|
581
|
+
unfile: '已移出集合',
|
|
582
|
+
'collection-merge': '已合并集合',
|
|
583
|
+
'collection-move-items': '已整组移动',
|
|
584
|
+
}[action] ?? '集合操作已完成'
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/**
|
|
588
|
+
* 把落盘的原页图变成附件引用,供工具以图片块返回。
|
|
589
|
+
*
|
|
590
|
+
* 三道门都要过,任何一道不过就返回 undefined(工具退回「只给路径」):
|
|
591
|
+
* 附件服务在、模型路由解析得出来、该路由**明确声明**了 image 输入。
|
|
592
|
+
* 最后一条不是保守,而是前提 —— 模型不收图时把图片塞进结果,只会在下一次请求里被提供商拒掉。
|
|
593
|
+
*
|
|
594
|
+
* @param {string} imagePath renderPageImages 落盘的 WebP 绝对路径
|
|
595
|
+
* @param {object} [agent] 调用方的 agent(用来解析本次请求实际走的路由)
|
|
596
|
+
* @returns {Promise<object|undefined>} 可直接放进工具结果的图片引用
|
|
597
|
+
*/
|
|
598
|
+
async function attachPageImage(imagePath, agent) {
|
|
599
|
+
const attachments = ctx.get('attachments')
|
|
600
|
+
const llm = ctx.get('llm')
|
|
601
|
+
if (attachments === undefined || typeof attachments.saveImage !== 'function') return undefined
|
|
602
|
+
if (llm === undefined || typeof llm.resolveModelInfo !== 'function') return undefined
|
|
603
|
+
|
|
604
|
+
const routed = typeof agent?.session?.requestHeader === 'function' ? agent.session.requestHeader()?.config : undefined
|
|
605
|
+
const provider = routed?.provider ?? agent?.options?.provider
|
|
606
|
+
const model = routed?.model ?? agent?.options?.model
|
|
607
|
+
if (provider === undefined || model === undefined) return undefined
|
|
608
|
+
const info = await llm.resolveModelInfo(provider, model)
|
|
609
|
+
if (!Array.isArray(info?.inputModalities) || !info.inputModalities.includes('image')) return undefined
|
|
610
|
+
|
|
611
|
+
const limits = attachments.imageLimits ?? {}
|
|
612
|
+
if (Array.isArray(limits.mediaTypes) && !limits.mediaTypes.includes('image/webp')) return undefined
|
|
613
|
+
|
|
614
|
+
const data = await readFile(imagePath)
|
|
615
|
+
const ref = await attachments.saveImage({ data, mediaType: 'image/webp', name: basename(imagePath) })
|
|
616
|
+
if (ref === undefined || ref === null || ref.attachmentId === undefined) return undefined
|
|
617
|
+
return {
|
|
618
|
+
attachmentId: String(ref.attachmentId),
|
|
619
|
+
mediaType: String(ref.mediaType ?? 'image/webp'),
|
|
620
|
+
bytes: Number.isFinite(ref.bytes) ? ref.bytes : data.byteLength,
|
|
621
|
+
width: Number.isFinite(ref.width) ? ref.width : 0,
|
|
622
|
+
height: Number.isFinite(ref.height) ? ref.height : 0,
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Paper_read 的执行侧:按结构读一篇。切片逻辑在 read-tool.js(可单测),这里只负责取数据。
|
|
628
|
+
*
|
|
629
|
+
* @param {object} request { action, documentId, section, from, to, page, width }
|
|
630
|
+
* @returns {Promise<object>} 工具要的中间结果;失败用 `ok:false` 交给工具折算成一句话
|
|
631
|
+
*/
|
|
632
|
+
|
|
633
|
+
/**
|
|
634
|
+
* 这批文档里不可能命中本次查询的那些(查询含 CJK,而这篇正文里一个 CJK 字符都没有)。
|
|
635
|
+
*
|
|
636
|
+
* 依据是构建索引时算好的 `cjk` 位,不需要读正文。三种情况一律不跳:索引还不存在或
|
|
637
|
+
* 版本对不上(不为一次中文查询触发整库重建)、对齐失败、这篇没有这个位(更早的索引)。
|
|
638
|
+
* 「宁可慢,不可漏」在这里是硬约束 —— 漏掉的命中不报错,只会悄悄少几处。
|
|
639
|
+
*/
|
|
640
|
+
async function docsWithoutCjk({ root, documents, parsed }) {
|
|
641
|
+
if (!parsed.words.concat(parsed.phrases).some(unit => hasCjk(unit))) return undefined
|
|
642
|
+
const total = parsed.words.length + parsed.phrases.length
|
|
643
|
+
const withoutCjk = parsed.words.concat(parsed.phrases).filter(unit => !hasCjk(unit)).length
|
|
644
|
+
if (!parsed.phrases.some(hasCjk) && withoutCjk >= degradedMinHits(total)) return undefined
|
|
645
|
+
if (documents.length === 0) return undefined
|
|
646
|
+
if (await readManifest(root) === null) return undefined
|
|
647
|
+
let manifest
|
|
648
|
+
try {
|
|
649
|
+
manifest = await syncIndex({ root, documents })
|
|
650
|
+
} catch (error) {
|
|
651
|
+
ctx.logger.warn('dsh-paper search: 对齐索引失败,本次不跳过任何篇:' + errorText(error))
|
|
652
|
+
return undefined
|
|
653
|
+
}
|
|
654
|
+
const skip = new Set()
|
|
655
|
+
for (const document of documents) {
|
|
656
|
+
if (manifest.docs[document.documentId]?.cjk === false) skip.add(document.documentId)
|
|
657
|
+
}
|
|
658
|
+
return skip.size > 0 ? skip : undefined
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* 跨篇全文检索。
|
|
663
|
+
*
|
|
664
|
+
* 扫的是**已打标的 Markdown**:命中段落的 id 直接取自文件里的 `<!-- b:... -->` 标记,
|
|
665
|
+
* 所以结果能原样喂回 `Paper_read action=blocks` 与 `Paper_annotate` —— 行号/偏移做不到这件事,
|
|
666
|
+
* 这也是它比 grep 多出来的那一点。
|
|
667
|
+
*
|
|
668
|
+
* 多词之间是 **AND**(同一段里都出现),不是 OR:问的是"哪几篇同时谈了这两件事"。
|
|
669
|
+
* `"..."` 里的整段算一个词组(必须连着出现),其余单词走词形归一(forget ↔ forgetting)。
|
|
670
|
+
* 没有块标记的论文不参与检索,单独计数报出去(不发明 id、也不假装搜过了)。
|
|
671
|
+
*
|
|
672
|
+
* 结果**按段落得分全局降序**排成一条序列(得分 = 出现次数 × 块种类权重,表格与参考文献降权),
|
|
673
|
+
* 同分时论文相关度 paperRank 靠前的先出。翻页(`offset`)只有在这条全序上才有意义 ——
|
|
674
|
+
* 过去按「论文轮着取」的排列 score 不单调,既会让人把第一条当最高分,也没法定义第 51 条是哪条。
|
|
675
|
+
*
|
|
676
|
+
* 结果里的 `engine` 写清这次是倒排(`index`)还是扫描(`scan`)回答的 —— 两者差 10 倍,
|
|
677
|
+
* 只靠耗时猜会被机器负载骗过去。
|
|
678
|
+
*
|
|
679
|
+
* @param {{query?: string, documentIds?: string[], collection?: string, limit?: number}} request
|
|
680
|
+
* @returns {Promise<{ok: boolean, notice: string, hits: object[], scanned?: number,
|
|
681
|
+
* matched?: number, offset?: number, nextOffset?: number, truncated?: boolean, failures?: string[]}>}
|
|
682
|
+
*/
|
|
683
|
+
async function searchPapers(request = {}) {
|
|
684
|
+
if (request.order !== undefined && !['score', 'paper'].includes(request.order)) return { ok: false, code: 'INVALID_ORDER', notice: 'order 必须是 score / paper。', hits: [] }
|
|
685
|
+
const { words, phrases } = parseQuery(request.query ?? '')
|
|
686
|
+
if (words.length === 0 && phrases.length === 0) {
|
|
687
|
+
return { ok: false, notice: '需要 query:要搜的词或 "词组";多个词之间是「同一段里都出现」。', hits: [] }
|
|
688
|
+
}
|
|
689
|
+
if (typeof allDocuments !== 'function') return { ok: false, notice: '这个宿主没有提供文献列表。', hits: [] }
|
|
690
|
+
const limit = clampSearchLimit(request.limit)
|
|
691
|
+
const explicit = Array.isArray(request.documentIds)
|
|
692
|
+
? request.documentIds.filter(id => typeof id === 'string' && id !== '')
|
|
693
|
+
: []
|
|
694
|
+
const records = await allDocuments()
|
|
695
|
+
let scope = records
|
|
696
|
+
if (explicit.length > 0) {
|
|
697
|
+
const wanted = new Set(explicit)
|
|
698
|
+
scope = records.filter(raw => wanted.has(raw.id))
|
|
699
|
+
}
|
|
700
|
+
if (typeof request.collection === 'string' && request.collection.trim() !== '') {
|
|
701
|
+
const wanted = request.collection.trim()
|
|
702
|
+
const model = createLibraryModel()
|
|
703
|
+
const library = await readLibrary(libraryFile)
|
|
704
|
+
const rows = model.collectionsOf(library)
|
|
705
|
+
const exact = rows.filter(entry => model.path(library, entry.id) === wanted)
|
|
706
|
+
const names = rows.filter(entry => entry.name === wanted)
|
|
707
|
+
const row = exact.length === 1 ? exact[0] : names.length === 1 ? names[0] : undefined
|
|
708
|
+
if (row === undefined) {
|
|
709
|
+
return { ok: false, notice: '没有叫「' + wanted + '」的集合。用 Paper_library 的 collections 动作看现有集合。', hits: [] }
|
|
710
|
+
}
|
|
711
|
+
const ids = new Set(model.memberIds(library, row.id, true))
|
|
712
|
+
scope = scope.filter(raw => ids.has(raw.id))
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// 阅读状态与标签:与「范围」正交,所以是在范围**之后**再筛一层,不是二选一。
|
|
716
|
+
// 最常问的是「还没读的论文里,哪些提到 X」—— 那决定下一篇读什么,只靠 papers/collection 答不了。
|
|
717
|
+
const statusWanted = typeof request.status === 'string' ? request.status.trim() : ''
|
|
718
|
+
const tagWanted = Array.isArray(request.tags)
|
|
719
|
+
? request.tags.map(tag => String(tag).trim()).filter(tag => tag !== '')
|
|
720
|
+
: []
|
|
721
|
+
const trashWanted = request.trashed === true
|
|
722
|
+
// 三个筛选都给了才走这一层;trashed 显式给了也算(true = 只看回收站,false = 排除回收站)。
|
|
723
|
+
if (statusWanted !== '' || tagWanted.length > 0 || typeof request.trashed === 'boolean') {
|
|
724
|
+
if (statusWanted !== '' && !READ_STATUSES.includes(statusWanted)) {
|
|
725
|
+
return { ok: false, notice: 'status 只能是 ' + READ_STATUSES.join(' / ') + '。', hits: [] }
|
|
726
|
+
}
|
|
727
|
+
const kept = []
|
|
728
|
+
for (const raw of scope) {
|
|
729
|
+
const path = itemPathOf(root, raw)
|
|
730
|
+
// 没有条目位置的旧记录:标记无处可放,按「未读、无标签、不在回收站」处理 ——
|
|
731
|
+
// 与库列表同一口径,不因为它没有 item.json 就从检索里消失。
|
|
732
|
+
// readItem 对缺失/坏文件返回默认条目且不抛(见 library.js),所以这里不需要再兜一层。
|
|
733
|
+
const item = path === '' ? null : await readItem(path)
|
|
734
|
+
const status = typeof item?.status === 'string' && item.status !== '' ? item.status : 'unread'
|
|
735
|
+
const tags = Array.isArray(item?.tags) ? item.tags.map(tag => String(tag).toLowerCase()) : []
|
|
736
|
+
const trashed = item?.trashed === true
|
|
737
|
+
if (statusWanted !== '' && status !== statusWanted) continue
|
|
738
|
+
// 多个标签是 AND:问的是「同时打了这两个标签的那几篇」。
|
|
739
|
+
if (tagWanted.length > 0 && !tagWanted.every(tag => tags.includes(tag.toLowerCase()))) continue
|
|
740
|
+
// 给了筛选就默认排除回收站里的(它们是用户主动丢掉的,不该混进「我该读什么」);
|
|
741
|
+
// 显式 trashed:true 才只看回收站。什么都不给时保持原行为(全库,含回收站)。
|
|
742
|
+
if (trashWanted !== trashed) continue
|
|
743
|
+
kept.push(raw)
|
|
744
|
+
}
|
|
745
|
+
scope = kept
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// ---- 两条路径,同一个形状:{hits, matched, offset, scanned, unmarked} ----
|
|
749
|
+
// 索引是**可选的加速层**:它答不了(词组 / 中文子串 / 落后于库 / 块序号对不上)或者
|
|
750
|
+
// 抛了任何错,都退回扫描。两条路径的打分与切词是同一份(search-terms.js),
|
|
751
|
+
// 所以退回只会慢,不会改变答案。
|
|
752
|
+
const offset = clampSearchOffset(request.offset)
|
|
753
|
+
const width = clampSnippetChars(request.snippetChars)
|
|
754
|
+
const narrowed = explicit.length > 0 || (typeof request.collection === 'string' && request.collection.trim() !== '')
|
|
755
|
+
|| statusWanted !== '' || tagWanted.length > 0 || typeof request.trashed === 'boolean'
|
|
756
|
+
const filterLabel = '状态「' + (statusWanted || '不限') + '」'
|
|
757
|
+
+ (tagWanted.length > 0 ? '、标签「' + tagWanted.join(' + ') + '」' : '')
|
|
758
|
+
const query = String(request.query ?? '')
|
|
759
|
+
|
|
760
|
+
/** 一篇记录 → 索引与检索共用的 { documentId, markdownPath, pdfName };没有正文的不参与。 */
|
|
761
|
+
const documentOf = raw => {
|
|
762
|
+
const document = hydrateDocument(raw)
|
|
763
|
+
const markdownPath = typeof document.markdownPath === 'string' ? document.markdownPath : ''
|
|
764
|
+
if (markdownPath === '') return null
|
|
765
|
+
return {
|
|
766
|
+
documentId: raw.id,
|
|
767
|
+
markdownPath,
|
|
768
|
+
contentPath: documentPaths(document).contentPath,
|
|
769
|
+
pdfName: typeof document.pdfName === 'string' && document.pdfName !== '' ? document.pdfName : String(raw.id),
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
// 索引镜像**整个库**,检索的范围只决定这次从结果里取哪些 —— 把范围当成「库里现在有这些」
|
|
773
|
+
// 传下去,一次 papers / collection / 状态 / 标签筛过的检索就会把其余篇的倒排全摘掉,
|
|
774
|
+
// 下一次全库检索得逐篇重写回来(实测约 9 s)。
|
|
775
|
+
const library = records.map(documentOf).filter(Boolean)
|
|
776
|
+
const inScope = new Set(scope.map(raw => raw.id))
|
|
777
|
+
const documents = library.filter(document => inScope.has(document.documentId))
|
|
778
|
+
|
|
779
|
+
// 只有「纯 ASCII 单词、没有词组」的查询才可能由倒排回答:词组要按原文子串校验,
|
|
780
|
+
// 中文是子串语义 —— 两者都不是词干能表达的东西。
|
|
781
|
+
const parsed = parseQuery(query)
|
|
782
|
+
const indexable = parsed.words.length > 0 && parsed.phrases.length === 0 && parsed.words.every(isPlainWord)
|
|
783
|
+
|
|
784
|
+
let result = null
|
|
785
|
+
let engine = 'scan'
|
|
786
|
+
if (indexable) {
|
|
787
|
+
try {
|
|
788
|
+
// 对齐与查询在**同一个临界区**里(见 runIndexedSearch):并发检索会排队,换来读者
|
|
789
|
+
// 永远看不到「新倒排 + 旧块长表」的中间态 —— 那个窗口里分数与命中数会悄悄不对。
|
|
790
|
+
result = await runIndexedSearch({
|
|
791
|
+
root, documents: library, scope: documents, query, limit, offset, snippetChars: width,
|
|
792
|
+
reuseMs: offset > 0 ? SYNC_REUSE_MS : 0,
|
|
793
|
+
order: request.order,
|
|
794
|
+
})
|
|
795
|
+
if (result !== null) engine = 'index'
|
|
796
|
+
} catch (error) {
|
|
797
|
+
// 索引是可选的:读不懂、写不成、分片坏了,都只记一条 warn,这一次走扫描。
|
|
798
|
+
ctx.logger.warn('dsh-paper search: 索引不可用,本次退回扫描:' + errorText(error))
|
|
799
|
+
result = null
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
if (result === null) {
|
|
803
|
+
const scanned = await scanMatches({
|
|
804
|
+
records: scope, query, order: request.order,
|
|
805
|
+
// 含 CJK 的查询是子串语义,倒排答不了;但 manifest 记着每篇正文里有没有 CJK 字符,
|
|
806
|
+
// 据此把不可能的篇整篇跳过(真实库 73 篇里只有 1 篇含中文 → 省掉 72 篇的读盘与切词)。
|
|
807
|
+
skipIds: await docsWithoutCjk({ root, documents: library, parsed }),
|
|
808
|
+
})
|
|
809
|
+
result = {
|
|
810
|
+
hits: pageOf({ rows: scanned.rows, offset, limit, snippetChars: width }),
|
|
811
|
+
matched: scanned.matched,
|
|
812
|
+
offset,
|
|
813
|
+
scanned: scanned.scanned,
|
|
814
|
+
unmarked: scanned.unmarked,
|
|
815
|
+
unreadable: scanned.unreadable,
|
|
816
|
+
degraded: scanned.degraded,
|
|
817
|
+
totalUnits: scanned.totalUnits,
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
const { hits, matched, scanned, unmarked, unreadable = [], degraded, totalUnits } = result
|
|
822
|
+
const hitsByDocument = new Map()
|
|
823
|
+
for (const hit of hits) {
|
|
824
|
+
if (!hitsByDocument.has(hit.documentId)) hitsByDocument.set(hit.documentId, [])
|
|
825
|
+
hitsByDocument.get(hit.documentId).push(hit)
|
|
826
|
+
}
|
|
827
|
+
for (const [documentId, paperHits] of hitsByDocument) {
|
|
828
|
+
if (typeof readerBlocksOf !== 'function') continue
|
|
829
|
+
const raw = records.find(record => record.id === documentId)
|
|
830
|
+
if (!raw) continue
|
|
831
|
+
const { blocks } = await readBlocks(raw)
|
|
832
|
+
const headings = new Map(headingEntries(blocks).filter(entry => !entry.noise && !entry.toc).map(entry => [entry.index, entry.title]))
|
|
833
|
+
// 🔴 归属按**阅读顺序**算,不按块数组顺序:MinerU 会把表格排到正文之前,
|
|
834
|
+
// 数组顺序下 `p17-t1`(Social values 的正文表)会被算成上一节 C.1 的 —— 于是
|
|
835
|
+
// 检索结果说「这条在 C.1 里」,读者去 C.1 找不到(它现在按阅读顺序切,不在 C.1),
|
|
836
|
+
// 而它真正属于的 Social values 又搜不到。`section()` 与 `search()` 必须同口径。
|
|
837
|
+
const owners = blockOwners(blocks)
|
|
838
|
+
for (const hit of paperHits) {
|
|
839
|
+
const index = blocks.findIndex(block => block.id === hit.blockId)
|
|
840
|
+
if (index < 0) continue
|
|
841
|
+
const owner = owners[index]
|
|
842
|
+
if (owner < 0 || !headings.has(owner)) continue
|
|
843
|
+
hit.section = { blockId: blocks[owner].id, title: headings.get(owner) }
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
const failures = [...unmarked, ...unreadable.map(name => name + ':正文无法读取,未参与检索。')]
|
|
847
|
+
const tail = (unmarked.length > 0 ? ' ' + unmarked.length + ' 篇没有块标记,未参与检索。' : '')
|
|
848
|
+
+ (unreadable.length > 0 ? ' ' + unreadable.length + ' 篇正文无法读取,未参与检索;未检索的论文不能视为零命中。' : '')
|
|
849
|
+
// 退化检索的提示:必须说清「这不是全词命中」,否则模型会把部分命中当成「论文就是这么写的」。
|
|
850
|
+
const degradedNote = degraded === true && Number.isFinite(totalUnits) && totalUnits > 1
|
|
851
|
+
? '⚠️ 这几个词没有任何一段**同时**全部出现,下面是保留多数关键词、引号词组与数字标识的**部分命中**(按命中词数多的先出,'
|
|
852
|
+
+ '每条标注 matched 命中数/' + totalUnits + ')—— 要精确命中请减少词数或改写措辞。'
|
|
853
|
+
: ''
|
|
854
|
+
if (scanned === 0) {
|
|
855
|
+
// 「范围被筛空了」与「范围内的论文都读不了」是两件事,处置也不同:
|
|
856
|
+
// 前者换个筛选条件就有结果,后者得先重新解析。别让前者显示成后者。
|
|
857
|
+
return {
|
|
858
|
+
ok: false,
|
|
859
|
+
hits: [],
|
|
860
|
+
engine,
|
|
861
|
+
failures: failures.slice(0, 5),
|
|
862
|
+
notice: unreadable.length > 0 ? '范围内正文无法读取,未完成检索。请用 Paper_library get 核对论文状态。'
|
|
863
|
+
: narrowed && unmarked.length === 0
|
|
864
|
+
? '这个筛选条件下没有可检索的论文(' + filterLabel + ')—— 换个条件试试,或用 Paper_library 的 list 看现在有哪些篇。'
|
|
865
|
+
: '范围内没有可检索的论文(没有块标记的 ' + unmarked.length + ' 篇需要先重新解析)。',
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
// 🔴 offset=0 时「已经越过」是句假话:0 就是从头开始,0 命中只说「没找到」。
|
|
869
|
+
// 只有 offset > 0 才谈得上「翻过头了」。
|
|
870
|
+
const shown = matched === 0
|
|
871
|
+
? '没有命中'
|
|
872
|
+
: offset >= matched
|
|
873
|
+
? 'offset ' + offset + ' 已经越过全部 ' + matched + ' 处命中'
|
|
874
|
+
: '返回第 ' + (offset + 1) + '–' + (offset + hits.length) + ' 条(共 ' + matched + ' 处)'
|
|
875
|
+
return {
|
|
876
|
+
ok: true,
|
|
877
|
+
hits,
|
|
878
|
+
engine,
|
|
879
|
+
scanned,
|
|
880
|
+
matched,
|
|
881
|
+
offset,
|
|
882
|
+
// truncated 只表示「这一页之后还有」:模型据此决定要不要翻页,不必自己算 offset+limit。
|
|
883
|
+
truncated: offset + hits.length < matched ? true : undefined,
|
|
884
|
+
nextOffset: offset + hits.length < matched ? offset + hits.length : undefined,
|
|
885
|
+
failures: failures.length > 0 ? failures.slice(0, 5) : undefined,
|
|
886
|
+
notice: (degradedNote === '' ? '' : degradedNote + ' ')
|
|
887
|
+
+ '在 ' + scanned + ' 篇里找到 ' + matched + ' 处,' + shown
|
|
888
|
+
+ (matched === 0 ? ';查询词未命中已解析正文,不代表原文没有讨论相关概念。可换关键词,或用 outline / section 阅读相关章节' : ';按 score 降序(同分时论文相关度 paperRank 靠前的先出)')
|
|
889
|
+
+ (offset + hits.length < matched
|
|
890
|
+
? ';还有更多:用 offset=' + (offset + hits.length) + ' 接着取'
|
|
891
|
+
: '')
|
|
892
|
+
+ (matched === 0 ? '' : '。') + tail,
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
async function readPdf(request) {
|
|
897
|
+
const invalid = validateReadRequest(request)
|
|
898
|
+
if (invalid) return invalid
|
|
899
|
+
const state = await repository.snapshot()
|
|
900
|
+
const raw = await readerDocumentOf(state, request.documentId)
|
|
901
|
+
if (!raw) return { ok: false, notice: '找不到这篇论文。' }
|
|
902
|
+
const document = hydrateDocument(raw)
|
|
903
|
+
const paths = documentPaths(document)
|
|
904
|
+
|
|
905
|
+
if (request.action === 'page') {
|
|
906
|
+
const page = Number.isFinite(request.page) ? Math.floor(request.page) : 1
|
|
907
|
+
if (page < 1) return { ok: false, notice: '页码从 1 开始。' }
|
|
908
|
+
const width = Number.isFinite(request.width) ? Math.floor(request.width) : 1200
|
|
909
|
+
try {
|
|
910
|
+
const rendered = await renderPages(
|
|
911
|
+
{ pdfPath: document.pdfPath, pages: [page], width: Math.min(Math.max(width, 200), 4096) },
|
|
912
|
+
// 🔴 这里必须用 deps 解构出来的 `mineruCommand`,不是 `config.mineruCommand` ——
|
|
913
|
+
// 整个文件没有 `config` 这个名字(那只存在于 index.js 的 apply 作用域),
|
|
914
|
+
// 写成 config.* 会抛 ReferenceError,被下面的 catch 收成
|
|
915
|
+
// 「原页渲染失败:config is not defined」,于是**每一次**读页都失败。
|
|
916
|
+
{ cacheDir: pageImageCacheDir, command: mineruCommand },
|
|
917
|
+
)
|
|
918
|
+
const image = Array.isArray(rendered?.images) ? rendered.images[0] : undefined
|
|
919
|
+
if (image === undefined) return { ok: false, notice: '第 ' + page + ' 页渲染不出来(可能超出页数)。' }
|
|
920
|
+
// 收图的模型直接看页面;任何一步不满足就只回路径 —— 塞进去只会被提供商在下一次请求里拒掉。
|
|
921
|
+
let attached
|
|
922
|
+
try {
|
|
923
|
+
attached = await attachPageImage(image.path, request.agent)
|
|
924
|
+
} catch (error) {
|
|
925
|
+
ctx.logger.warn('dsh-paper read: 原页图未能转成附件,按路径返回:' + errorText(error))
|
|
926
|
+
}
|
|
927
|
+
return attached === undefined
|
|
928
|
+
? { ok: true, path: image.path, notice: '' }
|
|
929
|
+
: { ok: true, path: image.path, image: attached, notice: '' }
|
|
930
|
+
} catch (error) {
|
|
931
|
+
return { ok: false, notice: '原页渲染失败:' + errorText(error) }
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
const { blocks, notice } = await readBlocks(document)
|
|
936
|
+
|
|
937
|
+
if (request.action === 'meta') {
|
|
938
|
+
if (typeof outlineTextOf === 'function') await outlineTextOf(document)
|
|
939
|
+
const metadata = await effectiveMetadata(raw)
|
|
940
|
+
const outline = await readFile(paths.outlinePath, 'utf8').then(parseOutlineFile).catch(() => ({ version: 0, budget: 0 }))
|
|
941
|
+
const outlineInfo = await stat(paths.outlinePath).catch(() => null)
|
|
942
|
+
const itemPath = itemPathOf(root, raw)
|
|
943
|
+
const item = itemPath === '' ? {} : await readItem(itemPath)
|
|
944
|
+
const cleared = Object.fromEntries(metadata.clearedMetadata.filter(field => ['title', 'authors', 'year'].includes(field)).map(field => [field, field === 'authors' ? [] : '']))
|
|
945
|
+
return { ok: true, metadata: { ...(typeof metadata.title === 'string' ? { title: metadata.title } : {}),
|
|
946
|
+
authors: metadata.authors, year: metadata.year, ...(metadata.etal === true ? { authorsEtal: true } : {}),
|
|
947
|
+
...cleared, bibliography: metadata.bibliography, blocks: blocks.length,
|
|
948
|
+
...(Object.keys(metadata.metadataSources).length ? { metadataSources: metadataSourceRows(metadata.metadataSources) } : {}),
|
|
949
|
+
outline: { version: outline.version ?? 0, budget: outline.budget ?? 0, truncated: typeof outline.text === 'string' ? outline.text.includes('…目录已截断') : raw.outlineTruncated === true,
|
|
950
|
+
...(outlineInfo ? { updatedAt: outlineInfo.mtime.toISOString() } : {}) },
|
|
951
|
+
tags: item.tags ?? [], starred: item.starred === true }, notice }
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
if (request.action === 'outline') {
|
|
955
|
+
if (typeof outlineTextOf === 'function') await outlineTextOf(document)
|
|
956
|
+
const text = blocks.length > 0
|
|
957
|
+
? buildOutline(await readFile(paths.markdownPath, 'utf8'), Number.MAX_SAFE_INTEGER, blocks).text
|
|
958
|
+
: await outlineTextOf(document)
|
|
959
|
+
return { ok: true, text, notice, truncated: text.includes('…目录已截断'),
|
|
960
|
+
sections: sectionStats(blocks, { chars: request.chars === true }) }
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
if (request.action === 'audit') return { ok: true, issues: auditSections(blocks), notice,
|
|
964
|
+
sections: sectionStats(blocks) }
|
|
965
|
+
|
|
966
|
+
if (request.action === 'section' || request.action === 'blocks') {
|
|
967
|
+
if (blocks.length === 0) return { ok: false, notice: notice === '' ? '这篇没有块列表。' : notice }
|
|
968
|
+
const range = request.action === 'section'
|
|
969
|
+
? (request.section === undefined ? { from: 0, to: blocks.length } : findSection(blocks, request.section, request.scope))
|
|
970
|
+
: addressedRange(blocks, request)
|
|
971
|
+
if (range.error) return { ok: false, code: range.code, notice: range.error, candidates: range.candidates }
|
|
972
|
+
// 🔴 章节按**阅读顺序**切(sectionBlocks),块区间按**数组顺序**切(slicePage):
|
|
973
|
+
// 两者是不同的坐标系,不是同一件事的两种写法。MinerU 会把表格 / 代码块排到正文之前,
|
|
974
|
+
// 数组顺序切出来的「C.1」于是多吞一张属于 C.2 的表,而 C.2 的正文读出来是空节
|
|
975
|
+
// (实测 6110086c:C.1 3337 字符里含 Social values 的表格正文)。
|
|
976
|
+
// 阅读顺序只在**可证页**上改序(见 reading-order.js),其余页两者逐块相同。
|
|
977
|
+
const members = request.action === 'section' && range.index !== undefined
|
|
978
|
+
? sectionBlocks(blocks, range.index, request.scope)
|
|
979
|
+
: null
|
|
980
|
+
if (members !== null) {
|
|
981
|
+
const kinds = contentKinds(blocks, members)
|
|
982
|
+
const pages = [...new Set(members.map(index => blocks[index].page))].filter(Number.isSafeInteger)
|
|
983
|
+
const pageFrom = pages.length > 0 ? Math.min(...pages) : blocks[range.from].page
|
|
984
|
+
const pageTo = pages.length > 0 ? Math.max(...pages) : pageFrom
|
|
985
|
+
// 一条内容都没有:如实说「没有正文」,并把能看原页的页码给出去。
|
|
986
|
+
// 🔴 提示必须**同时**说清三件事:这是解析结果里没有内容(不是工具读不到)、
|
|
987
|
+
// 原页可能真有内容、以及**去哪儿找**。前两条过去已经有了,第三条是本轮补的:
|
|
988
|
+
// MinerU 常把表格排在标题上方,于是正文按阅读顺序归给了上一节 —— 只说「没有正文」
|
|
989
|
+
// 或只说「可能是解析归错了」,读者仍然不知道该查哪一节。
|
|
990
|
+
// 证据由 `previousSectionEvidence` 给:同页、阅读顺序上紧邻、归属别节、
|
|
991
|
+
// 且与本节标题有区分度足够的实词重合。没有证据时退回笼统说法,不瞎指。
|
|
992
|
+
if (kinds.kinds.length === 0) {
|
|
993
|
+
const evidence = previousSectionEvidence(blocks, range.index)
|
|
994
|
+
const where = evidence === undefined
|
|
995
|
+
? '也可能是解析把正文归到了相邻标题下,可用 outline 核对。'
|
|
996
|
+
: '这一节的正文可能在上一节「' + evidence.sectionTitle + '」里:块 ' + evidence.blockId
|
|
997
|
+
+ ' 的文字与本节标题重合(' + evidence.words.join(' / ') + '),按阅读顺序归到了那一节。'
|
|
998
|
+
+ '用 Paper_read action="section" 并给出该节标题即可读到;确认属于本节的话,可用 blocks 按块 id 定位。'
|
|
999
|
+
return { ok: false, code: 'SECTION_TEXT_UNAVAILABLE', readPages: pages, pageFrom, pageTo,
|
|
1000
|
+
...(evidence === undefined ? {} : { evidence }),
|
|
1001
|
+
notice: '现有解析结果中这一节没有正文(这一节只有标题块)。可用 Paper_read action="page",paper 保持不变,page='
|
|
1002
|
+
+ (pages[0] ?? pageFrom) + ' 查看原页。' + where }
|
|
1003
|
+
}
|
|
1004
|
+
const page = sliceMembersPage(blocks, members, request.offset)
|
|
1005
|
+
const noticeOf = sectionNotice(kinds)
|
|
1006
|
+
if (noticeOf === '') return page
|
|
1007
|
+
const figures = [...new Set(members.filter(index => ['figure', 'image'].includes(blocks[index].type)).map(index => blocks[index].page))].filter(Number.isSafeInteger)
|
|
1008
|
+
return { ...page, notice: noticeOf, ...(figures.length > 0 ? { readPages: figures } : {}) }
|
|
1009
|
+
}
|
|
1010
|
+
const page = slicePage(blocks, range.from, range.to, request.offset)
|
|
1011
|
+
// 🔴 `blocks` 是**块级随机访问**,不是章节读取:`blockId + span` 会静默跨进下一节。
|
|
1012
|
+
// 调用方拿它当「读这一节」用时,跨节内容会被误当成本节内容(实测 `p17-h2 span 5`
|
|
1013
|
+
// 直接返回了 p18 的标题与正文)。这里只**如实提示**越界,不裁剪 —— 块级读取的语义
|
|
1014
|
+
// 就是「从这块起 N 块」,擅自截断会让按块号翻页的调用方算错偏移。
|
|
1015
|
+
const crossed = crossSections(blocks, range.from, range.to)
|
|
1016
|
+
if (crossed === '') return page
|
|
1017
|
+
return { ...page, notice: crossed }
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// 笔记与译文都要与**当前**块列表对齐,所以共用这一份合并后的块。
|
|
1021
|
+
const translationPath = translationPathOf(document)
|
|
1022
|
+
const translation = translationPath === '' ? null : await readTranslation(translationPath)
|
|
1023
|
+
const merged = mergeReaderBlocks(blocks, translation)
|
|
1024
|
+
|
|
1025
|
+
if (request.action === 'notes') {
|
|
1026
|
+
return {
|
|
1027
|
+
ok: true,
|
|
1028
|
+
marks: await readerMarksOf(document, merged),
|
|
1029
|
+
threads: await readerThreadsOf(document, merged),
|
|
1030
|
+
notice: '',
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
if (request.action === 'translation') {
|
|
1035
|
+
let selected = merged
|
|
1036
|
+
if (request.section !== undefined) {
|
|
1037
|
+
const range = findSection(blocks, request.section, request.scope)
|
|
1038
|
+
if (range.error) return { ok: false, code: range.code, notice: range.error, candidates: range.candidates }
|
|
1039
|
+
// 🔴 与 `section` 同口径:按**阅读顺序**取块,不按块数组区间。
|
|
1040
|
+
// 两者不一致时(表格被排到正文之前那类),按数组取会把上一节的块算进本节,
|
|
1041
|
+
// 于是同一节「读原文」和「读译文」给出的块集合不同 —— 读者对不上号。
|
|
1042
|
+
const members = sectionBlocks(blocks, range.index, request.scope)
|
|
1043
|
+
selected = members.map(index => merged[index]).filter(Boolean)
|
|
1044
|
+
}
|
|
1045
|
+
const staleTranslationCount = selected.filter(block => block.translationStale === true).length
|
|
1046
|
+
return {
|
|
1047
|
+
ok: true,
|
|
1048
|
+
translation: selected.map(block => ({ blockId: block.id, zh: typeof block.zh === 'string' ? block.zh : '' })),
|
|
1049
|
+
...(staleTranslationCount > 0 ? { staleTranslationCount } : {}),
|
|
1050
|
+
notice: staleTranslationCount > 0 ? staleTranslationCount + ' 块译文与当前原文指纹不一致,已按过期处理;请用 section / blocks 阅读当前原文,旧译文文件保留。' : '',
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
return { ok: false, notice: '不支持的动作:' + request.action }
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
return { exportFor, writeExportFile, runLibraryRequest, attachPageImage, readPdf, searchPapers }
|
|
1058
|
+
}
|