@ggboy123/dsh-paper-reader 0.6.2 → 1.1.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
@@ -1,11 +1,20 @@
1
1
  # dsh-paper-reader
2
2
 
3
+ [![npm version](https://img.shields.io/npm/v/@ggboy123/dsh-paper-reader)](https://www.npmjs.com/package/@ggboy123/dsh-paper-reader)
4
+ [![npm downloads](https://img.shields.io/npm/dm/@ggboy123/dsh-paper-reader)](https://www.npmjs.com/package/@ggboy123/dsh-paper-reader)
5
+ [![license](https://img.shields.io/github/license/GGboya/dsh-paper-reader)](https://github.com/GGboya/dsh-paper-reader/blob/main/LICENSE)
6
+ [![GitHub stars](https://img.shields.io/github/stars/GGboya/dsh-paper-reader?style=social)](https://github.com/GGboya/dsh-paper-reader/stargazers)
7
+
8
+ **English**: [README_EN.md](README_EN.md)
9
+
3
10
  [DeepSeek Harness (dsh)](https://github.com/deepseek-ai/deepseek-harness) 插件:论文伴读工作台 —— PDF 转录 / 检索 + 原生对话伴读 + 内置阅读器。
4
11
 
5
12
  功能迁移自本地独立产品 pdfqa(Go 实现的论文伴读工具)。原则:agent 循环 / 模型层 / 会话持久化全部交给 dsh 框架,插件只做「转录 + 检索 + 阅读器 UI」的薄壳组合。
6
13
 
7
14
  **安装后不改动官方界面** —— 侧栏底部多一行「📚 论文伴读」开关,点击才进入伴读模式(左侧变为文献库树),再点即还原官方工作区列表:
8
15
 
16
+ ![演示:选中即问 → 回答带页码 → 点页码跳回 PDF 并高亮原文](docs/demo.gif)
17
+
9
18
  ![默认安装:官方侧栏原样,只多一行开关](https://raw.githubusercontent.com/GGboya/dsh-paper-reader/main/docs/screenshot-default.png)
10
19
 
11
20
  ![伴读模式:文献库 + PDF 阅读器 + 原生对话](https://raw.githubusercontent.com/GGboya/dsh-paper-reader/main/docs/screenshot-reading.png)
@@ -19,11 +28,25 @@
19
28
  - 📖 **PDF 阅读器居中**:中间是论文(PDF.js 缩放 / Retina 高清 / 文本层选择 / 适宽模式),最右是该论文的原生对话 —— 视觉换位实现,列宽拖拽/折叠仍是 dsh 原生行为,关掉 PDF 页签即还原官方布局
20
29
  - 💬 **选中即问**:阅读器里选中文字 → 弹出提问框 → 注入当前会话,原生对话区实时回答
21
30
  - 📍 **引用定位**:回答里的「第 N 页」可点击,平滑跳回 PDF 对应页并闪烁
22
- - 🀄 **中英切换**:顶栏「中」按钮原文 ↔ 纯中文切换;无译文时一键后台生成(babeldoc),生成需配置 `translate` 端点;**无需预装 Python**——首次生成时自动下载 uv + 托管 Python + babeldoc(macOS/Linux,约几分钟),全程落在用户目录
23
- - 🔍 **PDF 转录 + 检索**:本地提取(pdf.js,纯 Node 无需 Python),页眉页脚剔除 / 连字 / 断词愈合 / 段落重排,产出页码偏移表;兼容 pdfqa 的 `data/` 缓存布局(旧缓存读取时自动补建页码索引)
31
+ - 🀄 **中英切换**:顶栏「中」按钮原文 ↔ 纯中文切换;无译文时一键后台生成(babeldoc),生成需配置 `translate` 端点;**无需预装 Python**——首次生成时自动下载 uv + 托管 Python + babeldoc(macOS / Linux / Windows,约几分钟),全程落在用户目录
32
+ - 🔍 **PDF 转录 + 检索**:本地提取(pdf.js,纯 Node 无需 Python),页眉页脚剔除 / 连字 / 断词愈合 / 段落重排,产出页码偏移表;可选接入 TypeSafe/Jev 语义重排(设置面板填端点即启用,不配置时退回纯关键词排序);兼容 pdfqa 的 `data/` 缓存布局(旧缓存读取时自动补建页码索引)
24
33
 
25
34
  ## 安装
26
35
 
36
+ ### 方式一:DSH Desktop(零环境,推荐普通用户)
37
+
38
+ [DSH Desktop](https://github.com/anywhere-labs/dsh-desktop) 是社区的 DeepSeek Harness 桌面客户端(macOS / Windows,开箱即用,不需要装 Node.js):
39
+
40
+ 1. 下载安装 DSH Desktop 并启动
41
+ 2. 托盘菜单 → **Open DSH Terminal**(终端里自带 `dsh`/`pnpm`,只对那个终端生效)
42
+ 3. 执行 `dsh plugin add @ggboy123/dsh-paper-reader@1.1.0`
43
+ 4. 退出并重开 DSH Desktop(插件变更要重启才进 Loader 组合)
44
+
45
+ > 已在 DSH Desktop 2.0.13(内置 dsh 0.1.5-rc.2)上实测通过:侧栏文献库、PDF 阅读器、选中即问、页码跳转、原生对话伴读、翻译引擎自动安装(uv + Python + babeldoc 全程落在用户目录)全部可用。
46
+ > 注意:Desktop 的 `desktop` profile 被 Electron 独占管理,外部 CLI 直接 `dsh plugin --profile desktop add` 会被拒(`managed exclusively by the Electron application`)——必须从 Desktop 自己的终端进。
47
+
48
+ ### 方式二:命令行 dsh(开发者)
49
+
27
50
  ```bash
28
51
  dsh plugin --profile web add @ggboy123/dsh-paper-reader
29
52
  ```
@@ -31,6 +54,23 @@ dsh plugin --profile web add @ggboy123/dsh-paper-reader
31
54
  > npm 包名走 `@ggboy123` 作用域:裸名 `dsh-paper-reader` 已被另一个插件占用(那是「输入文献、吐精读报告」的一次性分析工具,与本插件的「阅读器 + 会话伴读」定位不同)。
32
55
  > 不要用 `github:GGboya/dsh-paper-reader` 安装 —— dist 不入库,git 安装会导致 profile 起不来(构建产物只随 npm 包分发)。
33
56
 
57
+ ### 升级
58
+
59
+ **已装过的用户升级必须带显式版本号**——不带版本的 `add` 对已存在的依赖是 no-op(pnpm 按首次安装时记录的版本范围解析,不会追新):
60
+
61
+ ```bash
62
+ dsh plugin --profile web add @ggboy123/dsh-paper-reader@1.1.0
63
+ # 重启 dsh web 生效;浏览器 Cmd+Shift+R 强刷,避免旧阅读器页面缓存
64
+ ```
65
+
66
+ 确认当前装的是哪个版本:
67
+
68
+ ```bash
69
+ grep '"version"' ~/.dsh/profiles/web/node_modules/@ggboy123/dsh-paper-reader/package.json
70
+ ```
71
+
72
+ > pnpm 若开了供应链策略 `minimumReleaseAge`(发布 N 小时内的新包拒装):要么等过窗口期,要么在 `~/.dsh/profiles/web/.npmrc` 加一行 `minimum-release-age-exclude[]=@ggboy123/dsh-paper-reader`(只豁免本插件,不动全局策略)。
73
+
34
74
  本地开发:
35
75
 
36
76
  ```bash
@@ -58,7 +98,7 @@ dsh --profile web # 侧栏变为文献库树
58
98
  >
59
99
  > 翻译引擎**零预装**:找不到 babeldoc 时自动走 uv 链路安装——uv 独立二进制(GitHub Releases API 下载 + sha256 校验)→
60
100
  > uv 托管 Python 3.12 → `uv pip install babeldoc`,落在 `~/.dsh/.dsh-paper-reader/bin/` 与文献库同级 `.venv-pdf2zh/`,
61
- > 不碰系统 Python。已装有 uv / babeldoc(含 pdfqa 的 `.venv-pdf2zh`)则直接复用。Windows 暂不支持自动安装,需手动装 uv 后重试。
101
+ > 不碰系统 Python。已装有 uv / babeldoc(含 pdfqa 的 `.venv-pdf2zh`)则直接复用。macOS / Linux / Windows 均支持自动安装(Windows 走 uv 的 zip 包 + 系统自带 tar 解包)。
62
102
 
63
103
  > 伴读模式是**按需开启**的:默认不注册 `sidebar.workspaces`(官方工作区/会话列表原样),侧栏底部「📚 论文伴读」开关点击才接管,再点还原;模式选择记在 localStorage。退出模式时已打开的 PDF 页签和伴读会话不受影响。
64
104
 
@@ -77,6 +117,8 @@ src/
77
117
  translate.ts 纯函数:babeldoc 调用(中文/中英对照 PDF 生成)
78
118
  babeldoc-install.ts 纯函数:无 Python 环境时自动安装 babeldoc(uv → 托管 Python → venv)
79
119
  translate-config.ts 纯函数:翻译端点配置读写($DSH_HOME 下 0600)+ 保存前连接预检
120
+ rerank.ts 纯函数:search_paper 语义重排(TypeSafe/Jev,无凭据时退回关键词排序)
121
+ typesafe-config.ts 纯函数:TypeSafe 端点配置读写(与翻译配置同一套约定)
80
122
  preset.ts 纯函数:自带 agent preset 安装到 $DSH_HOME/.agent-presets/
81
123
  presets/paper-reader/ 「论文伴读」agent preset(persona 完整提示词 + compaction)
82
124
  reader/index.html 阅读器页面(pdf.js,独立于 React 宿主,iframe 承载)
@@ -3,20 +3,25 @@
3
3
  // 链路:uv 独立二进制(GitHub Releases,带 sha256 校验)
4
4
  // → `uv venv`(uv 自动下载托管 Python,系统没有 Python 也能跑)
5
5
  // → `uv pip install babeldoc`
6
- // 全部落在用户目录:uv 二进制在 <dshHome>/.dsh-paper-reader/bin/uv,
6
+ // 全部落在用户目录:uv 二进制在 <dshHome>/.dsh-paper-reader/bin/uv(win32 为 uv.exe),
7
7
  // venv 在 文献库同级 .venv-pdf2zh(必须与 translate.ts findBabeldoc 的第一候选位一致),
8
- // 不碰系统 Python、不需要 sudo。win32 不在支持范围(tar 解 zip、exe 后缀都要分叉),直接给手动指引。
8
+ // 不碰系统 Python、不需要 sudo。
9
+ // win32 差异:uv 发 zip 而非 tar.gz(Win10 1803+ 自带 bsdtar 可解 zip,tar -xf 通吃两种格式)、
10
+ // exe 后缀、venv 用 Scripts/ 而非 bin/、PATH 查找用 where 替代 which、不需要 chmod。
9
11
  import { execFile } from 'node:child_process';
10
12
  import { createHash } from 'node:crypto';
11
13
  import { existsSync } from 'node:fs';
12
14
  import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises';
13
15
  import { dirname, join } from 'node:path';
14
16
  import { homedir } from 'node:os';
17
+ const isWin = process.platform === 'win32';
15
18
  /** uv 发布的 target triple;不支持的平台返回 null(给手动安装指引)。 */
16
19
  function uvTriple() {
17
20
  const { platform, arch } = process;
18
21
  if (platform === 'darwin')
19
22
  return arch === 'arm64' ? 'aarch64-apple-darwin' : 'x86_64-apple-darwin';
23
+ if (platform === 'win32')
24
+ return arch === 'arm64' ? 'aarch64-pc-windows-msvc' : 'x86_64-pc-windows-msvc';
20
25
  // musl 静态构建:不依赖系统 glibc 版本,最省心
21
26
  if (platform === 'linux') {
22
27
  if (arch === 'x64')
@@ -43,13 +48,14 @@ function run(cmd, args, opts = {}) {
43
48
  });
44
49
  }
45
50
  async function whichOk(cmd) {
51
+ // win32 没有 which,用 where(两者都找不到时都只是跳下一个候选,不算错误)
46
52
  return new Promise((res) => {
47
- execFile('which', [cmd], (err, stdout) => res(!err && stdout.trim() !== ''));
53
+ execFile(isWin ? 'where' : 'which', [cmd], (err, stdout) => res(!err && stdout.trim() !== ''));
48
54
  });
49
55
  }
50
56
  /** 插件托管的 uv 位置(不落系统目录,删插件目录即清干净)。 */
51
57
  export function uvPath(home) {
52
- return join(home, '.dsh-paper-reader', 'bin', 'uv');
58
+ return join(home, '.dsh-paper-reader', 'bin', isWin ? 'uv.exe' : 'uv');
53
59
  }
54
60
  /** 找 uv:插件托管 → PATH → 常见安装位。 */
55
61
  async function findUv(home) {
@@ -58,7 +64,10 @@ async function findUv(home) {
58
64
  return own;
59
65
  if (await whichOk('uv'))
60
66
  return 'uv';
61
- for (const c of [join(homedir(), '.local', 'bin', 'uv'), join(homedir(), '.cargo', 'bin', 'uv')]) {
67
+ const candidates = isWin
68
+ ? [join(homedir(), '.local', 'bin', 'uv.exe')]
69
+ : [join(homedir(), '.local', 'bin', 'uv'), join(homedir(), '.cargo', 'bin', 'uv')];
70
+ for (const c of candidates) {
62
71
  if (existsSync(c))
63
72
  return c;
64
73
  }
@@ -75,7 +84,7 @@ async function downloadUv(home, onPhase) {
75
84
  if (!triple) {
76
85
  throw new Error(`当前平台(${process.platform}/${process.arch})暂不支持自动安装:请手动安装 uv(https://docs.astral.sh/uv/)后重试`);
77
86
  }
78
- const want = `uv-${triple}.tar.gz`;
87
+ const want = isWin ? `uv-${triple}.zip` : `uv-${triple}.tar.gz`;
79
88
  const tmp = join(home, '.dsh-paper-reader', 'bin', `.uv-install-${Date.now()}`);
80
89
  await mkdir(tmp, { recursive: true });
81
90
  try {
@@ -110,15 +119,18 @@ async function downloadUv(home, onPhase) {
110
119
  const actual = createHash('sha256').update(body).digest('hex');
111
120
  if (actual !== expect)
112
121
  throw new Error('uv 下载文件校验和不匹配,已丢弃(请重试)');
113
- const tgzPath = join(tmp, 'uv.tar.gz');
114
- await writeFile(tgzPath, body);
115
- await run('tar', ['-xzf', tgzPath, '-C', tmp], { timeout: 60_000 });
116
- const extracted = join(tmp, `uv-${triple}`, 'uv');
122
+ const pkgPath = join(tmp, isWin ? 'uv.zip' : 'uv.tar.gz');
123
+ await writeFile(pkgPath, body);
124
+ // 不带 -z:bsdtar(macOS 自带 / Win10 1803+ 的 tar.exe)和 GNU tar 解包时都自动探测格式,
125
+ // 同一条命令通吃 tar.gz 与 zip(win32 的 uv 只发 zip)
126
+ await run('tar', ['-xf', pkgPath, '-C', tmp], { timeout: 60_000 });
127
+ const extracted = join(tmp, `uv-${triple}`, isWin ? 'uv.exe' : 'uv');
117
128
  if (!existsSync(extracted))
118
129
  throw new Error('uv 解包结果不符合预期');
119
130
  const dst = uvPath(home);
120
131
  await rename(extracted, dst);
121
- await chmod(dst, 0o755);
132
+ if (!isWin)
133
+ await chmod(dst, 0o755); // win32 无可执行位概念
122
134
  return dst;
123
135
  }
124
136
  finally {
@@ -130,10 +142,11 @@ async function installBabeldoc(uv, venvDir, onPhase) {
130
142
  onPhase('正在安装翻译引擎(2/3 安装 Python)…');
131
143
  // --python-preference only-managed:不碰用户系统里可能残缺/带 externally-managed 标记的 Python
132
144
  await run(uv, ['venv', venvDir, '--python', '3.12', '--python-preference', 'only-managed'], { timeout: 10 * 60_000 });
133
- const py = join(venvDir, 'bin', 'python');
145
+ // win32 venv 用 Scripts/ 而非 bin/,可执行文件带 .exe
146
+ const py = isWin ? join(venvDir, 'Scripts', 'python.exe') : join(venvDir, 'bin', 'python');
134
147
  onPhase('正在安装翻译引擎(3/3 安装 babeldoc,首次约几分钟)…');
135
148
  await run(uv, ['pip', 'install', '--python', py, 'babeldoc'], { timeout: 20 * 60_000 });
136
- const bin = join(venvDir, 'bin', 'babeldoc');
149
+ const bin = isWin ? join(venvDir, 'Scripts', 'babeldoc.exe') : join(venvDir, 'bin', 'babeldoc');
137
150
  if (!existsSync(bin))
138
151
  throw new Error('babeldoc 安装完成但未找到可执行文件');
139
152
  return bin;
package/dist/host.js CHANGED
@@ -8,6 +8,7 @@ import { listPapers, listTopics, resolveDataDir, resolvePaper } from "./library.
8
8
  import { readTranscript, transcribePaper } from "./transcribe.js";
9
9
  import { pdfVariantPath, restartTranslation, startTranslation, zhStatus } from "./translate.js";
10
10
  import { clearTranslateConfig, maskApiKey, readTranslateConfig, resolveTranslateEndpoint, testTranslateEndpoint, writeTranslateConfig, } from "./translate-config.js";
11
+ import { clearTypesafeConfig, readTypesafeConfig, resolveTypesafeConfig, testTypesafeEndpoint, writeTypesafeConfig, } from "./typesafe-config.js";
11
12
  import { installPaperPreset, PAPER_PRESET_ID } from "./preset.js";
12
13
  import { noteOrigin } from "./origin.js";
13
14
  function json(res, status, body) {
@@ -353,6 +354,50 @@ export function registerRoutes(ctx, config) {
353
354
  json(res, 200, { ok: true });
354
355
  return;
355
356
  }
357
+ // ── Jev/TypeSafe 端点配置(设置面板的读写口)─────────────────────────
358
+ // 与翻译配置同一套约定:GET 只回显掩码 key;POST 预检通过才落盘;DELETE 回落
359
+ if (sub === '/api/typesafe/config' && req.method === 'GET') {
360
+ const { cfg, source } = await resolveTypesafeConfig(config.typesafe);
361
+ json(res, 200, {
362
+ baseUrl: cfg.baseUrl ?? '',
363
+ model: cfg.model ?? '',
364
+ hasApiKey: Boolean(cfg.apiKey),
365
+ apiKeyHint: cfg.apiKey ? maskApiKey(cfg.apiKey) : '',
366
+ source,
367
+ });
368
+ return;
369
+ }
370
+ // POST:baseUrl/model 可空(SDK 有默认值);key 留空 = 沿用已存的那把。
371
+ // 校验 → 预检 → 通了才落盘:重排失败会静默降级,key 填错很难察觉,这里先拦。
372
+ if (sub === '/api/typesafe/config' && req.method === 'POST') {
373
+ const body = (await readBody(req));
374
+ const baseUrl = body.baseUrl?.trim() ?? '';
375
+ const model = body.model?.trim() ?? '';
376
+ const prev = await readTypesafeConfig();
377
+ const apiKey = body.apiKey?.trim() || prev?.apiKey || '';
378
+ if (baseUrl && !/^https?:\/\//i.test(baseUrl)) {
379
+ json(res, 400, { error: '端点 URL 需要以 http:// 或 https:// 开头(留空用官方默认)' });
380
+ return;
381
+ }
382
+ if (!apiKey) {
383
+ json(res, 400, { error: 'API Key 不能为空' });
384
+ return;
385
+ }
386
+ const test = await testTypesafeEndpoint({ apiKey, ...(baseUrl ? { baseUrl } : {}), ...(model ? { model } : {}) });
387
+ if (!test.ok) {
388
+ json(res, 400, { error: `连接测试失败:${test.detail ?? '未知原因'}` });
389
+ return;
390
+ }
391
+ await writeTypesafeConfig({ apiKey, ...(baseUrl ? { baseUrl } : {}), ...(model ? { model } : {}) });
392
+ json(res, 200, { ok: true });
393
+ return;
394
+ }
395
+ // DELETE:清掉文件,回落到 profile 的 typesafe / 环境变量
396
+ if (sub === '/api/typesafe/config' && req.method === 'DELETE') {
397
+ await clearTypesafeConfig();
398
+ json(res, 200, { ok: true });
399
+ return;
400
+ }
356
401
  if (sub === '/api/transcribe' && req.method === 'POST') {
357
402
  const body = (await readBody(req));
358
403
  const ref = resolvePaper(dataDir, body);
package/dist/rerank.js ADDED
@@ -0,0 +1,85 @@
1
+ // rerank.ts — 语义重排(Jev / TypeSafe System One,不依赖 Cordis)。
2
+ //
3
+ // 两段式检索的第二段:search.ts 的关键词打分是「快搜」——按词面捞回 shortlist;
4
+ // 这里对 shortlist 里每个候选问一个 Noul(「这段能回答学生的问题吗」),
5
+ // 按 noul 概率重排。快搜召回、Jev 定序,代码保留排序和截断。
6
+ // 参考 https://docs.typesafe.ai/cookbooks/rerank_typesafe.md
7
+ //
8
+ // 凭据按「设置面板文件 > profile YAML > 环境变量」解析(typesafe-config.ts),
9
+ // 都配不出 apiKey 时 resolveRerankClient 返回 null,调用方退回纯关键词排序
10
+ // ——重排是可迭增强,不是硬依赖。
11
+ import { TypeSafeClient, noul } from '@typesafe-ai/sdk';
12
+ import { patientFetch, resolveTypesafeConfig } from "./typesafe-config.js";
13
+ /** 重排超预算(区别于网络/鉴权错误,方便上层区分日志)。 */
14
+ export class RerankDeadlineError extends Error {
15
+ deadlineMs;
16
+ constructor(deadlineMs) {
17
+ super(`Jev 重排超过 ${deadlineMs}ms 预算,已放弃`);
18
+ this.deadlineMs = deadlineMs;
19
+ this.name = 'RerankDeadlineError';
20
+ }
21
+ }
22
+ export function resolveShortlistSize(config) {
23
+ const n = config?.shortlistSize ?? 15;
24
+ return Math.max(1, Math.min(Math.trunc(n), 30));
25
+ }
26
+ /**
27
+ * 有凭据则建客户端,否则返回 null(调用方走降级路径)。
28
+ * 每次检索都调用:设置面板保存后无需重启即生效(读的是个小 JSON,开销可忽略)。
29
+ */
30
+ export async function resolveRerankClient(config) {
31
+ const { cfg } = await resolveTypesafeConfig(config);
32
+ if (!cfg.apiKey?.trim())
33
+ return null;
34
+ return new TypeSafeClient({
35
+ apiKey: cfg.apiKey,
36
+ ...(cfg.baseUrl ? { baseURL: cfg.baseUrl } : {}),
37
+ ...(cfg.model ? { defaultModel: cfg.model } : {}),
38
+ timeout: config?.timeoutMs ?? 60_000,
39
+ fetch: patientFetch,
40
+ logLevel: 'off',
41
+ });
42
+ }
43
+ /**
44
+ * 用 Jev 对 shortlist 重排,返回 top-k(按原文顺序)。
45
+ * 所有候选放进一份 state、一次请求并行问 N 个 Noul(同 state 的独立问题
46
+ * 官方建议同批发问);任何失败(网络/鉴权/超时)抛给调用方降级。
47
+ * deadlineMs > 0 时到点 abort 在飞请求并抛 RerankDeadlineError。
48
+ */
49
+ export async function rerankHits(client, query, shortlist, k, deadlineMs = 1500) {
50
+ // state 与问题:候选按 c1..cN 编号,问题里用反引号路径引用对应候选。
51
+ const candidates = {};
52
+ const questions = {};
53
+ shortlist.forEach((h, i) => {
54
+ const key = `c${i + 1}`;
55
+ candidates[key] = h.chunk.text;
56
+ questions[key] = noul(`Could the passage at \`candidates.${key}\` help answer the student's question at \`question\`?`, {
57
+ true: 'The passage contains facts, reasoning, definitions, or data that directly help answer the question.',
58
+ false: 'The passage is only topically related or shares keywords, without content that actually helps answer the question.',
59
+ });
60
+ });
61
+ const ac = new AbortController();
62
+ const timer = deadlineMs > 0 ? setTimeout(() => ac.abort(new RerankDeadlineError(deadlineMs)), deadlineMs) : null;
63
+ let answers;
64
+ try {
65
+ ;
66
+ ({ answers } = await client.systemOne({ state: { question: query, candidates }, questions }, deadlineMs > 0 ? { signal: ac.signal } : {}));
67
+ }
68
+ catch (e) {
69
+ // abort 触发时 SDK 抛 APIUserAbortError,换成我们带预算信息的错误
70
+ if (ac.signal.aborted)
71
+ throw ac.signal.reason ?? e;
72
+ throw e;
73
+ }
74
+ finally {
75
+ if (timer)
76
+ clearTimeout(timer);
77
+ }
78
+ return shortlist
79
+ .map((h, i) => ({ hit: h, noul: answers[`c${i + 1}`].noul }))
80
+ .sort((a, b) => b.noul - a.noul)
81
+ .slice(0, k)
82
+ // 重排后 score 改写为 noul(最终排序分),便于上层/调试脚本展示概率
83
+ .map((e) => ({ ...e.hit, score: Math.round(e.noul * 1000) / 1000 }))
84
+ .sort((a, b) => a.chunk.index - b.chunk.index); // 与 searchChunks 一致:按原文顺序返回
85
+ }
package/dist/tools.js CHANGED
@@ -3,6 +3,7 @@ import { defineTool } from '@deepseek-ai/dsh-tools';
3
3
  import { listPapers, listTopics, resolveDataDir, resolvePaper } from "./library.js";
4
4
  import { transcribePaper, readTranscript } from "./transcribe.js";
5
5
  import { chunkText, searchChunks, formatHits } from "./search.js";
6
+ import { resolveRerankClient, resolveShortlistSize, rerankHits } from "./rerank.js";
6
7
  import { completeStep, formatStudy, readStudy, recordQuiz, setPlan } from "./study.js";
7
8
  import { readerOrigin } from "./origin.js";
8
9
  const locateParams = {
@@ -60,6 +61,7 @@ const readerUrlSchema = {
60
61
  const readerUrlLine = (url) => (url ? `\n阅读器链接基址:${url}` : '');
61
62
  export function registerTools(ctx, config) {
62
63
  const dataDir = resolveDataDir(config.dataDir);
64
+ const shortlistSize = resolveShortlistSize(config.typesafe);
63
65
  ctx.tools.register(defineTool({
64
66
  name: 'list_papers',
65
67
  description: '列出文献库里的专题和文献。当用户提到某篇论文但你不知道它是否在库中、或用户问"我有哪些论文"时使用。',
@@ -164,6 +166,11 @@ export function registerTools(ctx, config) {
164
166
  paper: { type: 'string', required: true },
165
167
  query: { type: 'string', required: true },
166
168
  totalChunks: { type: 'integer', required: true },
169
+ reranked: {
170
+ type: 'boolean',
171
+ required: true,
172
+ description: '返回片段是否经过语义重排(配置了 Jev/TypeSafe 凭据且候选充足时为 true)。',
173
+ },
167
174
  hits: {
168
175
  type: 'array',
169
176
  required: true,
@@ -207,12 +214,28 @@ export function registerTools(ctx, config) {
207
214
  throw new Error('转录失败,无法检索');
208
215
  const chunks = chunkText(cached.text, 1500);
209
216
  const k = Math.max(1, Math.min(args.k ?? 5, 8));
210
- const hits = searchChunks(chunks, cached.pages, args.query, k);
217
+ // 两段式检索:关键词快搜捞 shortlist(宽召回),Jev 按语义重排取 top-k。
218
+ // 凭据每次现查(设置面板保存即生效);无凭据或候选不超过 k 时跳过重排。
219
+ const rerankClient = await resolveRerankClient(config.typesafe);
220
+ let hits = searchChunks(chunks, cached.pages, args.query, rerankClient ? shortlistSize : k);
221
+ let reranked = false;
222
+ if (rerankClient && hits.length > k) {
223
+ try {
224
+ hits = await rerankHits(rerankClient, args.query, hits, k, config.typesafe?.deadlineMs ?? 1500);
225
+ reranked = true;
226
+ }
227
+ catch (e) {
228
+ // 超预算/网络/鉴权任何失败都退回关键词 top-k(结果已算好,零成本降级)
229
+ console.warn('[dsh-paper-reader] 检索重排失败,退回关键词排序:', e);
230
+ hits = hits.slice(0, k);
231
+ }
232
+ }
211
233
  return {
212
234
  paper: `${ref.topic}/${ref.name}`,
213
235
  query: args.query,
214
236
  totalChunks: chunks.length,
215
237
  hits: hits.map((h) => ({ chunk: h.chunk.index, page: h.page, text: h.chunk.text })),
238
+ reranked,
216
239
  readerUrl: readerUrl(ref),
217
240
  };
218
241
  },
package/dist/translate.js CHANGED
@@ -4,9 +4,8 @@
4
4
  // babeldoc 只支持 OpenAI 兼容端点 → 端点/key/模型由插件配置提供。
5
5
  import { execFile } from 'node:child_process';
6
6
  import { existsSync } from 'node:fs';
7
- import { mkdir, rename, rm } from 'node:fs/promises';
8
- import { glob } from 'node:fs/promises';
9
- import { join, dirname, basename, extname } from 'node:path';
7
+ import { mkdir, rename, rm, readdir } from 'node:fs/promises';
8
+ import { join, dirname, basename, extname, isAbsolute } from 'node:path';
10
9
  import { dshHome } from "./library.js";
11
10
  import { ensureBabeldoc } from "./babeldoc-install.js";
12
11
  export function zhPdfPath(ref) {
@@ -30,22 +29,26 @@ export function zhStatus(ref) {
30
29
  ...(b && !b.error && b.phase ? { phase: b.phase } : {}),
31
30
  };
32
31
  }
33
- /** 找 babeldoc 可执行文件:pdfqa venv(文献库同级 .venv-pdf2zh)→ PATH → miniconda。 */
32
+ /** 找 babeldoc 可执行文件:pdfqa venv(文献库同级 .venv-pdf2zh)→ PATH → miniconda(仅 macOS)。 */
34
33
  async function findBabeldoc(dataDir) {
34
+ const isWin = process.platform === 'win32';
35
35
  const candidates = [
36
- join(dirname(dataDir), '.venv-pdf2zh', 'bin', 'babeldoc'),
36
+ // 与 babeldoc-install.ts installBabeldoc 的安装位严格一致(win32 venv 用 Scripts/)
37
+ isWin
38
+ ? join(dirname(dataDir), '.venv-pdf2zh', 'Scripts', 'babeldoc.exe')
39
+ : join(dirname(dataDir), '.venv-pdf2zh', 'bin', 'babeldoc'),
37
40
  'babeldoc',
38
- '/opt/homebrew/Caskroom/miniconda/base/bin/babeldoc',
41
+ ...(process.platform === 'darwin' ? ['/opt/homebrew/Caskroom/miniconda/base/bin/babeldoc'] : []),
39
42
  ];
40
43
  for (const c of candidates) {
41
- if (c.includes('/')) {
44
+ if (isAbsolute(c)) {
42
45
  if (existsSync(c))
43
46
  return c;
44
47
  continue;
45
48
  }
46
- // PATH 查找
49
+ // PATH 查找(win32 用 where)
47
50
  const found = await new Promise((res) => {
48
- execFile('which', [c], (err, stdout) => res(!err && stdout.trim() !== ''));
51
+ execFile(isWin ? 'where' : 'which', [c], (err, stdout) => res(!err && stdout.trim() !== ''));
49
52
  });
50
53
  if (found)
51
54
  return c;
@@ -180,11 +183,13 @@ async function launch(ref, dataDir, endpoint, bin) {
180
183
  }
181
184
  // 产出从 scratch 挪回文献目录:<名>.zh-CN.mono.pdf → -zh.pdf,.dual.pdf → -dual.pdf
182
185
  try {
183
- for await (const f of glob(join(tmpDir, `${stem}*.zh-CN.mono.pdf`))) {
184
- await rename(f, dstStem + '-zh.pdf');
185
- }
186
- for await (const f of glob(join(tmpDir, `${stem}*.zh-CN.dual.pdf`))) {
187
- await rename(f, dstStem + '-dual.pdf');
186
+ // 不用 glob:其 pattern 里反斜杠是转义符,win32 的 join 路径会踩雷;readdir + 前后缀匹配全平台稳
187
+ const files = await readdir(tmpDir);
188
+ for (const f of files) {
189
+ if (f.startsWith(stem) && f.endsWith('.zh-CN.mono.pdf'))
190
+ await rename(join(tmpDir, f), dstStem + '-zh.pdf');
191
+ if (f.startsWith(stem) && f.endsWith('.zh-CN.dual.pdf'))
192
+ await rename(join(tmpDir, f), dstStem + '-dual.pdf');
188
193
  }
189
194
  if (!existsSync(zhPdfPath(ref)) && !existsSync(dualPdfPath(ref))) {
190
195
  busy.set(ref.pdfPath, { error: 'babeldoc 未产出译文 PDF' });
@@ -0,0 +1,105 @@
1
+ // typesafe-config.ts — Jev/TypeSafe 端点配置的落盘与解析(纯函数,不依赖 Cordis)。
2
+ //
3
+ // 与 translate-config.ts 同一套约定:存 $DSH_HOME/.dsh-paper-reader/typesafe.json
4
+ // (0600,不进 dataDir——密钥不跟文献库走);密钥只落盘、只回显掩码。
5
+ // 优先级:文件(设置面板填的)> profile 的 cordis.patch.yml config.typesafe
6
+ // > 环境变量 TYPESAFE_API_KEY(部署方兜底)。
7
+ import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
8
+ import { dirname, join } from 'node:path';
9
+ import { TypeSafeClient, noul } from '@typesafe-ai/sdk';
10
+ import { Agent, fetch as undiciFetch } from 'undici';
11
+ import { dshHome } from "./library.js";
12
+ import { maskApiKey } from "./translate-config.js";
13
+ export { maskApiKey };
14
+ // 跨境/弱网链路 TCP 握手可能远超 undici 默认的 10s connect 超时(实测 30s+),
15
+ // 单独放宽 connect;总耗时仍由客户端 timeout 控制。fetch 与 Agent 必须用同一个
16
+ // undici 包(混用 npm undici 的 Agent + Node 内置 fetch 会因 dispatcher 内部
17
+ // 接口版本不匹配而炸),per-call dispatcher,不动全局 dispatcher。
18
+ const longConnectAgent = new Agent({ connect: { timeout: 60_000 } });
19
+ export const patientFetch = (input, init) =>
20
+ // 运行时同源;类型上 @types/node 的 undici-types 与 npm undici 不完全兼容,双断言绕过
21
+ undiciFetch(input, { ...init, dispatcher: longConnectAgent });
22
+ export function typesafeConfigPath(home = dshHome()) {
23
+ return join(home, '.dsh-paper-reader', 'typesafe.json');
24
+ }
25
+ /** 读配置;文件缺失/损坏/形状不对一律返回 null(与 translate-config 的读策略一致)。 */
26
+ export async function readTypesafeConfig(home = dshHome()) {
27
+ try {
28
+ const data = JSON.parse(await readFile(typesafeConfigPath(home), 'utf8'));
29
+ if (typeof data !== 'object' || data === null)
30
+ return null;
31
+ const rec = data;
32
+ const out = {};
33
+ if (typeof rec['apiKey'] === 'string')
34
+ out.apiKey = rec['apiKey'];
35
+ if (typeof rec['baseUrl'] === 'string')
36
+ out.baseUrl = rec['baseUrl'];
37
+ if (typeof rec['model'] === 'string')
38
+ out.model = rec['model'];
39
+ return out;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /** 写配置。0600:文件含明文密钥,不靠 umask。 */
46
+ export async function writeTypesafeConfig(cfg, home = dshHome()) {
47
+ const file = typesafeConfigPath(home);
48
+ await mkdir(dirname(file), { recursive: true });
49
+ await writeFile(file, JSON.stringify(cfg, null, 2) + '\n', { encoding: 'utf8', mode: 0o600 });
50
+ await chmod(file, 0o600); // mode 只在新建时生效;已存在的文件要显式收紧
51
+ }
52
+ /** 删除配置(回落到 profile 的 typesafe / 环境变量)。文件不存在也算成功。 */
53
+ export async function clearTypesafeConfig(home = dshHome()) {
54
+ await rm(typesafeConfigPath(home), { force: true });
55
+ }
56
+ /** 解析生效配置:按字段 file > profile > env(只 env 有 key 时 source=env)。 */
57
+ export async function resolveTypesafeConfig(profile, home = dshHome()) {
58
+ const file = await readTypesafeConfig(home);
59
+ const envKey = process.env['TYPESAFE_API_KEY'];
60
+ const cfg = {};
61
+ const apiKey = file?.apiKey || profile?.apiKey || envKey;
62
+ const baseUrl = file?.baseUrl || profile?.baseUrl;
63
+ const model = file?.model || profile?.model;
64
+ if (apiKey)
65
+ cfg.apiKey = apiKey;
66
+ if (baseUrl)
67
+ cfg.baseUrl = baseUrl;
68
+ if (model)
69
+ cfg.model = model;
70
+ const source = file?.apiKey
71
+ ? 'file'
72
+ : profile?.apiKey
73
+ ? 'profile'
74
+ : envKey?.trim()
75
+ ? 'env'
76
+ : 'none';
77
+ return { cfg, source };
78
+ }
79
+ /**
80
+ * 连接预检:打一发极小的 systemOne(一个 Noul、几个 token),确认 key/端点/模型有效。
81
+ * 与翻译预检同理:重排失败会静默降级成关键词排序,key 填错用户很难察觉,落盘前先拦。
82
+ */
83
+ export async function testTypesafeEndpoint(cfg) {
84
+ if (!cfg.apiKey?.trim())
85
+ return { ok: false, detail: 'API Key 不能为空' };
86
+ try {
87
+ const client = new TypeSafeClient({
88
+ apiKey: cfg.apiKey,
89
+ ...(cfg.baseUrl ? { baseURL: cfg.baseUrl } : {}),
90
+ ...(cfg.model ? { defaultModel: cfg.model } : {}),
91
+ timeout: 60_000, // 预检同样走慢链路,15s 容易误杀
92
+ fetch: patientFetch,
93
+ logLevel: 'off',
94
+ });
95
+ await client.systemOne({
96
+ state: 'ping',
97
+ questions: { ok: noul('Is this a connectivity check? Reply yes.') },
98
+ });
99
+ return { ok: true };
100
+ }
101
+ catch (err) {
102
+ const cause = err instanceof Error && err.cause instanceof Error ? `: ${err.cause.message}` : '';
103
+ return { ok: false, detail: (err instanceof Error ? err.message : String(err)) + cause };
104
+ }
105
+ }
package/lib/client.js CHANGED
@@ -33,6 +33,17 @@ window.__ModuleLoader__.load({
33
33
  history: '历史对话',
34
34
  sync: '对话还停在另一篇文献的会话里,点击切到当前文献',
35
35
  mode: '论文伴读', modeEnterTip: '进入论文伴读:左侧变为文献库树', modeExitTip: '退出论文伴读:恢复官方工作区列表',
36
+ settings: '论文伴读',
37
+ setRerankTitle: '检索重排(Jev)',
38
+ setRerankDesc: 'search_paper 检索的语义重排:关键词先捞候选,Jev 逐个判断「这段能否回答这个问题」再排序——大白话提问也能命中论文里的术语段落。不配则退回纯关键词排序。',
39
+ setTranslateTitle: '翻译端点',
40
+ setTranslateDesc: '「生成中文版」(babeldoc)用的 OpenAI 兼容端点,三项必填。保存前会先测连接。',
41
+ setBaseUrl: '端点 URL', setModel: '模型', setKey: 'API Key',
42
+ setSave: '测试并保存', setSaving: '测试连接中…', setClear: '清除自填配置',
43
+ setSaved: '已保存,立即生效', setCleared: '已清除,回落到部署方默认',
44
+ setKeyKeep: '留空沿用已保存的 ', setOptional: '可选',
45
+ setSourceFile: '当前来源:设置页', setSourceProfile: '当前来源:配置文件(部署方默认)',
46
+ setSourceEnv: '当前来源:环境变量', setSourceNone: '未配置',
36
47
  }
37
48
  const en = {
38
49
  library: 'Library',
@@ -41,6 +52,17 @@ window.__ModuleLoader__.load({
41
52
  history: 'Chat history',
42
53
  sync: 'Chat is still on another paper — click to switch to the current one',
43
54
  mode: 'Paper Reading', modeEnterTip: 'Enter paper-reading mode: sidebar becomes the library tree', modeExitTip: 'Exit paper-reading mode: restore the official workspace list',
55
+ settings: 'Paper Reader',
56
+ setRerankTitle: 'Search rerank (Jev)',
57
+ setRerankDesc: 'Semantic rerank for search_paper: keyword search shortlists candidates, Jev judges "can this passage answer the question" and reorders — plain-language questions hit terminology passages. Without it, plain keyword ranking is used.',
58
+ setTranslateTitle: 'Translate endpoint',
59
+ setTranslateDesc: 'OpenAI-compatible endpoint for "Generate Chinese version" (babeldoc). All three fields required. Connection is tested before saving.',
60
+ setBaseUrl: 'Endpoint URL', setModel: 'Model', setKey: 'API Key',
61
+ setSave: 'Test & save', setSaving: 'Testing…', setClear: 'Clear my config',
62
+ setSaved: 'Saved, effective immediately', setCleared: 'Cleared, falling back to deployment defaults',
63
+ setKeyKeep: 'Leave empty to keep saved ', setOptional: 'optional',
64
+ setSourceFile: 'Source: settings page', setSourceProfile: 'Source: config file (deployment default)',
65
+ setSourceEnv: 'Source: environment variable', setSourceNone: 'Not configured',
44
66
  }
45
67
 
46
68
  let t = (k) => k
@@ -744,6 +766,90 @@ window.__ModuleLoader__.load({
744
766
  }, wide ? h(React.Fragment, null, '📚', h('span', null, t('mode'))) : '📚')
745
767
  }
746
768
 
769
+ /* ---------- 设置面板:Jev 重排 + 翻译端点统一管理 ----------
770
+ settings.section 面板(与官方 通用设置/模型 同款缝)。两张端点卡片共用一套
771
+ 读写口(GET 掩码回显 / POST 预检后落盘 / DELETE 回落默认),key 明文永不回传,
772
+ 留空即沿用已保存的那把。保存即生效:宿主每次调用都现读配置文件。 */
773
+ const SET = {
774
+ card: { border: '1px solid var(--dsw-alias-border-l1, #30363d)', borderRadius: '10px', padding: '14px 16px', margin: '0 0 16px', background: 'var(--dsw-alias-bg-layer-1, #0d1117)' },
775
+ title: { fontSize: '14px', fontWeight: 600, color: 'var(--dsw-alias-label-primary, #24292f)', margin: '0 0 4px' },
776
+ desc: { fontSize: '12px', lineHeight: '1.6', color: 'var(--dsw-alias-label-secondary, #656d76)', margin: '0 0 12px' },
777
+ label: { display: 'block', fontSize: '12px', color: 'var(--dsw-alias-label-secondary, #656d76)', margin: '10px 0 4px' },
778
+ input: { width: '100%', boxSizing: 'border-box', fontSize: '13px', padding: '6px 8px', borderRadius: '6px', border: '1px solid var(--dsw-alias-border-l1, #30363d)', background: 'var(--dsw-alias-bg-layer-2, #161b22)', color: 'var(--dsw-alias-label-primary, #24292f)' },
779
+ row: { display: 'flex', alignItems: 'center', gap: '10px', marginTop: '12px' },
780
+ btn: { fontSize: '13px', padding: '6px 14px', borderRadius: '6px', border: 'none', cursor: 'pointer', background: 'var(--dsw-alias-button-primary-fill, #1f6feb)', color: 'var(--dsw-alias-label-primary-foreground, #fff)' },
781
+ btnGhost: { fontSize: '12px', padding: '6px 10px', borderRadius: '6px', cursor: 'pointer', background: 'none', border: '1px solid var(--dsw-alias-border-l1, #30363d)', color: 'var(--dsw-alias-label-secondary, #656d76)' },
782
+ ok: { fontSize: '12px', color: 'var(--dsw-alias-state-success-primary, #3fb950)' },
783
+ err: { fontSize: '12px', color: 'var(--dsw-alias-state-error-primary, #f85149)' },
784
+ meta: { fontSize: '12px', color: 'var(--dsw-alias-label-secondary, #656d76)' },
785
+ }
786
+
787
+ function EndpointCard(props) {
788
+ const [cfg, setCfg] = useState(null) // GET 结果(含 apiKeyHint/source)
789
+ const [form, setForm] = useState({ baseUrl: '', model: '', apiKey: '' })
790
+ const [busy, setBusy] = useState(false)
791
+ const [msg, setMsg] = useState(null) // { ok, text }
792
+ const load = useCallback(() => {
793
+ api(props.path).then((d) => {
794
+ setCfg(d)
795
+ setForm({ baseUrl: d.baseUrl || '', model: d.model || '', apiKey: '' })
796
+ }).catch((e) => setMsg({ ok: false, text: String(e.message || e) }))
797
+ }, [props.path])
798
+ useEffect(load, [load])
799
+ const sourceText = !cfg ? '' : { file: t('setSourceFile'), profile: t('setSourceProfile'), env: t('setSourceEnv'), none: t('setSourceNone') }[cfg.source] || ''
800
+ const save = async () => {
801
+ setBusy(true); setMsg(null)
802
+ try {
803
+ await api(props.path, {
804
+ method: 'POST', headers: { 'content-type': 'application/json' },
805
+ body: JSON.stringify(form),
806
+ })
807
+ setMsg({ ok: true, text: t('setSaved') })
808
+ load()
809
+ } catch (e) { setMsg({ ok: false, text: String(e.message || e) }) } finally { setBusy(false) }
810
+ }
811
+ const clear = async () => {
812
+ setBusy(true); setMsg(null)
813
+ try {
814
+ await api(props.path, { method: 'DELETE' })
815
+ setMsg({ ok: true, text: t('setCleared') })
816
+ load()
817
+ } catch (e) { setMsg({ ok: false, text: String(e.message || e) }) } finally { setBusy(false) }
818
+ }
819
+ const field = (key, label, placeholder, type) => h('div', null,
820
+ h('label', { style: SET.label }, label, props.optional && key !== 'apiKey' ? `(${t('setOptional')})` : ''),
821
+ h('input', {
822
+ style: SET.input, type: type || 'text', value: form[key], placeholder, disabled: busy,
823
+ onChange: (e) => setForm({ ...form, [key]: e.target.value }),
824
+ }),
825
+ )
826
+ return h('div', { style: SET.card, 'data-dsh-plugin': 'dsh-paper-reader', 'data-dsh-part': 'settings-card' },
827
+ h('h3', { style: SET.title }, props.title),
828
+ h('p', { style: SET.desc }, props.desc),
829
+ field('baseUrl', t('setBaseUrl'), props.baseUrlPlaceholder),
830
+ field('model', t('setModel'), props.modelPlaceholder),
831
+ field('apiKey', t('setKey'), cfg?.hasApiKey ? t('setKeyKeep') + cfg.apiKeyHint : props.keyPlaceholder, 'password'),
832
+ h('div', { style: SET.row },
833
+ h('button', { type: 'button', style: SET.btn, disabled: busy, onClick: save }, busy ? t('setSaving') : t('setSave')),
834
+ cfg?.source === 'file' ? h('button', { type: 'button', style: SET.btnGhost, disabled: busy, onClick: clear }, t('setClear')) : null,
835
+ msg ? h('span', { style: msg.ok ? SET.ok : SET.err }, msg.text) : h('span', { style: SET.meta }, sourceText),
836
+ ),
837
+ )
838
+ }
839
+
840
+ function SettingsPanel() {
841
+ return h('div', { style: { maxWidth: '560px' }, 'data-dsh-plugin': 'dsh-paper-reader', 'data-dsh-surface': 'settings-modal' },
842
+ h(EndpointCard, {
843
+ path: '/typesafe/config', title: t('setRerankTitle'), desc: t('setRerankDesc'), optional: true,
844
+ baseUrlPlaceholder: 'https://api.typesafe.ai', modelPlaceholder: 'jev-latest', keyPlaceholder: 'ts-...',
845
+ }),
846
+ h(EndpointCard, {
847
+ path: '/translate/config', title: t('setTranslateTitle'), desc: t('setTranslateDesc'),
848
+ baseUrlPlaceholder: 'https://api.deepseek.com/v1', modelPlaceholder: 'deepseek-chat', keyPlaceholder: 'sk-...',
849
+ }),
850
+ )
851
+ }
852
+
747
853
  return {
748
854
  inject: ['slots', 'locale', 'layout', 'uiWorkspace', 'sidebarRight', 'sidebarRightTabs'],
749
855
  apply(ctx) {
@@ -779,6 +885,12 @@ window.__ModuleLoader__.load({
779
885
  name: 'sidebar.right.pane.tab', key: 'dpr-reader', locale: NS,
780
886
  }, PdfTab))
781
887
 
888
+ // 设置面板(设置 → 论文伴读):Jev 重排 + 翻译端点统一管理
889
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
890
+ name: 'settings.section', id: 'dsh-paper-reader', order: 70,
891
+ label: () => bound('settings'), locale: NS,
892
+ }, SettingsPanel))
893
+
782
894
  clientApi = { slots: ctx.slots, layout: ctx.layout, uiWorkspace: ctx.uiWorkspace, sidebarRight: ctx.sidebarRight }
783
895
 
784
896
  // 阅读器跳转链接拦截(capture 阶段,一次绑定):渲染器给 http(s) 链接加了
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ggboy123/dsh-paper-reader",
3
- "version": "0.6.2",
3
+ "version": "1.1.0",
4
4
  "description": "DeepSeek Harness 插件:论文伴读工作台 — PDF 转录 / 检索 / 原生对话伴读 + 内置阅读器页面。",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -50,19 +50,31 @@
50
50
  "keywords": [
51
51
  "dsh-plugin",
52
52
  "deepseek-harness",
53
+ "deepseek",
53
54
  "pdf",
55
+ "pdf-reader",
54
56
  "paper",
55
- "reader"
57
+ "paper-reading",
58
+ "research-paper",
59
+ "citation",
60
+ "reader",
61
+ "arxiv",
62
+ "ai-assistant",
63
+ "rag",
64
+ "translation"
56
65
  ],
57
66
  "dependencies": {
58
- "@deepseek-ai/dsh-tools": "0.1.5-rc.2",
59
- "pdfjs-dist": "^6.3.289"
67
+ "@typesafe-ai/sdk": "^0.6.0",
68
+ "pdfjs-dist": "^6.3.289",
69
+ "undici": "^8.10.2"
60
70
  },
61
71
  "peerDependencies": {
62
- "@deepseek-ai/cordis": "^4.0.2"
72
+ "@deepseek-ai/cordis": "^4.0.2",
73
+ "@deepseek-ai/dsh-tools": ">=0.1.5-rc.1 <0.2.0-0"
63
74
  },
64
75
  "devDependencies": {
65
76
  "@deepseek-ai/cordis": "^4.0.2",
77
+ "@deepseek-ai/dsh-tools": "0.1.5-rc.2",
66
78
  "@types/node": "^22.10.0",
67
79
  "typescript": "^5.6.0"
68
80
  }
package/reader/index.html CHANGED
@@ -172,6 +172,7 @@ function esc(s) { return s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;
172
172
 
173
173
  let current = null; // { topic, name }
174
174
  let zhState = { zh: false, dual: false, busy: false };
175
+ let statusMeta = ''; // openPaper 的「name · N 页」基线,翻译阶段标签褪去后恢复它
175
176
  let zhVariant = null; // null=原文 'dual'=中英对照 'zh'=纯中文
176
177
  // 每篇论文记住上次用的语言版本:伴读会话的跳转链接原地跳页不重载,
177
178
  // 加上这里的恢复,「中文界面跳中文」在同篇跳转/重开/跨论文三条路径上都成立
@@ -190,9 +191,10 @@ async function openPaper(topic, name, opts = {}) {
190
191
  $('status').textContent = '加载 PDF…';
191
192
  const q = `topic=${encodeURIComponent(topic)}&name=${encodeURIComponent(name)}`;
192
193
  const meta = await api('/paper?' + q);
193
- $('status').textContent = meta.hasTranscript
194
+ statusMeta = meta.hasTranscript
194
195
  ? `${name} · ${meta.pageCount ?? '?'} 页`
195
196
  : `${name} · 未转录(提问时会自动转录)`;
197
+ $('status').textContent = statusMeta;
196
198
  await refreshZhState();
197
199
  // 恢复该论文上次的语言版本(译文已不存在时回落原文)
198
200
  const saved = localStorage.getItem(variantKey(topic, name));
@@ -213,8 +215,15 @@ async function refreshZhState() {
213
215
  btn.title = zhState.busy ? (zhState.phase || `翻译进行中${zhState.model ? `(${zhState.model})` : ''}…`)
214
216
  : (zhState.zh || zhState.dual) ? '切换中文译文'
215
217
  : '还没有中文版,点击生成(babeldoc,需要几分钟)';
216
- // 安装/准备阶段在状态栏持续可见(轮询每 5s 刷新一次)
217
- if (zhState.busy && zhState.phase) $('status').textContent = zhState.phase;
218
+ // 安装/准备阶段在状态栏持续可见(轮询每 5s 刷新一次);翻译结束后恢复论文基线信息
219
+ const statusEl = $('status');
220
+ if (zhState.busy && zhState.phase) {
221
+ statusEl.textContent = zhState.phase;
222
+ statusEl.dataset.phaseShown = '1';
223
+ } else if (!zhState.busy && statusEl.dataset.phaseShown) {
224
+ delete statusEl.dataset.phaseShown;
225
+ if (statusMeta) statusEl.textContent = statusMeta;
226
+ }
218
227
  // ↻ 只在「已有译文且空闲」时出现;状态变化时顺手拆掉两击确认的待确认态
219
228
  const regen = $('zh-regen');
220
229
  const canRegen = (zhState.zh || zhState.dual) && !zhState.busy;