@ggboy123/dsh-paper-reader 1.9.0 → 1.11.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.
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  **English**: [README_EN.md](README_EN.md)
9
9
 
10
- [DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:**论文伴读工作台** —— 文献库 + PDF 阅读器 + AI 伴读,回答自带页码、点页码跳回原文。当前版本 **v1.9.0**。
10
+ [DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:**论文伴读工作台** —— 文献库 + PDF 阅读器 + AI 伴读,回答自带页码、点页码跳回原文。当前版本 **v1.11.0**。
11
11
 
12
12
  > 💬 **QQ 交流群:1127244508** —— 安装/使用问题、功能建议、bug 反馈都欢迎来聊。
13
13
 
@@ -17,7 +17,7 @@
17
17
  2. **翻译不该打断阅读。** 不用把段落复制到别的软件,直接在原 PDF 版面上生成中文;支持纯中文、中英对照、左右分屏和划词翻译,公式也能保留。
18
18
  3. **AI 的回答,需要能回到原文核对。** 回答自带页码,点击就跳到对应原文并高亮;可以只问当前论文,也可以把范围扩大到整个专题,减少“答得流畅却找不到出处”。
19
19
 
20
- ![演示:选中即问 → 回答带页码 → 点页码跳回 PDF 并高亮原文](docs/demo.gif)
20
+ ![新版演示:文献管理 → 选中即问(划词翻译 / 笔记)→ 页码回答 → 原文高亮 → 中文视图](docs/demo.gif)
21
21
 
22
22
  ![默认安装:官方侧栏原样,只多一行开关](https://raw.githubusercontent.com/GGboya/dsh-paper-reader/main/docs/screenshot-default.png)
23
23
 
@@ -34,12 +34,13 @@
34
34
  - 🤖 **可选教练式带读**:专用 preset 制定分步计划;你读原文、作答,AI 点评追问,当前阶段答好才继续,学习进度跨会话累积
35
35
  - 🀄 **一键中文版**:原文 ↔ 纯中文原地切换,译文 PDF 一键导出(纯中文 / 中英对照),翻译引擎零预装自动安装
36
36
  - 📏 **长段落不截断 + 实时进度**:翻译由 `babeldoc-driver.py` 驱动 babeldoc —— 按输入估算输出预算(不再吃 babeldoc 写死的 2048),`finish_reason=length` 自动拆段重译;顶栏进度条实时显示「翻译段落 76%(521/798)」这样的阶段进度,端点拒绝关闭推理时自动降推理强度重试
37
- - 🈯 **划词翻译(公式保留)**(v1.9.0):选中点「译」出纯译文气泡;选区含公式时用 MinerU 识别的 LaTeX 替换文本层乱码、要求模型原样保留
38
- - 🖥️ **中英对照 / 分屏**(v1.9.0):并排对照页或左右分屏同步滚动,随时切换、按文献记忆
39
- - 📝 **笔记**(v1.9.0):划词仍直接弹回「选中即问」气泡(与旧版一致),气泡里新增「笔记」「全局搜索」小按钮;记过的文字下方画蓝色波浪线,鼠标停上去看笔记内容、点一下改或删;笔记窗口与查找窗同一套交互(可拖动、拖边框缩放、位置记忆),批量列表按页排序、点条目跳回原文,也可在条目上直接删除(二次确认)。笔记存在 `<文献>.notes.json`(跟文献走,换浏览器不丢)
37
+ - 🈯 **划词翻译(公式保留)**(v1.11.0):选中点「译」出纯译文气泡;选区含公式时用 MinerU 识别的 LaTeX 替换文本层乱码、要求模型原样保留
38
+ - 🖥️ **中英对照 / 分屏**(v1.11.0):并排对照页或左右分屏同步滚动,随时切换、按文献记忆
39
+ - 📝 **笔记**(v1.11.0):划词仍直接弹回「选中即问」气泡(与旧版一致),气泡里新增「笔记」「全局搜索」小按钮;记过的文字下方画蓝色波浪线,鼠标停上去看笔记内容、点一下改或删;笔记窗口与查找窗同一套交互(可拖动、拖边框缩放、位置记忆),批量列表按页排序、点条目跳回原文,也可在条目上直接删除(二次确认)。笔记存在 `<文献>.notes.json`(跟文献走,换浏览器不丢)
40
40
  - ⚡ **长文档也流畅**:滚动模式只画视口附近的页、页离开视口即释放画布(其余保留等高占位,滚动条与页码始终准);原文 ↔ 中文切换只摘挂缓存好的页节点,不重新解析不重绘;切语言 / 重开论文不重传 PDF(ETag 304)。前提与已知边界见 [docs/features.md](docs/features.md)
41
41
  - 🗂️ **文献管理**:专题/论文在文件名上原地改名,论文可跨专题移动;删除进回收站可恢复
42
- - 🛰️ **OpenCode Go 端点**(v1.9.0):翻译端点供应商预设新增「OpenCode Go」(订阅后复制 API Key 即用,模型名以控制台为准);对 opencode.ai 域的请求自动带稳定 `x-opencode-session` 会话头(同一篇论文的整篇与划词共用同一 ID、跨重启稳定,ID 由本机 0600 secret 派生不含论文名),其它端点不多发任何头
42
+ - 🛰️ **OpenCode Go 端点**(v1.11.0):翻译端点供应商预设新增「OpenCode Go」(订阅后复制 API Key 即用,模型名以控制台为准);对 opencode.ai 域的请求自动带稳定 `x-opencode-session` 会话头(同一篇论文的整篇与划词共用同一 ID、跨重启稳定,ID 由本机 0600 secret 派生不含论文名),其它端点不多发任何头
43
+ - 🔀 **翻译模型可跟随也可覆盖**:默认直接跟随 Harness 当前模型(含账号授权,不需要复制 Key);需要专门翻译模型时,可在「设置 → 论文伴读 → 全文翻译模型」选择预设厂商、从官方链接申请 Key、自动获取模型。自定义只作用于翻译,切回跟随时配置仍保留,绝不改写 Harness 设置
43
44
  - ➕ **可选增强**(默认关):MinerU 解析——扫描件可读、公式可点引用可检索;嵌入端点——大白话命中术语段落
44
45
 
45
46
  各功能的前提与配置细节见 [docs/features.md](docs/features.md)。
@@ -79,7 +80,7 @@ dsh plugin --profile web add @ggboy123/dsh-paper-reader@latest # 升级也是
79
80
  1. **进入**:侧栏底部点「📚 论文伴读」(再点还原)
80
81
  2. **入库**:+ 新建专题 → ⬆ 上传 PDF
81
82
  3. **读 + 问**:直接提问(回答自带页码),或选中文字弹框提问;点「第 N 页」跳回原文
82
- 4. **中文版**:顶栏「中」一键生成(首次需在弹出表单里配一次 OpenAI 兼容端点,DeepSeek/GLM/Kimi 的 key 都行)
83
+ 4. **中文版**:顶栏「中」一键生成,默认跟随 Harness 当前模型;需要专用翻译模型时在「设置 → 论文伴读 → 全文翻译模型」里单独配置
83
84
  5. **管理**:行悬停点「⋯」,文件名原地改名(Enter 保存 / Esc 取消),论文可移动到其它专题,也可删除;对话头部 🕐 历史、+ 新开
84
85
 
85
86
  ## 文献管理(安全说明)
@@ -0,0 +1,204 @@
1
+ // harness-translate.ts — 把 Harness 当前模型临时适配成 BabelDOC 需要的 OpenAI 补全端点。
2
+ //
3
+ // 不读取、复制或修改 Harness 的凭据:每次请求直接走 ctx.llm,provider/model 来自
4
+ // agentDefaultModel.currentSelection()。HTTP 服务只监听 127.0.0.1 的随机端口,使用一次性
5
+ // 随机 token,并随一次划词翻译或一个 BabelDOC 任务关闭。
6
+ import { randomUUID } from 'node:crypto';
7
+ import { createServer } from 'node:http';
8
+ export function currentHarnessModel(defaults, llm) {
9
+ if (!defaults || !llm)
10
+ return null;
11
+ const selected = defaults.currentSelection();
12
+ if (!selected?.provider || !selected?.model)
13
+ return null;
14
+ const provider = llm.listProviders().find((p) => p.id === selected.provider);
15
+ if (!provider)
16
+ return null;
17
+ return { provider: selected.provider, providerName: provider.name || selected.provider, model: selected.model };
18
+ }
19
+ function sendJson(res, status, body) {
20
+ const data = Buffer.from(JSON.stringify(body), 'utf8');
21
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': data.length });
22
+ res.end(data);
23
+ }
24
+ function openAiError(status, message) {
25
+ return { error: { message, type: status === 401 ? 'authentication_error' : 'invalid_request_error' } };
26
+ }
27
+ async function readJson(req) {
28
+ const chunks = [];
29
+ let size = 0;
30
+ for await (const raw of req) {
31
+ const chunk = raw;
32
+ size += chunk.length;
33
+ if (size > 4 * 1024 * 1024)
34
+ throw new Error('请求体超过 4 MiB 限制');
35
+ chunks.push(chunk);
36
+ }
37
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
38
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
39
+ throw new Error('请求体必须是 JSON 对象');
40
+ return parsed;
41
+ }
42
+ function textOf(content) {
43
+ if (typeof content === 'string')
44
+ return content;
45
+ if (!Array.isArray(content))
46
+ throw new Error('消息 content 必须是文本');
47
+ return content.map((part) => {
48
+ if (typeof part === 'string')
49
+ return part;
50
+ if (typeof part === 'object' && part !== null && part.type === 'text' && typeof part.text === 'string') {
51
+ return part.text;
52
+ }
53
+ throw new Error('临时翻译适配只支持文本消息');
54
+ }).join('');
55
+ }
56
+ function requestMessages(body) {
57
+ if (!Array.isArray(body['messages']) || body['messages'].length === 0)
58
+ throw new Error('messages 不能为空');
59
+ const system = [];
60
+ const messages = [];
61
+ for (const raw of body['messages']) {
62
+ if (typeof raw !== 'object' || raw === null)
63
+ throw new Error('消息必须是对象');
64
+ const message = raw;
65
+ if (message.role === 'system' || message.role === 'developer') {
66
+ system.push(textOf(message.content));
67
+ continue;
68
+ }
69
+ // BabelDOC 与划词翻译只发送 system/user;不悄悄把 assistant/tool 历史改成用户输入。
70
+ if (message.role !== 'user')
71
+ throw new Error('临时翻译适配只支持 system 与 user 消息');
72
+ messages.push({ role: 'user', content: [{ type: 'text', text: textOf(message.content) }] });
73
+ }
74
+ if (!messages.length)
75
+ throw new Error('至少需要一条 user 消息');
76
+ return { ...(system.length ? { system: system.join('\n\n') } : {}), messages };
77
+ }
78
+ /** 为一次翻译操作开启临时本地端点;close() 必须且只需调用一次。 */
79
+ export async function openHarnessTranslationBridge(llm, selected) {
80
+ const token = randomUUID();
81
+ const controllers = new Set();
82
+ let closing = false;
83
+ const server = createServer((req, res) => {
84
+ void (async () => {
85
+ const pathname = new URL(req.url ?? '/', 'http://127.0.0.1').pathname;
86
+ if (req.method !== 'POST' || !['/v1/chat/completions', '/chat/completions'].includes(pathname)) {
87
+ sendJson(res, 404, openAiError(404, 'Not found'));
88
+ return;
89
+ }
90
+ if (closing || req.headers.authorization !== `Bearer ${token}`) {
91
+ sendJson(res, 401, openAiError(401, 'Invalid translation bridge credential'));
92
+ return;
93
+ }
94
+ const controller = new AbortController();
95
+ controllers.add(controller);
96
+ res.on('close', () => { if (!res.writableEnded)
97
+ controller.abort(); });
98
+ try {
99
+ const body = await readJson(req);
100
+ if (body['stream'] === true)
101
+ throw new Error('临时翻译适配只支持非流式补全');
102
+ if (typeof body['model'] === 'string' && body['model'] !== selected.model)
103
+ throw new Error('请求模型与 Harness 当前选择不一致');
104
+ const { system, messages } = requestMessages(body);
105
+ const parts = new Map();
106
+ let finish = 'stop';
107
+ let usage;
108
+ let failure;
109
+ for await (const chunk of llm.stream({
110
+ provider: selected.provider,
111
+ model: selected.model,
112
+ messages,
113
+ ...(system !== undefined ? { system } : {}),
114
+ ...(typeof body['temperature'] === 'number' ? { temperature: body['temperature'] } : {}),
115
+ ...(typeof body['max_tokens'] === 'number' ? { maxTokens: body['max_tokens'] } : {}),
116
+ ...(typeof body['stop'] === 'string' ? { stop: [body['stop']] } : Array.isArray(body['stop']) ? { stop: body['stop'].filter((s) => typeof s === 'string') } : {}),
117
+ signal: controller.signal,
118
+ })) {
119
+ if (chunk.type === 'text-delta' && typeof chunk.index === 'number' && typeof chunk.text === 'string') {
120
+ parts.set(chunk.index, (parts.get(chunk.index) ?? '') + chunk.text);
121
+ }
122
+ else if (chunk.type === 'block-end' && typeof chunk.index === 'number' && chunk.block?.type === 'text' && !parts.has(chunk.index)) {
123
+ parts.set(chunk.index, chunk.block.text ?? '');
124
+ }
125
+ else if (chunk.type === 'usage') {
126
+ usage = chunk.usage;
127
+ }
128
+ else if (chunk.type === 'finish') {
129
+ if (chunk.reason?.kind === 'error' || chunk.reason?.kind === 'aborted')
130
+ failure = chunk.reason.failure;
131
+ finish = chunk.reason?.kind === 'max-tokens' ? 'length' : 'stop';
132
+ break;
133
+ }
134
+ }
135
+ if (failure) {
136
+ const err = new Error(failure.message || 'Harness 模型调用失败');
137
+ if (typeof failure.status === 'number')
138
+ err.status = failure.status;
139
+ throw err;
140
+ }
141
+ const content = [...parts.entries()].sort(([a], [b]) => a - b).map(([, text]) => text).join('');
142
+ const promptTokens = (usage?.inputTokens ?? 0) + (usage?.cacheReadTokens ?? 0) + (usage?.cacheWriteTokens ?? 0);
143
+ const completionTokens = usage?.outputTokens ?? 0;
144
+ sendJson(res, 200, {
145
+ id: `chatcmpl-${randomUUID()}`,
146
+ object: 'chat.completion',
147
+ created: Math.floor(Date.now() / 1000),
148
+ model: selected.model,
149
+ choices: [{ index: 0, message: { role: 'assistant', content }, finish_reason: finish }],
150
+ usage: {
151
+ prompt_tokens: promptTokens,
152
+ completion_tokens: completionTokens,
153
+ total_tokens: usage?.totalTokens ?? promptTokens + completionTokens,
154
+ ...(usage?.cacheReadTokens ? { prompt_cache_hit_tokens: usage.cacheReadTokens } : {}),
155
+ },
156
+ });
157
+ }
158
+ catch (err) {
159
+ if (res.writableEnded)
160
+ return;
161
+ const aborted = controller.signal.aborted && !closing;
162
+ const status = aborted ? 499 : typeof err.status === 'number' ? Number(err.status) : 400;
163
+ const message = closing || controller.signal.aborted ? '翻译已取消' : err instanceof Error ? err.message : String(err);
164
+ sendJson(res, status, openAiError(status, message.slice(0, 500)));
165
+ }
166
+ finally {
167
+ controllers.delete(controller);
168
+ }
169
+ })().catch(() => {
170
+ if (!res.writableEnded)
171
+ sendJson(res, 500, openAiError(500, '临时翻译适配失败'));
172
+ });
173
+ });
174
+ await new Promise((resolve, reject) => {
175
+ const onError = (err) => reject(err);
176
+ server.once('error', onError);
177
+ server.listen(0, '127.0.0.1', () => {
178
+ server.off('error', onError);
179
+ resolve();
180
+ });
181
+ });
182
+ const address = server.address();
183
+ if (typeof address !== 'object' || address === null) {
184
+ server.close();
185
+ throw new Error('无法分配本地翻译端口');
186
+ }
187
+ let closed = false;
188
+ return {
189
+ endpoint: { baseUrl: `http://127.0.0.1:${address.port}/v1`, apiKey: token, model: selected.model },
190
+ provider: selected.provider,
191
+ providerName: selected.providerName,
192
+ model: selected.model,
193
+ close: async () => {
194
+ if (closed)
195
+ return;
196
+ closed = true;
197
+ closing = true;
198
+ for (const controller of controllers)
199
+ controller.abort();
200
+ server.closeAllConnections();
201
+ await new Promise((resolve) => { server.close(() => resolve()); });
202
+ },
203
+ };
204
+ }
package/dist/host.js CHANGED
@@ -12,7 +12,8 @@ import { MAX_CHUNKS, MAX_LATEX_CHARS, MAX_TEXT_CHARS, MAX_TOTAL_CHARS, Selection
12
12
  import { MineruError, sanitizeDetail } from "./mineru.js";
13
13
  import { readTranscript, transcribePaper, ScannedPdfError, ShortTextError } from "./transcribe.js";
14
14
  import { cancelTranslation, pdfVariantPath, restartTranslation, startTranslation, zhStatus } from "./translate.js";
15
- import { clearTranslateConfig, deleteTranslateEndpoint, maskApiKey, readTranslateConfig, readTranslateEndpointStore, resolveTranslateEndpoint, saveTranslateEndpoint, selectTranslateEndpoint, testTranslateEndpoint, } from "./translate-config.js";
15
+ import { clearTranslateConfig, deleteTranslateEndpoint, listTranslateModels, maskApiKey, readTranslateConfig, readTranslateEndpointStore, resolveTranslateEndpoint, saveTranslateEndpoint, selectTranslateEndpoint, testTranslateEndpoint, writeTranslateRunOptions, } from "./translate-config.js";
16
+ import { currentHarnessModel, openHarnessTranslationBridge, } from "./harness-translate.js";
16
17
  import { clearTypesafeConfig, readTypesafeConfig, resolveTypesafeConfig, testTypesafeEndpoint, writeTypesafeConfig, } from "./typesafe-config.js";
17
18
  import { clearEmbedConfig, maskApiKey as maskEmbedApiKey, readEmbedConfig, resolveEmbedConfig, testEmbedEndpoint, writeEmbedConfig, } from "./embed-config.js";
18
19
  import { clearMineruConfig, mergeMineruBody, precheckMineruConfig, resolveMineruConfig, testMineruCloud, testMineruLocal, writeMineruConfig, } from "./mineru-config.js";
@@ -74,7 +75,24 @@ export function registerRoutes(ctx, config) {
74
75
  const sessionController = ctx.sessionController;
75
76
  const workspaceController = ctx.workspaceController;
76
77
  const workspaceRegistry = ctx.workspaceRegistry;
78
+ const agentDefaultModel = ctx.agentDefaultModel;
79
+ const llm = ctx.llm;
77
80
  const dataDir = resolveDataDir(config.dataDir);
81
+ const harnessModel = () => {
82
+ try {
83
+ return currentHarnessModel(agentDefaultModel, llm);
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ };
89
+ const resolveTranslation = async (...args) => {
90
+ const resolved = await resolveTranslateEndpoint(...args);
91
+ // 测试壳 / 非完整 web profile 没有宿主模型服务时,保持原有「未配置」提示,不假称能跟随。
92
+ if (resolved.source === 'harness' && !harnessModel())
93
+ return { endpoint: {}, source: 'none' };
94
+ return resolved;
95
+ };
78
96
  // dist/host.js → 包根/reader/index.html
79
97
  const readerHtml = new URL('../reader/index.html', import.meta.url);
80
98
  const readerVendorDir = new URL('../reader/vendor/', import.meta.url);
@@ -402,6 +420,8 @@ export function registerRoutes(ctx, config) {
402
420
  return;
403
421
  }
404
422
  const mime = { '.mjs': 'text/javascript', '.js': 'text/javascript', '.css': 'text/css', '.map': 'application/json',
423
+ // 字体与厂商 SVG 都是本地打包资源,不请求第三方图标站。
424
+ '.svg': 'image/svg+xml',
405
425
  // 字体(vendored KaTeX 的 woff2 就靠这条;不给对 MIME 时某些浏览器会拒绝 @font-face)
406
426
  '.woff2': 'font/woff2', '.woff': 'font/woff', '.ttf': 'font/ttf' };
407
427
  try {
@@ -410,7 +430,7 @@ export function registerRoutes(ctx, config) {
410
430
  const type = mime[ext] ?? 'application/octet-stream';
411
431
  // 只有文本类才追加 charset:给 font/woff2 这类二进制资源加 `; charset=utf-8` 是错的
412
432
  // (实测 font/woff2 被浏览器按未知类型处理的风险;见 test/reader-vendor-http.test.mjs)
413
- const texty = type.startsWith('text/') || type === 'application/json';
433
+ const texty = type.startsWith('text/') || type === 'application/json' || type === 'image/svg+xml';
414
434
  res.writeHead(200, { 'content-type': texty ? type + '; charset=utf-8' : type, 'content-length': body.length, 'cache-control': 'no-cache' });
415
435
  res.end(body);
416
436
  }
@@ -1197,7 +1217,7 @@ export function registerRoutes(ctx, config) {
1197
1217
  catch {
1198
1218
  throw notFound('文献不存在(划词翻译需要先能定位到该文献)');
1199
1219
  }
1200
- const { endpoint, source } = await resolveTranslateEndpoint(config.translate);
1220
+ const { endpoint, source } = await resolveTranslation(config.translate);
1201
1221
  if (source === 'none') {
1202
1222
  json(res, 503, { error: '未配置翻译端点:在阅读器里点 ⚙ 填写(OpenAI 兼容端点即可)', code: 'no-endpoint' });
1203
1223
  return;
@@ -1209,7 +1229,23 @@ export function registerRoutes(ctx, config) {
1209
1229
  ? await openCodeSessionId(`paper:${ref.topic}/${ref.name}`)
1210
1230
  : '';
1211
1231
  try {
1212
- const r = await translateSelection(endpoint, asm.source, ocSession ? { openCodeSessionId: ocSession } : {});
1232
+ let r;
1233
+ if (source === 'harness') {
1234
+ const selected = harnessModel();
1235
+ if (!selected)
1236
+ throw new SelectionTranslateError('no-endpoint', 503, 'Harness 当前模型不可用,请先在 Harness 模型设置中选择模型');
1237
+ // 划词翻译只跟随本次请求开始时的选择;临时端口与 token 在请求结束立即销毁。
1238
+ const bridge = await openHarnessTranslationBridge(llm, selected);
1239
+ try {
1240
+ r = await translateSelection(bridge.endpoint, asm.source);
1241
+ }
1242
+ finally {
1243
+ await bridge.close();
1244
+ }
1245
+ }
1246
+ else {
1247
+ r = await translateSelection(endpoint, asm.source, ocSession ? { openCodeSessionId: ocSession } : {});
1248
+ }
1213
1249
  json(res, 200, {
1214
1250
  translation: r.translation,
1215
1251
  model: r.model,
@@ -1328,16 +1364,18 @@ export function registerRoutes(ctx, config) {
1328
1364
  // 中文版状态:zh=纯中文 dual=中英对照 busy=翻译中。
1329
1365
  // 顺带返回生效端点的脱敏信息,让 UI 能回答「正在用哪个模型/key 翻」——key 只给掩码。
1330
1366
  if (sub === '/api/zh' && req.method === 'GET') {
1331
- const { endpoint, source } = await resolveTranslateEndpoint(config.translate);
1367
+ const { endpoint, source } = await resolveTranslation(config.translate);
1368
+ const followed = source === 'harness' ? harnessModel() : null;
1332
1369
  json(res, 200, {
1333
1370
  ...zhStatus(locate(url)),
1334
- model: endpoint.model ?? null,
1335
- apiKeyHint: endpoint.apiKey ? maskApiKey(endpoint.apiKey) : null,
1371
+ model: followed?.model ?? endpoint.model ?? null,
1372
+ provider: followed?.providerName ?? null,
1373
+ apiKeyHint: source === 'harness' ? '由 Harness 管理' : endpoint.apiKey ? maskApiKey(endpoint.apiKey) : null,
1336
1374
  endpointSource: source,
1337
1375
  });
1338
1376
  return;
1339
1377
  }
1340
- // 启动后台翻译(幂等;force=true 为重翻:先删已有译文再启动)。端点:UI 里填的 > profile 的 translate
1378
+ // 启动后台翻译(幂等;force=true 为重翻:先删已有译文再启动)。默认 Harness,显式 file/profile 为翻译专用覆盖。
1341
1379
  if (sub === '/api/zh/generate' && req.method === 'POST') {
1342
1380
  const body = (await readBody(req));
1343
1381
  let ref;
@@ -1350,17 +1388,34 @@ export function registerRoutes(ctx, config) {
1350
1388
  return;
1351
1389
  throw err;
1352
1390
  }
1353
- const { endpoint, source } = await resolveTranslateEndpoint(config.translate, undefined, body.endpointId);
1391
+ const { endpoint, source } = await resolveTranslation(config.translate, undefined, body.endpointId);
1354
1392
  if (body.endpointId && source === 'none') {
1355
1393
  json(res, 400, { error: '所选翻译端点不存在或配置不完整,请重新选择', code: 'endpoint-not-found' });
1356
1394
  return;
1357
1395
  }
1358
1396
  if (body.endpointId && source !== 'none')
1359
1397
  await selectTranslateEndpoint(body.endpointId);
1360
- const r = body.force
1361
- ? await restartTranslation(ref, dataDir, endpoint)
1362
- : await startTranslation(ref, dataDir, endpoint);
1363
- json(res, r.started ? 200 : 409, r);
1398
+ const followed = source === 'harness' ? harnessModel() : null;
1399
+ if (source === 'harness' && !followed) {
1400
+ json(res, 503, { error: 'Harness 当前模型不可用,请先在 Harness 模型设置中选择模型', code: 'no-endpoint' });
1401
+ return;
1402
+ }
1403
+ const bridge = followed ? await openHarnessTranslationBridge(llm, followed) : null;
1404
+ const hooks = bridge ? { onFinish: bridge.close } : {};
1405
+ const runOptions = (await readTranslateEndpointStore()).options;
1406
+ try {
1407
+ // 整篇 PDF 在任务开始时固定 provider/model;运行期间换 Harness 模型不会把任务切成两套模型。
1408
+ const r = body.force
1409
+ ? await restartTranslation(ref, dataDir, bridge?.endpoint ?? endpoint, hooks, runOptions)
1410
+ : await startTranslation(ref, dataDir, bridge?.endpoint ?? endpoint, hooks, runOptions);
1411
+ if (!r.started)
1412
+ await bridge?.close();
1413
+ json(res, r.started ? 200 : 409, r);
1414
+ }
1415
+ catch (err) {
1416
+ await bridge?.close();
1417
+ throw err;
1418
+ }
1364
1419
  return;
1365
1420
  }
1366
1421
  // 取消在途翻译:立即允许重新生成;旧进程回调由任务序号隔离,不得覆盖后续任务。
@@ -1382,11 +1437,14 @@ export function registerRoutes(ctx, config) {
1382
1437
  // ── 翻译端点配置(阅读器浮层的读写口)─────────────────────────────
1383
1438
  // GET 只回显掩码 key:明文永不离开服务端
1384
1439
  if (sub === '/api/translate/config' && req.method === 'GET') {
1385
- const { endpoint, source } = await resolveTranslateEndpoint(config.translate);
1440
+ const { endpoint, source } = await resolveTranslation(config.translate);
1386
1441
  const store = await readTranslateEndpointStore();
1442
+ const followed = harnessModel();
1387
1443
  const endpoints = store.endpoints.map((e) => ({
1388
1444
  id: e.id,
1389
1445
  label: e.label ?? '',
1446
+ provider: e.provider ?? '',
1447
+ providerName: '',
1390
1448
  baseUrl: e.baseUrl ?? '',
1391
1449
  model: e.model ?? '',
1392
1450
  hasApiKey: Boolean(e.apiKey),
@@ -1396,21 +1454,76 @@ export function registerRoutes(ctx, config) {
1396
1454
  }));
1397
1455
  if (config.translate?.baseUrl && config.translate.apiKey && config.translate.model) {
1398
1456
  endpoints.push({
1399
- id: 'profile', label: 'profile 默认配置', baseUrl: config.translate.baseUrl, model: config.translate.model,
1457
+ id: 'profile', label: 'profile 默认配置', provider: 'custom', providerName: '', baseUrl: config.translate.baseUrl, model: config.translate.model,
1400
1458
  hasApiKey: true, apiKeyHint: maskApiKey(config.translate.apiKey), complete: true, source: 'profile',
1401
1459
  });
1402
1460
  }
1461
+ if (followed) {
1462
+ endpoints.unshift({
1463
+ id: 'harness', label: '跟随 Harness', provider: 'harness', baseUrl: '', model: followed.model,
1464
+ providerName: followed.providerName, hasApiKey: true, apiKeyHint: '由 Harness 管理', complete: true, source: 'harness',
1465
+ });
1466
+ }
1403
1467
  json(res, 200, {
1404
1468
  baseUrl: endpoint.baseUrl ?? '',
1405
- model: endpoint.model ?? '',
1406
- hasApiKey: Boolean(endpoint.apiKey),
1407
- apiKeyHint: endpoint.apiKey ? maskApiKey(endpoint.apiKey) : '',
1469
+ model: followed && source === 'harness' ? followed.model : endpoint.model ?? '',
1470
+ hasApiKey: source === 'harness' ? true : Boolean(endpoint.apiKey),
1471
+ apiKeyHint: source === 'harness' ? '由 Harness 管理' : endpoint.apiKey ? maskApiKey(endpoint.apiKey) : '',
1408
1472
  source,
1409
- activeId: source === 'none' ? null : source === 'profile' ? 'profile' : store.activeId,
1473
+ mode: source === 'harness' || store.activeId === 'harness' ? 'follow' : 'custom',
1474
+ options: store.options,
1475
+ harness: followed,
1476
+ activeId: source === 'harness' ? 'harness' : source === 'none' ? null : source === 'profile' ? 'profile' : store.activeId,
1410
1477
  endpoints,
1411
1478
  });
1412
1479
  return;
1413
1480
  }
1481
+ // 整篇 PDF 的运行参数:上下文拆段、输出预算与 QPS;不含端点或凭据。
1482
+ if (sub === '/api/translate/config/options' && req.method === 'POST') {
1483
+ const body = await readBody(req);
1484
+ try {
1485
+ const options = await writeTranslateRunOptions(body);
1486
+ json(res, 200, { ok: true, options });
1487
+ }
1488
+ catch (err) {
1489
+ json(res, 400, { error: err instanceof Error ? err.message : String(err) });
1490
+ }
1491
+ return;
1492
+ }
1493
+ // 只切换翻译来源,不删除专用端点,也绝不调用 Harness 的 saveSelection。
1494
+ if (sub === '/api/translate/config/selection' && req.method === 'POST') {
1495
+ const body = (await readBody(req));
1496
+ const id = body.id?.trim() ?? '';
1497
+ if (!id) {
1498
+ json(res, 400, { error: '请选择翻译模型来源' });
1499
+ return;
1500
+ }
1501
+ try {
1502
+ await selectTranslateEndpoint(id);
1503
+ }
1504
+ catch {
1505
+ json(res, 400, { error: '所选翻译端点不存在,请重新选择', code: 'endpoint-not-found' });
1506
+ return;
1507
+ }
1508
+ json(res, 200, { ok: true, id });
1509
+ return;
1510
+ }
1511
+ // 填 Key 后自动发现模型:只读 /models,Key 可沿用正在编辑的已保存端点。
1512
+ if (sub === '/api/translate/models' && req.method === 'POST') {
1513
+ const body = (await readBody(req));
1514
+ const store = await readTranslateEndpointStore();
1515
+ const editing = body.id && body.id !== 'new' ? store.endpoints.find((e) => e.id === body.id) : undefined;
1516
+ const result = await listTranslateModels({
1517
+ baseUrl: body.baseUrl?.trim() || editing?.baseUrl || '',
1518
+ apiKey: body.apiKey?.trim() || editing?.apiKey || '',
1519
+ });
1520
+ if (!result.ok) {
1521
+ json(res, 400, { error: `获取模型失败:${result.detail ?? '未知原因'}`, code: 'models-unavailable' });
1522
+ return;
1523
+ }
1524
+ json(res, 200, { ok: true, models: result.models });
1525
+ return;
1526
+ }
1414
1527
  // POST:校验 → 预检 → 通了才落盘。key 填错在这里就拦下,
1415
1528
  // 不让它拖到 babeldoc 跑几分钟后才异步失败。
1416
1529
  if (sub === '/api/translate/config' && req.method === 'POST') {
@@ -1441,7 +1554,7 @@ export function registerRoutes(ctx, config) {
1441
1554
  json(res, 400, { error: `连接测试失败:${test.detail ?? '未知原因'}` });
1442
1555
  return;
1443
1556
  }
1444
- const saved = await saveTranslateEndpoint({ baseUrl, apiKey, model }, { ...(body.id ? { id: body.id } : {}), ...(body.label ? { label: body.label } : {}) });
1557
+ const saved = await saveTranslateEndpoint({ baseUrl, apiKey, model }, { ...(body.id ? { id: body.id } : {}), ...(body.label ? { label: body.label } : {}), ...(body.provider ? { provider: body.provider } : {}) });
1445
1558
  json(res, 200, { ok: true, id: saved.id });
1446
1559
  return;
1447
1560
  }
package/dist/index.js CHANGED
@@ -11,7 +11,8 @@ export function apply(ctx, config = {}) {
11
11
  console.log(`[dsh-paper-reader] registered tools: list_papers, transcribe_pdf, search_paper, study_progress, study_update`);
12
12
  // webServer 是可选服务(web profile 有,headless 没有):出现时再挂路由。
13
13
  // connection/sessionController/workspaceController/workspaceRegistry 同属 web profile(cordis 要求访问前先声明 inject)。
14
- ctx.inject(['webServer', 'connection', 'sessionController', 'workspaceController', 'workspaceRegistry'], (rctx) => {
14
+ // agentDefaultModel + llm 用于「全文翻译默认跟随 Harness」:只读当前选择并调用,不写宿主配置。
15
+ ctx.inject(['webServer', 'connection', 'sessionController', 'workspaceController', 'workspaceRegistry', 'agentDefaultModel', 'llm'], (rctx) => {
15
16
  registerRoutes(rctx, config);
16
17
  });
17
18
  }