@sparkelf/dsh-ocr 0.0.0-stage → 0.1.1
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/SKILL.md +85 -0
- package/cordis.patch.yml +17 -0
- package/i18n/zh.json +5 -0
- package/lib/client.js +892 -0
- package/lib/index.js +488 -0
- package/lib/types/api.d.ts +134 -0
- package/lib/types/client/SettingsSection.d.ts +47 -0
- package/lib/types/client/context.d.ts +35 -0
- package/lib/types/client/contract.d.ts +32 -0
- package/lib/types/client/index.d.ts +21 -0
- package/lib/types/client/locales.d.ts +98 -0
- package/lib/types/client/sectionVisibility.d.ts +57 -0
- package/lib/types/client/styles.d.ts +56 -0
- package/lib/types/index.d.ts +321 -0
- package/package.json +81 -4
- package/README.md +0 -3
package/lib/index.js
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { fileURLToPath } from "node:url";
|
|
4
|
+
import z from "@deepseek-ai/schemastery";
|
|
5
|
+
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
6
|
+
//#region src/api.ts
|
|
7
|
+
/**
|
|
8
|
+
* The same-origin API surface shared by this package's two halves.
|
|
9
|
+
*
|
|
10
|
+
* The Host registers one prefix and dispatches on the trailing method name; the browser
|
|
11
|
+
* calls the same strings. Keeping them in one module is what stops the two halves
|
|
12
|
+
* drifting apart -- the failure mode knowledge-base recorded when its panel called
|
|
13
|
+
* `/knowledge-base/config` while its Host served `/knowledge-base/api/config`.
|
|
14
|
+
*
|
|
15
|
+
* The namespace is `ocr` rather than a shared one, so this route can never collide with
|
|
16
|
+
* the knowledge base's `/knowledge-base/api/*` or any other plugin's prefix.
|
|
17
|
+
*
|
|
18
|
+
* This module must stay dependency-free so both bundles can import it: the Client bundle
|
|
19
|
+
* rejects Node builtins and non-platform packages.
|
|
20
|
+
*
|
|
21
|
+
* @module @sparkelf/dsh-ocr/api
|
|
22
|
+
*/
|
|
23
|
+
/** Prefix the Host registers and the browser calls. */
|
|
24
|
+
const OCR_API_PREFIX = "/ocr/api";
|
|
25
|
+
/** Method names the Host dispatches on. */
|
|
26
|
+
const OCR_API = {
|
|
27
|
+
/** The shared MinerU address plus whether the caller may change it. */
|
|
28
|
+
config: "config",
|
|
29
|
+
/** How many members a distribution reaches, and how many it would replace. */
|
|
30
|
+
impact: "impact",
|
|
31
|
+
/** Fill only members that hold no address of their own. */
|
|
32
|
+
distributeDefault: "distribute-default",
|
|
33
|
+
/** Replace every member's address, including ones they chose themselves. */
|
|
34
|
+
overwrite: "overwrite",
|
|
35
|
+
/**
|
|
36
|
+
* Probe a MinerU address before saving it.
|
|
37
|
+
*
|
|
38
|
+
* Not a backend route: the Host answers this one itself, because only this process can
|
|
39
|
+
* reach the address from inside the workspace network. It still reads the stored config
|
|
40
|
+
* through the backend first, so a caller who may not edit cannot make the relay fetch an
|
|
41
|
+
* arbitrary URL.
|
|
42
|
+
*/
|
|
43
|
+
testConnection: "test-connection"
|
|
44
|
+
};
|
|
45
|
+
//#endregion
|
|
46
|
+
//#region src/index.ts
|
|
47
|
+
/**
|
|
48
|
+
* Host half of the document-text-recognition plugin.
|
|
49
|
+
*
|
|
50
|
+
* Two contributions, and they serve different audiences:
|
|
51
|
+
*
|
|
52
|
+
* 1. **The skill provider.** The package ships one file the model needs -- `SKILL.md` -- and
|
|
53
|
+
* it does not live under a directory the skill registry scans, because `node_modules` is
|
|
54
|
+
* not a scan root. Registering it explicitly is the same thing
|
|
55
|
+
* `@sparkelf/dsh-dataops-admin` and `@sparkelf/dsh-knowledge-base` do.
|
|
56
|
+
*
|
|
57
|
+
* 2. **The settings route.** The settings page cannot call the DataOps backend directly: the
|
|
58
|
+
* browser's credential is an httpOnly cookie and the backend's `/api/ocr/*` routes want a
|
|
59
|
+
* bearer. This Host holds the DataOps JWT (or adopts the one the gateway attached), so it
|
|
60
|
+
* relays the four OCR calls and the page talks only to this process.
|
|
61
|
+
*
|
|
62
|
+
* The MinerU address is NOT stored here. Every member gets their own workspace container and
|
|
63
|
+
* their own DSH profile, so a per-profile setting cannot reach anybody else; the shared value
|
|
64
|
+
* lives in the backend (`GET /api/ocr/config`), which this half reads and relays. A copy in
|
|
65
|
+
* this profile would be a second source of truth that silently goes stale.
|
|
66
|
+
*
|
|
67
|
+
* @module @sparkelf/dsh-ocr
|
|
68
|
+
*/
|
|
69
|
+
/** The name this plugin mounts as in the profile composition. */
|
|
70
|
+
const PLUGIN_NAME = "@sparkelf/dsh-ocr";
|
|
71
|
+
/**
|
|
72
|
+
* Host services this plugin needs before `apply` runs.
|
|
73
|
+
*
|
|
74
|
+
* Declared rather than reached for: Cordis resolves a service through the plugin's own
|
|
75
|
+
* context, and touching one that was not injected throws
|
|
76
|
+
* `cannot get property "webServer" without inject` during apply -- which took the whole
|
|
77
|
+
* plugin down and, with it, the skill registration. `webServer` carries the settings relay,
|
|
78
|
+
* `credentials` resolves the fallback DataOps token.
|
|
79
|
+
*
|
|
80
|
+
* `skills` is deliberately absent: the registry is an OPTIONAL neighbour, so it is reached
|
|
81
|
+
* through `ctx.inject` inside apply and skipped on a host that does not have it.
|
|
82
|
+
*/
|
|
83
|
+
const inject = ["webServer", "credentials"];
|
|
84
|
+
/** Provider name reported to the skill registry. */
|
|
85
|
+
const SKILL_PROVIDER = "dsh-ocr";
|
|
86
|
+
/**
|
|
87
|
+
* Name the model sees in the skill catalog.
|
|
88
|
+
*
|
|
89
|
+
* Must match `^[a-z0-9]+(?:-[a-z0-9]+)*$`: the skill center silently skips a directory that
|
|
90
|
+
* does not, and this value keys the provider.
|
|
91
|
+
*/
|
|
92
|
+
const SKILL_NAME = "ocr";
|
|
93
|
+
/**
|
|
94
|
+
* Short description shown in the skill list.
|
|
95
|
+
*
|
|
96
|
+
* Kept beside the SKILL.md body rather than parsed out of its frontmatter: the catalog
|
|
97
|
+
* answers `list()` without reading any skill content, so the text has to be available
|
|
98
|
+
* without touching the file.
|
|
99
|
+
*/
|
|
100
|
+
const SKILL_DESCRIPTION = "识别 PDF、图片、扫描件等文档中的文字并输出 Markdown,使用管理员统一配置的 MinerU 服务。";
|
|
101
|
+
/** One-line Chinese introduction the skill center shows in place of the routing description. */
|
|
102
|
+
const SKILL_SUMMARY = "识别 PDF/图片/扫描件文字并输出 Markdown";
|
|
103
|
+
/**
|
|
104
|
+
* Display name the skill center shows for this skill.
|
|
105
|
+
*
|
|
106
|
+
* Deliberately NOT the registry name: `ocr` is the internal identifier, while users must see
|
|
107
|
+
* a business-facing Chinese name. The skill center reads the display name from the
|
|
108
|
+
* `i18n/zh.json` beside SKILL.md; this constant is the same string, so a host that reports
|
|
109
|
+
* the catalog without the translation file still has the right name.
|
|
110
|
+
*/
|
|
111
|
+
const SKILL_DISPLAY_NAME = "文档文字识别";
|
|
112
|
+
/**
|
|
113
|
+
* Where this package's SKILL.md lives, from either build layout.
|
|
114
|
+
*
|
|
115
|
+
* The build emits `lib/index.js` while a source run executes from `src/`; both sit one level
|
|
116
|
+
* below the package root, so the same `..` answers both.
|
|
117
|
+
*
|
|
118
|
+
* @returns absolute path of the skill document.
|
|
119
|
+
*/
|
|
120
|
+
function skillPath() {
|
|
121
|
+
return join(dirname(fileURLToPath(import.meta.url)), "..", "SKILL.md");
|
|
122
|
+
}
|
|
123
|
+
/** Both a human and the model may invoke this skill. */
|
|
124
|
+
const SKILL_INVOCATION = {
|
|
125
|
+
modelInvocable: true,
|
|
126
|
+
userInvocable: true
|
|
127
|
+
};
|
|
128
|
+
/**
|
|
129
|
+
* Rank places this beside the other bundled DataOps capabilities.
|
|
130
|
+
*
|
|
131
|
+
* `knowledge-base` uses 640 and `dataops-admin` uses 641; this one follows them. The value
|
|
132
|
+
* orders a catalog listing, not a priority -- the model reaches for these by name.
|
|
133
|
+
*/
|
|
134
|
+
const SKILL_RANK = 642;
|
|
135
|
+
/** Backend path each relayed method calls, and the HTTP method it uses. */
|
|
136
|
+
const OCR_BACKEND_ROUTES = {
|
|
137
|
+
config: {
|
|
138
|
+
path: "/api/ocr/config",
|
|
139
|
+
method: "GET"
|
|
140
|
+
},
|
|
141
|
+
impact: {
|
|
142
|
+
path: "/api/ocr/admin/impact",
|
|
143
|
+
method: "GET"
|
|
144
|
+
},
|
|
145
|
+
"distribute-default": {
|
|
146
|
+
path: "/api/ocr/admin/distribute-default",
|
|
147
|
+
method: "POST"
|
|
148
|
+
},
|
|
149
|
+
overwrite: {
|
|
150
|
+
path: "/api/ocr/admin/overwrite",
|
|
151
|
+
method: "POST"
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
/**
|
|
155
|
+
* The skill provider that teaches the model to recognise document text.
|
|
156
|
+
*
|
|
157
|
+
* One bundled skill, read from disk on `get()` rather than kept in memory: the body is
|
|
158
|
+
* documentation, and a host that never asks for it should not pay for it.
|
|
159
|
+
*
|
|
160
|
+
* @returns a provider the skill registry can register.
|
|
161
|
+
*/
|
|
162
|
+
function ocrSkillProvider() {
|
|
163
|
+
const path = skillPath();
|
|
164
|
+
const candidate = {
|
|
165
|
+
name: "ocr",
|
|
166
|
+
description: SKILL_DESCRIPTION,
|
|
167
|
+
summary: SKILL_SUMMARY,
|
|
168
|
+
invocation: SKILL_INVOCATION,
|
|
169
|
+
source: "bundled",
|
|
170
|
+
provider: SKILL_PROVIDER,
|
|
171
|
+
path,
|
|
172
|
+
resourceBase: {
|
|
173
|
+
kind: "directory",
|
|
174
|
+
path: dirname(path)
|
|
175
|
+
},
|
|
176
|
+
rank: 642,
|
|
177
|
+
locator: path
|
|
178
|
+
};
|
|
179
|
+
return {
|
|
180
|
+
name: SKILL_PROVIDER,
|
|
181
|
+
list: () => Promise.resolve([candidate]),
|
|
182
|
+
get: () => Promise.resolve({
|
|
183
|
+
...candidate,
|
|
184
|
+
content: readFileSync(path, "utf8")
|
|
185
|
+
})
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Read the bearer the browser gateway attached to one request.
|
|
190
|
+
*
|
|
191
|
+
* The page cannot supply its own credential: every browser request reaches this workspace
|
|
192
|
+
* through the DataOps gateway, which resolves the caller's session and forwards a fresh
|
|
193
|
+
* `authorization: Bearer <jwt>`. Relaying exactly that header is what keeps the backend's
|
|
194
|
+
* `AuthGuard` and `PermissionGuard` judging the CALLER rather than this plugin: the admin
|
|
195
|
+
* routes answer 403 for a member who is not a super administrator because the token in the
|
|
196
|
+
* header is theirs, not a service account's.
|
|
197
|
+
*
|
|
198
|
+
* @param request - the incoming request, whose headers the gateway filled in.
|
|
199
|
+
* @returns the token, or undefined when the request carries none.
|
|
200
|
+
*/
|
|
201
|
+
function bearerToken(request) {
|
|
202
|
+
const authorization = request.headers.authorization?.trim() ?? "";
|
|
203
|
+
if (!authorization.startsWith("Bearer ")) return void 0;
|
|
204
|
+
const token = authorization.slice(7).trim();
|
|
205
|
+
return token === "" ? void 0 : token;
|
|
206
|
+
}
|
|
207
|
+
/** Config schema; an invalid value fails the profile load loudly. */
|
|
208
|
+
const Config = z.object({
|
|
209
|
+
baseUrl: z.string().default(""),
|
|
210
|
+
credentialRef: z.string().role("credential-ref").default("DATAOPS_ACCESS_TOKEN"),
|
|
211
|
+
timeoutMs: z.number().default(15e3)
|
|
212
|
+
});
|
|
213
|
+
/**
|
|
214
|
+
* Resolve the token one relayed call acts with.
|
|
215
|
+
*
|
|
216
|
+
* The caller's own header wins: it is the only value that makes the backend's permission
|
|
217
|
+
* checks correct. The stored credential is the fallback for a same-origin fetch that arrived
|
|
218
|
+
* without a header (a probe, or an older page); a plugin instance without either refuses
|
|
219
|
+
* rather than calling the backend anonymously, because an anonymous call would be answered
|
|
220
|
+
* 401 by the backend anyway and the page could not tell why.
|
|
221
|
+
*
|
|
222
|
+
* @param ctx - host context carrying the credential store.
|
|
223
|
+
* @param config - relay configuration.
|
|
224
|
+
* @param request - the incoming request.
|
|
225
|
+
* @returns the token, or undefined when neither source has one.
|
|
226
|
+
*/
|
|
227
|
+
async function resolveRelayToken(ctx, config, request) {
|
|
228
|
+
const fromRequest = bearerToken(request);
|
|
229
|
+
if (fromRequest !== void 0) return fromRequest;
|
|
230
|
+
const value = (await ctx.credentials.resolve(credentialRef(config.credentialRef)).catch(() => void 0))?.value.trim() ?? "";
|
|
231
|
+
return value === "" ? void 0 : value;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Call one DataOps OCR route with the caller's authority.
|
|
235
|
+
*
|
|
236
|
+
* Kept separate from the route handler so the mapping from a page method to a backend path
|
|
237
|
+
* is testable without a server.
|
|
238
|
+
*
|
|
239
|
+
* @param method - which of the four relayed routes the page asked for.
|
|
240
|
+
* @param config - backend origin, credential fallback, and the call bound.
|
|
241
|
+
* @param token - the bearer to act with; a call without one is refused before the round trip.
|
|
242
|
+
* @param body - the JSON body, for the two write routes.
|
|
243
|
+
* @returns the backend's status and decoded body.
|
|
244
|
+
*/
|
|
245
|
+
async function callOcrBackend(method, config, token, body) {
|
|
246
|
+
if (token === void 0) return {
|
|
247
|
+
status: 401,
|
|
248
|
+
body: { error: "the request carries no DataOps session token" }
|
|
249
|
+
};
|
|
250
|
+
if (config.baseUrl.trim() === "") return {
|
|
251
|
+
status: 503,
|
|
252
|
+
body: { error: "the DataOps backend address is not configured" }
|
|
253
|
+
};
|
|
254
|
+
const route = OCR_BACKEND_ROUTES[method];
|
|
255
|
+
const url = `${config.baseUrl.trim().replace(/\/+$/u, "")}${route.path}`;
|
|
256
|
+
let response;
|
|
257
|
+
try {
|
|
258
|
+
response = await fetch(url, {
|
|
259
|
+
method: route.method,
|
|
260
|
+
headers: {
|
|
261
|
+
authorization: `Bearer ${token}`,
|
|
262
|
+
...route.method === "POST" ? { "content-type": "application/json" } : {}
|
|
263
|
+
},
|
|
264
|
+
...route.method === "POST" ? { body: JSON.stringify(body ?? {}) } : {},
|
|
265
|
+
signal: AbortSignal.timeout(config.timeoutMs)
|
|
266
|
+
});
|
|
267
|
+
} catch (cause) {
|
|
268
|
+
return {
|
|
269
|
+
status: 502,
|
|
270
|
+
body: {
|
|
271
|
+
error: `the DataOps backend is unreachable at ${url}`,
|
|
272
|
+
detail: String(cause)
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
const decoded = await response.json().catch(() => ({}));
|
|
277
|
+
return {
|
|
278
|
+
status: response.status,
|
|
279
|
+
body: decoded
|
|
280
|
+
};
|
|
281
|
+
}
|
|
282
|
+
/** Longest a single connection test may block the settings panel. */
|
|
283
|
+
const PROBE_TIMEOUT_MS = 8e3;
|
|
284
|
+
/**
|
|
285
|
+
* Probe one MinerU address from this process.
|
|
286
|
+
*
|
|
287
|
+
* The OpenAPI document is the cheapest endpoint that both proves an HTTP server answers
|
|
288
|
+
* and identifies it: MinerU titles its document "MinerU API", so a 200 with that title is
|
|
289
|
+
* a real match rather than "something is listening on this port". Any other 200 is
|
|
290
|
+
* reported as `not-mineru` -- a proxy error page or a different service are both reasons
|
|
291
|
+
* the reader should not save the address.
|
|
292
|
+
*
|
|
293
|
+
* The probe deliberately does not use the caller's DataOps credential: MinerU is not a
|
|
294
|
+
* DataOps service and has its own (usually absent) auth. It also refuses non-http(s)
|
|
295
|
+
* schemes so the relay cannot be used to read `file:` or `ftp:` URLs.
|
|
296
|
+
* @param address - the candidate base address, as typed or as stored.
|
|
297
|
+
* @param timeoutMs - the caller's relay bound; the probe is clamped to {@link PROBE_TIMEOUT_MS}.
|
|
298
|
+
* @returns a structured verdict for the settings page.
|
|
299
|
+
*/
|
|
300
|
+
async function probeMineruAddress(address, timeoutMs) {
|
|
301
|
+
const trimmed = address.trim();
|
|
302
|
+
let base;
|
|
303
|
+
try {
|
|
304
|
+
base = new URL(trimmed);
|
|
305
|
+
} catch {
|
|
306
|
+
return {
|
|
307
|
+
ok: false,
|
|
308
|
+
latencyMs: 0,
|
|
309
|
+
code: "bad-url",
|
|
310
|
+
testedUrl: trimmed
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
if (base.protocol !== "http:" && base.protocol !== "https:") return {
|
|
314
|
+
ok: false,
|
|
315
|
+
latencyMs: 0,
|
|
316
|
+
code: "bad-url",
|
|
317
|
+
testedUrl: trimmed
|
|
318
|
+
};
|
|
319
|
+
const endpoint = base.toString().replace(/\/+$/u, "") + "/openapi.json";
|
|
320
|
+
const started = Date.now();
|
|
321
|
+
try {
|
|
322
|
+
const response = await fetch(endpoint, {
|
|
323
|
+
method: "GET",
|
|
324
|
+
headers: { accept: "application/json" },
|
|
325
|
+
redirect: "manual",
|
|
326
|
+
signal: AbortSignal.timeout(Math.min(timeoutMs, PROBE_TIMEOUT_MS))
|
|
327
|
+
});
|
|
328
|
+
const latencyMs = Date.now() - started;
|
|
329
|
+
if (response.status !== 200) return {
|
|
330
|
+
ok: false,
|
|
331
|
+
latencyMs,
|
|
332
|
+
code: "http-error",
|
|
333
|
+
status: response.status,
|
|
334
|
+
testedUrl: trimmed
|
|
335
|
+
};
|
|
336
|
+
const document = await response.json().catch(() => void 0);
|
|
337
|
+
const title = typeof document?.info?.title === "string" ? document.info.title : "";
|
|
338
|
+
if (/mineru/iu.test(title)) return {
|
|
339
|
+
ok: true,
|
|
340
|
+
latencyMs,
|
|
341
|
+
code: "ok",
|
|
342
|
+
status: 200,
|
|
343
|
+
message: title,
|
|
344
|
+
testedUrl: trimmed
|
|
345
|
+
};
|
|
346
|
+
return {
|
|
347
|
+
ok: false,
|
|
348
|
+
latencyMs,
|
|
349
|
+
code: "not-mineru",
|
|
350
|
+
status: 200,
|
|
351
|
+
message: title === "" ? "the OpenAPI document has no service title" : title,
|
|
352
|
+
testedUrl: trimmed
|
|
353
|
+
};
|
|
354
|
+
} catch (cause) {
|
|
355
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
356
|
+
const code = /timeout|timed out|aborted/iu.test(message) ? "timeout" : "unreachable";
|
|
357
|
+
return {
|
|
358
|
+
ok: false,
|
|
359
|
+
latencyMs: Date.now() - started,
|
|
360
|
+
code,
|
|
361
|
+
message: message.slice(0, 300),
|
|
362
|
+
testedUrl: trimmed
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
/**
|
|
367
|
+
* Write one JSON reply.
|
|
368
|
+
*
|
|
369
|
+
* @param response - the browser-facing response.
|
|
370
|
+
* @param status - HTTP status to send.
|
|
371
|
+
* @param body - value to serialize.
|
|
372
|
+
*/
|
|
373
|
+
function writeJson(response, status, body) {
|
|
374
|
+
response.statusCode = status;
|
|
375
|
+
response.setHeader("content-type", "application/json; charset=utf-8");
|
|
376
|
+
response.setHeader("cache-control", "no-store");
|
|
377
|
+
response.end(JSON.stringify(body));
|
|
378
|
+
}
|
|
379
|
+
/**
|
|
380
|
+
* Read a JSON request body, treating an empty body as `{}`.
|
|
381
|
+
*
|
|
382
|
+
* @param request - the incoming request.
|
|
383
|
+
* @returns the parsed object.
|
|
384
|
+
*/
|
|
385
|
+
async function readJsonBody(request) {
|
|
386
|
+
return await new Promise((resolve, reject) => {
|
|
387
|
+
const chunks = [];
|
|
388
|
+
request.on("data", (chunk) => {
|
|
389
|
+
chunks.push(chunk);
|
|
390
|
+
});
|
|
391
|
+
request.on("end", () => {
|
|
392
|
+
const text = Buffer.concat(chunks).toString("utf8").trim();
|
|
393
|
+
if (text === "") return resolve({});
|
|
394
|
+
try {
|
|
395
|
+
resolve(JSON.parse(text));
|
|
396
|
+
} catch (error) {
|
|
397
|
+
reject(new Error("request body is not valid JSON", { cause: error }));
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
request.on("error", reject);
|
|
401
|
+
});
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Answer one `test-connection` request.
|
|
405
|
+
*
|
|
406
|
+
* The stored config is read through the backend first, for two reasons that are really
|
|
407
|
+
* one: the backend is the authority on whether this caller may change the address, and a
|
|
408
|
+
* caller who may not change it must not be able to make this process fetch an arbitrary
|
|
409
|
+
* URL. A super administrator may test the value they are about to save; everyone else
|
|
410
|
+
* tests the shared value.
|
|
411
|
+
* @param ctx - the host context, for the caller's token.
|
|
412
|
+
* @param config - backend origin and probe bound.
|
|
413
|
+
* @param request - the browser request, whose body may carry a candidate address.
|
|
414
|
+
* @param response - the reply.
|
|
415
|
+
*/
|
|
416
|
+
async function answerConnectionTest(ctx, config, request, response) {
|
|
417
|
+
const token = await resolveRelayToken(ctx, config, request);
|
|
418
|
+
if (token === void 0) {
|
|
419
|
+
writeJson(response, 401, { error: "the request carries no DataOps session token" });
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
const current = await callOcrBackend("config", config, token);
|
|
423
|
+
if (current.status !== 200) {
|
|
424
|
+
writeJson(response, 503, {
|
|
425
|
+
error: "the caller role could not be checked against the DataOps backend",
|
|
426
|
+
detail: current.body
|
|
427
|
+
});
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
const view = current.body;
|
|
431
|
+
const stored = typeof view.mineruUrl === "string" ? view.mineruUrl : "";
|
|
432
|
+
const body = await readJsonBody(request);
|
|
433
|
+
const candidate = typeof body.mineruUrl === "string" ? body.mineruUrl.trim() : "";
|
|
434
|
+
writeJson(response, 200, await probeMineruAddress(view.canEdit === true && candidate !== "" ? candidate : stored, config.timeoutMs));
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Mount the skill provider and the settings relay on a host context.
|
|
438
|
+
*
|
|
439
|
+
* `inject` rather than a hard dependency entry, and the `typeof` guard around it, are both
|
|
440
|
+
* copied from `@sparkelf/dsh-knowledge-base`: the skill registry is an optional neighbour, and
|
|
441
|
+
* calling `inject` on a host that does not expose it would throw during apply and take the
|
|
442
|
+
* whole plugin down.
|
|
443
|
+
*
|
|
444
|
+
* @param host - the plugin context.
|
|
445
|
+
* @param resolvedConfig - backend origin, credential fallback, and call bound.
|
|
446
|
+
*/
|
|
447
|
+
function apply(host, resolvedConfig) {
|
|
448
|
+
if (host === null || host === void 0) return;
|
|
449
|
+
const ctx = host;
|
|
450
|
+
const hostWithInject = ctx;
|
|
451
|
+
if (typeof hostWithInject.inject === "function") hostWithInject.inject(["skills"], (scoped) => {
|
|
452
|
+
scoped.skills.registerProvider(() => ocrSkillProvider());
|
|
453
|
+
});
|
|
454
|
+
if (ctx.webServer === void 0 || ctx.credentials === void 0 || typeof ctx.effect !== "function") return;
|
|
455
|
+
const config = {
|
|
456
|
+
baseUrl: resolvedConfig?.baseUrl ?? "",
|
|
457
|
+
credentialRef: resolvedConfig?.credentialRef ?? "DATAOPS_ACCESS_TOKEN",
|
|
458
|
+
timeoutMs: resolvedConfig?.timeoutMs ?? 15e3
|
|
459
|
+
};
|
|
460
|
+
ctx.effect(() => ctx.webServer.register({
|
|
461
|
+
kind: "prefix",
|
|
462
|
+
path: OCR_API_PREFIX,
|
|
463
|
+
handler: async (request, response) => {
|
|
464
|
+
const method = new URL(request.url ?? "/", "http://dsh.internal").pathname.slice(`${OCR_API_PREFIX}/`.length);
|
|
465
|
+
try {
|
|
466
|
+
if (method === OCR_API.testConnection) {
|
|
467
|
+
await answerConnectionTest(ctx, config, request, response);
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
const route = OCR_BACKEND_ROUTES[method];
|
|
471
|
+
if (route === void 0) {
|
|
472
|
+
writeJson(response, 404, { error: `unknown document-recognition method: ${method}` });
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
const token = await resolveRelayToken(ctx, config, request);
|
|
476
|
+
const body = route.method === "POST" ? await readJsonBody(request) : void 0;
|
|
477
|
+
const result = await callOcrBackend(method, config, token, body);
|
|
478
|
+
writeJson(response, result.status, result.body);
|
|
479
|
+
} catch (error) {
|
|
480
|
+
ctx.logger?.warn?.("dsh-ocr: settings relay failed");
|
|
481
|
+
ctx.logger?.warn?.(error);
|
|
482
|
+
writeJson(response, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
}), "dsh-ocr: settings relay");
|
|
486
|
+
}
|
|
487
|
+
//#endregion
|
|
488
|
+
export { Config, OCR_BACKEND_ROUTES, PLUGIN_NAME, PROBE_TIMEOUT_MS, SKILL_DESCRIPTION, SKILL_DISPLAY_NAME, SKILL_INVOCATION, SKILL_NAME, SKILL_PROVIDER, SKILL_RANK, SKILL_SUMMARY, answerConnectionTest, apply, bearerToken, callOcrBackend, inject, ocrSkillProvider, probeMineruAddress, readJsonBody, resolveRelayToken, skillPath, writeJson };
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The same-origin API surface shared by this package's two halves.
|
|
3
|
+
*
|
|
4
|
+
* The Host registers one prefix and dispatches on the trailing method name; the browser
|
|
5
|
+
* calls the same strings. Keeping them in one module is what stops the two halves
|
|
6
|
+
* drifting apart -- the failure mode knowledge-base recorded when its panel called
|
|
7
|
+
* `/knowledge-base/config` while its Host served `/knowledge-base/api/config`.
|
|
8
|
+
*
|
|
9
|
+
* The namespace is `ocr` rather than a shared one, so this route can never collide with
|
|
10
|
+
* the knowledge base's `/knowledge-base/api/*` or any other plugin's prefix.
|
|
11
|
+
*
|
|
12
|
+
* This module must stay dependency-free so both bundles can import it: the Client bundle
|
|
13
|
+
* rejects Node builtins and non-platform packages.
|
|
14
|
+
*
|
|
15
|
+
* @module @sparkelf/dsh-ocr/api
|
|
16
|
+
*/
|
|
17
|
+
/** Prefix the Host registers and the browser calls. */
|
|
18
|
+
export declare const OCR_API_PREFIX = "/ocr/api";
|
|
19
|
+
/** Method names the Host dispatches on. */
|
|
20
|
+
export declare const OCR_API: {
|
|
21
|
+
/** The shared MinerU address plus whether the caller may change it. */
|
|
22
|
+
readonly config: "config";
|
|
23
|
+
/** How many members a distribution reaches, and how many it would replace. */
|
|
24
|
+
readonly impact: "impact";
|
|
25
|
+
/** Fill only members that hold no address of their own. */
|
|
26
|
+
readonly distributeDefault: "distribute-default";
|
|
27
|
+
/** Replace every member's address, including ones they chose themselves. */
|
|
28
|
+
readonly overwrite: "overwrite";
|
|
29
|
+
/**
|
|
30
|
+
* Probe a MinerU address before saving it.
|
|
31
|
+
*
|
|
32
|
+
* Not a backend route: the Host answers this one itself, because only this process can
|
|
33
|
+
* reach the address from inside the workspace network. It still reads the stored config
|
|
34
|
+
* through the backend first, so a caller who may not edit cannot make the relay fetch an
|
|
35
|
+
* arbitrary URL.
|
|
36
|
+
*/
|
|
37
|
+
readonly testConnection: "test-connection";
|
|
38
|
+
};
|
|
39
|
+
/** One valid method name. */
|
|
40
|
+
export type OcrApiMethod = typeof OCR_API[keyof typeof OCR_API];
|
|
41
|
+
/**
|
|
42
|
+
* Build the browser path for one method.
|
|
43
|
+
* @param method - one of {@link OCR_API}.
|
|
44
|
+
* @returns the same-origin path the Host dispatches on.
|
|
45
|
+
*/
|
|
46
|
+
export declare function ocrApiPath(method: OcrApiMethod): string;
|
|
47
|
+
/**
|
|
48
|
+
* The shared configuration as the settings page reads it.
|
|
49
|
+
*
|
|
50
|
+
* `mineruUrl === ''` is "not configured yet", not an error: a deployment is allowed to
|
|
51
|
+
* have never had an OCR address. `canEdit` decides between two renderings of the same
|
|
52
|
+
* page and never whether the address may be USED -- every signed-in member can recognize
|
|
53
|
+
* documents with the shared value.
|
|
54
|
+
*/
|
|
55
|
+
export interface OcrConfigView {
|
|
56
|
+
/** The shared MinerU base address, or `''` when none is stored. */
|
|
57
|
+
mineruUrl: string;
|
|
58
|
+
/** Whether the caller holds the one role this deployment lets change the shared value. */
|
|
59
|
+
canEdit: boolean;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* How many members a distribution reaches.
|
|
63
|
+
*
|
|
64
|
+
* `withValue` is what an overwrite would replace while `onlyIfEmpty` would skip it, so
|
|
65
|
+
* the confirmation can name the number it is about to disturb instead of asking "are you
|
|
66
|
+
* sure?" with no quantity.
|
|
67
|
+
*/
|
|
68
|
+
export interface OcrImpactView {
|
|
69
|
+
/** Members who already hold an address of their own. */
|
|
70
|
+
withValue: number;
|
|
71
|
+
/** Members who hold none; `onlyIfEmpty` fills exactly these. */
|
|
72
|
+
withoutValue: number;
|
|
73
|
+
/** Every member the distribution considers. */
|
|
74
|
+
total: number;
|
|
75
|
+
}
|
|
76
|
+
/** Per-bucket counts one distribution reports back. */
|
|
77
|
+
export interface OcrDistributionView {
|
|
78
|
+
/** `onlyIfEmpty` or `force`, as the backend names the two modes. */
|
|
79
|
+
mode?: string;
|
|
80
|
+
/** Members written. */
|
|
81
|
+
filled: number;
|
|
82
|
+
/** Members left alone. */
|
|
83
|
+
skipped: number;
|
|
84
|
+
/** Members whose write failed. */
|
|
85
|
+
failed: number;
|
|
86
|
+
/** Every member considered. */
|
|
87
|
+
total: number;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* A refusal the page must show rather than swallow.
|
|
91
|
+
*
|
|
92
|
+
* The two write routes answer 400 for an empty address and 403 for a caller without the
|
|
93
|
+
* role. Both are decisions, so the page reports them instead of retrying.
|
|
94
|
+
*/
|
|
95
|
+
export interface OcrErrorView {
|
|
96
|
+
/** The backend's own message, already in the reader's language. */
|
|
97
|
+
error: string;
|
|
98
|
+
}
|
|
99
|
+
/** Why a probe ended as it did. The page maps these codes to locale copy. */
|
|
100
|
+
export type OcrProbeCode =
|
|
101
|
+
/** The address answered as a MinerU service. */
|
|
102
|
+
'ok'
|
|
103
|
+
/** Not an absolute http(s) address, so there is nothing to call. */
|
|
104
|
+
| 'bad-url'
|
|
105
|
+
/** No answer inside the probe window. */
|
|
106
|
+
| 'timeout'
|
|
107
|
+
/** The connection was refused, DNS failed, or the host is unreachable. */
|
|
108
|
+
| 'unreachable'
|
|
109
|
+
/** An HTTP server answered, but its OpenAPI document is not MinerU's. */
|
|
110
|
+
| 'not-mineru'
|
|
111
|
+
/** The service answered with a non-2xx status. */
|
|
112
|
+
| 'http-error';
|
|
113
|
+
/**
|
|
114
|
+
* What a connection test reports.
|
|
115
|
+
*
|
|
116
|
+
* `latencyMs` is measured around the probe request, not the whole redirect chain: a
|
|
117
|
+
* number that included the backend round trip would blame the MinerU box for the relay's
|
|
118
|
+
* latency. `testedUrl` is echoed because the caller may have typed a candidate before
|
|
119
|
+
* saving, and the panel has to label which address the tag refers to.
|
|
120
|
+
*/
|
|
121
|
+
export interface OcrProbeView {
|
|
122
|
+
/** Whether the address is a reachable MinerU service. */
|
|
123
|
+
ok: boolean;
|
|
124
|
+
/** Round-trip time of the probe request, in milliseconds. */
|
|
125
|
+
latencyMs: number;
|
|
126
|
+
/** Machine-readable outcome. */
|
|
127
|
+
code: OcrProbeCode;
|
|
128
|
+
/** The address that was actually tested. */
|
|
129
|
+
testedUrl: string;
|
|
130
|
+
/** HTTP status when a response arrived. */
|
|
131
|
+
status?: number;
|
|
132
|
+
/** A short technical detail, for the tooltip and the operator. */
|
|
133
|
+
message?: string;
|
|
134
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The 「文档识别」 settings section.
|
|
3
|
+
*
|
|
4
|
+
* Three actions, and they are genuinely different:
|
|
5
|
+
*
|
|
6
|
+
* - **Test connection** probes the address in the field without saving it. It is the only
|
|
7
|
+
* way to answer "is this address right?" before distributing it to every member.
|
|
8
|
+
* - **Distribute** fills members who hold no address of their own. Nobody's own choice is
|
|
9
|
+
* touched, so it is the safe default.
|
|
10
|
+
* - **Overwrite** replaces every member's address, including one they typed themselves.
|
|
11
|
+
*
|
|
12
|
+
* Both writes are gated on `canEdit`, which the backend answers from the caller's role.
|
|
13
|
+
* The write routes enforce that independently: hiding a button is not a permission, so a
|
|
14
|
+
* caller who forges the request is refused by the backend rather than by this page.
|
|
15
|
+
*
|
|
16
|
+
* The section deliberately carries no explanatory prose: a settings page states the field
|
|
17
|
+
* and its state, and the reader who needs the story has the skill document. The connection
|
|
18
|
+
* tag inside the field is the whole status surface.
|
|
19
|
+
*
|
|
20
|
+
* @module @sparkelf/dsh-ocr/client/SettingsSection
|
|
21
|
+
*/
|
|
22
|
+
import type { InjectFace } from '@deepseek-ai/dsh-client-ui-slots';
|
|
23
|
+
import type { en } from './locales.ts';
|
|
24
|
+
/** Values the Settings slot injects into this component. */
|
|
25
|
+
export interface OcrSettingsInjected {
|
|
26
|
+
/** Translate one section message key. */
|
|
27
|
+
t: (key: keyof typeof en) => string;
|
|
28
|
+
}
|
|
29
|
+
/** Props accepted by the injected Settings section. */
|
|
30
|
+
export type OcrSettingsProps = Partial<InjectFace<OcrSettingsInjected>>;
|
|
31
|
+
/**
|
|
32
|
+
* Whether a candidate is an absolute http(s) address.
|
|
33
|
+
*
|
|
34
|
+
* Mirrors the backend's own normaliser, and is checked before the round trip so the answer
|
|
35
|
+
* lands beside the field that was typed into rather than after a request that was always
|
|
36
|
+
* going to be refused. The path is preserved: a MinerU service may sit behind a prefix.
|
|
37
|
+
*
|
|
38
|
+
* @param value - the address as typed.
|
|
39
|
+
* @returns true when it parses and carries an http(s) scheme.
|
|
40
|
+
*/
|
|
41
|
+
export declare function isAbsoluteHttpAddress(value: string): boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Render the document-recognition settings section.
|
|
44
|
+
* @param props - the Settings slot injection.
|
|
45
|
+
* @returns the section, or nothing before injection.
|
|
46
|
+
*/
|
|
47
|
+
export declare function OcrSettingsSection(props: OcrSettingsProps): import("react").JSX.Element | null;
|