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/lib/client.js ADDED
@@ -0,0 +1,559 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-mineru",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ var React = require("react");
8
+ var { jsx, jsxs, Fragment } = require("react/jsx-runtime");
9
+ var { useState, useEffect, useCallback, useRef } = React;
10
+
11
+ // ------------------------------------------------------------------
12
+ // Shared helpers
13
+ // ------------------------------------------------------------------
14
+ var S = {
15
+ card: { background: "var(--dsw-alias-bg-layer-3, #16181d)", border: "1px solid var(--dsw-alias-border-l2, #2a2d34)", borderRadius: 8, padding: "16px 0" },
16
+ field: { display: "flex", flexDirection: "column", gap: 6, padding: "10px 0", borderTop: "1px solid var(--dsw-alias-border-l2, #2a2d34)" },
17
+ fieldHead: { display: "flex", alignItems: "center", gap: 8 },
18
+ label: { flex: 1, fontSize: 13, fontWeight: 500, color: "var(--dsw-alias-label-primary, #e8e8e8)" },
19
+ input: { background: "var(--dsw-alias-bg-layer-3, #16181d)", border: "1px solid var(--dsw-alias-border-l2, #2a2d34)", borderRadius: 8, height: 32, padding: "0 10px", fontSize: 13, color: "var(--dsw-alias-label-primary, #e8e8e8)" },
20
+ hint: { margin: 0, fontSize: 12, lineHeight: 1.5, color: "var(--dsw-alias-label-tertiary, #8a8f98)" },
21
+ badge: { whiteSpace: "nowrap", background: "var(--dsw-alias-bg-module-platform, #20242c)", color: "var(--dsw-alias-label-secondary, #a8adb8)", borderRadius: 999, padding: "1px 8px", fontSize: 11, lineHeight: "17px" },
22
+ badgeOk: { whiteSpace: "nowrap", background: "rgba(64, 160, 90, 0.15)", color: "#5dbb76", borderRadius: 999, padding: "1px 8px", fontSize: 11, lineHeight: "17px" },
23
+ badgeWarn: { whiteSpace: "nowrap", background: "rgba(214, 158, 46, 0.15)", color: "#d6a64b", borderRadius: 999, padding: "1px 8px", fontSize: 11, lineHeight: "17px" },
24
+ button: { font: "inherit", cursor: "pointer", background: "var(--dsw-alias-bg-module-platform, #20242c)", color: "var(--dsw-alias-label-primary, #e8e8e8)", border: "1px solid var(--dsw-alias-border-l2, #2a2d34)", borderRadius: 8, padding: "6px 14px", fontSize: 12 },
25
+ buttonPrimary: { font: "inherit", cursor: "pointer", background: "var(--dsw-alias-brand-primary, #4d6bfe)", color: "#fff", border: "none", borderRadius: 8, padding: "7px 16px", fontSize: 12, fontWeight: 500 },
26
+ row: { display: "flex", gap: 8, alignItems: "center" },
27
+ error: { color: "var(--dsw-alias-label-error, #e5484d)", fontSize: 12, margin: 0 },
28
+ okText: { color: "#5dbb76", fontSize: 12, margin: 0 },
29
+ code: { fontFamily: "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace", fontSize: 12 },
30
+ disclosure: { display: "flex", alignItems: "center", gap: 8, padding: "12px 0", cursor: "pointer", background: "none", border: "none", borderTop: "1px solid var(--dsw-alias-border-l2, #2a2d34)", font: "inherit", fontSize: 13, fontWeight: 600, color: "var(--dsw-alias-label-primary, #e8e8e8)", width: "100%", textAlign: "left" },
31
+ };
32
+
33
+ // ------------------------------------------------------------------
34
+ // Form primitives
35
+ // ------------------------------------------------------------------
36
+ var MODES = ["auto", "precision", "agent"];
37
+ var MODELS = ["pipeline", "vlm", "MinerU-HTML"];
38
+ var LANGUAGES = ["ch", "ch_server", "en", "japan", "korean", "chinese_cht", "ta", "te", "ka", "el", "th", "latin", "arabic", "cyrillic", "east_slavic", "devanagari"];
39
+ var EXTRA_FORMATS = ["docx", "html", "latex"];
40
+
41
+ var MODE_LABELS = { auto: "自动 (有 Token 用精准解析, 否则用 Agent 轻量解析)", precision: "精准解析 API (需 Token)", agent: "Agent 轻量解析 API (免 Token)" };
42
+ var MODEL_LABELS = { pipeline: "pipeline (基础)", vlm: "vlm (推荐)", "MinerU-HTML": "MinerU-HTML (HTML 专用)" };
43
+
44
+ function apiLabel(api) {
45
+ if (api === "precision") return "精准解析 API";
46
+ if (api === "agent") return "Agent 轻量解析 API";
47
+ if (api === "precision-missing-token") return "精准解析 (缺 Token)";
48
+ return String(api ?? "");
49
+ }
50
+
51
+ function Field(props) {
52
+ return jsxs("div", { style: S.field, children: [
53
+ jsxs("div", { style: S.fieldHead, children: [
54
+ jsx("label", { style: S.label, children: props.label }),
55
+ props.badge ? jsx("span", { style: S.badge, children: props.badge }) : null,
56
+ ] }),
57
+ props.children,
58
+ props.hint ? jsx("p", { style: S.hint, children: props.hint }) : null,
59
+ ] });
60
+ }
61
+
62
+ function TextField(props) {
63
+ return jsx(Field, { label: props.label, hint: props.hint, badge: props.badge, children: jsx("input", {
64
+ type: "text", style: { ...S.input, width: "100%", boxSizing: "border-box" }, value: props.value ?? "",
65
+ placeholder: props.placeholder, onChange: (e) => props.onChange(e.target.value),
66
+ }) });
67
+ }
68
+
69
+ function NumberField(props) {
70
+ return jsx(Field, { label: props.label, hint: props.hint, badge: props.badge, children: jsx("input", {
71
+ type: "text", inputMode: "numeric", style: { ...S.input, width: "100%", boxSizing: "border-box" }, value: String(props.value ?? ""),
72
+ onChange: (e) => props.onChange(e.target.value),
73
+ }) });
74
+ }
75
+
76
+ function SelectField(props) {
77
+ return jsx(Field, { label: props.label, hint: props.hint, badge: props.badge, children: jsx("select", {
78
+ style: { ...S.input, width: "100%", boxSizing: "border-box", height: 34 }, value: String(props.value ?? ""),
79
+ onChange: (e) => props.onChange(e.target.value),
80
+ children: props.options.map((o) => jsx("option", { value: o.value, children: o.label }, o.value)),
81
+ }) });
82
+ }
83
+
84
+ function CheckField(props) {
85
+ return jsx("div", { style: { ...S.field, flexDirection: "row", alignItems: "center" }, children: [
86
+ jsx("input", { type: "checkbox", checked: Boolean(props.value), style: { margin: 0 }, onChange: (e) => props.onChange(e.target.checked) }),
87
+ jsx("label", { style: { ...S.label, cursor: "pointer" }, children: props.label }),
88
+ ] });
89
+ }
90
+
91
+ async function apiPost(path, body) {
92
+ const res = await fetch("/plugin/mineru" + path, {
93
+ method: "POST",
94
+ headers: { "Content-Type": "application/json" },
95
+ body: JSON.stringify(body ?? {}),
96
+ });
97
+ let payload = null;
98
+ try { payload = await res.json(); } catch { /* non-JSON */ }
99
+ return { status: res.status, payload };
100
+ }
101
+
102
+ // Minimal toast stack (top-center, auto dismiss), used by drop/paste uploads.
103
+ var toastSeq = 0;
104
+ function toast(text, kind) {
105
+ var node = document.createElement("div");
106
+ node.style.cssText = [
107
+ "position: fixed", "top: 96px", "left: 50%", "transform: translateX(-50%)",
108
+ "z-index: 99999", "max-width: 70vw", "padding: " + 10 + "px 16px",
109
+ "border-radius: 8px", "font-size: 13px", "line-height: 1.5",
110
+ "box-shadow: 0 8px 24px rgba(0,0,0,.4)",
111
+ "transition: opacity .3s", "pointer-events: auto",
112
+ "background: " + (kind === "error" ? "#4a1e20" : "#1f2c22"),
113
+ "color: " + (kind === "error" ? "#ffb3b6" : "#a8e6b5"),
114
+ "border: 1px solid " + (kind === "error" ? "#7a3035" : "#2f5c3a"),
115
+ ].join("; ");
116
+ node.textContent = text;
117
+ document.body.appendChild(node);
118
+ toastSeq += 1;
119
+ var mine = toastSeq;
120
+ var stack = document.querySelectorAll("[data-mineru-toast]");
121
+ node.setAttribute("data-mineru-toast", String(mine));
122
+ node.style.top = (96 + stack.length * 52) + "px";
123
+ setTimeout(function () {
124
+ node.style.opacity = "0";
125
+ setTimeout(function () { node.remove(); var rest = document.querySelectorAll("[data-mineru-toast]"); for (var i = 0; i < rest.length; i++) rest[i].style.top = (96 + i * 52) + "px"; }, 320);
126
+ }, kind === "error" ? 6000 : 4200);
127
+ }
128
+
129
+ // ------------------------------------------------------------------
130
+ // Settings tab: MinerU 解析
131
+ // ------------------------------------------------------------------
132
+ function MineruSettingsTab() {
133
+ var [state, setState] = useState({ phase: "loading", revision: 0, value: {}, facts: null, defaults: {}, saveMsg: null, saveErr: null, testMsg: null, testErr: null });
134
+ var [busy, setBusy] = useState({ save: false, reload: false, token: false, testToken: false, testAgent: false });
135
+ var [showAdvanced, setShowAdvanced] = useState(false);
136
+ var [tokenDraft, setTokenDraft] = useState("");
137
+ var [dirty, setDirty] = useState(false);
138
+
139
+ var reload = useCallback(async function (announce) {
140
+ try {
141
+ var res = await fetch("/plugin/mineru/config", { cache: "no-store" });
142
+ var payload = await res.json();
143
+ if (!res.ok || !payload.ok) throw new Error(payload.error ?? ("HTTP " + res.status));
144
+ var value = payload.value ?? {};
145
+ setState(function (prev) { return { ...prev, phase: "ready", revision: payload.revision ?? 0, value: value, facts: payload.facts ?? prev.facts, defaults: payload.schemaHints?.defaults ?? {}, saveMsg: announce === true ? "已重新加载." : null, saveErr: null }; });
146
+ setDirty(false);
147
+ } catch (err) {
148
+ setState(function (prev) { return { ...prev, phase: "error", saveErr: "加载配置失败: " + (err?.message ?? String(err)) }; });
149
+ }
150
+ }, []);
151
+
152
+ useEffect(function () { reload(); }, [reload]);
153
+
154
+ var setValue = function (key, v) {
155
+ setState(function (prev) { return { ...prev, value: { ...prev.value, [key]: v } }; });
156
+ setDirty(true);
157
+ };
158
+
159
+ var save = async function () {
160
+ if (busy.save) return;
161
+ if (!dirty) {
162
+ setState(function (prev) { return { ...prev, saveMsg: "没有需要保存的更改.", saveErr: null }; });
163
+ return;
164
+ }
165
+ setBusy(function (b) { return { ...b, save: true }; });
166
+ setState(function (prev) { return { ...prev, saveMsg: null, saveErr: null }; });
167
+ try {
168
+ var res = await apiPost("/config", { patch: state.value, expectedRevision: state.revision });
169
+ if (res.status === 200 && res.payload?.ok) {
170
+ setState(function (prev) { return { ...prev, revision: res.payload.revision ?? prev.revision, saveMsg: "已保存并生效." }; });
171
+ setDirty(false);
172
+ await reload();
173
+ } else if (res.status === 409) {
174
+ setState(function (prev) { return { ...prev, saveErr: "保存冲突: 设置已被其他会话修改, 请点击重新加载后再保存." }; });
175
+ } else {
176
+ setState(function (prev) { return { ...prev, saveErr: "保存失败: " + (res.payload?.error ?? ("HTTP " + res.status)) }; });
177
+ }
178
+ } catch (err) {
179
+ setState(function (prev) { return { ...prev, saveErr: "保存失败 (网络错误): " + (err?.message ?? String(err)) }; });
180
+ } finally {
181
+ setBusy(function (b) { return { ...b, save: false }; });
182
+ }
183
+ };
184
+
185
+ var saveToken = async function () {
186
+ if (busy.token) return;
187
+ setBusy(function (b) { return { ...b, token: true }; });
188
+ setState(function (prev) { return { ...prev, saveMsg: null, saveErr: null }; });
189
+ try {
190
+ var res = await apiPost("/credential", { value: tokenDraft });
191
+ if (res.status === 200 && res.payload?.ok) {
192
+ setTokenDraft("");
193
+ await reload();
194
+ setState(function (prev) { return { ...prev, saveMsg: "Token 已保存 (当前解析通道: " + apiLabel(prev.facts?.api) + ")." }; });
195
+ } else {
196
+ setState(function (prev) { return { ...prev, saveErr: "保存 Token 失败: " + (res.payload?.error ?? ("HTTP " + res.status)) }; });
197
+ }
198
+ } catch (err) {
199
+ setState(function (prev) { return { ...prev, saveErr: "保存 Token 失败 (网络错误): " + (err?.message ?? String(err)) }; });
200
+ } finally {
201
+ setBusy(function (b) { return { ...b, token: false }; });
202
+ }
203
+ };
204
+
205
+ var clearToken = async function () {
206
+ if (busy.token) return;
207
+ setBusy(function (b) { return { ...b, token: true }; });
208
+ setState(function (prev) { return { ...prev, saveMsg: null, saveErr: null }; });
209
+ try {
210
+ var res = await apiPost("/credential", { clear: true });
211
+ if (res.status === 200 && res.payload?.ok) {
212
+ setState(function (prev) { return { ...prev, saveMsg: "Token 已清除 (将使用 Agent 轻量解析 API)." }; });
213
+ await reload();
214
+ } else {
215
+ setState(function (prev) { return { ...prev, saveErr: "清除 Token 失败: " + (res.payload?.error ?? ("HTTP " + res.status)) }; });
216
+ }
217
+ } catch (err) {
218
+ setState(function (prev) { return { ...prev, saveErr: "清除 Token 失败 (网络错误): " + (err?.message ?? String(err)) }; });
219
+ } finally {
220
+ setBusy(function (b) { return { ...b, token: false }; });
221
+ }
222
+ };
223
+
224
+ var runTest = async function (which) {
225
+ var key = which === "token" ? "testToken" : "testAgent";
226
+ if (busy[key]) return;
227
+ setBusy(function (b) { return { ...b, [key]: true }; });
228
+ setState(function (prev) { return { ...prev, testMsg: null, testErr: null }; });
229
+ try {
230
+ var res = await apiPost(which === "token" ? "/test-token" : "/test-agent", {});
231
+ if (res.status === 200 && res.payload?.ok) {
232
+ setState(function (prev) { return { ...prev, testMsg: res.payload.message ?? "测试通过." }; });
233
+ } else {
234
+ setState(function (prev) { return { ...prev, testErr: res.payload?.error ?? ("HTTP " + res.status) }; });
235
+ }
236
+ } catch (err) {
237
+ setState(function (prev) { return { ...prev, testErr: "测试请求失败 (网络错误): " + (err?.message ?? String(err)) }; });
238
+ } finally {
239
+ setBusy(function (b) { return { ...b, [key]: false }; });
240
+ }
241
+ };
242
+
243
+ if (state.phase === "loading") {
244
+ return jsx("p", { style: S.hint, children: "正在加载 MinerU 配置…" });
245
+ }
246
+ if (state.phase === "error") {
247
+ return jsxs("div", { children: [jsx("p", { style: S.error, children: state.saveErr }), jsx("button", { style: S.button, onClick: function () { setBusy(function (b) { return { ...b, reload: true }; }); reload(true).finally(function () { setBusy(function (b) { return { ...b, reload: false }; }); }); }, children: "重试" })] });
248
+ }
249
+
250
+ var facts = state.facts ?? {};
251
+ var v = state.value;
252
+ var anyBusy = busy.save || busy.reload || busy.token || busy.testToken || busy.testAgent;
253
+ return jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 4 }, children: [
254
+ jsxs("div", { style: S.row, children: [
255
+ jsx("span", { style: { fontSize: 13, fontWeight: 600, color: "var(--dsw-alias-label-primary, #e8e8e8)" }, children: "MinerU 文档解析" }),
256
+ facts.tokenConfigured ? jsx("span", { style: S.badgeOk, children: "Token 已配置" }) : jsx("span", { style: S.badgeWarn, children: "未配置 Token" }),
257
+ jsx("span", { style: S.badge, children: "当前: " + apiLabel(facts.api) }),
258
+ ] }),
259
+ jsx("p", { style: S.hint, children: "为 DeepSeek Harness 提供基于 MinerU 的多模态全格式文档解析 (PDF/Word/PPT/Excel/HTML/图片 → 结构化 Markdown). 填写 Token 走精准解析 API; Token 留空走 Agent 轻量解析 API. 也可以直接把文档/图片拖入聊天窗口, 插件会自动保存到工作区并发起解析." }),
260
+
261
+ // ---- Token ----
262
+ jsx(Field, { label: "MinerU Token (精准解析 API)", badge: facts.tokenConfigured ? "已配置 (" + (facts.tokenSource ?? "?") + ")" : "未配置", hint: "在 mineru.net 的 API 管理页面创建. 留空则自动使用 Agent 轻量解析 API (免登录, IP 限频). 值只写不读, 不落设置文件, 保存在 DSH 凭据中.", children: jsxs("div", { style: S.row, children: [
263
+ jsx("input", { type: "password", style: { ...S.input, flex: 1 }, value: tokenDraft, placeholder: "留空 = 保留现有 Token", onChange: (e) => setTokenDraft(e.target.value) }),
264
+ jsx("button", { style: S.buttonPrimary, disabled: busy.token || tokenDraft.length === 0, onClick: saveToken, children: busy.token ? "保存中…" : "保存密钥" }),
265
+ jsx("button", { style: S.button, disabled: busy.token, onClick: clearToken, children: "清除" }),
266
+ ] }) }),
267
+
268
+ // ---- Basic ----
269
+ jsx(SelectField, { label: "API 模式", hint: "auto: 有 Token 用精准解析, 否则用 Agent 轻量解析.", badge: "mode", value: v.mode ?? "auto", options: MODES.map(function (m) { return { value: m, label: m + " — " + MODE_LABELS[m] }; }), onChange: (val) => setValue("mode", val) }),
270
+ jsx(SelectField, { label: "精准解析模型版本", hint: "vlm 推荐; HTML 文件自动强制 MinerU-HTML.", value: v.modelVersion ?? "vlm", options: MODELS.map(function (m) { return { value: m, label: MODEL_LABELS[m] }; }), onChange: (val) => setValue("modelVersion", val) }),
271
+ jsx(SelectField, { label: "文档语言", hint: "影响 OCR 识别效果, 默认 ch (中英).", value: v.language ?? "ch", options: LANGUAGES.map(function (l) { return { value: l, label: l }; }), onChange: (val) => setValue("language", val) }),
272
+ jsx(CheckField, { label: "表格识别 (enableTable)", value: v.enableTable !== false, onChange: (val) => setValue("enableTable", val) }),
273
+ jsx(CheckField, { label: "公式识别 (enableFormula)", value: v.enableFormula !== false, onChange: (val) => setValue("enableFormula", val) }),
274
+ jsx(CheckField, { label: "强制 OCR (isOcr, 扫描件)", value: v.isOcr === true, onChange: (val) => setValue("isOcr", val) }),
275
+
276
+ jsx(Field, { label: "额外导出格式 (精准解析)", hint: "Markdown + JSON 为默认输出; 可追加 docx/html/latex 到结果 Zip.", children: jsx("div", { style: S.row, children: EXTRA_FORMATS.map(function (f) {
277
+ var on = Array.isArray(v.extraFormats) && v.extraFormats.indexOf(f) >= 0;
278
+ return jsx("label", { style: { ...S.row, cursor: "pointer" }, children: [jsx("input", { type: "checkbox", checked: on, onChange: function (e) {
279
+ var list = Array.isArray(v.extraFormats) ? v.extraFormats.slice() : [];
280
+ if (e.target.checked) { if (list.indexOf(f) < 0) list.push(f); } else { list = list.filter(function (x) { return x !== f; }); }
281
+ setValue("extraFormats", list);
282
+ } }), jsx("span", { style: { fontSize: 13 }, children: f })] }, f);
283
+ }) }) }),
284
+
285
+ // ---- Advanced (collapsed) ----
286
+ jsx("button", { type: "button", style: S.disclosure, onClick: function () { setShowAdvanced(!showAdvanced); }, children: (showAdvanced ? "▾ " : "▸ ") + "高级设置" + (dirty && !showAdvanced ? " (有未保存的更改)" : "") }),
287
+ showAdvanced ? jsxs(Fragment, { children: [
288
+ jsx(NumberField, { label: "整体超时 (ms)", hint: "含提交、上传、轮询等待与下载. 默认 600000 (10 分钟).", value: v.timeoutMs, onChange: (val) => setValue("timeoutMs", parseInt(val, 10)) }),
289
+ jsx(NumberField, { label: "轮询间隔 (ms)", hint: "查询任务结果的间隔, 官方查询限频 1000 次/分钟.", value: v.pollIntervalMs, onChange: (val) => setValue("pollIntervalMs", parseInt(val, 10)) }),
290
+ jsx(NumberField, { label: "本地文件大小上限 (字节)", hint: "0 = 按 API 限制 (精准 200MB / Agent 10MB).", value: v.maxFileBytes, onChange: (val) => setValue("maxFileBytes", parseInt(val, 10)) }),
291
+ jsx(NumberField, { label: "结果内联预览上限 (字节)", hint: "工具结果内附的 Markdown 预览长度; 全文始终写入 Artifact.", value: v.inlineMarkdownBytes, onChange: (val) => setValue("inlineMarkdownBytes", parseInt(val, 10)) }),
292
+ jsx(NumberField, { label: "提交限速 (个/分钟)", hint: "官方 50 个/分钟, 默认留 40 保有裕量.", value: v.submitRatePerMin, onChange: (val) => setValue("submitRatePerMin", parseInt(val, 10)) }),
293
+ jsx(NumberField, { label: "查询限速 (次/分钟)", hint: "官方 1000 次/分钟, 默认 900.", value: v.pollRatePerMin, onChange: (val) => setValue("pollRatePerMin", parseInt(val, 10)) }),
294
+ jsx(NumberField, { label: "每日提交上限 (个)", hint: "官方 5000 个/天 (html 100 个), 达到后在本地提前报错.", value: v.dailySubmitLimit, onChange: (val) => setValue("dailySubmitLimit", parseInt(val, 10)) }),
295
+ jsx(NumberField, { label: "预览链接有效期 (秒)", hint: "Artifact 签名预览 URL 的过期时间.", value: v.artifactUrlTtlSec, onChange: (val) => setValue("artifactUrlTtlSec", parseInt(val, 10)) }),
296
+ jsx(TextField, { label: "API 地址", hint: "默认 https://mineru.net.", value: v.apiBaseUrl, onChange: (val) => setValue("apiBaseUrl", val) }),
297
+ jsx(TextField, { label: "凭据引用名", hint: "DSH Credential 引用名 (POSIX 标识符), 默认 MINERU_API_TOKEN.", value: v.tokenCredential, onChange: (val) => setValue("tokenCredential", val) }),
298
+ jsx(TextField, { label: "Artifact 根目录名", hint: "每个工作区下的解析结果目录, 默认 .dsh-mineru.", value: v.artifactRootName, onChange: (val) => setValue("artifactRootName", val) }),
299
+ ] }) : null,
300
+
301
+ // ---- Actions ----
302
+ state.saveMsg ? jsx("p", { style: S.okText, children: state.saveMsg }) : null,
303
+ state.saveErr ? jsx("p", { style: S.error, children: state.saveErr }) : null,
304
+ jsxs("div", { style: { ...S.row, paddingTop: 12, flexWrap: "wrap" }, children: [
305
+ jsx("button", { style: S.buttonPrimary, onClick: save, disabled: anyBusy, children: busy.save ? "保存中…" : (dirty ? "保存并应用" : "保存并应用 (无更改)") }),
306
+ jsx("button", { style: S.button, disabled: anyBusy, onClick: function () { setBusy(function (b) { return { ...b, reload: true }; }); reload(true).finally(function () { setBusy(function (b) { return { ...b, reload: false }; }); }); }, children: busy.reload ? "加载中…" : "重新加载" }),
307
+ jsx("span", { style: { flex: 1 } }),
308
+ jsx("button", { style: S.button, disabled: anyBusy, onClick: function () { return runTest("agent"); }, children: busy.testAgent ? "测试中…(最多约3分钟)" : "测试 Agent API" }),
309
+ jsx("button", { style: S.button, disabled: anyBusy, onClick: function () { return runTest("token"); }, children: busy.testToken ? "测试中…(最多约3分钟)" : "测试 Token" }),
310
+ ] }),
311
+ state.testMsg ? jsx("p", { style: S.okText, children: state.testMsg }) : null,
312
+ state.testErr ? jsx("p", { style: S.error, children: state.testErr }) : null,
313
+ ] });
314
+ }
315
+
316
+ // ------------------------------------------------------------------
317
+ // Tool result cards for mineru_parse / mineru_batch_parse / mineru_task
318
+ // ------------------------------------------------------------------
319
+ function fmtBytes(n) {
320
+ if (!Number.isFinite(n) || n <= 0) return "0 B";
321
+ var units = ["B", "KB", "MB", "GB"];
322
+ var i = 0, v = n;
323
+ while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; }
324
+ return (i === 0 ? String(v) : v.toFixed(1)) + " " + units[i];
325
+ }
326
+
327
+ function ArtifactChip(props) {
328
+ var a = props.artifact;
329
+ return jsxs("span", { style: { display: "inline-flex", alignItems: "center", gap: 6, background: "var(--dsw-alias-bg-module-platform, #20242c)", border: "1px solid var(--dsw-alias-border-l2, #2a2d34)", borderRadius: 8, padding: "3px 10px", fontSize: 12 }, children: [
330
+ jsx("button", { type: "button", title: a.path, style: { ...S.button, padding: "0", border: "none", background: "transparent", fontSize: 12 }, onClick: function () { props.openFile(a.path); }, children: a.name }),
331
+ jsx("span", { style: S.hint, children: a.kind + " · " + fmtBytes(a.bytes) }),
332
+ a.url ? jsx("a", { href: a.url, target: "_blank", rel: "noopener noreferrer", style: { fontSize: 12, color: "var(--dsw-alias-brand-primary, #4d6bfe)" }, children: "预览" }) : null,
333
+ ] }, a.path);
334
+ }
335
+
336
+ function MetaCard(props) {
337
+ var meta = props.meta;
338
+ if (!meta || typeof meta !== "object") return null;
339
+ var artifacts = Array.isArray(meta.artifacts) ? meta.artifacts : [];
340
+ var preview = meta.preview?.markdown;
341
+ var header = [
342
+ jsx("span", { key: "api", style: S.badge, children: apiLabel(meta.api) }),
343
+ meta.modelVersion ? jsx("span", { key: "model", style: S.badge, children: String(meta.modelVersion) }) : null,
344
+ meta.durationMs ? jsx("span", { key: "dur", style: S.badge, children: (meta.durationMs / 1000).toFixed(1) + "s" }) : null,
345
+ meta.taskId ? jsx("span", { key: "task", style: { ...S.badge, fontFamily: "ui-monospace, Menlo, monospace" }, children: String(meta.taskId).slice(0, 12) }) : null,
346
+ ];
347
+ if (meta.warning) header.push(jsx("span", { key: "warn", style: S.badgeWarn, children: String(meta.warning) }));
348
+ var batchRows = null;
349
+ if (Array.isArray(meta.results) && meta.results.length > 0) {
350
+ batchRows = jsx("div", { style: { display: "flex", flexDirection: "column", gap: 4 }, children: meta.results.map(function (r, i) {
351
+ return jsxs("div", { key: i, style: S.row, children: [
352
+ jsx("span", { style: r.state === "done" ? S.badgeOk : S.badgeWarn, children: r.state }),
353
+ jsx("span", { style: { fontSize: 12 }, children: String(r.name ?? ("#" + i)) }),
354
+ r.errMsg ? jsx("span", { style: S.error, children: String(r.errMsg).slice(0, 120) }) : null,
355
+ ] });
356
+ }) });
357
+ }
358
+ return jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 8, padding: "8px 0" }, children: [
359
+ jsx("div", { style: { ...S.row, flexWrap: "wrap" }, children: header }),
360
+ batchRows,
361
+ artifacts.length > 0 ? jsx("div", { style: { ...S.row, flexWrap: "wrap", gap: 6 }, children: artifacts.map(function (a, i) { return jsx(ArtifactChip, { key: i, artifact: a, openFile: props.openFile }); }) }) : null,
362
+ preview ? jsx("pre", { style: { maxHeight: 240, overflow: "auto", margin: 0, padding: 10, background: "var(--dsw-alias-bg-layer-3, #16181d)", border: "1px solid var(--dsw-alias-border-l2, #2a2d34)", borderRadius: 8, fontSize: 12, lineHeight: 1.6, whiteSpace: "pre-wrap", wordBreak: "break-word", color: "var(--dsw-alias-label-primary, #e8e8e8)" }, children: String(preview) }) : null,
363
+ ] });
364
+ }
365
+
366
+ function MineruToolView(props) {
367
+ var block = props.block;
368
+ if (!block) return null;
369
+ var args = null;
370
+ try {
371
+ if (block.kind === "tool-result") args = block.call?.argsRaw ? JSON.parse(block.call.argsRaw) : null;
372
+ else args = block.argsRaw ? JSON.parse(block.argsRaw) : null;
373
+ } catch { /* args parse failure -> generic */ }
374
+
375
+ if (block.kind === "tool-result") {
376
+ var meta = block.meta;
377
+ if (block.isError) {
378
+ var text = "";
379
+ if (Array.isArray(block.content)) {
380
+ for (var i = 0; i < block.content.length; i++) {
381
+ var b = block.content[i];
382
+ if (b && b.type === "text") { text += b.text; break; }
383
+ }
384
+ }
385
+ return jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 6, padding: "8px 0" }, children: [
386
+ jsx("span", { style: S.badgeWarn, children: "解析失败" }),
387
+ jsx("p", { style: S.error, children: String(text || "MinerU 任务失败").slice(0, 600) }),
388
+ ] });
389
+ }
390
+ return jsx(MetaCard, { meta: meta, openFile: props.openFile });
391
+ }
392
+
393
+ // running
394
+ var source = args?.source ?? args?.taskId ?? "";
395
+ return jsxs("div", { style: { display: "flex", flexDirection: "column", gap: 6, padding: "8px 0" }, children: [
396
+ jsx("span", { style: S.badge, children: "MinerU 解析中…" }),
397
+ jsx("p", { style: S.hint, children: "来源: " + String(source).slice(0, 200) }),
398
+ ] });
399
+ }
400
+
401
+ // ------------------------------------------------------------------
402
+ // Drag-drop / paste bridge: files land in the session workspace and are
403
+ // parsed via mineru_parse instead of the native image-attachment channel
404
+ // (which text-only models reject at prompt admission).
405
+ // ------------------------------------------------------------------
406
+ var SUPPORTED_DROP_EXT = [".pdf", ".doc", ".docx", ".ppt", ".pptx", ".xls", ".xlsx", ".png", ".jpg", ".jpeg", ".jp2", ".webp", ".gif", ".bmp", ".html", ".htm"];
407
+ var IMAGE_DROP_EXT = { ".png": 1, ".jpg": 1, ".jpeg": 1, ".jp2": 1, ".webp": 1, ".gif": 1, ".bmp": 1 };
408
+ var DROP_MAX_BYTES = 210 * 1024 * 1024;
409
+
410
+ function dropExtOf(name) {
411
+ var i = String(name ?? "").lastIndexOf(".");
412
+ return i < 0 ? "" : name.slice(i).toLowerCase();
413
+ }
414
+
415
+ function installFileDropBridge(ctx) {
416
+ var currentSession = function () { return ctx.sessions.list.getSnapshot().current; };
417
+ var hasFiles = function (event) { return event.dataTransfer ? event.dataTransfer.types.includes("Files") : false; };
418
+ var supportedOf = function (list) {
419
+ return Array.from(list ?? []).filter(function (f) { return f && SUPPORTED_DROP_EXT.includes(dropExtOf(f.name)); });
420
+ };
421
+ // The native composer drag overlay can get stuck on for OS-originated
422
+ // drags (dragend never fires inside the browser). Dispatching a
423
+ // synthetic dragend lets the conversation plugin's reset path run.
424
+ var killOverlay = function () {
425
+ try { window.dispatchEvent(new Event("dragend")); } catch { /* ignore */ }
426
+ };
427
+ // Fills the composer draft (never auto-sends): the user keeps control
428
+ // over the final prompt and clicks send themselves.
429
+ var fillDraft = function (sessionId, text) {
430
+ var conversation = ctx.get("conversation");
431
+ var actx = ctx.sessions.scope(sessionId);
432
+ if (!conversation || !actx || typeof conversation.input?.for !== "function") {
433
+ throw new Error("输入框服务不可用");
434
+ }
435
+ conversation.input.for(actx).setDraft(text);
436
+ };
437
+
438
+ async function intake(files) {
439
+ var sessionId = currentSession();
440
+ if (!sessionId) {
441
+ toast("请先打开一个会话, 再拖入文档.", "error");
442
+ return;
443
+ }
444
+ var uploaded = [];
445
+ for (var i = 0; i < files.length; i++) {
446
+ var file = files[i];
447
+ if (file.size === 0) { toast("跳过空文件: " + file.name, "error"); continue; }
448
+ if (file.size > DROP_MAX_BYTES) { toast("文件超过 200MB 上限, 已跳过: " + file.name, "error"); continue; }
449
+ try {
450
+ var url = "/plugin/mineru/upload?sessionId=" + encodeURIComponent(sessionId) + "&name=" + encodeURIComponent(file.name);
451
+ var res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: file });
452
+ var payload = null;
453
+ try { payload = await res.json(); } catch { /* non-JSON */ }
454
+ if (!res.ok || !payload?.ok) throw new Error(payload?.error ?? ("HTTP " + res.status));
455
+ uploaded.push(payload.path);
456
+ } catch (err) {
457
+ toast("上传失败: " + file.name + " — " + (err?.message ?? String(err)), "error");
458
+ }
459
+ }
460
+ if (uploaded.length === 0) return;
461
+ // Only the file-list statement goes into the composer draft. The user
462
+ // appends their own requirements and sends; nothing is auto-submitted.
463
+ var text = "我拖入了以下文件 (已保存到工作区):\n" + uploaded.map(function (p) { return "- " + p; }).join("\n") + "\n\n";
464
+ try {
465
+ fillDraft(sessionId, text);
466
+ toast("已上传 " + uploaded.length + " 个文件并填入输入框: 请补充需求后点击发送.");
467
+ } catch (err) {
468
+ toast("文件已上传, 但写入输入框失败: " + (err?.message ?? String(err)) + " 文件路径: " + uploaded.join("; "), "error");
469
+ }
470
+ }
471
+
472
+ var overlayKilled = false;
473
+ var onDragEnter = function (event) {
474
+ if (!hasFiles(event)) return;
475
+ if (supportedOf(event.dataTransfer.files).length === 0) return;
476
+ event.stopPropagation();
477
+ };
478
+ var onDragOver = function (event) {
479
+ if (!hasFiles(event) || event.dataTransfer === null) return;
480
+ if (supportedOf(event.dataTransfer.files).length === 0) return;
481
+ event.preventDefault();
482
+ event.stopPropagation();
483
+ event.dataTransfer.dropEffect = "copy";
484
+ if (!overlayKilled) {
485
+ // First dragover with real files: clear any stuck native overlay
486
+ // (its dragenter may have seen an empty dataTransfer.types list).
487
+ overlayKilled = true;
488
+ killOverlay();
489
+ }
490
+ };
491
+ var onDrop = function (event) {
492
+ if (!hasFiles(event)) return;
493
+ var files = supportedOf(event.dataTransfer.files);
494
+ if (files.length === 0) return;
495
+ event.preventDefault();
496
+ event.stopPropagation();
497
+ overlayKilled = false;
498
+ killOverlay();
499
+ intake(files);
500
+ };
501
+ var onDragEnd = function () { overlayKilled = false; };
502
+ var onPaste = function (event) {
503
+ if (!event.clipboardData) return;
504
+ var files = Array.from(event.clipboardData.items ?? [])
505
+ .filter(function (it) { return it.kind === "file"; })
506
+ .map(function (it) { return it.getAsFile(); })
507
+ .filter(function (f) { return f !== null; })
508
+ .filter(function (f) { return SUPPORTED_DROP_EXT.includes(dropExtOf(f.name)) && !IMAGE_DROP_EXT[dropExtOf(f.name)]; });
509
+ if (files.length === 0) return;
510
+ event.preventDefault();
511
+ event.stopPropagation();
512
+ intake(files);
513
+ };
514
+
515
+ document.addEventListener("dragenter", onDragEnter, true);
516
+ document.addEventListener("dragover", onDragOver, true);
517
+ document.addEventListener("drop", onDrop, true);
518
+ document.addEventListener("dragend", onDragEnd, true);
519
+ document.addEventListener("paste", onPaste, true);
520
+ return function () {
521
+ document.removeEventListener("dragenter", onDragEnter, true);
522
+ document.removeEventListener("dragover", onDragOver, true);
523
+ document.removeEventListener("drop", onDrop, true);
524
+ document.removeEventListener("dragend", onDragEnd, true);
525
+ document.removeEventListener("paste", onPaste, true);
526
+ };
527
+ }
528
+
529
+ // ------------------------------------------------------------------
530
+ // Plugin entry
531
+ // ------------------------------------------------------------------
532
+ var inject = ["slots", "connection", "sessions", "conversation"];
533
+
534
+ function apply(ctx) {
535
+ ctx.slots.inject("settings.plugins.tab", () => ctx.slots.register({
536
+ name: "settings.plugins.tab",
537
+ id: "mineru",
538
+ order: 30,
539
+ label: "MinerU 解析",
540
+ }, MineruSettingsTab));
541
+
542
+ ctx.slots.inject("tool.call.toolview", function* () {
543
+ yield ctx.slots.register({ name: "tool.call.toolview", key: "mineru_parse" }, MineruToolView);
544
+ yield ctx.slots.register({ name: "tool.call.toolview", key: "mineru_batch_parse" }, MineruToolView);
545
+ yield ctx.slots.register({ name: "tool.call.toolview", key: "mineru_task" }, MineruToolView);
546
+ });
547
+
548
+ // File drop/paste bridge: document + image drops become workspace files
549
+ // parsed through MinerU (no native image-attachment channel involved).
550
+ ctx.effect(() => installFileDropBridge(ctx), "dsh-mineru: file drop bridge");
551
+ }
552
+
553
+ exports.apply = apply;
554
+ exports.inject = inject;
555
+ return module.exports;
556
+ }
557
+ });
558
+
559
+ //# sourceMappingURL=client.js.map