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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +137 -2
  3. package/cordis.patch.yml +4 -0
  4. package/lib/annotate-tool.js +334 -0
  5. package/lib/arxiv-id.js +74 -0
  6. package/lib/asset-routes.js +210 -0
  7. package/lib/bibliography-formats.js +126 -0
  8. package/lib/bibliography-import.js +105 -0
  9. package/lib/bibliography-service.js +43 -0
  10. package/lib/bibliography.js +42 -0
  11. package/lib/block-authors.js +292 -0
  12. package/lib/block-cache.js +39 -0
  13. package/lib/blocks-markdown.js +157 -0
  14. package/lib/blocks-reconcile.js +218 -0
  15. package/lib/blocks.js +1344 -0
  16. package/lib/citation-metadata.js +260 -0
  17. package/lib/citation-styles.js +120 -0
  18. package/lib/client-parts/01-pure-helpers.js +2607 -0
  19. package/lib/client.js +9569 -0
  20. package/lib/code-source.js +68 -0
  21. package/lib/concurrency-gate.js +91 -0
  22. package/lib/context.js +233 -0
  23. package/lib/csl/SOURCES.md +10 -0
  24. package/lib/csl/gb-t-7714.csl +441 -0
  25. package/lib/csl/ieee.csl +520 -0
  26. package/lib/csl/locales-zh-CN.xml +438 -0
  27. package/lib/csl/nature.csl +190 -0
  28. package/lib/discussion.js +400 -0
  29. package/lib/documents.js +67 -0
  30. package/lib/export.js +848 -0
  31. package/lib/file-lock.js +177 -0
  32. package/lib/gloss.js +181 -0
  33. package/lib/glossary.js +279 -0
  34. package/lib/index.js +3862 -0
  35. package/lib/inline-html.js +53 -0
  36. package/lib/install-dependency.js +120 -0
  37. package/lib/item-ops.js +83 -0
  38. package/lib/job-facade.js +58 -0
  39. package/lib/json-store.js +54 -0
  40. package/lib/library-model.js +132 -0
  41. package/lib/library-service.js +180 -0
  42. package/lib/library-tool.js +982 -0
  43. package/lib/library.js +814 -0
  44. package/lib/markdown-assets.js +138 -0
  45. package/lib/markdown-literals.js +93 -0
  46. package/lib/metadata-enrichment.js +516 -0
  47. package/lib/metadata-fetch.js +146 -0
  48. package/lib/metadata-node.js +158 -0
  49. package/lib/metadata-proxy.ps1 +35 -0
  50. package/lib/mineru-config.js +95 -0
  51. package/lib/mineru-sdk-helper.py +123 -0
  52. package/lib/mineru-sdk.js +182 -0
  53. package/lib/mineru.js +268 -0
  54. package/lib/mirror-export.js +240 -0
  55. package/lib/outline.js +296 -0
  56. package/lib/page-image-helper.py +294 -0
  57. package/lib/page-image.js +454 -0
  58. package/lib/paper-metadata.js +242 -0
  59. package/lib/parse-export.js +631 -0
  60. package/lib/pdf-analysis-tool.js +750 -0
  61. package/lib/pdf-metadata-helper.py +75 -0
  62. package/lib/pdf-metadata.js +141 -0
  63. package/lib/pdf-page.js +183 -0
  64. package/lib/pdf-scan.js +134 -0
  65. package/lib/pdf-text.js +68 -0
  66. package/lib/picker.js +305 -0
  67. package/lib/portable.js +379 -0
  68. package/lib/purge.js +170 -0
  69. package/lib/read-tool.js +660 -0
  70. package/lib/reader-store.js +497 -0
  71. package/lib/reading-order.js +207 -0
  72. package/lib/rename-document.js +480 -0
  73. package/lib/rename.js +372 -0
  74. package/lib/renderer-status.js +161 -0
  75. package/lib/resolver.js +1152 -0
  76. package/lib/result-archive.js +157 -0
  77. package/lib/revisions.js +330 -0
  78. package/lib/search-database.js +62 -0
  79. package/lib/search-index.js +601 -0
  80. package/lib/search-scan.js +185 -0
  81. package/lib/search-source.js +23 -0
  82. package/lib/search-terms.js +539 -0
  83. package/lib/section-audit.js +209 -0
  84. package/lib/selection-message.js +332 -0
  85. package/lib/serial-tail.js +21 -0
  86. package/lib/slicing.js +425 -0
  87. package/lib/source-resolver.js +581 -0
  88. package/lib/stem-repair.js +189 -0
  89. package/lib/storage.js +562 -0
  90. package/lib/store-paths.js +253 -0
  91. package/lib/table-gfm.js +236 -0
  92. package/lib/tasks.js +270 -0
  93. package/lib/tex-align.js +509 -0
  94. package/lib/tex-blocks.js +653 -0
  95. package/lib/tex-fetch.js +455 -0
  96. package/lib/tex-figures.js +140 -0
  97. package/lib/tex-inline.js +166 -0
  98. package/lib/tex-merge.js +279 -0
  99. package/lib/tex-pipeline.js +242 -0
  100. package/lib/tex-prepare.js +746 -0
  101. package/lib/tex-tables.js +210 -0
  102. package/lib/text-similarity.js +85 -0
  103. package/lib/tool-contract.js +86 -0
  104. package/lib/tool-host.js +1058 -0
  105. package/lib/tool-identity.js +214 -0
  106. package/lib/translatable-text.js +48 -0
  107. package/lib/translate-prompts.js +709 -0
  108. package/lib/translate-queue.js +418 -0
  109. package/lib/translate-task.js +158 -0
  110. package/lib/translate.js +909 -0
  111. package/lib/update-check.js +438 -0
  112. package/lib/update-contracts.js +75 -0
  113. package/lib/usage.js +282 -0
  114. package/package.json +55 -4
package/lib/usage.js ADDED
@@ -0,0 +1,282 @@
1
+ // lib/usage.js —— 模型调用的 token 用量账本:落盘、幂等并入与汇总
2
+ //
3
+ // 只做数据层的三件事:
4
+ // 1. 把每一次调用的用量记进 <runtimeDir>/usage.json(临时文件 + 原子替换);
5
+ // 2. 并入时按 jobId 幂等 —— 同一次调用被并入两次只算一次;
6
+ // 3. 按文档与时间汇总。
7
+ //
8
+ // 🔴 计数口径完全照搬宿主 TokenUsage 的**不相交**约定(见 toUsage 的注释):缺 totalTokens 时
9
+ // 的推导是 input + output + cacheRead + cacheWrite,不是 input + output。
10
+ //
11
+ // 采集点在翻译管线里(translate.js 消费宿主 stream 的 usage chunk),所以本模块**不认识宿主类型**,
12
+ // 只收普通对象,也不 import 任何 @deepseek-ai/* 包 —— 这样它能在宿主之外单独跑测试。
13
+
14
+ import { mkdir, readFile, writeFile } from 'node:fs/promises'
15
+ import { dirname, join } from 'node:path'
16
+
17
+ import { replaceStateFile } from './storage.js'
18
+
19
+ /** 账本文件名。所在目录由调用方注入(见 usagePathOf),本模块不读环境变量猜路径。 */
20
+ export const USAGE_FILE_NAME = 'usage.json'
21
+
22
+ /** 账本 schema 版本。 */
23
+ export const USAGE_SCHEMA_VERSION = 1
24
+
25
+ /**
26
+ * 缺 jobId 时的兜底幂等键前缀。
27
+ *
28
+ * jobId 是这次调用的身份,正常管线里不会缺;真缺了也不能把记录丢掉(那是漏记),
29
+ * 于是退一步用**记录内容的指纹**当键 —— 逐字段相同的两条匿名记录极可能是一次重放。
30
+ * 代价写在明处:两次真正独立、又恰好逐字段同值的匿名调用会被合成一条。
31
+ */
32
+ const ANONYMOUS_PREFIX = 'anon:'
33
+
34
+ // 同一毫秒内的两次写入会撞出同一个临时文件名:第一个 rename 已经把临时文件搬走,
35
+ // 第二个就会以 ENOENT 失败。计数器让进程内永远撞不上 —— 与 glossary.js / mineru-config.js 同一处取舍。
36
+ let temporarySequence = 0
37
+
38
+ /**
39
+ * 合法计数:有限且为正的数字。负数、-0、NaN、±Infinity、字符串数字、null、undefined、对象
40
+ * 一律读作 0 —— 账本是统计用途,一条坏记录不该让整条记录(乃至整次写入)失败。
41
+ */
42
+ function countOf(value) {
43
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
44
+ }
45
+
46
+ /** 可用的文本字段:非空字符串原样保留,其余(含纯空白)读作空串。 */
47
+ function textOf(value) {
48
+ return typeof value === 'string' && value.trim() !== '' ? value : ''
49
+ }
50
+
51
+ /**
52
+ * 时间戳归一化:可解析的 ISO 串 / 毫秒数 / Date → 毫秒数;其余返回 undefined。
53
+ *
54
+ * 只用来比较(summarizeUsage 的 since),不决定落盘形状 —— 落盘的是 toTimestampText 的 ISO 串。
55
+ */
56
+ function timestampOf(value) {
57
+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined
58
+ if (typeof value === 'string') {
59
+ const parsed = Date.parse(value)
60
+ return Number.isFinite(parsed) ? parsed : undefined
61
+ }
62
+ if (value instanceof Date) {
63
+ const parsed = value.getTime()
64
+ return Number.isFinite(parsed) ? parsed : undefined
65
+ }
66
+ return undefined
67
+ }
68
+
69
+ /** 落盘用的时间文本:一律规范成 UTC ISO 串(number / Date 也接受),不可解析则空串。 */
70
+ function toTimestampText(value) {
71
+ const parsed = timestampOf(value)
72
+ return parsed === undefined ? '' : new Date(parsed).toISOString()
73
+ }
74
+
75
+ /**
76
+ * 把一次调用的 usage 归一化成落盘形状(六个字段,缺一不可)。
77
+ *
78
+ * 🔴 计数字段**不相交**(宿主 TokenUsage 的 JSDoc 原文:inputTokens 是未命中缓存的输入,
79
+ * 缓存输入另记在 cacheReadTokens / cacheWriteTokens,计费输入 = 三者之和)。所以缺 totalTokens
80
+ * 时的推导是 input + output + cacheRead + cacheWrite —— 写成 input + output 会系统性少算缓存命中的
81
+ * 那一大块,而长文翻译里缓存命中恰恰是输入的大头。
82
+ *
83
+ * reasoningTokens 不参与推导:它属于输出侧的子集,加进去就是双计。
84
+ *
85
+ * 显式给了正数 totalTokens 就以它为准,不校验它与各项之和是否相等 —— 那是 provider 自己的口径,
86
+ * 账本只负责如实记录(也因此"推导"只在它缺失/不可用时兜底)。
87
+ */
88
+ function toUsage(value) {
89
+ const usage = value && typeof value === 'object' && !Array.isArray(value) ? value : {}
90
+ const inputTokens = countOf(usage.inputTokens)
91
+ const outputTokens = countOf(usage.outputTokens)
92
+ const cacheReadTokens = countOf(usage.cacheReadTokens)
93
+ const cacheWriteTokens = countOf(usage.cacheWriteTokens)
94
+ const reasoningTokens = countOf(usage.reasoningTokens)
95
+ const declared = countOf(usage.totalTokens)
96
+ const totalTokens = declared > 0 ? declared : inputTokens + outputTokens + cacheReadTokens + cacheWriteTokens
97
+ return { inputTokens, outputTokens, totalTokens, cacheReadTokens, cacheWriteTokens, reasoningTokens }
98
+ }
99
+
100
+ /**
101
+ * 一条记录归一化;返回 null 表示它连身份都取不到(非对象)。
102
+ *
103
+ * fallbackId 是它在 records 表里的键:手工编辑过的文件可能把身份写在键上而没写进值,
104
+ * 那种情况下认键不认空值。
105
+ */
106
+ function toRecord(value, fallbackId = '') {
107
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null
108
+ return {
109
+ jobId: textOf(value.jobId) || textOf(fallbackId),
110
+ documentId: textOf(value.documentId),
111
+ provider: textOf(value.provider),
112
+ model: textOf(value.model),
113
+ usage: toUsage(value.usage),
114
+ at: toTimestampText(value.at),
115
+ }
116
+ }
117
+
118
+ /**
119
+ * 记录在 records 表里的键。有 jobId 就用它(幂等键),没有才退回内容指纹。
120
+ *
121
+ * 指纹取归一化后的 documentId / provider / model / usage —— 形状由 toUsage 的字面量固定,
122
+ * 因此同一条记录每次算出来的指纹逐字节一致。
123
+ */
124
+ function keyOf(record) {
125
+ if (record.jobId !== '') return record.jobId
126
+ return ANONYMOUS_PREFIX + JSON.stringify([record.documentId, record.provider, record.model, record.usage])
127
+ }
128
+
129
+ /** 账本归一化。非对象入参(null / 数组 / 字符串 / undefined)一律当空账本。 */
130
+ function normalizeStore(value) {
131
+ const source = value && typeof value === 'object' && !Array.isArray(value) ? value : {}
132
+ const version = Number.isInteger(source.version) && source.version > 0 ? source.version : USAGE_SCHEMA_VERSION
133
+ const raw = source.records && typeof source.records === 'object' && !Array.isArray(source.records) ? source.records : {}
134
+ const records = {}
135
+ for (const [key, entry] of Object.entries(raw)) {
136
+ const record = toRecord(entry, key)
137
+ if (record) records[keyOf(record)] = record
138
+ }
139
+ return { version, records }
140
+ }
141
+
142
+ /** 空账本。读盘降级与坏入参共用同一份形状,调用方不必再判 undefined。 */
143
+ export function emptyUsage() {
144
+ return { version: USAGE_SCHEMA_VERSION, records: {} }
145
+ }
146
+
147
+ /** 账本文件的位置。runtimeRoot 由调用方注入(测试里指到临时目录)。 */
148
+ export function usagePathOf(runtimeRoot) {
149
+ return join(runtimeRoot, USAGE_FILE_NAME)
150
+ }
151
+
152
+ /**
153
+ * 读回账本;任何"读不出来"的情形都当作空账本返回,绝不抛错。
154
+ *
155
+ * 调用方是每次翻译都要跑的路径,而文件在用户手边(可能被删、被同步工具写坏、被手工编辑成
156
+ * 数组或字符串)。这里抛错就是整篇翻译挂掉,而不是"这次没有账"。读出来的记录同样过一遍归一化:
157
+ * 坏条目丢掉、计数归零、身份从键上补齐。
158
+ *
159
+ * @param {string} path
160
+ * @returns {Promise<{version: number, records: Record<string, object>}>}
161
+ */
162
+ export async function readUsage(path) {
163
+ let value
164
+ try {
165
+ value = JSON.parse(await readFile(path, 'utf8'))
166
+ } catch {
167
+ // ENOENT(还没记过账)、权限、非法 JSON、把目录当文件读(EISDIR)走同一条路:空账本。
168
+ return emptyUsage()
169
+ }
170
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return emptyUsage()
171
+ return normalizeStore(value)
172
+ }
173
+
174
+ /**
175
+ * 写账本:临时文件 + replaceStateFile(与 lib/storage.js 的 state.json 同一口径,含 Windows 上
176
+ * rename 被占用句柄时的 EPERM/EBUSY/EACCES 退避重试)。临时名带 pid、时间戳与进程内序号,
177
+ * 并发写不会互相覆盖。
178
+ *
179
+ * 落盘前过一遍归一化:文件里永远只有合法记录,一条坏记录不会被每一次读盘带进汇总。
180
+ *
181
+ * @param {string} path
182
+ * @param {unknown} value
183
+ * @returns {Promise<{version: number, records: Record<string, object>}>} 实际落盘的内容
184
+ */
185
+ export async function writeUsage(path, value) {
186
+ const body = normalizeStore(value)
187
+ const directory = dirname(path)
188
+ await mkdir(directory, { recursive: true })
189
+ temporarySequence += 1
190
+ const temporary = path + '.' + process.pid + '.' + Date.now() + '.' + temporarySequence + '.tmp'
191
+ await writeFile(temporary, JSON.stringify(body, null, 2) + '\n', 'utf8')
192
+ await replaceStateFile(temporary, path)
193
+ return body
194
+ }
195
+
196
+ /**
197
+ * 把一次调用的用量并入账本,返回**新**账本(纯函数:不改入参,也不碰磁盘)。
198
+ *
199
+ * 🔴 jobId 是幂等键,同一个 jobId 只留一条记录、**不累加**:
200
+ * 采集点重试(写盘失败重跑、事件重放)会把同一条记录并入两次,累加就会把一次调用记成两次;
201
+ * 覆盖天然幂等,重放多少次结果都一样。若同一 jobId 真的带来了两次不同的计量,那是同一次调用
202
+ * 路径上更晚的一次观测,取后到的 —— 把它俩相加才是真正的双计("同一次调用被观测两遍")。
203
+ * 真正独立的两次调用在采集点就有不同的 jobId,因此不靠这里区分。
204
+ *
205
+ * 缺 jobId 时退回内容指纹(见 keyOf 的注释)。
206
+ *
207
+ * at 缺省取当前时间:账本要按时间过滤,而 record 的冻结形状里没有时间字段,只能由这里补。
208
+ * 显式传 at(测试、补录历史)时不碰时钟。
209
+ *
210
+ * @param {unknown} store
211
+ * @param {unknown} record {{jobId, documentId, provider, model, usage, at?}}
212
+ */
213
+ export function mergeUsage(store, record) {
214
+ const current = normalizeStore(store)
215
+ const merged = toRecord(record)
216
+ if (!merged) return current
217
+ const entry = merged.at === '' ? { ...merged, at: new Date().toISOString() } : merged
218
+ return { ...current, records: { ...current.records, [keyOf(entry)]: entry } }
219
+ }
220
+
221
+ /**
222
+ * 删掉某篇论文的全部用量记录,返回**新**账本(纯函数:不改入参,也不碰磁盘)。
223
+ *
224
+ * 🔴 **永久删除要连账本一起清**:记录里带着 documentId,留着就是对一篇已经不存在的论文的
225
+ * 残留引用 —— 而且没有任何会清理它的路径(账本按 jobId 键控、无上限)。用户从回收站
226
+ * 彻底删除一篇后,「这一篇还花了多少 token」就不该再答得出来。
227
+ *
228
+ * 返回 `{ store, removed }`:removed 是删掉的记录条数,供调用方记账。
229
+ *
230
+ * @param {unknown} store
231
+ * @param {unknown} documentId
232
+ */
233
+ export function dropUsageForDocument(store, documentId) {
234
+ const current = normalizeStore(store)
235
+ const id = textOf(documentId)
236
+ if (id === '') return { store: current, removed: 0 }
237
+ const records = {}
238
+ let removed = 0
239
+ for (const [key, record] of Object.entries(current.records)) {
240
+ if (record.documentId === id) { removed += 1; continue }
241
+ records[key] = record
242
+ }
243
+ return { store: { ...current, records }, removed }
244
+ }
245
+
246
+ /**
247
+ * 汇总账本。filter 可选:{ documentId?, since? }。
248
+ *
249
+ * - documentId:只算该文档的记录(严格相等;给了空串/非字符串等于没给);
250
+ * - since:时间下界,**闭区间**(at >= since),接受 ISO 串、毫秒数或 Date;
251
+ * - 两者可同时给。
252
+ *
253
+ * 给了 since 却解析不出来时当作没给 —— 账本是统计用途,宁可多报,也不要因为一个坏参数
254
+ * 静默把记录全筛没。反过来,**记录自己的 at 坏掉**时按"太早"处理(不冒充当期数据),
255
+ * 只有带 since 的汇总会这样;不带 since 时它照常计入。
256
+ *
257
+ * 只返回四个字段。cache / reasoning 已经折进 totalTokens(见 toUsage),不单独拆出:
258
+ * 宿主 TokenUsage 的原始明细仍然逐条留在 records 里,需要时直接读记录。
259
+ *
260
+ * @param {unknown} store
261
+ * @param {{documentId?: unknown, since?: unknown}} [filter]
262
+ * @returns {{inputTokens: number, outputTokens: number, totalTokens: number, calls: number}}
263
+ */
264
+ export function summarizeUsage(store, filter) {
265
+ const current = normalizeStore(store)
266
+ const options = filter && typeof filter === 'object' && !Array.isArray(filter) ? filter : {}
267
+ const documentId = textOf(options.documentId)
268
+ const since = timestampOf(options.since)
269
+ const summary = { inputTokens: 0, outputTokens: 0, totalTokens: 0, calls: 0 }
270
+ for (const record of Object.values(current.records)) {
271
+ if (documentId !== '' && record.documentId !== documentId) continue
272
+ if (since !== undefined) {
273
+ const at = timestampOf(record.at)
274
+ if (at === undefined || at < since) continue
275
+ }
276
+ summary.inputTokens += record.usage.inputTokens
277
+ summary.outputTokens += record.usage.outputTokens
278
+ summary.totalTokens += record.usage.totalTokens
279
+ summary.calls += 1
280
+ }
281
+ return summary
282
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@li-canghai/dsh-paper",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.8.0",
4
+ "description": "PDF transcription with stable block ids, folder scanning up to two sub-levels, and session-scoped paper context with drag-select batch injection and removal for DSH.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./client": "./lib/client.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": [
13
+ "lib",
14
+ "cordis.patch.yml",
15
+ "README.md",
16
+ "LICENSE"
17
+ ],
18
+ "scripts": {
19
+ "test": "node --test \"test/*.test.js\"",
20
+ "test:mineru-sdk": "uvx --from mineru-open-sdk==0.2.5 python -B -m unittest discover -s test -p mineru_sdk_helper_test.py -v",
21
+ "check": "node scripts/check.mjs",
22
+ "smoke": "node scripts/smoke.mjs",
23
+ "deploy": "node scripts/sync-deploy.mjs",
24
+ "deploy:check": "node scripts/sync-deploy.mjs --check",
25
+ "prepack": "node scripts/prepack.mjs"
26
+ },
27
+ "engines": {
28
+ "node": ">=22.12.0",
29
+ "dsh": ">=0.2.0-rc.1 <=0.3.0-rc.1 || ^0.2.1-rc.1"
30
+ },
31
+ "peerDependencies": {
32
+ "@deepseek-ai/schemastery": "^3.18.1"
33
+ },
34
+ "dependencies": {
35
+ "@citation-js/core": "0.9.0",
36
+ "@citation-js/plugin-bibtex": "0.9.0",
37
+ "@citation-js/plugin-csl": "0.9.0",
38
+ "@citation-js/plugin-ris": "0.9.0",
39
+ "@xmldom/xmldom": "0.9.12",
40
+ "https-proxy-agent": "9.1.0",
41
+ "socks": "2.8.10"
42
+ },
43
+ "license": "MIT",
44
+ "dsh": {
45
+ "bundle": {
46
+ "patch": "./cordis.patch.yml"
47
+ },
48
+ "client": {
49
+ "platform": "web",
50
+ "inject": [
51
+ "@deepseek-ai/dsh-client-ui-renderer",
52
+ "@deepseek-ai/dsh-client-ui-session",
53
+ "@deepseek-ai/dsh-client-ui-sidebar-right"
54
+ ]
55
+ }
56
+ }
57
+ }