plugin-document-understanding 1.1.11 → 1.1.13

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.
Files changed (36) hide show
  1. package/dist/client/345.e6e484fb1974c3d3.js +10 -0
  2. package/dist/client/index.js +1 -1
  3. package/dist/client-v2/345.a8f28526ac21e02a.js +10 -0
  4. package/dist/client-v2/index.js +1 -1
  5. package/dist/externalVersion.js +7 -7
  6. package/dist/locale/en-US.json +182 -171
  7. package/dist/locale/vi-VN.json +182 -171
  8. package/dist/locale/zh-CN.json +182 -171
  9. package/dist/node_modules/form-data/lib/form_data.js +3 -3
  10. package/dist/node_modules/form-data/package.json +1 -1
  11. package/dist/server/collections/endpoints.js +5 -0
  12. package/dist/server/collections/jobs.js +13 -0
  13. package/dist/server/dugate-seed.js +411 -0
  14. package/dist/server/plugin.js +6 -0
  15. package/dist/server/services/AsyncJobManager.js +87 -31
  16. package/dist/server/services/DocumentUnderstandingService.js +48 -5
  17. package/dist/server/services/ExternalApiClient.js +38 -5
  18. package/dist/server/services/PipelineExecutor.js +115 -36
  19. package/package.json +1 -1
  20. package/src/client-v2/components/EndpointsTab.tsx +51 -0
  21. package/src/locale/en-US.json +182 -171
  22. package/src/locale/vi-VN.json +182 -171
  23. package/src/locale/zh-CN.json +182 -171
  24. package/src/server/__tests__/cluster-safety.test.ts +259 -0
  25. package/src/server/__tests__/dugate-integration.test.ts +221 -0
  26. package/src/server/collections/endpoints.ts +5 -0
  27. package/src/server/collections/jobs.ts +13 -0
  28. package/src/server/dugate-seed.ts +491 -0
  29. package/src/server/plugin.ts +143 -134
  30. package/src/server/services/AsyncJobManager.ts +98 -32
  31. package/src/server/services/DocumentUnderstandingService.ts +50 -4
  32. package/src/server/services/ExternalApiClient.ts +40 -5
  33. package/src/server/services/PipelineExecutor.ts +593 -477
  34. package/src/server/types.ts +90 -78
  35. package/dist/client/345.17f88ffb846ec69b.js +0 -10
  36. package/dist/client-v2/345.1e0c321d30702aa1.js +0 -10
@@ -1 +1 @@
1
- {"author":"Felix Geisendörfer <felix@debuggable.com> (http://debuggable.com/)","name":"form-data","description":"A library to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.","version":"4.0.5","repository":{"type":"git","url":"git://github.com/form-data/form-data.git"},"main":"./lib/form_data","browser":"./lib/browser","typings":"./index.d.ts","scripts":{"pretest":"npm run lint","pretests-only":"rimraf coverage test/tmp","tests-only":"istanbul cover test/run.js","posttests-only":"istanbul report lcov text","test":"npm run tests-only","posttest":"npx npm@'>=10.2' audit --production","lint":"eslint --ext=js,mjs .","report":"istanbul report lcov text","ci-lint":"is-node-modern 8 && npm run lint || is-node-not-modern 8","ci-test":"npm run tests-only && npm run browser && npm run report","predebug":"rimraf coverage test/tmp","debug":"verbose=1 ./test/run.js","browser":"browserify -t browserify-istanbul test/run-browser.js | obake --coverage","check":"istanbul check-coverage coverage/coverage*.json","files":"pkgfiles --sort=name","get-version":"node -e \"console.log(require('./package.json').version)\"","update-readme":"sed -i.bak 's/\\/master\\.svg/\\/v'$(npm --silent run get-version)'.svg/g' README.md","postupdate-readme":"mv README.md.bak READ.ME.md.bak","restore-readme":"mv READ.ME.md.bak README.md","prepublish":"not-in-publish || npm run prepublishOnly","prepack":"npm run update-readme","postpack":"npm run restore-readme","version":"auto-changelog && git add CHANGELOG.md","postversion":"auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""},"engines":{"node":">= 6"},"dependencies":{"asynckit":"^0.4.0","combined-stream":"^1.0.8","es-set-tostringtag":"^2.1.0","hasown":"^2.0.2","mime-types":"^2.1.12"},"devDependencies":{"@ljharb/eslint-config":"^21.4.0","auto-changelog":"^2.5.0","browserify":"^13.3.0","browserify-istanbul":"^2.0.0","coveralls":"^3.1.1","cross-spawn":"^6.0.6","eslint":"^8.57.1","fake":"^0.2.2","far":"^0.0.7","formidable":"^1.2.6","in-publish":"^2.0.1","is-node-modern":"^1.0.0","istanbul":"^0.4.5","js-randomness-predictor":"^1.5.5","obake":"^0.1.2","pkgfiles":"^2.3.2","pre-commit":"^1.2.2","puppeteer":"^1.20.0","request":"~2.87.0","rimraf":"^2.7.1","semver":"^6.3.1","tape":"^5.9.0"},"license":"MIT","auto-changelog":{"output":"CHANGELOG.md","template":"keepachangelog","unreleased":false,"commitLimit":false,"backfillLimit":false,"hideCredit":true},"_lastModified":"2026-04-09T17:58:37.184Z"}
1
+ {"author":"Felix Geisendörfer <felix@debuggable.com> (http://debuggable.com/)","name":"form-data","description":"A library to create readable \"multipart/form-data\" streams. Can be used to submit forms and file uploads to other web applications.","version":"4.0.6","repository":{"type":"git","url":"git://github.com/form-data/form-data.git"},"main":"./lib/form_data","browser":"./lib/browser","typings":"./index.d.ts","scripts":{"pretest":"npm run lint","pretests-only":"rimraf coverage test/tmp","tests-only":"istanbul cover test/run.js","posttests-only":"istanbul report lcov text","test":"npm run tests-only","posttest":"npx npm@'>=10.2' audit --production","lint":"eslint --ext=js,mjs .","report":"istanbul report lcov text","ci-lint":"is-node-modern 8 && npm run lint || is-node-not-modern 8","ci-test":"npm run tests-only && npm run browser && npm run report","predebug":"rimraf coverage test/tmp","debug":"verbose=1 ./test/run.js","browser":"browserify -t browserify-istanbul test/run-browser.js | obake --coverage","check":"istanbul check-coverage coverage/coverage*.json","files":"pkgfiles --sort=name","get-version":"node -e \"console.log(require('./package.json').version)\"","update-readme":"sed -i.bak 's/\\/master\\.svg/\\/v'$(npm --silent run get-version)'.svg/g' README.md","postupdate-readme":"mv README.md.bak READ.ME.md.bak","restore-readme":"mv READ.ME.md.bak README.md","prepublish":"not-in-publish || npm run prepublishOnly","prepack":"npm run update-readme","postpack":"npm run restore-readme","version":"auto-changelog && git add CHANGELOG.md","postversion":"auto-changelog && git add CHANGELOG.md && git commit --no-edit --amend && git tag -f \"v$(node -e \"console.log(require('./package.json').version)\")\""},"engines":{"node":">= 6"},"dependencies":{"asynckit":"^0.4.0","combined-stream":"^1.0.8","es-set-tostringtag":"^2.1.0","hasown":"^2.0.4","mime-types":"^2.1.35"},"devDependencies":{"@ljharb/eslint-config":"^22.2.3","auto-changelog":"^2.6.0","browserify":"^13.3.0","browserify-istanbul":"^2.0.0","coveralls":"^3.1.1","cross-spawn":"^6.0.6","eslint":"^8.57.1","fake":"^0.2.2","far":"^0.0.7","formidable":"^1.2.6","in-publish":"^2.0.1","is-node-modern":"^1.0.0","istanbul":"^0.4.5","js-randomness-predictor":"^3.6.0","obake":"^0.1.2","pkgfiles":"^2.3.2","pre-commit":"^1.2.2","puppeteer":"^1.20.0","request":"~2.87.0","rimraf":"^2.7.1","semver":"^6.3.1","tape":"^5.10.1"},"license":"MIT","auto-changelog":{"output":"CHANGELOG.md","template":"keepachangelog","unreleased":false,"commitLimit":false,"backfillLimit":false,"hideCredit":true},"_lastModified":"2026-08-17T10:39:36.887Z"}
@@ -43,6 +43,11 @@ var endpoints_default = {
43
43
  { type: "string", name: "fileFieldName", length: 100, defaultValue: "file" },
44
44
  { type: "integer", name: "maxFiles", defaultValue: 1 },
45
45
  { type: "string", name: "executionMode", length: 20 },
46
+ { type: "string", name: "discriminatorField", length: 50 },
47
+ { type: "string", name: "discriminatorValue", length: 100 },
48
+ { type: "string", name: "syncQueryParam", length: 50 },
49
+ { type: "string", name: "taskIdExtractPath", length: 200 },
50
+ { type: "string", name: "taskIdExtractRegex", length: 200 },
46
51
  { type: "string", name: "pollResultSubpath", length: 500 },
47
52
  { type: "string", name: "pollTaskIdField", length: 100, defaultValue: "task_id" },
48
53
  { type: "string", name: "pollResultField", length: 100 },
@@ -48,11 +48,24 @@ var jobs_default = {
48
48
  { type: "json", name: "externalTaskIds" },
49
49
  { type: "date", name: "startedAt" },
50
50
  { type: "date", name: "completedAt" },
51
+ // Cluster ownership: which node is executing/polling this job, and until when
52
+ // its lease is valid. Orphaned jobs (owner restarted or lease expired) are
53
+ // failed or re-adopted by the maintenance sweep.
54
+ { type: "string", name: "ownedBy", length: 255 },
55
+ { type: "date", name: "leaseExpiresAt" },
51
56
  {
52
57
  type: "belongsTo",
53
58
  name: "createdBy",
54
59
  target: "users",
55
60
  foreignKey: "createdById"
56
61
  }
62
+ ],
63
+ indexes: [
64
+ {
65
+ fields: ["status"]
66
+ },
67
+ {
68
+ fields: ["leaseExpiresAt"]
69
+ }
57
70
  ]
58
71
  };
@@ -0,0 +1,411 @@
1
+ /**
2
+ * This file is part of the NocoBase (R) project.
3
+ * Copyright (c) 2020-2024 NocoBase Co., Ltd.
4
+ * Authors: NocoBase Team.
5
+ *
6
+ * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
7
+ * For more information, please refer to: https://www.nocobase.com/agreement.
8
+ */
9
+
10
+ var __defProp = Object.defineProperty;
11
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
12
+ var __getOwnPropNames = Object.getOwnPropertyNames;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __export = (target, all) => {
15
+ for (var name in all)
16
+ __defProp(target, name, { get: all[name], enumerable: true });
17
+ };
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") {
20
+ for (let key of __getOwnPropNames(from))
21
+ if (!__hasOwnProp.call(to, key) && key !== except)
22
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
23
+ }
24
+ return to;
25
+ };
26
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
+ var dugate_seed_exports = {};
28
+ __export(dugate_seed_exports, {
29
+ seedDugateEndpoints: () => seedDugateEndpoints
30
+ });
31
+ module.exports = __toCommonJS(dugate_seed_exports);
32
+ const DEFAULT_POLL_INTERVAL = 3e3;
33
+ const DEFAULT_POLL_TIMEOUT = 3e5;
34
+ const asyncConfig = {
35
+ taskIdExtractPath: "name",
36
+ taskIdExtractRegex: "operations/([^/]+)",
37
+ pollResultSubpath: "/api/v1/operations/{taskId}",
38
+ pollTaskIdField: "id",
39
+ pollResultField: "result",
40
+ pollStatusField: "metadata.state",
41
+ pollCompletedValue: "SUCCEEDED",
42
+ pollInterval: DEFAULT_POLL_INTERVAL,
43
+ pollTimeout: DEFAULT_POLL_TIMEOUT
44
+ };
45
+ function coreEndpoint(service, discriminatorValue, overrides) {
46
+ const { name, ...rest } = overrides;
47
+ return {
48
+ name,
49
+ subpath: `/api/v1/docs/${service}`,
50
+ method: "POST",
51
+ fileInputMode: "multipart",
52
+ fileFieldName: "files[]",
53
+ maxFiles: 10,
54
+ executionMode: "sync",
55
+ discriminatorField: discriminatorValue === "diff" || discriminatorValue === "semantic" || discriminatorValue === "version" ? "mode" : ["parse", "ocr", "digitize", "split"].includes(discriminatorValue) ? "mode" : ["invoice", "contract", "id-card", "receipt", "table", "custom"].includes(discriminatorValue) ? "type" : ["classify", "sentiment", "compliance", "fact-check", "quality", "risk", "summarize-eval"].includes(
56
+ discriminatorValue
57
+ ) ? "task" : ["convert", "translate", "rewrite", "redact", "template"].includes(discriminatorValue) ? "action" : "mode",
58
+ discriminatorValue,
59
+ syncQueryParam: "sync",
60
+ ...asyncConfig,
61
+ ...rest
62
+ };
63
+ }
64
+ function workflowEndpoint(process, overrides) {
65
+ const { name, ...rest } = overrides;
66
+ return {
67
+ name,
68
+ subpath: "/api/v1/docs/workflows",
69
+ method: "POST",
70
+ fileInputMode: "multipart",
71
+ fileFieldName: "files[]",
72
+ maxFiles: 10,
73
+ executionMode: "sync",
74
+ // Will detect 202 and switch to polling automatically
75
+ discriminatorField: "process",
76
+ discriminatorValue: process,
77
+ syncQueryParam: "sync",
78
+ ...asyncConfig,
79
+ ...rest
80
+ };
81
+ }
82
+ const CORE_ENDPOINTS = [
83
+ // ── ingest ──
84
+ coreEndpoint("ingest", "parse", {
85
+ name: "dugate-ingest-parse",
86
+ description: "Parse digital documents (PDF/DOCX native), preserve headers, footers, tables. Supports output_format (md/json/html/csv) and language.",
87
+ fileFieldName: "files[]",
88
+ maxFiles: 5
89
+ }),
90
+ coreEndpoint("ingest", "ocr", {
91
+ name: "dugate-ingest-ocr",
92
+ description: "OCR scanned documents and images. Supports language parameter.",
93
+ fileFieldName: "files[]",
94
+ maxFiles: 5
95
+ }),
96
+ coreEndpoint("ingest", "digitize", {
97
+ name: "dugate-ingest-digitize",
98
+ description: "Digitize handwritten forms, checkboxes.",
99
+ fileFieldName: "files[]",
100
+ maxFiles: 5
101
+ }),
102
+ coreEndpoint("ingest", "split", {
103
+ name: "dugate-ingest-split",
104
+ description: 'Split/merge PDF pages. Use pages parameter (e.g. "1-5").',
105
+ fileFieldName: "file",
106
+ maxFiles: 1
107
+ }),
108
+ // ── extract ──
109
+ coreEndpoint("extract", "invoice", {
110
+ name: "dugate-extract-invoice",
111
+ description: "Extract structured data from Vietnamese VAT invoices / general invoices.",
112
+ fileFieldName: "files[]",
113
+ maxFiles: 5
114
+ }),
115
+ coreEndpoint("extract", "contract", {
116
+ name: "dugate-extract-contract",
117
+ description: "Extract parties, terms, obligations, penalties, signatures from contracts.",
118
+ fileFieldName: "files[]",
119
+ maxFiles: 5
120
+ }),
121
+ coreEndpoint("extract", "id-card", {
122
+ name: "dugate-extract-id-card",
123
+ description: "Extract identity information from CCCD/Passport.",
124
+ fileFieldName: "files[]",
125
+ maxFiles: 5
126
+ }),
127
+ coreEndpoint("extract", "receipt", {
128
+ name: "dugate-extract-receipt",
129
+ description: "Extract merchant, items, totals from receipts.",
130
+ fileFieldName: "files[]",
131
+ maxFiles: 5
132
+ }),
133
+ coreEndpoint("extract", "table", {
134
+ name: "dugate-extract-table",
135
+ description: "Extract all tables from documents as structured data.",
136
+ fileFieldName: "files[]",
137
+ maxFiles: 5
138
+ }),
139
+ coreEndpoint("extract", "custom", {
140
+ name: "dugate-extract-custom",
141
+ description: "Extract custom fields using dynamic schema. Use fields (comma-separated) or schema (JSON Schema string).",
142
+ fileFieldName: "files[]",
143
+ maxFiles: 5
144
+ }),
145
+ // ── analyze ──
146
+ coreEndpoint("analyze", "classify", {
147
+ name: "dugate-analyze-classify",
148
+ description: "Classify documents by taxonomy. Provide categories parameter.",
149
+ maxFiles: 5
150
+ }),
151
+ coreEndpoint("analyze", "sentiment", {
152
+ name: "dugate-analyze-sentiment",
153
+ description: "Analyze document sentiment: positive, negative, neutral.",
154
+ maxFiles: 5
155
+ }),
156
+ coreEndpoint("analyze", "compliance", {
157
+ name: "dugate-analyze-compliance",
158
+ description: "Check document compliance against criteria. Provide criteria parameter (semicolon-separated rules).",
159
+ maxFiles: 5
160
+ }),
161
+ coreEndpoint("analyze", "fact-check", {
162
+ name: "dugate-analyze-fact-check",
163
+ description: "Cross-reference document claims against reference data. Provide reference_data and extract_fields.",
164
+ maxFiles: 5
165
+ }),
166
+ coreEndpoint("analyze", "quality", {
167
+ name: "dugate-analyze-quality",
168
+ description: "Score document writing quality against criteria.",
169
+ maxFiles: 5
170
+ }),
171
+ coreEndpoint("analyze", "risk", {
172
+ name: "dugate-analyze-risk",
173
+ description: "Assess document risk level.",
174
+ maxFiles: 5
175
+ }),
176
+ coreEndpoint("analyze", "summarize-eval", {
177
+ name: "dugate-analyze-summarize-eval",
178
+ description: "Generate expert summary and evaluation of document.",
179
+ maxFiles: 5
180
+ }),
181
+ // ── transform ──
182
+ coreEndpoint("transform", "convert", {
183
+ name: "dugate-transform-convert",
184
+ description: "Convert document format (DOCX -> MD/HTML). Use output_format parameter.",
185
+ fileFieldName: "file",
186
+ maxFiles: 1
187
+ }),
188
+ coreEndpoint("transform", "translate", {
189
+ name: "dugate-transform-translate",
190
+ description: "Translate document to target language. Use target_language and tone parameters.",
191
+ fileFieldName: "file",
192
+ maxFiles: 1
193
+ }),
194
+ coreEndpoint("transform", "rewrite", {
195
+ name: "dugate-transform-rewrite",
196
+ description: "Rewrite/paraphrase document. Use style (academic/executive/simplified/bullet_points) and tone parameters.",
197
+ fileFieldName: "file",
198
+ maxFiles: 1
199
+ }),
200
+ coreEndpoint("transform", "redact", {
201
+ name: "dugate-transform-redact",
202
+ description: "Redact PII from document. Use redact_patterns parameter.",
203
+ fileFieldName: "file",
204
+ maxFiles: 1
205
+ }),
206
+ coreEndpoint("transform", "template", {
207
+ name: "dugate-transform-template",
208
+ description: "Mail merge using template. Use template parameter (JSON).",
209
+ fileFieldName: "file",
210
+ maxFiles: 1
211
+ }),
212
+ // ── generate ──
213
+ coreEndpoint("generate", "summary", {
214
+ name: "dugate-generate-summary",
215
+ description: "Generate condensed summary. Parameters: format (paragraph/bullets/numbered/table/mind_map), max_words, audience.",
216
+ fileFieldName: "files[]",
217
+ maxFiles: 5
218
+ }),
219
+ coreEndpoint("generate", "outline", {
220
+ name: "dugate-generate-outline",
221
+ description: "Extract H1/H2/H3 table of contents.",
222
+ fileFieldName: "files[]",
223
+ maxFiles: 5
224
+ }),
225
+ coreEndpoint("generate", "report", {
226
+ name: "dugate-generate-report",
227
+ description: "Generate expert analysis report.",
228
+ fileFieldName: "files[]",
229
+ maxFiles: 5
230
+ }),
231
+ coreEndpoint("generate", "email", {
232
+ name: "dugate-generate-email",
233
+ description: "Draft email response based on document. Use tone parameter.",
234
+ fileFieldName: "files[]",
235
+ maxFiles: 5
236
+ }),
237
+ coreEndpoint("generate", "minutes", {
238
+ name: "dugate-generate-minutes",
239
+ description: "Generate meeting minutes with action items. Use format parameter.",
240
+ fileFieldName: "files[]",
241
+ maxFiles: 5
242
+ }),
243
+ coreEndpoint("generate", "qa", {
244
+ name: "dugate-generate-qa",
245
+ description: "Ask questions about document content (RAG-like). Use questions parameter (JSON array).",
246
+ fileFieldName: "files[]",
247
+ maxFiles: 5
248
+ }),
249
+ // ── compare ──
250
+ coreEndpoint("compare", "diff", {
251
+ name: "dugate-compare-diff",
252
+ description: "Line-by-line text diff (git-diff style). Requires 2 files via files[]. Use output_format parameter.",
253
+ fileFieldName: "files[]",
254
+ maxFiles: 2
255
+ }),
256
+ coreEndpoint("compare", "semantic", {
257
+ name: "dugate-compare-semantic",
258
+ description: "Semantic/legal comparison. Requires 2 files. Use focus parameter for specific concerns.",
259
+ fileFieldName: "files[]",
260
+ maxFiles: 2
261
+ }),
262
+ coreEndpoint("compare", "version", {
263
+ name: "dugate-compare-version",
264
+ description: "Summarized changelog between versions. Requires 2 files. Use output_format parameter.",
265
+ fileFieldName: "files[]",
266
+ maxFiles: 2
267
+ })
268
+ ];
269
+ const WORKFLOW_ENDPOINTS = [
270
+ workflowEndpoint("disbursement", {
271
+ name: "dugate-workflow-disbursement",
272
+ description: "Disbursement reconciliation: classify files, extract data, cross-check resolution, generate disbursement memo.",
273
+ maxFiles: 10
274
+ }),
275
+ workflowEndpoint("lc-checker", {
276
+ name: "dugate-workflow-lc-checker",
277
+ description: "Letter of Credit document checking: validate documents against LC terms, detect discrepancies per UCP 600.",
278
+ maxFiles: 10
279
+ }),
280
+ workflowEndpoint("doc-compare", {
281
+ name: "dugate-workflow-doc-compare",
282
+ description: "Advanced document comparison: OCR, extract TOC, compare sections, generate comparison report. Requires exactly 2 files.",
283
+ maxFiles: 2
284
+ })
285
+ ];
286
+ function buildPipelines(epNames) {
287
+ return epNames.map((epName) => ({
288
+ name: epName.replace(/^dugate-/, "").replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
289
+ description: `Execute the DUGate ${epName.replace(/^dugate-/, "")} profile.`,
290
+ enabled: true,
291
+ steps: [
292
+ {
293
+ stepOrder: 1,
294
+ name: "Call DUGate API",
295
+ endpointName: epName,
296
+ outputAlias: "result",
297
+ inputMapping: {
298
+ file_urls: "$input.file_urls",
299
+ output_format: "$input.output_format",
300
+ language: "$input.language",
301
+ categories: "$input.categories",
302
+ criteria: "$input.criteria",
303
+ reference_data: "$input.reference_data",
304
+ fields: "$input.fields",
305
+ schema: "$input.schema",
306
+ questions: "$input.questions",
307
+ target_language: "$input.target_language",
308
+ tone: "$input.tone",
309
+ style: "$input.style",
310
+ redact_patterns: "$input.redact_patterns",
311
+ template: "$input.template",
312
+ format: "$input.format",
313
+ max_words: "$input.max_words",
314
+ audience: "$input.audience",
315
+ focus: "$input.focus",
316
+ pages: "$input.pages",
317
+ resolution_data: "$input.resolution_data",
318
+ extract_fields: "$input.extract_fields"
319
+ }
320
+ }
321
+ ],
322
+ outputMapping: {
323
+ content: "$step[result].response.content",
324
+ extracted_data: "$step[result].response.extracted_data",
325
+ usage: "$step[result].response.usage"
326
+ }
327
+ }));
328
+ }
329
+ async function seedDugateEndpoints(db) {
330
+ const endpointsRepo = db.getRepository("doc_understanding_endpoints");
331
+ const pipelinesRepo = db.getRepository("doc_understanding_pipelines");
332
+ const stepsRepo = db.getRepository("doc_understanding_pipeline_steps");
333
+ const allEndpoints = [...CORE_ENDPOINTS, ...WORKFLOW_ENDPOINTS];
334
+ const endpointNameToId = /* @__PURE__ */ new Map();
335
+ for (const ep of allEndpoints) {
336
+ const existing = await endpointsRepo.findOne({ filter: { name: ep.name } });
337
+ let record;
338
+ if (existing) {
339
+ await endpointsRepo.update({ filterByTk: existing.id, values: ep });
340
+ record = await endpointsRepo.findOne({ filter: { name: ep.name } });
341
+ } else {
342
+ record = await endpointsRepo.create({ values: ep });
343
+ }
344
+ endpointNameToId.set(ep.name, record.id);
345
+ }
346
+ const pipelineNames = allEndpoints.map((e) => e.name);
347
+ const pipelines = buildPipelines(pipelineNames);
348
+ for (const pipeline of pipelines) {
349
+ const existingPipeline = await pipelinesRepo.findOne({ filter: { name: pipeline.name } });
350
+ if (existingPipeline) {
351
+ await stepsRepo.destroy({ filter: { pipelineId: existingPipeline.id } });
352
+ await pipelinesRepo.update({
353
+ filterByTk: existingPipeline.id,
354
+ values: {
355
+ description: pipeline.description,
356
+ enabled: pipeline.enabled,
357
+ inputSchema: pipeline.inputSchema,
358
+ outputMapping: pipeline.outputMapping
359
+ }
360
+ });
361
+ for (const step of pipeline.steps) {
362
+ const endpointId = endpointNameToId.get(step.endpointName);
363
+ if (endpointId) {
364
+ await stepsRepo.create({
365
+ values: {
366
+ pipelineId: existingPipeline.id,
367
+ stepOrder: step.stepOrder,
368
+ name: step.name,
369
+ endpointId,
370
+ inputMapping: step.inputMapping || null,
371
+ outputAlias: step.outputAlias || null,
372
+ onError: step.onError || "fail",
373
+ retryCount: step.retryCount ?? 0
374
+ }
375
+ });
376
+ }
377
+ }
378
+ } else {
379
+ const created = await pipelinesRepo.create({
380
+ values: {
381
+ name: pipeline.name,
382
+ description: pipeline.description,
383
+ enabled: pipeline.enabled,
384
+ inputSchema: pipeline.inputSchema || null,
385
+ outputMapping: pipeline.outputMapping || null
386
+ }
387
+ });
388
+ for (const step of pipeline.steps) {
389
+ const endpointId = endpointNameToId.get(step.endpointName);
390
+ if (endpointId) {
391
+ await stepsRepo.create({
392
+ values: {
393
+ pipelineId: created.id,
394
+ stepOrder: step.stepOrder,
395
+ name: step.name,
396
+ endpointId,
397
+ inputMapping: step.inputMapping || null,
398
+ outputAlias: step.outputAlias || null,
399
+ onError: step.onError || "fail",
400
+ retryCount: step.retryCount ?? 0
401
+ }
402
+ });
403
+ }
404
+ }
405
+ }
406
+ }
407
+ }
408
+ // Annotate the CommonJS export names for ESM import in node:
409
+ 0 && (module.exports = {
410
+ seedDugateEndpoints
411
+ });
@@ -35,6 +35,7 @@ var import_path = require("path");
35
35
  var import_DocumentUnderstandingService = require("./services/DocumentUnderstandingService");
36
36
  var import_actions = require("./actions");
37
37
  var import_document_understanding_tool = require("./tools/document-understanding-tool");
38
+ var import_dugate_seed = require("./dugate-seed");
38
39
  const isAiManagerLike = (manager) => {
39
40
  var _a;
40
41
  const candidate = manager;
@@ -116,6 +117,11 @@ class PluginDocumentUnderstandingServer extends import_server.Plugin {
116
117
  }
117
118
  }
118
119
  async install() {
120
+ try {
121
+ await (0, import_dugate_seed.seedDugateEndpoints)(this.db);
122
+ } catch (err) {
123
+ this.app.logger.warn("Document Understanding: DUGate seed data could not be installed.", err);
124
+ }
119
125
  }
120
126
  async afterEnable() {
121
127
  }
@@ -26,9 +26,17 @@ var __copyProps = (to, from, except, desc) => {
26
26
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
27
27
  var AsyncJobManager_exports = {};
28
28
  __export(AsyncJobManager_exports, {
29
- AsyncJobManager: () => AsyncJobManager
29
+ AsyncJobManager: () => AsyncJobManager,
30
+ JOB_RUN_LEASE_MS: () => JOB_RUN_LEASE_MS,
31
+ pollLeaseMs: () => pollLeaseMs
30
32
  });
31
33
  module.exports = __toCommonJS(AsyncJobManager_exports);
34
+ const JOB_RUN_LEASE_MS = 10 * 60 * 1e3;
35
+ const JOB_POLL_LEASE_MIN_MS = 60 * 1e3;
36
+ function pollLeaseMs(pollInterval) {
37
+ return Math.max((pollInterval || 5e3) * 3, JOB_POLL_LEASE_MIN_MS);
38
+ }
39
+ const JOBS_COLLECTION = "doc_understanding_jobs";
32
40
  class AsyncJobManager {
33
41
  db;
34
42
  apiClient;
@@ -36,12 +44,14 @@ class AsyncJobManager {
36
44
  onJobComplete;
37
45
  onJobError;
38
46
  logger;
39
- constructor(db, apiClient, callbacks, logger) {
47
+ nodeId;
48
+ constructor(db, apiClient, callbacks, logger, nodeId) {
40
49
  this.db = db;
41
50
  this.apiClient = apiClient;
42
51
  this.onJobComplete = callbacks.onJobComplete;
43
52
  this.onJobError = callbacks.onJobError;
44
53
  this.logger = logger;
54
+ this.nodeId = nodeId;
45
55
  }
46
56
  async startPolling(jobId, endpoint, taskId, customInterval, customTimeout) {
47
57
  if (this.intervals.has(jobId)) return;
@@ -55,8 +65,13 @@ class AsyncJobManager {
55
65
  await this.onJobError(jobId, "Polling timeout exceeded");
56
66
  return;
57
67
  }
68
+ if (!await this.refreshLease(jobId, endpoint)) {
69
+ this.stopPolling(jobId);
70
+ return;
71
+ }
58
72
  const pollResultSubpath = endpoint.pollResultSubpath;
59
73
  if (!pollResultSubpath) {
74
+ this.stopPolling(jobId);
60
75
  await this.onJobError(jobId, "Polling result subpath is not configured");
61
76
  return;
62
77
  }
@@ -87,39 +102,54 @@ class AsyncJobManager {
87
102
  }, interval);
88
103
  this.intervals.set(jobId, timer);
89
104
  }
105
+ async refreshLease(jobId, endpoint) {
106
+ const jobsRepo = this.db.getRepository(JOBS_COLLECTION);
107
+ const updated = await jobsRepo.update({
108
+ filter: { id: jobId, status: "polling", ownedBy: this.nodeId },
109
+ values: { leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval)) }
110
+ });
111
+ return Array.isArray(updated) ? updated.length > 0 : Boolean(updated);
112
+ }
90
113
  /**
91
- * Transition pending and running jobs to failed state during startup.
114
+ * Fail pending/running jobs that can no longer be executing. First the jobs
115
+ * this node owned (in-memory execution state is lost across a restart), then
116
+ * any remaining job whose owner lease expired. Rows without a lease predate
117
+ * ownership tracking and are treated as orphaned too.
92
118
  */
93
- async cleanupStuckJobs() {
94
- const jobsRepo = this.db.getRepository("doc_understanding_jobs");
95
- const stuckJobs = await jobsRepo.find({
119
+ async failOrphanedActiveJobs() {
120
+ const jobsRepo = this.db.getRepository(JOBS_COLLECTION);
121
+ const now = /* @__PURE__ */ new Date();
122
+ await jobsRepo.update({
123
+ filter: { status: { $in: ["pending", "running"] }, ownedBy: this.nodeId },
124
+ values: { status: "failed", error: "Server restarted during execution", completedAt: now }
125
+ });
126
+ await jobsRepo.update({
96
127
  filter: {
97
- status: ["pending", "running"]
98
- }
128
+ status: { $in: ["pending", "running"] },
129
+ $or: [{ leaseExpiresAt: { $lt: now } }, { leaseExpiresAt: null }]
130
+ },
131
+ values: { status: "failed", error: "Job lease expired before completion", completedAt: now }
99
132
  });
100
- for (const job of stuckJobs) {
101
- await jobsRepo.update({
102
- filterByTk: job.id,
103
- values: {
104
- status: "failed",
105
- error: "Server restarted during execution",
106
- completedAt: /* @__PURE__ */ new Date()
107
- }
108
- });
109
- }
110
133
  }
111
134
  /**
112
- * Recover polling jobs that were in-flight when server restarted.
113
- * Call this during service initialization.
135
+ * Re-adopt 'polling' jobs whose owner can no longer be polling them: jobs this
136
+ * node owned before a restart, jobs whose lease expired, and legacy rows without
137
+ * ownership. Webhook-mode jobs are skipped — nothing polls them, and any node
138
+ * can process the webhook when it arrives.
114
139
  */
115
- async recoverPollingJobs() {
116
- var _a;
117
- const jobsRepo = this.db.getRepository("doc_understanding_jobs");
118
- const stuckJobs = await jobsRepo.find({ filter: { status: "polling" } });
119
- for (const job of stuckJobs) {
120
- if (!job.externalTaskIds) continue;
121
- const stepKey = job.currentStep.toString();
122
- const taskId = job.externalTaskIds[stepKey];
140
+ async adoptOrphanedPollingJobs() {
141
+ const jobsRepo = this.db.getRepository(JOBS_COLLECTION);
142
+ const now = /* @__PURE__ */ new Date();
143
+ const candidates = await jobsRepo.find({
144
+ filter: {
145
+ status: "polling",
146
+ $or: [{ ownedBy: this.nodeId }, { leaseExpiresAt: { $lt: now } }, { ownedBy: null }]
147
+ }
148
+ });
149
+ for (const job of candidates) {
150
+ const externalTaskIds = job.externalTaskIds || {};
151
+ const stepKey = String(job.currentStep);
152
+ const taskId = externalTaskIds[stepKey];
123
153
  if (!taskId) continue;
124
154
  const pipelineRepo = this.db.getRepository("doc_understanding_pipelines");
125
155
  const pipeline = await pipelineRepo.findOne({
@@ -127,11 +157,35 @@ class AsyncJobManager {
127
157
  appends: ["steps", "steps.endpoint"]
128
158
  });
129
159
  if (!pipeline) continue;
130
- const step = (_a = pipeline.steps) == null ? void 0 : _a.find((s) => s.stepOrder === job.currentStep);
160
+ const steps = pipeline.steps || [];
161
+ const step = steps.find((s) => s.stepOrder === job.currentStep);
131
162
  if (!(step == null ? void 0 : step.endpoint) || step.endpoint.executionMode !== "polling") continue;
132
- await this.startPolling(job.id, step.endpoint, taskId);
163
+ if (await this.claimJobForPolling(job.id, step.endpoint)) {
164
+ await this.startPolling(job.id, step.endpoint, taskId);
165
+ }
133
166
  }
134
167
  }
168
+ async claimJobForPolling(jobId, endpoint) {
169
+ return this.db.sequelize.transaction(async (transaction) => {
170
+ const jobsRepo = this.db.getRepository(JOBS_COLLECTION);
171
+ const row = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
172
+ if (!row) return false;
173
+ if (String(row.get("status")) !== "polling") return false;
174
+ const owner = row.get("ownedBy");
175
+ const lease = row.get("leaseExpiresAt");
176
+ const leaseValid = lease != null && new Date(lease).getTime() > Date.now();
177
+ if (owner !== this.nodeId && leaseValid) return false;
178
+ await jobsRepo.update({
179
+ filterByTk: jobId,
180
+ values: {
181
+ ownedBy: this.nodeId,
182
+ leaseExpiresAt: new Date(Date.now() + pollLeaseMs(endpoint.pollInterval))
183
+ },
184
+ transaction
185
+ });
186
+ return true;
187
+ });
188
+ }
135
189
  stopPolling(jobId) {
136
190
  const timer = this.intervals.get(jobId);
137
191
  if (timer) {
@@ -152,5 +206,7 @@ class AsyncJobManager {
152
206
  }
153
207
  // Annotate the CommonJS export names for ESM import in node:
154
208
  0 && (module.exports = {
155
- AsyncJobManager
209
+ AsyncJobManager,
210
+ JOB_RUN_LEASE_MS,
211
+ pollLeaseMs
156
212
  });