dsh-mineru 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +56 -0
- package/CONTRIBUTING.md +30 -0
- package/LICENSE +21 -0
- package/README.md +147 -0
- package/README.zh.md +147 -0
- package/RELEASE.md +87 -0
- package/cordis.patch.yml +8 -0
- package/lib/artifacts.js +307 -0
- package/lib/client.js +559 -0
- package/lib/config.js +174 -0
- package/lib/http.js +452 -0
- package/lib/index.js +135 -0
- package/lib/mineru-client.js +826 -0
- package/lib/skill.js +10 -0
- package/lib/tools.js +667 -0
- package/lib/types/client.d.ts +8 -0
- package/lib/types/index.d.ts +11 -0
- package/lib/zip.js +337 -0
- package/package.json +77 -0
package/lib/skill.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The bundled mineru-tools skill: what MinerU parsing is, how the two API
|
|
3
|
+
* modes behave, tool usage, limits, and the activation flow.
|
|
4
|
+
* @module dsh-mineru/skill
|
|
5
|
+
*/
|
|
6
|
+
export const SKILL_NAME = 'mineru-tools';
|
|
7
|
+
|
|
8
|
+
export const SKILL_DESCRIPTION = 'MinerU 多模态文档解析: PDF/Office/图片/HTML 转为结构化 Markdown. 涵盖精准解析 API 与 Agent 轻量解析 API 的调用、批量解析、结果文件与官方限制.';
|
|
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) 继续收集结果, 无需重新提交.';
|
package/lib/tools.js
ADDED
|
@@ -0,0 +1,667 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool definitions: mineru_activate (bootstrap), mineru_parse, mineru_batch_parse,
|
|
3
|
+
* mineru_task. The three parsing tools mount per agent after activation (or
|
|
4
|
+
* globally under exposeMode: always).
|
|
5
|
+
* @module dsh-mineru/tools
|
|
6
|
+
*/
|
|
7
|
+
import { basename, extname, join, resolve as pathResolve } from 'node:path';
|
|
8
|
+
import { rm } from 'node:fs/promises';
|
|
9
|
+
import { defineTool } from '@deepseek-ai/dsh-tools';
|
|
10
|
+
import { MineruError, resolveOptions, effectiveModelFor } from './mineru-client.js';
|
|
11
|
+
import { AGENT_UNSUPPORTED_EXTENSIONS, EXTRA_FORMAT_VALUES, LANGUAGE_VALUES, SUPPORTED_EXTENSIONS } from './config.js';
|
|
12
|
+
import { sanitizeFileName } from './artifacts.js';
|
|
13
|
+
import { SKILL_NAME } from './skill.js';
|
|
14
|
+
|
|
15
|
+
export const ACTIVATE_TOOL_NAME = 'mineru_activate';
|
|
16
|
+
export const TOOL_NAMES = Object.freeze(['mineru_parse', 'mineru_batch_parse', 'mineru_task']);
|
|
17
|
+
|
|
18
|
+
const MODE_ENUM = ['auto', 'precision', 'agent'];
|
|
19
|
+
const MODEL_ENUM = ['pipeline', 'vlm', 'MinerU-HTML'];
|
|
20
|
+
|
|
21
|
+
const isUrlSource = (s) => /^https?:\/\//i.test(String(s ?? ''));
|
|
22
|
+
|
|
23
|
+
function extOf(name) {
|
|
24
|
+
return extname(name).toLowerCase();
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @param {number} n @returns {string} */
|
|
28
|
+
function formatBytes(n) {
|
|
29
|
+
if (!Number.isFinite(n) || n <= 0) return '0 B';
|
|
30
|
+
const units = ['B', 'KB', 'MB', 'GB'];
|
|
31
|
+
let i = 0;
|
|
32
|
+
let v = n;
|
|
33
|
+
while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
|
|
34
|
+
return (i === 0 ? v : v.toFixed(1)) + ' ' + units[i];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Bound a markdown preview on UTF-8 boundaries. */
|
|
38
|
+
function truncateMarkdown(text, maxBytes) {
|
|
39
|
+
const buf = Buffer.from(text ?? '', 'utf8');
|
|
40
|
+
if (buf.length <= maxBytes) return { markdown: text ?? '', truncated: false, bytes: buf.length };
|
|
41
|
+
const cut = buf.subarray(0, maxBytes);
|
|
42
|
+
let end = cut.length;
|
|
43
|
+
while (end > 0 && (cut[end - 1] & 0xc0) === 0x80) end--;
|
|
44
|
+
return {
|
|
45
|
+
markdown: cut.subarray(0, end).toString('utf8') + '\n...(预览已截断, 完整内容见 Artifact full.md)',
|
|
46
|
+
truncated: true,
|
|
47
|
+
bytes: buf.length,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Shared option parameters for the three parsing tools. */
|
|
52
|
+
function parseOptionParams() {
|
|
53
|
+
return {
|
|
54
|
+
mode: { type: 'string', enum: MODE_ENUM, description: 'API 模式: auto 按 Token 是否配置自动选择, precision 强制精准解析(需 Token), agent 强制 Agent 轻量解析.' },
|
|
55
|
+
modelVersion: { type: 'string', enum: MODEL_ENUM, description: '精准解析模型版本: pipeline / vlm(默认, 推荐) / MinerU-HTML. HTML 源自动强制 MinerU-HTML.' },
|
|
56
|
+
language: { type: 'string', enum: LANGUAGE_VALUES, description: '文档语言包, 默认 ch (中英). 常用: en, japan, korean, latin, arabic, cyrillic, east_slavic, devanagari.' },
|
|
57
|
+
enableTable: { type: 'boolean', description: '是否开启表格识别, 默认 true.' },
|
|
58
|
+
enableFormula: { type: 'boolean', description: '是否开启公式识别, 默认 true.' },
|
|
59
|
+
isOcr: { type: 'boolean', description: '是否强制 OCR, 默认 false.' },
|
|
60
|
+
pageRanges: { type: 'string', description: '精准解析页码范围, 逗号分隔: "2,4-6", 支持倒数页码 "2--2".' },
|
|
61
|
+
pageRange: { type: 'string', description: 'Agent 轻量解析页码范围, 仅支持 from-to 或单页: "1-10".' },
|
|
62
|
+
extraFormats: { type: 'array', items: { type: 'string', enum: EXTRA_FORMAT_VALUES }, description: '精准解析额外导出格式: docx / html / latex.' },
|
|
63
|
+
dataId: { type: 'string', description: '解析对象对应的业务数据 ID (可选, <=128 字符).' },
|
|
64
|
+
timeoutMs: { type: 'number', description: '整个操作(含轮询等待)的超时毫秒数, 默认取插件配置.' },
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param {object} state plugin state (tools are built per plugin instance)
|
|
70
|
+
* @returns {(args: object, exec: import('@deepseek-ai/dsh-tools').ToolRunContext) => Promise<object>}
|
|
71
|
+
*/
|
|
72
|
+
function makeActivateExecute(state) {
|
|
73
|
+
return async function activateExecute(_args, exec) {
|
|
74
|
+
const agent = exec.agent;
|
|
75
|
+
if (!agent || !agent.ctx) {
|
|
76
|
+
throw new Error('mineru_activate 需要在 agent 会话中调用 (exec.agent 不可用)');
|
|
77
|
+
}
|
|
78
|
+
const facts = await state.collectFacts();
|
|
79
|
+
const already = state.activatedAgents.has(agent);
|
|
80
|
+
if (!already) {
|
|
81
|
+
for (const def of state.agentToolDefs) {
|
|
82
|
+
agent.ctx.tools.register(def);
|
|
83
|
+
}
|
|
84
|
+
agent.ctx.tools.restrict({ deny: [ACTIVATE_TOOL_NAME] });
|
|
85
|
+
state.activatedAgents.add(agent);
|
|
86
|
+
}
|
|
87
|
+
return {
|
|
88
|
+
ok: true,
|
|
89
|
+
active: true,
|
|
90
|
+
already,
|
|
91
|
+
tools: [...TOOL_NAMES],
|
|
92
|
+
skill: SKILL_NAME,
|
|
93
|
+
mode: facts.mode,
|
|
94
|
+
api: facts.api,
|
|
95
|
+
tokenConfigured: facts.tokenConfigured,
|
|
96
|
+
modelVersion: facts.modelVersion,
|
|
97
|
+
limits: {
|
|
98
|
+
precision: '<=200MB / <=200 页 / 支持批量',
|
|
99
|
+
agent: '<=10MB / <=20 页 / 仅单文件 Markdown',
|
|
100
|
+
},
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Build the activation bootstrap tool (registered globally in progressive mode). */
|
|
106
|
+
export function buildActivateTool(state) {
|
|
107
|
+
return defineTool({
|
|
108
|
+
name: ACTIVATE_TOOL_NAME,
|
|
109
|
+
description: '激活 MinerU 多模态文档解析工具集 (mineru_parse / mineru_batch_parse / mineru_task). 本插件默认只暴露此引导工具以节省上下文; 调用一次即可解锁其余工具, 激活后此工具对本会话隐藏. 解析能力: PDF/Word/PPT/Excel/HTML/图片 -> 结构化 Markdown (精准解析 API 需 Token, Agent 轻量 API 免 Token).',
|
|
110
|
+
parameters: {},
|
|
111
|
+
output: {
|
|
112
|
+
schema: {
|
|
113
|
+
type: 'object',
|
|
114
|
+
additionalProperties: false,
|
|
115
|
+
properties: {
|
|
116
|
+
ok: { type: 'boolean' },
|
|
117
|
+
active: { type: 'boolean' },
|
|
118
|
+
already: { type: 'boolean' },
|
|
119
|
+
tools: { type: 'array', items: { type: 'string' } },
|
|
120
|
+
skill: { type: 'string' },
|
|
121
|
+
mode: { type: 'string' },
|
|
122
|
+
api: { type: 'string' },
|
|
123
|
+
tokenConfigured: { type: 'boolean' },
|
|
124
|
+
modelVersion: { type: 'string' },
|
|
125
|
+
limits: { type: 'object', additionalProperties: false, properties: { precision: { type: 'string' }, agent: { type: 'string' } } },
|
|
126
|
+
},
|
|
127
|
+
},
|
|
128
|
+
render(_args, value) {
|
|
129
|
+
return [{
|
|
130
|
+
type: 'text',
|
|
131
|
+
text: [
|
|
132
|
+
'MinerU 解析已激活.',
|
|
133
|
+
'- 模式: ' + value.mode + ' -> ' + value.api + ' (' + (value.tokenConfigured ? 'Token 已配置' : '未配置 Token, 使用 Agent 轻量解析') + ')',
|
|
134
|
+
'- 已解锁工具: ' + value.tools.join(', '),
|
|
135
|
+
'- 限制: 精准解析 ' + value.limits.precision + '; Agent 轻量 ' + value.limits.agent,
|
|
136
|
+
'使用 skill 工具加载 ' + value.skill + ' 可查看完整用法.',
|
|
137
|
+
].join('\n'),
|
|
138
|
+
}];
|
|
139
|
+
},
|
|
140
|
+
},
|
|
141
|
+
timeoutMs: 30000,
|
|
142
|
+
execute: makeActivateExecute(state),
|
|
143
|
+
});
|
|
144
|
+
}/**
|
|
145
|
+
* Orchestrate one single-document parse: resolve mode/api, validate source,
|
|
146
|
+
* submit (URL or signature upload), wait, download, extract into a fresh run
|
|
147
|
+
* dir, and build the canonical result value.
|
|
148
|
+
* @param {object} input { source, args, cfg, exec, state }
|
|
149
|
+
*/
|
|
150
|
+
async function runSingleParse({ source, args, cfg, exec, state }) {
|
|
151
|
+
const cwd = exec.agent?.session?.header?.cwd ?? process.cwd();
|
|
152
|
+
const client = await state.clientFor(cfg);
|
|
153
|
+
const { api, effectiveMode } = client.resolveApi(args.mode, cfg.mode);
|
|
154
|
+
const opts = resolveOptions(cfg, args);
|
|
155
|
+
|
|
156
|
+
let filePath = null;
|
|
157
|
+
let fileName;
|
|
158
|
+
let displayName;
|
|
159
|
+
let fileSize = null;
|
|
160
|
+
let ext = '';
|
|
161
|
+
const urlSource = isUrlSource(source);
|
|
162
|
+
if (urlSource) {
|
|
163
|
+
let parsed;
|
|
164
|
+
try { parsed = new URL(source); } catch {
|
|
165
|
+
throw new MineruError('无效的 URL: ' + source, 'MINERU_BAD_ARGS');
|
|
166
|
+
}
|
|
167
|
+
displayName = basename(parsed.pathname) || 'document';
|
|
168
|
+
ext = extOf(displayName);
|
|
169
|
+
// An extension the server may not recognize is omitted from file_name so
|
|
170
|
+
// MinerU parses it from the URL itself; displayName stays a real string.
|
|
171
|
+
fileName = SUPPORTED_EXTENSIONS.includes(ext) ? displayName : undefined;
|
|
172
|
+
} else {
|
|
173
|
+
filePath = pathResolve(cwd, source);
|
|
174
|
+
const checked = await client.checkLocalFile(filePath, api, cfg.maxFileBytes);
|
|
175
|
+
fileName = basename(filePath);
|
|
176
|
+
displayName = fileName;
|
|
177
|
+
fileSize = checked.size;
|
|
178
|
+
ext = checked.ext;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
let warning;
|
|
182
|
+
if (api === 'precision') {
|
|
183
|
+
const forced = effectiveModelFor(ext, opts.modelVersion);
|
|
184
|
+
opts.modelVersion = forced.modelVersion;
|
|
185
|
+
if (forced.forced) warning = 'HTML 源已自动使用 MinerU-HTML 模型 (忽略其他 modelVersion)';
|
|
186
|
+
} else if (ext && AGENT_UNSUPPORTED_EXTENSIONS.includes(ext)) {
|
|
187
|
+
throw new MineruError(
|
|
188
|
+
'Agent 轻量解析 API 不支持 ' + ext + ' 文件: 请改用精准解析 API (mode=precision 并配置 Token).',
|
|
189
|
+
'MINERU_UNSUPPORTED_TYPE',
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const manager = await state.artifacts.managerFor(cwd);
|
|
194
|
+
const runBase = sanitizeFileName(args.output ?? (fileName ?? 'parse'));
|
|
195
|
+
const { dir, relDir } = await manager.createRun(runBase);
|
|
196
|
+
const started = Date.now();
|
|
197
|
+
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 });
|
|
202
|
+
const durationMs = Date.now() - started;
|
|
203
|
+
const metadata = {
|
|
204
|
+
plugin: 'dsh-mineru',
|
|
205
|
+
createdAt: new Date().toISOString(),
|
|
206
|
+
source: urlSource ? source : filePath,
|
|
207
|
+
sourceName: displayName,
|
|
208
|
+
api, mode: effectiveMode, modelVersion: opts.modelVersion,
|
|
209
|
+
taskId: outcome.taskId ?? null,
|
|
210
|
+
batchId: outcome.batchId ?? null,
|
|
211
|
+
state: 'done',
|
|
212
|
+
durationMs,
|
|
213
|
+
markdownBytes: collected.markdownBytes ?? null,
|
|
214
|
+
warning: warning ?? null,
|
|
215
|
+
};
|
|
216
|
+
await manager.writeFile(dir, 'run.json', JSON.stringify(metadata, null, 2));
|
|
217
|
+
const preview = truncateMarkdown(collected.markdownText, cfg.inlineMarkdownBytes);
|
|
218
|
+
const artifacts = await manager.describeRun(relDir, state.urlBuilder ? { capabilityFor: (rel) => state.urlBuilder(cwd, rel) } : undefined);
|
|
219
|
+
return {
|
|
220
|
+
ok: true,
|
|
221
|
+
api, mode: effectiveMode, modelVersion: opts.modelVersion,
|
|
222
|
+
taskId: outcome.taskId ?? null,
|
|
223
|
+
batchId: outcome.batchId ?? null,
|
|
224
|
+
state: 'done',
|
|
225
|
+
durationMs,
|
|
226
|
+
sourceName: displayName,
|
|
227
|
+
sourceKind: urlSource ? 'url' : 'file',
|
|
228
|
+
sourceBytes: fileSize,
|
|
229
|
+
runDir: dir,
|
|
230
|
+
warning: warning ?? null,
|
|
231
|
+
markdownBytes: collected.markdownBytes ?? null,
|
|
232
|
+
preview,
|
|
233
|
+
artifacts,
|
|
234
|
+
};
|
|
235
|
+
} catch (err) {
|
|
236
|
+
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
237
|
+
throw err;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const ARTIFACT_ITEM_SCHEMA = { type: 'object', additionalProperties: false, properties: {
|
|
242
|
+
name: { type: 'string' }, path: { type: 'string' }, rel: { type: 'string' },
|
|
243
|
+
kind: { type: 'string' }, mime: { type: 'string' }, bytes: { type: 'number' }, url: { type: 'string' },
|
|
244
|
+
} };
|
|
245
|
+
|
|
246
|
+
const PARSE_RESULT_SCHEMA = {
|
|
247
|
+
type: 'object',
|
|
248
|
+
additionalProperties: false,
|
|
249
|
+
properties: {
|
|
250
|
+
ok: { type: 'boolean' },
|
|
251
|
+
api: { type: 'string' },
|
|
252
|
+
mode: { type: 'string' },
|
|
253
|
+
modelVersion: { type: 'string' },
|
|
254
|
+
taskId: { type: 'json' },
|
|
255
|
+
batchId: { type: 'json' },
|
|
256
|
+
state: { type: 'string' },
|
|
257
|
+
durationMs: { type: 'number' },
|
|
258
|
+
sourceName: { type: 'string' },
|
|
259
|
+
sourceKind: { type: 'string' },
|
|
260
|
+
sourceBytes: { type: 'json' },
|
|
261
|
+
runDir: { type: 'string' },
|
|
262
|
+
warning: { type: 'json' },
|
|
263
|
+
markdownBytes: { type: 'json' },
|
|
264
|
+
preview: { type: 'object', additionalProperties: false, properties: { markdown: { type: 'string' }, truncated: { type: 'boolean' }, bytes: { type: 'number' } } },
|
|
265
|
+
artifacts: { type: 'array', items: ARTIFACT_ITEM_SCHEMA },
|
|
266
|
+
},
|
|
267
|
+
};
|
|
268
|
+
|
|
269
|
+
function renderParseContent(value) {
|
|
270
|
+
const lines = [
|
|
271
|
+
'MinerU 解析完成 (' + value.api + ' API, ' + value.modelVersion + ', 耗时 ' + (value.durationMs / 1000).toFixed(1) + 's)',
|
|
272
|
+
'- 任务: ' + value.taskId,
|
|
273
|
+
'- 结果目录: ' + value.runDir,
|
|
274
|
+
];
|
|
275
|
+
if (value.warning) lines.push('- 注意: ' + value.warning);
|
|
276
|
+
for (const a of value.artifacts ?? []) {
|
|
277
|
+
lines.push('- Artifact: ' + a.name + ' (' + a.kind + ', ' + formatBytes(a.bytes) + ')' + (a.url ? ' 预览: ' + a.url : ''));
|
|
278
|
+
}
|
|
279
|
+
lines.push('完整 Markdown 位于 Artifact full.md, 请用 read 工具读取; 下方为预览:');
|
|
280
|
+
lines.push('');
|
|
281
|
+
lines.push(value.preview?.markdown ?? '');
|
|
282
|
+
return [{ type: 'text', text: lines.join('\n') }];
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Build the mineru_parse tool definition. */
|
|
286
|
+
export function buildParseTool(state) {
|
|
287
|
+
return defineTool({
|
|
288
|
+
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 列表返回.',
|
|
290
|
+
parameters: {
|
|
291
|
+
source: { type: 'string', required: true, description: '工作区文件路径或完整 http(s) URL.' },
|
|
292
|
+
...parseOptionParams(),
|
|
293
|
+
output: { type: 'string', description: '结果目录基名 (默认取源文件名).' },
|
|
294
|
+
},
|
|
295
|
+
output: {
|
|
296
|
+
schema: PARSE_RESULT_SCHEMA,
|
|
297
|
+
render: (_args, value) => renderParseContent(value),
|
|
298
|
+
presentationMeta: (_args, value) => value,
|
|
299
|
+
},
|
|
300
|
+
presentCall(args) {
|
|
301
|
+
const source = String(args.source ?? '');
|
|
302
|
+
const name = basename(source) || source;
|
|
303
|
+
return {
|
|
304
|
+
card: 'generic',
|
|
305
|
+
title: 'MinerU 解析 ' + name,
|
|
306
|
+
kind: 'fetch',
|
|
307
|
+
rawInput: {
|
|
308
|
+
source,
|
|
309
|
+
mode: args.mode ?? 'auto',
|
|
310
|
+
...(args.modelVersion !== undefined ? { modelVersion: args.modelVersion } : {}),
|
|
311
|
+
...(args.language !== undefined ? { language: args.language } : {}),
|
|
312
|
+
},
|
|
313
|
+
locations: isUrlSource(source) ? undefined : [{ path: source }],
|
|
314
|
+
};
|
|
315
|
+
},
|
|
316
|
+
presentResult(args, result) {
|
|
317
|
+
const meta = result.meta;
|
|
318
|
+
if (result.isError) return { card: 'generic', title: 'MinerU 解析失败: ' + (basename(String(args.source ?? '')) || args.source) };
|
|
319
|
+
if (!meta || typeof meta !== 'object' || !meta.ok) return undefined;
|
|
320
|
+
return {
|
|
321
|
+
card: 'generic',
|
|
322
|
+
title: 'MinerU 解析完成: ' + meta.sourceName,
|
|
323
|
+
content: renderParseContent(meta),
|
|
324
|
+
};
|
|
325
|
+
},
|
|
326
|
+
isConcurrencySafe: () => true,
|
|
327
|
+
timeoutMs: 600000,
|
|
328
|
+
async execute(args, exec) {
|
|
329
|
+
const cfg = state.getCfg();
|
|
330
|
+
return runSingleParse({ source: String(args.source ?? '').trim(), args, cfg, exec, state });
|
|
331
|
+
},
|
|
332
|
+
});
|
|
333
|
+
}/**
|
|
334
|
+
* Orchestrate a precision-API batch parse. sources may mix local paths and
|
|
335
|
+
* URLs; each group submits as its own batch (local <=50, urls <=200).
|
|
336
|
+
*/
|
|
337
|
+
async function runBatchParse({ sources, args, cfg, exec, state }) {
|
|
338
|
+
const cwd = exec.agent?.session?.header?.cwd ?? process.cwd();
|
|
339
|
+
const client = await state.clientFor(cfg);
|
|
340
|
+
const { api } = client.resolveApi(args.mode ?? 'precision', cfg.mode);
|
|
341
|
+
if (api !== 'precision') {
|
|
342
|
+
throw new MineruError('mineru_batch_parse 仅精准解析 API 支持: 请配置 MinerU Token 后重试.', 'MINERU_TOKEN_REQUIRED');
|
|
343
|
+
}
|
|
344
|
+
const opts = resolveOptions(cfg, args);
|
|
345
|
+
const manager = await state.artifacts.managerFor(cwd);
|
|
346
|
+
const runBase = sanitizeFileName(args.outputPrefix ?? 'batch');
|
|
347
|
+
const { dir, relDir } = await manager.createRun(runBase);
|
|
348
|
+
const started = Date.now();
|
|
349
|
+
const batchIds = [];
|
|
350
|
+
const results = [];
|
|
351
|
+
const flatArtifacts = [];
|
|
352
|
+
let doneCount = 0;
|
|
353
|
+
let failedCount = 0;
|
|
354
|
+
const files = [];
|
|
355
|
+
const urls = [];
|
|
356
|
+
for (const raw of sources) {
|
|
357
|
+
const s = String(raw ?? '').trim();
|
|
358
|
+
if (!s) continue;
|
|
359
|
+
if (isUrlSource(s)) urls.push({ url: s });
|
|
360
|
+
else files.push({ filePath: pathResolve(cwd, s) });
|
|
361
|
+
}
|
|
362
|
+
if (files.length === 0 && urls.length === 0) {
|
|
363
|
+
throw new MineruError('sources 为空: 至少提供一个文件路径或 URL.', 'MINERU_BAD_ARGS');
|
|
364
|
+
}
|
|
365
|
+
const MAX_URLS_PER_BATCH = 200;
|
|
366
|
+
const MAX_FILES_PER_BATCH = 50;
|
|
367
|
+
const MAX_TOTAL = 1000;
|
|
368
|
+
if (urls.length + files.length > MAX_TOTAL) {
|
|
369
|
+
throw new MineruError('sources 超过单次调用上限 ' + MAX_TOTAL + ' 个: 请拆分后多次调用 mineru_batch_parse.', 'MINERU_BATCH_TOO_LARGE');
|
|
370
|
+
}
|
|
371
|
+
try {
|
|
372
|
+
const collectOne = async (item) => {
|
|
373
|
+
if (item.state === 'done' && item.fullZipUrl) {
|
|
374
|
+
const safeName = sanitizeFileName(item.name ?? ('item-' + results.length));
|
|
375
|
+
const itemDir = joinSafe(dir, safeName);
|
|
376
|
+
const collected = await client.collectPrecisionZip({ zipUrl: item.fullZipUrl, destDir: itemDir, opts, signal: exec.signal });
|
|
377
|
+
doneCount += 1;
|
|
378
|
+
const relItemDir = relDir.replace(/\\/g, '/') + '/' + safeName;
|
|
379
|
+
const itemArtifacts = await manager.describeRun(relItemDir, state.urlBuilder ? { capabilityFor: (rel) => state.urlBuilder(cwd, rel) } : undefined);
|
|
380
|
+
flatArtifacts.push(...itemArtifacts);
|
|
381
|
+
results.push({ name: item.name, state: 'done', dir: itemDir, markdownBytes: collected.markdownBytes ?? null, artifacts: itemArtifacts });
|
|
382
|
+
} else {
|
|
383
|
+
failedCount += 1;
|
|
384
|
+
results.push({ name: item.name, state: item.state ?? 'failed', errMsg: item.errMsg ?? null });
|
|
385
|
+
}
|
|
386
|
+
};
|
|
387
|
+
// URLs auto-chunked into batches of <= 200.
|
|
388
|
+
for (let i = 0; i < urls.length; i += MAX_URLS_PER_BATCH) {
|
|
389
|
+
const r = await client.submitAndWaitBatchUrls({ items: urls.slice(i, i + MAX_URLS_PER_BATCH), opts, signal: exec.signal });
|
|
390
|
+
batchIds.push(r.batchId);
|
|
391
|
+
for (const item of r.results) await collectOne(item);
|
|
392
|
+
}
|
|
393
|
+
// Local files auto-chunked into batches of <= 50 upload links.
|
|
394
|
+
for (let i = 0; i < files.length; i += MAX_FILES_PER_BATCH) {
|
|
395
|
+
const items = [];
|
|
396
|
+
for (const f of files.slice(i, i + MAX_FILES_PER_BATCH)) {
|
|
397
|
+
const checked = await client.checkLocalFile(f.filePath, 'precision', cfg.maxFileBytes);
|
|
398
|
+
items.push({ filePath: f.filePath, fileName: basename(f.filePath), dataId: undefined, size: checked.size });
|
|
399
|
+
}
|
|
400
|
+
const r = await client.submitAndWaitBatchFiles({ items, opts, signal: exec.signal });
|
|
401
|
+
batchIds.push(r.batchId);
|
|
402
|
+
for (const item of r.results) await collectOne(item);
|
|
403
|
+
}
|
|
404
|
+
const metadata = {
|
|
405
|
+
plugin: 'dsh-mineru',
|
|
406
|
+
createdAt: new Date().toISOString(),
|
|
407
|
+
api: 'precision',
|
|
408
|
+
modelVersion: opts.modelVersion,
|
|
409
|
+
batchIds,
|
|
410
|
+
total: results.length,
|
|
411
|
+
done: doneCount,
|
|
412
|
+
failed: failedCount,
|
|
413
|
+
durationMs: Date.now() - started,
|
|
414
|
+
};
|
|
415
|
+
await manager.writeFile(dir, 'run.json', JSON.stringify(metadata, null, 2));
|
|
416
|
+
const artifacts = await manager.describeRun(relDir, state.urlBuilder ? { capabilityFor: (rel) => state.urlBuilder(cwd, rel) } : undefined);
|
|
417
|
+
return {
|
|
418
|
+
ok: true,
|
|
419
|
+
api: 'precision',
|
|
420
|
+
modelVersion: opts.modelVersion,
|
|
421
|
+
batchIds,
|
|
422
|
+
state: 'done',
|
|
423
|
+
durationMs: Date.now() - started,
|
|
424
|
+
total: results.length,
|
|
425
|
+
done: doneCount,
|
|
426
|
+
failed: failedCount,
|
|
427
|
+
runDir: dir,
|
|
428
|
+
results,
|
|
429
|
+
artifacts,
|
|
430
|
+
};
|
|
431
|
+
} catch (err) {
|
|
432
|
+
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
433
|
+
throw err;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
/** join with a sanitized single segment. */
|
|
438
|
+
function joinSafe(dir, name) {
|
|
439
|
+
return join(dir, sanitizeFileName(name));
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const BATCH_RESULT_SCHEMA = {
|
|
443
|
+
type: 'object',
|
|
444
|
+
additionalProperties: false,
|
|
445
|
+
properties: {
|
|
446
|
+
ok: { type: 'boolean' },
|
|
447
|
+
api: { type: 'string' },
|
|
448
|
+
modelVersion: { type: 'string' },
|
|
449
|
+
batchIds: { type: 'array', items: { type: 'string' } },
|
|
450
|
+
state: { type: 'string' },
|
|
451
|
+
durationMs: { type: 'number' },
|
|
452
|
+
total: { type: 'number' },
|
|
453
|
+
done: { type: 'number' },
|
|
454
|
+
failed: { type: 'number' },
|
|
455
|
+
runDir: { type: 'string' },
|
|
456
|
+
results: { type: 'array', items: { type: 'object', additionalProperties: false, properties: {
|
|
457
|
+
name: { type: 'string' }, state: { type: 'string' }, dir: { type: 'json' },
|
|
458
|
+
errMsg: { type: 'json' }, markdownBytes: { type: 'json' },
|
|
459
|
+
artifacts: { type: 'array', items: ARTIFACT_ITEM_SCHEMA },
|
|
460
|
+
} } },
|
|
461
|
+
artifacts: { type: 'array', items: ARTIFACT_ITEM_SCHEMA },
|
|
462
|
+
},
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
function renderBatchContent(value) {
|
|
466
|
+
const lines = [
|
|
467
|
+
'MinerU 批量解析完成 (精准解析 API, ' + value.modelVersion + ', 耗时 ' + (value.durationMs / 1000).toFixed(1) + 's)',
|
|
468
|
+
'- 成功 ' + value.done + ' / 共 ' + value.total + (value.failed > 0 ? ', 失败 ' + value.failed : ''),
|
|
469
|
+
'- 结果目录: ' + value.runDir,
|
|
470
|
+
];
|
|
471
|
+
for (const r of value.results ?? []) {
|
|
472
|
+
if (r.state === 'done') {
|
|
473
|
+
lines.push('- [done] ' + r.name + ' -> ' + (r.dir ?? '') + '/full.md');
|
|
474
|
+
} else {
|
|
475
|
+
lines.push('- [' + (r.state ?? 'failed') + '] ' + r.name + ': ' + (r.errMsg ?? ''));
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
lines.push('请用 read 工具读取各 full.md 全文.');
|
|
479
|
+
return [{ type: 'text', text: lines.join('\n') }];
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** Build the mineru_batch_parse tool definition. */
|
|
483
|
+
export function buildBatchTool(state) {
|
|
484
|
+
return defineTool({
|
|
485
|
+
name: 'mineru_batch_parse',
|
|
486
|
+
description: '用 MinerU 精准解析 API 批量解析文档 (需要 Token): sources 为工作区文件路径与 http(s) URL 的混合列表. 自动分批提交 (本地文件每批 <=50 个, URL 每批 <=200 个, 单次调用总共 <=1000 个). 每个文档的结果解包到独立子目录 (<run>/<文件名>/full.md). 解析成功与失败逐项列出.',
|
|
487
|
+
parameters: {
|
|
488
|
+
sources: { type: 'array', items: { type: 'string' }, required: true, description: '文件路径或 http(s) URL 列表 (本地<=50, URL<=200).' },
|
|
489
|
+
...parseOptionParams(),
|
|
490
|
+
outputPrefix: { type: 'string', description: '结果目录基名 (默认 batch).' },
|
|
491
|
+
dataIdPrefix: { type: 'string', description: '业务数据 ID 前缀, 每项自动追加序号 (可选).' },
|
|
492
|
+
},
|
|
493
|
+
output: {
|
|
494
|
+
schema: BATCH_RESULT_SCHEMA,
|
|
495
|
+
render: (_args, value) => renderBatchContent(value),
|
|
496
|
+
presentationMeta: (_args, value) => value,
|
|
497
|
+
},
|
|
498
|
+
presentCall(args) {
|
|
499
|
+
const sources = Array.isArray(args.sources) ? args.sources.map(String) : [];
|
|
500
|
+
return {
|
|
501
|
+
card: 'generic',
|
|
502
|
+
title: 'MinerU 批量解析 (' + sources.length + ' 个文档)',
|
|
503
|
+
kind: 'fetch',
|
|
504
|
+
rawInput: {
|
|
505
|
+
count: sources.length,
|
|
506
|
+
...(args.modelVersion !== undefined ? { modelVersion: args.modelVersion } : {}),
|
|
507
|
+
...(args.language !== undefined ? { language: args.language } : {}),
|
|
508
|
+
},
|
|
509
|
+
};
|
|
510
|
+
},
|
|
511
|
+
presentResult(args, result) {
|
|
512
|
+
if (result.isError) return { card: 'generic', title: 'MinerU 批量解析失败' };
|
|
513
|
+
const meta = result.meta;
|
|
514
|
+
if (!meta || typeof meta !== 'object' || !meta.ok) return undefined;
|
|
515
|
+
return { card: 'generic', title: 'MinerU 批量解析完成 (' + meta.done + '/' + meta.total + ')', content: renderBatchContent(meta) };
|
|
516
|
+
},
|
|
517
|
+
isConcurrencySafe: () => true,
|
|
518
|
+
timeoutMs: 600000,
|
|
519
|
+
async execute(args, exec) {
|
|
520
|
+
const cfg = state.getCfg();
|
|
521
|
+
return runBatchParse({ sources: Array.isArray(args.sources) ? args.sources : [], args, cfg, exec, state });
|
|
522
|
+
},
|
|
523
|
+
});
|
|
524
|
+
}const TASK_RESULT_SCHEMA = {
|
|
525
|
+
type: 'object',
|
|
526
|
+
additionalProperties: false,
|
|
527
|
+
properties: {
|
|
528
|
+
ok: { type: 'boolean' },
|
|
529
|
+
api: { type: 'string' },
|
|
530
|
+
taskId: { type: 'string' },
|
|
531
|
+
state: { type: 'string' },
|
|
532
|
+
durationMs: { type: 'number' },
|
|
533
|
+
waitUsed: { type: 'boolean' },
|
|
534
|
+
collectible: { type: 'boolean' },
|
|
535
|
+
zipUrl: { type: 'json' },
|
|
536
|
+
markdownUrl: { type: 'json' },
|
|
537
|
+
errMsg: { type: 'json' },
|
|
538
|
+
progress: { type: 'json' },
|
|
539
|
+
runDir: { type: 'json' },
|
|
540
|
+
preview: { type: 'json' },
|
|
541
|
+
artifacts: { type: 'array', items: ARTIFACT_ITEM_SCHEMA },
|
|
542
|
+
},
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
function renderTaskContent(value) {
|
|
546
|
+
const lines = [
|
|
547
|
+
'MinerU 任务 ' + value.taskId + ' (' + value.api + ' API): ' + value.state,
|
|
548
|
+
];
|
|
549
|
+
if (value.progress?.total_pages) {
|
|
550
|
+
lines.push('- 进度: ' + (value.progress.extracted_pages ?? 0) + '/' + value.progress.total_pages + ' 页');
|
|
551
|
+
}
|
|
552
|
+
if (value.zipUrl) lines.push('- 结果包: ' + value.zipUrl);
|
|
553
|
+
if (value.markdownUrl) lines.push('- Markdown: ' + value.markdownUrl);
|
|
554
|
+
if (value.runDir) lines.push('- 已收集到: ' + value.runDir);
|
|
555
|
+
if (value.preview?.markdown) { lines.push(''); lines.push(value.preview.markdown); }
|
|
556
|
+
return [{ type: 'text', text: lines.join('\n') }];
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/** Build the mineru_task tool definition. */
|
|
560
|
+
export function buildTaskTool(state) {
|
|
561
|
+
return defineTool({
|
|
562
|
+
name: 'mineru_task',
|
|
563
|
+
description: '查询 (并可选收集) 一个已提交的 MinerU 任务: 传入 submit 时返回的 taskId 与 api (precision=精准解析 / agent=Agent轻量解析). wait=true 时轮询直到 done/failed/超时, 默认只查询一次; collect=true 且任务已完成时, 下载结果并落地为 Artifact (用于超时后恢复收集).',
|
|
564
|
+
parameters: {
|
|
565
|
+
taskId: { type: 'string', required: true, description: '提交任务时返回的 task_id.' },
|
|
566
|
+
api: { type: 'string', enum: ['precision', 'agent'], required: true, description: '任务所属 API: precision 或 agent.' },
|
|
567
|
+
wait: { type: 'boolean', description: '是否轮询等待任务完成 (默认 false, 只查询一次).' },
|
|
568
|
+
collect: { type: 'boolean', description: '任务完成时是否下载结果落地为 Artifact (默认 true).' },
|
|
569
|
+
output: { type: 'string', description: '收集结果目录基名 (默认 task).' },
|
|
570
|
+
timeoutMs: { type: 'number', description: 'wait 模式下的超时毫秒数.' },
|
|
571
|
+
},
|
|
572
|
+
output: {
|
|
573
|
+
schema: TASK_RESULT_SCHEMA,
|
|
574
|
+
render: (_args, value) => renderTaskContent(value),
|
|
575
|
+
presentationMeta: (_args, value) => value,
|
|
576
|
+
},
|
|
577
|
+
presentCall(args) {
|
|
578
|
+
return {
|
|
579
|
+
card: 'generic',
|
|
580
|
+
title: 'MinerU 任务查询 ' + String(args.taskId ?? '').slice(0, 24),
|
|
581
|
+
kind: 'fetch',
|
|
582
|
+
rawInput: { taskId: args.taskId, api: args.api, wait: Boolean(args.wait), collect: Boolean(args.collect) },
|
|
583
|
+
};
|
|
584
|
+
},
|
|
585
|
+
presentResult(args, result) {
|
|
586
|
+
if (result.isError) return { card: 'generic', title: 'MinerU 任务查询失败' };
|
|
587
|
+
const meta = result.meta;
|
|
588
|
+
if (!meta || typeof meta !== 'object') return undefined;
|
|
589
|
+
return { card: 'generic', title: 'MinerU 任务 ' + meta.state + ': ' + String(args.taskId ?? '').slice(0, 24), content: renderTaskContent(meta) };
|
|
590
|
+
},
|
|
591
|
+
isConcurrencySafe: () => true,
|
|
592
|
+
timeoutMs: 600000,
|
|
593
|
+
async execute(args, exec) {
|
|
594
|
+
const cfg = state.getCfg();
|
|
595
|
+
const client = await state.clientFor(cfg);
|
|
596
|
+
const api = String(args.api ?? 'precision');
|
|
597
|
+
if (api !== 'precision' && api !== 'agent') throw new MineruError('api 必须是 precision 或 agent.', 'MINERU_BAD_ARGS');
|
|
598
|
+
if (api === 'precision' && !client.precisionEnabled()) {
|
|
599
|
+
throw new MineruError('查询精准解析任务需要 MinerU Token.', 'MINERU_TOKEN_REQUIRED');
|
|
600
|
+
}
|
|
601
|
+
const started = Date.now();
|
|
602
|
+
const collect = args.collect !== false;
|
|
603
|
+
const wait = args.wait === true;
|
|
604
|
+
let outcome;
|
|
605
|
+
if (wait) {
|
|
606
|
+
const opts = resolveOptions(cfg, { ...args, timeoutMs: args.timeoutMs });
|
|
607
|
+
outcome = await client.waitTask({ taskId: String(args.taskId), api, opts, signal: exec.signal });
|
|
608
|
+
} else {
|
|
609
|
+
const status = await client.queryTask({ taskId: String(args.taskId), api, signal: exec.signal });
|
|
610
|
+
outcome = {
|
|
611
|
+
api, taskId: status.taskId, state: status.state,
|
|
612
|
+
fullZipUrl: status.fullZipUrl, markdownUrl: status.markdownUrl,
|
|
613
|
+
errMsg: status.errMsg, progress: status.progress,
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
const base = {
|
|
617
|
+
ok: true,
|
|
618
|
+
api,
|
|
619
|
+
taskId: String(args.taskId),
|
|
620
|
+
state: outcome.state,
|
|
621
|
+
durationMs: Date.now() - started,
|
|
622
|
+
waitUsed: wait,
|
|
623
|
+
collectible: outcome.state === 'done',
|
|
624
|
+
zipUrl: outcome.fullZipUrl ?? null,
|
|
625
|
+
markdownUrl: outcome.markdownUrl ?? null,
|
|
626
|
+
errMsg: outcome.errMsg ?? null,
|
|
627
|
+
progress: outcome.progress ?? null,
|
|
628
|
+
runDir: null,
|
|
629
|
+
preview: null,
|
|
630
|
+
artifacts: [],
|
|
631
|
+
};
|
|
632
|
+
if (outcome.state !== 'done') return base;
|
|
633
|
+
if (!collect) return base;
|
|
634
|
+
const cwd = exec.agent?.session?.header?.cwd ?? process.cwd();
|
|
635
|
+
const manager = await state.artifacts.managerFor(cwd);
|
|
636
|
+
const { dir, relDir } = await manager.createRun(sanitizeFileName(args.output ?? 'task'));
|
|
637
|
+
try {
|
|
638
|
+
const collected = await client.collectSingle({ outcome, destDir: dir, opts: resolveOptions(cfg, { ...args, timeoutMs: args.timeoutMs }), signal: exec.signal });
|
|
639
|
+
const metadata = {
|
|
640
|
+
plugin: 'dsh-mineru',
|
|
641
|
+
createdAt: new Date().toISOString(),
|
|
642
|
+
api, taskId: String(args.taskId), state: 'done',
|
|
643
|
+
collectedFrom: 'mineru_task',
|
|
644
|
+
markdownBytes: collected.markdownBytes ?? null,
|
|
645
|
+
};
|
|
646
|
+
await manager.writeFile(dir, 'run.json', JSON.stringify(metadata, null, 2));
|
|
647
|
+
const preview = truncateMarkdown(collected.markdownText, cfg.inlineMarkdownBytes);
|
|
648
|
+
const artifacts = await manager.describeRun(relDir, state.urlBuilder ? { capabilityFor: (rel) => state.urlBuilder(cwd, rel) } : undefined);
|
|
649
|
+
return {
|
|
650
|
+
...base,
|
|
651
|
+
state: 'done',
|
|
652
|
+
runDir: dir,
|
|
653
|
+
preview,
|
|
654
|
+
artifacts,
|
|
655
|
+
};
|
|
656
|
+
} catch (err) {
|
|
657
|
+
await rm(dir, { recursive: true, force: true }).catch(() => {});
|
|
658
|
+
throw err;
|
|
659
|
+
}
|
|
660
|
+
},
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
/** Build all three parsing tools (used by progressive activation and exposeMode: always). */
|
|
665
|
+
export function buildAgentTools(state) {
|
|
666
|
+
return [buildParseTool(state), buildBatchTool(state), buildTaskTool(state)];
|
|
667
|
+
}
|