dsh-mineru 0.1.7
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/CHANGELOG.md +56 -0
- package/CONTRIBUTING.md +30 -0
- package/LICENSE +21 -0
- package/README.md +147 -0
- package/README.zh.md +147 -0
- package/RELEASE.md +87 -0
- package/cordis.patch.yml +8 -0
- package/lib/artifacts.js +307 -0
- package/lib/client.js +559 -0
- package/lib/config.js +174 -0
- package/lib/http.js +452 -0
- package/lib/index.js +135 -0
- package/lib/mineru-client.js +826 -0
- package/lib/skill.js +10 -0
- package/lib/tools.js +667 -0
- package/lib/types/client.d.ts +8 -0
- package/lib/types/index.d.ts +11 -0
- package/lib/zip.js +337 -0
- package/package.json +77 -0
package/lib/config.js
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-mineru configuration schema and defaults.
|
|
3
|
+
*
|
|
4
|
+
* The config document carries only references — the MinerU token VALUE lives in
|
|
5
|
+
* DSH Credentials under the `tokenCredential` reference name (default
|
|
6
|
+
* MINERU_API_TOKEN), never in settings or composition files.
|
|
7
|
+
*
|
|
8
|
+
* Resolution layers per the settings seam: schema defaults < composition base
|
|
9
|
+
* (the bundle row's config) < the user settings section (written through the
|
|
10
|
+
* Web Settings card or any host-side settings.update).
|
|
11
|
+
* @module dsh-mineru/config
|
|
12
|
+
*/
|
|
13
|
+
import z from '@deepseek-ai/schemastery';
|
|
14
|
+
|
|
15
|
+
/** Supported MinerU document languages (language packs from the API docs). */
|
|
16
|
+
export const LANGUAGE_VALUES = Object.freeze([
|
|
17
|
+
'ch', 'ch_server', 'en', 'japan', 'korean', 'chinese_cht',
|
|
18
|
+
'ta', 'te', 'ka', 'el', 'th',
|
|
19
|
+
'latin', 'arabic', 'cyrillic', 'east_slavic', 'devanagari',
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
/** Precision-API model versions. */
|
|
23
|
+
export const MODEL_VERSION_VALUES = Object.freeze(['pipeline', 'vlm', 'MinerU-HTML']);
|
|
24
|
+
|
|
25
|
+
/** API-mode selection. 'auto' resolves token present -> precision, absent -> agent. */
|
|
26
|
+
export const MODE_VALUES = Object.freeze(['auto', 'precision', 'agent']);
|
|
27
|
+
|
|
28
|
+
/** Extra export formats the precision API can add to the result zip. */
|
|
29
|
+
export const EXTRA_FORMAT_VALUES = Object.freeze(['docx', 'html', 'latex']);
|
|
30
|
+
|
|
31
|
+
/** Model-facing exposure strategy. */
|
|
32
|
+
export const EXPOSE_MODE_VALUES = Object.freeze(['progressive', 'always']);
|
|
33
|
+
|
|
34
|
+
/** File extensions MinerU accepts (precision). */
|
|
35
|
+
export const SUPPORTED_EXTENSIONS = Object.freeze([
|
|
36
|
+
'.pdf', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx',
|
|
37
|
+
'.png', '.jpg', '.jpeg', '.jp2', '.webp', '.gif', '.bmp', '.html', '.htm',
|
|
38
|
+
]);
|
|
39
|
+
|
|
40
|
+
/** Extensions the Agent lightweight API rejects (HTML is precision-only). */
|
|
41
|
+
export const AGENT_UNSUPPORTED_EXTENSIONS = Object.freeze(['.html', '.htm', '.doc', '.ppt', '.xls']);
|
|
42
|
+
|
|
43
|
+
export const DEFAULTS = Object.freeze({
|
|
44
|
+
apiBaseUrl: 'https://mineru.net',
|
|
45
|
+
/** DSH Credential reference that holds the MinerU token. Never a secret itself. */
|
|
46
|
+
tokenCredential: 'MINERU_API_TOKEN',
|
|
47
|
+
/** auto | precision | agent */
|
|
48
|
+
mode: 'auto',
|
|
49
|
+
/** Precision model: pipeline | vlm | MinerU-HTML. HTML sources force MinerU-HTML. */
|
|
50
|
+
modelVersion: 'vlm',
|
|
51
|
+
language: 'ch',
|
|
52
|
+
enableTable: true,
|
|
53
|
+
enableFormula: true,
|
|
54
|
+
isOcr: false,
|
|
55
|
+
/** Precision-only extra exports: docx | html | latex. */
|
|
56
|
+
extraFormats: [],
|
|
57
|
+
/** progressive: bootstrap + per-agent activation; always: register everything globally. */
|
|
58
|
+
exposeMode: 'progressive',
|
|
59
|
+
/** Artifact root directory name under each session workspace. */
|
|
60
|
+
artifactRootName: '.dsh-mineru',
|
|
61
|
+
/** Base poll interval for task result queries (ms). */
|
|
62
|
+
pollIntervalMs: 3000,
|
|
63
|
+
/** Random poll jitter added per query (ms). */
|
|
64
|
+
pollJitterMs: 500,
|
|
65
|
+
/** Whole-operation deadline (ms). */
|
|
66
|
+
timeoutMs: 600000,
|
|
67
|
+
/** Local file byte cap. 0 = per-mode API limits (200 MB precision / 10 MB agent). */
|
|
68
|
+
maxFileBytes: 0,
|
|
69
|
+
/** Markdown preview bytes returned inline with the tool result. */
|
|
70
|
+
inlineMarkdownBytes: 12000,
|
|
71
|
+
/** Signed artifact URL lifetime (seconds). */
|
|
72
|
+
artifactUrlTtlSec: 86400,
|
|
73
|
+
/** Client-side submission rate cap (official limit: 50 files/min). */
|
|
74
|
+
submitRatePerMin: 40,
|
|
75
|
+
/** Client-side result-query rate cap (official limit: 1000/min). */
|
|
76
|
+
pollRatePerMin: 900,
|
|
77
|
+
/** Daily submission cap reported before the API rejects (official: 5000 files/day). */
|
|
78
|
+
dailySubmitLimit: 5000,
|
|
79
|
+
userAgent: 'dsh-mineru (+DeepSeek-Harness)',
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
export const CONFIG_SCHEMA = z.object({
|
|
83
|
+
apiBaseUrl: z.string().role('text')
|
|
84
|
+
.default(DEFAULTS.apiBaseUrl)
|
|
85
|
+
.description('MinerU API base URL (https://mineru.net).'),
|
|
86
|
+
tokenCredential: z.string().role('text')
|
|
87
|
+
.default(DEFAULTS.tokenCredential)
|
|
88
|
+
.description('DSH Credential reference name holding the MinerU token.'),
|
|
89
|
+
mode: z.union([z.const('auto'), z.const('precision'), z.const('agent')])
|
|
90
|
+
.default(DEFAULTS.mode)
|
|
91
|
+
.description('API mode: auto (token present -> precision, else agent), precision, or agent.'),
|
|
92
|
+
modelVersion: z.union([z.const('pipeline'), z.const('vlm'), z.const('MinerU-HTML')])
|
|
93
|
+
.default(DEFAULTS.modelVersion)
|
|
94
|
+
.description('Precision-API model version (pipeline | vlm | MinerU-HTML).'),
|
|
95
|
+
language: z.string().role('text')
|
|
96
|
+
.default(DEFAULTS.language)
|
|
97
|
+
.description('Document language pack, e.g. ch, en, latin (see README table).'),
|
|
98
|
+
enableTable: z.boolean().default(DEFAULTS.enableTable)
|
|
99
|
+
.description('Enable table recognition.'),
|
|
100
|
+
enableFormula: z.boolean().default(DEFAULTS.enableFormula)
|
|
101
|
+
.description('Enable formula recognition.'),
|
|
102
|
+
isOcr: z.boolean().default(DEFAULTS.isOcr)
|
|
103
|
+
.description('Force OCR for scanned content.'),
|
|
104
|
+
extraFormats: z.array(z.union([z.const('docx'), z.const('html'), z.const('latex')]))
|
|
105
|
+
.default(DEFAULTS.extraFormats)
|
|
106
|
+
.description('Precision-only extra export formats added to the result zip.'),
|
|
107
|
+
exposeMode: z.union([z.const('progressive'), z.const('always')])
|
|
108
|
+
.default(DEFAULTS.exposeMode)
|
|
109
|
+
.description('progressive: mineru_activate bootstrap + skill-based activation; always: register all tools globally.'),
|
|
110
|
+
artifactRootName: z.string().role('text')
|
|
111
|
+
.default(DEFAULTS.artifactRootName)
|
|
112
|
+
.description('Artifact root directory name inside each session workspace.'),
|
|
113
|
+
pollIntervalMs: z.number().default(DEFAULTS.pollIntervalMs)
|
|
114
|
+
.description('Task-result poll interval (ms).'),
|
|
115
|
+
pollJitterMs: z.number().default(DEFAULTS.pollJitterMs)
|
|
116
|
+
.description('Per-query poll jitter (ms).'),
|
|
117
|
+
timeoutMs: z.number().default(DEFAULTS.timeoutMs)
|
|
118
|
+
.description('Whole-operation deadline (ms).'),
|
|
119
|
+
maxFileBytes: z.number().default(DEFAULTS.maxFileBytes)
|
|
120
|
+
.description('Local file byte cap; 0 = per-mode API limits (200 MB / 10 MB).'),
|
|
121
|
+
inlineMarkdownBytes: z.number().default(DEFAULTS.inlineMarkdownBytes)
|
|
122
|
+
.description('Markdown preview bytes returned inline with the tool result.'),
|
|
123
|
+
artifactUrlTtlSec: z.number().default(DEFAULTS.artifactUrlTtlSec)
|
|
124
|
+
.description('Signed artifact preview URL lifetime (seconds).'),
|
|
125
|
+
submitRatePerMin: z.number().default(DEFAULTS.submitRatePerMin)
|
|
126
|
+
.description('Submission rate cap per minute (official limit: 50/min).'),
|
|
127
|
+
pollRatePerMin: z.number().default(DEFAULTS.pollRatePerMin)
|
|
128
|
+
.description('Result-query rate cap per minute (official limit: 1000/min).'),
|
|
129
|
+
dailySubmitLimit: z.number().default(DEFAULTS.dailySubmitLimit)
|
|
130
|
+
.description('Daily submission cap reported before the API rejects (official: 5000/day).'),
|
|
131
|
+
userAgent: z.string().role('text').default(DEFAULTS.userAgent)
|
|
132
|
+
.description('User-Agent header sent to MinerU.'),
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Validate one resolved config section (schema has already run).
|
|
137
|
+
* Cross-field and range constraints the schema cannot express.
|
|
138
|
+
* @param {object} value resolved section
|
|
139
|
+
* @throws {Error} when the section is unusable
|
|
140
|
+
*/
|
|
141
|
+
export function validateConfig(value) {
|
|
142
|
+
const err = (msg) => { throw new Error('dsh-mineru config: ' + msg); };
|
|
143
|
+
if (!MODE_VALUES.includes(value.mode)) err('mode must be one of ' + MODE_VALUES.join('|'));
|
|
144
|
+
if (!MODEL_VERSION_VALUES.includes(value.modelVersion)) err('modelVersion must be one of ' + MODEL_VERSION_VALUES.join('|'));
|
|
145
|
+
if (!LANGUAGE_VALUES.includes(value.language)) err('language must be one of ' + LANGUAGE_VALUES.join('|'));
|
|
146
|
+
if (!EXPOSE_MODE_VALUES.includes(value.exposeMode)) err('exposeMode must be one of ' + EXPOSE_MODE_VALUES.join('|'));
|
|
147
|
+
for (const f of value.extraFormats) {
|
|
148
|
+
if (!EXTRA_FORMAT_VALUES.includes(f)) err('extraFormats may only contain ' + EXTRA_FORMAT_VALUES.join('|'));
|
|
149
|
+
}
|
|
150
|
+
if (!/^https?:\/\//i.test(value.apiBaseUrl ?? '')) err('apiBaseUrl must be an http(s) URL');
|
|
151
|
+
const integerIn = (name, v, min, max) => {
|
|
152
|
+
if (!Number.isInteger(v) || v < min || v > max) err(name + ' must be an integer in [' + min + ', ' + max + ']');
|
|
153
|
+
};
|
|
154
|
+
integerIn('pollIntervalMs', value.pollIntervalMs, 500, 60000);
|
|
155
|
+
integerIn('pollJitterMs', value.pollJitterMs, 0, 10000);
|
|
156
|
+
integerIn('timeoutMs', value.timeoutMs, 10000, 3600000);
|
|
157
|
+
integerIn('maxFileBytes', value.maxFileBytes, 0, 512 * 1024 * 1024);
|
|
158
|
+
integerIn('inlineMarkdownBytes', value.inlineMarkdownBytes, 256, 1024 * 1024);
|
|
159
|
+
integerIn('artifactUrlTtlSec', value.artifactUrlTtlSec, 60, 30 * 24 * 3600);
|
|
160
|
+
integerIn('submitRatePerMin', value.submitRatePerMin, 1, 60);
|
|
161
|
+
integerIn('pollRatePerMin', value.pollRatePerMin, 10, 1000);
|
|
162
|
+
integerIn('dailySubmitLimit', value.dailySubmitLimit, 1, 100000);
|
|
163
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value.tokenCredential ?? '')) err('tokenCredential must be a POSIX-shell-shaped reference name');
|
|
164
|
+
const root = value.artifactRootName ?? '';
|
|
165
|
+
if (!root || root.includes('/') || root.includes('\\') || root === '.' || root === '..') err('artifactRootName must be a single directory name');
|
|
166
|
+
return value;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** Merged defaults + overrides (used at plugin load for exposeMode, which is composition-scoped). */
|
|
170
|
+
export function resolveLoadConfig(config) {
|
|
171
|
+
const value = { ...DEFAULTS, ...(config ?? {}) };
|
|
172
|
+
validateConfig(value);
|
|
173
|
+
return value;
|
|
174
|
+
}
|
package/lib/http.js
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web host surface for the Web profile: /plugin/mineru/* routes serving the
|
|
3
|
+
* Settings card, credential writes, token/agent connection tests, and signed
|
|
4
|
+
* artifact preview/download.
|
|
5
|
+
*
|
|
6
|
+
* Config reads/writes go through the settings seam (revision-fenced); the
|
|
7
|
+
* token VALUE crosses the wire only inside a POST body and is stored through
|
|
8
|
+
* the credentials seam. Origin checks allow only same-origin browser calls.
|
|
9
|
+
* @module dsh-mineru/http
|
|
10
|
+
*/
|
|
11
|
+
import { createReadStream, createWriteStream } from 'node:fs';
|
|
12
|
+
import { randomBytes } from 'node:crypto';
|
|
13
|
+
import { mkdir, rm, stat } from 'node:fs/promises';
|
|
14
|
+
import { join } from 'node:path';
|
|
15
|
+
import { SettingsConflictError } from '@deepseek-ai/dsh-settings';
|
|
16
|
+
import { MineruError } from './mineru-client.js';
|
|
17
|
+
import { ArtifactError, inlineable, sanitizeFileName } from './artifacts.js';
|
|
18
|
+
import { DEFAULTS, SUPPORTED_EXTENSIONS } from './config.js';
|
|
19
|
+
|
|
20
|
+
const JSON_BODY_LIMIT = 1 << 20;
|
|
21
|
+
|
|
22
|
+
function readBody(req, limit = JSON_BODY_LIMIT) {
|
|
23
|
+
return new Promise((resolve, reject) => {
|
|
24
|
+
const chunks = [];
|
|
25
|
+
let size = 0;
|
|
26
|
+
req.on('data', (c) => {
|
|
27
|
+
size += c.length;
|
|
28
|
+
if (size > limit) {
|
|
29
|
+
reject(new Error('body too large'));
|
|
30
|
+
req.destroy();
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
chunks.push(c);
|
|
34
|
+
});
|
|
35
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
36
|
+
req.on('error', reject);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function sendJson(res, status, payload) {
|
|
41
|
+
const body = JSON.stringify(payload);
|
|
42
|
+
res.writeHead(status, {
|
|
43
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
44
|
+
'Cache-Control': 'no-store',
|
|
45
|
+
'X-Content-Type-Options': 'nosniff',
|
|
46
|
+
});
|
|
47
|
+
res.end(body);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function sendText(res, status, text) {
|
|
51
|
+
res.writeHead(status, {
|
|
52
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
53
|
+
'Cache-Control': 'no-store',
|
|
54
|
+
'X-Content-Type-Options': 'nosniff',
|
|
55
|
+
});
|
|
56
|
+
res.end(text);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sendEmpty(res, status) {
|
|
60
|
+
res.writeHead(status, { 'X-Content-Type-Options': 'nosniff' });
|
|
61
|
+
res.end();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** @param {string} value */
|
|
65
|
+
function stripToken(value) {
|
|
66
|
+
const v = String(value ?? '').trim();
|
|
67
|
+
return v.length > 0 && v.length <= 4096 ? v : undefined;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Mount the /plugin/mineru route tree.
|
|
72
|
+
* @param {object} ctx injected web context (webServer service available)
|
|
73
|
+
* @param {object} deps
|
|
74
|
+
* @param {object} deps.settings the settings service (describe)
|
|
75
|
+
* @param {object} deps.scope the mineru SettingsScope (get/update)
|
|
76
|
+
* @param {object} deps.credentials the credentials service
|
|
77
|
+
* @param {object} deps.schema the registered schemastery schema
|
|
78
|
+
* @param {object} deps.state plugin state (clientFor, collectFacts, artifacts)
|
|
79
|
+
*/
|
|
80
|
+
export function mountHttp(ctx, deps) {
|
|
81
|
+
const { webServer } = ctx;
|
|
82
|
+
ctx.effect(() => webServer.register({
|
|
83
|
+
kind: 'prefix',
|
|
84
|
+
path: '/plugin/mineru',
|
|
85
|
+
handler: (req, res) => handle(req, res, { ...deps, webServer }).catch((err) => {
|
|
86
|
+
if (!res.headersSent) {
|
|
87
|
+
if (err instanceof ArtifactError) {
|
|
88
|
+
const status = err.code === 'ARTIFACT_NOT_FOUND' ? 404 : 400;
|
|
89
|
+
sendJson(res, status, { ok: false, error: err.message });
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
sendJson(res, 500, { ok: false, error: 'internal error: ' + String(err?.message ?? err).slice(0, 400) });
|
|
93
|
+
} else {
|
|
94
|
+
res.destroy();
|
|
95
|
+
}
|
|
96
|
+
}),
|
|
97
|
+
}));
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function handle(req, res, deps) {
|
|
101
|
+
const { webServer } = deps;
|
|
102
|
+
const method = req.method ?? 'GET';
|
|
103
|
+
const url = new URL(req.url ?? '/', 'http://localhost');
|
|
104
|
+
const pathname = url.pathname.replace(/\/+$/, '') || '/';
|
|
105
|
+
const route = pathname.slice('/plugin/mineru'.length) || '/';
|
|
106
|
+
|
|
107
|
+
// Same-origin only: refuse requests carrying a foreign Origin header.
|
|
108
|
+
const origin = req.headers.origin;
|
|
109
|
+
if (origin) {
|
|
110
|
+
const allowed = new Set([
|
|
111
|
+
'http://' + webServer.host + ':' + webServer.port,
|
|
112
|
+
'http://localhost:' + webServer.port,
|
|
113
|
+
'http://127.0.0.1:' + webServer.port,
|
|
114
|
+
]);
|
|
115
|
+
if (!allowed.has(origin)) {
|
|
116
|
+
sendJson(res, 403, { ok: false, error: 'cross-origin request refused' });
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
if (method === 'OPTIONS') {
|
|
121
|
+
// No CORS headers: cross-origin preflights fail, same-origin calls proceed.
|
|
122
|
+
sendEmpty(res, 204);
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (route === '/' && method === 'GET') {
|
|
127
|
+
const facts = await deps.state.collectFacts();
|
|
128
|
+
sendJson(res, 200, { ok: true, health: facts, plugin: 'dsh-mineru' });
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
if (route === '/config' && method === 'GET') {
|
|
132
|
+
const descriptor = (deps.settings.describe({ redactSecrets: true }) ?? [])
|
|
133
|
+
.find((d) => d.ns === 'mineru');
|
|
134
|
+
const facts = await deps.state.collectFacts();
|
|
135
|
+
sendJson(res, 200, {
|
|
136
|
+
ok: true,
|
|
137
|
+
revision: descriptor?.revision ?? 0,
|
|
138
|
+
value: descriptor?.value ?? {},
|
|
139
|
+
base: descriptor?.base ?? {},
|
|
140
|
+
userOverrides: descriptor?.user ?? {},
|
|
141
|
+
applies: descriptor?.applies ?? 'live',
|
|
142
|
+
secrets: descriptor?.secrets ?? [],
|
|
143
|
+
facts,
|
|
144
|
+
schemaHints: {
|
|
145
|
+
modes: ['auto', 'precision', 'agent'],
|
|
146
|
+
modelVersions: ['pipeline', 'vlm', 'MinerU-HTML'],
|
|
147
|
+
extraFormats: ['docx', 'html', 'latex'],
|
|
148
|
+
languages: [
|
|
149
|
+
'ch', 'ch_server', 'en', 'japan', 'korean', 'chinese_cht',
|
|
150
|
+
'ta', 'te', 'ka', 'el', 'th',
|
|
151
|
+
'latin', 'arabic', 'cyrillic', 'east_slavic', 'devanagari',
|
|
152
|
+
],
|
|
153
|
+
defaults: DEFAULTS,
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (route === '/config' && method === 'POST') {
|
|
159
|
+
const raw = await readBody(req);
|
|
160
|
+
let body;
|
|
161
|
+
try { body = JSON.parse(raw || '{}'); } catch { sendJson(res, 400, { ok: false, error: 'invalid JSON body' }); return; }
|
|
162
|
+
const patch = body && typeof body.patch === 'object' && body.patch !== null ? body.patch : null;
|
|
163
|
+
if (!patch) { sendJson(res, 400, { ok: false, error: 'missing patch object' }); return; }
|
|
164
|
+
try {
|
|
165
|
+
await deps.settings.update('mineru', patch, Number.isInteger(body.expectedRevision) ? body.expectedRevision : undefined);
|
|
166
|
+
const descriptor = (deps.settings.describe({ redactSecrets: true }) ?? []).find((d) => d.ns === 'mineru');
|
|
167
|
+
sendJson(res, 200, { ok: true, revision: descriptor?.revision ?? 0 });
|
|
168
|
+
} catch (err) {
|
|
169
|
+
if (err instanceof SettingsConflictError) {
|
|
170
|
+
sendJson(res, 409, { ok: false, conflict: true, error: '设置已被其他会话修改, 请刷新后重试.', currentRevision: err.actual });
|
|
171
|
+
} else {
|
|
172
|
+
sendJson(res, 400, { ok: false, error: String(err?.message ?? err).slice(0, 500) });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
if (route === '/credential' && method === 'POST') {
|
|
178
|
+
const raw = await readBody(req);
|
|
179
|
+
let body;
|
|
180
|
+
try { body = JSON.parse(raw || '{}'); } catch { sendJson(res, 400, { ok: false, error: 'invalid JSON body' }); return; }
|
|
181
|
+
const cfg = deps.scope.get();
|
|
182
|
+
const refName = typeof body.ref === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(body.ref) ? body.ref : cfg.tokenCredential;
|
|
183
|
+
let ref;
|
|
184
|
+
try {
|
|
185
|
+
ref = (await import('@deepseek-ai/dsh-credentials')).credentialRef(refName);
|
|
186
|
+
} catch {
|
|
187
|
+
sendJson(res, 400, { ok: false, error: 'invalid credential reference' });
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
try {
|
|
191
|
+
if (body.clear === true) {
|
|
192
|
+
await deps.credentials.unset(ref);
|
|
193
|
+
} else {
|
|
194
|
+
const value = stripToken(body.value);
|
|
195
|
+
if (value === undefined) { sendJson(res, 400, { ok: false, error: 'value 为空或过长 (1..4096 字符)' }); return; }
|
|
196
|
+
await deps.credentials.set(ref, value);
|
|
197
|
+
}
|
|
198
|
+
const describe = await deps.credentials.describe(ref);
|
|
199
|
+
sendJson(res, 200, { ok: true, ref: refName, configured: Boolean(describe?.configured) });
|
|
200
|
+
} catch (err) {
|
|
201
|
+
sendJson(res, 400, { ok: false, error: String(err?.message ?? err).slice(0, 400) });
|
|
202
|
+
}
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (route === '/test-token' && method === 'POST') {
|
|
206
|
+
const outcome = await testToken(deps);
|
|
207
|
+
sendJson(res, outcome.status, outcome.body);
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
if (route === '/test-agent' && method === 'POST') {
|
|
211
|
+
const outcome = await testAgent(deps);
|
|
212
|
+
sendJson(res, outcome.status, outcome.body);
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (route === '/artifact' && method === 'GET') {
|
|
216
|
+
await serveArtifact(req, res, deps, url);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
if (route === '/upload' && method === 'POST') {
|
|
220
|
+
await handleUpload(req, res, deps, url);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
sendJson(res, 404, { ok: false, error: 'unknown route: ' + route });
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Token connection test: submits the official one-page demo PDF through the
|
|
227
|
+
* precision API and polls briefly. Success proves the token works; this is an
|
|
228
|
+
* explicit user action and consumes at most one page of the 1000-page daily
|
|
229
|
+
* priority quota.
|
|
230
|
+
*/
|
|
231
|
+
async function testToken(deps) {
|
|
232
|
+
const cfg = deps.scope.get();
|
|
233
|
+
const client = await deps.state.clientFor(cfg);
|
|
234
|
+
if (!client.precisionEnabled()) {
|
|
235
|
+
return { status: 400, body: { ok: false, error: '未配置 MinerU Token: 请先在上方填写并保存 Token.' } };
|
|
236
|
+
}
|
|
237
|
+
const demo = 'https://cdn-mineru.openxlab.org.cn/demo/example.pdf';
|
|
238
|
+
const opts = {
|
|
239
|
+
language: cfg.language,
|
|
240
|
+
enableTable: true,
|
|
241
|
+
enableFormula: true,
|
|
242
|
+
isOcr: false,
|
|
243
|
+
modelVersion: 'vlm',
|
|
244
|
+
pageRanges: undefined,
|
|
245
|
+
pageRange: undefined,
|
|
246
|
+
extraFormats: [],
|
|
247
|
+
dataId: 'dsh-mineru-token-test',
|
|
248
|
+
timeoutMs: 180000,
|
|
249
|
+
pollIntervalMs: 2000,
|
|
250
|
+
pollJitterMs: 200,
|
|
251
|
+
};
|
|
252
|
+
const controller = new AbortController();
|
|
253
|
+
const timer = setTimeout(() => controller.abort(), 185000);
|
|
254
|
+
try {
|
|
255
|
+
const outcome = await client.submitAndWaitUrl({
|
|
256
|
+
url: demo,
|
|
257
|
+
fileName: 'example.pdf',
|
|
258
|
+
opts,
|
|
259
|
+
api: 'precision',
|
|
260
|
+
signal: controller.signal,
|
|
261
|
+
});
|
|
262
|
+
return {
|
|
263
|
+
status: 200,
|
|
264
|
+
body: {
|
|
265
|
+
ok: true,
|
|
266
|
+
message: 'Token 有效: 示例 PDF 解析成功 (taskId=' + outcome.taskId + '). 本次测试消耗约 1 页精准解析额度.',
|
|
267
|
+
},
|
|
268
|
+
};
|
|
269
|
+
} catch (err) {
|
|
270
|
+
const message = err instanceof MineruError ? err.message : String(err?.message ?? err);
|
|
271
|
+
return { status: 400, body: { ok: false, error: message } };
|
|
272
|
+
} finally {
|
|
273
|
+
clearTimeout(timer);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Agent API availability test: submits the demo PDF through the tokenless
|
|
279
|
+
* Agent lightweight API. Reports success or the current IP rate-limit state.
|
|
280
|
+
*/
|
|
281
|
+
async function testAgent(deps) {
|
|
282
|
+
const cfg = deps.scope.get();
|
|
283
|
+
const client = await deps.state.clientFor(cfg);
|
|
284
|
+
const opts = {
|
|
285
|
+
language: cfg.language,
|
|
286
|
+
enableTable: true,
|
|
287
|
+
enableFormula: true,
|
|
288
|
+
isOcr: false,
|
|
289
|
+
modelVersion: 'vlm',
|
|
290
|
+
pageRanges: undefined,
|
|
291
|
+
pageRange: undefined,
|
|
292
|
+
extraFormats: [],
|
|
293
|
+
dataId: undefined,
|
|
294
|
+
timeoutMs: 180000,
|
|
295
|
+
pollIntervalMs: 2000,
|
|
296
|
+
pollJitterMs: 200,
|
|
297
|
+
};
|
|
298
|
+
const controller = new AbortController();
|
|
299
|
+
const timer = setTimeout(() => controller.abort(), 185000);
|
|
300
|
+
try {
|
|
301
|
+
const outcome = await client.submitAndWaitUrl({
|
|
302
|
+
url: 'https://cdn-mineru.openxlab.org.cn/demo/example.pdf',
|
|
303
|
+
fileName: 'example.pdf',
|
|
304
|
+
opts,
|
|
305
|
+
api: 'agent',
|
|
306
|
+
signal: controller.signal,
|
|
307
|
+
});
|
|
308
|
+
return {
|
|
309
|
+
status: 200,
|
|
310
|
+
body: {
|
|
311
|
+
ok: true,
|
|
312
|
+
message: 'Agent 轻量解析 API 可用: 示例 PDF 解析成功 (taskId=' + outcome.taskId + ').',
|
|
313
|
+
},
|
|
314
|
+
};
|
|
315
|
+
} catch (err) {
|
|
316
|
+
const message = err instanceof MineruError ? err.message : String(err?.message ?? err);
|
|
317
|
+
return { status: 400, body: { ok: false, error: message } };
|
|
318
|
+
} finally {
|
|
319
|
+
clearTimeout(timer);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Serve one signed artifact. */
|
|
324
|
+
async function serveArtifact(req, res, deps, url) {
|
|
325
|
+
const w = url.searchParams.get('w');
|
|
326
|
+
const p = url.searchParams.get('p');
|
|
327
|
+
const t = url.searchParams.get('t');
|
|
328
|
+
const manager = deps.state.artifacts.managerByIndex(w);
|
|
329
|
+
if (!manager) { sendJson(res, 404, { ok: false, error: 'workspace not found' }); return; }
|
|
330
|
+
const check = manager.verifyCapability(w + '|' + p, t);
|
|
331
|
+
if (!check.ok) { sendJson(res, 401, { ok: false, error: 'invalid capability token' }); return; }
|
|
332
|
+
if (check.expired) { sendJson(res, 410, { ok: false, error: 'artifact link expired' }); return; }
|
|
333
|
+
let info;
|
|
334
|
+
try {
|
|
335
|
+
info = await manager.resolveServe(p, { maxBytes: 256 << 20 });
|
|
336
|
+
} catch (err) {
|
|
337
|
+
const status = err instanceof ArtifactError && err.code === 'ARTIFACT_NOT_FOUND' ? 404 : 400;
|
|
338
|
+
sendJson(res, status, { ok: false, error: String(err?.message ?? err) });
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
const disposition = inlineable(info.abs) ? 'inline' : 'attachment';
|
|
342
|
+
res.writeHead(200, {
|
|
343
|
+
'Content-Type': info.mime,
|
|
344
|
+
'Content-Length': info.bytes,
|
|
345
|
+
'Content-Disposition': disposition,
|
|
346
|
+
'Cache-Control': 'private, max-age=3600',
|
|
347
|
+
'X-Content-Type-Options': 'nosniff',
|
|
348
|
+
});
|
|
349
|
+
if (req.method === 'HEAD') { res.end(); return; }
|
|
350
|
+
const stream = createReadStream(info.abs);
|
|
351
|
+
stream.on('error', () => { res.destroy(); });
|
|
352
|
+
stream.pipe(res);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const UPLOAD_MAX_BYTES = 210 * 1024 * 1024; // precision limit (200MB) + margin
|
|
356
|
+
const UPLOAD_MEDIA = 'application/octet-stream';
|
|
357
|
+
|
|
358
|
+
function extOfPath(name) {
|
|
359
|
+
const i = name.lastIndexOf('.');
|
|
360
|
+
return i < 0 ? '' : name.slice(i).toLowerCase();
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* POST /plugin/mineru/upload?sessionId=<id>&name=<file>
|
|
365
|
+
* Raw octet-stream body streamed into <cwd>/.dsh-mineru/uploads/<stamp>/<name>.
|
|
366
|
+
* The client sends this for drag-dropped documents/images so the file lands
|
|
367
|
+
* inside the session workspace as a regular file (mineru_parse reads paths),
|
|
368
|
+
* instead of riding the native image-attachment channel that text-only models
|
|
369
|
+
* reject at prompt admission.
|
|
370
|
+
*/
|
|
371
|
+
async function handleUpload(req, res, deps, url) {
|
|
372
|
+
const sessionId = url.searchParams.get('sessionId');
|
|
373
|
+
const rawName = url.searchParams.get('name');
|
|
374
|
+
if (!sessionId || !rawName) {
|
|
375
|
+
sendJson(res, 400, { ok: false, error: 'missing sessionId or name' });
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
const name = (() => {
|
|
379
|
+
try { return sanitizeFileName(rawName); } catch { return ''; }
|
|
380
|
+
})();
|
|
381
|
+
if (!name || !SUPPORTED_EXTENSIONS.includes(extOfPath(name))) {
|
|
382
|
+
sendJson(res, 400, { ok: false, error: '不支持的文件类型: 仅支持 pdf/doc/docx/ppt/pptx/xls/xlsx/html 与 png/jpg/jpeg/jp2/webp/gif/bmp.' });
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
const ctype = String(req.headers['content-type'] ?? '').split(';')[0].trim();
|
|
386
|
+
if (ctype && ctype !== UPLOAD_MEDIA && ctype !== 'application/json') {
|
|
387
|
+
sendJson(res, 415, { ok: false, error: 'upload body must be application/octet-stream' });
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
// Resolve the session workspace through the live agent registry.
|
|
391
|
+
const agent = deps.agents.get(sessionId);
|
|
392
|
+
if (!agent) {
|
|
393
|
+
sendJson(res, 404, { ok: false, error: '会话不存在或未激活 (sessionId=' + sessionId + ')' });
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const cwd = agent.session?.header?.cwd;
|
|
397
|
+
if (!cwd) {
|
|
398
|
+
sendJson(res, 400, { ok: false, error: '会话没有工作区 (cwd 缺失)' });
|
|
399
|
+
return;
|
|
400
|
+
}
|
|
401
|
+
const manager = await deps.state.artifacts.managerFor(cwd);
|
|
402
|
+
// Timestamp + random suffix: concurrent/same-second uploads of the same name
|
|
403
|
+
// each land in their own directory instead of colliding on 'wx'.
|
|
404
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19) + '-' + randomBytes(3).toString('hex');
|
|
405
|
+
const dir = join(manager.rootDir, 'uploads', stamp);
|
|
406
|
+
await mkdir(dir, { recursive: true });
|
|
407
|
+
const target = join(dir, name);
|
|
408
|
+
const stream = createWriteStream(target, { flags: 'wx' });
|
|
409
|
+
let size = 0;
|
|
410
|
+
let aborted = false;
|
|
411
|
+
const fail = (status, message) => {
|
|
412
|
+
aborted = true;
|
|
413
|
+
stream.destroy();
|
|
414
|
+
rm(target, { force: true }).catch(() => {});
|
|
415
|
+
if (!res.headersSent) sendJson(res, status, { ok: false, error: message });
|
|
416
|
+
else res.destroy();
|
|
417
|
+
};
|
|
418
|
+
stream.on('error', () => fail(500, '写入上传文件失败'));
|
|
419
|
+
req.on('data', (chunk) => {
|
|
420
|
+
if (aborted) return;
|
|
421
|
+
size += chunk.length;
|
|
422
|
+
if (size > UPLOAD_MAX_BYTES) {
|
|
423
|
+
fail(413, '文件超过 200MB 上限 (精准解析 API 限制)');
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
if (!stream.write(chunk)) req.pause();
|
|
427
|
+
});
|
|
428
|
+
stream.on('drain', () => req.resume());
|
|
429
|
+
req.on('end', () => {
|
|
430
|
+
if (aborted) return;
|
|
431
|
+
stream.end(async () => {
|
|
432
|
+
try {
|
|
433
|
+
if (size === 0) {
|
|
434
|
+
await rm(target, { force: true });
|
|
435
|
+
sendJson(res, 400, { ok: false, error: '文件为空' });
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
const st = await stat(target);
|
|
439
|
+
sendJson(res, 200, { ok: true, path: target, bytes: st.size, name });
|
|
440
|
+
} catch (err) {
|
|
441
|
+
fail(500, '上传收尾失败: ' + String(err?.message ?? err).slice(0, 200));
|
|
442
|
+
}
|
|
443
|
+
});
|
|
444
|
+
});
|
|
445
|
+
req.on('error', () => {
|
|
446
|
+
if (!aborted) {
|
|
447
|
+
aborted = true;
|
|
448
|
+
stream.destroy();
|
|
449
|
+
rm(target, { force: true }).catch(() => {});
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
}
|