plugin-document-understanding 1.1.16 → 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 +9 -7
  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 +12 -0
  44. package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
  45. package/src/client-v2/components/__tests__/PluginSettings.test.tsx +4 -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.277fbb2b97424db5.js +0 -10
  82. package/dist/client-v2/345.2fa9834b46dd4531.js +0 -10
@@ -0,0 +1,1223 @@
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 BuiltinBusinessEngine_exports = {};
28
+ __export(BuiltinBusinessEngine_exports, {
29
+ BuiltinBusinessEngine: () => BuiltinBusinessEngine
30
+ });
31
+ module.exports = __toCommonJS(BuiltinBusinessEngine_exports);
32
+ var import_du_contracts = require("../contracts/du-contracts");
33
+ var import_ArtifactStorageService = require("./ArtifactStorageService");
34
+ function isRecord(value) {
35
+ return typeof value === "object" && value !== null && !Array.isArray(value);
36
+ }
37
+ function extractMessageText(content) {
38
+ if (typeof content === "string") return content;
39
+ if (Array.isArray(content)) {
40
+ return content.map((part) => {
41
+ if (typeof part === "string") return part;
42
+ if (isRecord(part) && typeof part.text === "string") return part.text;
43
+ return "";
44
+ }).filter(Boolean).join("\n");
45
+ }
46
+ return content == null ? "" : JSON.stringify(content);
47
+ }
48
+ function parseJsonFromLlm(rawText) {
49
+ const trimmed = rawText.trim();
50
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(trimmed);
51
+ const candidate = fenced ? fenced[1].trim() : trimmed;
52
+ try {
53
+ const parsed = JSON.parse(candidate);
54
+ return isRecord(parsed) ? parsed : { value: parsed };
55
+ } catch {
56
+ const firstBrace = candidate.indexOf("{");
57
+ const lastBrace = candidate.lastIndexOf("}");
58
+ if (firstBrace >= 0 && lastBrace > firstBrace) {
59
+ const sliced = candidate.slice(firstBrace, lastBrace + 1);
60
+ const parsed = JSON.parse(sliced);
61
+ return isRecord(parsed) ? parsed : { value: parsed };
62
+ }
63
+ throw new Error("Model response did not contain valid JSON output");
64
+ }
65
+ }
66
+ async function mapWithConcurrency(items, concurrency, worker) {
67
+ const limit = Math.max(1, Math.min(concurrency, items.length || 1));
68
+ const results = new Array(items.length);
69
+ let cursor = 0;
70
+ const runWorker = async () => {
71
+ while (cursor < items.length) {
72
+ const idx = cursor;
73
+ cursor += 1;
74
+ results[idx] = await worker(items[idx], idx);
75
+ }
76
+ };
77
+ await Promise.all(Array.from({ length: limit }, () => runWorker()));
78
+ return results;
79
+ }
80
+ function computeLineDiff(sourceText, targetText) {
81
+ const a = sourceText.split(/\r?\n/);
82
+ const b = targetText.split(/\r?\n/);
83
+ const diffLines = [];
84
+ let additions = 0;
85
+ let deletions = 0;
86
+ let unchangedLines = 0;
87
+ if (a.length * b.length <= 4e5) {
88
+ const dp = Array.from({ length: a.length + 1 }, () => new Array(b.length + 1).fill(0));
89
+ for (let i2 = a.length - 1; i2 >= 0; i2 -= 1) {
90
+ for (let j2 = b.length - 1; j2 >= 0; j2 -= 1) {
91
+ dp[i2][j2] = a[i2] === b[j2] ? dp[i2 + 1][j2 + 1] + 1 : Math.max(dp[i2 + 1][j2], dp[i2][j2 + 1]);
92
+ }
93
+ }
94
+ let i = 0;
95
+ let j = 0;
96
+ while (i < a.length && j < b.length) {
97
+ if (a[i] === b[j]) {
98
+ diffLines.push(` ${a[i]}`);
99
+ unchangedLines += 1;
100
+ i += 1;
101
+ j += 1;
102
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
103
+ diffLines.push(`- ${a[i]}`);
104
+ deletions += 1;
105
+ i += 1;
106
+ } else {
107
+ diffLines.push(`+ ${b[j]}`);
108
+ additions += 1;
109
+ j += 1;
110
+ }
111
+ }
112
+ while (i < a.length) {
113
+ diffLines.push(`- ${a[i]}`);
114
+ deletions += 1;
115
+ i += 1;
116
+ }
117
+ while (j < b.length) {
118
+ diffLines.push(`+ ${b[j]}`);
119
+ additions += 1;
120
+ j += 1;
121
+ }
122
+ } else {
123
+ const maxLen = Math.max(a.length, b.length);
124
+ for (let k = 0; k < maxLen; k += 1) {
125
+ if (k < a.length && k < b.length && a[k] === b[k]) {
126
+ diffLines.push(` ${a[k]}`);
127
+ unchangedLines += 1;
128
+ } else {
129
+ if (k < a.length) {
130
+ diffLines.push(`- ${a[k]}`);
131
+ deletions += 1;
132
+ }
133
+ if (k < b.length) {
134
+ diffLines.push(`+ ${b[k]}`);
135
+ additions += 1;
136
+ }
137
+ }
138
+ }
139
+ }
140
+ return {
141
+ unifiedDiff: diffLines.join("\n"),
142
+ additions,
143
+ deletions,
144
+ unchangedLines
145
+ };
146
+ }
147
+ function redactTextLocally(text, patterns) {
148
+ let output = text;
149
+ const normalized = patterns.length > 0 ? patterns : ["CCCD", "PHONE_NUMBER", "EMAIL"];
150
+ for (const patternName of normalized) {
151
+ const upper = patternName.toUpperCase();
152
+ if (upper === "CCCD" || upper === "ID_CARD") {
153
+ output = output.replace(/\b\d{12}\b/g, "[REDACTED]").replace(/\b\d{9}\b/g, "[REDACTED]");
154
+ } else if (upper === "PHONE" || upper === "PHONE_NUMBER") {
155
+ output = output.replace(/(?:\+?84|0)(?:3|5|7|8|9)\d{8}\b/g, "[REDACTED]");
156
+ } else if (upper === "EMAIL") {
157
+ output = output.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, "[REDACTED]");
158
+ } else if (upper === "BANK_ACCOUNT" || upper === "CARD_NUMBER") {
159
+ output = output.replace(/\b\d{10,19}\b/g, "[REDACTED]");
160
+ } else if (upper === "TAX_ID") {
161
+ output = output.replace(/\b\d{10}(?:-\d{3})?\b/g, "[REDACTED]");
162
+ } else {
163
+ try {
164
+ const customRe = new RegExp(patternName, "gi");
165
+ output = output.replace(customRe, "[REDACTED]");
166
+ } catch {
167
+ }
168
+ }
169
+ }
170
+ return output;
171
+ }
172
+ function mergeTemplateLocally(template, variables) {
173
+ return template.replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (_match, rawPath) => {
174
+ const val = rawPath.split(".").reduce((acc, key) => isRecord(acc) ? acc[key] : void 0, variables);
175
+ if (val === void 0 || val === null) return "";
176
+ return typeof val === "object" ? JSON.stringify(val) : String(val);
177
+ });
178
+ }
179
+ function markdownToSimpleHtml(md) {
180
+ const escaped = md.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
181
+ return escaped.replace(/^### (.+)$/gm, "<h3>$1</h3>").replace(/^## (.+)$/gm, "<h2>$1</h2>").replace(/^# (.+)$/gm, "<h1>$1</h1>").replace(/^- (.+)$/gm, "<li>$1</li>").replace(/\n\n+/g, "</p><p>").replace(/^/, "<p>").concat("</p>");
182
+ }
183
+ class UsageAccumulator {
184
+ inputTokens = 0;
185
+ outputTokens = 0;
186
+ model = "local-deterministic";
187
+ provider = "builtin";
188
+ measured = false;
189
+ add(params) {
190
+ this.inputTokens += params.inputTokens;
191
+ this.outputTokens += params.outputTokens;
192
+ this.model = params.model;
193
+ if (params.provider) this.provider = params.provider;
194
+ if (params.measured) this.measured = true;
195
+ }
196
+ toMetrics() {
197
+ const costMicrousd = Math.round(this.inputTokens * 1.5 + this.outputTokens * 6);
198
+ return {
199
+ inputTokens: this.inputTokens,
200
+ outputTokens: this.outputTokens,
201
+ costMicrousd,
202
+ costStatus: this.inputTokens === 0 && this.outputTokens === 0 ? "final" : this.measured ? "measured" : "estimated",
203
+ model: this.model,
204
+ provider: this.provider,
205
+ measurement: this.measured || this.inputTokens === 0 && this.outputTokens === 0 ? "measured" : "estimated"
206
+ };
207
+ }
208
+ }
209
+ class BuiltinBusinessEngine {
210
+ app;
211
+ artifactStorage;
212
+ runSchemaPipeline;
213
+ constructor(app, artifactStorage, runSchemaPipeline) {
214
+ this.app = app;
215
+ this.artifactStorage = artifactStorage;
216
+ this.runSchemaPipeline = runSchemaPipeline;
217
+ }
218
+ resolveAiManager() {
219
+ var _a, _b, _c, _d, _e, _f;
220
+ const appWithAi = this.app;
221
+ const candidates = [
222
+ appWithAi.aiManager,
223
+ (_c = (_b = (_a = this.app.pm) == null ? void 0 : _a.get) == null ? void 0 : _b.call(_a, "@nocobase/plugin-ai")) == null ? void 0 : _c.aiManager,
224
+ (_f = (_e = (_d = this.app.pm) == null ? void 0 : _d.get) == null ? void 0 : _e.call(_d, "ai")) == null ? void 0 : _f.aiManager
225
+ ];
226
+ for (const candidate of candidates) {
227
+ if (candidate && typeof candidate.getLLMService === "function") {
228
+ return candidate;
229
+ }
230
+ }
231
+ return null;
232
+ }
233
+ async listAvailableLlmServices() {
234
+ const aiManager = this.resolveAiManager();
235
+ if (!(aiManager == null ? void 0 : aiManager.listAllEnabledModels)) return [];
236
+ try {
237
+ return await aiManager.listAllEnabledModels();
238
+ } catch {
239
+ return [];
240
+ }
241
+ }
242
+ async invokeLlm(params) {
243
+ var _a, _b, _c, _d, _e, _f;
244
+ const aiManager = this.resolveAiManager();
245
+ if (!aiManager) {
246
+ throw new import_ArtifactStorageService.DuHttpError(
247
+ (0, import_du_contracts.createProblem)(
248
+ 503,
249
+ "TEMPORARY_UNAVAILABLE",
250
+ "NocoBase @nocobase/plugin-ai LLM service is not configured or enabled for built-in AI execution"
251
+ )
252
+ );
253
+ }
254
+ const preferredService = params.vision ? params.config.visionLlmService || params.config.llmService : params.config.llmService;
255
+ const preferredModel = params.vision ? params.config.visionLlmModel || params.config.llmModel : params.config.llmModel;
256
+ let resolved;
257
+ if (preferredService && preferredModel) {
258
+ resolved = { llmService: preferredService, model: preferredModel };
259
+ } else if (aiManager.resolveModel) {
260
+ try {
261
+ resolved = await aiManager.resolveModel(
262
+ preferredService && preferredModel ? { llmService: preferredService, model: preferredModel } : null
263
+ );
264
+ } catch (err) {
265
+ throw new import_ArtifactStorageService.DuHttpError(
266
+ (0, import_du_contracts.createProblem)(
267
+ 503,
268
+ "TEMPORARY_UNAVAILABLE",
269
+ err instanceof Error ? err.message : "No enabled LLM service found in NocoBase AI settings"
270
+ )
271
+ );
272
+ }
273
+ } else {
274
+ throw new import_ArtifactStorageService.DuHttpError(
275
+ (0, import_du_contracts.createProblem)(503, "TEMPORARY_UNAVAILABLE", "Please configure an active LLM service and model in NocoBase")
276
+ );
277
+ }
278
+ const { provider, model } = await aiManager.getLLMService(resolved);
279
+ const response = await provider.invoke({
280
+ messages: [
281
+ { role: "system", content: params.systemPrompt },
282
+ { role: "user", content: params.userContent }
283
+ ]
284
+ });
285
+ const text = extractMessageText(response.content);
286
+ const metaIn = ((_a = response.usage_metadata) == null ? void 0 : _a.input_tokens) ?? ((_c = (_b = response.response_metadata) == null ? void 0 : _b.tokenUsage) == null ? void 0 : _c.promptTokens);
287
+ const metaOut = ((_d = response.usage_metadata) == null ? void 0 : _d.output_tokens) ?? ((_f = (_e = response.response_metadata) == null ? void 0 : _e.tokenUsage) == null ? void 0 : _f.completionTokens);
288
+ const measured = typeof metaIn === "number" || typeof metaOut === "number";
289
+ const serializedUser = typeof params.userContent === "string" ? params.userContent : JSON.stringify(params.userContent);
290
+ params.usage.add({
291
+ inputTokens: typeof metaIn === "number" ? metaIn : Math.ceil((params.systemPrompt.length + serializedUser.length) / 4),
292
+ outputTokens: typeof metaOut === "number" ? metaOut : Math.ceil(text.length / 4),
293
+ model: model || resolved.model,
294
+ provider: resolved.llmService,
295
+ measured
296
+ });
297
+ return text;
298
+ }
299
+ async invokeLlmJson(params) {
300
+ const raw = await this.invokeLlm({
301
+ ...params,
302
+ systemPrompt: `${params.systemPrompt}
303
+ Return ONLY valid JSON without markdown commentary.`
304
+ });
305
+ return parseJsonFromLlm(raw);
306
+ }
307
+ resolveSelectionForArtifact(artifactId, planItems, fallbackPagesSpec) {
308
+ const planItem = planItems.find((p) => p.artifactId === artifactId);
309
+ if (planItem) return planItem.selection;
310
+ if (fallbackPagesSpec && fallbackPagesSpec.trim()) {
311
+ const ranges = (0, import_du_contracts.parsePageRangeString)(fallbackPagesSpec);
312
+ if (ranges.length > 0) {
313
+ return { kind: "ranges", ranges };
314
+ }
315
+ }
316
+ return { kind: "all" };
317
+ }
318
+ async readAndOcrDocuments(ctx, usage, options = {}) {
319
+ const pagesInput = typeof ctx.input.pages === "string" ? ctx.input.pages : void 0;
320
+ const docs = [];
321
+ const outcomes = [];
322
+ for (const artifact of ctx.artifacts) {
323
+ const selection = this.resolveSelectionForArtifact(artifact.artifactId, ctx.planItems, pagesInput);
324
+ const parsed = await this.artifactStorage.parseArtifactPages(artifact, selection);
325
+ if ((options.forceVisionOcr || options.digitize || parsed.requiresVision) && (!parsed.text.trim() || options.digitize || options.forceVisionOcr)) {
326
+ const buffer = this.artifactStorage.readArtifactBuffer(artifact);
327
+ if (artifact.mimeType.startsWith("image/")) {
328
+ const prompt = options.digitize ? "Digitize this handwritten/printed form accurately, preserving all labels, values, and checkbox states ([x]/[ ]) in clean Markdown." : "Transcribe all visible text, tables, headers, and stamps from this document image into clean Markdown.";
329
+ const ocrMd = await this.invokeLlm({
330
+ config: ctx.config,
331
+ systemPrompt: prompt,
332
+ vision: true,
333
+ usage,
334
+ userContent: [
335
+ {
336
+ type: "image_url",
337
+ image_url: { url: `data:${artifact.mimeType};base64,${buffer.toString("base64")}` }
338
+ }
339
+ ]
340
+ });
341
+ parsed.markdown = ocrMd.trim();
342
+ parsed.text = ocrMd.trim();
343
+ parsed.parser = options.digitize ? "vision-digitize" : "vision-ocr";
344
+ } else if (parsed.text.trim() && options.digitize) {
345
+ const digitized = await this.invokeLlm({
346
+ config: ctx.config,
347
+ systemPrompt: "Normalize and structure all form fields, checkboxes, and tables from this raw document text into clean Markdown.",
348
+ userContent: parsed.text,
349
+ usage
350
+ });
351
+ parsed.markdown = digitized.trim();
352
+ parsed.text = digitized.trim();
353
+ parsed.parser = "llm-digitize";
354
+ }
355
+ }
356
+ docs.push(parsed);
357
+ outcomes.push({
358
+ artifactId: artifact.artifactId,
359
+ selection,
360
+ status: "processed",
361
+ pagesProcessed: parsed.selectedPages.map((p) => p.pageNumber),
362
+ outputRefs: []
363
+ });
364
+ }
365
+ return { docs, outcomes };
366
+ }
367
+ async execute(ctx) {
368
+ const usage = new UsageAccumulator();
369
+ const warnings = [];
370
+ if (ctx.businessId === "lc-checker") {
371
+ return this.executeLcChecker(ctx, usage, warnings);
372
+ }
373
+ if (ctx.businessId === "example-review") {
374
+ return this.executeExampleReview(ctx, usage, warnings);
375
+ }
376
+ if (ctx.businessId !== "document-core") {
377
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(404, "NOT_FOUND", `Unknown businessId "${ctx.businessId}"`));
378
+ }
379
+ switch (ctx.action) {
380
+ case "ingest":
381
+ return this.executeIngest(ctx, usage, warnings);
382
+ case "extract":
383
+ return this.executeExtract(ctx, usage, warnings);
384
+ case "analyze":
385
+ return this.executeAnalyze(ctx, usage, warnings);
386
+ case "transform":
387
+ return this.executeTransform(ctx, usage, warnings);
388
+ case "generate":
389
+ return this.executeGenerate(ctx, usage, warnings);
390
+ case "compare":
391
+ return this.executeCompare(ctx, usage, warnings);
392
+ case "disbursement":
393
+ return this.executeDisbursementWorkflow(ctx, usage, warnings);
394
+ case "doc-compare":
395
+ return this.executeDocCompareWorkflow(ctx, usage, warnings);
396
+ case "schema-workflow":
397
+ return this.executeSchemaWorkflow(ctx, usage, warnings);
398
+ default:
399
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", `Unsupported document-core action "${ctx.action}"`));
400
+ }
401
+ }
402
+ async executeIngest(ctx, usage, warnings) {
403
+ var _a, _b;
404
+ if (ctx.artifacts.length === 0) {
405
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "ingest requires at least one input artifact"));
406
+ }
407
+ const mode = String(ctx.input.mode || "parse");
408
+ if (!["parse", "ocr", "digitize", "split"].includes(mode)) {
409
+ throw new import_ArtifactStorageService.DuHttpError(
410
+ (0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", `Invalid ingest mode "${mode}"`, {
411
+ errors: [{ pointer: "/input/mode", message: "Expected parse | ocr | digitize | split" }]
412
+ })
413
+ );
414
+ }
415
+ if (mode === "split") {
416
+ const target = ctx.artifacts[0];
417
+ const parsedAll = await this.artifactStorage.parseArtifactPages(target, { kind: "all" });
418
+ const rawPages = typeof ctx.input.pages === "string" && ctx.input.pages.trim() ? ctx.input.pages : `1-${parsedAll.totalPageCount}`;
419
+ let ranges;
420
+ try {
421
+ ranges = (0, import_du_contracts.parsePageRangeString)(rawPages, 500);
422
+ } catch (err) {
423
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", err instanceof Error ? err.message : String(err)));
424
+ }
425
+ const extraOutputArtifacts = [];
426
+ const splitArtifacts = [];
427
+ const effectiveRanges = ranges.length > 0 ? ranges : [{ from: 1, to: parsedAll.totalPageCount }];
428
+ for (let idx = 0; idx < effectiveRanges.length; idx += 1) {
429
+ const range = effectiveRanges[idx];
430
+ const slice = await this.artifactStorage.parseArtifactPages(target, { kind: "ranges", ranges: [range] });
431
+ const partName = `part-${idx + 1}-pages-${range.from}-${range.to}.md`;
432
+ const createdPart = await this.artifactStorage.createReadyArtifactFromBuffer({
433
+ tenantId: ctx.tenantId,
434
+ operationId: ctx.operationId,
435
+ role: "output",
436
+ fileName: partName,
437
+ mimeType: "text/markdown",
438
+ buffer: Buffer.from(slice.markdown || slice.text, "utf8"),
439
+ userId: ctx.userId
440
+ });
441
+ extraOutputArtifacts.push(createdPart);
442
+ splitArtifacts.push({
443
+ artifactId: createdPart.artifactId,
444
+ fileName: partName,
445
+ pageCount: slice.selectedPages.length,
446
+ pageRange: `${range.from}-${range.to}`
447
+ });
448
+ }
449
+ return {
450
+ kind: "completed",
451
+ outputPayload: {
452
+ version: "document-core-result-v1",
453
+ splitArtifacts,
454
+ metadata: {
455
+ pageCount: parsedAll.totalPageCount,
456
+ detectedFormat: parsedAll.detectedFormat,
457
+ parser: parsedAll.parser,
458
+ provenance: "split"
459
+ }
460
+ },
461
+ extraOutputArtifacts,
462
+ coverageOutcomes: [
463
+ {
464
+ artifactId: target.artifactId,
465
+ selection: { kind: "ranges", ranges: effectiveRanges },
466
+ status: "processed",
467
+ outputRefs: extraOutputArtifacts.map((a) => a.artifactId)
468
+ }
469
+ ],
470
+ usage: usage.toMetrics(),
471
+ warnings
472
+ };
473
+ }
474
+ const { docs, outcomes } = await this.readAndOcrDocuments(ctx, usage, {
475
+ forceVisionOcr: mode === "ocr",
476
+ digitize: mode === "digitize"
477
+ });
478
+ const markdown = docs.map((d) => docs.length > 1 ? `## ${d.fileName}
479
+
480
+ ${d.markdown}` : d.markdown).join("\n\n");
481
+ const text = docs.map((d) => d.text).join("\n\n");
482
+ const totalPages = docs.reduce((sum, d) => sum + d.selectedPages.length, 0);
483
+ return {
484
+ kind: "completed",
485
+ outputPayload: {
486
+ version: "document-core-result-v1",
487
+ markdown,
488
+ text,
489
+ metadata: {
490
+ pageCount: totalPages,
491
+ detectedFormat: ((_a = docs[0]) == null ? void 0 : _a.detectedFormat) || "unknown",
492
+ parser: ((_b = docs[0]) == null ? void 0 : _b.parser) || "local",
493
+ provenance: mode
494
+ }
495
+ },
496
+ extraOutputArtifacts: [],
497
+ coverageOutcomes: outcomes,
498
+ usage: usage.toMetrics(),
499
+ warnings
500
+ };
501
+ }
502
+ async executeExtract(ctx, usage, warnings) {
503
+ const variant = String(ctx.input.type || "invoice");
504
+ if (!["invoice", "contract", "id-card", "receipt", "table", "custom"].includes(variant)) {
505
+ throw new import_ArtifactStorageService.DuHttpError(
506
+ (0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", `Invalid extract type "${variant}"`, {
507
+ errors: [{ pointer: "/input/type", message: "Invalid enum value" }]
508
+ })
509
+ );
510
+ }
511
+ const inlineText = typeof ctx.input.text === "string" ? ctx.input.text : "";
512
+ const { docs, outcomes } = ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
513
+ const combinedText = [inlineText, ...docs.map((d) => `### File: ${d.fileName}
514
+ ${d.markdown || d.text}`)].filter(Boolean).join("\n\n");
515
+ if (!combinedText.trim()) {
516
+ throw new import_ArtifactStorageService.DuHttpError(
517
+ (0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "No document content or input text provided for extract")
518
+ );
519
+ }
520
+ const schemaPrompts = {
521
+ invoice: 'Extract invoice fields as JSON: { "supplier": {"name","taxId","address"}, "buyer": {"name","taxId","address"}, "invoiceNumber": string, "invoiceDate": string, "lineItems": [{"description","quantity","unitPrice","amount"}], "subtotal": number, "vatRate": number, "vatAmount": number, "total": number, "currency": string }.',
522
+ contract: 'Extract contract fields as JSON: { "contractNumber": string, "title": string, "effectiveDate": string, "expiryDate": string, "parties": [{"role","name","representative"}], "contractValue": {"amount": number, "currency": string}, "keyObligations": string[], "penaltyClauses": string[] }.',
523
+ "id-card": 'Extract identity card / passport fields as JSON: { "documentType": string, "idNumber": string, "fullName": string, "dateOfBirth": string, "gender": string, "nationality": string, "placeOfOrigin": string, "placeOfResidence": string, "issueDate": string, "expiryDate": string }.',
524
+ receipt: 'Extract receipt fields as JSON: { "merchantName": string, "receiptDate": string, "items": [{"name","quantity","price"}], "total": number, "currency": string, "paymentMethod": string }.',
525
+ table: 'Extract all tables from the document as JSON: { "tables": [{ "title": string, "headers": string[], "rows": string[][] }] }.',
526
+ custom: `Extract structured JSON matching this specification: ${JSON.stringify(
527
+ ctx.input.schema || ctx.input.fields || { summary: "string" }
528
+ )}.`
529
+ };
530
+ const data = await this.invokeLlmJson({
531
+ config: ctx.config,
532
+ systemPrompt: `You are a high-precision Document Understanding extraction engine.
533
+ ${schemaPrompts[variant]}`,
534
+ userContent: combinedText,
535
+ usage
536
+ });
537
+ return {
538
+ kind: "completed",
539
+ outputPayload: {
540
+ version: "document-core-result-v1",
541
+ data,
542
+ provenance: { slot: "reasoning", action: "extract", variant }
543
+ },
544
+ extraOutputArtifacts: [],
545
+ coverageOutcomes: outcomes,
546
+ usage: usage.toMetrics(),
547
+ warnings
548
+ };
549
+ }
550
+ async executeAnalyze(ctx, usage, warnings) {
551
+ const task = String(ctx.input.task || "classify");
552
+ if (!["classify", "sentiment", "compliance", "fact-check", "quality", "risk", "summarize-eval"].includes(task)) {
553
+ throw new import_ArtifactStorageService.DuHttpError(
554
+ (0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", `Invalid analyze task "${task}"`, {
555
+ errors: [{ pointer: "/input/task", message: "Invalid enum value" }]
556
+ })
557
+ );
558
+ }
559
+ const inlineText = typeof ctx.input.text === "string" ? ctx.input.text : "";
560
+ const { docs, outcomes } = ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
561
+ const combinedText = [inlineText, ...docs.map((d) => `### File: ${d.fileName}
562
+ ${d.markdown || d.text}`)].filter(Boolean).join("\n\n");
563
+ const taskPrompts = {
564
+ classify: `Classify the document into categories (${JSON.stringify(
565
+ ctx.input.categories || ["invoice", "contract", "report", "id-card", "other"]
566
+ )}). Return JSON: { "category": string, "confidence": number, "reasoning": string }.`,
567
+ sentiment: 'Analyze document sentiment. Return JSON: { "sentiment": "POSITIVE" | "NEGATIVE" | "NEUTRAL" | "MIXED", "confidence": number, "keyPhrases": string[], "summary": string }.',
568
+ compliance: `Evaluate compliance against criteria: ${JSON.stringify(
569
+ ctx.input.criteria || []
570
+ )}. Return JSON: { "verdict": "PASS" | "FAIL" | "WARNING", "summary": string, "violations": [{"rule": string, "severity": string, "detail": string}] }.`,
571
+ "fact-check": `Cross-check the document against referenceData: ${JSON.stringify(
572
+ ctx.input.referenceData ?? ctx.input.reference_data ?? {}
573
+ )}. Return JSON: { "verdict": "PASS" | "FAIL", "summary": string, "checks": [{"field": string, "status": "PASS" | "FAIL" | "UNVERIFIED", "detail": string}] }.`,
574
+ quality: 'Score document writing & structural quality (0-100). Return JSON: { "score": number, "dimensions": {"clarity": number, "completeness": number, "consistency": number}, "recommendations": string[] }.',
575
+ risk: `Assess legal and operational risk (focus: ${String(
576
+ ctx.input.focus || "general"
577
+ )}). Return JSON: { "riskLevel": "LOW" | "MEDIUM" | "HIGH" | "CRITICAL", "summary": string, "riskFactors": [{"clause": string, "severity": string, "mitigation": string}] }.`,
578
+ "summarize-eval": 'Summarize the document and evaluate the author perspective, strengths, and limitations. Return JSON: { "summary": string, "perspective": string, "strengths": string[], "limitations": string[] }.'
579
+ };
580
+ const data = await this.invokeLlmJson({
581
+ config: ctx.config,
582
+ systemPrompt: `You are an enterprise Document Understanding analysis engine.
583
+ ${taskPrompts[task]}`,
584
+ userContent: combinedText,
585
+ usage
586
+ });
587
+ return {
588
+ kind: "completed",
589
+ outputPayload: {
590
+ version: "document-core-result-v1",
591
+ data,
592
+ provenance: { slot: "reasoning", action: "analyze", variant: task }
593
+ },
594
+ extraOutputArtifacts: [],
595
+ coverageOutcomes: outcomes,
596
+ usage: usage.toMetrics(),
597
+ warnings
598
+ };
599
+ }
600
+ async executeTransform(ctx, usage, warnings) {
601
+ const variant = String(ctx.input.variant || ctx.input.action || "convert");
602
+ if (!["convert", "translate", "rewrite", "redact", "template"].includes(variant)) {
603
+ throw new import_ArtifactStorageService.DuHttpError(
604
+ (0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", `Invalid transform variant "${variant}"`, {
605
+ errors: [{ pointer: "/input/variant", message: "Invalid enum value" }]
606
+ })
607
+ );
608
+ }
609
+ const inlineText = typeof ctx.input.text === "string" ? ctx.input.text : "";
610
+ const { docs, outcomes } = ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
611
+ const sourceText = [inlineText, ...docs.map((d) => d.markdown || d.text)].filter(Boolean).join("\n\n");
612
+ const outputFormat = String(ctx.input.outputFormat || ctx.input.output_format || "text");
613
+ let transformedText = sourceText;
614
+ let slot;
615
+ if (variant === "convert") {
616
+ if (outputFormat === "html") {
617
+ transformedText = markdownToSimpleHtml(sourceText);
618
+ } else if (outputFormat === "json") {
619
+ transformedText = JSON.stringify({ paragraphs: sourceText.split(/\n{2,}/).filter(Boolean) }, null, 2);
620
+ } else {
621
+ transformedText = sourceText;
622
+ }
623
+ } else if (variant === "template") {
624
+ const tpl = typeof ctx.input.templateText === "string" && ctx.input.templateText ? ctx.input.templateText : sourceText;
625
+ const vars = isRecord(ctx.input.variables) ? ctx.input.variables : isRecord(ctx.input.template) ? ctx.input.template : {};
626
+ transformedText = mergeTemplateLocally(tpl, vars);
627
+ } else if (variant === "redact") {
628
+ const rawPatterns = ctx.input.redactPatterns ?? ctx.input.redact_patterns;
629
+ const patterns = Array.isArray(rawPatterns) ? rawPatterns.map(String) : typeof rawPatterns === "string" ? rawPatterns.split(",").map((s) => s.trim()) : ["CCCD", "PHONE_NUMBER", "EMAIL"];
630
+ transformedText = redactTextLocally(sourceText, patterns);
631
+ if (ctx.input.useAi === true) {
632
+ slot = "reasoning";
633
+ transformedText = await this.invokeLlm({
634
+ config: ctx.config,
635
+ systemPrompt: `Redact all sensitive PII matching ${JSON.stringify(
636
+ patterns
637
+ )} by replacing sensitive values with [REDACTED]. Preserve all other text verbatim.`,
638
+ userContent: transformedText,
639
+ usage
640
+ });
641
+ }
642
+ } else if (variant === "translate") {
643
+ slot = "reasoning";
644
+ const targetLang = String(ctx.input.targetLanguage || ctx.input.target_language || "en");
645
+ const tone = String(ctx.input.tone || "professional");
646
+ transformedText = await this.invokeLlm({
647
+ config: ctx.config,
648
+ systemPrompt: `Translate the document accurately into "${targetLang}" with a "${tone}" tone. Preserve Markdown structure and numbers.`,
649
+ userContent: sourceText,
650
+ usage
651
+ });
652
+ } else if (variant === "rewrite") {
653
+ slot = "reasoning";
654
+ const style = String(ctx.input.style || "executive");
655
+ const tone = String(ctx.input.tone || "clear");
656
+ transformedText = await this.invokeLlm({
657
+ config: ctx.config,
658
+ systemPrompt: `Rewrite the document in "${style}" style and "${tone}" tone while preserving factual accuracy.`,
659
+ userContent: sourceText,
660
+ usage
661
+ });
662
+ }
663
+ return {
664
+ kind: "completed",
665
+ outputPayload: {
666
+ version: "document-core-result-v1",
667
+ data: {
668
+ transformedText,
669
+ outputFormat
670
+ },
671
+ provenance: { ...slot ? { slot } : {}, action: "transform", variant }
672
+ },
673
+ extraOutputArtifacts: [],
674
+ coverageOutcomes: outcomes,
675
+ usage: usage.toMetrics(),
676
+ warnings
677
+ };
678
+ }
679
+ async executeGenerate(ctx, usage, warnings) {
680
+ const task = String(ctx.input.task || "summary");
681
+ if (!["summary", "outline", "report", "email", "minutes", "qa"].includes(task)) {
682
+ throw new import_ArtifactStorageService.DuHttpError(
683
+ (0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", `Invalid generate task "${task}"`, {
684
+ errors: [{ pointer: "/input/task", message: "Invalid enum value" }]
685
+ })
686
+ );
687
+ }
688
+ const inlineText = typeof ctx.input.text === "string" ? ctx.input.text : "";
689
+ const { docs, outcomes } = ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
690
+ const combinedText = [inlineText, ...docs.map((d) => `### File: ${d.fileName}
691
+ ${d.markdown || d.text}`)].filter(Boolean).join("\n\n");
692
+ const prompts = {
693
+ summary: `Generate a ${String(ctx.input.format || "bullets")} summary in at most ${Number(
694
+ ctx.input.maxWords ?? ctx.input.max_words ?? 300
695
+ )} words${ctx.input.audience ? ` for audience "${String(ctx.input.audience)}"` : ""}. Return JSON: { "summary": string, "keyPoints": string[] }.`,
696
+ outline: 'Extract a hierarchical outline of the document. Return JSON: { "sections": [{ "level": number, "title": string, "summary": string }] }.',
697
+ report: `Generate an executive analytical report (focus: ${String(
698
+ ctx.input.focus || "comprehensive"
699
+ )}). Return JSON: { "title": string, "markdownReport": string, "highlights": string[] }.`,
700
+ email: `Draft a "${String(
701
+ ctx.input.tone || "formal"
702
+ )}" email based on the document. Return JSON: { "subject": string, "body": string }.`,
703
+ minutes: 'Generate structured meeting minutes. Return JSON: { "title": string, "summary": string, "decisions": string[], "actionItems": [{"task": string, "owner": string, "dueDate": string}] }.',
704
+ qa: `Answer each question grounded strictly in the document with verbatim evidence quotes: ${JSON.stringify(
705
+ ctx.input.questions || []
706
+ )}. Return JSON: { "answers": [{ "question": string, "answer": string, "evidenceQuote": string, "confidence": number }] }.`
707
+ };
708
+ const data = await this.invokeLlmJson({
709
+ config: ctx.config,
710
+ systemPrompt: `You are a grounded Document Understanding generation engine.
711
+ ${prompts[task]}`,
712
+ userContent: combinedText,
713
+ usage
714
+ });
715
+ return {
716
+ kind: "completed",
717
+ outputPayload: {
718
+ version: "document-core-result-v1",
719
+ data,
720
+ provenance: { slot: "reasoning", action: "generate", variant: task }
721
+ },
722
+ extraOutputArtifacts: [],
723
+ coverageOutcomes: outcomes,
724
+ usage: usage.toMetrics(),
725
+ warnings
726
+ };
727
+ }
728
+ async executeCompare(ctx, usage, warnings) {
729
+ var _a, _b;
730
+ const mode = String(ctx.input.mode || "diff");
731
+ if (!["diff", "semantic", "version"].includes(mode)) {
732
+ throw new import_ArtifactStorageService.DuHttpError(
733
+ (0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", `Invalid compare mode "${mode}"`, {
734
+ errors: [{ pointer: "/input/mode", message: "Invalid enum value" }]
735
+ })
736
+ );
737
+ }
738
+ const { docs, outcomes } = ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
739
+ const sourceText = (isRecord(ctx.input.source) && typeof ctx.input.source.text === "string" ? ctx.input.source.text : void 0) ?? ((_a = docs[0]) == null ? void 0 : _a.text) ?? "";
740
+ const targetText = (isRecord(ctx.input.target) && typeof ctx.input.target.text === "string" ? ctx.input.target.text : void 0) ?? ((_b = docs[1]) == null ? void 0 : _b.text) ?? "";
741
+ if (docs.length < 2 && (!sourceText || !targetText)) {
742
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "compare requires two documents (source and target)"));
743
+ }
744
+ if (mode === "diff") {
745
+ const diffData = computeLineDiff(sourceText, targetText);
746
+ return {
747
+ kind: "completed",
748
+ outputPayload: {
749
+ version: "document-core-result-v1",
750
+ data: diffData,
751
+ provenance: { action: "compare", variant: "diff" }
752
+ },
753
+ extraOutputArtifacts: [],
754
+ coverageOutcomes: outcomes,
755
+ usage: usage.toMetrics(),
756
+ warnings
757
+ };
758
+ }
759
+ const prompt = mode === "semantic" ? `Compare SOURCE vs TARGET clauses${ctx.input.focus ? ` focusing on "${String(ctx.input.focus)}"` : ""}. Return JSON: { "changes": [{ "clauseTitle": string, "sourceExcerpt": string, "targetExcerpt": string, "changeType": "ADDED" | "REMOVED" | "MODIFIED", "legalSignificance": "NEGLIGIBLE" | "MODERATE" | "HIGH", "commentary": string }] }.` : 'Generate a version changelog between SOURCE and TARGET. Return JSON: { "summary": string, "breakingChanges": string[], "additions": string[], "modifications": string[], "removals": string[] }.';
760
+ const data = await this.invokeLlmJson({
761
+ config: ctx.config,
762
+ systemPrompt: prompt,
763
+ userContent: `=== SOURCE ===
764
+ ${sourceText}
765
+
766
+ === TARGET ===
767
+ ${targetText}`,
768
+ usage
769
+ });
770
+ return {
771
+ kind: "completed",
772
+ outputPayload: {
773
+ version: "document-core-result-v1",
774
+ data,
775
+ provenance: { slot: "reasoning", action: "compare", variant: mode }
776
+ },
777
+ extraOutputArtifacts: [],
778
+ coverageOutcomes: outcomes,
779
+ usage: usage.toMetrics(),
780
+ warnings
781
+ };
782
+ }
783
+ async executeDisbursementWorkflow(ctx, usage, warnings) {
784
+ var _a, _b;
785
+ const maxConcurrency = Math.min(8, Math.max(1, Number(ctx.input.maxConcurrency) || 4));
786
+ const requireApproval = ctx.input.requireApproval === true;
787
+ let perFileRecords = [];
788
+ let outcomes = [];
789
+ if (ctx.checkpointData && Array.isArray(ctx.checkpointData.perFileRecords)) {
790
+ perFileRecords = ctx.checkpointData.perFileRecords;
791
+ outcomes = ctx.checkpointData.outcomes || [];
792
+ } else {
793
+ await ((_a = ctx.onProgress) == null ? void 0 : _a.call(ctx, 20, "Classifying and extracting disbursement documents"));
794
+ const parsedBundle = await this.readAndOcrDocuments(ctx, usage);
795
+ outcomes = parsedBundle.outcomes;
796
+ perFileRecords = await mapWithConcurrency(parsedBundle.docs, maxConcurrency, async (doc) => {
797
+ const res = await this.invokeLlmJson({
798
+ config: ctx.config,
799
+ systemPrompt: 'Classify this credit disbursement document (e.g. promissory_note, vat_invoice, disbursement_request, contract, resolution) and extract key financial fields. Return JSON: { "docType": string, "extracted": Record<string, unknown> }.',
800
+ userContent: `File: ${doc.fileName}
801
+
802
+ ${doc.markdown || doc.text}`,
803
+ usage
804
+ });
805
+ return {
806
+ fileName: doc.fileName,
807
+ docType: typeof res.docType === "string" ? res.docType : "supporting_document",
808
+ extracted: isRecord(res.extracted) ? res.extracted : res
809
+ };
810
+ });
811
+ if (requireApproval && !ctx.resumedInput) {
812
+ return {
813
+ kind: "waiting_input",
814
+ waitState: {
815
+ waitId: "approval-wait",
816
+ prompt: "Review extracted disbursement records before cross-checking against credit approval.",
817
+ inputSchema: {
818
+ type: "object",
819
+ properties: {
820
+ approved: { type: "boolean", default: true },
821
+ approver: { type: "string" },
822
+ note: { type: "string" }
823
+ },
824
+ required: ["approved"]
825
+ },
826
+ previewData: { perFileRecords },
827
+ expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1e3).toISOString()
828
+ },
829
+ checkpointData: { perFileRecords, outcomes },
830
+ usage: usage.toMetrics()
831
+ };
832
+ }
833
+ }
834
+ if (ctx.resumedInput && ctx.resumedInput.approved === false) {
835
+ throw new import_ArtifactStorageService.DuHttpError(
836
+ (0, import_du_contracts.createProblem)(
837
+ 409,
838
+ "STATE_CONFLICT",
839
+ `Disbursement rejected by reviewer: ${String(ctx.resumedInput.note || "")}`
840
+ )
841
+ );
842
+ }
843
+ await ((_b = ctx.onProgress) == null ? void 0 : _b.call(ctx, 70, "Cross-checking extracted evidence against referenceData"));
844
+ const referenceData = ctx.input.referenceData ?? ctx.input.resolution_data ?? [];
845
+ const synthesis = await this.invokeLlmJson({
846
+ config: ctx.config,
847
+ systemPrompt: 'Cross-check the extracted disbursement documents against referenceData and write a Vietnamese appraisal report. Return JSON: { "findings": [{"key": string, "status": "match" | "mismatch" | "unresolved", "detail": string}], "report": string }.',
848
+ userContent: JSON.stringify({
849
+ referenceData,
850
+ extractedDocuments: perFileRecords,
851
+ reviewerDecision: ctx.resumedInput
852
+ }),
853
+ usage
854
+ });
855
+ const findings = Array.isArray(synthesis.findings) ? synthesis.findings : [];
856
+ const matchedCount = findings.filter((f) => f.status === "match").length;
857
+ const mismatchedCount = findings.filter((f) => f.status === "mismatch").length;
858
+ return {
859
+ kind: "completed",
860
+ outputPayload: {
861
+ resultVersion: "disbursement-result-v1",
862
+ businessId: "document-core",
863
+ businessVersion: "2.0.0",
864
+ report: typeof synthesis.report === "string" ? synthesis.report : "# B\xC1O C\xC1O \u0110\u1ED0I CHI\u1EBEU H\u1ED2 S\u01A0 GI\u1EA2I NG\xC2N",
865
+ crosscheck: {
866
+ findings,
867
+ matchedCount,
868
+ mismatchedCount
869
+ },
870
+ evidence: {
871
+ filesAnalyzed: perFileRecords.length,
872
+ logicalDocumentCount: perFileRecords.length,
873
+ extractedRecordCount: perFileRecords.length,
874
+ perFile: perFileRecords.map((r) => ({ fileName: r.fileName, docType: r.docType }))
875
+ },
876
+ failedChildren: []
877
+ },
878
+ extraOutputArtifacts: [],
879
+ coverageOutcomes: outcomes,
880
+ usage: usage.toMetrics(),
881
+ warnings
882
+ };
883
+ }
884
+ async executeDocCompareWorkflow(ctx, usage, warnings) {
885
+ let comparisonPayload;
886
+ let outcomes = [];
887
+ if (ctx.checkpointData && isRecord(ctx.checkpointData.comparisonPayload)) {
888
+ comparisonPayload = ctx.checkpointData.comparisonPayload;
889
+ outcomes = ctx.checkpointData.outcomes || [];
890
+ } else {
891
+ const parsedBundle = await this.readAndOcrDocuments(ctx, usage);
892
+ outcomes = parsedBundle.outcomes;
893
+ if (parsedBundle.docs.length < 2) {
894
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "doc-compare workflow requires 2 input artifacts"));
895
+ }
896
+ const chunkSize = Math.min(2e5, Math.max(200, Number(ctx.input.chunkSizeChars) || 8e3));
897
+ const src = (parsedBundle.docs[0].markdown || parsedBundle.docs[0].text).slice(0, chunkSize * 4);
898
+ const tgt = (parsedBundle.docs[1].markdown || parsedBundle.docs[1].text).slice(0, chunkSize * 4);
899
+ comparisonPayload = await this.invokeLlmJson({
900
+ config: ctx.config,
901
+ systemPrompt: 'Perform deep structural and cross-reference comparison between two long documents. Return JSON: { "structureClaims": [{"section": string, "status": "unchanged" | "modified" | "added" | "removed" | "moved", "detail": string}], "referenceClaims": [{"reference": string, "status": "resolved" | "unresolved" | "contradicted", "detail": string}], "report": string }.',
902
+ userContent: `=== SOURCE (${parsedBundle.docs[0].fileName}) ===
903
+ ${src}
904
+
905
+ === TARGET (${parsedBundle.docs[1].fileName}) ===
906
+ ${tgt}`,
907
+ usage
908
+ });
909
+ if (ctx.input.requireHumanReview === true && !ctx.resumedInput) {
910
+ return {
911
+ kind: "waiting_input",
912
+ waitState: {
913
+ waitId: "doc-compare-review",
914
+ prompt: "Confirm structural and cross-reference comparison claims before finalizing.",
915
+ inputSchema: {
916
+ type: "object",
917
+ properties: {
918
+ approved: { type: "boolean", default: true },
919
+ note: { type: "string" }
920
+ },
921
+ required: ["approved"]
922
+ },
923
+ previewData: comparisonPayload
924
+ },
925
+ checkpointData: { comparisonPayload, outcomes },
926
+ usage: usage.toMetrics()
927
+ };
928
+ }
929
+ }
930
+ return {
931
+ kind: "completed",
932
+ outputPayload: {
933
+ resultVersion: "doc-compare-result-v1",
934
+ businessId: "document-core",
935
+ businessVersion: "2.0.0",
936
+ ...comparisonPayload,
937
+ reviewerDecision: ctx.resumedInput ?? null
938
+ },
939
+ extraOutputArtifacts: [],
940
+ coverageOutcomes: outcomes,
941
+ usage: usage.toMetrics(),
942
+ warnings
943
+ };
944
+ }
945
+ async executeSchemaWorkflow(ctx, usage, warnings) {
946
+ if (!this.runSchemaPipeline) {
947
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(501, "NOT_IMPLEMENTED", "Dynamic pipeline runner is not attached"));
948
+ }
949
+ const pipelineId = typeof ctx.input.pipelineId === "number" ? ctx.input.pipelineId : void 0;
950
+ const pipelineName = typeof ctx.input.pipelineName === "string" ? ctx.input.pipelineName : void 0;
951
+ const params = isRecord(ctx.input.parameters) ? ctx.input.parameters : ctx.input;
952
+ const result = await this.runSchemaPipeline({ pipelineId, pipelineName }, params, ctx.userId);
953
+ return {
954
+ kind: "completed",
955
+ outputPayload: {
956
+ resultVersion: "schema-workflow-result-v1",
957
+ businessId: "document-core",
958
+ businessVersion: "2.0.0",
959
+ data: result
960
+ },
961
+ extraOutputArtifacts: [],
962
+ coverageOutcomes: [],
963
+ usage: usage.toMetrics(),
964
+ warnings
965
+ };
966
+ }
967
+ /**
968
+ * `lc-checker@1.2.0` — 5-step Trade Finance examination:
969
+ * 1. ocr -> 2. screen -> 3. visual -> 4. adjudicate (UCP 600 / ISBP 821) -> 5. Vietnamese report
970
+ */
971
+ async executeLcChecker(ctx, usage, warnings) {
972
+ var _a, _b, _c, _d, _e;
973
+ if (ctx.artifacts.length === 0) {
974
+ throw new import_ArtifactStorageService.DuHttpError(
975
+ (0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "lc-checker requires at least one L/C presentation document")
976
+ );
977
+ }
978
+ if (ctx.artifacts.length > 50) {
979
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "lc-checker accepts at most 50 presentation files"));
980
+ }
981
+ await ((_a = ctx.onProgress) == null ? void 0 : _a.call(ctx, 15, "Step 1/5: OCR & text extraction"));
982
+ const { docs, outcomes } = await this.readAndOcrDocuments(ctx, usage, { forceVisionOcr: true });
983
+ const filesWithoutOcrText = docs.filter((d) => !d.text.trim()).map((d) => d.fileName);
984
+ const totalOcrChars = docs.reduce((sum, d) => sum + d.text.length, 0);
985
+ await ((_b = ctx.onProgress) == null ? void 0 : _b.call(ctx, 35, "Step 2/5: Screening presentation & identifying visual checks"));
986
+ const rulesCatalogSummary = import_du_contracts.UCP600_ISBP821_RULES.map((r) => `${r.ruleId}: ${r.title} - ${r.description}`).join(
987
+ "\n"
988
+ );
989
+ const combinedDocsText = docs.map((d) => `=== DOCUMENT: ${d.fileName} ===
990
+ ${d.markdown || d.text}`).join("\n\n");
991
+ const screenResult = await this.invokeLlmJson({
992
+ config: ctx.config,
993
+ systemPrompt: `You are a Trade Finance L/C examiner screening documents against UCP 600 / ISBP 821.
994
+ Available Rule Registry:
995
+ ${rulesCatalogSummary}
996
+ Return JSON: { "documentsPresent": string[], "documentsMissing": string[], "visualRequests": [{ "document": string, "check": string, "ruleId": string }] }. Cite ONLY ruleIds from the registry (max 24 visualRequests).`,
997
+ userContent: combinedDocsText,
998
+ usage
999
+ });
1000
+ const rawVisualRequests = Array.isArray(screenResult.visualRequests) ? screenResult.visualRequests.slice(0, 24) : [];
1001
+ const validVisualRequests = rawVisualRequests.filter(
1002
+ (req) => typeof req.ruleId === "string" && import_du_contracts.VALID_LC_RULE_IDS.has(req.ruleId)
1003
+ );
1004
+ await ((_c = ctx.onProgress) == null ? void 0 : _c.call(ctx, 55, "Step 3/5: Executing visual verification checks"));
1005
+ const outstandingVisualChecks = [];
1006
+ let satisfiedVisualCount = 0;
1007
+ for (const vReq of validVisualRequests) {
1008
+ const docName = String(vReq.document || "");
1009
+ const checkDesc = String(vReq.check || "");
1010
+ const ruleId = String(vReq.ruleId);
1011
+ const matchedArtifact = ctx.artifacts.find((a) => a.fileName === docName) || ctx.artifacts[0];
1012
+ if (matchedArtifact && matchedArtifact.mimeType.startsWith("image/")) {
1013
+ const imgBuf = this.artifactStorage.readArtifactBuffer(matchedArtifact);
1014
+ const vRes = await this.invokeLlmJson({
1015
+ config: ctx.config,
1016
+ vision: true,
1017
+ systemPrompt: 'Verify the requested visual feature (signature, stamp, endorsement) on this document image. Return JSON: { "satisfied": boolean, "observation": string }.',
1018
+ userContent: [
1019
+ { type: "text", text: `Check "${checkDesc}" under rule ${ruleId}` },
1020
+ {
1021
+ type: "image_url",
1022
+ image_url: { url: `data:${matchedArtifact.mimeType};base64,${imgBuf.toString("base64")}` }
1023
+ }
1024
+ ],
1025
+ usage
1026
+ });
1027
+ if (vRes.satisfied === true) {
1028
+ satisfiedVisualCount += 1;
1029
+ } else {
1030
+ outstandingVisualChecks.push({
1031
+ document: docName,
1032
+ check: checkDesc,
1033
+ ruleId,
1034
+ reason: String(vRes.observation || "Visual element could not be confirmed")
1035
+ });
1036
+ }
1037
+ } else {
1038
+ const matchedDoc = docs.find((d) => d.fileName === docName);
1039
+ if (matchedDoc && /sign|stamp|ký|đóng dấu/i.test(matchedDoc.text)) {
1040
+ satisfiedVisualCount += 1;
1041
+ } else {
1042
+ outstandingVisualChecks.push({
1043
+ document: docName || (((_d = docs[0]) == null ? void 0 : _d.fileName) ?? "presentation"),
1044
+ check: checkDesc,
1045
+ ruleId,
1046
+ reason: "Requires physical/raster visual inspection of signature or endorsement"
1047
+ });
1048
+ }
1049
+ }
1050
+ }
1051
+ await ((_e = ctx.onProgress) == null ? void 0 : _e.call(ctx, 80, "Step 4-5/5: Adjudicating UCP 600 / ISBP 821 compliance & generating Vietnamese report"));
1052
+ const adjudication = await this.invokeLlmJson({
1053
+ config: ctx.config,
1054
+ systemPrompt: `Adjudicate the L/C presentation strictly under UCP 600 / ISBP 821.
1055
+ Allowed ruleIds ONLY:
1056
+ ${Array.from(
1057
+ import_du_contracts.VALID_LC_RULE_IDS
1058
+ ).join(
1059
+ ", "
1060
+ )}
1061
+ Return JSON: { "verdict": "COMPLIANT" | "DISCREPANT", "discrepancies": [{ "id": string, "severity": "MAJOR" | "MINOR" | "ADVISORY", "document": string, "field": string, "issue": string, "ruleId": string, "recommendation": string }], "summary": string, "report": string (detailed Markdown report in Vietnamese) }.`,
1062
+ userContent: JSON.stringify({
1063
+ documents: docs.map((d) => ({ fileName: d.fileName, content: d.markdown || d.text })),
1064
+ outstandingVisualChecks
1065
+ }),
1066
+ usage
1067
+ });
1068
+ const rawDiscrepancies = Array.isArray(adjudication.discrepancies) ? adjudication.discrepancies : [];
1069
+ const verifiedDiscrepancies = rawDiscrepancies.map((disc, index) => {
1070
+ var _a2;
1071
+ const cited = typeof disc.ruleId === "string" && import_du_contracts.VALID_LC_RULE_IDS.has(disc.ruleId) ? disc.ruleId : "UCP600-ART14-A";
1072
+ if (cited !== disc.ruleId) {
1073
+ warnings.push(`Normalized unregistered rule citation "${String(disc.ruleId)}" to UCP600-ART14-A.`);
1074
+ }
1075
+ const severityRaw = String(disc.severity || "MAJOR").toUpperCase();
1076
+ const severity = ["MAJOR", "MINOR", "ADVISORY"].includes(severityRaw) ? severityRaw : "MAJOR";
1077
+ return {
1078
+ id: String(disc.id || `DISC-${String(index + 1).padStart(2, "0")}`),
1079
+ severity,
1080
+ document: String(disc.document || ((_a2 = docs[0]) == null ? void 0 : _a2.fileName) || "unknown"),
1081
+ field: String(disc.field || "General"),
1082
+ issue: String(disc.issue || ""),
1083
+ ruleId: cited,
1084
+ recommendation: String(disc.recommendation || "Xin \xFD ki\u1EBFn ch\u1EA5p nh\u1EADn b\u1EA5t h\u1EE3p l\u1EC7 ho\u1EB7c tu ch\u1EC9nh ch\u1EE9ng t\u1EEB.")
1085
+ };
1086
+ });
1087
+ const majorDiscrepancies = verifiedDiscrepancies.filter((d) => d.severity === "MAJOR").length;
1088
+ const minorDiscrepancies = verifiedDiscrepancies.filter((d) => d.severity === "MINOR").length;
1089
+ const advisoryCount = verifiedDiscrepancies.filter((d) => d.severity === "ADVISORY").length;
1090
+ const totalDiscrepancies = verifiedDiscrepancies.length;
1091
+ const canBeCompliant = outstandingVisualChecks.length === 0 && majorDiscrepancies === 0 && minorDiscrepancies === 0;
1092
+ const verdict = canBeCompliant && adjudication.verdict === "COMPLIANT" ? "COMPLIANT" : "DISCREPANT";
1093
+ const citedRuleIds = Array.from(new Set(verifiedDiscrepancies.map((d) => d.ruleId)));
1094
+ return {
1095
+ kind: "completed",
1096
+ outputPayload: {
1097
+ resultVersion: "lc-checker-result-v1",
1098
+ businessId: "lc-checker",
1099
+ businessVersion: "1.2.0",
1100
+ verdict,
1101
+ recommendation: verdict === "COMPLIANT" ? "PROCEED_TO_HUMAN_SIGN_OFF" : "RESERVE_FOR_REVIEW",
1102
+ totalDiscrepancies,
1103
+ majorDiscrepancies,
1104
+ minorDiscrepancies,
1105
+ advisoryCount,
1106
+ documentsPresent: Array.isArray(screenResult.documentsPresent) ? screenResult.documentsPresent : docs.map((d) => d.fileName),
1107
+ documentsMissing: Array.isArray(screenResult.documentsMissing) ? screenResult.documentsMissing : [],
1108
+ discrepancies: verifiedDiscrepancies,
1109
+ summary: typeof adjudication.summary === "string" ? adjudication.summary : `Ph\xE1t hi\u1EC7n ${totalDiscrepancies} \u0111i\u1EC3m l\u01B0u \xFD/b\u1EA5t h\u1EE3p l\u1EC7.`,
1110
+ report: typeof adjudication.report === "string" ? adjudication.report : "# B\xC1O C\xC1O KI\u1EC2M TRA B\u1ED8 CH\u1EE8NG T\u1EEA T\xCDN D\u1EE4NG TH\u01AF (L/C)",
1111
+ evidence: {
1112
+ filesSubmitted: ctx.artifacts.length,
1113
+ filesOcred: docs.length,
1114
+ filesWithoutOcrText,
1115
+ totalOcrChars,
1116
+ ruleSetId: import_du_contracts.LC_RULESET_ID,
1117
+ ruleSetVersion: String(ctx.input.ruleSetVersion || import_du_contracts.LC_RULESET_VERSION),
1118
+ ruleSetStatus: "PROVISIONAL",
1119
+ citedRuleIds,
1120
+ visualVerification: {
1121
+ requested: validVisualRequests.length,
1122
+ satisfied: satisfiedVisualCount,
1123
+ complete: outstandingVisualChecks.length === 0
1124
+ }
1125
+ },
1126
+ humanSignOffRequired: true,
1127
+ outstandingVisualChecks,
1128
+ failedChildren: []
1129
+ },
1130
+ extraOutputArtifacts: [],
1131
+ coverageOutcomes: outcomes,
1132
+ usage: usage.toMetrics(),
1133
+ warnings
1134
+ };
1135
+ }
1136
+ /**
1137
+ * `example-review@1.0.0` — Multi-document compliance review (1..10 files) with optional HITL approval.
1138
+ */
1139
+ async executeExampleReview(ctx, usage, warnings) {
1140
+ if (ctx.artifacts.length < 1 || ctx.artifacts.length > 10) {
1141
+ throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "example-review requires between 1 and 10 documents"));
1142
+ }
1143
+ const reviewId = String(ctx.input.reviewId || ctx.operationId);
1144
+ let itemReviews = [];
1145
+ let outcomes = [];
1146
+ if (ctx.checkpointData && Array.isArray(ctx.checkpointData.itemReviews)) {
1147
+ itemReviews = ctx.checkpointData.itemReviews;
1148
+ outcomes = ctx.checkpointData.outcomes || [];
1149
+ } else {
1150
+ const parsedBundle = await this.readAndOcrDocuments(ctx, usage);
1151
+ outcomes = parsedBundle.outcomes;
1152
+ const useAi = ctx.input.useAi !== false && Boolean(this.resolveAiManager());
1153
+ itemReviews = await mapWithConcurrency(parsedBundle.docs, 4, async (doc) => {
1154
+ if (!useAi) {
1155
+ return {
1156
+ fileName: doc.fileName,
1157
+ format: doc.detectedFormat,
1158
+ pageCount: doc.selectedPages.length,
1159
+ charCount: doc.text.length,
1160
+ status: doc.text.length > 0 ? "PASS" : "EMPTY"
1161
+ };
1162
+ }
1163
+ const aiItem = await this.invokeLlmJson({
1164
+ config: ctx.config,
1165
+ systemPrompt: `Review this document item against criteria ${JSON.stringify(
1166
+ ctx.input.criteria || ["completeness", "consistency"]
1167
+ )}. Return JSON: { "status": "PASS" | "REVIEW_REQUIRED", "summary": string, "issues": string[] }.`,
1168
+ userContent: `File: ${doc.fileName}
1169
+
1170
+ ${doc.markdown || doc.text}`,
1171
+ usage
1172
+ });
1173
+ return {
1174
+ fileName: doc.fileName,
1175
+ format: doc.detectedFormat,
1176
+ pageCount: doc.selectedPages.length,
1177
+ ...aiItem
1178
+ };
1179
+ });
1180
+ if (ctx.input.requireApproval === true && !ctx.resumedInput) {
1181
+ return {
1182
+ kind: "waiting_input",
1183
+ waitState: {
1184
+ waitId: "compliance-officer-approval",
1185
+ prompt: "Compliance Officer approval required to finalize multi-document review.",
1186
+ inputSchema: {
1187
+ type: "object",
1188
+ properties: {
1189
+ approved: { type: "boolean", default: true },
1190
+ approver: { type: "string" },
1191
+ comment: { type: "string" }
1192
+ },
1193
+ required: ["approved"]
1194
+ },
1195
+ previewData: { reviewId, items: itemReviews }
1196
+ },
1197
+ checkpointData: { itemReviews, outcomes },
1198
+ usage: usage.toMetrics()
1199
+ };
1200
+ }
1201
+ }
1202
+ return {
1203
+ kind: "completed",
1204
+ outputPayload: {
1205
+ resultVersion: "example-review-result-v1",
1206
+ businessId: "example-review",
1207
+ businessVersion: "1.0.0",
1208
+ reviewId,
1209
+ approved: ctx.resumedInput ? Boolean(ctx.resumedInput.approved) : true,
1210
+ approverDecision: ctx.resumedInput ?? null,
1211
+ items: itemReviews
1212
+ },
1213
+ extraOutputArtifacts: [],
1214
+ coverageOutcomes: outcomes,
1215
+ usage: usage.toMetrics(),
1216
+ warnings
1217
+ };
1218
+ }
1219
+ }
1220
+ // Annotate the CommonJS export names for ESM import in node:
1221
+ 0 && (module.exports = {
1222
+ BuiltinBusinessEngine
1223
+ });