sci-paper-digest 0.0.0-stage → 1.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sci-paper-digest contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # sci-paper-digest
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read an SCI journal or conference paper from a **PDF**, **DOI**, **arXiv id**, or **URL** and produce a
4
+ compact bilingual Chinese–English digest: methods, every main finding as a **method → object → result**
5
+ triple, publication-grade English for each finding, **6–8 reusable SCI sentence patterns**, novelty, and
6
+ limitations.
7
+
8
+ ## Use
9
+
10
+ Paste a paper URL or DOI on its own and send it: the plugin treats a bare paper link (or a PDF attachment)
11
+ as a digest request.
12
+
13
+ ```text
14
+ /paper 10.1016/j.oceaneng.2024.117567
15
+ /paper https://arxiv.org/abs/1706.03762
16
+ ```
17
+
18
+ Or attach a PDF and send `/paper`. The command hands the source to the current agent, which calls the
19
+ `sci_paper_digest` tool and follows the `sci-paper-digest` skill.
20
+
21
+ The agent can also call the tool directly:
22
+
23
+ ```json
24
+ { "source": "C:/path/to/paper.pdf", "max_chars": 60000 }
25
+ ```
26
+
27
+ ## What it reads
28
+
29
+ - Local PDF / text / Markdown.
30
+ - Journal or conference article URLs (follows `citation_pdf_url` for the full text).
31
+ - DOIs (doi.org landing page, then Crossref metadata and OpenAlex OA PDF).
32
+ - arXiv abstract pages, PDFs, and the arXiv API for missing authors/year.
33
+
34
+ ## Limits
35
+
36
+ - No OCR: scanned PDFs without a text layer are reported, never invented.
37
+ - Paywalled pages yield metadata and, when available, the abstract; the digest states its reading scope.
38
+ - The plugin does not search by title; give it a DOI, link, or PDF.
39
+ - URL/DOI reading contacts doi.org, Crossref, OpenAlex, arXiv, and the publisher page. Local files are
40
+ never uploaded. Extracted text is cached under `$DSH_HOME/cache/sci-paper-digest/`.
41
+
42
+ ## Install
43
+
44
+ Install this directory as a bundle (Plugin Manager → Add plugin, or `install_bundle` with its absolute
45
+ path). Dependency: `unpdf`; without it the plugin falls back to its built-in zero-dependency PDF parser.
46
+
47
+ ## Files
48
+
49
+ - `index.js` — tool, `/paper` command, runtime skill registration.
50
+ - `lib/source.js` — source resolution, HTML/PDF ingestion, metadata, sections.
51
+ - `lib/pdf-extract.js` — `unpdf` first, built-in parser fallback.
52
+ - `lib/pdf.js` — zero-dependency PDF text extractor.
53
+ - `skill/SKILL.md` — the bilingual digest contract and SCI English rules.
54
+ - `docs/DETAIL.md` — user-facing detail page.
package/README.zh.md ADDED
@@ -0,0 +1,71 @@
1
+ # SCI 论文速读插件(sci-paper-digest)
2
+
3
+ 一个 DeepSeek Harness(DSH)插件:把 SCI 期刊/会议论文的 **PDF、链接、DOI 或 arXiv 号**读成
4
+ **中英对照**的速读摘要,重点给出每个主要结果的「方法 — 研究对象 — 结果」三要素和对应的
5
+ **SCI 级英文表达**。
6
+
7
+ ## 快速使用
8
+
9
+ 最省事:直接把论文链接或 DOI 粘进输入框发送(单独一行即可),插件会把“只有论文链接”识别为速读请求。
10
+
11
+ 也可以显式命令:
12
+
13
+ ```text
14
+ /paper 10.1016/j.oceaneng.2024.117567
15
+ ```
16
+
17
+ 或先附加 PDF,再发送:
18
+
19
+ ```text
20
+ /paper
21
+ ```
22
+
23
+ 也可以直接说“帮我速读这篇论文:<链接/DOI>”,模型会调用 `sci_paper_digest` 工具并按
24
+ `sci-paper-digest` 技能输出。
25
+
26
+ ## 输出内容
27
+
28
+ 默认“3 分钟速读版”:
29
+
30
+ 1. 论文档案(题目、作者、期刊/会议、年份、DOI、阅读范围)
31
+ 2. 一句话速览(中/英)
32
+ 3. 方法(3–5 条)
33
+ 4. 主要结果:每条都有「方法 / 研究对象 / 研究结果 / SCI English」
34
+ 5. **SCI 表达提炼**:6–8 条可复用句式模板,`[ ]` 占位,替换即可用
35
+ 6. 创新点与局限
36
+
37
+ 说“精读 / 详细 / 逐段 / 审稿”时再展开深读版:研究缺口、逐节要点、证据强度、可引用英文句、术语表。
38
+
39
+ ## 能力边界
40
+
41
+ - 扫描版 PDF(无文字层)不做 OCR,会明确提示。
42
+ - 付费墙只能拿摘要/元数据时,会写明“仅摘要”,不给全文级结论。
43
+ - 按标题检索不是本插件职责;请给 DOI、链接或 PDF。
44
+ - 联网读取会访问 doi.org、Crossref、OpenAlex、arXiv 和出版社页面;本地文件不会上传。
45
+ - 抽取的全文缓存在 `$DSH_HOME/cache/sci-paper-digest/`,可手动清理。
46
+
47
+ ## 安装
48
+
49
+ 以本目录为 bundle 安装:插件页 **Add plugin** 选择本目录,或对绝对路径执行 `install_bundle`。
50
+ 依赖 `unpdf`;依赖缺失时自动回退到内置零依赖 PDF 解析器。
51
+
52
+ ## 目录
53
+
54
+ | 文件 | 作用 |
55
+ |---|---|
56
+ | `index.js` | Host 入口:工具、`/paper` 命令、运行时技能 |
57
+ | `lib/source.js` | 来源解析、网页/PDF 读取、元数据、章节切分 |
58
+ | `lib/pdf-extract.js` | 优先 `unpdf`,失败回退内置解析器 |
59
+ | `lib/pdf.js` | 零依赖 PDF 正文抽取器 |
60
+ | `skill/SKILL.md` | 双语速读格式与 SCI 英文规范 |
61
+ | `docs/DETAIL.md` | 插件详情页文案 |
62
+
63
+ ## 开发自测
64
+
65
+ ```powershell
66
+ node test/pdf-smoke.mjs <paper.pdf>
67
+ node test/source-smoke.mjs <paper.pdf|url|doi>
68
+ node test/format-smoke.mjs <paper.pdf|url|doi> 6000
69
+ node test/plugin-smoke.mjs <paper.pdf>
70
+ node --check index.js
71
+ ```
@@ -0,0 +1,7 @@
1
+ # 本包的 bundle 层:一个 Host 插件行。
2
+ # 把包名加入 profile 的 package.json -> dsh.profile.bundles(插件页会自动完成两步),
3
+ # 这一行就会变成 Loader 条目。
4
+ - insert:
5
+ - id: sci-paper-digest
6
+ name: sci-paper-digest
7
+ config: {}
package/docs/DETAIL.md ADDED
@@ -0,0 +1,90 @@
1
+ # SCI 论文速读 | SCI paper digest
2
+
3
+ 上传一篇 SCI 期刊/会议论文的 PDF,或粘贴论文链接 / DOI / arXiv 号,得到一份**中英对照**的速读摘要:
4
+
5
+ - 一句话结论;
6
+ - 研究方法(3–5 条);
7
+ - 每一个主要结果的「方法 — 研究对象 — 研究结果」三要素;
8
+ - 对应的 **SCI 级英文表达**;
9
+ - **6–8 条可复用的 SCI 句式模板**(`[ ]` 占位,替换即可用);
10
+ - 创新点、局限与证据强度。
11
+
12
+ 默认是“3 分钟速读版”;用户说“精读 / 详细 / 逐段 / 审稿”时再展开深读版(研究缺口、逐节要点、证据强度、引用句)。
13
+
14
+ ## 怎么用
15
+
16
+ ### 方式一:直接粘贴链接(最省事)
17
+
18
+ 把论文链接或 DOI 单独粘进输入框发送即可。插件会在系统提示里把“只有论文链接/DOI”识别为速读请求,自动调用工具并按技能输出。
19
+
20
+ ```text
21
+ https://doi.org/10.5194/os-19-1-2023
22
+ ```
23
+
24
+ ### 方式二:命令
25
+
26
+ 在对话输入框里:
27
+
28
+ ```text
29
+ /paper 10.1016/j.oceaneng.2024.117567
30
+ /paper https://arxiv.org/abs/1706.03762
31
+ ```
32
+
33
+ 或者先把 PDF 作为附件添加,再发送:
34
+
35
+ ```text
36
+ /paper
37
+ ```
38
+
39
+ 命令会把来源交给当前会话的模型,模型先抽取全文,再按固定格式输出。
40
+
41
+ ### 方式三:直接说
42
+
43
+ ```text
44
+ 帮我速读这篇论文:https://doi.org/10.5194/os-19-1-2023
45
+ ```
46
+
47
+ 或上传 PDF 后说“总结这篇”。模型会调用 `sci_paper_digest` 工具并加载 `sci-paper-digest` 技能。
48
+
49
+ ### 方式四:只要正文
50
+
51
+ 模型也可以直接调用工具 `sci_paper_digest`,拿到元数据、分章节正文、全文缓存路径。适合你想自己组织输出格式的场景。
52
+
53
+ ## 支持哪些来源
54
+
55
+ | 来源 | 说明 |
56
+ |---|---|
57
+ | 本地 PDF | 用 `unpdf`(内置 PDF.js)抽正文;失败时回退到零依赖解析器 |
58
+ | 期刊/会议页面链接 | 抽正文;若页面声明 `citation_pdf_url`,优先下载 PDF 全文 |
59
+ | DOI | 先走 `doi.org` 落地页;失败时用 Crossref 补元数据、OpenAlex 找开放获取 PDF |
60
+ | arXiv | 摘要页 + PDF,或按 arXiv 号回查官方 API 补作者/年份 |
61
+ | 纯文本/Markdown | 直接读取 |
62
+
63
+ ## 输出示例(节选,数值仅示意)
64
+
65
+ > #### 结果 1|开孔率对晃荡压力的抑制
66
+ > - 方法 | Method:三维 URANS + 浮力修正 k-ω SST,开孔率 0–12% 参数扫描
67
+ > - 研究对象 | Object:矩形液舱,充液率 50%,一阶共振工况
68
+ > - 研究结果 | Finding:开孔率 8% 时首阶压力峰值较无隔板下降 23.6%(p < 0.05),二阶峰上升 6.1%
69
+ > - **SCI English**: At an opening ratio of 8%, the first-order impact pressure on the tank wall was 23.6% lower than that of the unbaffled case (p < 0.05), whereas the second-order peak increased by 6.1%, indicating that the perforated baffle attenuates low-frequency sloshing loads more effectively than high-frequency components.
70
+
71
+ > **表达提炼(节选)**
72
+ >
73
+ > | 功能 | 可复用模板(英文) | 本文对应句/来源 |
74
+ > |---|---|---|
75
+ > | 报告提升/下降 | [Metric] decreased by [X]% (from [A] to [B]; p < [value], n = [N]) under [condition]. | 据结果段改写 |
76
+ > | 解释机理 | The observed [trend] is consistent with [mechanism], although [alternative] cannot be excluded. | 据讨论段改写 |
77
+
78
+ ## 边界
79
+
80
+ - **不做 OCR**:扫描版 PDF 没有文字层时读不出正文,会明确提示,而不是编造。
81
+ - **付费墙**:只能拿到摘要/元数据时会写明“仅摘要”,不会给全文级结论。
82
+ - **不跨库检索**:给标题而不给链接/PDF 时,插件不会自己猜论文;请补 DOI 或附件。
83
+ - **联网**:URL/DOI 路径会访问 doi.org、Crossref、OpenAlex、arXiv 和出版社页面;只发送论文标识符,不上传本地文件。
84
+ - 全文缓存写在 `$DSH_HOME/cache/sci-paper-digest/`,可自行清理。
85
+
86
+ ## 安装 / 卸载
87
+
88
+ 插件以本目录为一个 bundle。用 Plugin Manager 的 **Add plugin** 选择本目录,或在 `plugin_manager` 里对该绝对路径执行 `install_bundle`。卸载时在 Plugins 页移除 `sci-paper-digest`。
89
+
90
+ 依赖:`unpdf`(安装时由包管理器拉取;缺失时自动回退到内置解析器)。
package/icon.svg ADDED
@@ -0,0 +1,27 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="SCI paper digest">
2
+ <defs>
3
+ <linearGradient id="paper" x1="0" y1="0" x2="1" y2="1">
4
+ <stop offset="0" stop-color="#2f6fed"/>
5
+ <stop offset="1" stop-color="#1b3f9e"/>
6
+ </linearGradient>
7
+ <linearGradient id="lens" x1="0" y1="0" x2="0" y2="1">
8
+ <stop offset="0" stop-color="#5ee0c8"/>
9
+ <stop offset="1" stop-color="#18a88f"/>
10
+ </linearGradient>
11
+ </defs>
12
+ <rect x="2" y="2" width="60" height="60" rx="14" fill="#0f1b33"/>
13
+ <path d="M17 12h20l9 9v29a3 3 0 0 1-3 3H17a3 3 0 0 1-3-3V15a3 3 0 0 1 3-3Z" fill="url(#paper)"/>
14
+ <path d="M37 12v9h9" fill="#9db9ff" opacity=".85"/>
15
+ <g fill="#ffffff" opacity=".92">
16
+ <rect x="20" y="26" width="18" height="2.6" rx="1.3"/>
17
+ <rect x="20" y="32" width="14" height="2.6" rx="1.3"/>
18
+ <rect x="20" y="38" width="17" height="2.6" rx="1.3"/>
19
+ <rect x="20" y="44" width="10" height="2.6" rx="1.3"/>
20
+ </g>
21
+ <circle cx="43" cy="42" r="10.5" fill="none" stroke="url(#lens)" stroke-width="4"/>
22
+ <path d="M50.5 49.5 57 56" stroke="#5ee0c8" stroke-width="4.5" stroke-linecap="round"/>
23
+ <g stroke="#0f1b33" stroke-width="2" stroke-linecap="round">
24
+ <path d="M38.5 40h9"/>
25
+ <path d="M38.5 44h6"/>
26
+ </g>
27
+ </svg>
package/index.js ADDED
@@ -0,0 +1,222 @@
1
+ /**
2
+ * sci-paper-digest —— Host 半边。
3
+ *
4
+ * 三件事:
5
+ * 1. 工具 `sci_paper_digest`:把 PDF / 链接 / DOI / arXiv 号变成“元数据 + 分章节正文”;
6
+ * 2. 技能 `sci-paper-digest`:规定中英对照的“方法—研究对象—结果”速读格式与 SCI 英文规范;
7
+ * 3. 命令 `/paper`:把附件 PDF 或链接直接变成一轮模型任务,用户不需要再组织提示词。
8
+ *
9
+ * 真正的“理解与写作”交给模型;插件只负责把论文读进来、把输出契约固定下来。
10
+ */
11
+
12
+ import { readFileSync } from 'node:fs'
13
+ import { randomUUID } from 'node:crypto'
14
+ import { fileURLToPath } from 'node:url'
15
+ import { loadPaper } from './lib/source.js'
16
+ import {
17
+ DEFAULT_MAX_CHARS,
18
+ HARD_MAX_CHARS,
19
+ basenameOf,
20
+ buildFollowupPrompt,
21
+ clampChars,
22
+ formatDigest,
23
+ renderMetadataOnly,
24
+ } from './lib/format.js'
25
+
26
+ /** Loader 行 id。 */
27
+ export const name = 'sci-paper-digest'
28
+
29
+ /** 依赖的 Host 服务。附件存储按需通过 `ctx.get('attachments')` 取,缺了也能用链接/DOI。 */
30
+ export const inject = ['tools', 'commands', 'skills', 'systemPrompt']
31
+
32
+ /** 让“只粘贴链接/DOI/PDF”也自动进入论文速读的提示词规则。 */
33
+ const LINK_POLICY = [
34
+ 'Paper links: when a user message is mainly a journal or conference paper URL, a DOI, or an arXiv link,',
35
+ 'or is a PDF attachment with no other request, treat it as a request for a quick bilingual paper digest.',
36
+ 'Call `sci_paper_digest` with that source and follow the `sci-paper-digest` skill. Do not summarize from',
37
+ 'the title alone, and do not answer with a generic link preview.',
38
+ ].join(' ')
39
+
40
+ /** 技能正文(打包后随插件一起走)。 */
41
+ const SKILL_CONTENT = readFileSync(new URL('./skill/SKILL.md', import.meta.url), 'utf8')
42
+
43
+ /** 技能资源目录,供相对引用。 */
44
+ const SKILL_DIR = fileURLToPath(new URL('./skill/', import.meta.url))
45
+
46
+ /** `/paper` 的用法说明。 */
47
+ const USAGE = [
48
+ '用法:',
49
+ ' /paper <论文链接 | DOI | arXiv 号>',
50
+ ' /paper(先把 PDF 作为附件添加,再发送)',
51
+ '',
52
+ '例子:',
53
+ ' /paper 10.1016/j.oceaneng.2024.117567',
54
+ ' /paper https://arxiv.org/abs/1706.03762',
55
+ ].join('\n')
56
+
57
+ /** 注册工具、技能与命令。 */
58
+ export function apply(ctx) {
59
+ ctx.effect(() => ctx.tools.register(createDigestTool(ctx)))
60
+ ctx.effect(() => ctx.systemPrompt.section({
61
+ name: 'sci-paper-digest:link-policy',
62
+ order: 700,
63
+ text: LINK_POLICY,
64
+ }))
65
+ ctx.effect(() => ctx.skills.register({
66
+ name: 'sci-paper-digest',
67
+ description: 'Summarize an SCI journal or conference paper from a PDF, DOI, or link into a bilingual '
68
+ + '(Chinese–English) method–object–finding digest, and extract reusable publication-grade English sentence patterns.',
69
+ whenToUse: 'Use when the user uploads a paper PDF or gives a paper link/DOI/arXiv id and asks to '
70
+ + 'summarize, digest, read, or extract the methods, findings, and usable SCI expressions.',
71
+ content: SKILL_CONTENT,
72
+ source: 'runtime',
73
+ resourceBase: { kind: 'directory', path: SKILL_DIR },
74
+ }))
75
+ ctx.effect(() => ctx.commands.register({
76
+ name: 'paper',
77
+ description: '速读论文:/paper <链接|DOI|arXiv号>,或附加 PDF 后发送 /paper',
78
+ input: { hint: '<论文链接 / DOI / 本地 PDF 路径>', attachments: true },
79
+ handler: (invocation) => runPaperCommand(ctx, invocation),
80
+ }))
81
+ }
82
+
83
+ /**
84
+ * 构造模型可调用的论文抽取工具。
85
+ * @param {import('@deepseek-ai/cordis').Context} ctx Host 上下文。
86
+ * @returns {object}
87
+ */
88
+ function createDigestTool(ctx) {
89
+ return {
90
+ name: 'sci_paper_digest',
91
+ description: 'Extract the metadata and sectioned full text of an SCI journal/conference paper from a '
92
+ + 'PDF path, URL, DOI, or arXiv id, as the input for a bilingual digest. Returns title/authors/venue/DOI, '
93
+ + 'abstract/methods/results/conclusion sections, a cached full-text path, coverage, and warnings. Call this '
94
+ + 'before writing any paper summary; then follow the `sci-paper-digest` skill for the bilingual output format.',
95
+ parameters: {
96
+ type: 'object',
97
+ properties: {
98
+ source: {
99
+ type: 'string',
100
+ description: 'Paper source: an absolute local PDF/text path, an http(s) URL, a DOI (10.xxxx/...), '
101
+ + 'an arXiv id (1706.03762), or a DSH attachment handle path.',
102
+ },
103
+ max_chars: {
104
+ type: 'number',
105
+ description: `Maximum characters of sectioned text returned to the model (default ${DEFAULT_MAX_CHARS}, `
106
+ + `max ${HARD_MAX_CHARS}). The complete text is still cached on disk.`,
107
+ },
108
+ },
109
+ required: ['source'],
110
+ additionalProperties: false,
111
+ },
112
+ output: {
113
+ schema: { type: 'string' },
114
+ render: (_args, value) => [{ type: 'text', text: value }],
115
+ },
116
+ async execute(args) {
117
+ const source = typeof args?.source === 'string' ? args.source.trim() : ''
118
+ if (source === '') throw new Error('source 必须是非空字符串(PDF 路径 / URL / DOI / arXiv 号)。')
119
+ const maxChars = clampChars(typeof args?.max_chars === 'number' ? args.max_chars : undefined)
120
+ const warnings = []
121
+ let paper
122
+ try {
123
+ // 先完整抽取,再按预算裁剪章节,避免“只读到前 6000 字就切章节”。
124
+ paper = await loadPaper(source, { maxChars: 800_000, sectionBudget: maxChars })
125
+ } catch (error) {
126
+ throw new Error(`读取论文失败:${messageOf(error)}。请确认链接可访问,或改为上传 PDF。`)
127
+ }
128
+ warnings.push(...paper.warnings)
129
+ if (paper.text.trim() === '') {
130
+ return renderMetadataOnly(paper, warnings)
131
+ }
132
+ return formatDigest(paper, maxChars, warnings)
133
+ },
134
+ }
135
+ }
136
+
137
+ /**
138
+ * `/paper` 命令:把附件或链接变成一轮普通用户消息,交给模型按技能输出。
139
+ * @param {import('@deepseek-ai/cordis').Context} ctx Host 上下文。
140
+ * @param {object} invocation 命令调用。
141
+ * @returns {Promise<{kind: 'success'|'error', text: string}>}
142
+ */
143
+ async function runPaperCommand(ctx, invocation) {
144
+ const raw = String(invocation.rawInput ?? '').trim()
145
+ const attachmentPath = firstAttachmentPath(ctx, invocation.attachments)
146
+ if (raw === '' && attachmentPath === undefined) {
147
+ return { kind: 'error', text: `没看到论文来源。\n${USAGE}` }
148
+ }
149
+ if (invocation.attachments.length > 0 && attachmentPath === undefined) {
150
+ return { kind: 'error', text: '附件不是可读取的 PDF/文件,或附件存储不可用。请直接上传 PDF,或用链接。' }
151
+ }
152
+ const source = attachmentPath ?? raw
153
+ const prompt = buildFollowupPrompt(source, raw, attachmentPath !== undefined)
154
+ invocation.agent.followup(createUserMessage(prompt))
155
+ return {
156
+ kind: 'success',
157
+ text: `已开始速读:${attachmentPath === undefined ? raw : `附件 ${basenameOf(attachmentPath)}`}\n`
158
+ + '模型会先抽取全文,再按「方法—研究对象—结果」给出中英对照摘要。',
159
+ }
160
+ }
161
+
162
+ /**
163
+ * 取第一个附件的 Host 路径。
164
+ * @param {import('@deepseek-ai/cordis').Context} ctx Host 上下文。
165
+ * @param {readonly object[]} attachments 附件块。
166
+ * @returns {string|undefined}
167
+ */
168
+ function firstAttachmentPath(ctx, attachments) {
169
+ const store = ctx.get?.('attachments')
170
+ for (const block of attachments) {
171
+ if (block?.type !== 'file') continue
172
+ try {
173
+ const path = store?.fileHostPath?.(block.attachment)
174
+ if (typeof path === 'string' && path !== '') return path
175
+ } catch {
176
+ /* 换下一个附件 */
177
+ }
178
+ }
179
+ return undefined
180
+ }
181
+
182
+ /** 错误消息。 */
183
+ function messageOf(error) {
184
+ return error instanceof Error ? error.message : String(error)
185
+ }
186
+
187
+ /**
188
+ * 构造一条普通用户消息。形状与 `@deepseek-ai/dsh-llm` 的 `createUserMessage`
189
+ * 一致(品牌化 id 只是类型层约束),但不在运行时 import DSH 包——本地目录安装的
190
+ * 插件解析不到 `@deepseek-ai/*`,手写可避免加载期 `ERR_MODULE_NOT_FOUND`。
191
+ * @param {string} text 消息正文。
192
+ * @returns {object} 冻结的用户消息。
193
+ */
194
+ function createUserMessage(text) {
195
+ return deepFreeze({
196
+ id: randomUUID(),
197
+ role: 'user',
198
+ content: [{ type: 'text', text }],
199
+ source: { kind: 'user' },
200
+ })
201
+ }
202
+
203
+ /** 递归冻结,模拟 `createMessage` 的不可变语义。 */
204
+ function deepFreeze(value) {
205
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
206
+ Object.freeze(value)
207
+ for (const child of Object.values(value)) deepFreeze(child)
208
+ }
209
+ return value
210
+ }
211
+
212
+ /**
213
+ * 纯函数与小工具,供离线自测直接调用;不参与 Host 行为,改它们不影响插件契约。
214
+ */
215
+ export const internals = {
216
+ formatDigest,
217
+ renderMetadataOnly,
218
+ buildFollowupPrompt,
219
+ clampChars,
220
+ firstAttachmentPath,
221
+ }
222
+
package/lib/format.js ADDED
@@ -0,0 +1,130 @@
1
+ /**
2
+ * 把 loadPaper 的结果格式化成模型看到的文本,以及 `/paper` 的任务提示。
3
+ * 这里全是纯函数,方便离线自测;不依赖任何 DSH 服务。
4
+ */
5
+
6
+ /** 单次交给模型的正文预算(字符)。 */
7
+ export const DEFAULT_MAX_CHARS = 60_000
8
+
9
+ /** 工具允许的最大预算。 */
10
+ export const HARD_MAX_CHARS = 200_000
11
+
12
+ /**
13
+ * 把论文对象格式化成工具结果。
14
+ * @param {object} paper loadPaper 的返回值。
15
+ * @param {number} maxChars 正文预算。
16
+ * @param {string[]} warnings 额外警告。
17
+ * @returns {string}
18
+ */
19
+ export function formatDigest(paper, maxChars, warnings = []) {
20
+ const meta = paper.meta
21
+ const lines = [
22
+ '【论文速读材料 | paper digest packet】',
23
+ `source: ${paper.source}`,
24
+ `kind: ${paper.kind}`,
25
+ `coverage: ${paper.coverage}`,
26
+ `title: ${meta.title || '(未识别)'}`,
27
+ `authors: ${meta.authors.length > 0 ? meta.authors.join('; ') : '(未识别)'}`,
28
+ `venue: ${meta.venue || '(未识别)'}${meta.year ? `, ${meta.year}` : ''}`,
29
+ `doi: ${meta.doi || '(未识别)'}`,
30
+ `pages: ${paper.stats.pages ?? '—'} | chars: ${paper.stats.chars} | sections: ${paper.sections.length}`,
31
+ '',
32
+ ]
33
+
34
+ if (meta.abstract !== '' && !paper.sections.some((section) => section.key === 'abstract')) {
35
+ lines.push('## Abstract', meta.abstract, '')
36
+ }
37
+ for (const section of paper.sections) {
38
+ lines.push(`## ${section.title}`, section.text, '')
39
+ }
40
+ if (paper.omittedChars > 0) {
41
+ lines.push(`[正文还有约 ${paper.omittedChars} 字符未放入上下文;需要时按 fullTextPath 读取。]`, '')
42
+ }
43
+ if (paper.cache?.textPath !== undefined) lines.push(`fullTextPath: ${paper.cache.textPath}`)
44
+ if (paper.cache?.jsonPath !== undefined) lines.push(`metaPath: ${paper.cache.jsonPath}`)
45
+ const allWarnings = [...new Set(warnings)]
46
+ if (allWarnings.length > 0) {
47
+ lines.push('', 'warnings:')
48
+ for (const warning of allWarnings) lines.push(`- ${warning}`)
49
+ }
50
+ const budgetNote = paper.stats.chars > maxChars
51
+ ? `正文约 ${paper.stats.chars} 字符,本次只放入 ${maxChars};summary 中不要假装读过未提供部分。`
52
+ : '正文已完整放入上下文。'
53
+ lines.push(
54
+ '',
55
+ '【输出要求】按 `sci-paper-digest` 技能输出“速读版”:论文档案、一句话速览、方法(3–5 条)、逐条结果(方法—研究对象—结果 + SCI English)、6–8 条可复用 SCI 表达模板、创新点与局限。用户要精读时再展开深读版。',
56
+ `【范围提示】${budgetNote}`,
57
+ )
58
+ return lines.join('\n')
59
+ }
60
+
61
+ /**
62
+ * 只有元数据时给模型一个明确的失败说明,而不是空正文。
63
+ * @param {object} paper 论文对象。
64
+ * @param {string[]} warnings 警告。
65
+ * @returns {string}
66
+ */
67
+ export function renderMetadataOnly(paper, warnings = []) {
68
+ const meta = paper.meta
69
+ return [
70
+ '【论文速读材料 | paper digest packet】',
71
+ `source: ${paper.source}`,
72
+ 'coverage: metadata-only',
73
+ `title: ${meta.title || '(未识别)'}`,
74
+ `authors: ${meta.authors.length > 0 ? meta.authors.join('; ') : '(未识别)'}`,
75
+ `venue: ${meta.venue || '(未识别)'}${meta.year ? `, ${meta.year}` : ''}`,
76
+ `doi: ${meta.doi || '(未识别)'}`,
77
+ '',
78
+ '没有取得可读正文,因此无法做内容速读。请让用户上传 PDF,或提供可直接访问的全文链接。',
79
+ '不要根据题名猜测方法或结果。',
80
+ '',
81
+ 'warnings:',
82
+ ...[...new Set(warnings)].map((warning) => `- ${warning}`),
83
+ ].join('\n')
84
+ }
85
+
86
+ /**
87
+ * 组装 `/paper` 交给模型的任务提示。
88
+ * @param {string} source 工具参数里的来源。
89
+ * @param {string} raw 用户原始输入。
90
+ * @param {boolean} fromAttachment 来源是否来自附件。
91
+ * @returns {string}
92
+ */
93
+ export function buildFollowupPrompt(source, raw, fromAttachment) {
94
+ const origin = fromAttachment
95
+ ? `来源:用户上传的 PDF 附件,本地路径为 \`${source}\`。`
96
+ : `来源:${source}。`
97
+ const extra = fromAttachment && raw !== '' ? `\n用户补充说明:${raw}` : ''
98
+ return [
99
+ '请用 `sci-paper-digest` 技能速读这篇论文,并严格按技能里的中英对照格式输出。',
100
+ '',
101
+ origin + extra,
102
+ '',
103
+ '执行要求:',
104
+ '1. 先调用工具 `sci_paper_digest`,`source` 传上面的来源(附件就传本地路径),拿到元数据与分章节正文。',
105
+ '2. 只依据工具返回的文本;数字、样本量、统计量必须能在原文中找到,找不到写“未报告 / not reported”。',
106
+ '3. 每个主要结果都要有「方法—研究对象—研究结果」三要素,并给出一句可直接写进 SCI 论文的英文。',
107
+ '4. 中文与英文同时展示;英文要符合 SCI 写作规范(时态、hedging、量化、术语一致)。',
108
+ '5. 最后写明阅读范围(全文/仅摘要)与证据强度;若只有摘要,明确说明不能给出全文级结论。',
109
+ ].join('\n')
110
+ }
111
+
112
+ /**
113
+ * 约束字符预算。
114
+ * @param {number|undefined} value 模型传入的预算。
115
+ * @returns {number}
116
+ */
117
+ export function clampChars(value) {
118
+ if (!Number.isFinite(value) || value <= 0) return DEFAULT_MAX_CHARS
119
+ return Math.min(Math.floor(value), HARD_MAX_CHARS)
120
+ }
121
+
122
+ /**
123
+ * 取路径最后一段。
124
+ * @param {string} path 路径。
125
+ * @returns {string}
126
+ */
127
+ export function basenameOf(path) {
128
+ const parts = String(path).split(/[\\/]/)
129
+ return parts[parts.length - 1] || String(path)
130
+ }