plugin-document-understanding 1.1.15 → 2.0.0

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 (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -25
  3. package/dist/client/169.6888909107c553c3.js +10 -0
  4. package/dist/client/379.e29f5ced467ce23d.js +10 -0
  5. package/dist/client/867.3ed3b814115181ca.js +10 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/169.53bf1be2ec192f0c.js +10 -0
  8. package/dist/client-v2/379.e75c4829567cdb89.js +10 -0
  9. package/dist/client-v2/867.66d7291e95f1de78.js +10 -0
  10. package/dist/client-v2/index.js +1 -1
  11. package/dist/externalVersion.js +10 -8
  12. package/dist/locale/en-US.json +126 -0
  13. package/dist/locale/vi-VN.json +130 -2
  14. package/dist/locale/zh-CN.json +127 -1
  15. package/dist/node_modules/form-data/package.json +1 -1
  16. package/dist/node_modules/mime-types/package.json +1 -1
  17. package/dist/server/actions.js +211 -11
  18. package/dist/server/collections/api-keys.js +55 -0
  19. package/dist/server/collections/artifacts.js +59 -0
  20. package/dist/server/collections/config.js +9 -3
  21. package/dist/server/collections/endpoints.js +3 -0
  22. package/dist/server/collections/jobs.js +7 -4
  23. package/dist/server/collections/operations.js +76 -0
  24. package/dist/server/contracts/du-contracts.js +828 -0
  25. package/dist/server/dugate-seed.js +98 -340
  26. package/dist/server/plugin.js +49 -7
  27. package/dist/server/routes/du-gateway-router.js +443 -0
  28. package/dist/server/services/ArtifactStorageService.js +459 -0
  29. package/dist/server/services/AsyncJobManager.js +1 -1
  30. package/dist/server/services/BuiltinBusinessEngine.js +1223 -0
  31. package/dist/server/services/DocumentUnderstandingService.js +151 -25
  32. package/dist/server/services/ExternalDuReworkClient.js +210 -0
  33. package/dist/server/services/OperationOrchestrator.js +1087 -0
  34. package/dist/server/services/PipelineExecutor.js +164 -43
  35. package/dist/server/tools/document-understanding-tool.js +49 -24
  36. package/dist/server/workflow/DocumentUnderstandingInstruction.js +292 -0
  37. package/package.json +8 -4
  38. package/src/client/index.tsx +11 -0
  39. package/src/client-v2/components/ApiKeysTab.tsx +198 -0
  40. package/src/client-v2/components/EndpointsTab.tsx +39 -2
  41. package/src/client-v2/components/JobsTab.tsx +136 -21
  42. package/src/client-v2/components/OperationsTab.tsx +586 -0
  43. package/src/client-v2/components/PluginSettings.tsx +24 -8
  44. package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
  45. package/src/client-v2/components/__tests__/PluginSettings.test.tsx +43 -0
  46. package/src/client-v2/locale.ts +1 -8
  47. package/src/client-v2/models/index.ts +1 -8
  48. package/src/client-v2/plugin.tsx +12 -8
  49. package/src/client-v2/types.ts +13 -1
  50. package/src/client-v2/workflow/DocumentUnderstandingFieldset.tsx +122 -0
  51. package/src/client-v2/workflow/DocumentUnderstandingInstruction.tsx +49 -0
  52. package/src/locale/en-US.json +126 -0
  53. package/src/locale/vi-VN.json +130 -2
  54. package/src/locale/zh-CN.json +127 -1
  55. package/src/server/__tests__/actions.test.ts +1 -8
  56. package/src/server/__tests__/du-rework-gateway.test.ts +462 -0
  57. package/src/server/__tests__/dugate-integration.test.ts +79 -42
  58. package/src/server/__tests__/smoke.test.ts +1 -8
  59. package/src/server/__tests__/upload-security.test.ts +1 -8
  60. package/src/server/actions.ts +252 -36
  61. package/src/server/collections/api-keys.ts +35 -0
  62. package/src/server/collections/artifacts.ts +39 -0
  63. package/src/server/collections/config.ts +18 -2
  64. package/src/server/collections/endpoints.ts +12 -0
  65. package/src/server/collections/jobs.ts +16 -4
  66. package/src/server/collections/operations.ts +56 -0
  67. package/src/server/contracts/du-contracts.ts +1026 -0
  68. package/src/server/dugate-seed.ts +126 -453
  69. package/src/server/plugin.ts +64 -14
  70. package/src/server/routes/du-gateway-router.ts +465 -0
  71. package/src/server/services/ArtifactStorageService.ts +596 -0
  72. package/src/server/services/AsyncJobManager.ts +10 -1
  73. package/src/server/services/BuiltinBusinessEngine.ts +1544 -0
  74. package/src/server/services/DocumentUnderstandingService.ts +186 -44
  75. package/src/server/services/ExternalDuReworkClient.ts +222 -0
  76. package/src/server/services/OperationOrchestrator.ts +1359 -0
  77. package/src/server/services/PipelineExecutor.ts +245 -108
  78. package/src/server/tools/document-understanding-tool.ts +63 -45
  79. package/src/server/types.ts +101 -16
  80. package/src/server/workflow/DocumentUnderstandingInstruction.ts +308 -0
  81. package/dist/client/345.e6e484fb1974c3d3.js +0 -10
  82. package/dist/client-v2/345.a8f28526ac21e02a.js +0 -10
@@ -46,11 +46,14 @@ 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 isRecord(value) {
50
+ return typeof value === "object" && value !== null && !Array.isArray(value);
51
+ }
49
52
  function extractTaskId(responseData, endpoint) {
50
53
  var _a, _b;
51
54
  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);
55
+ if (extractPath && isRecord(responseData)) {
56
+ const raw = extractPath.split(".").reduce((acc, k) => isRecord(acc) ? acc[k] : void 0, responseData);
54
57
  if (raw != null) {
55
58
  const regex = (_b = endpoint.taskIdExtractRegex) == null ? void 0 : _b.trim();
56
59
  if (regex) {
@@ -64,8 +67,11 @@ function extractTaskId(responseData, endpoint) {
64
67
  }
65
68
  }
66
69
  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);
70
+ if (isRecord(responseData)) {
71
+ const fieldVal = idField.split(".").reduce((acc, k) => isRecord(acc) ? acc[k] : void 0, responseData);
72
+ if (fieldVal != null) return String(fieldVal);
73
+ if (typeof responseData.operationId === "string") return responseData.operationId;
74
+ }
69
75
  if (typeof responseData === "string") return responseData;
70
76
  if (typeof responseData === "number") return String(responseData);
71
77
  return null;
@@ -110,12 +116,14 @@ class PipelineExecutor {
110
116
  jobManager;
111
117
  logger;
112
118
  nodeId;
113
- constructor(db, apiClient, jobManager, logger, nodeId = "") {
119
+ orchestrator;
120
+ constructor(db, apiClient, jobManager, logger, nodeId = "", orchestrator) {
114
121
  this.db = db;
115
122
  this.apiClient = apiClient;
116
123
  this.jobManager = jobManager;
117
124
  this.logger = logger;
118
125
  this.nodeId = nodeId;
126
+ this.orchestrator = orchestrator;
119
127
  }
120
128
  async resolveFile(urlOrPath, fieldName = "file") {
121
129
  var _a, _b, _c, _d;
@@ -129,7 +137,7 @@ class PipelineExecutor {
129
137
  fieldName,
130
138
  buffer,
131
139
  filename: (0, import_path.basename)(localPath),
132
- mimeType
140
+ mimeType: String(mimeType)
133
141
  };
134
142
  }
135
143
  if (urlOrPath.startsWith("http://") || urlOrPath.startsWith("https://")) {
@@ -156,7 +164,6 @@ class PipelineExecutor {
156
164
  status: "pending",
157
165
  input,
158
166
  currentStep: 1,
159
- // 1-based ordering
160
167
  stepResults: {},
161
168
  externalTaskIds: {},
162
169
  startedAt: /* @__PURE__ */ new Date(),
@@ -189,12 +196,12 @@ class PipelineExecutor {
189
196
  const val = input[key];
190
197
  if (!val) continue;
191
198
  if (typeof val === "string") {
192
- if (val.startsWith("http://") || val.startsWith("https://") || val.startsWith("/") || val.startsWith("storage/")) {
199
+ if (val.startsWith("http://") || val.startsWith("https://") || val.startsWith("/") || val.startsWith("storage/") || val.startsWith("uploads/")) {
193
200
  await tryAddFile(val, "file");
194
201
  } else if (val.includes(",")) {
195
202
  const urls = val.split(",").map((s) => s.trim());
196
203
  for (const u of urls) {
197
- if (u.startsWith("http://") || u.startsWith("https://") || u.startsWith("/") || u.startsWith("storage/")) {
204
+ if (u.startsWith("http://") || u.startsWith("https://") || u.startsWith("/") || u.startsWith("storage/") || u.startsWith("uploads/")) {
198
205
  await tryAddFile(u, "file");
199
206
  }
200
207
  }
@@ -202,14 +209,14 @@ class PipelineExecutor {
202
209
  } else if (Array.isArray(val)) {
203
210
  for (const item of val) {
204
211
  if (typeof item === "string") {
205
- if (item.startsWith("http://") || item.startsWith("https://") || item.startsWith("/") || item.startsWith("storage/")) {
212
+ if (item.startsWith("http://") || item.startsWith("https://") || item.startsWith("/") || item.startsWith("storage/") || item.startsWith("uploads/")) {
206
213
  await tryAddFile(item, "file");
207
214
  }
208
- } else if (item && typeof item === "object" && item.url) {
215
+ } else if (isRecord(item) && typeof item.url === "string") {
209
216
  await tryAddFile(item.url, "file");
210
217
  }
211
218
  }
212
- } else if (val && typeof val === "object" && val.url) {
219
+ } else if (isRecord(val) && typeof val.url === "string") {
213
220
  await tryAddFile(val.url, "file");
214
221
  }
215
222
  }
@@ -224,14 +231,114 @@ class PipelineExecutor {
224
231
  input,
225
232
  files: resolvedFiles,
226
233
  stepResults: {},
227
- jobId: job.id
234
+ jobId: job.id,
235
+ userId
228
236
  };
229
- const steps = [...pipeline.steps || []].sort((a, b) => a.stepOrder - b.stepOrder);
237
+ const rawSteps = pipeline.steps || [];
238
+ const steps = [...rawSteps].sort((a, b) => a.stepOrder - b.stepOrder);
230
239
  this.runSteps(job, steps, context).catch((err) => {
231
240
  this.logger.error(`Background pipeline error for job ${job.id}`, err);
232
241
  });
233
242
  return job;
234
243
  }
244
+ async ensureArtifactsForContext(context) {
245
+ if (context.artifactIds) return context.artifactIds;
246
+ const ids = [];
247
+ if (Array.isArray(context.input.artifactIds)) {
248
+ for (const id of context.input.artifactIds) {
249
+ if (typeof id === "string" && id.trim()) ids.push(id.trim());
250
+ }
251
+ }
252
+ if (this.orchestrator && context.files.length > 0) {
253
+ for (const file of context.files) {
254
+ const created = await this.orchestrator.artifactStorage.createReadyArtifactFromBuffer({
255
+ tenantId: "default",
256
+ fileName: file.filename,
257
+ mimeType: file.mimeType,
258
+ buffer: file.buffer,
259
+ userId: context.userId
260
+ });
261
+ ids.push(created.artifactId);
262
+ }
263
+ }
264
+ context.artifactIds = ids;
265
+ return ids;
266
+ }
267
+ isCanonicalEndpoint(endpoint) {
268
+ if (!this.orchestrator) return false;
269
+ return endpoint.protocolMode === "builtin_du" || endpoint.protocolMode === "du_rework_v1" || Boolean(endpoint.businessId && endpoint.actionName);
270
+ }
271
+ async executeCanonicalStep(job, step, mappedBody, context) {
272
+ var _a, _b;
273
+ if (!this.orchestrator) {
274
+ throw new Error("OperationOrchestrator is not attached");
275
+ }
276
+ const endpoint = step.endpoint;
277
+ const businessId = endpoint.businessId || "document-core";
278
+ const action = endpoint.actionName || "ingest";
279
+ const stepInput = {};
280
+ for (const [k, v] of Object.entries(mappedBody || {})) {
281
+ if (v !== void 0) stepInput[k] = v;
282
+ }
283
+ if (endpoint.discriminatorField && endpoint.discriminatorValue) {
284
+ stepInput[endpoint.discriminatorField] = endpoint.discriminatorValue;
285
+ }
286
+ const artifactIds = await this.ensureArtifactsForContext(context);
287
+ const submitted = await this.orchestrator.submitOperation({
288
+ principal: {
289
+ kind: "nocobase_user",
290
+ tenantId: "default",
291
+ userId: context.userId,
292
+ allowedBusinesses: ["*"],
293
+ allowedActions: ["*"]
294
+ },
295
+ businessId,
296
+ action,
297
+ submission: {
298
+ input: stepInput,
299
+ artifacts: artifactIds.map((artifactId) => ({ artifactId, role: "input" })),
300
+ documentSelection: isRecord(context.input.documentSelection) ? context.input.documentSelection : void 0
301
+ },
302
+ waitCompletionMs: endpoint.pollTimeout || 12e4
303
+ });
304
+ const opRecord = await this.orchestrator.getOperationRecordOrThrow("default", submitted.operationId);
305
+ const jobsRepo = this.db.getRepository("doc_understanding_jobs");
306
+ if (opRecord.state === "WAITING_INPUT") {
307
+ const externalTaskIds = { ...job.externalTaskIds || {}, [String(step.stepOrder)]: opRecord.operationId };
308
+ await jobsRepo.update({
309
+ filterByTk: job.id,
310
+ values: {
311
+ status: "waiting_input",
312
+ operationId: opRecord.operationId,
313
+ waitState: opRecord.waitState,
314
+ usage: opRecord.usage,
315
+ externalTaskIds,
316
+ leaseExpiresAt: null
317
+ }
318
+ });
319
+ return { halted: true };
320
+ }
321
+ if (opRecord.state !== "SUCCEEDED") {
322
+ throw new Error(
323
+ ((_a = opRecord.errorProblem) == null ? void 0 : _a.detail) || ((_b = opRecord.errorProblem) == null ? void 0 : _b.title) || `Operation ended in state ${opRecord.state}`
324
+ );
325
+ }
326
+ await jobsRepo.update({
327
+ filterByTk: job.id,
328
+ values: {
329
+ operationId: opRecord.operationId,
330
+ usage: opRecord.usage ?? null
331
+ }
332
+ });
333
+ return {
334
+ halted: false,
335
+ responsePayload: {
336
+ ...opRecord.outputPayload || {},
337
+ usage: opRecord.usage,
338
+ operationId: opRecord.operationId
339
+ }
340
+ };
341
+ }
235
342
  async runSteps(job, steps, context, startFromOrder = 1) {
236
343
  var _a;
237
344
  const jobsRepo = this.db.getRepository("doc_understanding_jobs");
@@ -261,6 +368,15 @@ class PipelineExecutor {
261
368
  let lastError = null;
262
369
  while (retries >= 0 && !success) {
263
370
  try {
371
+ if (this.isCanonicalEndpoint(step.endpoint)) {
372
+ const canonicalOutcome = await this.executeCanonicalStep(job, step, mappedBody, context);
373
+ if (canonicalOutcome.halted) {
374
+ return;
375
+ }
376
+ context.stepResults[step.outputAlias || step.stepOrder.toString()] = canonicalOutcome.responsePayload;
377
+ success = true;
378
+ continue;
379
+ }
264
380
  const fileFieldName = step.endpoint.fileFieldName || "file";
265
381
  const mappedFiles = context.files ? context.files.map((f) => ({
266
382
  ...f,
@@ -273,7 +389,7 @@ class PipelineExecutor {
273
389
  });
274
390
  if (step.endpoint.executionMode === "sync") {
275
391
  const responseData = result.data;
276
- const isAsyncAccepted = result.status === 202 || responseData && typeof responseData === "object" && responseData.done === false;
392
+ const isAsyncAccepted = result.status === 202 || isRecord(responseData) && responseData.done === false;
277
393
  if (isAsyncAccepted) {
278
394
  const taskId = extractTaskId(responseData, step.endpoint);
279
395
  if (taskId) {
@@ -303,7 +419,6 @@ class PipelineExecutor {
303
419
  values: {
304
420
  status: "polling",
305
421
  externalTaskIds,
306
- // This node keeps polling and refreshes the lease on every tick.
307
422
  leaseExpiresAt: new Date(Date.now() + (0, import_AsyncJobManager.pollLeaseMs)(step.endpoint.pollInterval))
308
423
  }
309
424
  });
@@ -319,16 +434,14 @@ class PipelineExecutor {
319
434
  values: {
320
435
  status: "polling",
321
436
  externalTaskIds,
322
- // No process actively owns a webhook wait: the callback may arrive
323
- // at any node, so there is no lease to renew.
324
437
  leaseExpiresAt: null
325
438
  }
326
439
  });
327
440
  return;
328
441
  }
329
442
  } catch (err) {
330
- lastError = err;
331
- retries--;
443
+ lastError = err instanceof Error ? err : new Error(String(err));
444
+ retries -= 1;
332
445
  }
333
446
  }
334
447
  if (!success) {
@@ -339,9 +452,10 @@ class PipelineExecutor {
339
452
  }
340
453
  await this.finishJob(job.id, context);
341
454
  } catch (err) {
455
+ const errorMessage = err instanceof Error ? err.message : String(err);
342
456
  await jobsRepo.update({
343
457
  filterByTk: job.id,
344
- values: { status: "failed", error: err.message, completedAt: /* @__PURE__ */ new Date() }
458
+ values: { status: "failed", error: errorMessage, completedAt: /* @__PURE__ */ new Date() }
345
459
  });
346
460
  }
347
461
  }
@@ -350,17 +464,21 @@ class PipelineExecutor {
350
464
  const pipelineRepo = this.db.getRepository("doc_understanding_pipelines");
351
465
  const resume = await this.db.sequelize.transaction(
352
466
  async (transaction) => {
353
- const locked = await jobsRepo.findOne({ filterByTk: jobId, transaction, lock: transaction.LOCK.UPDATE });
354
- if (!locked || String(locked.get("status")) !== "polling") return void 0;
467
+ const locked = await jobsRepo.findOne({
468
+ filterByTk: jobId,
469
+ transaction,
470
+ lock: transaction.LOCK.UPDATE
471
+ });
472
+ const lockedStatus = locked ? String(locked.get("status")) : "";
473
+ if (!locked || lockedStatus !== "polling" && lockedStatus !== "waiting_input") return void 0;
355
474
  const pipeline = await pipelineRepo.findOne({
356
475
  filter: { id: locked.get("pipelineId") },
357
476
  appends: ["steps", "steps.endpoint"],
358
477
  transaction
359
478
  });
360
479
  if (!pipeline) return void 0;
361
- const steps = [...pipeline.steps || []].sort(
362
- (a, b) => a.stepOrder - b.stepOrder
363
- );
480
+ const rawSteps = pipeline.steps || [];
481
+ const steps = [...rawSteps].sort((a, b) => a.stepOrder - b.stepOrder);
364
482
  const currentStep = Number(locked.get("currentStep"));
365
483
  const step = steps.find((s) => s.stepOrder === currentStep);
366
484
  const stepResults = { ...locked.get("stepResults") || {} };
@@ -371,6 +489,7 @@ class PipelineExecutor {
371
489
  filterByTk: jobId,
372
490
  values: {
373
491
  status: "running",
492
+ waitState: null,
374
493
  ownedBy: this.nodeId,
375
494
  leaseExpiresAt: new Date(Date.now() + import_AsyncJobManager.JOB_RUN_LEASE_MS),
376
495
  stepResults
@@ -382,9 +501,8 @@ class PipelineExecutor {
382
501
  );
383
502
  if (!resume) return;
384
503
  const context = {
385
- input: resume.job.get("input"),
504
+ input: resume.job.get("input") || {},
386
505
  files: [],
387
- // Files cannot easily persist across webhook unless stored in bucket. For now assume next steps use only json.
388
506
  stepResults: resume.stepResults,
389
507
  jobId: resume.job.id
390
508
  };
@@ -399,7 +517,12 @@ class PipelineExecutor {
399
517
  if (!job) return;
400
518
  const pipeline = await pipelineRepo.findOne({ filter: { id: job.pipelineId } });
401
519
  if (!pipeline) return;
402
- const finalResult = pipeline.outputMapping ? this.resolveMapping(pipeline.outputMapping, context) : context.stepResults;
520
+ let finalResult = context.stepResults;
521
+ if (pipeline.outputMapping && Object.keys(pipeline.outputMapping).length > 0) {
522
+ const mapped = this.resolveMapping(pipeline.outputMapping, context);
523
+ const compact = Object.fromEntries(Object.entries(mapped).filter(([, v]) => v !== void 0));
524
+ finalResult = Object.keys(compact).length > 0 ? compact : context.stepResults;
525
+ }
403
526
  await jobsRepo.update({
404
527
  filterByTk: jobId,
405
528
  values: {
@@ -417,12 +540,12 @@ class PipelineExecutor {
417
540
  if (value.startsWith("$input.")) {
418
541
  result[key] = this.getNestedValue(context.input, value.replace("$input.", ""));
419
542
  } else if (value.startsWith("$step[")) {
420
- const match = value.match(/\$step\[(.*?)\]\.response\.(.*)/);
543
+ const match = value.match(/^\$step\[(.*?)\]\.(?:response\.)?(.*)$/);
421
544
  if (match) {
422
545
  const stepKey = match[1];
423
546
  const path = match[2];
424
547
  const stepResult = context.stepResults[stepKey];
425
- result[key] = this.getNestedValue(stepResult, path);
548
+ result[key] = path ? this.getNestedValue(stepResult, path) : stepResult;
426
549
  } else {
427
550
  result[key] = value;
428
551
  }
@@ -437,13 +560,11 @@ class PipelineExecutor {
437
560
  return result;
438
561
  }
439
562
  evaluateCondition(condition, context) {
440
- if (!condition) return true;
563
+ if (!condition || !isRecord(condition)) return true;
441
564
  const resolveValue = (v) => {
442
- if (typeof v === "string" && v.startsWith("$")) {
443
- if (v.startsWith("$step[")) {
444
- const match = v.match(/\$step\[(.*?)\]\.response\.(.*)/);
445
- if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
446
- }
565
+ if (typeof v === "string" && v.startsWith("$step[")) {
566
+ const match = v.match(/^\$step\[(.*?)\]\.(?:response\.)?(.*)$/);
567
+ if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
447
568
  }
448
569
  return v;
449
570
  };
@@ -455,13 +576,13 @@ class PipelineExecutor {
455
576
  case "neq":
456
577
  return fieldVal !== val;
457
578
  case "gt":
458
- return fieldVal > val;
579
+ return Number(fieldVal) > Number(val);
459
580
  case "gte":
460
- return fieldVal >= val;
581
+ return Number(fieldVal) >= Number(val);
461
582
  case "lt":
462
- return fieldVal < val;
583
+ return Number(fieldVal) < Number(val);
463
584
  case "lte":
464
- return fieldVal <= val;
585
+ return Number(fieldVal) <= Number(val);
465
586
  case "in":
466
587
  return Array.isArray(val) && val.includes(fieldVal);
467
588
  case "contains":
@@ -471,8 +592,8 @@ class PipelineExecutor {
471
592
  }
472
593
  }
473
594
  getNestedValue(obj, path) {
474
- if (!obj) return obj;
475
- return path.split(".").reduce((acc, part) => acc && acc[part], obj);
595
+ if (!obj || !path) return obj;
596
+ return path.split(".").reduce((acc, part) => isRecord(acc) ? acc[part] : void 0, obj);
476
597
  }
477
598
  }
478
599
  // Annotate the CommonJS export names for ESM import in node:
@@ -29,6 +29,9 @@ __export(document_understanding_tool_exports, {
29
29
  createDynamicPipelineToolsProvider: () => createDynamicPipelineToolsProvider
30
30
  });
31
31
  module.exports = __toCommonJS(document_understanding_tool_exports);
32
+ function isRecord(value) {
33
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34
+ }
32
35
  function cloneJson(value) {
33
36
  if (value === void 0 || value === null) {
34
37
  return value;
@@ -49,26 +52,33 @@ function buildSchema(pipeline) {
49
52
  }
50
53
  }
51
54
  };
52
- if (baseSchema.type === "object" && baseSchema.properties) {
55
+ if (baseSchema.type === "object" && isRecord(baseSchema.properties)) {
53
56
  baseSchema.properties.file_urls = {
54
57
  type: "array",
55
58
  items: { type: "string" },
56
- description: "Danh s\xE1ch c\xE1c URL c\u1EE7a file/\u1EA3nh \u0111\xEDnh k\xE8m trong chat"
59
+ description: "Danh s\xE1ch \u0111\u01B0\u1EDDng d\u1EABn t\u1EC7p/\u1EA3nh \u0111\xEDnh k\xE8m trong NocoBase uploads"
57
60
  };
61
+ if (!baseSchema.properties.pages) {
62
+ baseSchema.properties.pages = {
63
+ type: "string",
64
+ description: 'D\u1EA3i trang ch\u1ECDn l\u1ECDc c\u1EA7n x\u1EED l\xFD (v\xED d\u1EE5: "1-3, 5")'
65
+ };
66
+ }
58
67
  }
59
68
  return baseSchema;
60
69
  }
61
70
  function applySchemaDefaults(value, schema) {
62
- if (!schema || typeof schema !== "object") {
71
+ if (!isRecord(schema)) {
63
72
  return value;
64
73
  }
65
74
  if (value === void 0 && Object.prototype.hasOwnProperty.call(schema, "default")) {
66
75
  return cloneJson(schema.default);
67
76
  }
68
- const isObjectSchema = schema.type === "object" || schema.properties;
77
+ const isObjectSchema = schema.type === "object" || isRecord(schema.properties);
69
78
  if (isObjectSchema) {
70
- const source = value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
71
- for (const [key, propertySchema] of Object.entries(schema.properties || {})) {
79
+ const source = isRecord(value) ? { ...value } : {};
80
+ const props = isRecord(schema.properties) ? schema.properties : {};
81
+ for (const [key, propertySchema] of Object.entries(props)) {
72
82
  const currentValue = source[key];
73
83
  const nextValue = applySchemaDefaults(currentValue, propertySchema);
74
84
  if (nextValue !== void 0) {
@@ -87,7 +97,7 @@ function createToolForPipeline(service, pipeline) {
87
97
  const description = [
88
98
  pipeline.description || `Th\u1EF1c thi pipeline "${pipeline.name}".`,
89
99
  stepNames ? `Steps: ${stepNames}` : "",
90
- "Tr\u1EA3 v\u1EC1 k\u1EBFt qu\u1EA3 ph\xE2n t\xEDch JSON ho\u1EB7c Job ID n\u1EBFu ch\u1EA1y async."
100
+ "Tr\u1EA3 v\u1EC1 k\u1EBFt qu\u1EA3 ph\xE2n t\xEDch JSON, tr\u1EA1ng th\xE1i ch\u1EDD ph\xEA duy\u1EC7t (WAITING_INPUT), ho\u1EB7c Job ID."
91
101
  ].filter(Boolean).join(" ");
92
102
  return {
93
103
  scope: "CUSTOM",
@@ -102,42 +112,57 @@ function createToolForPipeline(service, pipeline) {
102
112
  description,
103
113
  schema: buildSchema(pipeline)
104
114
  },
105
- invoke: async (ctx, args) => {
115
+ invoke: async (_ctx, rawArgs) => {
106
116
  try {
117
+ const args = isRecord(rawArgs) ? rawArgs : {};
107
118
  const config = await service.getConfig();
108
- const pollInterval = Math.max(config.pollInterval || 2e3, 1e3);
119
+ const pollInterval = Math.max(config.pollInterval || 2e3, 500);
109
120
  const maxWait = Math.min(config.pollTimeout || 3e4, 3e4);
110
- let files = [];
111
- if (args.file_urls && Array.isArray(args.file_urls)) {
112
- files = args.file_urls.map((url) => ({ url }));
113
- }
114
- const hasInputSchema = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0;
115
- let input = hasInputSchema ? args : args.input || args;
116
- if (input === args) {
117
- input = { ...args };
118
- delete input.file_urls;
121
+ const files = Array.isArray(args.file_urls) ? args.file_urls.filter((u) => typeof u === "string" && Boolean(u.trim())).map((url) => ({
122
+ url,
123
+ fieldName: "file",
124
+ buffer: void 0,
125
+ filename: "",
126
+ mimeType: ""
127
+ })) : [];
128
+ const hasInputSchema = Boolean(pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0);
129
+ let inputValue = hasInputSchema ? args : isRecord(args.input) ? args.input : args;
130
+ if (inputValue === args) {
131
+ const copy = { ...args };
132
+ delete copy.file_urls;
133
+ inputValue = copy;
119
134
  }
120
135
  if (hasInputSchema) {
121
- input = applySchemaDefaults(input, pipeline.inputSchema);
136
+ inputValue = applySchemaDefaults(inputValue, pipeline.inputSchema);
122
137
  }
123
- const { jobId } = await service.executePipeline(pipeline.id, input, files);
138
+ const { jobId } = await service.executePipeline(pipeline.id, isRecord(inputValue) ? inputValue : {}, files);
124
139
  const start = Date.now();
125
140
  while (Date.now() - start < maxWait) {
126
141
  const job = await service.getJobStatus(jobId);
127
142
  if (job.status === "completed") {
128
- return { status: "completed", result: job.finalResult };
129
- } else if (job.status === "failed" || job.status === "timeout") {
143
+ return { status: "completed", result: job.finalResult, usage: job.usage ?? void 0 };
144
+ }
145
+ if (job.status === "waiting_input") {
146
+ return {
147
+ status: "waiting_input",
148
+ jobId,
149
+ operationId: job.operationId,
150
+ wait: job.waitState,
151
+ message: `T\xE1c v\u1EE5 \u0111ang t\u1EA1m d\u1EEBng ch\u1EDD ng\u01B0\u1EDDi ph\xEA duy\u1EC7t (WAITING_INPUT).`
152
+ };
153
+ }
154
+ if (job.status === "failed" || job.status === "timeout" || job.status === "cancelled") {
130
155
  return { status: job.status, error: job.error };
131
156
  }
132
157
  await new Promise((resolve) => setTimeout(resolve, pollInterval));
133
158
  }
134
159
  return {
135
160
  status: "polling",
136
- message: `Pipeline "${pipeline.name}" \u0111ang ch\u1EA1y, tr\u1EA3 v\u1EC1 job ID \u0111\u1EC3 theo d\xF5i.`,
161
+ message: `Pipeline "${pipeline.name}" \u0111ang ch\u1EA1y b\u1EA5t \u0111\u1ED3ng b\u1ED9, d\xF9ng jobId \u0111\u1EC3 theo d\xF5i.`,
137
162
  jobId
138
163
  };
139
164
  } catch (err) {
140
- return { error: err.message };
165
+ return { error: err instanceof Error ? err.message : String(err) };
141
166
  }
142
167
  }
143
168
  };