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.
@@ -0,0 +1,826 @@
1
+ /**
2
+ * MinerU API client: 精准解析 API (v4, token) and Agent 轻量解析 API (v1, no
3
+ * token), with client-side rate limiting, 429 handling, polling, result
4
+ * download, and zip extraction.
5
+ *
6
+ * Official limits honored by default (see docs):
7
+ * - submissions: 50 files/min shared across submit endpoints; 5000 files/day
8
+ * per user (max 100 HTML files/day)
9
+ * - result queries: 1000/min
10
+ * - precision: <= 200 MB, <= 200 pages, batch <= 200 urls / 50 upload links
11
+ * - agent: <= 10 MB, <= 20 pages, single file, Markdown-only output
12
+ * @module dsh-mineru/mineru-client
13
+ */
14
+ import { extname, join } from 'node:path';
15
+ import { createReadStream, createWriteStream } from 'node:fs';
16
+ import { mkdir, readFile, rm, stat } from 'node:fs/promises';
17
+ import { pipeline } from 'node:stream/promises';
18
+ import { Readable } from 'node:stream';
19
+ import { extractZip, readZipEntryText } from './zip.js';
20
+ import { AGENT_UNSUPPORTED_EXTENSIONS, MODEL_VERSION_VALUES, SUPPORTED_EXTENSIONS } from './config.js';
21
+
22
+ export class MineruError extends Error {
23
+ /**
24
+ * @param {string} message user-facing message
25
+ * @param {string} code stable machine code
26
+ * @param {{httpStatus?: number, taskId?: string, api?: string, rawCode?: string|number}} [info]
27
+ */
28
+ constructor(message, code = 'MINERU_ERROR', info = {}) {
29
+ super(message);
30
+ this.name = 'MineruError';
31
+ this.code = code;
32
+ this.httpStatus = info.httpStatus;
33
+ this.taskId = info.taskId;
34
+ this.api = info.api;
35
+ this.rawCode = info.rawCode;
36
+ }
37
+ }
38
+
39
+ const PRECISION_FILE_LIMIT = 200 * 1024 * 1024;
40
+ const AGENT_FILE_LIMIT = 10 * 1024 * 1024;
41
+
42
+ /** Map MinerU error codes to actionable messages. */
43
+ const ERROR_MESSAGES = Object.freeze({
44
+ A0202: 'MinerU Token 错误:请检查 Token 是否正确(Bearer 前缀由插件自动添加),或更换新 Token。',
45
+ A0211: 'MinerU Token 已过期:请更换新 Token。',
46
+ '-500': 'MinerU 传参错误:请检查参数类型及 Content-Type。',
47
+ '-10001': 'MinerU 服务异常,请稍后再试。',
48
+ '-10002': 'MinerU 请求参数错误:请检查请求参数格式。',
49
+ '-60001': 'MinerU 生成上传 URL 失败,请稍后再试。',
50
+ '-60002': 'MinerU 无法识别文件类型:请确认文件名带有正确的后缀(pdf/doc/docx/ppt/pptx/xls/xlsx/png/jpg/jpeg 等)。',
51
+ '-60003': 'MinerU 文件读取失败:请检查文件是否损坏并重新上传。',
52
+ '-60004': 'MinerU 收到空文件:请上传有效文件。',
53
+ '-60005': '文件大小超出限制:精准解析 API 最大支持 200MB,Agent 轻量解析 API 最大 10MB。',
54
+ '-60006': '文件页数超过限制:精准解析 API 最大 200 页,Agent 轻量解析 API 最大 20 页,请拆分文件或使用 page_ranges。',
55
+ '-60007': 'MinerU 模型服务暂时不可用,请稍后重试。',
56
+ '-60008': 'MinerU 文件读取超时:请检查 URL 是否可访问。',
57
+ '-60009': 'MinerU 任务提交队列已满,请稍后再试。',
58
+ '-60010': 'MinerU 解析失败,请稍后再试。',
59
+ '-60011': 'MinerU 获取有效文件失败:请确保文件已上传。',
60
+ '-60012': 'MinerU 找不到任务:请确认 task_id 有效且未删除。',
61
+ '-60013': 'MinerU 没有权限访问该任务:只能访问自己提交的任务。',
62
+ '-60014': 'MinerU 任务正在运行中,暂不支持删除。',
63
+ '-60015': 'MinerU 文件转换失败:可以手动转为 PDF 再上传。',
64
+ '-60017': 'MinerU 重试次数达到上限:请等后续模型升级后重试。',
65
+ '-60021': 'MinerU 读取文件页数失败,请稍后重试。',
66
+ '-60016': 'MinerU 文件转换失败:可以尝试其他导出格式或重试。',
67
+ '-60018': 'MinerU 每日解析任务数量已达上限,请明日再试。',
68
+ '-60019': 'MinerU HTML 文件解析额度不足,请明日再试。',
69
+ '-60020': 'MinerU 文件拆分失败,请稍后重试。',
70
+ '-60022': 'MinerU 网页读取失败:可能因网络问题或限频导致,请稍后重试。',
71
+ '-30001': '文件大小超出 Agent 轻量解析接口限制(10MB):请改用精准解析 API(填写 Token)或拆分文件。',
72
+ '-30002': 'Agent 轻量解析接口不支持该文件类型:请上传 PDF/图片/Docx/PPTx/Xlsx。',
73
+ '-30003': '文件页数超出 Agent 轻量解析接口限制(20 页):请改用精准解析 API 或指定 page_range。',
74
+ '-30004': 'MinerU Agent 接口请求参数错误:请检查必填参数。',
75
+ });
76
+
77
+ /** @param {string|number|undefined} code @returns {string|undefined} */
78
+ function messageForCode(code) {
79
+ if (code === undefined || code === null) return undefined;
80
+ return ERROR_MESSAGES[String(code)];
81
+ }
82
+
83
+ /**
84
+ * Abortable sleep.
85
+ * @param {number} ms
86
+ * @param {AbortSignal} [signal]
87
+ */
88
+ function sleep(ms, signal) {
89
+ return new Promise((resolve, reject) => {
90
+ if (signal?.aborted) { reject(abortError()); return; }
91
+ const timer = setTimeout(done, ms);
92
+ function done() {
93
+ signal?.removeEventListener('abort', onAbort);
94
+ resolve();
95
+ }
96
+ function onAbort() {
97
+ clearTimeout(timer);
98
+ reject(abortError());
99
+ }
100
+ signal?.addEventListener('abort', onAbort, { once: true });
101
+ });
102
+ }
103
+
104
+ function abortError() {
105
+ const err = new Error('operation aborted');
106
+ err.name = 'AbortError';
107
+ return err;
108
+ }
109
+
110
+ /** Simple client-side token bucket shared across concurrent calls. */
111
+ export class RateLimiter {
112
+ /**
113
+ * @param {number} perMinute tokens refilled per minute
114
+ * @param {{burst?: number}} [opts]
115
+ */
116
+ constructor(perMinute, opts = {}) {
117
+ this.rate = perMinute / 60000; // tokens per ms
118
+ this.capacity = Math.max(1, opts.burst ?? Math.ceil(perMinute / 5));
119
+ this.tokens = this.capacity;
120
+ this.updatedAt = Date.now();
121
+ }
122
+
123
+ /**
124
+ * Take one token, waiting if the bucket is empty.
125
+ * @param {AbortSignal} [signal]
126
+ */
127
+ async acquire(signal) {
128
+ for (;;) {
129
+ this.refill();
130
+ if (this.tokens >= 1) {
131
+ this.tokens -= 1;
132
+ return;
133
+ }
134
+ const waitMs = Math.ceil((1 - this.tokens) / this.rate);
135
+ await sleep(Math.min(waitMs, 5000), signal);
136
+ }
137
+ }
138
+
139
+ refill() {
140
+ const now = Date.now();
141
+ const delta = now - this.updatedAt;
142
+ if (delta > 0) {
143
+ this.tokens = Math.min(this.capacity, this.tokens + delta * this.rate);
144
+ this.updatedAt = now;
145
+ }
146
+ }
147
+ }
148
+
149
+ /** Best-effort daily submission counter (the API is authoritative). */
150
+ export class DailyCounter {
151
+ /**
152
+ * @param {number} limit daily submission cap
153
+ */
154
+ constructor(limit) {
155
+ this.limit = limit;
156
+ this.day = '';
157
+ this.count = 0;
158
+ }
159
+
160
+ /**
161
+ * @param {number} n files about to be submitted
162
+ */
163
+ add(n) {
164
+ const day = new Date().toISOString().slice(0, 10);
165
+ if (day !== this.day) { this.day = day; this.count = 0; }
166
+ this.count += n;
167
+ if (this.count > this.limit) {
168
+ throw new MineruError(
169
+ '已达本地每日提交上限 ' + this.limit + ' 个文件(MinerU 官方限制 5000 个/天,其中 html 最多 100 个),请明日再试。',
170
+ 'MINERU_DAILY_LIMIT',
171
+ );
172
+ }
173
+ }
174
+ }
175
+
176
+ function sanitizeDataId(value) {
177
+ const v = String(value ?? '').replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 128);
178
+ return v || undefined;
179
+ }
180
+
181
+ function normalizeBaseUrl(base) {
182
+ return String(base ?? '').trim().replace(/\/+$/, '');
183
+ }
184
+
185
+ /** @param {string} p */
186
+ function extOf(p) {
187
+ return extname(p).toLowerCase();
188
+ }
189
+
190
+ function mergeHeaders(base, extra) {
191
+ return { ...(base ?? {}), ...(extra ?? {}) };
192
+ }
193
+
194
+ /** @param {object} item @param {number} index @param {object} opts */
195
+ function dataIdFor(item, index, opts) {
196
+ return sanitizeDataId(item.dataId ?? (opts.dataIdPrefix ? opts.dataIdPrefix + '-' + (index + 1) : undefined));
197
+ }/** One HTTP request with JSON decoding. 429 throws a retryable MineruError. */
198
+ async function requestJson({ url, method = 'GET', headers = {}, body, signal, timeoutMs = 60000, userAgent }) {
199
+ const controller = new AbortController();
200
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
201
+ const onAbort = () => controller.abort();
202
+ signal?.addEventListener('abort', onAbort, { once: true });
203
+ let res;
204
+ try {
205
+ res = await fetch(url, {
206
+ method,
207
+ headers: { 'User-Agent': userAgent ?? 'dsh-mineru', ...headers },
208
+ body,
209
+ signal: controller.signal,
210
+ });
211
+ } catch (err) {
212
+ if (err?.name === 'AbortError') {
213
+ if (signal?.aborted) throw abortError();
214
+ throw new MineruError('MinerU 请求超时(' + timeoutMs + 'ms):请稍后重试或增大 timeoutMs。', 'MINERU_TIMEOUT');
215
+ }
216
+ throw new MineruError('无法连接 MinerU API:' + (err?.message ?? String(err)), 'MINERU_NETWORK');
217
+ } finally {
218
+ clearTimeout(timer);
219
+ signal?.removeEventListener('abort', onAbort);
220
+ }
221
+ const text = await res.text();
222
+ let payload = null;
223
+ if (text) {
224
+ try { payload = JSON.parse(text); } catch { /* non-JSON body */ }
225
+ }
226
+ if (res.status === 429) {
227
+ const retryAfter = Number(res.headers.get('retry-after')) || 30;
228
+ const err = new MineruError('MinerU 接口限频(HTTP 429):官方限制 50 个文件/分钟提交、1000 次/分钟查询,请降低并发或稍后重试。', 'MINERU_RATE_LIMITED', { httpStatus: 429 });
229
+ err.retryAfterSec = Math.min(120, retryAfter);
230
+ throw err;
231
+ }
232
+ if (res.status === 401 || res.status === 403) {
233
+ throw new MineruError('MinerU Token 校验失败(HTTP ' + res.status + '):请在设置中更新 Token。', 'MINERU_TOKEN_INVALID', { httpStatus: res.status });
234
+ }
235
+ if (!res.ok) {
236
+ throw new MineruError('MinerU 请求失败(HTTP ' + res.status + '):' + String(payload?.msg || text).slice(0, 400), 'MINERU_HTTP', { httpStatus: res.status });
237
+ }
238
+ return { status: res.status, payload, headers: res.headers };
239
+ }
240
+
241
+ async function requestJsonWithRetry(args) {
242
+ try {
243
+ return await requestJson(args);
244
+ } catch (err) {
245
+ if (err instanceof MineruError && err.code === 'MINERU_RATE_LIMITED' && (args.retries ?? 0) < 2) {
246
+ await sleep(err.retryAfterSec * 1000, args.signal);
247
+ return requestJsonWithRetry({ ...args, retries: (args.retries ?? 0) + 1 });
248
+ }
249
+ throw err;
250
+ }
251
+ }
252
+
253
+ /** Upload one local file to a signed OSS URL (PUT, no auth). */
254
+ async function uploadToSignedUrl(filePath, uploadUrl, { signal, timeoutMs, userAgent }) {
255
+ const size = (await stat(filePath)).size;
256
+ const controller = new AbortController();
257
+ const timer = setTimeout(() => controller.abort(), Math.max(timeoutMs, 60000));
258
+ const onAbort = () => controller.abort();
259
+ signal?.addEventListener('abort', onAbort, { once: true });
260
+ try {
261
+ const body = Readable.toWeb(createReadStream(filePath));
262
+ const res = await fetch(uploadUrl, {
263
+ method: 'PUT',
264
+ headers: { 'User-Agent': userAgent ?? 'dsh-mineru', 'Content-Length': String(size) },
265
+ body,
266
+ // undici requires the duplex option for stream bodies
267
+ duplex: 'half',
268
+ signal: controller.signal,
269
+ });
270
+ if (res.status !== 200 && res.status !== 201 && res.status !== 204) {
271
+ const text = await res.text().catch(() => '');
272
+ throw new MineruError('MinerU OSS 文件上传失败(HTTP ' + res.status + '):' + text.slice(0, 300), 'MINERU_UPLOAD_FAILED');
273
+ }
274
+ } catch (err) {
275
+ if (err instanceof MineruError) throw err;
276
+ if (err?.name === 'AbortError') {
277
+ if (signal?.aborted) throw abortError();
278
+ throw new MineruError('MinerU 文件上传超时', 'MINERU_TIMEOUT');
279
+ }
280
+ throw new MineruError('MinerU 文件上传失败:' + (err?.message ?? String(err)), 'MINERU_UPLOAD_FAILED');
281
+ } finally {
282
+ clearTimeout(timer);
283
+ signal?.removeEventListener('abort', onAbort);
284
+ }
285
+ }
286
+
287
+ /** Download a URL to a local file (result zips / markdown). */
288
+ async function downloadTo(url, destPath, { signal, timeoutMs, userAgent, maxBytes }) {
289
+ const controller = new AbortController();
290
+ const timer = setTimeout(() => controller.abort(), Math.max(timeoutMs, 120000));
291
+ const onAbort = () => controller.abort();
292
+ signal?.addEventListener('abort', onAbort, { once: true });
293
+ let size = 0;
294
+ try {
295
+ const res = await fetch(url, {
296
+ headers: { 'User-Agent': userAgent ?? 'dsh-mineru' },
297
+ signal: controller.signal,
298
+ redirect: 'follow',
299
+ });
300
+ if (!res.ok || !res.body) {
301
+ throw new MineruError('MinerU 结果下载失败(HTTP ' + res.status + ')', 'MINERU_DOWNLOAD_FAILED');
302
+ }
303
+ const reader = res.body.getReader();
304
+ const stream = new Readable({
305
+ async read() {
306
+ const { done, value } = await reader.read();
307
+ if (done) { this.push(null); return; }
308
+ size += value.byteLength;
309
+ if (maxBytes && size > maxBytes) {
310
+ this.destroy(new MineruError('MinerU 结果超过下载上限 ' + maxBytes + ' 字节', 'MINERU_TOO_LARGE'));
311
+ return;
312
+ }
313
+ this.push(Buffer.from(value));
314
+ },
315
+ });
316
+ await pipeline(stream, createWriteStream(destPath));
317
+ return size;
318
+ } catch (err) {
319
+ await rm(destPath, { force: true }).catch(() => {});
320
+ if (err instanceof MineruError) throw err;
321
+ if (err?.name === 'AbortError') {
322
+ if (signal?.aborted) throw abortError();
323
+ throw new MineruError('MinerU 结果下载超时', 'MINERU_TIMEOUT');
324
+ }
325
+ throw new MineruError('MinerU 结果下载失败:' + (err?.message ?? String(err)), 'MINERU_DOWNLOAD_FAILED');
326
+ } finally {
327
+ clearTimeout(timer);
328
+ signal?.removeEventListener('abort', onAbort);
329
+ }
330
+ }/**
331
+ * The Mineru client. Create one per API base + token; rate limiters and the
332
+ * daily counter are shared so concurrent tool calls stay under the official
333
+ * frequency caps.
334
+ */
335
+ export class MineruClient {
336
+ /**
337
+ * @param {object} opts
338
+ * @param {string} opts.baseUrl
339
+ * @param {string} [opts.token] precision-API token; absent selects the agent API
340
+ * @param {object} [opts.limiters] { submit: RateLimiter, poll: RateLimiter, daily: DailyCounter }
341
+ * @param {string} [opts.userAgent]
342
+ */
343
+ constructor(opts) {
344
+ this.baseUrl = normalizeBaseUrl(opts.baseUrl);
345
+ this.token = opts.token ?? '';
346
+ this.submit = opts.limiters?.submit ?? new RateLimiter(40);
347
+ this.poll = opts.limiters?.poll ?? new RateLimiter(900);
348
+ this.daily = opts.limiters?.daily ?? new DailyCounter(5000);
349
+ this.userAgent = opts.userAgent ?? 'dsh-mineru';
350
+ this.tmpFiles = [];
351
+ }
352
+
353
+ authHeaders() {
354
+ return this.token ? { Authorization: 'Bearer ' + this.token } : {};
355
+ }
356
+
357
+ precisionEnabled() { return Boolean(this.token); }
358
+
359
+ /** Register a temp file for cleanup on dispose. */
360
+ trackTmp(path) { this.tmpFiles.push(path); }
361
+
362
+ /**
363
+ * Resolve which API serves one call.
364
+ * @param {string} [modeArg] auto | precision | agent (per-call override)
365
+ * @param {string} [cfgMode] auto | precision | agent (config default)
366
+ * @returns {{api:'precision'|'agent', effectiveMode:string}}
367
+ */
368
+ resolveApi(modeArg, cfgMode) {
369
+ const requested = modeArg ?? cfgMode ?? 'auto';
370
+ if (requested === 'precision') {
371
+ if (!this.precisionEnabled()) {
372
+ throw new MineruError(
373
+ 'mode=precision 需要 MinerU Token:请在 Web 设置中填写 Token,或在 $DSH_HOME/.credentials.yaml 中配置 MINERU_API_TOKEN。',
374
+ 'MINERU_TOKEN_REQUIRED',
375
+ );
376
+ }
377
+ return { api: 'precision', effectiveMode: 'precision' };
378
+ }
379
+ if (requested === 'agent') return { api: 'agent', effectiveMode: 'agent' };
380
+ return this.precisionEnabled()
381
+ ? { api: 'precision', effectiveMode: 'precision' }
382
+ : { api: 'agent', effectiveMode: 'agent' };
383
+ }
384
+
385
+ /**
386
+ * Validate a local file before upload.
387
+ * @param {string} filePath
388
+ * @param {'precision'|'agent'} api
389
+ * @param {number} maxFileBytes config cap (0 = API limit)
390
+ */
391
+ async checkLocalFile(filePath, api, maxFileBytes) {
392
+ let st;
393
+ try { st = await stat(filePath); } catch {
394
+ throw new MineruError('找不到文件:' + filePath, 'MINERU_FILE_NOT_FOUND');
395
+ }
396
+ if (!st.isFile()) throw new MineruError('不是常规文件:' + filePath, 'MINERU_FILE_NOT_FOUND');
397
+ const ext = extOf(filePath);
398
+ if (!SUPPORTED_EXTENSIONS.includes(ext)) {
399
+ throw new MineruError(
400
+ '不支持的文件类型 ' + (ext || '(无后缀)') + ':支持 pdf/doc/docx/ppt/pptx/xls/xlsx 与 png/jpg/jpeg/jp2/webp/gif/bmp' + (api === 'precision' ? '/html' : '') + '。',
401
+ 'MINERU_UNSUPPORTED_TYPE',
402
+ );
403
+ }
404
+ if (api === 'agent' && AGENT_UNSUPPORTED_EXTENSIONS.includes(ext)) {
405
+ throw new MineruError('Agent 轻量解析 API 不支持 ' + ext + ' 文件:请改用精准解析 API(填写 Token)。', 'MINERU_UNSUPPORTED_TYPE');
406
+ }
407
+ const limit = maxFileBytes > 0 ? maxFileBytes : (api === 'precision' ? PRECISION_FILE_LIMIT : AGENT_FILE_LIMIT);
408
+ if (st.size > limit) {
409
+ throw new MineruError(
410
+ '文件过大:' + st.size + ' 字节,超出 ' + (api === 'precision' ? '精准解析 API 200MB' : 'Agent 轻量解析 API 10MB') + ' 限制。',
411
+ 'MINERU_FILE_TOO_LARGE',
412
+ );
413
+ }
414
+ if (st.size === 0) throw new MineruError('文件为空:' + filePath, 'MINERU_EMPTY_FILE');
415
+ return { size: st.size, ext };
416
+ }
417
+
418
+ /** Common precision request body for URL submissions. */
419
+ precisionUrlBody(opts, url) {
420
+ const body = {
421
+ url,
422
+ model_version: opts.modelVersion,
423
+ is_ocr: opts.isOcr,
424
+ enable_formula: opts.enableFormula,
425
+ enable_table: opts.enableTable,
426
+ language: opts.language,
427
+ };
428
+ if (opts.dataId) body.data_id = opts.dataId;
429
+ if (opts.pageRanges) body.page_ranges = opts.pageRanges;
430
+ if (opts.extraFormats?.length) body.extra_formats = opts.extraFormats;
431
+ body.no_cache = true;
432
+ return body;
433
+ }
434
+
435
+ agentUrlBody(opts, url) {
436
+ const body = {
437
+ url,
438
+ language: opts.language,
439
+ enable_table: opts.enableTable,
440
+ is_ocr: opts.isOcr,
441
+ enable_formula: opts.enableFormula,
442
+ };
443
+ if (opts.pageRange) body.page_range = opts.pageRange;
444
+ return body;
445
+ }
446
+
447
+ agentFileBody(opts, fileName) {
448
+ const body = {
449
+ file_name: fileName,
450
+ language: opts.language,
451
+ enable_table: opts.enableTable,
452
+ is_ocr: opts.isOcr,
453
+ enable_formula: opts.enableFormula,
454
+ };
455
+ if (opts.pageRange) body.page_range = opts.pageRange;
456
+ return body;
457
+ }
458
+
459
+ /**
460
+ * @param {object} payload
461
+ * @param {'precision'|'agent'} api
462
+ */
463
+ parsePayloadError(payload, api) {
464
+ if (payload && typeof payload === 'object') {
465
+ const code = payload.code;
466
+ const data = payload.data;
467
+ if (code !== undefined && code !== 0 && code !== '0') {
468
+ const mapped = messageForCode(code) ?? (data?.err_code !== undefined ? messageForCode(data.err_code) : undefined);
469
+ return new MineruError(mapped ?? ('MinerU 接口错误:' + (payload.msg || String(code))), 'MINERU_API', { rawCode: String(code), api });
470
+ }
471
+ if (data && typeof data === 'object' && data.err_code !== undefined) {
472
+ const mapped = messageForCode(data.err_code);
473
+ if (mapped) return new MineruError(mapped, 'MINERU_API', { rawCode: String(data.err_code), api });
474
+ }
475
+ }
476
+ return new MineruError('MinerU 返回异常:' + String(payload ?? '').slice(0, 400), 'MINERU_API', { api });
477
+ }
478
+
479
+ /** Submit one URL and wait until done/failed. */
480
+ async submitAndWaitUrl({ url, fileName, opts, api, signal, onState }) {
481
+ await this.submit.acquire(signal);
482
+ this.daily.add(1);
483
+ let taskId;
484
+ if (api === 'precision') {
485
+ const { payload } = await requestJsonWithRetry({
486
+ url: this.baseUrl + '/api/v4/extract/task',
487
+ method: 'POST',
488
+ headers: mergeHeaders({ 'Content-Type': 'application/json' }, this.authHeaders()),
489
+ body: JSON.stringify(this.precisionUrlBody(opts, url)),
490
+ signal, timeoutMs: 60000, userAgent: this.userAgent,
491
+ });
492
+ if (!payload || payload.code !== 0 || !payload.data?.task_id) {
493
+ throw this.parsePayloadError(payload, api);
494
+ }
495
+ taskId = payload.data.task_id;
496
+ onState?.({ phase: 'submitted', taskId });
497
+ } else {
498
+ const body = this.agentUrlBody(opts, url);
499
+ if (fileName) body.file_name = fileName;
500
+ const { payload } = await requestJsonWithRetry({
501
+ url: this.baseUrl + '/api/v1/agent/parse/url',
502
+ method: 'POST',
503
+ headers: { 'Content-Type': 'application/json' },
504
+ body: JSON.stringify(body),
505
+ signal, timeoutMs: 60000, userAgent: this.userAgent,
506
+ });
507
+ if (!payload || payload.code !== 0 || !payload.data?.task_id) {
508
+ throw this.parsePayloadError(payload, api);
509
+ }
510
+ taskId = payload.data.task_id;
511
+ onState?.({ phase: 'submitted', taskId });
512
+ }
513
+ return this.waitTask({ taskId, api, opts, signal, onState });
514
+ } /** Upload one local file (signature upload) and wait until done/failed. */
515
+ async submitAndWaitFile({ filePath, fileName, opts, api, signal, onState }) {
516
+ await this.submit.acquire(signal);
517
+ this.daily.add(1);
518
+ if (api === 'precision') {
519
+ const body = {
520
+ files: [{
521
+ name: fileName,
522
+ ...(opts.dataId ? { data_id: opts.dataId } : {}),
523
+ ...(opts.isOcr !== undefined ? { is_ocr: opts.isOcr } : {}),
524
+ ...(opts.pageRanges ? { page_ranges: opts.pageRanges } : {}),
525
+ }],
526
+ model_version: opts.modelVersion,
527
+ enable_formula: opts.enableFormula,
528
+ enable_table: opts.enableTable,
529
+ language: opts.language,
530
+ };
531
+ if (opts.extraFormats?.length) body.extra_formats = opts.extraFormats;
532
+ const { payload } = await requestJsonWithRetry({
533
+ url: this.baseUrl + '/api/v4/file-urls/batch',
534
+ method: 'POST',
535
+ headers: mergeHeaders({ 'Content-Type': 'application/json' }, this.authHeaders()),
536
+ body: JSON.stringify(body),
537
+ signal, timeoutMs: 60000, userAgent: this.userAgent,
538
+ });
539
+ if (!payload || payload.code !== 0 || !payload.data?.batch_id || !payload.data?.file_urls?.[0]) {
540
+ throw this.parsePayloadError(payload, api);
541
+ }
542
+ const batchId = payload.data.batch_id;
543
+ const uploadUrl = payload.data.file_urls[0];
544
+ onState?.({ phase: 'uploading', batchId });
545
+ await uploadToSignedUrl(filePath, uploadUrl, { signal, timeoutMs: opts.timeoutMs, userAgent: this.userAgent });
546
+ onState?.({ phase: 'uploaded', batchId });
547
+ const items = await this.waitBatch({ batchId, api, opts, signal, onState });
548
+ const item = items[0];
549
+ if (!item) throw new MineruError('MinerU 批量结果为空', 'MINERU_API', { api });
550
+ return {
551
+ api, taskId: item.taskId, batchId, state: item.state,
552
+ fullZipUrl: item.fullZipUrl, errMsg: item.errMsg, progress: item.progress,
553
+ };
554
+ }
555
+ const body = this.agentFileBody(opts, fileName);
556
+ const { payload } = await requestJsonWithRetry({
557
+ url: this.baseUrl + '/api/v1/agent/parse/file',
558
+ method: 'POST',
559
+ headers: { 'Content-Type': 'application/json' },
560
+ body: JSON.stringify(body),
561
+ signal, timeoutMs: 60000, userAgent: this.userAgent,
562
+ });
563
+ if (!payload || payload.code !== 0 || !payload.data?.task_id || !payload.data?.file_url) {
564
+ throw this.parsePayloadError(payload, api);
565
+ }
566
+ const taskId = payload.data.task_id;
567
+ const uploadUrl = payload.data.file_url;
568
+ onState?.({ phase: 'uploading', taskId });
569
+ await uploadToSignedUrl(filePath, uploadUrl, { signal, timeoutMs: opts.timeoutMs, userAgent: this.userAgent });
570
+ onState?.({ phase: 'uploaded', taskId });
571
+ return this.waitTask({ taskId, api, opts, signal, onState });
572
+ }
573
+
574
+ /** Query one task (agent or precision single). */
575
+ async queryTask({ taskId, api, signal }) {
576
+ await this.poll.acquire(signal);
577
+ if (api === 'precision') {
578
+ const { payload } = await requestJsonWithRetry({
579
+ url: this.baseUrl + '/api/v4/extract/task/' + encodeURIComponent(taskId),
580
+ headers: this.authHeaders(),
581
+ signal, timeoutMs: 60000, userAgent: this.userAgent,
582
+ });
583
+ if (!payload || payload.code !== 0) throw this.parsePayloadError(payload, api);
584
+ const d = payload.data ?? {};
585
+ return {
586
+ taskId: d.task_id ?? taskId,
587
+ state: d.state ?? 'unknown',
588
+ fullZipUrl: d.full_zip_url,
589
+ errMsg: d.err_msg,
590
+ progress: d.extract_progress,
591
+ };
592
+ }
593
+ const { payload } = await requestJsonWithRetry({
594
+ url: this.baseUrl + '/api/v1/agent/parse/' + encodeURIComponent(taskId),
595
+ signal, timeoutMs: 60000, userAgent: this.userAgent,
596
+ });
597
+ if (!payload || payload.code !== 0) throw this.parsePayloadError(payload, api);
598
+ const d = payload.data ?? {};
599
+ return {
600
+ taskId: d.task_id ?? taskId,
601
+ state: d.state ?? 'unknown',
602
+ markdownUrl: d.markdown_url,
603
+ errMsg: d.err_msg,
604
+ errCode: d.err_code,
605
+ };
606
+ }
607
+
608
+ /** Wait for one task: poll until done/failed/timeout. */
609
+ async waitTask({ taskId, api, opts, signal, onState }) {
610
+ const started = Date.now();
611
+ const deadline = started + (opts.timeoutMs ?? 600000);
612
+ for (;;) {
613
+ if (Date.now() > deadline) {
614
+ throw new MineruError(
615
+ 'MinerU 任务等待超时(' + (opts.timeoutMs ?? 600000) + 'ms)。任务仍在服务端处理,可稍后用 mineru_task 以 taskId=' + taskId + '(api=' + api + ')继续收集结果。',
616
+ 'MINERU_TIMEOUT', { taskId, api },
617
+ );
618
+ }
619
+ const last = await this.queryTask({ taskId, api, signal });
620
+ if (last.state === 'done') {
621
+ onState?.({ phase: 'done', taskId, state: last });
622
+ return { api, taskId, state: 'done', fullZipUrl: last.fullZipUrl, markdownUrl: last.markdownUrl, errMsg: last.errMsg, progress: last.progress };
623
+ }
624
+ if (last.state === 'failed') {
625
+ throw new MineruError(
626
+ last.errMsg ?? 'MinerU 解析失败',
627
+ 'MINERU_PARSE_FAILED', { taskId, api },
628
+ );
629
+ }
630
+ onState?.({ phase: 'waiting', taskId, state: last });
631
+ await sleep(opts.pollIntervalMs + Math.floor(Math.random() * (opts.pollJitterMs + 1)), signal);
632
+ }
633
+ } /** Submit a URL batch (precision only) and wait for every item. */
634
+ async submitAndWaitBatchUrls({ items, opts, signal, onState }) {
635
+ if (items.length > 200) throw new MineruError('精准解析 API 批量 URL 解析单次最多 200 个文件。', 'MINERU_BATCH_TOO_LARGE');
636
+ await this.submit.acquire(signal);
637
+ this.daily.add(items.length);
638
+ const body = {
639
+ files: items.map((it, i) => {
640
+ const dataId = dataIdFor(it, i, opts);
641
+ return {
642
+ url: it.url,
643
+ ...(dataId ? { data_id: dataId } : {}),
644
+ ...(opts.isOcr !== undefined ? { is_ocr: opts.isOcr } : {}),
645
+ ...(opts.pageRanges ? { page_ranges: opts.pageRanges } : {}),
646
+ };
647
+ }),
648
+ model_version: opts.modelVersion,
649
+ enable_formula: opts.enableFormula,
650
+ enable_table: opts.enableTable,
651
+ language: opts.language,
652
+ };
653
+ if (opts.extraFormats?.length) body.extra_formats = opts.extraFormats;
654
+ const { payload } = await requestJsonWithRetry({
655
+ url: this.baseUrl + '/api/v4/extract/task/batch',
656
+ method: 'POST',
657
+ headers: mergeHeaders({ 'Content-Type': 'application/json' }, this.authHeaders()),
658
+ body: JSON.stringify(body),
659
+ signal, timeoutMs: 60000, userAgent: this.userAgent,
660
+ });
661
+ if (!payload || payload.code !== 0 || !payload.data?.batch_id) throw this.parsePayloadError(payload, 'precision');
662
+ const batchId = payload.data.batch_id;
663
+ onState?.({ phase: 'submitted', batchId });
664
+ const results = await this.waitBatch({ batchId, api: 'precision', opts, signal, onState });
665
+ return { api: 'precision', batchId, results };
666
+ }
667
+
668
+ /** Submit a local-file batch (precision only) and wait for every item. */
669
+ async submitAndWaitBatchFiles({ items, opts, signal, onState }) {
670
+ if (items.length > 50) throw new MineruError('精准解析 API 本地批量上传单次最多申请 50 个上传链接。', 'MINERU_BATCH_TOO_LARGE');
671
+ await this.submit.acquire(signal);
672
+ this.daily.add(items.length);
673
+ const body = {
674
+ files: items.map((it, i) => {
675
+ const dataId = dataIdFor(it, i, opts);
676
+ return {
677
+ name: it.fileName,
678
+ ...(dataId ? { data_id: dataId } : {}),
679
+ ...(opts.isOcr !== undefined ? { is_ocr: opts.isOcr } : {}),
680
+ ...(opts.pageRanges ? { page_ranges: opts.pageRanges } : {}),
681
+ };
682
+ }),
683
+ model_version: opts.modelVersion,
684
+ enable_formula: opts.enableFormula,
685
+ enable_table: opts.enableTable,
686
+ language: opts.language,
687
+ };
688
+ if (opts.extraFormats?.length) body.extra_formats = opts.extraFormats;
689
+ const { payload } = await requestJsonWithRetry({
690
+ url: this.baseUrl + '/api/v4/file-urls/batch',
691
+ method: 'POST',
692
+ headers: mergeHeaders({ 'Content-Type': 'application/json' }, this.authHeaders()),
693
+ body: JSON.stringify(body),
694
+ signal, timeoutMs: 60000, userAgent: this.userAgent,
695
+ });
696
+ if (!payload || payload.code !== 0 || !payload.data?.batch_id || !Array.isArray(payload.data.file_urls)) {
697
+ throw this.parsePayloadError(payload, 'precision');
698
+ }
699
+ const batchId = payload.data.batch_id;
700
+ const uploadUrls = payload.data.file_urls;
701
+ onState?.({ phase: 'uploading', batchId, total: items.length });
702
+ for (let i = 0; i < items.length; i++) {
703
+ await uploadToSignedUrl(items[i].filePath, uploadUrls[i], { signal, timeoutMs: opts.timeoutMs, userAgent: this.userAgent });
704
+ onState?.({ phase: 'uploaded', batchId, done: i + 1, total: items.length });
705
+ }
706
+ const results = await this.waitBatch({ batchId, api: 'precision', opts, signal, onState });
707
+ return { api: 'precision', batchId, results };
708
+ }
709
+
710
+ /** Poll a precision batch until every item is done/failed. */
711
+ async waitBatch({ batchId, api, opts, signal, onState }) {
712
+ const deadline = Date.now() + (opts.timeoutMs ?? 600000);
713
+ let last = [];
714
+ for (;;) {
715
+ if (Date.now() > deadline) {
716
+ throw new MineruError(
717
+ 'MinerU 批量任务等待超时(' + (opts.timeoutMs ?? 600000) + 'ms)。可稍后用 mineru_task 查询 batchId=' + batchId + '。',
718
+ 'MINERU_TIMEOUT', { taskId: batchId, api },
719
+ );
720
+ }
721
+ await this.poll.acquire(signal);
722
+ const { payload } = await requestJsonWithRetry({
723
+ url: this.baseUrl + '/api/v4/extract-results/batch/' + encodeURIComponent(batchId),
724
+ headers: this.authHeaders(),
725
+ signal, timeoutMs: 60000, userAgent: this.userAgent,
726
+ });
727
+ if (!payload || payload.code !== 0) throw this.parsePayloadError(payload, 'precision');
728
+ last = Array.isArray(payload.data?.extract_result) ? payload.data.extract_result : [];
729
+ const active = last.filter((r) => !['done', 'failed'].includes(r.state));
730
+ if (last.length > 0 && active.length === 0) {
731
+ onState?.({ phase: 'done', batchId, state: last });
732
+ return last.map((r) => ({
733
+ name: r.file_name,
734
+ state: r.state,
735
+ fullZipUrl: r.full_zip_url,
736
+ errMsg: r.err_msg,
737
+ progress: r.extract_progress,
738
+ dataId: r.data_id,
739
+ }));
740
+ }
741
+ onState?.({ phase: 'waiting', batchId, state: last });
742
+ await sleep(opts.pollIntervalMs + Math.floor(Math.random() * (opts.pollJitterMs + 1)), signal);
743
+ }
744
+ }
745
+
746
+ /** Download and extract one precision result zip. */
747
+ async collectPrecisionZip({ zipUrl, destDir, opts, signal }) {
748
+ await mkdir(destDir, { recursive: true });
749
+ const zipPath = join(destDir, 'result.zip');
750
+ await downloadTo(zipUrl, zipPath, {
751
+ signal, timeoutMs: Math.max(opts.timeoutMs ?? 600000, 120000),
752
+ userAgent: this.userAgent, maxBytes: 1 << 30,
753
+ });
754
+ this.trackTmp(zipPath);
755
+ const { files } = await extractZip(zipPath, destDir, { signal, maxTotalBytes: 1 << 30 });
756
+ const markdownEntry = files.find((f) => f.name === 'full.md') ?? files.find((f) => f.name.endsWith('/full.md'));
757
+ let markdownText = '';
758
+ let markdownBytes = 0;
759
+ if (markdownEntry) {
760
+ const md = await readZipEntryText(zipPath, markdownEntry.name, { signal, maxBytes: 64 << 20 });
761
+ markdownText = md?.text ?? '';
762
+ markdownBytes = md?.bytes ?? 0;
763
+ }
764
+ const contentList = files.find((f) => /_content_list\.json$/.test(f.name) || f.name === 'content_list.json');
765
+ const layoutJson = files.find((f) => /layout\.json$/.test(f.name));
766
+ return { zipPath, files, markdownEntry, markdownText, markdownBytes, contentListEntry: contentList, layoutEntry: layoutJson };
767
+ }
768
+
769
+ /** Download one agent-API markdown result. */
770
+ async collectAgentMarkdown({ markdownUrl, destDir, opts, signal }) {
771
+ await mkdir(destDir, { recursive: true });
772
+ const destPath = join(destDir, 'full.md');
773
+ const bytes = await downloadTo(markdownUrl, destPath, {
774
+ signal, timeoutMs: Math.max(opts.timeoutMs ?? 600000, 120000),
775
+ userAgent: this.userAgent, maxBytes: 64 << 20,
776
+ });
777
+ const text = await readFile(destPath, 'utf8');
778
+ return { markdownPath: destPath, markdownText: text, markdownBytes: bytes };
779
+ }
780
+
781
+ /** Collect a finished single task's result into destDir (task or url based). */
782
+ async collectSingle({ outcome, destDir, opts, signal }) {
783
+ if (outcome.state !== 'done') {
784
+ throw new MineruError('任务未完成(state=' + outcome.state + '),无法收集结果。', 'MINERU_NOT_DONE', { taskId: outcome.taskId, api: outcome.api });
785
+ }
786
+ if (outcome.api === 'precision') {
787
+ if (!outcome.fullZipUrl) throw new MineruError('精准解析任务完成但缺少 full_zip_url。', 'MINERU_API', { taskId: outcome.taskId, api: outcome.api });
788
+ return this.collectPrecisionZip({ zipUrl: outcome.fullZipUrl, destDir, opts, signal });
789
+ }
790
+ if (!outcome.markdownUrl) throw new MineruError('Agent 解析任务完成但缺少 markdown_url。', 'MINERU_API', { taskId: outcome.taskId, api: outcome.api });
791
+ return this.collectAgentMarkdown({ markdownUrl: outcome.markdownUrl, destDir, opts, signal });
792
+ }
793
+ }
794
+
795
+ /** Resolve per-call options from config + tool args. */
796
+ export function resolveOptions(cfg, args) {
797
+ const modelVersion = args.modelVersion ?? cfg.modelVersion;
798
+ if (!MODEL_VERSION_VALUES.includes(modelVersion)) {
799
+ throw new MineruError('model_version 必须是 pipeline / vlm / MinerU-HTML 之一。', 'MINERU_BAD_ARGS');
800
+ }
801
+ return {
802
+ language: args.language ?? cfg.language,
803
+ enableTable: args.enableTable ?? cfg.enableTable,
804
+ enableFormula: args.enableFormula ?? cfg.enableFormula,
805
+ isOcr: args.isOcr ?? cfg.isOcr,
806
+ modelVersion,
807
+ pageRanges: args.pageRanges ?? undefined,
808
+ pageRange: args.pageRange ?? undefined,
809
+ extraFormats: args.extraFormats ?? cfg.extraFormats ?? [],
810
+ dataId: sanitizeDataId(args.dataId),
811
+ dataIdPrefix: sanitizeDataId(args.dataIdPrefix),
812
+ timeoutMs: args.timeoutMs ?? cfg.timeoutMs,
813
+ pollIntervalMs: cfg.pollIntervalMs,
814
+ pollJitterMs: cfg.pollJitterMs,
815
+ };
816
+ }
817
+
818
+ /** Force the MinerU-HTML model for HTML sources (precision). */
819
+ export function effectiveModelFor(ext, modelVersion) {
820
+ if (ext === '.html' || ext === '.htm') {
821
+ if (modelVersion !== 'MinerU-HTML') {
822
+ return { modelVersion: 'MinerU-HTML', forced: true };
823
+ }
824
+ }
825
+ return { modelVersion, forced: false };
826
+ }