plugin-document-understanding 1.1.12 → 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.
@@ -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
  }
@@ -289,7 +289,7 @@ class DocumentUnderstandingService {
289
289
  throw new Error("Webhook signature verification failed");
290
290
  }
291
291
  }
292
- const taskId = payload.task_id;
292
+ const taskId = payload.task_id ?? payload.operation_id;
293
293
  const result = payload.result;
294
294
  if (!taskId) throw new Error("Webhook missing task_id");
295
295
  const jobsRepo = this.db.getRepository("doc_understanding_jobs");
@@ -83,6 +83,36 @@ class ExternalApiClient {
83
83
  }
84
84
  return normalized;
85
85
  }
86
+ /**
87
+ * Appends the endpoint discriminator (if configured) to the request body so
88
+ * DUGate-style gateways can route to the correct sub-case/profile.
89
+ */
90
+ withDiscriminator(endpoint, body) {
91
+ var _a;
92
+ const field = (_a = endpoint.discriminatorField) == null ? void 0 : _a.trim();
93
+ if (!field || !endpoint.discriminatorValue) {
94
+ return body;
95
+ }
96
+ const merged = { ...body || {} };
97
+ if (merged[field] !== void 0 && merged[field] !== endpoint.discriminatorValue) {
98
+ throw new Error(
99
+ `Discriminator field '${field}' is locked by endpoint configuration (expected '${endpoint.discriminatorValue}', got '${merged[field]}').`
100
+ );
101
+ }
102
+ merged[field] = endpoint.discriminatorValue;
103
+ return merged;
104
+ }
105
+ /**
106
+ * Appends the DUGate sync flag (?sync=true) for endpoints configured with
107
+ * `syncQueryParam`. Kept separate from other query parameters so GET/DELETE
108
+ * params in `body` are not polluted by the discriminator logic.
109
+ */
110
+ syncQueryParams(endpoint) {
111
+ var _a;
112
+ const param = (_a = endpoint.syncQueryParam) == null ? void 0 : _a.trim();
113
+ if (!param) return {};
114
+ return { [param]: "true" };
115
+ }
86
116
  async call(options) {
87
117
  const { endpoint, body, files, overrideHeaders } = options;
88
118
  const url = endpoint.subpath;
@@ -95,8 +125,9 @@ class ExternalApiClient {
95
125
  };
96
126
  if (endpoint.fileInputMode === "multipart" && files && files.length > 0) {
97
127
  const formData = new import_form_data.default();
98
- if (body) {
99
- for (const [key, value] of Object.entries(body)) {
128
+ const bodyWithDiscriminator = this.withDiscriminator(endpoint, body);
129
+ if (bodyWithDiscriminator) {
130
+ for (const [key, value] of Object.entries(bodyWithDiscriminator)) {
100
131
  formData.append(key, typeof value === "object" ? JSON.stringify(value) : String(value));
101
132
  }
102
133
  }
@@ -117,17 +148,19 @@ class ExternalApiClient {
117
148
  mimeType: f.mimeType
118
149
  };
119
150
  }
120
- requestData = { ...body, _files: base64Files };
151
+ requestData = { ...this.withDiscriminator(endpoint, body), _files: base64Files };
121
152
  headers["Content-Type"] = "application/json";
122
153
  } else {
154
+ requestData = this.withDiscriminator(endpoint, body);
123
155
  headers["Content-Type"] = "application/json";
124
156
  }
125
157
  try {
158
+ const isBodyless = ["get", "delete"].includes(method);
126
159
  const response = await this.client.request({
127
160
  url,
128
161
  method,
129
- data: ["post", "put", "patch"].includes(method) ? requestData : void 0,
130
- params: ["get", "delete"].includes(method) ? requestData : void 0,
162
+ data: isBodyless ? void 0 : requestData,
163
+ params: isBodyless ? { ...requestData || {}, ...this.syncQueryParams(endpoint) } : this.syncQueryParams(endpoint),
131
164
  headers
132
165
  });
133
166
  return {
@@ -46,6 +46,30 @@ var import_mime_types = __toESM(require("mime-types"));
46
46
  var import_AsyncJobManager = require("./AsyncJobManager");
47
47
  const UPLOAD_ROOTS = [(0, import_path.resolve)(process.cwd(), "storage", "uploads")];
48
48
  const isInsidePath = (basePath, targetPath) => targetPath === basePath || targetPath.startsWith(`${basePath}${import_path.sep}`);
49
+ function extractTaskId(responseData, endpoint) {
50
+ var _a, _b;
51
+ const extractPath = (_a = endpoint.taskIdExtractPath) == null ? void 0 : _a.trim();
52
+ if (extractPath) {
53
+ const raw = extractPath.split(".").reduce((acc, k) => acc != null ? acc[k] : void 0, responseData);
54
+ if (raw != null) {
55
+ const regex = (_b = endpoint.taskIdExtractRegex) == null ? void 0 : _b.trim();
56
+ if (regex) {
57
+ try {
58
+ const m = String(raw).match(new RegExp(regex));
59
+ if (m == null ? void 0 : m[1]) return m[1];
60
+ } catch {
61
+ }
62
+ }
63
+ return String(raw);
64
+ }
65
+ }
66
+ const idField = endpoint.pollTaskIdField || "task_id";
67
+ const fieldVal = idField.split(".").reduce((acc, k) => acc != null ? acc[k] : void 0, responseData);
68
+ if (fieldVal != null) return String(fieldVal);
69
+ if (typeof responseData === "string") return responseData;
70
+ if (typeof responseData === "number") return String(responseData);
71
+ return null;
72
+ }
49
73
  function resolveUploadFilePath(urlOrPath) {
50
74
  if (!urlOrPath || urlOrPath.includes("\0")) return null;
51
75
  let pathname = urlOrPath.replace(/\\/g, "/").split(/[?#]/)[0];
@@ -231,7 +255,7 @@ class PipelineExecutor {
231
255
  if (!((_a = step.endpoint) == null ? void 0 : _a.enabled)) {
232
256
  throw new Error(`Endpoint for step ${step.name} is disabled`);
233
257
  }
234
- const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
258
+ const mappedBody = step.inputMapping && Object.keys(step.inputMapping).length > 0 ? this.resolveMapping(step.inputMapping, context) : context.input;
235
259
  let retries = step.onError === "retry" ? step.retryCount || 0 : 0;
236
260
  let success = false;
237
261
  let lastError = null;
@@ -248,12 +272,30 @@ class PipelineExecutor {
248
272
  files: mappedFiles
249
273
  });
250
274
  if (step.endpoint.executionMode === "sync") {
251
- context.stepResults[step.outputAlias || step.stepOrder.toString()] = result.data;
275
+ const responseData = result.data;
276
+ const isAsyncAccepted = result.status === 202 || responseData && typeof responseData === "object" && responseData.done === false;
277
+ if (isAsyncAccepted) {
278
+ const taskId = extractTaskId(responseData, step.endpoint);
279
+ if (taskId) {
280
+ const externalTaskIds = { ...job.externalTaskIds || {} };
281
+ externalTaskIds[step.stepOrder.toString()] = taskId;
282
+ await jobsRepo.update({
283
+ filterByTk: job.id,
284
+ values: {
285
+ status: "polling",
286
+ externalTaskIds,
287
+ leaseExpiresAt: new Date(Date.now() + (0, import_AsyncJobManager.pollLeaseMs)(step.endpoint.pollInterval))
288
+ }
289
+ });
290
+ await this.jobManager.startPolling(job.id, step.endpoint, taskId);
291
+ return;
292
+ }
293
+ }
294
+ context.stepResults[step.outputAlias || step.stepOrder.toString()] = responseData;
252
295
  success = true;
253
296
  } else if (step.endpoint.executionMode === "polling") {
254
- const taskIdField = step.endpoint.pollTaskIdField || "task_id";
255
- const taskId = this.getNestedValue(result.data, taskIdField);
256
- if (!taskId) throw new Error(`Polling taskId not found in field ${taskIdField}`);
297
+ const taskId = extractTaskId(result.data, step.endpoint);
298
+ if (!taskId) throw new Error("Polling taskId not found in response");
257
299
  const externalTaskIds = job.externalTaskIds || {};
258
300
  externalTaskIds[step.stepOrder.toString()] = taskId;
259
301
  await jobsRepo.update({
@@ -268,8 +310,8 @@ class PipelineExecutor {
268
310
  await this.jobManager.startPolling(job.id, step.endpoint, taskId);
269
311
  return;
270
312
  } else if (step.endpoint.executionMode === "webhook") {
271
- const taskIdField = step.endpoint.pollTaskIdField || "task_id";
272
- const taskId = this.getNestedValue(result.data, taskIdField);
313
+ const taskId = extractTaskId(result.data, step.endpoint);
314
+ if (!taskId) throw new Error("Webhook taskId not found in response");
273
315
  const externalTaskIds = job.externalTaskIds || {};
274
316
  externalTaskIds[step.stepOrder.toString()] = taskId;
275
317
  await jobsRepo.update({
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "displayName": "Document Understanding",
4
4
  "displayName.zh-CN": "文档理解",
5
5
  "description": "Configure external document processing endpoints, chain them into pipelines, and expose enabled pipelines as AI tools.",
6
- "version": "1.1.12",
6
+ "version": "1.1.13",
7
7
  "license": "Apache-2.0",
8
8
  "main": "dist/server/index.js",
9
9
  "files": [
@@ -406,6 +406,57 @@ export const EndpointsTab = () => {
406
406
  </>
407
407
  ),
408
408
  },
409
+ {
410
+ key: 'gateway',
411
+ label: t('Gateway / Discriminator'),
412
+ children: (
413
+ <>
414
+ <Form.Item
415
+ name="discriminatorField"
416
+ label={t('Discriminator Field')}
417
+ help={t(
418
+ 'Form field that selects the API sub-case (e.g. mode/type/task/action/process). Sent automatically.',
419
+ )}
420
+ >
421
+ <Input placeholder="mode" style={{ width: 200 }} />
422
+ </Form.Item>
423
+ <Form.Item
424
+ name="discriminatorValue"
425
+ label={t('Discriminator Value')}
426
+ help={t('Value sent in the discriminator field (e.g. parse, invoice, disbursement).')}
427
+ >
428
+ <Input placeholder="parse" style={{ width: 200 }} />
429
+ </Form.Item>
430
+ <Form.Item
431
+ name="syncQueryParam"
432
+ label={t('Sync Query Param')}
433
+ help={t(
434
+ 'When set, the request appends ?<param>=true to ask for a synchronous response (e.g. sync).',
435
+ )}
436
+ >
437
+ <Input placeholder="sync" style={{ width: 200 }} />
438
+ </Form.Item>
439
+ <Form.Item
440
+ name="taskIdExtractPath"
441
+ label={t('Task ID Extract Path')}
442
+ help={t(
443
+ 'JSON path of the async task id in the 202 response (e.g. name). Used when the response is 202 even in sync mode.',
444
+ )}
445
+ >
446
+ <Input placeholder="name" style={{ width: 200 }} />
447
+ </Form.Item>
448
+ <Form.Item
449
+ name="taskIdExtractRegex"
450
+ label={t('Task ID Extract Regex')}
451
+ help={t(
452
+ 'Regex with one capture group to pull the task id from the extracted path value (e.g. operations/([^/]+)).',
453
+ )}
454
+ >
455
+ <Input placeholder="operations/([^/]+)" style={{ width: 240 }} />
456
+ </Form.Item>
457
+ </>
458
+ ),
459
+ },
409
460
  {
410
461
  key: 'async',
411
462
  label: t('Async Config'),