dsh-mineru 0.1.13 → 0.1.14

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/lib/tools.js CHANGED
@@ -4,13 +4,23 @@
4
4
  * globally under exposeMode: always).
5
5
  * @module dsh-mineru/tools
6
6
  */
7
- import { basename, extname, join, resolve as pathResolve } from 'node:path';
8
- import { rm } from 'node:fs/promises';
7
+ import { createHash } from 'node:crypto';
8
+ import { createReadStream } from 'node:fs';
9
+ import { basename, dirname, extname, join, resolve as pathResolve } from 'node:path';
10
+ import { access, copyFile, mkdir, readFile, rm } from 'node:fs/promises';
9
11
  import { defineTool } from '@deepseek-ai/dsh-tools';
10
- import { MineruError, resolveOptions, effectiveModelFor } from './mineru-client.js';
11
12
  import { AGENT_UNSUPPORTED_EXTENSIONS, EXTRA_FORMAT_VALUES, LANGUAGE_VALUES, SUPPORTED_EXTENSIONS } from './config.js';
13
+ import { MineruError, PRECISION_PAGE_LIMIT, effectiveModelFor, resolveOptions, sanitizeDataId } from './mineru-client.js';
14
+ import { mergeChunksMarkdown, remapChunkPages } from './chunk-merge.js';
15
+ import { planPageChunks, parsePageRanges } from './page-ranges.js';
16
+ import { countPdfPages } from './pdf-pages.js';
17
+ import { readContentListFile, synthesizeDocument } from './anchors.js';
12
18
  import { sanitizeFileName } from './artifacts.js';
13
19
  import { SKILL_NAME } from './skill.js';
20
+ import {
21
+ RUN_STATE_SCHEMA, buildRunCacheKey, chunkResumeMap, decideRunResume,
22
+ readChunkMarker, writeChunkMarker,
23
+ } from './run-state.js';
14
24
 
15
25
  export const ACTIVATE_TOOL_NAME = 'mineru_activate';
16
26
  export const TOOL_NAMES = Object.freeze(['mineru_parse', 'mineru_batch_parse', 'mineru_task']);
@@ -57,9 +67,10 @@ function parseOptionParams() {
57
67
  enableTable: { type: 'boolean', description: '是否开启表格识别, 默认 true.' },
58
68
  enableFormula: { type: 'boolean', description: '是否开启公式识别, 默认 true.' },
59
69
  isOcr: { type: 'boolean', description: '是否强制 OCR, 默认 false.' },
60
- pageRanges: { type: 'string', description: '精准解析页码范围, 逗号分隔: "2,4-6", 支持倒数页码 "2--2".' },
70
+ pageRanges: { type: 'string', description: '精准解析页码范围, 逗号分隔: "2,4-6", 支持倒数页码 "2--2". 不传表示整份文档; 本次要解析的页数超过单次 200 页上限时(仅工作区 PDF, 本地能读出页数), 自动按页分片提交并合并结果.' },
61
71
  pageRange: { type: 'string', description: 'Agent 轻量解析页码范围, 仅支持 from-to 或单页: "1-10".' },
62
72
  extraFormats: { type: 'array', items: { type: 'string', enum: EXTRA_FORMAT_VALUES }, description: '精准解析额外导出格式: docx / html / latex.' },
73
+ anchor: { type: 'boolean', description: '额外产出一份带页级块锚点的 document.md (每块前一行 <!-- pN bK -->, N 为原文页码, K 为页内块序, 默认 false). 仅精准解析 API 的结果含 content_list.json, 故该产物只在精准解析下生成; 开启后 full.md 等既有产物不变.' },
63
74
  dataId: { type: 'string', description: '解析对象对应的业务数据 ID (可选, <=128 字符).' },
64
75
  timeoutMs: { type: 'number', description: '整个操作(含轮询等待)的超时毫秒数, 默认取插件配置.' },
65
76
  };
@@ -142,9 +153,528 @@ export function buildActivateTool(state) {
142
153
  execute: makeActivateExecute(state),
143
154
  });
144
155
  }/**
156
+ * Decide whether this call can be split into several `page_ranges` requests.
157
+ *
158
+ * Splitting needs the page count **locally**: of all supported formats only a
159
+ * PDF can be counted without calling the API (see `countPdfPages`), and only the
160
+ * precision API takes `page_ranges` at all. Everything else — the tokenless
161
+ * Agent API, URL sources (the bytes are not on disk), non-PDF formats — keeps
162
+ * the previous single-request behaviour, and the failure path then explains why
163
+ * no split happened instead of quietly retrying.
164
+ *
165
+ * @param {{api: string, ext: string, filePath: string|null, urlSource: boolean, pageRanges: string|undefined}} input
166
+ * @returns {Promise<{reason: string, chunks: object[], totalPages: number|null, method: string|null, pagesRequested: number|null}>}
167
+ */
168
+ async function planChunking({ api, ext, filePath, urlSource, pageRanges }) {
169
+ const none = (reason) => ({ reason, chunks: [], totalPages: null, method: null, pagesRequested: null });
170
+ if (api !== 'precision') return none('agent-api');
171
+ if (urlSource) return none('url-source');
172
+ if (ext !== '.pdf') return none('pages-unknown');
173
+ let bytes;
174
+ try {
175
+ bytes = await readFile(filePath);
176
+ } catch {
177
+ return none('unreadable');
178
+ }
179
+ const counted = countPdfPages(bytes);
180
+ if (!Number.isInteger(counted.pages) || counted.pages < 1) return none('pages-undetermined');
181
+ let spec;
182
+ if (pageRanges === undefined) {
183
+ spec = { pages: Array.from({ length: counted.pages }, (_, index) => index + 1) };
184
+ } else {
185
+ try {
186
+ spec = parsePageRanges(pageRanges, { totalPages: counted.pages });
187
+ } catch {
188
+ // The server stays the authority on `page_ranges` syntax: a spec it
189
+ // accepts but the local planner cannot split must not start failing here.
190
+ // Pass it through untouched and report why no split happened.
191
+ return { ...none('unparsable-ranges'), totalPages: counted.pages, method: counted.method };
192
+ }
193
+ }
194
+ const chunks = planPageChunks(spec.pages, PRECISION_PAGE_LIMIT);
195
+ return {
196
+ reason: chunks.length > 1 ? 'over-limit' : 'within-limit',
197
+ chunks,
198
+ totalPages: counted.pages,
199
+ method: counted.method,
200
+ pagesRequested: spec.pages.length,
201
+ };
202
+ }
203
+
204
+ /**
205
+ * Why this call was not split automatically, phrased as a clause.
206
+ * @param {{reason: string}} plan @returns {string|null}
207
+ */
208
+ function chunkingUnavailableReason(plan) {
209
+ switch (plan.reason) {
210
+ case 'url-source': return 'URL 源的文件不在本地,读不出页数';
211
+ case 'pages-unknown': return '该格式(docx/pptx 等)的页数只能由云端读出';
212
+ case 'pages-undetermined': return '本地读不出这份 PDF 的页数(加密或结构异常)';
213
+ case 'unreadable': return '本地读取文件失败';
214
+ case 'unparsable-ranges': return 'pageRanges 写法在本地解析不出来(要求升序、不重叠、页码在文档总页数之内)';
215
+ case 'agent-api': return 'Agent 轻量解析 API 按 IP 限流,不做自动分片';
216
+ default: return null;
217
+ }
218
+ }
219
+
220
+ /** True when an API failure is the per-request page cap. */
221
+ function isPageLimitFailure(err) {
222
+ if (!(err instanceof MineruError)) return false;
223
+ if (String(err.rawCode ?? '') === '-60006') return true;
224
+ return /-60006|页数超(出|过)限制|page[^\n]{0,16}(limit|count)/i.test(String(err.message ?? ''));
225
+ }
226
+
227
+ /**
228
+ * Name the chunk this failure belongs to, and keep its actionable code.
229
+ *
230
+ * The upstream failure semantics stay: one failed chunk fails the call and the
231
+ * run directory is removed. Only the message gains the chunk's page range, so a
232
+ * multi-chunk run is debuggable without a local state file.
233
+ */
234
+ function withChunkLabel(label, err) {
235
+ if (err?.name === 'AbortError') return err;
236
+ const message = label + ':' + (err?.message ?? String(err));
237
+ const wrapped = err instanceof MineruError
238
+ ? new MineruError(message, err.code, { httpStatus: err.httpStatus, taskId: err.taskId, api: err.api, rawCode: err.rawCode })
239
+ : new MineruError(message, err?.code ?? 'MINERU_ERROR');
240
+ wrapped.cause = err;
241
+ return wrapped;
242
+ }
243
+
244
+ /** Append the call-specific reason when the page cap was hit without a split. */
245
+ function withChunkingHint(err, plan) {
246
+ if (plan.reason === 'within-limit') return err;
247
+ if (!isPageLimitFailure(err)) return err;
248
+ const reason = chunkingUnavailableReason(plan);
249
+ if (!reason) return err;
250
+ const wrapped = new MineruError(
251
+ err.message + ' 未自动分片的原因:' + reason,
252
+ err.code,
253
+ { httpStatus: err.httpStatus, taskId: err.taskId, api: err.api, rawCode: err.rawCode },
254
+ );
255
+ wrapped.cause = err;
256
+ return wrapped;
257
+ }
258
+
259
+ /** One `data_id` per chunk, so two chunks of one file cannot collide server-side. */
260
+ function chunkDataId(base, chunk) {
261
+ const suffix = 'p' + chunk.spec.replace(/,/g, '_');
262
+ return sanitizeDataId(base ? String(base) + '-' + suffix : suffix);
263
+ }
264
+
265
+ /** The on-disk path of one extracted zip entry, or null. */
266
+ function extractedPath(collected, entry) {
267
+ if (!entry) return null;
268
+ const file = (collected.files ?? []).find((candidate) => candidate.name === entry.name);
269
+ return file?.path ?? null;
270
+ }
271
+
272
+ /**
273
+ * Move one chunk's `images/` entries to the run root.
274
+ *
275
+ * Image names are content hashes, so the union of all chunks is conflict-free
276
+ * and the merged `full.md` keeps resolving its relative image links. Same-named
277
+ * entries from two chunks are the same bytes; `copyFile` overwrites on every
278
+ * platform, while `rename` refuses an existing target on Windows.
279
+ *
280
+ * Entry names come from the zip extractor, which already rejects absolute and
281
+ * `..` names, so every target stays inside the run directory.
282
+ *
283
+ * @returns {Promise<number>} how many entries were moved
284
+ */
285
+ async function hoistChunkImages(collected, runDir) {
286
+ let moved = 0;
287
+ for (const file of collected.files ?? []) {
288
+ if (!file.name.startsWith('images/')) continue;
289
+ const target = join(runDir, file.name);
290
+ await mkdir(dirname(target), { recursive: true });
291
+ await copyFile(file.path, target);
292
+ await rm(file.path, { force: true });
293
+ moved += 1;
294
+ }
295
+ return moved;
296
+ }
297
+
298
+ /** Stream-hash a local file (avoids buffering a large PDF). @param {string} filePath @returns {Promise<string>} */
299
+ function hashFile(filePath) {
300
+ return new Promise((resolve, reject) => {
301
+ const hash = createHash('sha256');
302
+ const stream = createReadStream(filePath);
303
+ stream.on('error', reject);
304
+ stream.on('data', (chunk) => hash.update(chunk));
305
+ stream.on('end', () => resolve(hash.digest('hex')));
306
+ });
307
+ }
308
+
309
+ /** @param {string} p @returns {Promise<boolean>} */
310
+ async function fileExists(p) {
311
+ try { await access(p); return true; } catch { return false; }
312
+ }
313
+
314
+ /**
315
+ * Read every prior run.json under a manager's artifacts dir. Unreadable /
316
+ * non-JSON entries are skipped.
317
+ * @param {import('./artifacts.js').ArtifactManager} manager
318
+ * @returns {Promise<Array<{runName: string, dir: string, meta: object, artifactsPresent: boolean}>>}
319
+ */
320
+ async function scanPriorRuns(manager) {
321
+ const names = await manager.listRunDirs();
322
+ const runs = [];
323
+ for (const runName of names) {
324
+ const dir = join(manager.rootDir, 'artifacts', runName);
325
+ let meta = null;
326
+ try {
327
+ meta = JSON.parse(await readFile(join(dir, 'run.json'), 'utf8'));
328
+ } catch {
329
+ continue;
330
+ }
331
+ const artifactsPresent = await fileExists(join(dir, 'full.md')) && await fileExists(join(dir, 'content_list.json'));
332
+ runs.push({ runName, dir, meta, artifactsPresent });
333
+ }
334
+ return runs;
335
+ }
336
+
337
+ /**
338
+ * A chunk snapshot is usable only when every recorded entry is on disk. A half
339
+ * snapshot (process killed mid-extract), or one whose images were already
340
+ * hoisted, reports false so the caller re-downloads that chunk rather than
341
+ * trusting it.
342
+ * @param {string} chunkDir
343
+ * @param {object} marker
344
+ * @returns {Promise<boolean>}
345
+ */
346
+ async function snapshotUsable(chunkDir, marker) {
347
+ const entries = Array.isArray(marker.entries) ? marker.entries : [];
348
+ if (entries.length === 0) return false;
349
+ for (const name of entries) {
350
+ if (!(await fileExists(join(chunkDir, name)))) return false;
351
+ }
352
+ return true;
353
+ }
354
+
355
+ /**
356
+ * Rebuild a `collected`-shaped value from a finished snapshot (zero network).
357
+ * @returns {Promise<object>}
358
+ */
359
+ async function recordFromSnapshot({ chunk, label, chunkDir, marker, chunkOpts }) {
360
+ const files = (Array.isArray(marker.entries) ? marker.entries : [])
361
+ .map((name) => ({ name, path: join(chunkDir, name) }));
362
+ let markdownText = '';
363
+ try {
364
+ markdownText = await readFile(join(chunkDir, 'full.md'), 'utf8');
365
+ } catch {
366
+ markdownText = '';
367
+ }
368
+ const contentListName = typeof marker.contentListName === 'string' ? marker.contentListName : null;
369
+ const collected = {
370
+ files,
371
+ markdownEntry: { name: 'full.md', path: join(chunkDir, 'full.md') },
372
+ markdownText,
373
+ contentListEntry: contentListName
374
+ ? { name: contentListName, path: join(chunkDir, contentListName) }
375
+ : undefined,
376
+ layoutEntry: null,
377
+ };
378
+ return {
379
+ chunk, label,
380
+ batchId: marker.batchId ?? null,
381
+ taskId: null,
382
+ dataId: chunkOpts.dataId ?? null,
383
+ collected,
384
+ resumed: 'snapshot',
385
+ };
386
+ }
387
+
388
+ /**
389
+ * Split path: one `page_ranges` request per chunk, then merge into one result.
390
+ *
391
+ * Each chunk is an independent batch over the same upload, collected into
392
+ * `chunks/chunk-<n>/`, and the run root is rebuilt with the layout a single
393
+ * request produces: `full.md` (concatenated, one provenance line per chunk) plus
394
+ * `content_list.json` (merged, page indexes mapped back) plus the union of
395
+ * `images/`. `layout.json` and `<uuid>_model.json` are page-indexed arrays, so
396
+ * they stay per chunk where they remain readable.
397
+ *
398
+ * @returns {Promise<{chunks: object[], taskId: null, batchId: null, markdownText: string, markdownBytes: number}>}
399
+ */
400
+ async function runChunkedParse({ client, filePath, fileName, opts, plan, dir, manager, exec, warnings, cacheKey, prevMeta = null }) {
401
+ const createdAt = prevMeta?.createdAt ?? new Date().toISOString();
402
+ const prevBySpec = chunkResumeMap(prevMeta?.chunks);
403
+ const chunkStates = [];
404
+ const records = [];
405
+ let doneCount = 0;
406
+
407
+ const persist = async (status, finishedAt) => {
408
+ await manager.writeFile(dir, 'run.json', JSON.stringify({
409
+ plugin: 'dsh-mineru',
410
+ schema: RUN_STATE_SCHEMA,
411
+ status,
412
+ createdAt,
413
+ ...(finishedAt ? { finishedAt } : {}),
414
+ source: filePath,
415
+ sourceName: fileName,
416
+ api: 'precision',
417
+ modelVersion: opts.modelVersion,
418
+ cacheKey,
419
+ totalPages: plan.totalPages,
420
+ chunkCount: plan.chunks.length,
421
+ chunks: chunkStates,
422
+ }, null, 2));
423
+ };
424
+
425
+ try {
426
+ for (const chunk of plan.chunks) {
427
+ const label = '第 ' + chunk.index + '/' + plan.chunks.length + ' 片(第 ' + chunk.spec + ' 页)';
428
+ const chunkStarted = Date.now();
429
+ const chunkDir = join(dir, 'chunks', 'chunk-' + chunk.index);
430
+ const chunkOpts = { ...opts, pageRanges: chunk.spec, dataId: chunkDataId(opts.dataId ?? fileName, chunk) };
431
+ const state = {
432
+ index: chunk.index, range: chunk.spec, pages: chunk.pages.length,
433
+ batchId: null, taskId: null, dataId: chunkOpts.dataId ?? null,
434
+ state: 'running', startedAt: new Date().toISOString(),
435
+ };
436
+ chunkStates.push(state);
437
+ await persist('running');
438
+ try {
439
+ let record = null;
440
+ // (1) finished local snapshot -> zero network
441
+ const marker = await readChunkMarker(chunkDir);
442
+ if (marker && await snapshotUsable(chunkDir, marker)) {
443
+ record = await recordFromSnapshot({ chunk, label, chunkDir, marker, chunkOpts });
444
+ Object.assign(state, {
445
+ state: 'done', batchId: marker.batchId ?? null, resumed: 'snapshot',
446
+ durationMs: Date.now() - chunkStarted, finishedAt: new Date().toISOString(),
447
+ });
448
+ } else {
449
+ // (2) prior batch aligned by spec: reuse done/running, never re-upload
450
+ const prior = prevBySpec.get(chunk.spec);
451
+ let outcome = null;
452
+ let resumed = null;
453
+ if (prior && (prior.state === 'done' || prior.state === 'running') && prior.batchId) {
454
+ try {
455
+ outcome = await client.resumePrecisionBatch({ batchId: prior.batchId, opts: chunkOpts, signal: exec.signal });
456
+ resumed = 'redownload';
457
+ } catch (err) {
458
+ if (!err?.batchFailed) throw err;
459
+ outcome = null; // a done/running batch that actually failed -> re-submit
460
+ }
461
+ }
462
+ // (3) fresh / prior failed / resumed-as-failed -> new submit
463
+ if (!outcome) {
464
+ outcome = await client.submitAndWaitFile({
465
+ filePath, fileName, opts: chunkOpts, api: 'precision', signal: exec.signal,
466
+ });
467
+ resumed = resumed ?? 'submit';
468
+ }
469
+ if (outcome.state !== 'done') {
470
+ throw new MineruError(
471
+ '云端返回 state=' + outcome.state + (outcome.errMsg ? ':' + outcome.errMsg : ''),
472
+ 'MINERU_PARSE_FAILED',
473
+ { taskId: outcome.taskId, api: 'precision', rawCode: outcome.errCode },
474
+ );
475
+ }
476
+ if (!outcome.fullZipUrl) {
477
+ throw new MineruError('云端状态为 done 但没有返回结果包地址', 'MINERU_API', { taskId: outcome.taskId, api: 'precision' });
478
+ }
479
+ const collected = await client.collectPrecisionZip({
480
+ zipUrl: outcome.fullZipUrl, destDir: chunkDir, opts: chunkOpts, signal: exec.signal,
481
+ });
482
+ await writeChunkMarker(chunkDir, {
483
+ batchId: outcome.batchId ?? null,
484
+ contentListName: collected.contentListEntry?.name ?? null,
485
+ entries: collected.files.map((f) => f.name),
486
+ });
487
+ record = {
488
+ chunk, label,
489
+ batchId: outcome.batchId ?? null,
490
+ taskId: outcome.taskId ?? null,
491
+ dataId: chunkOpts.dataId ?? null,
492
+ collected,
493
+ resumed,
494
+ durationMs: Date.now() - chunkStarted,
495
+ };
496
+ Object.assign(state, {
497
+ state: 'done', batchId: outcome.batchId ?? null, taskId: outcome.taskId ?? null,
498
+ resumed, durationMs: Date.now() - chunkStarted, finishedAt: new Date().toISOString(),
499
+ });
500
+ }
501
+ records.push(record);
502
+ doneCount++;
503
+ await persist('running');
504
+ } catch (err) {
505
+ throw withChunkLabel(label, err);
506
+ }
507
+ }
508
+
509
+ // All chunks collected: remap each chunk's local page numbers to absolute.
510
+ const blocks = [];
511
+ const segments = [];
512
+ let outOfRangeBlocks = 0;
513
+ let imageCount = 0;
514
+ for (const record of records) {
515
+ const contentListPath = extractedPath(record.collected, record.collected.contentListEntry);
516
+ let parsed = null;
517
+ if (contentListPath) {
518
+ try {
519
+ parsed = JSON.parse(await readFile(contentListPath, 'utf8'));
520
+ } catch {
521
+ parsed = null;
522
+ }
523
+ }
524
+ if (!Array.isArray(parsed)) {
525
+ throw new MineruError(
526
+ record.label + ':结果里的 content_list.json 缺失或不是合法 JSON 数组(分片页码映射依赖它)',
527
+ 'MINERU_API',
528
+ { api: 'precision' },
529
+ );
530
+ }
531
+ const mapped = remapChunkPages(parsed, record.chunk.pages);
532
+ blocks.push(...mapped.blocks);
533
+ outOfRangeBlocks += mapped.outOfRange;
534
+ segments.push({
535
+ note: 'chunk ' + record.chunk.index + '/' + plan.chunks.length
536
+ + ': pages ' + record.chunk.spec
537
+ + ' (batch_id ' + (record.batchId ?? '-') + ')',
538
+ markdown: record.collected.markdownText ?? '',
539
+ });
540
+ imageCount += await hoistChunkImages(record.collected, dir);
541
+ }
542
+
543
+ const markdownText = mergeChunksMarkdown(segments);
544
+ await manager.writeFile(dir, 'full.md', markdownText);
545
+ await manager.writeFile(dir, 'content_list.json', JSON.stringify(blocks, null, 2));
546
+ if (outOfRangeBlocks > 0) {
547
+ warnings.push('有 ' + outOfRangeBlocks + ' 个块的 page_idx 落在请求页范围之外,已从合并的 content_list.json 里摘除该字段(页码不可信,宁缺勿错)');
548
+ }
549
+ warnings.push('多分片结果:layout.json 与 <uuid>_model.json 按页数组组织,按片保留在 chunks/chunk-<n>/ 下(共 ' + imageCount + ' 个图片条目已并入 images/)');
550
+
551
+ // Success: drop the raw per-chunk zips (results are merged); the markers and
552
+ // extracted files stay so a later identical run still reuses the snapshot.
553
+ for (let i = 1; i <= plan.chunks.length; i++) {
554
+ await rm(join(dir, 'chunks', 'chunk-' + i, 'result.zip'), { force: true });
555
+ }
556
+ await persist('done', new Date().toISOString());
557
+
558
+ return {
559
+ chunks: records.map((record) => ({
560
+ index: record.chunk.index,
561
+ range: record.chunk.spec,
562
+ pages: record.chunk.pages.length,
563
+ batchId: record.batchId,
564
+ taskId: record.taskId,
565
+ dataId: record.dataId,
566
+ state: 'done',
567
+ resumed: record.resumed ?? null,
568
+ durationMs: record.durationMs,
569
+ })),
570
+ taskId: null,
571
+ batchId: null,
572
+ markdownText,
573
+ markdownBytes: Buffer.byteLength(markdownText, 'utf8'),
574
+ };
575
+ } catch (err) {
576
+ // Keep the run dir: mark the in-flight chunk failed and persist partial
577
+ // (>=1 chunk done) or failed. A re-run aligns by spec and redoes only the
578
+ // failed chunk.
579
+ const running = chunkStates.find((s) => s.state === 'running');
580
+ if (running) {
581
+ Object.assign(running, {
582
+ state: 'failed',
583
+ errCode: err.code ?? 'MINERU_ERROR',
584
+ errMsg: String(err.message ?? err).slice(0, 300),
585
+ finishedAt: new Date().toISOString(),
586
+ });
587
+ }
588
+ await persist(doneCount > 0 ? 'partial' : 'failed', new Date().toISOString());
589
+ throw err;
590
+ }
591
+ }
592
+
593
+ /** Single-request path: one submit, one collect — the pre-existing behaviour. */
594
+ async function runSingleRequest({ client, urlSource, source, filePath, fileName, opts, api, dir, exec, plan }) {
595
+ const started = Date.now();
596
+ const outcome = urlSource
597
+ ? await client.submitAndWaitUrl({ url: source, fileName, opts, api, signal: exec.signal })
598
+ : await client.submitAndWaitFile({ filePath, fileName, opts, api, signal: exec.signal });
599
+ const collected = await client.collectSingle({ outcome, destDir: dir, opts, signal: exec.signal });
600
+ return {
601
+ collected,
602
+ taskId: outcome.taskId ?? null,
603
+ batchId: outcome.batchId ?? null,
604
+ markdownText: collected.markdownText ?? '',
605
+ markdownBytes: collected.markdownBytes ?? null,
606
+ chunks: [{
607
+ index: 1,
608
+ range: opts.pageRanges ?? null,
609
+ pages: plan.chunks.length === 1 ? plan.chunks[0].pages.length : null,
610
+ batchId: outcome.batchId ?? null,
611
+ taskId: outcome.taskId ?? null,
612
+ dataId: opts.dataId ?? null,
613
+ state: 'done',
614
+ durationMs: Date.now() - started,
615
+ }],
616
+ };
617
+ }
618
+ /**
619
+ * Write the opt-in `document.md` (page-anchored Markdown) next to `full.md`.
620
+ *
621
+ * Additive by design: `full.md`, `content_list.json` and `layout.json` keep
622
+ * their existing shape, and a result without a `content_list.json` (the Agent
623
+ * API) only produces a warning instead of failing the parse.
624
+ *
625
+ * @param {object} input
626
+ * @param {{writeFile: Function}} input.manager artifact manager owning the run dir
627
+ * @param {string} input.dir absolute run dir
628
+ * @param {object} input.collected value returned by `client.collectSingle`
629
+ * @param {object} input.opts resolved API options (carries `pageRanges`)
630
+ * @returns {Promise<object|null>} anchor summary, or null when nothing was written
631
+ */
632
+ async function writeAnchoredDocument({ manager, dir, collected, opts, contentListPath, absolutePages }) {
633
+ const listPath = contentListPath ?? collected?.contentListEntry?.path;
634
+ if (!listPath) {
635
+ return {
636
+ document: null,
637
+ written: false,
638
+ warnings: ['本结果不含 content_list.json(Agent 轻量解析 API 或异常结果包),未生成 document.md'],
639
+ };
640
+ }
641
+ let contentList;
642
+ try {
643
+ contentList = await readContentListFile(listPath);
644
+ } catch (err) {
645
+ return {
646
+ document: null,
647
+ written: false,
648
+ warnings: ['读取 content_list.json 失败,未生成 document.md: ' + (err?.message ?? String(err))],
649
+ };
650
+ }
651
+ const { markdown, stats, warnings, pageNumbers } = synthesizeDocument(contentList, {
652
+ pageRanges: absolutePages ? null : (typeof opts?.pageRanges === 'string' ? opts.pageRanges : null),
653
+ });
654
+ await manager.writeFile(dir, 'document.md', markdown);
655
+ return {
656
+ document: join(dir, 'document.md'),
657
+ written: true,
658
+ blocks: stats.bodyBlocks,
659
+ pages: stats.pages,
660
+ pageNumbers,
661
+ unreadableBlocks: stats.unreadableBlocks,
662
+ warnings,
663
+ };
664
+ }
665
+
666
+ /** Anchor summary: null when the caller did not ask for `document.md`. */
667
+ const ANCHOR_SCHEMA = { type: 'json' };
668
+
669
+ /**
145
670
  * Orchestrate one single-document parse: resolve mode/api, validate source,
146
671
  * submit (URL or signature upload), wait, download, extract into a fresh run
147
672
  * dir, and build the canonical result value.
673
+ *
674
+ * A precision request that asks for more than the per-request page cap is split
675
+ * into `page_ranges` chunks transparently — no new parameter, same artifact
676
+ * layout — while the Agent API and sources whose page count cannot be read
677
+ * locally keep the single-request behaviour.
148
678
  * @param {object} input { source, args, cfg, exec, state }
149
679
  */
150
680
  async function runSingleParse({ source, args, cfg, exec, state }) {
@@ -178,11 +708,11 @@ async function runSingleParse({ source, args, cfg, exec, state }) {
178
708
  ext = checked.ext;
179
709
  }
180
710
 
181
- let warning;
711
+ const warnings = [];
182
712
  if (api === 'precision') {
183
713
  const forced = effectiveModelFor(ext, opts.modelVersion);
184
714
  opts.modelVersion = forced.modelVersion;
185
- if (forced.forced) warning = 'HTML 源已自动使用 MinerU-HTML 模型 (忽略其他 modelVersion)';
715
+ if (forced.forced) warnings.push('HTML 源已自动使用 MinerU-HTML 模型 (忽略其他 modelVersion)');
186
716
  } else if (ext && AGENT_UNSUPPORTED_EXTENSIONS.includes(ext)) {
187
717
  throw new MineruError(
188
718
  'Agent 轻量解析 API 不支持 ' + ext + ' 文件: 请改用精准解析 API (mode=precision 并配置 Token).',
@@ -190,51 +720,127 @@ async function runSingleParse({ source, args, cfg, exec, state }) {
190
720
  );
191
721
  }
192
722
 
723
+ const plan = await planChunking({ api, ext, filePath, urlSource, pageRanges: opts.pageRanges });
724
+ const chunked = plan.chunks.length > 1;
725
+
193
726
  const manager = await state.artifacts.managerFor(cwd);
194
727
  const runBase = sanitizeFileName(args.output ?? (fileName ?? 'parse'));
195
- const { dir, relDir } = await manager.createRun(runBase);
728
+
729
+ // Chunked runs are content-addressed: locate a prior run of this exact source
730
+ // + intent before creating anything. Single-request runs keep the old flow.
731
+ let dir;
732
+ let relDir;
733
+ let cacheKey = null;
734
+ let prevMeta = null;
735
+ if (chunked) {
736
+ cacheKey = buildRunCacheKey({
737
+ sha256: await hashFile(filePath),
738
+ requestedSpec: plan.chunks.map((chunk) => chunk.spec).join(','),
739
+ modelVersion: opts.modelVersion,
740
+ isOcr: opts.isOcr,
741
+ language: opts.language,
742
+ });
743
+ const decision = decideRunResume({ runs: await scanPriorRuns(manager), cacheKey });
744
+ if (decision.action === 'reuse') {
745
+ const reused = decision.run;
746
+ dir = reused.dir;
747
+ relDir = join('artifacts', reused.runName);
748
+ const markdownText = await readFile(join(dir, 'full.md'), 'utf8');
749
+ const preview = truncateMarkdown(markdownText, cfg.inlineMarkdownBytes);
750
+ const artifacts = await manager.describeRun(
751
+ relDir,
752
+ state.urlBuilder ? { capabilityFor: (rel) => state.urlBuilder(cwd, rel) } : undefined,
753
+ );
754
+ return {
755
+ ok: true,
756
+ api, mode: effectiveMode, modelVersion: opts.modelVersion,
757
+ taskId: null, batchId: null, state: 'done', durationMs: 0,
758
+ sourceName: displayName, sourceKind: 'file', sourceBytes: fileSize,
759
+ runDir: dir, reused: true, warning: null,
760
+ markdownBytes: reused.meta.markdownBytes ?? Buffer.byteLength(markdownText, 'utf8'),
761
+ anchor: null, preview, artifacts,
762
+ chunkCount: reused.meta.chunkCount ?? plan.chunks.length,
763
+ chunks: reused.meta.chunks ?? [],
764
+ };
765
+ }
766
+ if (decision.action === 'resume') {
767
+ dir = decision.run.dir;
768
+ relDir = join('artifacts', decision.run.runName);
769
+ prevMeta = decision.run.meta;
770
+ } else {
771
+ ({ dir, relDir } = await manager.createRun(runBase));
772
+ }
773
+ } else {
774
+ ({ dir, relDir } = await manager.createRun(runBase));
775
+ }
776
+
196
777
  const started = Date.now();
197
778
  try {
198
- const outcome = urlSource
199
- ? await client.submitAndWaitUrl({ url: source, fileName, opts, api, signal: exec.signal })
200
- : await client.submitAndWaitFile({ filePath, fileName, opts, api, signal: exec.signal });
201
- const collected = await client.collectSingle({ outcome, destDir: dir, opts, signal: exec.signal });
779
+ const result = chunked
780
+ ? await runChunkedParse({ client, filePath, fileName, opts, plan, dir, manager, exec, warnings, cacheKey, prevMeta })
781
+ : await runSingleRequest({ client, urlSource, source, filePath, fileName, opts, api, dir, exec, plan });
782
+ const anchor = args.anchor !== true ? null
783
+ : chunked
784
+ ? await writeAnchoredDocument({ manager, dir, contentListPath: join(dir, 'content_list.json'), absolutePages: true })
785
+ : await writeAnchoredDocument({ manager, dir, collected: result.collected, opts });
202
786
  const durationMs = Date.now() - started;
787
+ if (chunked) {
788
+ warnings.unshift('文档共 ' + plan.totalPages + ' 页,超过单次请求 ' + PRECISION_PAGE_LIMIT
789
+ + ' 页上限,已自动分 ' + plan.chunks.length + ' 片解析并合并结果(每片一次 page_ranges 请求,timeoutMs 对每片生效)');
790
+ }
791
+ const warning = warnings.length > 0 ? warnings.join(';') : null;
203
792
  const metadata = {
204
793
  plugin: 'dsh-mineru',
205
794
  createdAt: new Date().toISOString(),
206
795
  source: urlSource ? source : filePath,
207
796
  sourceName: displayName,
208
797
  api, mode: effectiveMode, modelVersion: opts.modelVersion,
209
- taskId: outcome.taskId ?? null,
210
- batchId: outcome.batchId ?? null,
798
+ taskId: result.taskId,
799
+ batchId: result.batchId,
211
800
  state: 'done',
212
801
  durationMs,
213
- markdownBytes: collected.markdownBytes ?? null,
214
- warning: warning ?? null,
802
+ markdownBytes: result.markdownBytes,
803
+ warning,
804
+ // Only a split run adds chunk bookkeeping; a single-request run.json is
805
+ // unchanged so anything reading it keeps working.
806
+ ...(chunked ? {
807
+ status: 'done',
808
+ cacheKey,
809
+ chunkCount: plan.chunks.length,
810
+ pagesPerRequest: PRECISION_PAGE_LIMIT,
811
+ pagesRequested: plan.pagesRequested,
812
+ totalPages: plan.totalPages,
813
+ pageCountMethod: plan.method,
814
+ chunks: result.chunks,
815
+ } : {}),
215
816
  };
216
817
  await manager.writeFile(dir, 'run.json', JSON.stringify(metadata, null, 2));
217
- const preview = truncateMarkdown(collected.markdownText, cfg.inlineMarkdownBytes);
818
+ const preview = truncateMarkdown(result.markdownText, cfg.inlineMarkdownBytes);
218
819
  const artifacts = await manager.describeRun(relDir, state.urlBuilder ? { capabilityFor: (rel) => state.urlBuilder(cwd, rel) } : undefined);
219
820
  return {
220
821
  ok: true,
221
822
  api, mode: effectiveMode, modelVersion: opts.modelVersion,
222
- taskId: outcome.taskId ?? null,
223
- batchId: outcome.batchId ?? null,
823
+ taskId: result.taskId,
824
+ batchId: result.batchId,
224
825
  state: 'done',
225
826
  durationMs,
226
827
  sourceName: displayName,
227
828
  sourceKind: urlSource ? 'url' : 'file',
228
829
  sourceBytes: fileSize,
229
830
  runDir: dir,
230
- warning: warning ?? null,
231
- markdownBytes: collected.markdownBytes ?? null,
831
+ warning,
832
+ markdownBytes: result.markdownBytes,
833
+ anchor,
232
834
  preview,
233
835
  artifacts,
836
+ chunkCount: result.chunks.length,
837
+ chunks: result.chunks,
234
838
  };
235
839
  } catch (err) {
236
- await rm(dir, { recursive: true, force: true }).catch(() => {});
237
- throw err;
840
+ // Chunked runs persist partial/failed and keep their snapshots for resume;
841
+ // only single-request runs clean up the run dir on failure.
842
+ if (!chunked) await rm(dir, { recursive: true, force: true }).catch(() => {});
843
+ throw withChunkingHint(err, plan);
238
844
  }
239
845
  }
240
846
 
@@ -243,6 +849,23 @@ const ARTIFACT_ITEM_SCHEMA = { type: 'object', additionalProperties: false, prop
243
849
  kind: { type: 'string' }, mime: { type: 'string' }, bytes: { type: 'number' }, url: { type: 'string' },
244
850
  } };
245
851
 
852
+ /** One submitted request: the whole call, or one chunk of a split call. */
853
+ const CHUNK_ITEM_SCHEMA = {
854
+ type: 'object',
855
+ additionalProperties: false,
856
+ properties: {
857
+ index: { type: 'number' },
858
+ range: { type: 'json' },
859
+ pages: { type: 'json' },
860
+ batchId: { type: 'json' },
861
+ taskId: { type: 'json' },
862
+ dataId: { type: 'json' },
863
+ state: { type: 'string' },
864
+ resumed: { type: 'json' },
865
+ durationMs: { type: 'number' },
866
+ },
867
+ };
868
+
246
869
  const PARSE_RESULT_SCHEMA = {
247
870
  type: 'object',
248
871
  additionalProperties: false,
@@ -259,20 +882,38 @@ const PARSE_RESULT_SCHEMA = {
259
882
  sourceKind: { type: 'string' },
260
883
  sourceBytes: { type: 'json' },
261
884
  runDir: { type: 'string' },
885
+ reused: { type: 'boolean' },
262
886
  warning: { type: 'json' },
263
887
  markdownBytes: { type: 'json' },
888
+ anchor: ANCHOR_SCHEMA,
264
889
  preview: { type: 'object', additionalProperties: false, properties: { markdown: { type: 'string' }, truncated: { type: 'boolean' }, bytes: { type: 'number' } } },
265
890
  artifacts: { type: 'array', items: ARTIFACT_ITEM_SCHEMA },
891
+ chunkCount: { type: 'number' },
892
+ chunks: { type: 'array', items: CHUNK_ITEM_SCHEMA },
266
893
  },
267
894
  };
268
895
 
269
896
  function renderParseContent(value) {
270
897
  const lines = [
271
898
  'MinerU 解析完成 (' + value.api + ' API, ' + value.modelVersion + ', 耗时 ' + (value.durationMs / 1000).toFixed(1) + 's)',
272
- '- 任务: ' + value.taskId,
899
+ '- 任务: ' + (value.taskId ?? '-'),
273
900
  '- 结果目录: ' + value.runDir,
274
901
  ];
902
+ const chunks = Array.isArray(value.chunks) ? value.chunks : [];
903
+ if (chunks.length > 1) {
904
+ lines.push('- 分片: ' + chunks.length + ' 片 (每片一次 page_ranges 请求, 结果已合并)');
905
+ for (const chunk of chunks) {
906
+ lines.push(' - 第 ' + chunk.index + '/' + chunks.length + ' 片: 第 ' + chunk.range + ' 页, batchId '
907
+ + (chunk.batchId ?? '-') + ', ' + chunk.state + ', ' + ((chunk.durationMs ?? 0) / 1000).toFixed(1) + 's');
908
+ }
909
+ }
275
910
  if (value.warning) lines.push('- 注意: ' + value.warning);
911
+ if (value.anchor?.written) {
912
+ lines.push('- 页级块锚点: ' + value.anchor.document + ' (' + value.anchor.blocks + ' 个正文块 / ' + value.anchor.pages + ' 页)');
913
+ }
914
+ for (const note of value.anchor?.warnings ?? []) {
915
+ lines.push('- 锚点提示: ' + note);
916
+ }
276
917
  for (const a of value.artifacts ?? []) {
277
918
  lines.push('- Artifact: ' + a.name + ' (' + a.kind + ', ' + formatBytes(a.bytes) + ')' + (a.url ? ' 预览: ' + a.url : ''));
278
919
  }
@@ -286,7 +927,7 @@ function renderParseContent(value) {
286
927
  export function buildParseTool(state) {
287
928
  return defineTool({
288
929
  name: 'mineru_parse',
289
- description: '用 MinerU 解析单个文档为结构化 Markdown: 支持 PDF/Word(doc,docx)/PPT(ppt,pptx)/Excel(xls,xlsx)/HTML/图片(png,jpg,jpeg,jp2,webp,gif,bmp). source 为工作区文件路径或 http(s) URL. 已配置 Token 时默认走精准解析 API(<=200MB/<=200页, Zip 含 full.md+JSON+可加 docx/html/latex), 未配置 Token 时走 Agent 轻量解析 API(<=10MB/<=20页, 仅 Markdown). 结果落地到 <workspace>/.dsh-mineru/artifacts/<run>/ 并以 Artifact 列表返回.',
930
+ description: '用 MinerU 解析单个文档为结构化 Markdown: 支持 PDF/Word(doc,docx)/PPT(ppt,pptx)/Excel(xls,xlsx)/HTML/图片(png,jpg,jpeg,jp2,webp,gif,bmp). source 为工作区文件路径或 http(s) URL. 已配置 Token 时默认走精准解析 API(<=200MB/<=200页, Zip 含 full.md+JSON+可加 docx/html/latex), 未配置 Token 时走 Agent 轻量解析 API(<=10MB/<=20页, 仅 Markdown). 工作区 PDF 本次要解析的页数超过单次 200 页上限时, 自动按 page_ranges 分片提交并合并为一份结果(无需新参数; 多片时每片独立轮询, timeoutMs 对每片生效; layout.json 与模型 JSON 按片保留在 chunks/ 下). Agent 轻量解析 API 与本地读不出页数的来源不做自动分片. 结果落地到 <workspace>/.dsh-mineru/artifacts/<run>/ 并以 Artifact 列表返回.',
290
931
  parameters: {
291
932
  source: { type: 'string', required: true, description: '工作区文件路径或完整 http(s) URL.' },
292
933
  ...parseOptionParams(),
@@ -374,11 +1015,14 @@ async function runBatchParse({ sources, args, cfg, exec, state }) {
374
1015
  const safeName = sanitizeFileName(item.name ?? ('item-' + results.length));
375
1016
  const itemDir = joinSafe(dir, safeName);
376
1017
  const collected = await client.collectPrecisionZip({ zipUrl: item.fullZipUrl, destDir: itemDir, opts, signal: exec.signal });
1018
+ const anchor = args.anchor === true
1019
+ ? await writeAnchoredDocument({ manager, dir: itemDir, collected, opts })
1020
+ : null;
377
1021
  doneCount += 1;
378
1022
  const relItemDir = relDir.replace(/\\/g, '/') + '/' + safeName;
379
1023
  const itemArtifacts = await manager.describeRun(relItemDir, state.urlBuilder ? { capabilityFor: (rel) => state.urlBuilder(cwd, rel) } : undefined);
380
1024
  flatArtifacts.push(...itemArtifacts);
381
- results.push({ name: item.name, state: 'done', dir: itemDir, markdownBytes: collected.markdownBytes ?? null, artifacts: itemArtifacts });
1025
+ results.push({ name: item.name, state: 'done', dir: itemDir, markdownBytes: collected.markdownBytes ?? null, anchor, artifacts: itemArtifacts });
382
1026
  } else {
383
1027
  failedCount += 1;
384
1028
  results.push({ name: item.name, state: item.state ?? 'failed', errMsg: item.errMsg ?? null });
@@ -456,6 +1100,7 @@ const BATCH_RESULT_SCHEMA = {
456
1100
  results: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
457
1101
  name: { type: 'string' }, state: { type: 'string' }, dir: { type: 'json' },
458
1102
  errMsg: { type: 'json' }, markdownBytes: { type: 'json' },
1103
+ anchor: ANCHOR_SCHEMA,
459
1104
  artifacts: { type: 'array', items: ARTIFACT_ITEM_SCHEMA },
460
1105
  } } },
461
1106
  artifacts: { type: 'array', items: ARTIFACT_ITEM_SCHEMA },
@@ -538,6 +1183,7 @@ export function buildBatchTool(state) {
538
1183
  progress: { type: 'json' },
539
1184
  runDir: { type: 'json' },
540
1185
  preview: { type: 'json' },
1186
+ anchor: ANCHOR_SCHEMA,
541
1187
  artifacts: { type: 'array', items: ARTIFACT_ITEM_SCHEMA },
542
1188
  },
543
1189
  };
@@ -566,6 +1212,7 @@ export function buildTaskTool(state) {
566
1212
  api: { type: 'string', enum: ['precision', 'agent'], required: true, description: '任务所属 API: precision 或 agent.' },
567
1213
  wait: { type: 'boolean', description: '是否轮询等待任务完成 (默认 false, 只查询一次).' },
568
1214
  collect: { type: 'boolean', description: '任务完成时是否下载结果落地为 Artifact (默认 true).' },
1215
+ anchor: { type: 'boolean', description: '收集结果时额外产出一份带页级块锚点的 document.md (默认 false, 仅精准解析结果含 content_list.json).' },
569
1216
  output: { type: 'string', description: '收集结果目录基名 (默认 task).' },
570
1217
  timeoutMs: { type: 'number', description: 'wait 模式下的超时毫秒数.' },
571
1218
  },
@@ -627,6 +1274,7 @@ export function buildTaskTool(state) {
627
1274
  progress: outcome.progress ?? null,
628
1275
  runDir: null,
629
1276
  preview: null,
1277
+ anchor: null,
630
1278
  artifacts: [],
631
1279
  };
632
1280
  if (outcome.state !== 'done') return base;
@@ -634,8 +1282,12 @@ export function buildTaskTool(state) {
634
1282
  const cwd = exec.agent?.session?.header?.cwd ?? process.cwd();
635
1283
  const manager = await state.artifacts.managerFor(cwd);
636
1284
  const { dir, relDir } = await manager.createRun(sanitizeFileName(args.output ?? 'task'));
1285
+ const collectOpts = resolveOptions(cfg, { ...args, timeoutMs: args.timeoutMs });
637
1286
  try {
638
- const collected = await client.collectSingle({ outcome, destDir: dir, opts: resolveOptions(cfg, { ...args, timeoutMs: args.timeoutMs }), signal: exec.signal });
1287
+ const collected = await client.collectSingle({ outcome, destDir: dir, opts: collectOpts, signal: exec.signal });
1288
+ const anchor = args.anchor === true
1289
+ ? await writeAnchoredDocument({ manager, dir, collected, opts: collectOpts })
1290
+ : null;
639
1291
  const metadata = {
640
1292
  plugin: 'dsh-mineru',
641
1293
  createdAt: new Date().toISOString(),
@@ -651,6 +1303,7 @@ export function buildTaskTool(state) {
651
1303
  state: 'done',
652
1304
  runDir: dir,
653
1305
  preview,
1306
+ anchor,
654
1307
  artifacts,
655
1308
  };
656
1309
  } catch (err) {