@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.
- package/LICENSE +21 -0
- package/README.md +150 -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 +2762 -0
- package/lib/client-parts/02-author-year.js +95 -0
- package/lib/client.js +10381 -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 +308 -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 +261 -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
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 表格层:LaTeX 的 tabular 家族 → HTML 表格。
|
|
3
|
+
*
|
|
4
|
+
* 为什么输出 HTML 而不是 GFM:抽样 48 张表里有 16 张超过 7 列,GFM 表格没有横向滚动,
|
|
5
|
+
* 转过去就是一堆换行的乱码。HTML 表格在阅读器里能横向滚动,也能保留合并单元格 ——
|
|
6
|
+
* 而合并单元格在 MinerU 那一侧正是最容易塌的东西(677 张表里 295 张含 rowspan/colspan)。
|
|
7
|
+
*
|
|
8
|
+
* 纯函数:无 IO、无时钟。
|
|
9
|
+
*/
|
|
10
|
+
import { readGroup, skipSpaces } from './tex-prepare.js'
|
|
11
|
+
import { inlineText } from './tex-inline.js'
|
|
12
|
+
|
|
13
|
+
const BACKSLASH = '\\'
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 列格式串 → 列数。
|
|
17
|
+
*
|
|
18
|
+
* 只数「产出列」的字母:l / c / r / X / p{..} / m{..} / b{..}。
|
|
19
|
+
* 不数对齐修饰(竖线、at 表达式、大于小于号修饰)—— 它们不占列。
|
|
20
|
+
* 星号重复写法(星号 + 个数 + 一个组)展开成对应列数。
|
|
21
|
+
*/
|
|
22
|
+
export function columnCountOf(spec) {
|
|
23
|
+
const source = typeof spec === 'string' ? spec : ''
|
|
24
|
+
let count = 0
|
|
25
|
+
let index = 0
|
|
26
|
+
while (index < source.length) {
|
|
27
|
+
const char = source[index]
|
|
28
|
+
if (char === BACKSLASH) { index += 1; continue }
|
|
29
|
+
if (/[lcrX]/.test(char)) { count += 1; index += 1; continue }
|
|
30
|
+
if (/[pmb]/.test(char)) {
|
|
31
|
+
const group = readGroup(source, skipSpaces(source, index + 1))
|
|
32
|
+
if (group !== null) { count += 1; index = group.end; continue }
|
|
33
|
+
index += 1
|
|
34
|
+
continue
|
|
35
|
+
}
|
|
36
|
+
if (char === '*') {
|
|
37
|
+
const countGroup = readGroup(source, skipSpaces(source, index + 1))
|
|
38
|
+
if (countGroup === null) { index += 1; continue }
|
|
39
|
+
const inner = readGroup(source, skipSpaces(source, countGroup.end))
|
|
40
|
+
const times = Number.parseInt(countGroup.content, 10)
|
|
41
|
+
if (inner !== null && Number.isInteger(times) && times > 0) {
|
|
42
|
+
count += times * Math.max(1, columnCountOf(inner.content))
|
|
43
|
+
index = inner.end
|
|
44
|
+
continue
|
|
45
|
+
}
|
|
46
|
+
index = countGroup.end
|
|
47
|
+
continue
|
|
48
|
+
}
|
|
49
|
+
index += 1
|
|
50
|
+
}
|
|
51
|
+
return count
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 去掉纯排版命令:横线、间距、列宽设置。它们不产出内容,留着会变成正文里的碎片。 */
|
|
55
|
+
/** 去掉纯排版命令:横线、间距、列宽设置。它们不产出内容,留着会变成正文里的碎片。 */
|
|
56
|
+
function stripRules(body) {
|
|
57
|
+
return String(body ?? '')
|
|
58
|
+
.replace(/\\hline/g, ' ')
|
|
59
|
+
.replace(/\\toprule/g, ' ')
|
|
60
|
+
.replace(/\\midrule/g, ' ')
|
|
61
|
+
.replace(/\\bottomrule/g, ' ')
|
|
62
|
+
.replace(/\\cline\s*\{[^{}]*\}/g, ' ')
|
|
63
|
+
.replace(/\\cmidrule(?:\([^)]*\))?\s*\{[^{}]*\}/g, ' ')
|
|
64
|
+
.replace(/\\addlinespace(?:\[[^\]]*\])?/g, ' ')
|
|
65
|
+
.replace(/\\rule\s*\{[^{}]*\}\s*\{[^{}]*\}/g, ' ')
|
|
66
|
+
.replace(/\\specialrule\s*\{[^{}]*\}\s*\{[^{}]*\}\s*\{[^{}]*\}/g, ' ')
|
|
67
|
+
.replace(/\\(?:hspace|vspace)\*?\s*\{[^{}]*\}/g, ' ')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* 按顶层分隔符切分。
|
|
72
|
+
*
|
|
73
|
+
* 必须跟踪花括号深度与反斜杠转义:单元格里常见「合并两列、内容里再带与号」的写法,
|
|
74
|
+
* 朴素地按与号切会把一个单元格切成三个。
|
|
75
|
+
*/
|
|
76
|
+
function splitTopLevel(text, separator) {
|
|
77
|
+
const source = typeof text === 'string' ? text : ''
|
|
78
|
+
const parts = []
|
|
79
|
+
let depth = 0
|
|
80
|
+
let current = ''
|
|
81
|
+
for (let index = 0; index < source.length; index += 1) {
|
|
82
|
+
const char = source[index]
|
|
83
|
+
if (char === BACKSLASH) {
|
|
84
|
+
const next = source[index + 1]
|
|
85
|
+
if (depth === 0 && separator === BACKSLASH + BACKSLASH && next === BACKSLASH) {
|
|
86
|
+
parts.push(current)
|
|
87
|
+
current = ''
|
|
88
|
+
index += 1
|
|
89
|
+
// 跳过行尾的可选垂直间距与多余空白。
|
|
90
|
+
let cursor = index + 1
|
|
91
|
+
if (source[cursor] === '[') {
|
|
92
|
+
while (cursor < source.length && source[cursor] !== ']') cursor += 1
|
|
93
|
+
cursor += 1
|
|
94
|
+
} else {
|
|
95
|
+
while (source[cursor] === ' ') cursor += 1
|
|
96
|
+
}
|
|
97
|
+
index = cursor - 1
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
current += char
|
|
101
|
+
if (next !== undefined) { current += next; index += 1 }
|
|
102
|
+
continue
|
|
103
|
+
}
|
|
104
|
+
if (depth === 0 && separator === '&' && char === '&') {
|
|
105
|
+
parts.push(current)
|
|
106
|
+
current = ''
|
|
107
|
+
continue
|
|
108
|
+
}
|
|
109
|
+
if (char === '{') depth += 1
|
|
110
|
+
else if (char === '}') depth = Math.max(0, depth - 1)
|
|
111
|
+
current += char
|
|
112
|
+
}
|
|
113
|
+
parts.push(current)
|
|
114
|
+
return parts
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** 取一个合并命令的跨度与内容,返回 { span, content } 或 null。 */
|
|
118
|
+
function spanCommandOf(cell, command) {
|
|
119
|
+
const at = cell.indexOf(BACKSLASH + command)
|
|
120
|
+
if (at === -1) return null
|
|
121
|
+
let cursor = at + command.length + 1
|
|
122
|
+
const countGroup = readGroup(cell, skipSpaces(cell, cursor))
|
|
123
|
+
if (countGroup === null) return null
|
|
124
|
+
cursor = countGroup.end
|
|
125
|
+
const specGroup = readGroup(cell, skipSpaces(cell, cursor))
|
|
126
|
+
if (specGroup === null) return null
|
|
127
|
+
cursor = specGroup.end
|
|
128
|
+
const body = readGroup(cell, skipSpaces(cell, cursor))
|
|
129
|
+
if (body === null) return null
|
|
130
|
+
const span = Number.parseInt(countGroup.content, 10)
|
|
131
|
+
return { span: Number.isInteger(span) && span > 0 ? span : 1, content: body.content }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** HTML 转义:inlineText 产出的是纯文本,放进标签里必须转义。 */
|
|
135
|
+
function escapeHtml(text) {
|
|
136
|
+
return String(text ?? '')
|
|
137
|
+
.replace(/&/g, '&')
|
|
138
|
+
.replace(/</g, '<')
|
|
139
|
+
.replace(/>/g, '>')
|
|
140
|
+
.replace(/"/g, '"')
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 兜底:单元格里残留的颜色表达式与裸尺寸。
|
|
145
|
+
*
|
|
146
|
+
* 实测 `gray!600.5pt1pt1ptblack Evaluation Granularity` —— `\cellcolor{gray!60}` 与一串
|
|
147
|
+
* `\rule` 尺寸没被命令层吃掉(有的藏在 `>{\columncolor{…}}` 这类列修饰里,切分时就已成碎片)。
|
|
148
|
+
* 颜色语法 `word!数字` 在正文里没有别的含义;裸尺寸只在表格里清 —— 正文里 `≤0.5pt` 是
|
|
149
|
+
* 真实读数,不能碰。
|
|
150
|
+
*/
|
|
151
|
+
function stripTypesetting(text) {
|
|
152
|
+
return String(text ?? '')
|
|
153
|
+
.replace(/[a-z]+!\d+(?:![a-z]+)?/gi, ' ')
|
|
154
|
+
.replace(/\b\d+(?:\.\d+)?(?:pt|em|ex|bp)\b/g, ' ')
|
|
155
|
+
.replace(/\s+/g, ' ')
|
|
156
|
+
.trim()
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** 解析单个单元格:合并与内容。 */
|
|
160
|
+
function cellOf(raw) {
|
|
161
|
+
let text = String(raw ?? '')
|
|
162
|
+
let colspan = 1
|
|
163
|
+
let rowspan = 1
|
|
164
|
+
const multi = spanCommandOf(text, 'multicolumn')
|
|
165
|
+
if (multi !== null) { colspan = multi.span; text = multi.content }
|
|
166
|
+
const row = spanCommandOf(text, 'multirow')
|
|
167
|
+
if (row !== null) { rowspan = row.span; text = row.content }
|
|
168
|
+
return { text: stripTypesetting(inlineText(text)), colspan, rowspan }
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* tabular 家族 → HTML。
|
|
173
|
+
*
|
|
174
|
+
* @param {unknown} body tabular 环境内部的文本(不含环境起止标记)
|
|
175
|
+
* @param {{columnSpec?: string}} [options] 列格式串(用来定列数;缺省按最宽的一行算)
|
|
176
|
+
* @returns {{html: string, rows: number, columns: number}}
|
|
177
|
+
*/
|
|
178
|
+
export function tabularToHtml(body, options = {}) {
|
|
179
|
+
const source = stripRules(body)
|
|
180
|
+
const rowTexts = splitTopLevel(source, BACKSLASH + BACKSLASH)
|
|
181
|
+
.map(row => row.trim())
|
|
182
|
+
.filter(row => row !== '')
|
|
183
|
+
const rows = []
|
|
184
|
+
let widest = 0
|
|
185
|
+
for (const rowText of rowTexts) {
|
|
186
|
+
const cells = splitTopLevel(rowText, '&').map(cellOf)
|
|
187
|
+
let width = 0
|
|
188
|
+
for (const cell of cells) width += cell.colspan
|
|
189
|
+
if (width > widest) widest = width
|
|
190
|
+
rows.push(cells)
|
|
191
|
+
}
|
|
192
|
+
const declared = columnCountOf(options.columnSpec)
|
|
193
|
+
const columns = declared > 0 ? declared : widest
|
|
194
|
+
if (rows.length === 0 || columns === 0) return { html: '', rows: 0, columns: 0 }
|
|
195
|
+
|
|
196
|
+
const html = ['<table>']
|
|
197
|
+
for (const cells of rows) {
|
|
198
|
+
html.push('<tr>')
|
|
199
|
+
for (const cell of cells) {
|
|
200
|
+
const attrs = [
|
|
201
|
+
cell.colspan > 1 ? ' colspan="' + cell.colspan + '"' : '',
|
|
202
|
+
cell.rowspan > 1 ? ' rowspan="' + cell.rowspan + '"' : '',
|
|
203
|
+
].join('')
|
|
204
|
+
html.push('<td' + attrs + '>' + escapeHtml(cell.text) + '</td>')
|
|
205
|
+
}
|
|
206
|
+
html.push('</tr>')
|
|
207
|
+
}
|
|
208
|
+
html.push('</table>')
|
|
209
|
+
return { html: html.join(''), rows: rows.length, columns }
|
|
210
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 文本相似度:对齐与合并两处共用的一套口径。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独成模块而不是各写一份:对齐拿它判断「源码这一块是不是落在这一段 PDF 文本上」,
|
|
5
|
+
* 合并拿它判断「源码这一块和 MinerU 那一块是不是同一块」。两处若用不同口径,会出现
|
|
6
|
+
* 「对齐说匹配、合并说不是」的自相矛盾,而阈值就是按这一套口径试出来的。
|
|
7
|
+
*
|
|
8
|
+
* 纯函数,无 IO 无时钟。
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 词元化。
|
|
13
|
+
*
|
|
14
|
+
* 三条口径,各有实测理由:
|
|
15
|
+
* - **小写折叠**:LaTeX 源码与 PDF 文本层的大小写差异只来自排版(首字母大写、小型大写),
|
|
16
|
+
* 不是内容差异。
|
|
17
|
+
* - **拉丁词按空白与标点切**:PDF 文本层会把连字符断词写成两个词、把公式周围插进空格,
|
|
18
|
+
* 逐字符比较会被这些噪声淹没。
|
|
19
|
+
* - **CJK 按字符二元组**:中文没有空格分词,按单字切会让「的」「是」这类高频字主导相似度;
|
|
20
|
+
* 二元组既保留了局部顺序,又不需要词典。
|
|
21
|
+
*
|
|
22
|
+
* 数学符号(\alpha、_、^)留在词元里:公式块与正文块的相似度本就该由这些符号决出。
|
|
23
|
+
*/
|
|
24
|
+
export function tokenize(text) {
|
|
25
|
+
const source = typeof text === 'string' ? text : ''
|
|
26
|
+
if (source === '') return []
|
|
27
|
+
const tokens = []
|
|
28
|
+
const lower = source.toLowerCase()
|
|
29
|
+
// CJK 段单独扫:拉丁词元正则的 \w 不含汉字,混在一次扫描里会把中英混排的段落切碎。
|
|
30
|
+
const cjk = /[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]+/g
|
|
31
|
+
const rest = lower.replace(cjk, match => {
|
|
32
|
+
// 二元组;单字段(长度 1)退化成单字,否则整段中文会一个词元都不产。
|
|
33
|
+
for (let index = 0; index < match.length; index += 1) {
|
|
34
|
+
tokens.push(match.length === 1 ? match[index] : match.slice(index, index + 2))
|
|
35
|
+
}
|
|
36
|
+
return ' '
|
|
37
|
+
})
|
|
38
|
+
for (const word of rest.split(/[^a-z0-9\\$_{}^]+/)) {
|
|
39
|
+
if (word !== '') tokens.push(word)
|
|
40
|
+
}
|
|
41
|
+
return tokens
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 词元集合的 Jaccard 相似度:交集 / 并集。空集对空集记 1(两块都没内容,形式相同)。
|
|
46
|
+
*
|
|
47
|
+
* 用集合而不是多重集:PDF 文本层把同一句话说两遍的情况极少,而重复词元(the)在多重集里
|
|
48
|
+
* 会被放大,反而让两块无关正文因为共享虚词而显得相似。
|
|
49
|
+
*/
|
|
50
|
+
export function similarity(left, right) {
|
|
51
|
+
const a = left instanceof Set ? left : new Set(tokenize(left))
|
|
52
|
+
const b = right instanceof Set ? right : new Set(tokenize(right))
|
|
53
|
+
if (a.size === 0 && b.size === 0) return 1
|
|
54
|
+
if (a.size === 0 || b.size === 0) return 0
|
|
55
|
+
let shared = 0
|
|
56
|
+
const [small, large] = a.size <= b.size ? [a, b] : [b, a]
|
|
57
|
+
for (const token of small) if (large.has(token)) shared += 1
|
|
58
|
+
return shared / (a.size + b.size - shared)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 单向覆盖率:left 的词元有多大比例出现在 right 里。
|
|
63
|
+
*
|
|
64
|
+
* 与 Jaccard 分工:Jaccard 对长度差异敏感(一句标题对一整段正文约 0.2),而**对齐**要问的
|
|
65
|
+
* 恰恰是「这段源码是不是被这段 PDF 文本完整覆盖」,短的被长的包含就该算命中。
|
|
66
|
+
* **合并**仍用 Jaccard,因为那里要的正是「两边说的是不是同一件事」,长度差异是有效信号。
|
|
67
|
+
*/
|
|
68
|
+
export function coverage(left, right) {
|
|
69
|
+
const a = left instanceof Set ? left : new Set(tokenize(left))
|
|
70
|
+
const b = right instanceof Set ? right : new Set(tokenize(right))
|
|
71
|
+
if (a.size === 0) return b.size === 0 ? 1 : 0
|
|
72
|
+
let shared = 0
|
|
73
|
+
for (const token of a) if (b.has(token)) shared += 1
|
|
74
|
+
return shared / a.size
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* 归一化后的可比较文本:折空白、去首尾空白。
|
|
79
|
+
*
|
|
80
|
+
* 对齐把 PDF 文本层的多行合成一段、把源码里的多行合回一段之后,两边仍会差在换行与
|
|
81
|
+
* 制表符上;这里统一折成单空格,让「同一段话」在字符串层面也可比较(用于定位下标)。
|
|
82
|
+
*/
|
|
83
|
+
export function normalizeForMatch(value) {
|
|
84
|
+
return String(value ?? '').replace(/\s+/g, ' ').trim()
|
|
85
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { isAbsolute, relative, resolve, sep } from 'node:path'
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
|
|
4
|
+
/** Keep recoverable failures in the same result shape through DSH's tool executor. */
|
|
5
|
+
export function toolContract(tool) {
|
|
6
|
+
tool.parameters.additionalProperties = false
|
|
7
|
+
const parameters = new Set(Object.keys(tool.parameters.properties))
|
|
8
|
+
const failure = (args, code, notice) => {
|
|
9
|
+
const result = { ok: false, code, notice }
|
|
10
|
+
if (tool.name === 'Paper_analysis') return { ...result, mode: 'result', papers: [] }
|
|
11
|
+
if (tool.name === 'Paper_annotate') return { ...result, documentId: '', blockId: 'head', kind: 'note' }
|
|
12
|
+
return { ...result, action: typeof args?.action === 'string' ? args.action : '' }
|
|
13
|
+
}
|
|
14
|
+
tool.output.schema = structuredClone(tool.output.schema)
|
|
15
|
+
tool.output.schema.properties.code = { type: 'string', description: '机器可读的失败原因。' }
|
|
16
|
+
tool.output.render = (_args, value) => {
|
|
17
|
+
const { image, ...data } = value
|
|
18
|
+
const blocks = [{ type: 'text', text: JSON.stringify(data) }]
|
|
19
|
+
if (image !== undefined) blocks.push({ type: 'image', attachment: image })
|
|
20
|
+
return blocks
|
|
21
|
+
}
|
|
22
|
+
const execute = tool.execute
|
|
23
|
+
tool.execute = async function (args, exec) {
|
|
24
|
+
try {
|
|
25
|
+
const unknown = Object.keys(args ?? {}).filter(key => !parameters.has(key))
|
|
26
|
+
if (unknown.length > 0) return failure(args, 'INVALID_ARGUMENTS', '不支持参数 ' + unknown.join(' / ') + '。请使用工具声明的参数。')
|
|
27
|
+
const result = await execute.call(this, args, exec)
|
|
28
|
+
return result?.ok === false ? { ...result, code: result.code ?? 'INVALID_REQUEST' } : result
|
|
29
|
+
} catch (error) {
|
|
30
|
+
const notice = String(error?.message ?? error).slice(0, 500)
|
|
31
|
+
return failure(args, 'OPERATION_FAILED', notice)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return tool
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function paperOutput(root) {
|
|
38
|
+
const base = resolve(root)
|
|
39
|
+
const fold = value => value.replaceAll('\\', '/').toLowerCase()
|
|
40
|
+
const internalRoot = fold(base)
|
|
41
|
+
const within = value => {
|
|
42
|
+
if (typeof value !== 'string' || !isAbsolute(value)) return false
|
|
43
|
+
const path = relative(base, resolve(value))
|
|
44
|
+
return path === '' || (path !== '..' && !path.startsWith('..' + sep) && !isAbsolute(path))
|
|
45
|
+
}
|
|
46
|
+
const message = value => typeof value === 'string' && fold(value).includes(internalRoot)
|
|
47
|
+
? '论文数据操作失败,请按论文 id 查询状态后重试。' : value
|
|
48
|
+
const pathFields = new Set(['pdfPath', 'markdownPath', 'outlinePath', 'contentPath', 'manifestPath', 'path', 'sourceDir', 'sourcePdfPath'])
|
|
49
|
+
const messages = new Set(['notice', 'error', 'failures', 'jobUnavailableReason', 'reason', 'detail', 'result'])
|
|
50
|
+
const project = (value, key) => {
|
|
51
|
+
if (Array.isArray(value)) return value.map(item => project(item, key))
|
|
52
|
+
if (!value || typeof value !== 'object') return messages.has(key) ? message(value) : value
|
|
53
|
+
return Object.fromEntries(Object.entries(value)
|
|
54
|
+
.filter(([key, item]) => !pathFields.has(key) || !within(item))
|
|
55
|
+
.map(([key, item]) => [key, project(item, key)]))
|
|
56
|
+
}
|
|
57
|
+
return { within, message, project }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Publish paper addresses and user-owned paths; internal storage locations remain host-only. */
|
|
61
|
+
export function publicPaperTool(tool, root) {
|
|
62
|
+
const { within, project } = paperOutput(root)
|
|
63
|
+
const execute = tool.execute
|
|
64
|
+
tool.execute = async function (args, exec) {
|
|
65
|
+
const raw = await execute.call(this, args, exec)
|
|
66
|
+
const value = project(raw)
|
|
67
|
+
if (tool.name === 'Paper_read' && args?.action === 'page' && within(raw.path)) {
|
|
68
|
+
const id = value.paper?.documentId
|
|
69
|
+
value.url = '/api/dsh-paper/page-image?documentId=' + encodeURIComponent(id) + '&page=' + (Number.isFinite(args.page) ? Math.floor(args.page) : 1)
|
|
70
|
+
value.notice = value.image ? '原页图片已返回。' : '原页已生成,可通过链接查看;当前模型不接收图片。'
|
|
71
|
+
}
|
|
72
|
+
// The registry replaces an aborted return value; deferred context survives native and PTC cancellation.
|
|
73
|
+
if (tool.name === 'Paper_analysis' && exec?.signal?.aborted && typeof exec.deferContext === 'function') {
|
|
74
|
+
const pending = value.papers?.some(paper => paper.status === 'queued' || paper.status === 'running')
|
|
75
|
+
const notice = pending
|
|
76
|
+
? 'Paper_analysis 的调用等待已中断;解析已提交后台队列,不能据此判定解析失败或重新提交。请按以下回执查询实际状态。'
|
|
77
|
+
: 'Paper_analysis 的调用等待已中断;实际处理回执如下,请据此判断完成或失败。'
|
|
78
|
+
exec.deferContext({ id: randomUUID(), role: 'user', source: { kind: 'dsh-paper' },
|
|
79
|
+
content: [{ type: 'text', text: notice + '\n' + JSON.stringify(value) }] })
|
|
80
|
+
}
|
|
81
|
+
return value
|
|
82
|
+
}
|
|
83
|
+
const paper = tool.output.schema.properties.papers?.items
|
|
84
|
+
if (paper?.required) paper.required = paper.required.filter(key => key !== 'pdfPath')
|
|
85
|
+
return tool
|
|
86
|
+
}
|