@li-canghai/dsh-paper 0.8.2 → 0.8.3

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.
@@ -102,7 +102,7 @@ export function createTranslateQueue(options = {}) {
102
102
 
103
103
  /**
104
104
  * 已结算的任务会被 maybeSettle 从表里摘掉(taskId 用的是 documentId,不摘就再也不能入队)。
105
- * 但 pause/resume/cancel/retryFailed/stats 仍要能在结算后回答那个 taskId —— 否则
105
+ * 但 pause/resume/cancel/stats 仍要能在结算后回答那个 taskId —— 否则
106
106
  * 「失败页可一键重试」这条验收就断了(重试只能发生在结算之后)。
107
107
  * 所以这里额外保留一份**只读的结算快照**,五个读侧接口从它兜底。
108
108
  */
@@ -342,31 +342,6 @@ export function createTranslateQueue(options = {}) {
342
342
  return task.deferred.promise
343
343
  }
344
344
 
345
- /** 只重跑 failed 的批次;在飞时拒绝,避免同一任务被两个驱动同时跑 */
346
- function retryFailed(taskId) {
347
- const task = lookupTask(taskId, 'retryFailed')
348
- if (task.running.size > 0) {
349
- throw new Error('任务 ' + taskId + ' 仍有批次在执行,无法重试')
350
- }
351
- if (task.cancelled) throw new Error('任务 ' + taskId + ' 已取消,无法重试')
352
- if (task.paused) throw new Error('任务 ' + taskId + ' 处于暂停状态,请先 resume 再重试')
353
-
354
- for (let i = 0; i < task.states.length; i += 1) {
355
- if (task.states[i] !== FAILED) continue
356
- task.states[i] = PENDING
357
- task.results[i] = undefined
358
- }
359
- // 重新登记为活动任务:结算时它又被摘掉并刷新快照。
360
- settledTasks.delete(task.taskId)
361
- tasks.set(task.taskId, task)
362
- task.deferred = createDeferred()
363
- task.settled = false
364
- task.updatedAt = now()
365
- schedule()
366
- maybeSettle(task)
367
- return task.deferred.promise
368
- }
369
-
370
345
  function stats(taskId) {
371
346
  const task = tasks.get(taskId) ?? settledTasks.get(taskId)
372
347
  if (!task) return null
@@ -385,20 +360,12 @@ export function createTranslateQueue(options = {}) {
385
360
  }
386
361
  }
387
362
 
388
- /** 改并发上限:立即影响后续调度(已排队未开始的批次按新并发放行) */
389
- function setConcurrency(value) {
390
- concurrency = assertPositiveInteger(value, 'concurrency')
391
- schedule()
392
- }
393
-
394
363
  return {
395
364
  enqueue,
396
365
  pause,
397
366
  resume,
398
367
  cancel,
399
- retryFailed,
400
368
  stats,
401
- setConcurrency,
402
369
  runningCount,
403
370
  /** 全局刹车(D70)。不给 documentId 时侧栏与脚本都走这一条。 */
404
371
  pauseAll() { globalPaused = true },
@@ -148,7 +148,7 @@ export async function translateDocumentToDisk(document, deps = {}) {
148
148
  glossary: deps.glossary,
149
149
  // 输出协议:专用翻译模型(lines)走逐行方言,其余走默认 JSON 数组。
150
150
  protocol: deps.protocol,
151
- }, deps)
151
+ }, deps) // deps 原样透传:sessionId 等"跟着请求走"的字段由 translateBatch 消费
152
152
  // 合并要基于**磁盘上读到的**旧译文,而不是这次参与翻译的那部分 —— 范围之外的块也得留下。
153
153
  const previous = (await readTranslation(planned.path))?.blocks ?? null
154
154
  const merged = await saveTranslation(planned.path, outcome.blocks, previous, outcome.stats)
package/lib/translate.js CHANGED
@@ -402,6 +402,9 @@ async function attemptBatch(batch, deps, acquireImages, messages) {
402
402
  maxTokens: deps.maxTokens,
403
403
  temperature: deps.temperature,
404
404
  }, deps.signal)
405
+ // 会话 id 只有线路用得着(opencode-go 用它发 `x-opencode-session`,网关据此选路与复用
406
+ // prompt 缓存),但它不属于 LlmCallConfig,所以不参与下面的逐字段比较。
407
+ const sessionId = typeof deps.sessionId === 'string' ? deps.sessionId : ''
405
408
 
406
409
  // 🔴 只有模型**明确声明**接受图像时才附图。inputModalities 为 undefined 是"能力未知",
407
410
  // 乐观假设会在运行期换来一次必然失败的请求;保守假设只损失一次图像上下文(决策 D66)。
@@ -429,15 +432,30 @@ async function attemptBatch(batch, deps, acquireImages, messages) {
429
432
  // 图**在这之后**才去取:能力不支持视觉时连附件都不该写(渲染与落盘都是有代价的副作用)。
430
433
  const imageRefs = supportsImages ? await acquireImages() : []
431
434
  for (const ref of imageRefs) content.push({ type: 'image', attachment: ref })
435
+ // 🔴 派发必须以 `prepared.config` 为基座,不能自己另写一份 provider / model / maxTokens。
436
+ // 宿主会把路由的默认值并进 prepared.config(`resolveCallWithInfo`:适配器声明的
437
+ // defaultMaxTokens 与 reasoning.defaultEffort),而派发前的 `callConfigEquals` 是**逐字段相等**
438
+ // 判断 —— 自己那份缺这些默认值,于是每次都被判成「配置在派发前被改动」并抛
439
+ // INVALID_PREPARED_CALL(实测:官方与 opencode 线路每次翻译都失败,本地 MT 模型因为没有
440
+ // 默认值恰好不受影响)。provider / model 再显式写一遍:它们与 prepareCall 的入参必然相同,
441
+ // 写在这里让「基座到底是什么」在代码里看得出来。
442
+ // messages / system / signal / sessionId 不参与该比较,照常由这里补。
443
+ //
444
+ // 句柄上没有 config 时不硬读:老一代宿主的 PreparedLlmCall 只有 inputModalities / stream,
445
+ // 那时退回"自己那份控制值"就是唯一的、也是本来就该发的形态。
446
+ const base = prepared.config !== null && typeof prepared.config === 'object' ? prepared.config : {}
432
447
  const request = {
448
+ ...base,
433
449
  provider: model.provider,
434
450
  model: model.model,
435
451
  messages: [{ role: 'user', content }],
436
452
  system: text.system,
437
- maxTokens: deps.maxTokens,
438
- temperature: deps.temperature,
439
453
  signal: deps.signal,
454
+ ...(sessionId === '' ? {} : { sessionId }),
440
455
  }
456
+ // 控制值只在基座没给的时候补:基座里的默认值是宿主校验过的,覆盖它等于把比较又弄回不一致。
457
+ if (base.maxTokens === undefined && deps.maxTokens !== undefined) request.maxTokens = deps.maxTokens
458
+ if (base.temperature === undefined && deps.temperature !== undefined) request.temperature = deps.temperature
441
459
 
442
460
  let raw = ''
443
461
  // 终止原因要留住:`max-tokens` 意味着回复被输出上限截断(推理型模型可能把额度全花在推理上、
@@ -785,23 +803,45 @@ export async function translateDocument(input = {}, deps = {}) {
785
803
  let usage
786
804
  // 并发上限:设置页那一档(deps.concurrency),非法或没给按 1(串行)。
787
805
  // 它同时是队列的跨文档并发数(见 index.js 的 enqueue),两层各限各的。
788
- const outcomes = await mapLimit(plan, positiveInt(deps.concurrency, 1, 'concurrency'), batch => translateBatch(
789
- { ...batch, blocks: batch.blockIds.map(id => byId.get(id)).filter(Boolean) },
790
- {
791
- ...deps,
792
- blocksById: byId,
793
- targetLanguage: input.targetLanguage,
794
- glossary: input.glossary,
795
- // 输出协议随批次走(与 targetLanguage 同路):专用翻译模型用 lines / plain,通用模型用默认 json。
796
- protocol: input.protocol,
797
- // 参考段(标题 + 摘要)只给模型当背景,明确不翻译(D140)。一次算好、每个批次都用同一份。
798
- previousContext: reference,
799
- },
800
- ))
801
- // 汇总放在全部批次跑完之后:并发下"边跑边累加"会因为交错而丢掉用量。
806
+ let outcomes
807
+ try {
808
+ outcomes = await mapLimit(plan, positiveInt(deps.concurrency, 1, 'concurrency'), async batch => {
809
+ const outcome = await translateBatch(
810
+ { ...batch, blocks: batch.blockIds.map(id => byId.get(id)).filter(Boolean) },
811
+ {
812
+ ...deps,
813
+ blocksById: byId,
814
+ targetLanguage: input.targetLanguage,
815
+ glossary: input.glossary,
816
+ // 输出协议随批次走(与 targetLanguage 同路):专用翻译模型用 lines / plain,通用模型用默认 json。
817
+ protocol: input.protocol,
818
+ // 参考段(标题 + 摘要)只给模型当背景,明确不翻译(D140)。一次算好、每个批次都用同一份。
819
+ previousContext: reference,
820
+ },
821
+ )
822
+ // 🔴 用量**每批回来就累加**,不等到全部跑完再汇总。
823
+ // `mapLimit` 在任一 worker 抛出时整个 Promise 立刻 reject,末尾那段汇总根本不会执行 ——
824
+ // 而此刻已经发出(甚至已经计费)的批次就一笔都记不上。实测:3 次请求、前两次各带
825
+ // 1500 token,账本记 0,用户看到的是「花掉的钱没记上」。
826
+ // 这里不会交错:JS 单线程,`await` 的续体之间没有真正的并行。
827
+ usage = addUsage(usage, outcome.usage)
828
+ return outcome
829
+ })
830
+ } finally {
831
+ // 成功、取消、抛错三条路都要记账 —— 记的是已经花掉的量。
832
+ if (usage !== undefined && typeof deps.onUsage === 'function') {
833
+ // 记账是**副作用**,绝不让它影响翻译结果:账本写不进去(磁盘满、被占用、权限)时
834
+ // 整篇翻译照常返回,只记一行警告 —— 用户要的是译文,账是附属品。
835
+ // 放在 finally 里同理:记账失败不能把真正的翻译异常替换掉。
836
+ try {
837
+ await deps.onUsage(usage, { batches: plan.length, model })
838
+ } catch (error) {
839
+ warn(deps.logger, `dsh-paper translate: 用量记账失败,本篇译文不受影响:${error?.message ?? error}`)
840
+ }
841
+ }
842
+ }
802
843
  for (const [index, batch] of plan.entries()) {
803
844
  const outcome = outcomes[index]
804
- usage = addUsage(usage, outcome.usage)
805
845
  images += outcome.images
806
846
  const translated = new Map(outcome.translations.map(item => [item.id, item.zh]))
807
847
  for (const id of batch.blockIds) {
@@ -857,15 +897,6 @@ export async function translateDocument(input = {}, deps = {}) {
857
897
  else counts.skipped += 1
858
898
  out.push(entry)
859
899
  }
860
- if (usage !== undefined && typeof deps.onUsage === 'function') {
861
- // 记账是**副作用**,绝不让它影响翻译结果:账本写不进去(磁盘满、被占用、权限)时
862
- // 整篇翻译照常返回,只记一行警告 —— 用户要的是译文,账是附属品。
863
- try {
864
- await deps.onUsage(usage, { batches: plan.length, model })
865
- } catch (error) {
866
- warn(deps.logger, `dsh-paper translate: 用量记账失败,本篇译文不受影响:${error?.message ?? error}`)
867
- }
868
- }
869
900
  return { blocks: out, stats: { ...counts, batches: plan.length, images } }
870
901
  }
871
902
 
@@ -39,17 +39,17 @@ export function updateAddCommand(spec = UPDATE_INSTALL_SPEC) {
39
39
  /** 卡片装不了时用户自己跑的命令。 */
40
40
  export const UPDATE_MANUAL_COMMAND = updateAddCommand()
41
41
 
42
- /** 这一份副本是怎么到磁盘上的。 */
43
- export const INSTALL_KINDS = Object.freeze(['registry', 'link', 'file', 'unknown'])
44
-
45
42
  /**
46
- * 一键升级不可用的原因。
43
+ * 一键升级的三个判定结果,**取值写在 `update-check.js` 的判定处**,这里只留说明。
47
44
  *
48
45
  * - `development-install`:正在跑的是 `link:`/`file:` 依赖,装上去会覆盖开发者正在编辑的工作树;
49
46
  * - `plugin-manager-missing`:这台宿主没有 pluginManager 服务,没有任何东西能跑 pnpm;
50
47
  * - `registry-unreachable`:版本检查本身失败,还不知道有什么可装。
48
+ *
49
+ * 曾经在这里导出过 `INSTALL_KINDS` 与 `UPDATE_BLOCKED_REASONS` 两个冻结数组,但没有任何
50
+ * 消费者 import 它们——判定处全部写成内联字面量。一份「合法取值的唯一来源」没人用,
51
+ * 就只是装饰:改字面量时它不会拦下任何东西。
51
52
  */
52
- export const UPDATE_BLOCKED_REASONS = Object.freeze(['development-install', 'plugin-manager-missing', 'registry-unreachable'])
53
53
 
54
54
  /**
55
55
  * 一次版本检查的结论。
package/locale/en.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "Paper Reading",
4
- "description": "PDF transcription into stable block ids, folder scanning two levels deep, and session-scoped paper context injected or removed by dragging a selection."
4
+ "description": "PDF transcription into stable block ids, folder scanning two levels deep, and session-scoped paper context injected or removed by dragging a selection. Citation rendering uses citeproc-js (© 2009-2019 Frank Bennett, CPAL-1.0)."
5
5
  }
6
6
  }
package/locale/zh.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "meta": {
3
3
  "title": "论文阅读",
4
- "description": "把 PDF 转成稳定块号的正文,支持两级文件夹扫描,并按会话注入或移除论文上下文,可拖选批量处理。"
4
+ "description": "把 PDF 转成稳定块号的正文,支持两级文件夹扫描,并按会话注入或移除论文上下文,可拖选批量处理。引用渲染使用 citeproc-js(© 2009-2019 Frank Bennett,CPAL-1.0)。"
5
5
  }
6
6
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@li-canghai/dsh-paper",
3
- "version": "0.8.2",
3
+ "version": "0.8.3",
4
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
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -16,6 +16,7 @@
16
16
  "cordis.patch.yml",
17
17
  "README.md",
18
18
  "LICENSE",
19
+ "THIRD_PARTY_NOTICES.md",
19
20
  "locale"
20
21
  ],
21
22
  "scripts": {
@@ -41,6 +42,7 @@
41
42
  "@citation-js/plugin-ris": "0.9.0",
42
43
  "@xmldom/xmldom": "0.9.12",
43
44
  "https-proxy-agent": "9.1.0",
45
+ "katex": "^0.16.47",
44
46
  "socks": "2.8.10"
45
47
  },
46
48
  "license": "MIT",