dsh-fulltext 0.0.0-stage → 0.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.
@@ -0,0 +1,23 @@
1
+ export const ROUTE = '/api/fulltext';
2
+ export const PANEL = 'fulltext';
3
+ export const OWN_KEY = 'FULLTEXT_API_KEY';
4
+ export const SHARED_KEY = 'AI4SCHOLAR_API_KEY';
5
+ export const isRecord = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
6
+ export const safeUrl = (v) => {
7
+ if (typeof v !== 'string')
8
+ return undefined;
9
+ try {
10
+ const u = new URL(v);
11
+ return ['http:', 'https:'].includes(u.protocol) ? u.href : undefined;
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ };
17
+ export const paperKey = (s) => s.corpusId ?? s.paperId ?? s.title;
18
+ export const paperCount = (r) => new Set(r.snippets.map(paperKey)).size;
19
+ export const totalCharge = (r) => r.charges.some(x => x.charged !== undefined)
20
+ ? r.charges.reduce((n, x) => n + (x.charged ?? 0), 0) : undefined;
21
+ export const entryOf = (r) => ({ id: r.id, query: r.input.query, createdAt: r.createdAt,
22
+ updatedAt: r.updatedAt, count: r.snippets.length, papers: paperCount(r),
23
+ ...(totalCharge(r) === undefined ? {} : { charged: totalCharge(r) }) });
package/lib/store.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { Report, ReportEntry } from './shared/types.js';
2
+ export declare class ReportStore {
3
+ readonly root: string;
4
+ constructor(root: string);
5
+ paths(id: string): {
6
+ html: string;
7
+ csv: string;
8
+ json: string;
9
+ };
10
+ save(report: Report): Promise<void>;
11
+ get(id: string): Promise<Report>;
12
+ list(): Promise<ReportEntry[]>;
13
+ }
package/lib/store.js ADDED
@@ -0,0 +1,59 @@
1
+ import { mkdir, readdir, readFile, writeFile, rename, rm } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { entryOf, isRecord } from './shared/types.js';
5
+ import { renderReport, renderCsv } from './report.js';
6
+ const ID = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;
7
+ export class ReportStore {
8
+ root;
9
+ constructor(root) {
10
+ this.root = root;
11
+ }
12
+ paths(id) {
13
+ if (!ID.test(id))
14
+ throw new Error('无效的报告 ID。');
15
+ return { html: join(this.root, id, 'report.html'), csv: join(this.root, id, 'report.csv'), json: join(this.root, id, 'report.json') };
16
+ }
17
+ async save(report) {
18
+ const paths = this.paths(report.id), directory = join(this.root, report.id);
19
+ const html = await renderReport(report);
20
+ await mkdir(directory, { recursive: true, mode: 0o700 });
21
+ // Generated views precede the canonical commit. Readers always regenerate
22
+ // from report.json, so an interrupted update never serves mixed revisions.
23
+ for (const [path, data] of [[paths.html, html], [paths.csv, renderCsv(report)], [paths.json, JSON.stringify(report, null, 2) + '\n']]) {
24
+ const temp = `${path}.${randomUUID()}.tmp`;
25
+ try {
26
+ await writeFile(temp, data, { mode: 0o600, flag: 'wx' });
27
+ await rename(temp, path);
28
+ }
29
+ finally {
30
+ await rm(temp, { force: true });
31
+ }
32
+ }
33
+ }
34
+ async get(id) {
35
+ const p = this.paths(id);
36
+ const raw = JSON.parse(await readFile(p.json, 'utf8'));
37
+ if (!isRecord(raw) || raw.id !== id || !Array.isArray(raw.snippets) || !isRecord(raw.input))
38
+ throw new Error('报告数据无效。');
39
+ return raw;
40
+ }
41
+ async list() {
42
+ let files;
43
+ try {
44
+ files = await readdir(this.root);
45
+ }
46
+ catch (error) {
47
+ if (error.code === 'ENOENT')
48
+ return [];
49
+ throw error;
50
+ }
51
+ const reports = await Promise.all(files.filter(x => ID.test(x)).map(async (id) => { try {
52
+ return entryOf(await this.get(id));
53
+ }
54
+ catch {
55
+ return undefined;
56
+ } }));
57
+ return reports.filter((x) => !!x).sort((a, b) => b.createdAt.localeCompare(a.createdAt)).slice(0, 100);
58
+ }
59
+ }
package/lib/tools.d.ts ADDED
@@ -0,0 +1,4 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { FulltextSearch } from './search.js';
3
+ import { ReportStore } from './store.js';
4
+ export declare function applyTools(ctx: Context, service: FulltextSearch, store: ReportStore, defaultLimit: number): void;
package/lib/tools.js ADDED
@@ -0,0 +1,122 @@
1
+ import { defineTool } from '@deepseek-ai/dsh-tools';
2
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
3
+ import { FulltextSearch, parseSearch } from './search.js';
4
+ import { ReportStore } from './store.js';
5
+ import { paperCount, totalCharge } from './shared/types.js';
6
+ const OUTPUT = {
7
+ type: 'object', additionalProperties: false,
8
+ properties: {
9
+ report_id: { type: 'string', required: true }, query: { type: 'string', required: true },
10
+ html_path: { type: 'string', required: true }, csv_path: { type: 'string', required: true }, json_path: { type: 'string', required: true },
11
+ snippet_count: { type: 'integer', required: true }, paper_count: { type: 'integer', required: true },
12
+ charged: { type: 'number' }, remaining: { type: 'number' }, summary: { type: 'string' },
13
+ warnings: { type: 'array', required: true, items: { type: 'string' } },
14
+ snippets: { type: 'array', required: true, items: { type: 'object', additionalProperties: false, properties: {
15
+ id: { type: 'string', required: true }, title: { type: 'string', required: true }, title_zh: { type: 'string' },
16
+ text: { type: 'string', required: true }, kind: { type: 'string', required: true }, section: { type: 'string' },
17
+ corpus_id: { type: 'string' }, paper_id: { type: 'string' }, year: { type: 'integer' }, venue: { type: 'string' },
18
+ authors: { type: 'array', required: true, items: { type: 'string' } }, url: { type: 'string' }, pdf_url: { type: 'string' },
19
+ } } },
20
+ },
21
+ };
22
+ function valueOf(report, store) {
23
+ const p = store.paths(report.id), charged = totalCharge(report);
24
+ const remaining = [...report.charges].reverse().find(c => c.remaining !== undefined)?.remaining;
25
+ return { report_id: report.id, query: report.input.query, html_path: p.html, csv_path: p.csv, json_path: p.json,
26
+ snippet_count: report.snippets.length, paper_count: paperCount(report), warnings: report.warnings,
27
+ ...(charged === undefined ? {} : { charged }), ...(remaining === undefined ? {} : { remaining }), ...(report.summary ? { summary: report.summary } : {}),
28
+ snippets: report.snippets.map(s => ({ id: s.id, title: s.title, text: s.text, kind: s.kind, authors: s.authors,
29
+ ...(s.titleZh ? { title_zh: s.titleZh } : {}), ...(s.section ? { section: s.section } : {}), ...(s.corpusId ? { corpus_id: s.corpusId } : {}),
30
+ ...(s.paperId ? { paper_id: s.paperId } : {}), ...(s.year ? { year: s.year } : {}), ...(s.venue ? { venue: s.venue } : {}),
31
+ ...(s.url ? { url: s.url } : {}), ...(s.pdfUrl ? { pdf_url: s.pdfUrl } : {}),
32
+ })),
33
+ };
34
+ }
35
+ function render(value, cached = false) {
36
+ return [{ type: 'text', text: [
37
+ `全文片段报告:${value.query}`, `报告 ID:${value.report_id}`, `${value.snippet_count} 个片段 · ${value.paper_count} 篇论文`,
38
+ `[HTML 报告](<${value.html_path}>) · [CSV 数据](<${value.csv_path}>)`,
39
+ cached ? '读取 / 更新已有报告,无额外检索费用。下列积分为原报告的历史费用。' : '',
40
+ value.charged !== undefined ? `报告累计检索费用:${value.charged} 积分${value.remaining !== undefined ? `;检索结束时剩余 ${value.remaining}` : ''}` : '',
41
+ value.summary, ...value.warnings,
42
+ ...value.snippets.map((s, i) => `[${i + 1}] ${s.title}\n${[s.authors.join(', '), s.year, s.venue, s.kind, s.section, s.corpus_id ? `CorpusId:${s.corpus_id}` : s.paper_id, s.url].filter(Boolean).join(' · ')}\n原文:${s.text}`),
43
+ ].filter(Boolean).join('\n\n') }];
44
+ }
45
+ export function applyTools(ctx, service, store, defaultLimit) {
46
+ ctx.tools.register(defineTool({
47
+ name: 'search_fulltext', description: 'Search Semantic Scholar indexed title, abstract and body excerpts via AI4Scholar, then save a standalone interactive HTML report and CSV. Costs credits; optional metadata enrichment makes one additional billed batch request. This does not fetch complete PDFs. Use existing report IDs instead of repeating a search.',
48
+ parameters: { query: { type: 'string', required: true, description: 'A phrase or question. English queries usually have better index coverage.' },
49
+ limit: { type: 'integer', description: `Number of snippets, 1–100, default ${defaultLimit}.` }, year: { type: 'string', description: 'Year/range, e.g. 2024, 2020-2025, 2020-, -2025.' },
50
+ venue: { type: 'string', description: 'Comma-separated journal/conference names.' }, fields_of_study: { type: 'string', description: 'Comma-separated Semantic Scholar fields, e.g. Computer Science,Materials Science.' },
51
+ min_citation_count: { type: 'integer' }, enrich: { type: 'boolean', description: 'Enrich year, venue and open-access PDF links in one paid batch request. Default true.' },
52
+ },
53
+ output: { schema: OUTPUT, render: (_a, v) => render(v) }, timeoutMs: 120_000, isConcurrencySafe: () => true,
54
+ presentCall: a => ({ card: 'generic', title: `全文搜索 · ${a.query}`, kind: 'search' }),
55
+ async execute(args, exec) {
56
+ const report = await service.search(parseSearch({ ...args, fieldsOfStudy: args.fields_of_study, minCitationCount: args.min_citation_count }, defaultLimit), exec.signal);
57
+ await store.save(report);
58
+ return valueOf(report, store);
59
+ },
60
+ }));
61
+ ctx.tools.register(defineTool({
62
+ name: 'get_fulltext_report', description: 'Read an existing fulltext report by its exact report_id. Returns original snippets, identifiers and saved HTML/CSV paths without another paid API request.',
63
+ parameters: { report_id: { type: 'string', required: true } }, output: { schema: OUTPUT, render: (_a, v) => render(v, true) },
64
+ isConcurrencySafe: () => true, async execute(args) { return valueOf(await store.get(args.report_id), store); },
65
+ }));
66
+ ctx.tools.register(defineTool({
67
+ name: 'update_fulltext_report', description: 'Add an evidence-grounded plain-text synthesis and optional Chinese title translations to an existing report. No API charge. Read it first; preserve original excerpts and all metadata. This regenerates the same HTML/CSV files.',
68
+ parameters: { report_id: { type: 'string', required: true }, summary: { type: 'string', description: 'Plain-text synthesis, up to 12000 characters; use [1], [2] to refer to snippet indices. No HTML.' },
69
+ translations: { type: 'array', items: { type: 'object', additionalProperties: false, properties: { corpus_id: { type: 'string', required: true }, title_zh: { type: 'string', required: true } } }, description: 'Chinese title translations keyed by an existing corpus_id.' },
70
+ }, output: { schema: OUTPUT, render: (_a, v) => render(v, true) }, isConcurrencySafe: () => false,
71
+ async execute(args, exec) {
72
+ exec.signal.throwIfAborted();
73
+ if (!args.summary && !args.translations?.length)
74
+ throw new Error('请提供总结或标题翻译。');
75
+ if (args.summary && args.summary.length > 12000)
76
+ throw new Error('总结不能超过 12000 个字符。');
77
+ const report = await store.get(args.report_id);
78
+ for (const translation of args.translations ?? []) {
79
+ if (!report.snippets.some(s => s.corpusId === translation.corpus_id))
80
+ throw new Error('翻译使用了不属于该报告的 CorpusId。');
81
+ if (!translation.title_zh.trim() || translation.title_zh.length > 2000)
82
+ throw new Error('无效的标题翻译。');
83
+ }
84
+ if (args.summary !== undefined)
85
+ report.summary = args.summary.trim();
86
+ for (const translation of args.translations ?? [])
87
+ for (const s of report.snippets.filter(x => x.corpusId === translation.corpus_id))
88
+ s.titleZh = translation.title_zh.trim();
89
+ report.updatedAt = new Date().toISOString();
90
+ exec.signal.throwIfAborted();
91
+ await store.save(report);
92
+ return valueOf(report, store);
93
+ },
94
+ }));
95
+ ctx.inject(['commands'], child => {
96
+ const seen = new WeakMap();
97
+ child.commands.register({ name: 'fulltext', description: '全文搜索 · 查找原文片段,生成 HTML / CSV 报告',
98
+ input: { hint: '查找固态电池界面阻抗的实验方法,返回 10 个片段', images: false },
99
+ async handler(invocation) {
100
+ const text = invocation.rawInput.trim();
101
+ if (!text)
102
+ return { kind: 'success', text: '用法:/fulltext + 自然语言。例:查找 solid-state battery interfacial resistance 的实验方法,返回 10 个片段。也可以打开左侧「全文搜索」,直接检索并预览 / 下载 HTML 和 CSV。' };
103
+ invocation.signal.throwIfAborted();
104
+ const agent = invocation.agent, id = String(invocation.commandId);
105
+ let receipts = seen.get(agent);
106
+ if (!receipts) {
107
+ receipts = new Set();
108
+ seen.set(agent, receipts);
109
+ }
110
+ if (receipts.has(id))
111
+ return { kind: 'success', text: '已加入当前对话。' };
112
+ if (typeof agent.followup !== 'function')
113
+ return { kind: 'error', text: '当前 Harness 不支持此命令,请使用左侧全文搜索。' };
114
+ agent.followup(createUserMessage({ source: { kind: 'user' }, content: [{ type: 'text', text: `/fulltext ${text}` }] }));
115
+ receipts.add(id);
116
+ while (receipts.size > 128)
117
+ receipts.delete(receipts.values().next().value);
118
+ return { kind: 'success', text: '已加入当前对话;将使用全文片段工具处理,并保存 HTML / CSV 报告。' };
119
+ },
120
+ });
121
+ });
122
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Ai4Scholar Fulltext",
4
+ "description": "Search indexed paper excerpts, preview the interactive HTML report, and export standalone HTML/CSV files. Reuses an existing AI4Scholar API key when available."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Ai4Scholar Fulltext",
4
+ "description": "在已索引论文的标题、摘要和正文中查找原文片段。工作台预览,HTML / CSV 报告导出,支持沿用 Ai4Scholar API Key。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,116 @@
1
1
  {
2
2
  "name": "dsh-fulltext",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Ai4Scholar Fulltext for DeepSeek Harness: indexed full-text excerpt search, an interactive reading workspace, and offline HTML/CSV reports.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "ai4scholar",
8
+ "main": "./lib/index.js",
9
+ "types": "./lib/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./lib/index.d.ts",
13
+ "default": "./lib/index.js"
14
+ },
15
+ "./client": {
16
+ "types": "./lib/client-types/client/index.d.ts",
17
+ "default": "./lib/client.js"
18
+ },
19
+ "./package.json": "./package.json",
20
+ "./locale/*.json": "./locale/*.json"
21
+ },
22
+ "files": [
23
+ "lib",
24
+ "assets",
25
+ "locale",
26
+ "cordis.patch.yml",
27
+ "README.md",
28
+ "LICENSE",
29
+ "CHANGELOG.md",
30
+ "README_CN.md",
31
+ "RELEASING.md"
32
+ ],
33
+ "sideEffects": false,
34
+ "keywords": [
35
+ "dsh-plugin",
36
+ "deepseek-harness",
37
+ "fulltext",
38
+ "ai4scholar",
39
+ "semantic-scholar"
40
+ ],
41
+ "engines": {
42
+ "node": ">=22.19.0"
43
+ },
44
+ "dsh": {
45
+ "bundle": {
46
+ "patch": "./cordis.patch.yml"
47
+ },
48
+ "client": {
49
+ "platform": "web",
50
+ "inject": [
51
+ "@deepseek-ai/dsh-client-runtime",
52
+ "@deepseek-ai/dsh-client-connection",
53
+ "@deepseek-ai/dsh-client-ui-layout",
54
+ "@deepseek-ai/dsh-client-ui-sidebar"
55
+ ]
56
+ }
57
+ },
58
+ "publishConfig": {
59
+ "access": "public",
60
+ "registry": "https://registry.npmjs.org/"
61
+ },
62
+ "scripts": {
63
+ "build": "pnpm run build:lib && pnpm run build:client",
64
+ "build:lib": "tsc -p tsconfig.build.json",
65
+ "build:client": "tsdown && tsc -p tsconfig.client-types.json",
66
+ "clean": "rm -rf lib",
67
+ "typecheck": "tsc -p tsconfig.json",
68
+ "pretest": "pnpm run build",
69
+ "test": "vitest run",
70
+ "prepare": "pnpm run build",
71
+ "prepublishOnly": "pnpm run clean && pnpm run typecheck && pnpm run test",
72
+ "postpublish": "node scripts/sync-mirror.mjs",
73
+ "sync-mirror": "node scripts/sync-mirror.mjs"
74
+ },
75
+ "dependencies": {},
76
+ "peerDependencies": {
77
+ "@deepseek-ai/cordis": ">=4.0.1",
78
+ "@deepseek-ai/dsh-commands": ">=0.1.0-rc.6",
79
+ "@deepseek-ai/dsh-credentials": ">=0.1.0-rc.6",
80
+ "@deepseek-ai/dsh-llm": ">=0.1.0-rc.6",
81
+ "@deepseek-ai/dsh-system-prompt": ">=0.1.0-rc.6",
82
+ "@deepseek-ai/dsh-tools": ">=0.1.0-rc.6",
83
+ "@deepseek-ai/schemastery": ">=3.18.1",
84
+ "react": "^18.2.0"
85
+ },
86
+ "peerDependenciesMeta": {
87
+ "react": {
88
+ "optional": true
89
+ },
90
+ "@deepseek-ai/dsh-commands": {
91
+ "optional": true
92
+ }
93
+ },
94
+ "devDependencies": {
95
+ "@deepseek-ai/cordis": "4.0.2",
96
+ "@deepseek-ai/dsh-client-runtime": "0.1.1-rc.2",
97
+ "@deepseek-ai/dsh-commands": "0.1.1-rc.2",
98
+ "@deepseek-ai/dsh-credentials": "0.1.1-rc.2",
99
+ "@deepseek-ai/dsh-llm": "0.1.1-rc.2",
100
+ "@deepseek-ai/dsh-system-prompt": "0.1.1-rc.2",
101
+ "@deepseek-ai/dsh-tools": "0.1.1-rc.2",
102
+ "@deepseek-ai/schemastery": "3.18.5",
103
+ "@types/jsdom": "^21.1.7",
104
+ "@types/node": "^22.20.0",
105
+ "@types/react": "^18.3.31",
106
+ "@types/react-dom": "^18.3.7",
107
+ "jsdom": "^26.1.0",
108
+ "react": "^18.3.1",
109
+ "react-dom": "^18.3.1",
110
+ "tsdown": "^0.22.14",
111
+ "typescript": "^5.9.0",
112
+ "vitest": "^4.1.8"
113
+ },
114
+ "icon": "./assets/icon.svg",
115
+ "homepage": "https://www.npmjs.com/package/dsh-fulltext"
116
+ }