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.
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Best-effort local page count for PDFs (pure function, no I/O).
3
+ *
4
+ * Why it exists: splitting a long document means asking for `page_ranges`
5
+ * chunks, and both the chunk plan and a negative spec like `"2--2"` need the
6
+ * document total before any request goes out. The host half is plain Node with
7
+ * no PDF library, so this reads the page tree the way a viewer's preflight does:
8
+ *
9
+ * 1. the `/Count` of a `/Type /Pages` node — the largest one found is the
10
+ * document total, because a root node's count covers its subtrees (bounded
11
+ * lookahead after each node, see COUNT_WINDOW);
12
+ * 2. how many `/Type /Page` leaf objects appear;
13
+ * 3. the same two scans over every decodable stream, because PDF 1.5+ may keep
14
+ * page objects inside `/Type /ObjStm` object streams.
15
+ *
16
+ * Boundaries: an encrypted, damaged or otherwise unusual file can leave the
17
+ * count undetermined; the function then reports `pages: null` and the caller
18
+ * keeps its previous single-request behaviour instead of guessing a number.
19
+ * @module dsh-mineru/pdf-pages
20
+ */
21
+ import { inflateRawSync, inflateSync } from 'node:zlib';
22
+
23
+ /**
24
+ * Largest PDF read into one latin1 string. V8 caps string length well above
25
+ * this, but a whole-file scan of a 200 MB upload is already the expensive path,
26
+ * and an undetermined count is a supported outcome.
27
+ */
28
+ const MAX_SCAN_BYTES = 256 * 1024 * 1024;
29
+ /** Bytes searched after a `/Type /Pages` node for its own `/Count`. */
30
+ const COUNT_WINDOW = 1024 * 1024;
31
+ /** Upper bound on one decoded stream (an image stream is not a page tree). */
32
+ const MAX_STREAM_BYTES = 16 * 1024 * 1024;
33
+ /** Upper bound on all decoded stream text per document. */
34
+ const MAX_DECODED_BYTES = 64 * 1024 * 1024;
35
+
36
+ const PAGES_NODE_SOURCE = String.raw`\/Type\s*\/Pages\b`;
37
+ const PAGE_LEAF_SOURCE = String.raw`\/Type\s*\/Page(?![A-Za-z])`;
38
+ const COUNT_VALUE = /^\s+(\d+)/;
39
+
40
+ /** @param {string} text @param {string} source @returns {number} */
41
+ function countMatches(text, source) {
42
+ const re = new RegExp(source, 'g');
43
+ let count = 0;
44
+ while (re.exec(text) !== null) count += 1;
45
+ return count;
46
+ }
47
+
48
+ /**
49
+ * Collect the `/Count` of every page-tree node found in one text blob.
50
+ *
51
+ * The lookahead is `indexOf`-based rather than a windowed regex: a big document
52
+ * has many page-tree nodes, and a per-node regex window would rescan megabytes
53
+ * per node.
54
+ * @param {string} text @param {number[]} counts output list
55
+ */
56
+ function collectCounts(text, counts) {
57
+ const re = new RegExp(PAGES_NODE_SOURCE, 'g');
58
+ let match;
59
+ while ((match = re.exec(text)) !== null) {
60
+ const from = match.index + match[0].length;
61
+ const at = text.indexOf('/Count', from);
62
+ if (at === -1 || at - from > COUNT_WINDOW) continue;
63
+ const value = COUNT_VALUE.exec(text.slice(at + 6, at + 30));
64
+ if (value) counts.push(Number.parseInt(value[1], 10));
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Texts of every deflate-decodable stream in the file.
70
+ *
71
+ * Page objects of PDF 1.5+ documents live inside object streams, so the raw byte
72
+ * scan sees only the container. Only streams that decompress without error
73
+ * contribute, and only up to the byte caps above.
74
+ * @param {Buffer} buffer @returns {string[]}
75
+ */
76
+ function decodedStreamTexts(buffer) {
77
+ const texts = [];
78
+ const streamMarker = Buffer.from('stream');
79
+ const endMarker = Buffer.from('endstream');
80
+ let total = 0;
81
+ let index = buffer.indexOf(streamMarker);
82
+ while (index !== -1 && total < MAX_DECODED_BYTES) {
83
+ // "endstream" contains "stream" too; only real stream starts count.
84
+ if (index >= 3 && buffer.toString('latin1', index - 3, index) === 'end') {
85
+ index = buffer.indexOf(streamMarker, index + streamMarker.length);
86
+ continue;
87
+ }
88
+ let dataStart = index + streamMarker.length;
89
+ if (buffer[dataStart] === 0x0d) dataStart += 1;
90
+ if (buffer[dataStart] === 0x0a) dataStart += 1;
91
+ const dataEnd = buffer.indexOf(endMarker, dataStart);
92
+ if (dataEnd === -1) break;
93
+ const raw = buffer.subarray(dataStart, dataEnd);
94
+ if (raw.length > 0 && raw.length <= MAX_STREAM_BYTES) {
95
+ for (const inflate of [inflateSync, inflateRawSync]) {
96
+ try {
97
+ const out = inflate(raw, { maxOutputLength: MAX_STREAM_BYTES });
98
+ texts.push(out.toString('latin1'));
99
+ total += out.length;
100
+ break;
101
+ } catch {
102
+ // Not a zlib/deflate stream (image data, ASCII filters) — try the next
103
+ // inflate flavour and otherwise ignore the stream.
104
+ }
105
+ }
106
+ }
107
+ index = buffer.indexOf(streamMarker, dataEnd + endMarker.length);
108
+ }
109
+ return texts;
110
+ }
111
+
112
+ /**
113
+ * @typedef {object} PdfPageCount
114
+ * @property {number|null} pages total pages, or null when it cannot be determined
115
+ * @property {'count'|'count+objstm'|'page-objects'|'none'} method how it was obtained;
116
+ * `count+objstm` means the number came out of a decoded object stream
117
+ */
118
+
119
+ /**
120
+ * @param {Buffer|Uint8Array} input PDF bytes
121
+ * @returns {PdfPageCount}
122
+ */
123
+ export function countPdfPages(input) {
124
+ const buffer = Buffer.isBuffer(input) ? input : Buffer.from(input);
125
+ if (buffer.length === 0) return { pages: null, method: 'none' };
126
+ const head = buffer.subarray(0, Math.min(buffer.length, 1024)).toString('latin1');
127
+ if (!head.includes('%PDF-')) return { pages: null, method: 'none' };
128
+ if (buffer.length > MAX_SCAN_BYTES) return { pages: null, method: 'none' };
129
+
130
+ const counts = [];
131
+ const rawText = buffer.toString('latin1');
132
+ collectCounts(rawText, counts);
133
+ let pageObjects = countMatches(rawText, PAGE_LEAF_SOURCE);
134
+
135
+ let countFromStream = false;
136
+ const decoded = decodedStreamTexts(buffer);
137
+ for (const text of decoded) {
138
+ const before = counts.length;
139
+ collectCounts(text, counts);
140
+ if (counts.length > before) countFromStream = true;
141
+ pageObjects += countMatches(text, PAGE_LEAF_SOURCE);
142
+ }
143
+
144
+ let maxCount = 0;
145
+ for (const value of counts) if (value > maxCount) maxCount = value;
146
+ if (maxCount > 0) {
147
+ return { pages: maxCount, method: countFromStream ? 'count+objstm' : 'count' };
148
+ }
149
+ if (pageObjects > 0) return { pages: pageObjects, method: 'page-objects' };
150
+ return { pages: null, method: 'none' };
151
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Chunk-level run state, snapshots and resume decisions (pure functions plus a
3
+ * few small file helpers).
4
+ *
5
+ * Why this exists: an over-limit precision parse is several `page_ranges`
6
+ * requests. If the process is killed (or one chunk fails) after some chunks are
7
+ * already parsed — and billed — re-running the same instruction must (1) find
8
+ * the previous run by content, not a fresh timestamp dir, (2) align chunks by
9
+ * their page spec, never array order, and (3) reuse finished chunks from a
10
+ * snapshot or re-download them, re-submitting only chunks the cloud marked
11
+ * failed. Nothing here re-uploads a finished chunk.
12
+ * @module dsh-mineru/run-state
13
+ */
14
+ import { createHash } from 'node:crypto';
15
+ import { readFile, writeFile } from 'node:fs/promises';
16
+ import { join } from 'node:path';
17
+
18
+ export const RUN_STATE_SCHEMA = 'dsh-mineru/run/1';
19
+
20
+ /** Written last inside a chunk snapshot; its absence means a half snapshot. */
21
+ export const CHUNK_MARKER = '.complete.json';
22
+
23
+ /** @param {Buffer | string} data @returns {string} hex sha256 */
24
+ export function sha256Of(data) {
25
+ return createHash('sha256').update(data).digest('hex');
26
+ }
27
+
28
+ /**
29
+ * Stable key for "the same source parsed with the same intent". sha256 alone is
30
+ * insufficient: different page selections / models of one file must not collide.
31
+ * @param {{ sha256: string, requestedSpec?: string|null, modelVersion?: string, isOcr?: boolean, language?: string }} input
32
+ * @returns {string}
33
+ */
34
+ export function buildRunCacheKey(input) {
35
+ return [
36
+ 'api-v4',
37
+ input.sha256,
38
+ input.requestedSpec ?? 'all',
39
+ input.modelVersion ?? 'vlm',
40
+ input.isOcr ? 'ocr' : 'noocr',
41
+ input.language ?? 'ch',
42
+ ].join('|');
43
+ }
44
+
45
+ /**
46
+ * Decide what to do given prior runs of this workspace.
47
+ *
48
+ * @param {{ runs: Array<{dir: string, meta: Record<string, unknown>, artifactsPresent: boolean}>, cacheKey: string }} input
49
+ * @returns {{ action: 'fresh' | 'reuse' | 'resume', run: object | null }}
50
+ * reuse — done and artifacts present (zero network); resume — a partial /
51
+ * running run exists; fresh — nothing reusable (no match, done-but-missing, or
52
+ * failed).
53
+ */
54
+ export function decideRunResume(input) {
55
+ const matches = input.runs
56
+ .filter((r) => r.meta && r.meta.cacheKey === input.cacheKey)
57
+ .sort((a, b) => String(b.meta.createdAt ?? '').localeCompare(String(a.meta.createdAt ?? '')));
58
+ if (matches.length === 0) return { action: 'fresh', run: null };
59
+ for (const run of matches) {
60
+ if (run.meta.status === 'done' && run.artifactsPresent) return { action: 'reuse', run };
61
+ }
62
+ for (const run of matches) {
63
+ if (run.meta.status === 'partial' || run.meta.status === 'running') {
64
+ return { action: 'resume', run };
65
+ }
66
+ }
67
+ return { action: 'fresh', run: null };
68
+ }
69
+
70
+ /**
71
+ * Index prior chunk records by their page spec. The spec string is the only
72
+ * safe alignment key: array order silently mismatches when the requested spec
73
+ * changes and would write one chunk's content under another chunk's pages.
74
+ * @param {Array<Record<string, unknown>>} prevChunks
75
+ * @returns {Map<string, Record<string, unknown>>}
76
+ */
77
+ export function chunkResumeMap(prevChunks) {
78
+ const map = new Map();
79
+ for (const chunk of Array.isArray(prevChunks) ? prevChunks : []) {
80
+ if (chunk && typeof chunk.range === 'string' && !map.has(chunk.range)) map.set(chunk.range, chunk);
81
+ }
82
+ return map;
83
+ }
84
+
85
+ /** @param {string} chunkDir @returns {string} */
86
+ export function chunkMarkerPath(chunkDir) {
87
+ return join(chunkDir, CHUNK_MARKER);
88
+ }
89
+
90
+ /**
91
+ * Persist a chunk snapshot marker (written after every entry is on disk).
92
+ * @param {string} chunkDir
93
+ * @param {{ batchId: string|null, contentListName: string|null, entries: string[] }} payload
94
+ */
95
+ export async function writeChunkMarker(chunkDir, payload) {
96
+ await writeFile(
97
+ chunkMarkerPath(chunkDir),
98
+ JSON.stringify({ ...payload, finishedAt: new Date().toISOString() }, null, 2) + '\n',
99
+ );
100
+ }
101
+
102
+ /**
103
+ * Read a chunk snapshot marker. Missing / unreadable -> null (caller treats it
104
+ * as no snapshot).
105
+ * @param {string} chunkDir
106
+ * @returns {Promise<Record<string, unknown> | null>}
107
+ */
108
+ export async function readChunkMarker(chunkDir) {
109
+ try {
110
+ return JSON.parse(await readFile(chunkMarkerPath(chunkDir), 'utf8'));
111
+ } catch {
112
+ return null;
113
+ }
114
+ }
package/lib/skill.js CHANGED
@@ -7,4 +7,4 @@ export const SKILL_NAME = 'mineru-tools';
7
7
 
8
8
  export const SKILL_DESCRIPTION = 'MinerU 多模态文档解析: PDF/Office/图片/HTML 转为结构化 Markdown. 涵盖精准解析 API 与 Agent 轻量解析 API 的调用、批量解析、结果文件与官方限制.';
9
9
 
10
- export const SKILL_CONTENT = '# MinerU 文档解析 (dsh-mineru)\n\n本技能授予你基于 MinerU 的多模态全格式文档解析能力. 所有解析结果以结构化 Markdown 落地为工作区文件 (Artifact), 同时工具结果内附有限长度的预览.\n\n## 可用工具\n\n- mineru_parse — 解析单个文档 (本地文件路径或 http(s) URL).\n- mineru_batch_parse — 批量解析 (仅精准解析 API, 需要 Token; 本地文件或 URL 列表).\n- mineru_task — 查询/收集已提交任务的结果 (超时后恢复用).\n\n若上述工具未出现在你的工具列表中, 先调用一次 mineru_activate 激活本插件 (该工具在激活后对本会话隐藏).\n\n## 两种 API 模式 (自动选择, 可显式覆盖)\n\n| 维度 | 精准解析 API (需 Token) | Agent 轻量解析 API (免 Token) |\n| --- | --- | --- |\n| 触发 | 已配置 MinerU Token (默认自动) | Token 留空 (默认自动) |\n| 模型 | pipeline / vlm (默认) / MinerU-HTML | 固定 pipeline 轻量模型 |\n| 限制 | <=200MB, <=200 页 | <=10MB, <=20 页 |\n| 批量 | 支持 (URL <=200 个/批, 本地上传 <=50 个/批) | 仅单文件 |\n| 输出 | Zip: full.md + JSON (可加 docx/html/latex) | 仅 Markdown |\n\nmode 参数可显式指定: mode="precision" 强制精准解析 (无 Token 会报错), mode="agent" 强制轻量解析, 缺省 auto 按 Token 是否配置自动选择.\n\n## 使用要点\n\n1. 来源: 本地文件用工作区路径; 远程文档用完整 http(s) URL (注意 MinerU 无法访问 github/aws 等被墙 URL).\n2. HTML 文件仅精准解析支持, 且自动强制 model_version=MinerU-HTML. Agent 模式不支持 html/doc/ppt/xls.\n3. 页码范围: 精准解析用 pageRanges (逗号分隔, 如 "2,4-6", 支持 "2--2" 倒数页码); Agent 用 pageRange (如 "1-10").\n4. language 取值: ch (中英, 默认), en, japan, korean, chinese_cht, latin, arabic, cyrillic, east_slavic, devanagari, ch_server, ta, te, ka, el, th.\n5. extraFormats 仅精准解析有效: ["docx","html","latex"] 会随 Zip 一并导出.\n6. 长文档优先用精准解析 + pageRanges 分段; 大批量文档用 mineru_batch_parse.\n6b. Web 界面可直接把文档/图片拖入聊天窗口: 插件会自动保存到工作区并把文件路径填入输入框 (不自动发送), 用户补充需求后自行发送; 你收到文件路径后按第 7 条调用 mineru_parse.\n7. 结果目录: <workspace>/.dsh-mineru/artifacts/<run>/. 精准解析为解包后的完整 Zip (full.md, *_content_list.json, layout.json, images/ 等), Agent 为 full.md. 请用 read 工具读取 full.md 全文; 工具结果里的 preview 字段是截断预览.\n8. 结果文件路径同时出现在 tool/result 中, Web 界面可直接预览/打开; URL 为签名链接, 带有效期.\n\n## 官方限流 (插件已内置本地限速与 429 退避)\n\n- 提交: 50 个文件/分钟 (含单文件、批量上传、批量 URL), 5000 个文件/天/用户 (html 最多 100 个/天).\n- 查询: 1000 次/分钟.\n- 超出限制的请求会被系统拒绝 (HTTP 429).\n\n## 错误处理\n\n- A0202/A0211 → Token 错误/过期, 提示用户在设置中更新 Token.\n- -60005/-30001 → 文件超限 (200MB / 10MB); -60006/-30003 → 页数超限 (200 / 20 页).\n- -60018 → 当日配额已满; 429 → 限频, 稍后重试或降低并发.\n- 超时: 任务仍在服务端, 可稍后用 mineru_task (taskId + api) 继续收集结果, 无需重新提交.';
10
+ export const SKILL_CONTENT = '# MinerU 文档解析 (dsh-mineru)\n\n本技能授予你基于 MinerU 的多模态全格式文档解析能力. 所有解析结果以结构化 Markdown 落地为工作区文件 (Artifact), 同时工具结果内附有限长度的预览.\n\n## 可用工具\n\n- mineru_parse — 解析单个文档 (本地文件路径或 http(s) URL).\n- mineru_batch_parse — 批量解析 (仅精准解析 API, 需要 Token; 本地文件或 URL 列表).\n- mineru_task — 查询/收集已提交任务的结果 (超时后恢复用).\n\n若上述工具未出现在你的工具列表中, 先调用一次 mineru_activate 激活本插件 (该工具在激活后对本会话隐藏).\n\n## 两种 API 模式 (自动选择, 可显式覆盖)\n\n| 维度 | 精准解析 API (需 Token) | Agent 轻量解析 API (免 Token) |\n| --- | --- | --- |\n| 触发 | 已配置 MinerU Token (默认自动) | Token 留空 (默认自动) |\n| 模型 | pipeline / vlm (默认) / MinerU-HTML | 固定 pipeline 轻量模型 |\n| 限制 | <=200MB, 单次请求 <=200 页 (工作区 PDF 超出时自动分片) | <=10MB, <=20 页 (不自动分片) |\n| 批量 | 支持 (URL <=200 个/批, 本地上传 <=50 个/批) | 仅单文件 |\n| 输出 | Zip: full.md + JSON (可加 docx/html/latex) | 仅 Markdown |\n\nmode 参数可显式指定: mode="precision" 强制精准解析 (无 Token 会报错), mode="agent" 强制轻量解析, 缺省 auto 按 Token 是否配置自动选择.\n\n## 使用要点\n\n1. 来源: 本地文件用工作区路径; 远程文档用完整 http(s) URL (注意 MinerU 无法访问 github/aws 等被墙 URL).\n2. HTML 文件仅精准解析支持, 且自动强制 model_version=MinerU-HTML. Agent 模式不支持 html/doc/ppt/xls.\n3. 页码范围: 精准解析用 pageRanges (逗号分隔, 如 "2,4-6", 支持 "2--2" 倒数页码); Agent 用 pageRange (如 "1-10"). 工作区 PDF 本次要解析的页数超过单次 200 页上限时, 插件自动按页分片提交并合并结果, 不需要新参数.\n4. language 取值: ch (中英, 默认), en, japan, korean, chinese_cht, latin, arabic, cyrillic, east_slavic, devanagari, ch_server, ta, te, ka, el, th.\n5. extraFormats 仅精准解析有效: ["docx","html","latex"] 会随 Zip 一并导出.\n6. 长文档用精准解析: 工作区 PDF 超过单次 200 页上限会自动分片并合并, 一般不必手动分段; 也可以显式传 pageRanges 只解析一部分. 大批量文档用 mineru_batch_parse (批量不按页分片).\n6b. Web 界面可直接把文档/图片拖入聊天窗口: 插件会自动保存到工作区并把文件路径填入输入框 (不自动发送), 用户补充需求后自行发送; 你收到文件路径后按第 7 条调用 mineru_parse.\n7. 结果目录: <workspace>/.dsh-mineru/artifacts/<run>/. 精准解析为解包后的完整 Zip (full.md, *_content_list.json, layout.json, images/ 等), Agent 为 full.md. 自动分片时: 运行目录根部是 full.md (按片拼接, 每段前有一行分片注释) 与 content_list.json (合并, page_idx 已映射回原文档页码); layout.json 与 <uuid>_model.json 按页数组组织, 按片保留在 chunks/chunk-<n>/ 下; 图片并入根目录 images/. 工具结果的 chunkCount/chunks 字段列出每片的页码范围、batchId、状态与耗时. 请用 read 工具读取 full.md 全文; 工具结果里的 preview 字段是截断预览.\n8. 结果文件路径同时出现在 tool/result 中, Web 界面可直接预览/打开; URL 为签名链接, 带有效期.\n8b. 需要按页码核引 (学术引用, 逐页校对) 时传 anchor=true: 精准解析会在同目录额外产出 document.md, 每块前一行 <!-- pN bK --> 标明原文档页码 (1 基) 与页内块序 (1 基, 按 content_list.json 顺序, 页眉/页脚/页码占号故可能不连续). 该产物是纯增量, 不开时 full.md 等既有产物完全不变; Agent 轻量解析没有 content_list.json, 传了只会得到一条提示.\n\n## 官方限流 (插件已内置本地限速与 429 退避)\n\n- 提交: 50 个文件/分钟 (含单文件、批量上传、批量 URL), 5000 个文件/天/用户 (html 最多 100 个/天).\n- 查询: 1000 次/分钟.\n- 超出限制的请求会被系统拒绝 (HTTP 429).\n\n## 错误处理\n\n- A0202/A0211 → Token 错误/过期, 提示用户在设置中更新 Token.\n- -60005/-30001 → 文件超限 (200MB / 10MB); -60006/-30003 → 页数超限 (200 / 20 页). 仍看到 -60006 说明本地读不出该文件的页数 (非 PDF、加密或结构异常) 或 pageRanges 写法无法在本地分片, 按提示手动分段; Agent 免 Token 路径按 IP 限流, 不做自动分片, 请改用精准解析或自行分段.\n- -60018 → 当日配额已满; 429 → 限频, 稍后重试或降低并发.\n- 超时: 任务仍在服务端, 可稍后用 mineru_task (taskId + api) 继续收集结果, 无需重新提交.\n- 传了 anchor=true 但结果是 Agent 轻量解析 (无 content_list.json) 时: 只返回一条提示且不产出 document.md, 解析本身仍然成功.';