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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +150 -2
  3. package/cordis.patch.yml +4 -0
  4. package/lib/annotate-tool.js +334 -0
  5. package/lib/arxiv-id.js +74 -0
  6. package/lib/asset-routes.js +210 -0
  7. package/lib/bibliography-formats.js +126 -0
  8. package/lib/bibliography-import.js +105 -0
  9. package/lib/bibliography-service.js +43 -0
  10. package/lib/bibliography.js +42 -0
  11. package/lib/block-authors.js +292 -0
  12. package/lib/block-cache.js +39 -0
  13. package/lib/blocks-markdown.js +157 -0
  14. package/lib/blocks-reconcile.js +218 -0
  15. package/lib/blocks.js +1344 -0
  16. package/lib/citation-metadata.js +260 -0
  17. package/lib/citation-styles.js +120 -0
  18. package/lib/client-parts/01-pure-helpers.js +2762 -0
  19. package/lib/client-parts/02-author-year.js +95 -0
  20. package/lib/client.js +10381 -0
  21. package/lib/code-source.js +68 -0
  22. package/lib/concurrency-gate.js +91 -0
  23. package/lib/context.js +233 -0
  24. package/lib/csl/SOURCES.md +10 -0
  25. package/lib/csl/gb-t-7714.csl +441 -0
  26. package/lib/csl/ieee.csl +520 -0
  27. package/lib/csl/locales-zh-CN.xml +438 -0
  28. package/lib/csl/nature.csl +190 -0
  29. package/lib/discussion.js +400 -0
  30. package/lib/documents.js +67 -0
  31. package/lib/export.js +848 -0
  32. package/lib/file-lock.js +177 -0
  33. package/lib/gloss.js +181 -0
  34. package/lib/glossary.js +279 -0
  35. package/lib/index.js +3862 -0
  36. package/lib/inline-html.js +53 -0
  37. package/lib/install-dependency.js +120 -0
  38. package/lib/item-ops.js +83 -0
  39. package/lib/job-facade.js +58 -0
  40. package/lib/json-store.js +54 -0
  41. package/lib/library-model.js +132 -0
  42. package/lib/library-service.js +180 -0
  43. package/lib/library-tool.js +982 -0
  44. package/lib/library.js +814 -0
  45. package/lib/markdown-assets.js +138 -0
  46. package/lib/markdown-literals.js +93 -0
  47. package/lib/metadata-enrichment.js +516 -0
  48. package/lib/metadata-fetch.js +146 -0
  49. package/lib/metadata-node.js +158 -0
  50. package/lib/metadata-proxy.ps1 +35 -0
  51. package/lib/mineru-config.js +95 -0
  52. package/lib/mineru-sdk-helper.py +123 -0
  53. package/lib/mineru-sdk.js +182 -0
  54. package/lib/mineru.js +268 -0
  55. package/lib/mirror-export.js +240 -0
  56. package/lib/outline.js +296 -0
  57. package/lib/page-image-helper.py +308 -0
  58. package/lib/page-image.js +454 -0
  59. package/lib/paper-metadata.js +242 -0
  60. package/lib/parse-export.js +631 -0
  61. package/lib/pdf-analysis-tool.js +750 -0
  62. package/lib/pdf-metadata-helper.py +75 -0
  63. package/lib/pdf-metadata.js +141 -0
  64. package/lib/pdf-page.js +261 -0
  65. package/lib/pdf-scan.js +134 -0
  66. package/lib/pdf-text.js +68 -0
  67. package/lib/picker.js +305 -0
  68. package/lib/portable.js +379 -0
  69. package/lib/purge.js +170 -0
  70. package/lib/read-tool.js +660 -0
  71. package/lib/reader-store.js +497 -0
  72. package/lib/reading-order.js +207 -0
  73. package/lib/rename-document.js +480 -0
  74. package/lib/rename.js +372 -0
  75. package/lib/renderer-status.js +161 -0
  76. package/lib/resolver.js +1152 -0
  77. package/lib/result-archive.js +157 -0
  78. package/lib/revisions.js +330 -0
  79. package/lib/search-database.js +62 -0
  80. package/lib/search-index.js +601 -0
  81. package/lib/search-scan.js +185 -0
  82. package/lib/search-source.js +23 -0
  83. package/lib/search-terms.js +539 -0
  84. package/lib/section-audit.js +209 -0
  85. package/lib/selection-message.js +332 -0
  86. package/lib/serial-tail.js +21 -0
  87. package/lib/slicing.js +425 -0
  88. package/lib/source-resolver.js +581 -0
  89. package/lib/stem-repair.js +189 -0
  90. package/lib/storage.js +562 -0
  91. package/lib/store-paths.js +253 -0
  92. package/lib/table-gfm.js +236 -0
  93. package/lib/tasks.js +270 -0
  94. package/lib/tex-align.js +509 -0
  95. package/lib/tex-blocks.js +653 -0
  96. package/lib/tex-fetch.js +455 -0
  97. package/lib/tex-figures.js +140 -0
  98. package/lib/tex-inline.js +166 -0
  99. package/lib/tex-merge.js +279 -0
  100. package/lib/tex-pipeline.js +242 -0
  101. package/lib/tex-prepare.js +746 -0
  102. package/lib/tex-tables.js +210 -0
  103. package/lib/text-similarity.js +85 -0
  104. package/lib/tool-contract.js +86 -0
  105. package/lib/tool-host.js +1058 -0
  106. package/lib/tool-identity.js +214 -0
  107. package/lib/translatable-text.js +48 -0
  108. package/lib/translate-prompts.js +709 -0
  109. package/lib/translate-queue.js +418 -0
  110. package/lib/translate-task.js +158 -0
  111. package/lib/translate.js +909 -0
  112. package/lib/update-check.js +438 -0
  113. package/lib/update-contracts.js +75 -0
  114. package/lib/usage.js +282 -0
  115. package/package.json +55 -4
@@ -0,0 +1,982 @@
1
+ /**
2
+ * Paper_library 工具:文献库的读取与管理。
3
+ *
4
+ * 分工与 pdf-analysis-tool.js 一致 —— 这里是**模型的入口**(schema、校验、可执行的中文回执),
5
+ * 真正的库操作经 deps.run 交回 index.js:那条路已经拥有写锁(serializeLibrary)、条目文件、
6
+ * 集合校验与回收站语义,工具另起一套只会造出第二个真相源。
7
+ *
8
+ * 查询与筛选是纯函数,留在这个模块里是为了能直接测:它们决定模型能不能在几十上百篇里
9
+ * 找到目标,属于本工具的行为,不是执行细节。
10
+ */
11
+
12
+ import { identifyDocument, identityRecordOf } from './tool-identity.js'
13
+ import { createLibraryModel } from './library-model.js'
14
+ import { citationMetadataWithDisk } from './citation-metadata.js'
15
+ import { BIBLIOGRAPHY_SCHEMA, METADATA_FIELDS, METADATA_SOURCES_SCHEMA, ENRICHMENT_SCHEMA, metadataSourceRows, validateMetadata } from './paper-metadata.js'
16
+ import { toolContract } from './tool-contract.js'
17
+
18
+ /** 一页最多返回多少篇。再多人也读不完,而且会一次性吃满上下文。 */
19
+ export const MAX_LIMIT = 100
20
+
21
+ /** list 的默认页大小。 */
22
+ export const DEFAULT_LIMIT = 20
23
+
24
+ /** 阅读状态的合法取值,与 library.js 的 READ_STATUSES 同值。 */
25
+ export const STATUSES = Object.freeze(['unread', 'reading', 'read'])
26
+
27
+ /**
28
+ * 引用格式。三份实现都在 export.js 里,工具只负责选一种。
29
+ *
30
+ * 🔴 **拼写必须与宿主侧一致**(`tool-host.js` 的 `exportFor`、`/export` 路由的缺省值、
31
+ * 客户端按钮传的值都是 `gb-t-7714`)。这里曾写成 `gb7714`,于是两个值都取不到结果:
32
+ * 传 `gb7714` 被工具层放行、到宿主层被判「引用格式必须是 gb-t-7714」;
33
+ * 传 `gb-t-7714` 又被工具层的 enum 先拒掉 —— **一个能用的值都没有**。
34
+ * 工具层的 enum 是模型唯一看得到的说明书,它以什么拼写出现,模型就会以什么拼写调用。
35
+ */
36
+ export const CITATION_FORMATS = Object.freeze(['bibtex', 'ris', 'csl-json', 'csl', 'apa', 'gb-t-7714'])
37
+
38
+ /** 排序方式,与 library.js 的 SORT_MODES 同值。 */
39
+ export const SORT_MODES = Object.freeze(['added', 'title', 'opened'])
40
+
41
+ const NEEDS_COLLECTION = new Set(['collection-rename', 'collection-move', 'collection-remove', 'file', 'unfile', 'collection-merge', 'collection-move-items'])
42
+ const NEEDS_NAME = new Set(['rename', 'collection-add', 'collection-rename'])
43
+ const NEEDS_TAG = new Set(['tag', 'untag'])
44
+ const GROUP_ACTIONS = new Set(['group-hide', 'group-pin'])
45
+
46
+ export const ACTIONS = Object.freeze([
47
+ 'list', 'get', 'metadata', 'rebuild', 'collections', 'citation', 'notes', 'html',
48
+ 'star', 'pin', 'status', 'tag', 'untag',
49
+ 'collection-add', 'collection-rename', 'collection-move', 'collection-remove', 'file', 'unfile',
50
+ 'rename', 'trash', 'restore', 'inject', 'uninject',
51
+ 'sort', 'group-hide', 'group-pin',
52
+ 'bind', 'rebind', 'unbind',
53
+ 'tags', 'tag-rename',
54
+ 'collection-merge', 'collection-move-items',
55
+ 'import', 'export', 'styles', 'style-install', 'style-select',
56
+ ])
57
+
58
+ /** 动作 → 一句话用途。给模型看,也用来拼「动作不认识」的提示。 */
59
+ const ACTION_TEXT = Object.freeze({
60
+ list: '列出/筛选库里的论文',
61
+ get: '看一篇的完整记录',
62
+ metadata: '手工修改 fields,或 enrich=true 查询补全书目(默认预览)',
63
+ rebuild: '重建章节树或检索索引;默认 dryRun=true 只预览,不重新解析 PDF',
64
+ collections: '看集合树与各集合的篇数',
65
+ citation: '导出单篇书目或 CSL 引用(bibtex / ris / csl-json / csl / apa / gb-t-7714)',
66
+ import: '导入 data 中的 BibTeX/RIS/CSL-JSON;默认预览,dryRun=false 保存,可无 PDF',
67
+ export: '批量导出 papers 的书目文件或 CSL 参考文献表,返回下载地址',
68
+ styles: '列出内置与已安装的 CSL 样式、默认样式和语言',
69
+ 'style-install': '安装 data 中的本地 CSL XML;父样式须已安装,不联网下载',
70
+ 'style-select': '按 style 键选择默认 CSL 样式,可指定 locale',
71
+ notes: '导出这批论文的笔记 Markdown',
72
+ html: '把论文导出成 HTML 文件',
73
+ star: '加/取消星标',
74
+ pin: '置顶/取消置顶',
75
+ status: '改阅读状态(unread / reading / read)',
76
+ tag: '加标签',
77
+ untag: '移除标签',
78
+ 'collection-add': '建集合(可指定父集合)',
79
+ 'collection-rename': '集合改名',
80
+ 'collection-move': '把集合移到另一个父集合下',
81
+ 'collection-remove': '删集合(只删集合,不动论文本体)',
82
+ file: '把论文归入集合',
83
+ unfile: '把论文移出集合',
84
+ rename: '重命名论文(改 PDF 文件名与全部派生文件)',
85
+ trash: '移入回收站(可还原)',
86
+ restore: '从回收站还原',
87
+ inject: '把论文推进当前会话上下文,提供论文 id 与目录;正文通过 Paper_read 继续读取',
88
+ uninject: '取消注入',
89
+ sort: '改文献库排序方式',
90
+ 'group-hide': '显示/隐藏侧栏的某个分组',
91
+ 'group-pin': '置顶/取消置顶侧栏的某个分组',
92
+ bind: '把工作区文件夹绑到库记录上(扫目录、按内容匹配、记下 sourceDir;不解析也不动你的文件)',
93
+ rebind: '把某条记录的源目录显式指到一个文件夹(PDF 换过版本、哈希对不上时用这个)',
94
+ unbind: '解绑某条记录的源目录(划线与笔记都保留)',
95
+ tags: '列出全库所有标签 + 每个标签多少篇(找分叉、决定归并)',
96
+ 'tag-rename': '全库把一个标签改成另一个(改名即合并:撞上同名标签时两拨自动收拢)',
97
+ 'collection-merge': '把一个集合的全部成员并入另一个集合,然后删掉来源集合(并集,不搬走)',
98
+ 'collection-move-items': '把来源集合里的成员整体移到目标集合(keepInSource=true 则只加入不移动)',
99
+ })
100
+
101
+ /**
102
+ * 回执动词:宿主没给 notice 时的兜底。
103
+ *
104
+ * 🔴 不能用 ACTION_TEXT —— 那是给 enum 看的一句话说明,拼进「…完成。」会变成
105
+ * 「删集合(只删集合,不动论文本体)完成。」。这里只放动词。
106
+ */
107
+ const ACTION_VERB = Object.freeze({
108
+ 'collection-remove': '删集合',
109
+ 'collection-merge': '合并集合',
110
+ 'collection-move-items': '整组移动',
111
+ 'collection-add': '建集合',
112
+ 'collection-rename': '集合改名',
113
+ 'collection-move': '移动集合',
114
+ file: '归入集合',
115
+ unfile: '移出集合',
116
+ rename: '改名',
117
+ 'tag-rename': '改名标签',
118
+ })
119
+
120
+ const PAPER_SCHEMA = {
121
+ type: 'object',
122
+ additionalProperties: false,
123
+ properties: {
124
+ paper: { type: 'string' },
125
+ documentId: { type: 'string' },
126
+ title: { type: 'string' },
127
+ authors: { type: 'array', items: { type: 'string' } },
128
+ authorsEtal: { type: 'boolean', description: '作者名单不完整(只拿到首位,后面还有人):渲染引用时写「等 / et al.」。' },
129
+ year: { type: 'string' },
130
+ bibliography: BIBLIOGRAPHY_SCHEMA,
131
+ metadataSources: METADATA_SOURCES_SCHEMA,
132
+ status: { type: 'string' },
133
+ tags: { type: 'array', items: { type: 'string' } },
134
+ starred: { type: 'boolean' },
135
+ collections: { type: 'array', items: { type: 'string' } },
136
+ markdownPath: { type: 'string' },
137
+ sourceDir: { type: 'string', description: '这篇论文在用户工作文件夹中的来源目录,可关联配套资料。' },
138
+ sourcePdfPath: { type: 'string', description: '导入时的工作文件夹 PDF;与 documentId 指向同一份论文内容,文件可能已被用户移动。' },
139
+ readable: { type: 'boolean', description: 'Markdown 是否存在、非空且带块标记(false = 这篇现在读不了,跨篇检索也搜不到它)。' },
140
+ bibliographicOnly: { type: 'boolean', description: 'true 表示仅有书目信息,尚无 PDF。' },
141
+ trashed: { type: 'boolean' },
142
+ },
143
+ required: ['paper', 'documentId'],
144
+ }
145
+
146
+ const OUTPUT_SCHEMA = {
147
+ type: 'object',
148
+ additionalProperties: false,
149
+ properties: {
150
+ ok: { type: 'boolean', description: '这次操作是否执行成功。' },
151
+ action: { type: 'string', description: '执行的是哪个动作。' },
152
+ notice: { type: 'string', description: '一句话说明发生了什么。' },
153
+ papers: { type: 'array', items: PAPER_SCHEMA, description: '涉及或命中的论文。' },
154
+ tags: {
155
+ type: 'array',
156
+ items: {
157
+ type: 'object',
158
+ additionalProperties: false,
159
+ properties: {
160
+ tag: { type: 'string' },
161
+ count: { type: 'number', description: '有多少篇打了这个标签。' },
162
+ },
163
+ required: ['tag', 'count'],
164
+ },
165
+ description: 'tags 动作:全库标签清单,按篇数降序。',
166
+ },
167
+ collections: {
168
+ type: 'array',
169
+ items: {
170
+ type: 'object',
171
+ additionalProperties: false,
172
+ properties: {
173
+ name: { type: 'string' },
174
+ path: { type: 'string' },
175
+ parent: { type: 'string' },
176
+ count: { type: 'number' },
177
+ },
178
+ required: ['name', 'path', 'count'],
179
+ },
180
+ description: '集合树(扁平前序列表,path 是「父 / 子」全路径)。',
181
+ },
182
+ total: { type: 'number', description: '符合筛选条件的总篇数(不受分页影响)。' },
183
+ offset: { type: 'number' },
184
+ limit: { type: 'number' },
185
+ order: { type: 'string', description: 'list 实际使用的排序方式(order 参数,或全局设置)。' },
186
+ citation: { type: 'string', description: 'citation 动作产出的引用文本。' },
187
+ path: { type: 'string', description: '导出文件的绝对路径。' },
188
+ url: { type: 'string', description: '导出结果的下载地址。' },
189
+ bibliography: BIBLIOGRAPHY_SCHEMA,
190
+ importReport: { type: 'object', additionalProperties: false, properties: {
191
+ dryRun: { type: 'boolean' }, total: { type: 'number' }, imported: { type: 'number' }, updated: { type: 'number' }, unchanged: { type: 'number' },
192
+ } },
193
+ styleCatalog: { type: 'object', additionalProperties: false, properties: {
194
+ selected: { type: 'string' }, locale: { type: 'string' }, locales: { type: 'array', items: { type: 'string' } }, warnings: { type: 'array', items: { type: 'string' } },
195
+ styles: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
196
+ key: { type: 'string' }, id: { type: 'string' }, title: { type: 'string' }, parent: { type: 'string' }, builtin: { type: 'boolean' },
197
+ } } },
198
+ } },
199
+ enrichment: ENRICHMENT_SCHEMA,
200
+ maintenance: { type: 'object', additionalProperties: false, properties: {
201
+ target: { type: 'string' }, dryRun: { type: 'boolean' }, count: { type: 'number' },
202
+ } },
203
+ failures: { type: 'array', items: { type: 'string' }, description: '逐篇失败的原因;其余照常执行。' },
204
+ },
205
+ required: ['ok', 'action', 'notice'],
206
+ }
207
+
208
+ function textOf(value) {
209
+ return typeof value === 'string' ? value : ''
210
+ }
211
+
212
+ function messageOf(error) {
213
+ if (error instanceof Error && error.message !== '') return error.message
214
+ const text = textOf(error)
215
+ return text === '' ? '未知错误' : text
216
+ }
217
+
218
+ /** 丢掉 undefined 的键:输出 schema 是 additionalProperties: false,写明的 undefined 同样是多余键。 */
219
+ function definedFields(source) {
220
+ const result = {}
221
+ for (const [key, value] of Object.entries(source)) {
222
+ if (value !== undefined) result[key] = value
223
+ }
224
+ return result
225
+ }
226
+
227
+ const lower = value => textOf(value).trim().toLowerCase()
228
+
229
+ /** 一篇的摘要行:只放模型真正会用的字段。 */
230
+ export function summarizePaper(entry, collectionPaths = new Map()) {
231
+ const item = entry.item ?? {}
232
+ const collections = collectionPaths.get(entry.documentId) ?? []
233
+ return definedFields({
234
+ paper: textOf(entry.pdfName) || textOf(entry.documentId),
235
+ documentId: textOf(entry.documentId),
236
+ bibliographicOnly: entry.kind === 'bibliography' ? true : undefined,
237
+ title: textOf(entry.title) || undefined,
238
+ authors: Array.isArray(entry.authors) && entry.authors.length > 0 ? entry.authors.map(String) : undefined,
239
+ year: textOf(entry.year) || undefined,
240
+ status: textOf(item.status) || undefined,
241
+ tags: Array.isArray(item.tags) && item.tags.length > 0 ? item.tags.map(String) : undefined,
242
+ starred: item.starred === true ? true : undefined,
243
+ collections: collections.length > 0 ? collections : undefined,
244
+ markdownPath: textOf(entry.markdownPath) || undefined,
245
+ // 用户工作区里那篇论文的文件夹:sibling 的 Source/、Reproduction/、Thought.md 都按它推。
246
+ // 只有本地入库过的论文才有,缺一个不动手(arxiv/doi 直接入库的没有可选目录)。
247
+ sourceDir: textOf(entry.sourceDir) || undefined,
248
+ sourcePdfPath: textOf(entry.sourcePdfPath) || undefined,
249
+ // 能不能读:Markdown 存在、非空、且带块标记(没有标记的正文检索看不见)。
250
+ // 由库视图(index.js 的 libraryItems)算好带上来 —— 只给路径等于把这件事推给调用方,
251
+ // 而模型没有 stat,更没有「文件里有没有块标记」这个知识。
252
+ readable: entry.readable === false ? false : true,
253
+ trashed: item.trashed === true ? true : undefined,
254
+ })
255
+ }
256
+
257
+ /**
258
+ * 库列表的排序。与面板 `client.js` 的 `librarySort` **同一条规则**(两处各写一份会分叉):
259
+ * 置顶恒定在最前,同一档内再按所选方式排;时间缺失(还没落过 item.json)排在最后,
260
+ * 它表达的是「还没登记」而不是「很久以前」。
261
+ *
262
+ * @param {object[]} entries 库视图的条目
263
+ * @param {'added'|'title'|'opened'} mode 排序方式
264
+ * @returns {object[]} 新数组(不改入参)
265
+ */
266
+ export function sortEntries(entries, mode) {
267
+ const list = [...(Array.isArray(entries) ? entries : [])]
268
+ const timeOf = value => (typeof value === 'string' && value !== '' ? Date.parse(value) : NaN)
269
+ const compare = (left, right) => {
270
+ if (mode === 'title') return String(left.pdfName ?? '').localeCompare(String(right.pdfName ?? ''), 'zh')
271
+ const field = mode === 'opened' ? 'lastOpened' : 'added'
272
+ const a = timeOf(left.item?.[field])
273
+ const b = timeOf(right.item?.[field])
274
+ if (Number.isNaN(a) && Number.isNaN(b)) return 0
275
+ if (Number.isNaN(a)) return 1
276
+ if (Number.isNaN(b)) return -1
277
+ return b - a
278
+ }
279
+ return list.sort((left, right) => {
280
+ const pin = (right.item?.pinned === true ? 1 : 0) - (left.item?.pinned === true ? 1 : 0)
281
+ return pin !== 0 ? pin : compare(left, right)
282
+ })
283
+ }
284
+
285
+ /**
286
+ * compact 模式的摘要行:拿全库 id 去批量操作时用的最小集合。
287
+ *
288
+ * 73 篇全量 `summarizePaper` 会带上标题、作者、路径、可读性…… 一次几万字符;
289
+ * 而「把全库 id 收集起来打标签」这类操作只要 id + 名字 + 所属集合。
290
+ *
291
+ * 🔴 但**状态字段必须留着**(status / tags / starred):它们正是「批量操作」要参考的东西 ——
292
+ * 没有它们,模型拿到的是一张 id 列表,仍然不知道哪些还没读、哪些打了标、哪些星标过,
293
+ * 只能再来一次完整 list(那 compact 就白省了)。这三个都是短值,73 篇合计几 KB。
294
+ * 路径与可读性才是不该进 compact 的部分,它们贵且批量操作不需要。
295
+ */
296
+ export function compactPaper(entry, collectionPaths = new Map()) {
297
+ const item = entry.item ?? {}
298
+ const collections = collectionPaths.get(entry.documentId) ?? []
299
+ return definedFields({
300
+ paper: textOf(entry.pdfName) || textOf(entry.documentId),
301
+ documentId: textOf(entry.documentId),
302
+ status: textOf(item.status) || undefined,
303
+ tags: Array.isArray(item.tags) && item.tags.length > 0 ? item.tags.map(String) : undefined,
304
+ starred: item.starred === true ? true : undefined,
305
+ collections: collections.length > 0 ? collections : undefined,
306
+ })
307
+ }
308
+
309
+ /** documentId → 它所在的集合全路径列表。集合是树,模型看全路径才认得出「综述 / Transformer」。 */
310
+ export function collectionPathsOf(library) {
311
+ const model = createLibraryModel()
312
+ const paths = new Map()
313
+ for (const row of model.collectionsOf(library)) {
314
+ const full = model.path(library, row.id)
315
+ for (const documentId of row.documentIds ?? []) {
316
+ const list = paths.get(documentId) ?? []
317
+ list.push(full)
318
+ paths.set(documentId, list)
319
+ }
320
+ }
321
+ return paths
322
+ }
323
+
324
+ /**
325
+ * 筛选 + 分页。纯函数。
326
+ *
327
+ * query 只做子串匹配(篇名/标题/作者/年份/路径/标签),**不是**界面的条件搜索 DSL:
328
+ * 模型说得出「按标题找」,却说不清 12 个字段的操作符表;把那条 DSL 搬进 schema 只会增加选错的机会。
329
+ */
330
+ export function selectPapers(items, { query = '', status = '', tag = '', collectionId = '', starred = false, trashed = false, includeTrashed = false, library = {} } = {}) {
331
+ const model = createLibraryModel()
332
+ const needle = lower(query)
333
+ const canonicalNeedle = needle.normalize('NFC')
334
+ const members = collectionId === '' ? null : new Set(model.memberIds(library, collectionId, true))
335
+ return items.filter(entry => {
336
+ const item = entry.item ?? {}
337
+ if (!includeTrashed && (item.trashed === true) !== trashed) return false
338
+ if (status !== '' && item.status !== status) return false
339
+ if (tag !== '' && !(item.tags ?? []).some(value => lower(value) === lower(tag))) return false
340
+ if (starred && item.starred !== true) return false
341
+ if (members !== null && !members.has(entry.documentId)) return false
342
+ if (needle === '') return true
343
+ const haystack = [entry.pdfName, entry.title, entry.year, entry.pdfPath, entry.markdownPath, ...(entry.authors ?? []), ...(item.tags ?? [])]
344
+ return haystack.some(value => {
345
+ const text = lower(value)
346
+ return text.includes(needle) || text.normalize('NFC').includes(canonicalNeedle)
347
+ })
348
+ })
349
+ }
350
+
351
+ export function clampLimit(value) {
352
+ if (typeof value !== 'number' || !Number.isFinite(value)) return DEFAULT_LIMIT
353
+ return Math.min(Math.max(Math.floor(value), 1), MAX_LIMIT)
354
+ }
355
+
356
+ export function clampOffset(value) {
357
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return 0
358
+ return Math.floor(value)
359
+ }
360
+
361
+ /** 在集合树里按「名字」或「父 / 子 全路径」找到那个集合。 */
362
+ export function findCollection(library, reference) {
363
+ const model = createLibraryModel()
364
+ const wanted = textOf(reference).trim()
365
+ if (wanted === '') return undefined
366
+ const rows = model.collectionsOf(library)
367
+ const exact = rows.filter(row => model.path(library, row.id) === wanted)
368
+ if (exact.length === 1) return exact[0]
369
+ const names = rows.filter(row => row.name === wanted)
370
+ return names.length === 1 ? names[0] : undefined
371
+ }
372
+
373
+ export function createLibraryTool(deps = {}) {
374
+ const model = createLibraryModel()
375
+
376
+ async function view(sessionId) {
377
+ if (typeof deps.view !== 'function') throw new Error('文献库服务不可用')
378
+ return await deps.view({ sessionId })
379
+ }
380
+
381
+ /** 把模型给的引用折成文档 id;把「找不到 / 重名」原样变成可执行的提示。 */
382
+ function resolveIds(reference, items) {
383
+ const references = (Array.isArray(reference) ? reference : [reference]).filter(value => typeof value === 'string' && value.trim() !== '')
384
+ const ids = []
385
+ const failures = []
386
+ // 🔴 不在这里手拼字段:与 Paper_read / Paper_annotate 共用 identityRecordOf,
387
+ // 否则「按文件夹名找不到」会在补了一处之后继续留在另一处(实测发生过)。
388
+ const records = items.map(identityRecordOf).filter(record => record !== null)
389
+ for (const value of references) {
390
+ const hit = identifyDocument(records, value)
391
+ if (hit.document !== undefined) ids.push(hit.document.id)
392
+ else failures.push(hit.error)
393
+ }
394
+ return { ids: [...new Set(ids)], failures }
395
+ }
396
+
397
+ const fail = (action, notice) => definedFields({ ok: false, action, notice })
398
+
399
+ /**
400
+ * 宿主没给回执时的一句话。
401
+ *
402
+ * 集合与标签那几个动作的「做了什么」只有工具侧知道(trashItems、合并了几篇),
403
+ * 所以这里按动作补,而不是一律「…完成。」—— 那句话对「删集合并移入回收站」等于没说。
404
+ */
405
+ function fallbackNotice(action, { ids, papers, result, keepInSource = false }) {
406
+ const succeeded = Array.isArray(result.succeeded) ? result.succeeded.length : 0
407
+ if (action === 'collection-remove') {
408
+ return succeeded > 0
409
+ ? '集合已删除,' + succeeded + ' 篇论文移入了回收站。'
410
+ : '已删集合(论文本体未动)。'
411
+ }
412
+ if (action === 'collection-merge') {
413
+ const merged = Number(result.merged)
414
+ return '已合并集合' + (Number.isFinite(merged) ? ':目标集合新增 ' + merged + ' 篇,来源集合已删除。' : '。')
415
+ }
416
+ if (action === 'collection-move-items') {
417
+ // keepInSource 是这次调用的参数,只有工具侧知道;宿主回的篇数不带这层语义。
418
+ return (keepInSource ? '已加入目标集合(保留在来源集合):' : '已整体移到目标集合(从来源移除):')
419
+ + (succeeded || ids.length) + ' 篇。'
420
+ }
421
+ return ids.length > 0
422
+ ? ACTION_VERB[action] + ':' + (papers?.length ?? 0) + ' 篇。'
423
+ : (ACTION_VERB[action] ?? ACTION_TEXT[action]) + '完成。'
424
+ }
425
+
426
+ /**
427
+ * 「没有可用源目录」的筛选:未绑定(记录里没有 sourceDir),或绑过的目录已经不在磁盘上。
428
+ *
429
+ * 只在开了这个过滤时逐条问磁盘 —— 它的用处是找漏,不是日常视图。
430
+ * 宿主没给 dirExists 时(单测)只按「有没有 sourceDir」判,不假装知道磁盘。
431
+ */
432
+ async function missingSourceDirs(rows) {
433
+ const kept = []
434
+ for (const entry of rows) {
435
+ const dir = textOf(entry.sourceDir).trim()
436
+ if (dir === '') { kept.push(entry); continue }
437
+ if (typeof deps.dirExists !== 'function') continue
438
+ if (!(await deps.dirExists(dir))) kept.push(entry)
439
+ }
440
+ return kept
441
+ }
442
+
443
+ return toolContract({
444
+ name: 'Paper_library',
445
+ description: [
446
+ '文献库的读取与管理:按关键词/状态/标签/集合/星标找论文,改条目属性、集合、名字与回收站,',
447
+ '导入/导出 BibTeX、RIS、CSL-JSON,安装和选择 CSL 期刊样式,生成引用与参考文献表;也可将论文推进当前会话上下文。',
448
+ 'paper / papers 都接受 64 位 id、PDF 文件名(可省 .pdf)、Markdown 路径或标题片段;重名时列候选而不是猜。',
449
+ 'sourceDir 是论文在用户工作区的位置。bind 按 PDF 内容哈希「磁盘 → 库」,' +
450
+ 'rebind / unbind 按指认「库 → 磁盘」—— PDF 换过版本、哈希对不上时用后者,不必删掉重入。',
451
+ '只能移入回收站与还原,永久删除不在模型权限内。',
452
+ ].join('\n'),
453
+ parameters: {
454
+ type: 'object',
455
+ properties: {
456
+ action: {
457
+ type: 'string',
458
+ enum: [...ACTIONS],
459
+ description: ACTIONS.map(name => name + '(' + ACTION_TEXT[name] + ')').join(';'),
460
+ },
461
+ paper: { type: 'string', description: '单篇:id、PDF 文件名、Markdown 路径或标题片段。' },
462
+ papers: { type: 'array', items: { type: 'string' }, description: '多篇:写法同 paper,一次批量处理。' },
463
+ query: { type: 'string', description: 'list 的关键词:篇名/标题/作者/年份/路径/标签的子串。' },
464
+ status: { type: 'string', enum: [...STATUSES], description: 'list 按阅读状态筛;status 动作则以它作为要设的值。' },
465
+ tag: { type: 'string', description: 'list 按标签筛;tag / untag 动作则以它作为要加/删的标签。' },
466
+ collection: { type: 'string', description: '集合名或「父 / 子」全路径。list 按集合筛;file / unfile / collection-* 指定目标集合。' },
467
+ parent: { type: 'string', description: 'collection-add / collection-move 的父集合名;省略表示放到顶层。' },
468
+ name: { type: 'string', description: 'rename 的新名字(不含 .pdf);collection-add / collection-rename 的集合名。' },
469
+ starred: { type: 'boolean', description: 'list 只看星标;star 动作里表示设为星标(默认 true)。' },
470
+ pinned: { type: 'boolean', description: 'pin / group-pin 是否置顶(默认 true)。' },
471
+ hidden: { type: 'boolean', description: 'group-hide 是否隐藏(默认 true)。' },
472
+ mode: { type: 'string', enum: [...SORT_MODES], description: 'sort 的排序方式(改全局偏好)。list 想临时换排序用 order,不动全局设置。' },
473
+ order: { type: 'string', enum: [...SORT_MODES], description: 'list 的排序方式,只影响这一次:added 按加入时间、title 按篇名、opened 按最后打开时间。省略则用全局设置。' },
474
+ format: { type: 'string', enum: [...CITATION_FORMATS], description: 'import 的来源格式或 citation/export 的输出格式;csl 使用所选样式,citation 默认 bibtex。' },
475
+ data: { type: 'string', description: 'import 的完整书目文本,或 style-install 的完整 CSL XML;不读取其中的附件路径、不自动下载 PDF。' },
476
+ style: { type: 'string', description: 'CSL 样式键,先用 styles 获取;省略使用默认样式。style-select 必填。' },
477
+ locale: { type: 'string', description: 'CSL 语言,取 styles 的 locales。' },
478
+ citationMode: { type: 'string', enum: ['bibliography', 'citation'], description: 'CSL 输出参考文献表(默认)或文内引用。' },
479
+ fields: { type: 'object', additionalProperties: false, properties: Object.fromEntries(METADATA_FIELDS.map(key => [key,
480
+ key === 'authors' ? { type: 'array', items: { type: 'string' } } : { type: 'string' },
481
+ ])), description: 'metadata:只填写要修改的事实;空字符串清空字段,authors=[] 清空作者。未知信息留空,不推测。' },
482
+ enrich: { type: 'boolean', description: 'metadata:true 按 DOI/arXiv/出版方补全空缺书目;默认预览,dryRun=false 才保存。不可与 fields 同用。' },
483
+ keep: { type: 'array', items: { type: 'string' }, description: 'metadata:这些字段判定为「保持原样」—— 记下来源值,来源记录不变时下次补全不再报冲突(不是永久忽略:来源值变了会重新报)。与 fields / enrich 互斥。' },
484
+ identifier: { type: 'string', description: 'metadata enrich:可指定核对过的 DOI、arXiv 编号或官方页面;省略使用已有标识,无标识时仅列题名检索候选。' },
485
+ injected: { type: 'boolean', description: 'list:只看当前会话选中注入的论文,支持 offset / limit 查询完整清单。' },
486
+ target: { type: 'string', enum: ['outline', 'index'], description: 'rebuild:重建 outline 或 index;index 始终覆盖整个库。' },
487
+ group: { type: 'string', description: 'group-hide / group-pin 的分组键:视图名(all/reading/unread/read/starred/unfiled)或 c:<集合名>。' },
488
+ trashed: { type: 'boolean', description: 'list 时 true 表示列回收站里的论文。' },
489
+ dir: { type: 'string', description: 'bind 的目标:论文所在文件夹的绝对路径,一行一个(可以是分类根目录,会往下扫)。rebind 则是要指过去的那一个文件夹。' },
490
+ from: { type: 'string', description: 'tag-rename 的旧标签;collection-merge / collection-move-items 的来源集合(短名或「父 / 子」全路径)。' },
491
+ to: { type: 'string', description: 'tag-rename 的新标签。' },
492
+ sourceCollection: { type: 'string', description: 'collection-merge / collection-move-items 的来源集合;与 from 二选一。' },
493
+ keepInSource: { type: 'boolean', description: 'collection-move-items:true = 只加入目标集合、不从来源移除(默认 false = 搬走)。' },
494
+ unfiled: { type: 'boolean', description: 'list 筛选:只看不属于任何集合的论文。' },
495
+ compact: { type: 'boolean', description: 'list 时只回 documentId / paper / status / tags / starred / collections(拿全库 id 去批量操作时用)。' },
496
+ trashItems: { type: 'boolean', description: 'collection-remove 时把集合里的论文一并移入回收站(默认 false = 只删集合,论文留着)。' },
497
+ dryRun: { type: 'boolean', description: 'bind:true 只预览;import、rebuild 与 metadata enrich:默认 true 只预览,false 执行。' },
498
+ unbound: { type: 'boolean', description: 'list 筛选:只看「没有可用源目录」的记录(未绑定,或绑过的目录已经不在磁盘上)。' },
499
+ limit: { type: 'number', description: 'list 每页篇数,默认 ' + DEFAULT_LIMIT + ',上限 ' + MAX_LIMIT + '。' },
500
+ offset: { type: 'number', description: 'list 的翻页偏移。' },
501
+ },
502
+ required: ['action'],
503
+ },
504
+ output: {
505
+ schema: OUTPUT_SCHEMA,
506
+ render: (_args, value) => [{ type: 'text', text: value.notice }],
507
+ },
508
+
509
+ async execute(args, exec) {
510
+ const action = textOf(args?.action).trim()
511
+ if (!ACTIONS.includes(action)) {
512
+ return fail(action, '不认识的 action。可用的是:' + ACTIONS.join('、') + '。')
513
+ }
514
+ if (action !== 'metadata' && (args?.enrich !== undefined || args?.identifier !== undefined)) return fail(action, 'enrich / identifier 只用于 metadata。')
515
+
516
+ let data
517
+ try {
518
+ data = await view(exec?.agent?.session?.id)
519
+ } catch (error) {
520
+ return fail(action, '读不到文献库:' + messageOf(error))
521
+ }
522
+ const library = data?.library ?? {}
523
+ const items = Array.isArray(data?.items) ? data.items : []
524
+
525
+ if (['import', 'styles', 'style-install', 'style-select'].includes(action)) {
526
+ if (typeof deps.run !== 'function') return fail(action, '这个宿主没有提供书目管理能力。')
527
+ const collection = args?.collection ? findCollection(library, args.collection) : undefined
528
+ if (args?.collection && !collection) return fail(action, '目标集合不存在或名称不唯一。')
529
+ try {
530
+ const result = await deps.run({ action, data: args?.data, format: args?.format, dryRun: args?.dryRun !== false,
531
+ style: args?.style, locale: args?.locale, collectionId: collection?.id })
532
+ const report = result.importReport
533
+ const catalog = result.styleCatalog ? { ...result.styleCatalog } : undefined
534
+ if (catalog) delete catalog.installed
535
+ return definedFields({ ok: result.ok !== false, action, notice: result.notice,
536
+ styleCatalog: catalog,
537
+ importReport: report ? { dryRun: report.dryRun, total: report.total, imported: report.imported, updated: report.updated, unchanged: report.unchanged } : undefined,
538
+ papers: report?.rows.slice(0, MAX_LIMIT).map(row => ({ paper: row.title || row.documentId, documentId: row.documentId, title: row.title })),
539
+ total: report?.total, failures: report?.failures.length ? report.failures.map(row => '第 ' + row.index + ' 条:' + row.error) : undefined })
540
+ } catch (error) { return fail(action, '书目操作失败:' + messageOf(error)) }
541
+ }
542
+
543
+ // ---- 读:不经过写路径 ----
544
+ if (action === 'list') {
545
+ if (args?.injected === true && !exec?.agent?.session?.id) return fail(action, '查询注入清单需要当前会话。')
546
+ const query = textOf(args?.query)
547
+ const status = textOf(args?.status)
548
+ if (status !== '' && !STATUSES.includes(status)) return fail(action, 'status 只能是 ' + STATUSES.join(' / ') + '。')
549
+ const collectionText = textOf(args?.collection)
550
+ const collection = collectionText === '' ? undefined : findCollection(library, collectionText)
551
+ if (collectionText !== '' && collection === undefined) {
552
+ return fail(action, '没有叫「' + collectionText + '」的集合。用 collections 动作看现有集合。')
553
+ }
554
+ const rows = selectPapers(items, {
555
+ query,
556
+ status,
557
+ tag: textOf(args?.tag),
558
+ collectionId: collection?.id ?? '',
559
+ starred: args?.starred === true,
560
+ trashed: args?.trashed === true,
561
+ includeTrashed: args?.injected === true && args?.trashed === undefined,
562
+ library,
563
+ })
564
+ // 反方向找漏:库里有、磁盘上没有。bind 从磁盘出发,看不见这一半。
565
+ const unbound = args?.unbound === true
566
+ const unfiled = args?.unfiled === true
567
+ // 未归档 = 不属于任何集合(与面板 unfiled 视图同一条判据:collectionsOf 的并集里没有它)。
568
+ const filed = unfiled ? new Set(model.collectionsOf(library).flatMap(row => row.documentIds ?? [])) : null
569
+ let shown = filed === null ? rows : rows.filter(entry => !filed.has(entry.documentId))
570
+ if (args?.injected === true) {
571
+ const selected = new Set(data?.injectedIds ?? [])
572
+ shown = shown.filter(entry => selected.has(entry.documentId))
573
+ }
574
+ if (unbound) shown = await missingSourceDirs(shown)
575
+ // 排序:默认用全局设置(面板上那个下拉),order 只在这一次调用里覆盖它。
576
+ // 置顶恒定在最前,与排序方式无关 —— 与面板的 librarySort 同一条规则。
577
+ const orderText = textOf(args?.order)
578
+ if (orderText !== '' && !SORT_MODES.includes(orderText)) {
579
+ return fail(action, 'order 只能是 ' + SORT_MODES.join(' / ') + '。')
580
+ }
581
+ const order = orderText !== '' ? orderText : (SORT_MODES.includes(library.sort) ? library.sort : SORT_MODES[0])
582
+ const ordered = sortEntries(shown, order)
583
+ const limit = clampLimit(args?.limit)
584
+ const offset = clampOffset(args?.offset)
585
+ const paths = collectionPathsOf(library)
586
+ const compact = args?.compact === true
587
+ const page = ordered.slice(offset, offset + limit).map(entry => compact
588
+ ? compactPaper(entry, paths)
589
+ : summarizePaper(entry, paths))
590
+ const filters = [
591
+ query === '' ? '' : '关键词「' + query + '」',
592
+ textOf(args?.tag) === '' ? '' : '标签「' + textOf(args?.tag) + '」',
593
+ status === '' ? '' : '状态 ' + status,
594
+ collectionText === '' ? '' : '集合「' + collectionText + '」',
595
+ args?.starred === true ? '只看星标' : '',
596
+ args?.trashed === true ? '回收站' : '',
597
+ unbound ? '只看没有可用源目录的' : '',
598
+ unfiled ? '只看不属于任何集合的' : '',
599
+ // 只有显式给了 order 才提排序:默认排序是全局设置,每次回执都念一遍是噪声。
600
+ orderText === '' ? '' : '按 ' + order + ' 排',
601
+ ].filter(Boolean).join('、')
602
+ const scope = filters === '' ? '' : '(' + filters + ')'
603
+ // 缺源目录分两种:从没绑过(不知道在哪)与绑过的目录已经不在磁盘上(可能被删/改名)。
604
+ // 归在一起看待时处置不同,所以两个数都要报。
605
+ const noDir = unbound ? shown.filter(entry => textOf(entry.sourceDir).trim() === '').length : 0
606
+ const staleDir = unbound ? shown.length - noDir : 0
607
+ return definedFields({
608
+ ok: true,
609
+ action,
610
+ notice: shown.length === 0
611
+ ? (unbound ? '每一条记录都有可用的源目录' + scope + '。'
612
+ : unfiled ? '每一条记录都归了集合' + scope + '。'
613
+ : '没有符合条件的论文' + scope + '。')
614
+ : '共 ' + shown.length + ' 篇' + scope
615
+ + (unbound ? '(未绑定 ' + noDir + ' 篇,目录已不存在 ' + staleDir + ' 篇)' : '')
616
+ + ',本页 ' + page.length + ' 篇' + (offset + page.length < shown.length ? ',还有更多(用 offset 翻页)。' : '。'),
617
+ papers: page,
618
+ total: shown.length,
619
+ offset,
620
+ limit,
621
+ order,
622
+ })
623
+ }
624
+
625
+ // ---- 全局标签视图:全库所有标签 + 每个标签多少篇 ----
626
+ // 纯读,不经过写路径。标签分叉(事实 / Fact / 事实类)只有这里能看见。
627
+ if (action === 'tags') {
628
+ const counts = new Map()
629
+ for (const entry of items) {
630
+ if ((entry.item ?? {}).trashed === true) continue
631
+ for (const tag of Array.isArray(entry.item?.tags) ? entry.item.tags : []) {
632
+ const name = textOf(tag).trim()
633
+ if (name === '') continue
634
+ // 大小写不敏感地合并计数(与 tag 的去重口径一致),但显示保留首次写法。
635
+ const key = name.toLowerCase()
636
+ const row = counts.get(key)
637
+ if (row === undefined) counts.set(key, { tag: name, count: 1 })
638
+ else row.count += 1
639
+ }
640
+ }
641
+ const rows = [...counts.values()].sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag))
642
+ return definedFields({
643
+ ok: true,
644
+ action,
645
+ notice: rows.length === 0
646
+ ? '全库还没有任何标签。'
647
+ : '共 ' + rows.length + ' 个标签,覆盖 ' + rows.reduce((sum, row) => sum + row.count, 0) + ' 次标注。'
648
+ + (rows.some(row => row.count === 1) ? ' 只出现一次的标签最容易分叉,改名/合并前先看一眼。' : ''),
649
+ tags: rows.length > 0 ? rows : undefined,
650
+ })
651
+ }
652
+
653
+ // ---- 全库改名 / 合并标签:宿主侧走 libraryService 的 tags-rename(与面板同一个实现)----
654
+ if (action === 'tag-rename') {
655
+ const from = textOf(args?.from).trim() || textOf(args?.tag).trim()
656
+ const to = textOf(args?.to).trim() || textOf(args?.name).trim()
657
+ if (from === '') return fail(action, 'tag-rename 需要 from:要改掉的旧标签。')
658
+ if (to === '') return fail(action, 'tag-rename 需要 to:改成什么。')
659
+ if (typeof deps.run !== 'function') return fail(action, '这个宿主没有提供文献库写入能力。')
660
+ let outcome
661
+ try {
662
+ outcome = await deps.run({ action, sessionId: exec?.agent?.session?.id, tag: from, next: to })
663
+ } catch (error) {
664
+ return fail(action, '改名失败:' + messageOf(error))
665
+ }
666
+ const result = outcome ?? {}
667
+ const changed = Array.isArray(result.succeeded) ? result.succeeded.length : 0
668
+ const bad = Array.isArray(result.failures) ? result.failures.map(row => (typeof row === 'string' ? row : textOf(row?.documentId) + ':' + textOf(row?.error))) : []
669
+ // 宿主已经把「已把 X 改成 Y:N 篇」写好了;工具侧不重拼一遍,免得两处口径分叉。
670
+ return definedFields({
671
+ ok: result.ok !== false && bad.length === 0,
672
+ action,
673
+ notice: '把「' + from + '」改成「' + to + '」:' + changed + ' 篇'
674
+ + (bad.length > 0 ? ',' + bad.length + ' 篇失败' : '') + '。',
675
+ failures: bad.length > 0 ? bad : undefined,
676
+ })
677
+ }
678
+
679
+ if (action === 'collections') {
680
+ const rows = model.tree(library).map(row => definedFields({
681
+ name: row.name,
682
+ path: model.path(library, row.id),
683
+ parent: row.parentId === null || row.parentId === undefined
684
+ ? undefined
685
+ : (model.collectionsOf(library).find(parent => parent.id === row.parentId)?.name ?? ''),
686
+ count: (row.documentIds ?? []).length,
687
+ }))
688
+ const total = model.collectionsOf(library).length
689
+ return definedFields({
690
+ ok: true,
691
+ action,
692
+ notice: total === 0 ? '还没有任何集合。' : '共 ' + total + ' 个集合。',
693
+ collections: rows,
694
+ })
695
+ }
696
+
697
+ // ---- 目录 → 记录:把工作区里的论文文件夹绑回库记录 ----
698
+ // 反方向(记录 → 目录)由 summarizePaper 的 sourceDir 承担。这个动作只读用户目录、
699
+ // 只写库记录:不解析、不旁挂、不改用户文件里的任何一个字节。
700
+ if (action === 'bind') {
701
+ const dir = textOf(args?.dir).trim()
702
+ if (dir === '') return fail(action, 'bind 需要 dir:要绑定的绝对文件夹路径,一行一个。')
703
+ if (typeof deps.run !== 'function') return fail(action, '这个宿主没有提供文献库写入能力。')
704
+ const dryRun = args?.dryRun === true
705
+ let outcome
706
+ try {
707
+ outcome = await deps.run({ action: 'bind', sessionId: exec?.agent?.session?.id, dir, dryRun })
708
+ } catch (error) {
709
+ return fail(action, '绑定失败:' + messageOf(error))
710
+ }
711
+ const result = outcome ?? {}
712
+ const bound = (Array.isArray(result.bound) ? result.bound : []).map(row => definedFields({
713
+ paper: textOf(row?.pdfName) || textOf(row?.documentId),
714
+ documentId: textOf(row?.documentId),
715
+ sourceDir: textOf(row?.sourceDir) || undefined,
716
+ })).filter(row => row.documentId !== '')
717
+ const unknown = (Array.isArray(result.unknown) ? result.unknown : []).map(String)
718
+ const extra = (Array.isArray(result.failures) ? result.failures : []).map(String)
719
+ const already = Number(result.already) || 0
720
+ const scanned = Number(result.scanned) || 0
721
+ const unboundCount = Number(result.unboundCount)
722
+ // 绑完再报一次「还剩多少条没有源目录」:这一句是 bind 唯一能看见反方向的地方。
723
+ const unboundNote = !dryRun && Number.isFinite(unboundCount) && unboundCount > 0
724
+ ? '另有 ' + unboundCount + ' 条记录没有源目录(list 加 unbound: true 看是哪几条)。'
725
+ : ''
726
+ return definedFields({
727
+ ok: result.ok !== false,
728
+ action,
729
+ notice: (dryRun ? '(预演,未写记录)' : '')
730
+ + '扫描 ' + scanned + ' 个 PDF:' + (dryRun ? '会绑定 ' : '新绑定 ') + bound.length + ' 篇'
731
+ + (already > 0 ? ',已是最新 ' + already + ' 篇' : '')
732
+ + (unknown.length > 0 ? ',库里没有 ' + unknown.length + ' 个(先入库再绑)' : '')
733
+ + '。' + unboundNote,
734
+ papers: bound.length > 0 ? bound : undefined,
735
+ failures: [...unknown, ...extra].length > 0 ? [...unknown, ...extra] : undefined,
736
+ })
737
+ }
738
+
739
+ // ---- 以下动作要先定位到论文 ----
740
+ const single = textOf(args?.paper)
741
+ const multiple = Array.isArray(args?.papers) ? args.papers : []
742
+ const wantsPapers = single !== '' || multiple.length > 0
743
+ const NEEDS_PAPERS = new Set(['get', 'metadata', 'file', 'unfile', 'star', 'pin', 'status', 'tag', 'untag',
744
+ 'trash', 'restore', 'inject', 'uninject', 'citation', 'notes', 'html', 'rename',
745
+ 'rebind', 'unbind', 'export'])
746
+ if (NEEDS_PAPERS.has(action) && !wantsPapers) {
747
+ return fail(action, action + ' 需要 paper 或 papers:写 64 位 id、PDF 文件名、Markdown 路径或标题片段都行。')
748
+ }
749
+ if (NEEDS_COLLECTION.has(action) && textOf(args?.collection) === '') {
750
+ return fail(action, action + ' 需要 collection(集合名或「父 / 子」全路径)。')
751
+ }
752
+ if (NEEDS_NAME.has(action) && textOf(args?.name) === '') {
753
+ return fail(action, '需要 name。')
754
+ }
755
+ if (NEEDS_TAG.has(action) && textOf(args?.tag) === '') {
756
+ return fail(action, action + ' 需要 tag:要加/删的那个标签名。')
757
+ }
758
+
759
+ let ids = []
760
+ const failures = []
761
+ if (wantsPapers) {
762
+ const resolved = resolveIds([...multiple, single], items)
763
+ ids = resolved.ids
764
+ failures.push(...resolved.failures)
765
+ if (ids.length === 0) {
766
+ return definedFields({ ok: false, action, notice: failures[0] ?? '没有找到要操作的论文。', failures })
767
+ }
768
+ if (['get', 'metadata', 'rename', 'rebind', 'unbind', 'citation', 'html', 'notes'].includes(action)
769
+ && (ids.length !== 1 || failures.length > 0)) return fail(action, '这个动作一次处理一篇论文,所有引用都必须成功指向同一篇。请唯一指定 paper。' + (failures[0] ?? ''))
770
+ }
771
+
772
+ // `get` 是纯读:直接回摘要,不经过宿主写路径(也就不需要 `run`)。
773
+ if (action === 'rebuild' && !['outline', 'index'].includes(args?.target)) return fail(action, 'rebuild 需要 target=outline / index。')
774
+ if (action === 'metadata') {
775
+ if (ids.length !== 1 || failures.length > 0) return fail(action, 'metadata 必须唯一指定一篇论文。')
776
+ if (args?.enrich === true) {
777
+ if (args.fields !== undefined) return fail(action, 'enrich 与 fields 不可同时使用。')
778
+ if (args?.keep !== undefined) return fail(action, 'enrich 与 keep 不可同时使用。')
779
+ } else if (args?.keep !== undefined) {
780
+ if (args.fields !== undefined) return fail(action, 'keep 与 fields 不可同时使用。')
781
+ if (!Array.isArray(args.keep) || args.keep.length === 0 || args.keep.some(key => typeof key !== 'string' || key === '')) {
782
+ return fail(action, 'keep 必须是非空的书目字段名数组。')
783
+ }
784
+ if (args.keep.some(key => !METADATA_FIELDS.includes(key))) return fail(action, 'keep 里有不支持的书目字段名。')
785
+ } else {
786
+ if (args?.identifier !== undefined) return fail(action, 'identifier 需要 enrich=true。')
787
+ try { validateMetadata(args?.fields) } catch (error) { return fail(action, messageOf(error)) }
788
+ }
789
+ }
790
+ if (action === 'get') {
791
+ const entry = items.find(row => row.documentId === ids[0])
792
+ if (entry === undefined) return fail(action, '这篇论文已经不在文献库里了。')
793
+ const paper = summarizePaper(entry, collectionPathsOf(library))
794
+ // 🔴 get 与 citation 必须是**同一套**值。citation 会从文件名 / 正文 / 磁盘上的规范名
795
+ // 补齐作者与年份,而 get 只回 state.json 里存的那两个键 —— 于是同一篇论文,
796
+ // 审计看到「无作者」,导出却写着作者。差的不是数据,是两条读取路径各算了一遍。
797
+ // 宿主给了 metadataOf 就用它 —— 那与 citation 是**同一个函数**,两边不可能再漂。
798
+ // 没给(单测直接构造工具)时退回「记录 + 文件名」的较弱降级。
799
+ const derived = typeof deps.metadataOf === 'function'
800
+ ? await deps.metadataOf(entry.documentId)
801
+ : await citationMetadataWithDisk(entry)
802
+ if (derived !== undefined && derived !== null) {
803
+ if (typeof derived.title === 'string') paper.title = derived.title
804
+ if (Array.isArray(derived.authors) && derived.authors.length > 0) paper.authors = derived.authors.map(String)
805
+ if (derived.year !== '') paper.year = derived.year
806
+ // 名单不完整时必须说清:只报首位而不写「等」,等于断言这是单作者论文(比没有更糟)。
807
+ if (derived.etal === true) paper.authorsEtal = true
808
+ if (derived.bibliography) paper.bibliography = derived.bibliography
809
+ if (Object.keys(derived.metadataSources ?? {}).length) paper.metadataSources = metadataSourceRows(derived.metadataSources)
810
+ for (const field of derived.clearedMetadata ?? []) delete paper[field]
811
+ }
812
+ // 回收站里的记录也查得到(它是用户数据,不该藏起来),但要说清自己在看什么 ——
813
+ // 否则「list 里没有、get 里有」看起来像两处不一致。
814
+ const trashed = (entry.item ?? {}).trashed === true
815
+ const filled = []
816
+ if (derived?.filledAuthors) filled.push('作者')
817
+ if (derived?.filledYear) filled.push('年份')
818
+ const base = trashed ? '论文信息如下。这篇在回收站里(可还原)。' : '论文信息如下。'
819
+ const suffix = filled.length === 0 ? '' : `(${filled.join('、')}是按文件名或正文补出来的,与 citation 一致。)`
820
+ return definedFields({
821
+ ok: true,
822
+ action,
823
+ notice: base + suffix,
824
+ papers: [paper],
825
+ failures: failures.length > 0 ? failures : undefined,
826
+ })
827
+ }
828
+
829
+ // 源目录的显式改写:只动记录上的一个字段。回执必须按**这次的结果**给 sourceDir ——
830
+ // items 是这次调用开始时的快照,改写之后它还带着旧值。
831
+ if (action === 'rebind' || action === 'unbind') {
832
+ const dir = textOf(args?.dir).trim()
833
+ if (action === 'rebind' && dir === '') return fail(action, 'rebind 需要 dir:这篇论文所在文件夹的绝对路径。')
834
+ if (typeof deps.run !== 'function') return fail(action, '这个宿主没有提供文献库写入能力。')
835
+ let outcome
836
+ try {
837
+ outcome = await deps.run({ action, sessionId: exec?.agent?.session?.id, documentIds: ids, documentId: ids[0], dir })
838
+ } catch (error) {
839
+ return fail(action, (action === 'rebind' ? '改指向失败:' : '解绑失败:') + messageOf(error))
840
+ }
841
+ const result = outcome ?? {}
842
+ const entry = items.find(row => row.documentId === ids[0]) ?? { documentId: ids[0] }
843
+ // 解绑就是清空;rebind 失败时保留原值(宿主没回 sourceDir 不代表它被清掉了)。
844
+ const nextDir = action === 'unbind' ? '' : (textOf(result.sourceDir) || textOf(entry.sourceDir))
845
+ const paper = summarizePaper({ ...entry, sourceDir: nextDir, sourcePdfPath: textOf(result.sourcePdfPath) }, collectionPathsOf(library))
846
+ const all = [...failures, ...(Array.isArray(result.failures) ? result.failures.map(String) : [])]
847
+ return definedFields({
848
+ ok: result.ok !== false,
849
+ action,
850
+ notice: textOf(result.notice) || (action === 'rebind' ? '已改指向。' : '已解绑。'),
851
+ papers: [paper],
852
+ failures: all.length > 0 ? all : undefined,
853
+ })
854
+ }
855
+
856
+ if (GROUP_ACTIONS.has(action) && textOf(args?.group) === '') {
857
+ return fail(action, '需要 group:视图名(all/reading/unread/read/starred/unfiled)或 c:<集合名>。')
858
+ }
859
+ if (action === 'sort' && !SORT_MODES.includes(textOf(args?.mode))) {
860
+ return fail(action, 'mode 只能是 ' + SORT_MODES.join(' / ') + '。')
861
+ }
862
+ if (action === 'status' && !STATUSES.includes(textOf(args?.status))) {
863
+ return fail(action, 'status 只能是 ' + STATUSES.join(' / ') + '。')
864
+ }
865
+ if (action === 'citation' && !CITATION_FORMATS.includes(textOf(args?.format) || 'bibtex')) {
866
+ return fail(action, 'format 只能是 bibtex / apa / gb-t-7714 / ris / csl-json / csl。')
867
+ }
868
+
869
+ // 集合相关的动作在这里就把名字折成 id:宿主侧只认 id,不必再解析一遍名字。
870
+ let collectionId
871
+ let parentId
872
+ let sourceCollectionId
873
+ if (action === 'collection-merge' || action === 'collection-move-items') {
874
+ const from = textOf(args?.from) !== '' ? textOf(args?.from) : textOf(args?.sourceCollection)
875
+ if (from.trim() === '') return fail(action, action + ' 需要 from(或 sourceCollection):来源集合名。')
876
+ const row = findCollection(library, from)
877
+ if (row === undefined) return fail(action, '没有叫「' + from + '」的集合。用 collections 动作看现有集合。')
878
+ sourceCollectionId = row.id
879
+ }
880
+ if (NEEDS_COLLECTION.has(action) || action === 'collection-add') {
881
+ if (textOf(args?.collection) !== '') {
882
+ const row = findCollection(library, textOf(args?.collection))
883
+ if (row === undefined) return fail(action, '没有叫「' + textOf(args?.collection) + '」的集合。用 collections 动作看现有集合。')
884
+ collectionId = row.id
885
+ }
886
+ if (typeof args?.parent === 'string' && args.parent.trim() !== '') {
887
+ const parent = findCollection(library, args.parent)
888
+ if (parent === undefined) return fail(action, '没有叫「' + args.parent + '」的父集合。')
889
+ parentId = parent.id
890
+ }
891
+ }
892
+
893
+ const request = {
894
+ action,
895
+ sessionId: exec?.agent?.session?.id,
896
+ collectionId,
897
+ parentId,
898
+ sourceCollectionId: sourceCollectionId,
899
+ keepInSource: args?.keepInSource === true,
900
+ trashItems: args?.trashItems === true,
901
+ documentIds: ids,
902
+ documentId: ids[0],
903
+ name: textOf(args?.name),
904
+ collection: textOf(args?.collection),
905
+ parent: typeof args?.parent === 'string' ? args.parent : undefined,
906
+ status: textOf(args?.status),
907
+ tag: textOf(args?.tag),
908
+ starred: args?.starred !== false,
909
+ pinned: args?.pinned !== false,
910
+ hidden: args?.hidden !== false,
911
+ mode: textOf(args?.mode),
912
+ format: textOf(args?.format) || 'bibtex',
913
+ style: args?.style,
914
+ locale: args?.locale,
915
+ citationMode: args?.citationMode,
916
+ fields: args?.fields,
917
+ enrich: args?.enrich === true,
918
+ keep: args?.keep,
919
+ identifier: args?.identifier,
920
+ target: args?.target,
921
+ dryRun: args?.dryRun !== false,
922
+ group: textOf(args?.group),
923
+ trashed: args?.trashed === true,
924
+ }
925
+
926
+ if (typeof deps.run !== 'function') return fail(action, '这个宿主没有提供文献库写入能力。')
927
+ let outcome
928
+ try {
929
+ outcome = await deps.run(request)
930
+ } catch (error) {
931
+ const code = action === 'metadata' && ['METADATA_TIMEOUT', 'METADATA_NETWORK', 'METADATA_TLS'].includes(error?.code) ? error.code : undefined
932
+ return definedFields({ ok: false, action, code, notice: ACTION_TEXT[action] + '失败:' + messageOf(error), failures: failures.length > 0 ? failures : undefined })
933
+ }
934
+
935
+ const result = outcome ?? {}
936
+ const extra = Array.isArray(result.failures) ? result.failures : []
937
+ const all = [...failures, ...extra]
938
+ // 宿主把「执行之后的那几条」直接带回来,就不再整库重读一遍
939
+ // (过去每次写操作读两次全库:写前 view + 写后回读)。
940
+ const updated = Array.isArray(result.items) ? result.items : []
941
+ const finalLibrary = result.library !== null && typeof result.library === 'object' ? result.library : library
942
+ let finalItems = items
943
+ if (updated.length > 0) {
944
+ const byId = new Map(items.map(entry => [entry.documentId, entry]))
945
+ for (const row of updated) {
946
+ const id = textOf(row?.documentId)
947
+ if (id === '') continue
948
+ byId.set(id, { ...(byId.get(id) ?? { documentId: id }), item: row.item })
949
+ }
950
+ finalItems = [...byId.values()]
951
+ }
952
+ let papers
953
+ if (ids.length > 0) {
954
+ const byId = new Map(finalItems.map(entry => [entry.documentId, entry]))
955
+ const paths = collectionPathsOf(finalLibrary)
956
+ papers = ids.map(id => byId.get(id)).filter(Boolean).map(entry => summarizePaper(entry, paths))
957
+ }
958
+ if (action === 'metadata' && papers?.length === 1 && result.metadata) {
959
+ const metadata = result.metadata
960
+ for (const field of ['title', 'authors', 'year', 'bibliography']) if (metadata[field] !== undefined) papers[0][field] = metadata[field]
961
+ if (metadata.etal) papers[0].authorsEtal = true
962
+ else delete papers[0].authorsEtal
963
+ for (const field of metadata.clearedMetadata ?? []) if (['title', 'authors', 'year'].includes(field)) delete papers[0][field]
964
+ if (Object.keys(metadata.metadataSources ?? {}).length) papers[0].metadataSources = metadataSourceRows(metadata.metadataSources)
965
+ }
966
+ return definedFields({
967
+ ok: result.ok !== false && all.length === 0,
968
+ action,
969
+ notice: textOf(result.notice) || fallbackNotice(action, { ids, papers, result, keepInSource: args?.keepInSource === true }),
970
+ papers: papers !== undefined && papers.length > 0 ? papers : undefined,
971
+ citation: textOf(result.citation) || undefined,
972
+ path: textOf(result.path) || undefined,
973
+ url: textOf(result.url) || undefined,
974
+ bibliography: result.bibliography,
975
+ enrichment: result.enrichment,
976
+ maintenance: result.maintenance,
977
+ code: result.code,
978
+ failures: all.length > 0 ? all : undefined,
979
+ })
980
+ },
981
+ })
982
+ }