@ggboy123/dsh-paper-reader 1.8.3 → 1.10.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.
@@ -14,7 +14,7 @@ import { lstatSync, mkdirSync, readdirSync, realpathSync, renameSync, rmSync, rm
14
14
  // 注意口径(评审 F-F):组合层**两套并存**——生产写路径用本模块的 resolveTopicDirChecked
15
15
  // (在其上更严),#4 的 resolveSafeTopic 组合层只被 library.ts 的适配器(上游测试用)调用。
16
16
  // 本模块**消费**它,不再自己重复一套词法/realpath 校验;我们的加严叠在其上(见下)。
17
- import { MAX_TOPIC_DEPTH, MAX_TOPIC_PATH, MAX_TOPIC_SEG, caseVariantCollisions, encodedEscapeError, assertInside as assertInsideShared, existingEntryName, isPaperDir, isPaperPDF, paperDirAncestor, realDataDir as realDataDirShared, validateEntryBoundary as validateBoundaryShared, validateEntryName, } from "./library.js";
17
+ import { MAX_TOPIC_DEPTH, MAX_TOPIC_PATH, MAX_TOPIC_SEG, caseVariantCollisions, encodedEscapeError, assertInside as assertInsideShared, existingEntryName, flatArtifactNames, isPaperDir, isPaperPDF, paperDirAncestor, realDataDir as realDataDirShared, validateEntryBoundary as validateBoundaryShared, validateEntryName, } from "./library.js";
18
18
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
19
19
  import { randomBytes } from 'node:crypto';
20
20
  /** HTTP 状态与机器可读 code 双携带;`extra` 会并入响应体(前端只认 code,不匹配中文)。 */
@@ -1177,6 +1177,105 @@ function renameLegacyPaper(dataDir, topicDir, paperName, newName, renameImpl) {
1177
1177
  }
1178
1178
  return { ok: true, moved: moved.map((m) => basename(m.to)), from: paperName, to: newName };
1179
1179
  }
1180
+ /**
1181
+ * 移动论文到另一个已存在专题。新布局整目录移动;旧平铺布局顺手收纳为论文文件夹。
1182
+ * 目标名不变,因此目标专题下的同名论文目录、平铺 PDF 与大小写变体都必须在动手前拒绝。
1183
+ */
1184
+ export function movePaper(dataDir, topic, name, toTopicRaw, renameImpl = renameSync) {
1185
+ const plan = planPaperDelete(dataDir, topic, name);
1186
+ const toTopic = validateTopicPath(toTopicRaw, true);
1187
+ if (toTopic === plan.topic)
1188
+ throw new ManageError('bad-request', 400, '论文已经在目标专题中');
1189
+ const root = realDataDir(dataDir);
1190
+ const targetTopicDir = resolveExistingTopicDir(dataDir, toTopic);
1191
+ const paperParent = paperDirAncestor(root, toTopic.split('/'));
1192
+ if (paperParent)
1193
+ throw new ManageError('target-exists', 409, `目标专题是论文目录,不能移入:${paperParent}`, { conflicts: [paperParent] });
1194
+ const sourceDir = resolveExistingPaperDir(dataDir, plan.topic, plan.name);
1195
+ const targetDir = join(targetTopicDir, plan.name);
1196
+ let targetExists = false;
1197
+ try {
1198
+ lstatSync(targetDir);
1199
+ targetExists = true;
1200
+ }
1201
+ catch { /* 不存在才可移入 */ }
1202
+ const clashes = [...new Set([
1203
+ ...(targetExists ? [plan.name] : []),
1204
+ ...flatArtifactNames(targetTopicDir, plan.name),
1205
+ ...caseVariantCollisions(targetTopicDir, plan.name),
1206
+ ])];
1207
+ if (clashes.length > 0) {
1208
+ throw new ManageError('target-exists', 409, `目标专题已存在同名文献:${clashes.join('、')}`, { conflicts: clashes });
1209
+ }
1210
+ assertInside(root, targetDir);
1211
+ let targetCreated = false;
1212
+ const fail = (err, rollback = () => ({ rolledBack: [], rollbackFailed: [] })) => {
1213
+ const code = err.code;
1214
+ const { rolledBack, rollbackFailed } = rollback();
1215
+ if (plan.layout === 'legacy' && targetCreated) {
1216
+ try {
1217
+ rmdirSync(targetDir);
1218
+ }
1219
+ catch { /* 非空则保留现场 */ }
1220
+ }
1221
+ const tail = rollbackFailed.length === 0
1222
+ ? '本次移动已全部撤销,文献库未改变'
1223
+ : `但 ${rollbackFailed.length} 个文件未能移回原处,请手动检查:${rollbackFailed.join('、')}`;
1224
+ if (code === 'EBUSY' || code === 'EPERM') {
1225
+ throw new ManageError('file-busy', 409, `文件被占用(可能正在阅读器或其他程序中打开),关闭后重试;${tail}`, {
1226
+ busy: plan.name, moved: [], rolledBack, rollbackFailed, cause: code,
1227
+ });
1228
+ }
1229
+ if (typeof code === 'string' && code && rollbackFailed.length === 0)
1230
+ throw err;
1231
+ throw new ManageError('rename-partial', 500, `移动文献中途失败;${tail}`, {
1232
+ moved: [], rolledBack, rollbackFailed, cause: code ?? 'unknown',
1233
+ });
1234
+ };
1235
+ if (plan.layout === 'folder') {
1236
+ try {
1237
+ renameImpl(sourceDir, targetDir);
1238
+ }
1239
+ catch (err) {
1240
+ fail(err);
1241
+ }
1242
+ }
1243
+ else {
1244
+ try {
1245
+ mkdirSync(targetDir);
1246
+ targetCreated = true;
1247
+ }
1248
+ catch (err) {
1249
+ fail(err);
1250
+ }
1251
+ const moved = [];
1252
+ try {
1253
+ for (const f of plan.files) {
1254
+ const from = join(sourceDir, f.name);
1255
+ const to = join(targetDir, f.name);
1256
+ renameImpl(from, to);
1257
+ moved.push({ from, to });
1258
+ }
1259
+ }
1260
+ catch (err) {
1261
+ fail(err, () => {
1262
+ const rolledBack = [];
1263
+ const rollbackFailed = [];
1264
+ for (const m of [...moved].reverse()) {
1265
+ try {
1266
+ renameImpl(m.to, m.from);
1267
+ rolledBack.push(basename(m.from));
1268
+ }
1269
+ catch {
1270
+ rollbackFailed.push(basename(m.from));
1271
+ }
1272
+ }
1273
+ return { rolledBack, rollbackFailed };
1274
+ });
1275
+ }
1276
+ }
1277
+ return { ok: true, moved: plan.files.map((f) => f.name), from: plan.name, to: plan.name, fromTopic: plan.topic, toTopic, name: plan.name };
1278
+ }
1180
1279
  /**
1181
1280
  * 重命名/移动专题(新布局):`to` 是**相对 dataDir 的路径**(`A/B`)⇒ 天然支持「移动到另一父」。
1182
1281
  * 附带两条新不变量(方案 §B2.5):
@@ -2,11 +2,12 @@
2
2
  //
3
3
  // 存 $DSH_HOME/.dsh-paper-reader/translate.json(0600)——刻意不放 dataDir:
4
4
  // dataDir 是文献库目录,可能被 git / 云盘同步出去,密钥不该跟着走。
5
- // 优先级:文件 > profile 的 cordis.patch.yml config.translate(后者退为部署方默认值)。
6
- // 密钥只落盘、只回显掩码:任何读接口都不返回明文(apiKeyHint 是掩码后的展示串)。
5
+ // 优先级:显式选择的 file/profile 覆盖 > 部署方 profile 默认 > Harness 当前模型。
6
+ // 自定义密钥只落盘、只回显掩码;Harness 跟随只保存 activeId='harness',不复制宿主凭据。
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
9
9
  import { dirname, join } from 'node:path';
10
+ import { DEFAULT_TRANSLATION_RUN_OPTIONS, sanitizeTranslationRunOptions, validateTranslationRunOptions, } from "./translation-options.js";
10
11
  import { dshHome } from "./library.js";
11
12
  import { isOpenCodeEndpoint, openCodeSessionHeaders, openCodeSessionId } from "./opencode.js";
12
13
  // 预检会把端点响应体片段拼进错误文案,必须先脱敏(否则端点回显 Authorization 时 key 会泄露)。
@@ -50,7 +51,7 @@ function endpointFields(rec) {
50
51
  /** 新格式是多端点;旧版单对象自动视为 id=legacy 的第一项,读取无需用户重配。 */
51
52
  function parseStore(data) {
52
53
  if (typeof data !== 'object' || data === null)
53
- return { activeId: null, endpoints: [] };
54
+ return { activeId: null, endpoints: [], options: { ...DEFAULT_TRANSLATION_RUN_OPTIONS } };
54
55
  const rec = data;
55
56
  const endpoints = [];
56
57
  if (Array.isArray(rec['endpoints'])) {
@@ -63,6 +64,7 @@ function parseStore(data) {
63
64
  endpoints.push({
64
65
  id: e['id'],
65
66
  ...(typeof e['label'] === 'string' && e['label'] ? { label: e['label'] } : {}),
67
+ ...(typeof e['provider'] === 'string' && e['provider'] ? { provider: e['provider'] } : {}),
66
68
  ...endpointFields(e),
67
69
  });
68
70
  }
@@ -73,15 +75,18 @@ function parseStore(data) {
73
75
  endpoints.push({ id: 'legacy', ...legacy });
74
76
  }
75
77
  const requested = typeof rec['activeId'] === 'string' ? rec['activeId'] : null;
76
- const activeId = requested === 'profile' || endpoints.some((e) => e.id === requested) ? requested : (endpoints[0]?.id ?? null);
77
- return { activeId, endpoints };
78
+ // 空库缺省跟随 Harness;已有文件配置的老用户仍选中自己的端点,不被升级改写。
79
+ const activeId = requested === 'profile' || requested === 'harness' || endpoints.some((e) => e.id === requested)
80
+ ? requested
81
+ : (endpoints[0]?.id ?? 'harness');
82
+ return { activeId, endpoints, options: sanitizeTranslationRunOptions(rec['options']) };
78
83
  }
79
84
  export async function readTranslateEndpointStore(home = dshHome()) {
80
85
  try {
81
86
  return parseStore(JSON.parse(await readFile(translateConfigPath(home), 'utf8')));
82
87
  }
83
88
  catch {
84
- return { activeId: null, endpoints: [] };
89
+ return { activeId: null, endpoints: [], options: { ...DEFAULT_TRANSLATION_RUN_OPTIONS } };
85
90
  }
86
91
  }
87
92
  async function writeStore(store, home) {
@@ -98,7 +103,8 @@ export async function readTranslateConfig(home = dshHome()) {
98
103
  }
99
104
  /** 兼容旧调用方:单端点写入会替换整个文件;UI 多端点保存走 saveTranslateEndpoint。 */
100
105
  export async function writeTranslateConfig(cfg, home = dshHome()) {
101
- await writeStore({ activeId: 'legacy', endpoints: [{ id: 'legacy', ...cfg }] }, home);
106
+ const current = await readTranslateEndpointStore(home);
107
+ await writeStore({ activeId: 'legacy', endpoints: [{ id: 'legacy', ...cfg }], options: current.options }, home);
102
108
  }
103
109
  /** 新建/更新并选中一个端点;id='new' 强制新增,缺省 id 更新当前项(旧 UI 语义)。 */
104
110
  export async function saveTranslateEndpoint(cfg, options = {}) {
@@ -108,21 +114,23 @@ export async function saveTranslateEndpoint(cfg, options = {}) {
108
114
  ? undefined
109
115
  : store.endpoints.find((e) => e.id === (options.id ?? store.activeId));
110
116
  const label = options.label?.trim() || existing?.label;
117
+ const provider = options.provider?.trim() || existing?.provider;
111
118
  const entry = {
112
119
  id: existing?.id ?? randomUUID(),
113
120
  ...(label ? { label } : {}),
121
+ ...(provider ? { provider } : {}),
114
122
  ...cfg,
115
123
  };
116
124
  const endpoints = existing
117
125
  ? store.endpoints.map((e) => e.id === existing.id ? entry : e)
118
126
  : [...store.endpoints, entry];
119
- await writeStore({ activeId: entry.id, endpoints }, home);
127
+ await writeStore({ activeId: entry.id, endpoints, options: store.options }, home);
120
128
  return entry;
121
129
  }
122
- /** 记住生成时选择的端点,划词翻译与下次打开选择器也沿用同一项。 */
130
+ /** 记住生成时选择的来源;harness 不删除任何自定义端点,切回时可继续使用。 */
123
131
  export async function selectTranslateEndpoint(id, home = dshHome()) {
124
132
  const store = await readTranslateEndpointStore(home);
125
- if (id !== 'profile' && !store.endpoints.some((e) => e.id === id))
133
+ if (!['profile', 'harness'].includes(id) && !store.endpoints.some((e) => e.id === id))
126
134
  throw new Error('翻译端点不存在');
127
135
  await writeStore({ ...store, activeId: id }, home);
128
136
  }
@@ -130,15 +138,24 @@ export async function selectTranslateEndpoint(id, home = dshHome()) {
130
138
  export async function deleteTranslateEndpoint(id, home = dshHome()) {
131
139
  const store = await readTranslateEndpointStore(home);
132
140
  const endpoints = store.endpoints.filter((e) => e.id !== id);
133
- await writeStore({ activeId: store.activeId === id ? (endpoints[0]?.id ?? null) : store.activeId, endpoints }, home);
141
+ await writeStore({ activeId: store.activeId === id ? (endpoints[0]?.id ?? null) : store.activeId, endpoints, options: store.options }, home);
142
+ }
143
+ /** 更新整篇 PDF 的运行参数;与选择哪个端点无关,写回时不改变 activeId。 */
144
+ export async function writeTranslateRunOptions(input, home = dshHome()) {
145
+ const options = validateTranslationRunOptions(input);
146
+ const store = await readTranslateEndpointStore(home);
147
+ await writeStore({ ...store, options }, home);
148
+ return options;
134
149
  }
135
150
  /** 删除配置(回落到 profile 的 translate)。文件不存在也算成功。 */
136
151
  export async function clearTranslateConfig(home = dshHome()) {
137
152
  await rm(translateConfigPath(home), { force: true });
138
153
  }
139
- /** 解析生效端点:文件配全则用文件,否则用 profile,都配不全则返回能凑到的部分供报错。 */
154
+ /** 解析生效来源:显式 harness 永远跟随宿主;空库有 profile 时兼容部署默认,否则跟随宿主。 */
140
155
  export async function resolveTranslateEndpoint(profile, home = dshHome(), endpointId) {
141
156
  const store = await readTranslateEndpointStore(home);
157
+ if (endpointId === 'harness' || (!endpointId && store.activeId === 'harness'))
158
+ return { endpoint: {}, source: 'harness' };
142
159
  if (endpointId === 'profile' || (!endpointId && store.activeId === 'profile'))
143
160
  return isComplete(profile)
144
161
  ? { endpoint: profile, source: 'profile' }
@@ -151,6 +168,9 @@ export async function resolveTranslateEndpoint(profile, home = dshHome(), endpoi
151
168
  return { endpoint: file, source: 'file' };
152
169
  if (!endpointId && isComplete(profile))
153
170
  return { endpoint: profile, source: 'profile' };
171
+ // 全新安装没有任何专用配置时默认跟随;显式选择了一个残缺端点仍如实报 none。
172
+ if (!endpointId && !file)
173
+ return { endpoint: {}, source: 'harness' };
154
174
  return { endpoint: endpointId ? (file ?? {}) : pick(profile, file), source: 'none' };
155
175
  }
156
176
  /** 掩码展示:只露头 3 尾 4,够用户认出是哪把 key,又不足以还原。 */
@@ -208,3 +228,56 @@ export async function testTranslateEndpoint(ep) {
208
228
  return { ok: false, detail: sanitizeDetail((err instanceof Error ? err.message : String(err)) + cause, apiKey) };
209
229
  }
210
230
  }
231
+ /** 自动获取 OpenAI 兼容端点可见的聊天模型;只读,不落盘 Key,也不发推理请求。 */
232
+ export async function listTranslateModels(endpoint, fetchImpl = fetch) {
233
+ const baseUrl = endpoint.baseUrl?.trim().replace(/\/+$/, '') ?? '';
234
+ const apiKey = endpoint.apiKey?.trim() ?? '';
235
+ if (!/^https?:\/\//i.test(baseUrl))
236
+ return { ok: false, models: [], detail: '端点 URL 需要以 http:// 或 https:// 开头' };
237
+ if (!apiKey)
238
+ return { ok: false, models: [], detail: '请先填写 API Key' };
239
+ const headers = { authorization: `Bearer ${apiKey}` };
240
+ // Anthropic 的 /v1/models 使用原生鉴权头;其 chat/completions 仍走 OpenAI 兼容模式。
241
+ if (/^https:\/\/api\.anthropic\.com(?:\/|$)/i.test(baseUrl)) {
242
+ headers['x-api-key'] = apiKey;
243
+ headers['anthropic-version'] = '2023-06-01';
244
+ }
245
+ try {
246
+ const r = await fetchImpl(baseUrl + '/models', { headers, signal: AbortSignal.timeout(15_000) });
247
+ const text = (await r.text().catch(() => '')).slice(0, 2_000_000);
248
+ if (!r.ok)
249
+ return { ok: false, models: [], detail: `HTTP ${r.status}${text ? ' ' + sanitizeDetail(text.slice(0, 200), apiKey) : ''}` };
250
+ let data;
251
+ try {
252
+ data = JSON.parse(text);
253
+ }
254
+ catch {
255
+ return { ok: false, models: [], detail: '模型列表响应不是合法 JSON' };
256
+ }
257
+ const rec = data;
258
+ const rows = Array.isArray(rec.data) ? rec.data : Array.isArray(rec.models) ? rec.models : [];
259
+ const models = [];
260
+ for (const row of rows) {
261
+ const raw = typeof row === 'string'
262
+ ? row
263
+ : typeof row === 'object' && row !== null
264
+ ? row.id ?? row.name
265
+ : null;
266
+ if (typeof raw !== 'string' || !raw)
267
+ continue;
268
+ const id = raw.replace(/^models\//, '');
269
+ // 列表端点常混入嵌入/语音/重排模型,它们不能用于 chat/completions。
270
+ if (/(?:embedding|embed-|rerank|whisper|tts|transcribe|moderation|dall-e|image)/i.test(id))
271
+ continue;
272
+ if (!models.includes(id))
273
+ models.push(id);
274
+ }
275
+ if (!models.length)
276
+ return { ok: false, models: [], detail: '端点没有返回可用于翻译的模型,请在高级设置中手动填写' };
277
+ return { ok: true, models: models.slice(0, 200) };
278
+ }
279
+ catch (err) {
280
+ const cause = err instanceof Error && err.cause instanceof Error ? `: ${err.cause.message}` : '';
281
+ return { ok: false, models: [], detail: sanitizeDetail((err instanceof Error ? err.message : String(err)) + cause, apiKey) };
282
+ }
283
+ }
package/dist/translate.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // translate.ts — 中文对照 PDF 生成(纯函数,不依赖 Cordis)。
2
2
  // 移植 pdfqa 的 runPdf2zh:shell 调 babeldoc(pdf2zh 2.x),版式/图/公式原地保留,
3
3
  // 产出 <文献>-zh.pdf(纯中文)与 <文献>-dual.pdf(中英对照)。
4
- // babeldoc 只支持 OpenAI 兼容端点 → 端点/key/模型由插件配置提供。
4
+ // babeldoc 只支持 OpenAI 兼容端点 → 使用翻译专用端点,或由宿主路由传入临时 Harness 适配端点。
5
5
  //
6
6
  // 注:本文件里 TranslatePaperRef / TranslateEndpoint 是「结构最小要求」,只声明本模块真正
7
7
  // 用到的字段;仓库里若已有 library.ts 的 PaperRef 与 translate-config.ts 的端点类型,
@@ -15,6 +15,7 @@ import { fileURLToPath } from 'node:url';
15
15
  import { dshHome } from "./library.js";
16
16
  import { ensureBabeldoc } from "./babeldoc-install.js";
17
17
  import { isOpenCodeEndpoint, openCodeDriverEnv, openCodeSessionId } from "./opencode.js";
18
+ import { DEFAULT_TRANSLATION_RUN_OPTIONS } from "./translation-options.js";
18
19
  export function zhPdfPath(ref) {
19
20
  return ref.pdfPath.slice(0, -extname(ref.pdfPath).length) + '-zh.pdf';
20
21
  }
@@ -118,13 +119,7 @@ function babeldocFlags(bin) {
118
119
  }
119
120
  return p;
120
121
  }
121
- /**
122
- * 启动 babeldoc 后台翻译。幂等:已生成或进行中直接返回 false 表示未新启动。
123
- * 完成/失败结果写进 busy map,由 zhStatus 暴露。
124
- * babeldoc 缺失时不再报错:后台自动走 uv 安装链路(首次约几分钟),
125
- * 期间 zhStatus.phase 展示安装进度,装完直接接着翻译。
126
- */
127
- export async function startTranslation(ref, dataDir, endpoint) {
122
+ export async function startTranslation(ref, dataDir, endpoint, hooks = {}, options = DEFAULT_TRANSLATION_RUN_OPTIONS) {
128
123
  const st = zhStatus(ref);
129
124
  if (st.zh || st.dual)
130
125
  return { started: false, reason: 'already-exists' };
@@ -134,7 +129,7 @@ export async function startTranslation(ref, dataDir, endpoint) {
134
129
  if (pre)
135
130
  return pre;
136
131
  const firstRun = !(await findBabeldoc(dataDir));
137
- void runPipeline(ref, dataDir, endpoint);
132
+ void runPipeline(ref, dataDir, endpoint, hooks, options);
138
133
  return { started: true, firstRun };
139
134
  }
140
135
  /** 端点预检:不齐全时返回与 startTranslation 同形的失败结果。 */
@@ -150,7 +145,7 @@ function precheck(endpoint) {
150
145
  return null;
151
146
  }
152
147
  /** 后台流水线:确保 babeldoc 可用(缺失则自动安装)→ 拉起翻译。 */
153
- async function runPipeline(ref, dataDir, endpoint) {
148
+ async function runPipeline(ref, dataDir, endpoint, hooks, options) {
154
149
  const task = { cancelled: false, kill: null };
155
150
  tasks.set(ref.pdfPath, task);
156
151
  const setPhase = (phase) => setTaskBusy(ref, task, { phase });
@@ -165,7 +160,7 @@ async function runPipeline(ref, dataDir, endpoint) {
165
160
  return;
166
161
  if (!bin)
167
162
  throw new Error('找不到 babeldoc 可执行文件');
168
- await launch(ref, dataDir, endpoint, bin, task);
163
+ await launch(ref, dataDir, endpoint, bin, task, options);
169
164
  }
170
165
  catch (e) {
171
166
  const msg = e instanceof Error ? e.message : String(e);
@@ -176,6 +171,12 @@ async function runPipeline(ref, dataDir, endpoint) {
176
171
  finally {
177
172
  if (tasks.get(ref.pdfPath) === task)
178
173
  tasks.delete(ref.pdfPath);
174
+ try {
175
+ await hooks.onFinish?.();
176
+ }
177
+ catch (e) {
178
+ console.warn('[dsh-paper-reader] 翻译资源清理失败:', e instanceof Error ? e.message : String(e));
179
+ }
179
180
  }
180
181
  }
181
182
  /**
@@ -183,7 +184,7 @@ async function runPipeline(ref, dataDir, endpoint) {
183
184
  * 先预检再删——端点不齐时不动旧译文,免得删完才发现跑不起来。
184
185
  * babeldoc 的段落缓存 key 含模型名,换模型自然失效,无需 --ignore-cache。
185
186
  */
186
- export async function restartTranslation(ref, dataDir, endpoint) {
187
+ export async function restartTranslation(ref, dataDir, endpoint, hooks = {}, options = DEFAULT_TRANSLATION_RUN_OPTIONS) {
187
188
  if (zhStatus(ref).busy)
188
189
  return { started: false, reason: 'busy' };
189
190
  const pre = precheck(endpoint);
@@ -192,7 +193,7 @@ export async function restartTranslation(ref, dataDir, endpoint) {
192
193
  await rm(zhPdfPath(ref), { force: true });
193
194
  await rm(dualPdfPath(ref), { force: true });
194
195
  const firstRun = !(await findBabeldoc(dataDir));
195
- void runPipeline(ref, dataDir, endpoint);
196
+ void runPipeline(ref, dataDir, endpoint, hooks, options);
196
197
  return { started: true, firstRun };
197
198
  }
198
199
  /** 驱动脚本:包装 babeldoc(加结构化进度事件 + 解除单次请求的输出长度限制)。 */
@@ -270,7 +271,7 @@ function resolveDriverPython(bin) {
270
271
  return candidates.find((c) => existsSync(c)) ?? null;
271
272
  }
272
273
  /** 真正拉起 babeldoc 子进程(bin 已就绪、产物不存在/已删)。 */
273
- async function launch(ref, dataDir, endpoint, bin, task) {
274
+ async function launch(ref, dataDir, endpoint, bin, task, options) {
274
275
  // 走到这里之前 precheck 已保证三项齐全;收窄一次,后续按 string 用
275
276
  const ep = endpoint;
276
277
  const tmpDir = join(dataDir, '.pdf2zh-tmp');
@@ -307,7 +308,7 @@ async function launch(ref, dataDir, endpoint, bin, task) {
307
308
  '--openai', '--openai-model', ep.model,
308
309
  '--openai-base-url', ep.baseUrl, '--openai-api-key', ep.apiKey,
309
310
  ...noThink,
310
- '--qps', '16', '--no-watermark', '--output', tmpDir,
311
+ '--qps', String(options.qps), '--no-watermark', '--output', tmpDir,
311
312
  ...(workParent ? ['--working-dir', workParent] : []),
312
313
  // 图/图片区域内的文字保持原文(架构图术语不翻)——目前仅 fork(PR#616)支持
313
314
  ...opt('skip-figure-text'),
@@ -342,7 +343,14 @@ async function launch(ref, dataDir, endpoint, bin, task) {
342
343
  const child = spawnError
343
344
  ? null
344
345
  : spawn(cmd, args, {
345
- env: { ...process.env, HF_ENDPOINT: 'https://hf-mirror.com', PYTHONIOENCODING: 'utf-8', ...openCodeDriverEnv(ep.baseUrl, ocSession) },
346
+ env: {
347
+ ...process.env,
348
+ HF_ENDPOINT: 'https://hf-mirror.com',
349
+ PYTHONIOENCODING: 'utf-8',
350
+ DPR_SPLIT_TOKENS: String(options.splitTokens),
351
+ DPR_MAX_OUTPUT_TOKENS: String(options.maxOutputTokens),
352
+ ...openCodeDriverEnv(ep.baseUrl, ocSession),
353
+ },
346
354
  windowsHide: true,
347
355
  stdio: ['ignore', logFd, logFd],
348
356
  });
@@ -0,0 +1,40 @@
1
+ // translation-options.ts — 整篇 PDF 翻译的运行参数(不含端点凭据)。
2
+ export const DEFAULT_TRANSLATION_RUN_OPTIONS = Object.freeze({
3
+ splitTokens: 100000,
4
+ maxOutputTokens: 32768,
5
+ qps: 16,
6
+ });
7
+ const RULES = {
8
+ splitTokens: { min: 200, max: 128_000, label: '单段上下文上限' },
9
+ maxOutputTokens: { min: 0, max: 32_768, label: '单次输出上限' },
10
+ qps: { min: 1, max: 32, label: '并发请求数' },
11
+ };
12
+ /** 损坏配置逐字段回落默认,不让一个脏数字阻断整篇翻译。 */
13
+ export function sanitizeTranslationRunOptions(input) {
14
+ const rec = typeof input === 'object' && input !== null ? input : {};
15
+ const out = { ...DEFAULT_TRANSLATION_RUN_OPTIONS };
16
+ for (const key of Object.keys(RULES)) {
17
+ const value = rec[key];
18
+ if (typeof value !== 'number' || !Number.isFinite(value))
19
+ continue;
20
+ const { min, max } = RULES[key];
21
+ out[key] = Math.max(min, Math.min(max, Math.trunc(value)));
22
+ }
23
+ return out;
24
+ }
25
+ /** HTTP 写入严格校验:不接受字符串、NaN、小数和越界值,避免“保存了但没按预期生效”。 */
26
+ export function validateTranslationRunOptions(input) {
27
+ const rec = typeof input === 'object' && input !== null ? input : {};
28
+ const out = { ...DEFAULT_TRANSLATION_RUN_OPTIONS };
29
+ for (const key of Object.keys(RULES)) {
30
+ const value = rec[key];
31
+ if (value === undefined)
32
+ continue;
33
+ const { min, max, label } = RULES[key];
34
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < min || value > max) {
35
+ throw new Error(`${label}必须是 ${min}–${max} 之间的整数`);
36
+ }
37
+ out[key] = value;
38
+ }
39
+ return out;
40
+ }