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
@@ -0,0 +1,1544 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import type { Application } from '@nocobase/server';
4
+ import {
5
+ createProblem,
6
+ LC_RULESET_ID,
7
+ LC_RULESET_VERSION,
8
+ parsePageRangeString,
9
+ UCP600_ISBP821_RULES,
10
+ VALID_LC_RULE_IDS,
11
+ type CoverageOutcome,
12
+ type DocumentInputPlanItem,
13
+ type PageSelectionSpec,
14
+ type UsageMetrics,
15
+ type WaitState,
16
+ } from '../contracts/du-contracts';
17
+ import type { ServiceConfig } from '../types';
18
+ import {
19
+ ArtifactStorageService,
20
+ DuHttpError,
21
+ type ArtifactRecord,
22
+ type ParsedDocument,
23
+ } from './ArtifactStorageService';
24
+
25
+ interface LlmMessage {
26
+ role: 'system' | 'user';
27
+ content: unknown;
28
+ }
29
+
30
+ interface LlmResponseLike {
31
+ content?: unknown;
32
+ usage_metadata?: {
33
+ input_tokens?: number;
34
+ output_tokens?: number;
35
+ };
36
+ response_metadata?: {
37
+ tokenUsage?: {
38
+ promptTokens?: number;
39
+ completionTokens?: number;
40
+ };
41
+ };
42
+ }
43
+
44
+ interface AiManagerRuntime {
45
+ resolveModel?: (model?: { llmService?: string; model?: string } | null) => Promise<{
46
+ llmService: string;
47
+ model: string;
48
+ }>;
49
+ getLLMService: (options: { llmService: string; model: string }) => Promise<{
50
+ provider: {
51
+ invoke: (context: { messages: LlmMessage[] }) => Promise<LlmResponseLike>;
52
+ };
53
+ model: string;
54
+ }>;
55
+ listAllEnabledModels?: () => Promise<
56
+ Array<{
57
+ llmService: string;
58
+ llmServiceTitle: string;
59
+ provider: string;
60
+ enabledModels: Array<{ label: string; value: string }>;
61
+ }>
62
+ >;
63
+ }
64
+
65
+ export interface EngineExecutionContext {
66
+ operationId: string;
67
+ tenantId: string;
68
+ businessId: string;
69
+ action: string;
70
+ input: Record<string, unknown>;
71
+ artifacts: ArtifactRecord[];
72
+ planItems: DocumentInputPlanItem[];
73
+ config: ServiceConfig;
74
+ resumedInput?: Record<string, unknown>;
75
+ checkpointData?: Record<string, unknown>;
76
+ userId?: number;
77
+ onProgress?: (percent: number, message: string) => Promise<void>;
78
+ }
79
+
80
+ export type EngineExecutionOutcome =
81
+ | {
82
+ kind: 'completed';
83
+ outputPayload: Record<string, unknown>;
84
+ extraOutputArtifacts: ArtifactRecord[];
85
+ coverageOutcomes: CoverageOutcome[];
86
+ usage: UsageMetrics;
87
+ warnings: string[];
88
+ }
89
+ | {
90
+ kind: 'waiting_input';
91
+ waitState: WaitState;
92
+ checkpointData: Record<string, unknown>;
93
+ usage: UsageMetrics;
94
+ };
95
+
96
+ function isRecord(value: unknown): value is Record<string, unknown> {
97
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
98
+ }
99
+
100
+ function extractMessageText(content: unknown): string {
101
+ if (typeof content === 'string') return content;
102
+ if (Array.isArray(content)) {
103
+ return content
104
+ .map((part) => {
105
+ if (typeof part === 'string') return part;
106
+ if (isRecord(part) && typeof part.text === 'string') return part.text;
107
+ return '';
108
+ })
109
+ .filter(Boolean)
110
+ .join('\n');
111
+ }
112
+ return content == null ? '' : JSON.stringify(content);
113
+ }
114
+
115
+ function parseJsonFromLlm(rawText: string): Record<string, unknown> {
116
+ const trimmed = rawText.trim();
117
+ const fenced = /```(?:json)?\s*([\s\S]*?)```/i.exec(trimmed);
118
+ const candidate = fenced ? fenced[1].trim() : trimmed;
119
+ try {
120
+ const parsed: unknown = JSON.parse(candidate);
121
+ return isRecord(parsed) ? parsed : { value: parsed };
122
+ } catch {
123
+ const firstBrace = candidate.indexOf('{');
124
+ const lastBrace = candidate.lastIndexOf('}');
125
+ if (firstBrace >= 0 && lastBrace > firstBrace) {
126
+ const sliced = candidate.slice(firstBrace, lastBrace + 1);
127
+ const parsed: unknown = JSON.parse(sliced);
128
+ return isRecord(parsed) ? parsed : { value: parsed };
129
+ }
130
+ throw new Error('Model response did not contain valid JSON output');
131
+ }
132
+ }
133
+
134
+ async function mapWithConcurrency<T, R>(
135
+ items: readonly T[],
136
+ concurrency: number,
137
+ worker: (item: T, index: number) => Promise<R>,
138
+ ): Promise<R[]> {
139
+ const limit = Math.max(1, Math.min(concurrency, items.length || 1));
140
+ const results = new Array<R>(items.length);
141
+ let cursor = 0;
142
+
143
+ const runWorker = async () => {
144
+ while (cursor < items.length) {
145
+ const idx = cursor;
146
+ cursor += 1;
147
+ results[idx] = await worker(items[idx], idx);
148
+ }
149
+ };
150
+
151
+ await Promise.all(Array.from({ length: limit }, () => runWorker()));
152
+ return results;
153
+ }
154
+
155
+ function computeLineDiff(sourceText: string, targetText: string) {
156
+ const a = sourceText.split(/\r?\n/);
157
+ const b = targetText.split(/\r?\n/);
158
+ const diffLines: string[] = [];
159
+ let additions = 0;
160
+ let deletions = 0;
161
+ let unchangedLines = 0;
162
+
163
+ // Bounded LCS for reasonable document sizes; linear scan fallback for huge files.
164
+ if (a.length * b.length <= 400_000) {
165
+ const dp: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
166
+ for (let i = a.length - 1; i >= 0; i -= 1) {
167
+ for (let j = b.length - 1; j >= 0; j -= 1) {
168
+ dp[i][j] = a[i] === b[j] ? dp[i + 1][j + 1] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);
169
+ }
170
+ }
171
+ let i = 0;
172
+ let j = 0;
173
+ while (i < a.length && j < b.length) {
174
+ if (a[i] === b[j]) {
175
+ diffLines.push(` ${a[i]}`);
176
+ unchangedLines += 1;
177
+ i += 1;
178
+ j += 1;
179
+ } else if (dp[i + 1][j] >= dp[i][j + 1]) {
180
+ diffLines.push(`- ${a[i]}`);
181
+ deletions += 1;
182
+ i += 1;
183
+ } else {
184
+ diffLines.push(`+ ${b[j]}`);
185
+ additions += 1;
186
+ j += 1;
187
+ }
188
+ }
189
+ while (i < a.length) {
190
+ diffLines.push(`- ${a[i]}`);
191
+ deletions += 1;
192
+ i += 1;
193
+ }
194
+ while (j < b.length) {
195
+ diffLines.push(`+ ${b[j]}`);
196
+ additions += 1;
197
+ j += 1;
198
+ }
199
+ } else {
200
+ const maxLen = Math.max(a.length, b.length);
201
+ for (let k = 0; k < maxLen; k += 1) {
202
+ if (k < a.length && k < b.length && a[k] === b[k]) {
203
+ diffLines.push(` ${a[k]}`);
204
+ unchangedLines += 1;
205
+ } else {
206
+ if (k < a.length) {
207
+ diffLines.push(`- ${a[k]}`);
208
+ deletions += 1;
209
+ }
210
+ if (k < b.length) {
211
+ diffLines.push(`+ ${b[k]}`);
212
+ additions += 1;
213
+ }
214
+ }
215
+ }
216
+ }
217
+
218
+ return {
219
+ unifiedDiff: diffLines.join('\n'),
220
+ additions,
221
+ deletions,
222
+ unchangedLines,
223
+ };
224
+ }
225
+
226
+ function redactTextLocally(text: string, patterns: readonly string[]): string {
227
+ let output = text;
228
+ const normalized = patterns.length > 0 ? patterns : ['CCCD', 'PHONE_NUMBER', 'EMAIL'];
229
+
230
+ for (const patternName of normalized) {
231
+ const upper = patternName.toUpperCase();
232
+ if (upper === 'CCCD' || upper === 'ID_CARD') {
233
+ output = output.replace(/\b\d{12}\b/g, '[REDACTED]').replace(/\b\d{9}\b/g, '[REDACTED]');
234
+ } else if (upper === 'PHONE' || upper === 'PHONE_NUMBER') {
235
+ output = output.replace(/(?:\+?84|0)(?:3|5|7|8|9)\d{8}\b/g, '[REDACTED]');
236
+ } else if (upper === 'EMAIL') {
237
+ output = output.replace(/[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/g, '[REDACTED]');
238
+ } else if (upper === 'BANK_ACCOUNT' || upper === 'CARD_NUMBER') {
239
+ output = output.replace(/\b\d{10,19}\b/g, '[REDACTED]');
240
+ } else if (upper === 'TAX_ID') {
241
+ output = output.replace(/\b\d{10}(?:-\d{3})?\b/g, '[REDACTED]');
242
+ } else {
243
+ try {
244
+ const customRe = new RegExp(patternName, 'gi');
245
+ output = output.replace(customRe, '[REDACTED]');
246
+ } catch {
247
+ // Ignore invalid user regex pattern
248
+ }
249
+ }
250
+ }
251
+ return output;
252
+ }
253
+
254
+ function mergeTemplateLocally(template: string, variables: Record<string, unknown>): string {
255
+ return template.replace(/\{\{\s*([a-zA-Z0-9_.-]+)\s*\}\}/g, (_match, rawPath: string) => {
256
+ const val = rawPath.split('.').reduce<unknown>((acc, key) => (isRecord(acc) ? acc[key] : undefined), variables);
257
+ if (val === undefined || val === null) return '';
258
+ return typeof val === 'object' ? JSON.stringify(val) : String(val);
259
+ });
260
+ }
261
+
262
+ function markdownToSimpleHtml(md: string): string {
263
+ const escaped = md.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
264
+ return escaped
265
+ .replace(/^### (.+)$/gm, '<h3>$1</h3>')
266
+ .replace(/^## (.+)$/gm, '<h2>$1</h2>')
267
+ .replace(/^# (.+)$/gm, '<h1>$1</h1>')
268
+ .replace(/^- (.+)$/gm, '<li>$1</li>')
269
+ .replace(/\n\n+/g, '</p><p>')
270
+ .replace(/^/, '<p>')
271
+ .concat('</p>');
272
+ }
273
+
274
+ class UsageAccumulator {
275
+ private inputTokens = 0;
276
+ private outputTokens = 0;
277
+ private model = 'local-deterministic';
278
+ private provider = 'builtin';
279
+ private measured = false;
280
+
281
+ add(params: { inputTokens: number; outputTokens: number; model: string; provider?: string; measured: boolean }) {
282
+ this.inputTokens += params.inputTokens;
283
+ this.outputTokens += params.outputTokens;
284
+ this.model = params.model;
285
+ if (params.provider) this.provider = params.provider;
286
+ if (params.measured) this.measured = true;
287
+ }
288
+
289
+ toMetrics(): UsageMetrics {
290
+ // Approximate $1.50 / 1M input + $6.00 / 1M output when provider does not emit USD billing
291
+ const costMicrousd = Math.round(this.inputTokens * 1.5 + this.outputTokens * 6);
292
+ return {
293
+ inputTokens: this.inputTokens,
294
+ outputTokens: this.outputTokens,
295
+ costMicrousd,
296
+ costStatus:
297
+ this.inputTokens === 0 && this.outputTokens === 0 ? 'final' : this.measured ? 'measured' : 'estimated',
298
+ model: this.model,
299
+ provider: this.provider,
300
+ measurement: this.measured || (this.inputTokens === 0 && this.outputTokens === 0) ? 'measured' : 'estimated',
301
+ };
302
+ }
303
+ }
304
+
305
+ export class BuiltinBusinessEngine {
306
+ private readonly app: Application;
307
+ private readonly artifactStorage: ArtifactStorageService;
308
+ private readonly runSchemaPipeline?: (
309
+ pipelineRef: { pipelineId?: number; pipelineName?: string },
310
+ input: Record<string, unknown>,
311
+ userId?: number,
312
+ ) => Promise<Record<string, unknown>>;
313
+
314
+ constructor(
315
+ app: Application,
316
+ artifactStorage: ArtifactStorageService,
317
+ runSchemaPipeline?: (
318
+ pipelineRef: { pipelineId?: number; pipelineName?: string },
319
+ input: Record<string, unknown>,
320
+ userId?: number,
321
+ ) => Promise<Record<string, unknown>>,
322
+ ) {
323
+ this.app = app;
324
+ this.artifactStorage = artifactStorage;
325
+ this.runSchemaPipeline = runSchemaPipeline;
326
+ }
327
+
328
+ resolveAiManager(): AiManagerRuntime | null {
329
+ const appWithAi = this.app as Application & { aiManager?: unknown };
330
+ const candidates: unknown[] = [
331
+ appWithAi.aiManager,
332
+ this.app.pm?.get?.('@nocobase/plugin-ai')?.aiManager,
333
+ this.app.pm?.get?.('ai')?.aiManager,
334
+ ];
335
+ for (const candidate of candidates) {
336
+ if (candidate && typeof (candidate as AiManagerRuntime).getLLMService === 'function') {
337
+ return candidate as AiManagerRuntime;
338
+ }
339
+ }
340
+ return null;
341
+ }
342
+
343
+ async listAvailableLlmServices(): Promise<
344
+ Array<{
345
+ llmService: string;
346
+ llmServiceTitle: string;
347
+ provider: string;
348
+ enabledModels: Array<{ label: string; value: string }>;
349
+ }>
350
+ > {
351
+ const aiManager = this.resolveAiManager();
352
+ if (!aiManager?.listAllEnabledModels) return [];
353
+ try {
354
+ return await aiManager.listAllEnabledModels();
355
+ } catch {
356
+ return [];
357
+ }
358
+ }
359
+
360
+ private async invokeLlm(params: {
361
+ config: ServiceConfig;
362
+ systemPrompt: string;
363
+ userContent: string | Array<Record<string, unknown>>;
364
+ vision?: boolean;
365
+ usage: UsageAccumulator;
366
+ }): Promise<string> {
367
+ const aiManager = this.resolveAiManager();
368
+ if (!aiManager) {
369
+ throw new DuHttpError(
370
+ createProblem(
371
+ 503,
372
+ 'TEMPORARY_UNAVAILABLE',
373
+ 'NocoBase @nocobase/plugin-ai LLM service is not configured or enabled for built-in AI execution',
374
+ ),
375
+ );
376
+ }
377
+
378
+ const preferredService = params.vision
379
+ ? params.config.visionLlmService || params.config.llmService
380
+ : params.config.llmService;
381
+ const preferredModel = params.vision
382
+ ? params.config.visionLlmModel || params.config.llmModel
383
+ : params.config.llmModel;
384
+
385
+ let resolved: { llmService: string; model: string };
386
+ if (preferredService && preferredModel) {
387
+ resolved = { llmService: preferredService, model: preferredModel };
388
+ } else if (aiManager.resolveModel) {
389
+ try {
390
+ resolved = await aiManager.resolveModel(
391
+ preferredService && preferredModel ? { llmService: preferredService, model: preferredModel } : null,
392
+ );
393
+ } catch (err) {
394
+ throw new DuHttpError(
395
+ createProblem(
396
+ 503,
397
+ 'TEMPORARY_UNAVAILABLE',
398
+ err instanceof Error ? err.message : 'No enabled LLM service found in NocoBase AI settings',
399
+ ),
400
+ );
401
+ }
402
+ } else {
403
+ throw new DuHttpError(
404
+ createProblem(503, 'TEMPORARY_UNAVAILABLE', 'Please configure an active LLM service and model in NocoBase'),
405
+ );
406
+ }
407
+
408
+ const { provider, model } = await aiManager.getLLMService(resolved);
409
+ const response = await provider.invoke({
410
+ messages: [
411
+ { role: 'system', content: params.systemPrompt },
412
+ { role: 'user', content: params.userContent },
413
+ ],
414
+ });
415
+
416
+ const text = extractMessageText(response.content);
417
+ const metaIn = response.usage_metadata?.input_tokens ?? response.response_metadata?.tokenUsage?.promptTokens;
418
+ const metaOut = response.usage_metadata?.output_tokens ?? response.response_metadata?.tokenUsage?.completionTokens;
419
+ const measured = typeof metaIn === 'number' || typeof metaOut === 'number';
420
+ const serializedUser =
421
+ typeof params.userContent === 'string' ? params.userContent : JSON.stringify(params.userContent);
422
+
423
+ params.usage.add({
424
+ inputTokens:
425
+ typeof metaIn === 'number' ? metaIn : Math.ceil((params.systemPrompt.length + serializedUser.length) / 4),
426
+ outputTokens: typeof metaOut === 'number' ? metaOut : Math.ceil(text.length / 4),
427
+ model: model || resolved.model,
428
+ provider: resolved.llmService,
429
+ measured,
430
+ });
431
+
432
+ return text;
433
+ }
434
+
435
+ private async invokeLlmJson(params: {
436
+ config: ServiceConfig;
437
+ systemPrompt: string;
438
+ userContent: string | Array<Record<string, unknown>>;
439
+ vision?: boolean;
440
+ usage: UsageAccumulator;
441
+ }): Promise<Record<string, unknown>> {
442
+ const raw = await this.invokeLlm({
443
+ ...params,
444
+ systemPrompt: `${params.systemPrompt}\nReturn ONLY valid JSON without markdown commentary.`,
445
+ });
446
+ return parseJsonFromLlm(raw);
447
+ }
448
+
449
+ private resolveSelectionForArtifact(
450
+ artifactId: string,
451
+ planItems: readonly DocumentInputPlanItem[],
452
+ fallbackPagesSpec?: string,
453
+ ): PageSelectionSpec {
454
+ const planItem = planItems.find((p) => p.artifactId === artifactId);
455
+ if (planItem) return planItem.selection;
456
+ if (fallbackPagesSpec && fallbackPagesSpec.trim()) {
457
+ const ranges = parsePageRangeString(fallbackPagesSpec);
458
+ if (ranges.length > 0) {
459
+ return { kind: 'ranges', ranges };
460
+ }
461
+ }
462
+ return { kind: 'all' };
463
+ }
464
+
465
+ private async readAndOcrDocuments(
466
+ ctx: EngineExecutionContext,
467
+ usage: UsageAccumulator,
468
+ options: { forceVisionOcr?: boolean; digitize?: boolean } = {},
469
+ ): Promise<{ docs: ParsedDocument[]; outcomes: CoverageOutcome[] }> {
470
+ const pagesInput = typeof ctx.input.pages === 'string' ? ctx.input.pages : undefined;
471
+ const docs: ParsedDocument[] = [];
472
+ const outcomes: CoverageOutcome[] = [];
473
+
474
+ for (const artifact of ctx.artifacts) {
475
+ const selection = this.resolveSelectionForArtifact(artifact.artifactId, ctx.planItems, pagesInput);
476
+ const parsed = await this.artifactStorage.parseArtifactPages(artifact, selection);
477
+
478
+ if (
479
+ (options.forceVisionOcr || options.digitize || parsed.requiresVision) &&
480
+ (!parsed.text.trim() || options.digitize || options.forceVisionOcr)
481
+ ) {
482
+ const buffer = this.artifactStorage.readArtifactBuffer(artifact);
483
+ if (artifact.mimeType.startsWith('image/')) {
484
+ const prompt = options.digitize
485
+ ? 'Digitize this handwritten/printed form accurately, preserving all labels, values, and checkbox states ([x]/[ ]) in clean Markdown.'
486
+ : 'Transcribe all visible text, tables, headers, and stamps from this document image into clean Markdown.';
487
+ const ocrMd = await this.invokeLlm({
488
+ config: ctx.config,
489
+ systemPrompt: prompt,
490
+ vision: true,
491
+ usage,
492
+ userContent: [
493
+ {
494
+ type: 'image_url',
495
+ image_url: { url: `data:${artifact.mimeType};base64,${buffer.toString('base64')}` },
496
+ },
497
+ ],
498
+ });
499
+ parsed.markdown = ocrMd.trim();
500
+ parsed.text = ocrMd.trim();
501
+ parsed.parser = options.digitize ? 'vision-digitize' : 'vision-ocr';
502
+ } else if (parsed.text.trim() && options.digitize) {
503
+ const digitized = await this.invokeLlm({
504
+ config: ctx.config,
505
+ systemPrompt:
506
+ 'Normalize and structure all form fields, checkboxes, and tables from this raw document text into clean Markdown.',
507
+ userContent: parsed.text,
508
+ usage,
509
+ });
510
+ parsed.markdown = digitized.trim();
511
+ parsed.text = digitized.trim();
512
+ parsed.parser = 'llm-digitize';
513
+ }
514
+ }
515
+
516
+ docs.push(parsed);
517
+ outcomes.push({
518
+ artifactId: artifact.artifactId,
519
+ selection,
520
+ status: 'processed',
521
+ pagesProcessed: parsed.selectedPages.map((p) => p.pageNumber),
522
+ outputRefs: [],
523
+ });
524
+ }
525
+
526
+ return { docs, outcomes };
527
+ }
528
+
529
+ async execute(ctx: EngineExecutionContext): Promise<EngineExecutionOutcome> {
530
+ const usage = new UsageAccumulator();
531
+ const warnings: string[] = [];
532
+
533
+ if (ctx.businessId === 'lc-checker') {
534
+ return this.executeLcChecker(ctx, usage, warnings);
535
+ }
536
+ if (ctx.businessId === 'example-review') {
537
+ return this.executeExampleReview(ctx, usage, warnings);
538
+ }
539
+ if (ctx.businessId !== 'document-core') {
540
+ throw new DuHttpError(createProblem(404, 'NOT_FOUND', `Unknown businessId "${ctx.businessId}"`));
541
+ }
542
+
543
+ switch (ctx.action) {
544
+ case 'ingest':
545
+ return this.executeIngest(ctx, usage, warnings);
546
+ case 'extract':
547
+ return this.executeExtract(ctx, usage, warnings);
548
+ case 'analyze':
549
+ return this.executeAnalyze(ctx, usage, warnings);
550
+ case 'transform':
551
+ return this.executeTransform(ctx, usage, warnings);
552
+ case 'generate':
553
+ return this.executeGenerate(ctx, usage, warnings);
554
+ case 'compare':
555
+ return this.executeCompare(ctx, usage, warnings);
556
+ case 'disbursement':
557
+ return this.executeDisbursementWorkflow(ctx, usage, warnings);
558
+ case 'doc-compare':
559
+ return this.executeDocCompareWorkflow(ctx, usage, warnings);
560
+ case 'schema-workflow':
561
+ return this.executeSchemaWorkflow(ctx, usage, warnings);
562
+ default:
563
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', `Unsupported document-core action "${ctx.action}"`));
564
+ }
565
+ }
566
+
567
+ private async executeIngest(
568
+ ctx: EngineExecutionContext,
569
+ usage: UsageAccumulator,
570
+ warnings: string[],
571
+ ): Promise<EngineExecutionOutcome> {
572
+ if (ctx.artifacts.length === 0) {
573
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', 'ingest requires at least one input artifact'));
574
+ }
575
+
576
+ const mode = String(ctx.input.mode || 'parse');
577
+ if (!['parse', 'ocr', 'digitize', 'split'].includes(mode)) {
578
+ throw new DuHttpError(
579
+ createProblem(422, 'INVALID_SCHEMA', `Invalid ingest mode "${mode}"`, {
580
+ errors: [{ pointer: '/input/mode', message: 'Expected parse | ocr | digitize | split' }],
581
+ }),
582
+ );
583
+ }
584
+
585
+ if (mode === 'split') {
586
+ const target = ctx.artifacts[0];
587
+ const parsedAll = await this.artifactStorage.parseArtifactPages(target, { kind: 'all' });
588
+ const rawPages =
589
+ typeof ctx.input.pages === 'string' && ctx.input.pages.trim()
590
+ ? ctx.input.pages
591
+ : `1-${parsedAll.totalPageCount}`;
592
+ let ranges;
593
+ try {
594
+ ranges = parsePageRangeString(rawPages, 500);
595
+ } catch (err) {
596
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', err instanceof Error ? err.message : String(err)));
597
+ }
598
+
599
+ const extraOutputArtifacts: ArtifactRecord[] = [];
600
+ const splitArtifacts: Array<{
601
+ artifactId: string;
602
+ fileName: string;
603
+ pageCount: number;
604
+ pageRange: string;
605
+ }> = [];
606
+
607
+ const effectiveRanges = ranges.length > 0 ? ranges : [{ from: 1, to: parsedAll.totalPageCount }];
608
+ for (let idx = 0; idx < effectiveRanges.length; idx += 1) {
609
+ const range = effectiveRanges[idx];
610
+ const slice = await this.artifactStorage.parseArtifactPages(target, { kind: 'ranges', ranges: [range] });
611
+ const partName = `part-${idx + 1}-pages-${range.from}-${range.to}.md`;
612
+ const createdPart = await this.artifactStorage.createReadyArtifactFromBuffer({
613
+ tenantId: ctx.tenantId,
614
+ operationId: ctx.operationId,
615
+ role: 'output',
616
+ fileName: partName,
617
+ mimeType: 'text/markdown',
618
+ buffer: Buffer.from(slice.markdown || slice.text, 'utf8'),
619
+ userId: ctx.userId,
620
+ });
621
+ extraOutputArtifacts.push(createdPart);
622
+ splitArtifacts.push({
623
+ artifactId: createdPart.artifactId,
624
+ fileName: partName,
625
+ pageCount: slice.selectedPages.length,
626
+ pageRange: `${range.from}-${range.to}`,
627
+ });
628
+ }
629
+
630
+ return {
631
+ kind: 'completed',
632
+ outputPayload: {
633
+ version: 'document-core-result-v1',
634
+ splitArtifacts,
635
+ metadata: {
636
+ pageCount: parsedAll.totalPageCount,
637
+ detectedFormat: parsedAll.detectedFormat,
638
+ parser: parsedAll.parser,
639
+ provenance: 'split',
640
+ },
641
+ },
642
+ extraOutputArtifacts,
643
+ coverageOutcomes: [
644
+ {
645
+ artifactId: target.artifactId,
646
+ selection: { kind: 'ranges', ranges: effectiveRanges },
647
+ status: 'processed',
648
+ outputRefs: extraOutputArtifacts.map((a) => a.artifactId),
649
+ },
650
+ ],
651
+ usage: usage.toMetrics(),
652
+ warnings,
653
+ };
654
+ }
655
+
656
+ const { docs, outcomes } = await this.readAndOcrDocuments(ctx, usage, {
657
+ forceVisionOcr: mode === 'ocr',
658
+ digitize: mode === 'digitize',
659
+ });
660
+
661
+ const markdown = docs.map((d) => (docs.length > 1 ? `## ${d.fileName}\n\n${d.markdown}` : d.markdown)).join('\n\n');
662
+ const text = docs.map((d) => d.text).join('\n\n');
663
+ const totalPages = docs.reduce((sum, d) => sum + d.selectedPages.length, 0);
664
+
665
+ return {
666
+ kind: 'completed',
667
+ outputPayload: {
668
+ version: 'document-core-result-v1',
669
+ markdown,
670
+ text,
671
+ metadata: {
672
+ pageCount: totalPages,
673
+ detectedFormat: docs[0]?.detectedFormat || 'unknown',
674
+ parser: docs[0]?.parser || 'local',
675
+ provenance: mode,
676
+ },
677
+ },
678
+ extraOutputArtifacts: [],
679
+ coverageOutcomes: outcomes,
680
+ usage: usage.toMetrics(),
681
+ warnings,
682
+ };
683
+ }
684
+
685
+ private async executeExtract(
686
+ ctx: EngineExecutionContext,
687
+ usage: UsageAccumulator,
688
+ warnings: string[],
689
+ ): Promise<EngineExecutionOutcome> {
690
+ const variant = String(ctx.input.type || 'invoice');
691
+ if (!['invoice', 'contract', 'id-card', 'receipt', 'table', 'custom'].includes(variant)) {
692
+ throw new DuHttpError(
693
+ createProblem(422, 'INVALID_SCHEMA', `Invalid extract type "${variant}"`, {
694
+ errors: [{ pointer: '/input/type', message: 'Invalid enum value' }],
695
+ }),
696
+ );
697
+ }
698
+
699
+ const inlineText = typeof ctx.input.text === 'string' ? ctx.input.text : '';
700
+ const { docs, outcomes } =
701
+ ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
702
+ const combinedText = [inlineText, ...docs.map((d) => `### File: ${d.fileName}\n${d.markdown || d.text}`)]
703
+ .filter(Boolean)
704
+ .join('\n\n');
705
+
706
+ if (!combinedText.trim()) {
707
+ throw new DuHttpError(
708
+ createProblem(422, 'INVALID_SCHEMA', 'No document content or input text provided for extract'),
709
+ );
710
+ }
711
+
712
+ const schemaPrompts: Record<string, string> = {
713
+ invoice:
714
+ '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 }.',
715
+ contract:
716
+ '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[] }.',
717
+ 'id-card':
718
+ '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 }.',
719
+ receipt:
720
+ 'Extract receipt fields as JSON: { "merchantName": string, "receiptDate": string, "items": [{"name","quantity","price"}], "total": number, "currency": string, "paymentMethod": string }.',
721
+ table:
722
+ 'Extract all tables from the document as JSON: { "tables": [{ "title": string, "headers": string[], "rows": string[][] }] }.',
723
+ custom: `Extract structured JSON matching this specification: ${JSON.stringify(
724
+ ctx.input.schema || ctx.input.fields || { summary: 'string' },
725
+ )}.`,
726
+ };
727
+
728
+ const data = await this.invokeLlmJson({
729
+ config: ctx.config,
730
+ systemPrompt: `You are a high-precision Document Understanding extraction engine.\n${schemaPrompts[variant]}`,
731
+ userContent: combinedText,
732
+ usage,
733
+ });
734
+
735
+ return {
736
+ kind: 'completed',
737
+ outputPayload: {
738
+ version: 'document-core-result-v1',
739
+ data,
740
+ provenance: { slot: 'reasoning', action: 'extract', variant },
741
+ },
742
+ extraOutputArtifacts: [],
743
+ coverageOutcomes: outcomes,
744
+ usage: usage.toMetrics(),
745
+ warnings,
746
+ };
747
+ }
748
+
749
+ private async executeAnalyze(
750
+ ctx: EngineExecutionContext,
751
+ usage: UsageAccumulator,
752
+ warnings: string[],
753
+ ): Promise<EngineExecutionOutcome> {
754
+ const task = String(ctx.input.task || 'classify');
755
+ if (!['classify', 'sentiment', 'compliance', 'fact-check', 'quality', 'risk', 'summarize-eval'].includes(task)) {
756
+ throw new DuHttpError(
757
+ createProblem(422, 'INVALID_SCHEMA', `Invalid analyze task "${task}"`, {
758
+ errors: [{ pointer: '/input/task', message: 'Invalid enum value' }],
759
+ }),
760
+ );
761
+ }
762
+
763
+ const inlineText = typeof ctx.input.text === 'string' ? ctx.input.text : '';
764
+ const { docs, outcomes } =
765
+ ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
766
+ const combinedText = [inlineText, ...docs.map((d) => `### File: ${d.fileName}\n${d.markdown || d.text}`)]
767
+ .filter(Boolean)
768
+ .join('\n\n');
769
+
770
+ const taskPrompts: Record<string, string> = {
771
+ classify: `Classify the document into categories (${JSON.stringify(
772
+ ctx.input.categories || ['invoice', 'contract', 'report', 'id-card', 'other'],
773
+ )}). Return JSON: { "category": string, "confidence": number, "reasoning": string }.`,
774
+ sentiment:
775
+ 'Analyze document sentiment. Return JSON: { "sentiment": "POSITIVE" | "NEGATIVE" | "NEUTRAL" | "MIXED", "confidence": number, "keyPhrases": string[], "summary": string }.',
776
+ compliance: `Evaluate compliance against criteria: ${JSON.stringify(
777
+ ctx.input.criteria || [],
778
+ )}. Return JSON: { "verdict": "PASS" | "FAIL" | "WARNING", "summary": string, "violations": [{"rule": string, "severity": string, "detail": string}] }.`,
779
+ 'fact-check': `Cross-check the document against referenceData: ${JSON.stringify(
780
+ ctx.input.referenceData ?? ctx.input.reference_data ?? {},
781
+ )}. Return JSON: { "verdict": "PASS" | "FAIL", "summary": string, "checks": [{"field": string, "status": "PASS" | "FAIL" | "UNVERIFIED", "detail": string}] }.`,
782
+ quality:
783
+ 'Score document writing & structural quality (0-100). Return JSON: { "score": number, "dimensions": {"clarity": number, "completeness": number, "consistency": number}, "recommendations": string[] }.',
784
+ risk: `Assess legal and operational risk (focus: ${String(
785
+ ctx.input.focus || 'general',
786
+ )}). Return JSON: { "riskLevel": "LOW" | "MEDIUM" | "HIGH" | "CRITICAL", "summary": string, "riskFactors": [{"clause": string, "severity": string, "mitigation": string}] }.`,
787
+ 'summarize-eval':
788
+ 'Summarize the document and evaluate the author perspective, strengths, and limitations. Return JSON: { "summary": string, "perspective": string, "strengths": string[], "limitations": string[] }.',
789
+ };
790
+
791
+ const data = await this.invokeLlmJson({
792
+ config: ctx.config,
793
+ systemPrompt: `You are an enterprise Document Understanding analysis engine.\n${taskPrompts[task]}`,
794
+ userContent: combinedText,
795
+ usage,
796
+ });
797
+
798
+ return {
799
+ kind: 'completed',
800
+ outputPayload: {
801
+ version: 'document-core-result-v1',
802
+ data,
803
+ provenance: { slot: 'reasoning', action: 'analyze', variant: task },
804
+ },
805
+ extraOutputArtifacts: [],
806
+ coverageOutcomes: outcomes,
807
+ usage: usage.toMetrics(),
808
+ warnings,
809
+ };
810
+ }
811
+
812
+ private async executeTransform(
813
+ ctx: EngineExecutionContext,
814
+ usage: UsageAccumulator,
815
+ warnings: string[],
816
+ ): Promise<EngineExecutionOutcome> {
817
+ // Support both canonical `variant` and legacy alias `action`
818
+ const variant = String(ctx.input.variant || ctx.input.action || 'convert');
819
+ if (!['convert', 'translate', 'rewrite', 'redact', 'template'].includes(variant)) {
820
+ throw new DuHttpError(
821
+ createProblem(422, 'INVALID_SCHEMA', `Invalid transform variant "${variant}"`, {
822
+ errors: [{ pointer: '/input/variant', message: 'Invalid enum value' }],
823
+ }),
824
+ );
825
+ }
826
+
827
+ const inlineText = typeof ctx.input.text === 'string' ? ctx.input.text : '';
828
+ const { docs, outcomes } =
829
+ ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
830
+ const sourceText = [inlineText, ...docs.map((d) => d.markdown || d.text)].filter(Boolean).join('\n\n');
831
+ const outputFormat = String(ctx.input.outputFormat || ctx.input.output_format || 'text');
832
+
833
+ let transformedText = sourceText;
834
+ let slot: string | undefined;
835
+
836
+ if (variant === 'convert') {
837
+ if (outputFormat === 'html') {
838
+ transformedText = markdownToSimpleHtml(sourceText);
839
+ } else if (outputFormat === 'json') {
840
+ transformedText = JSON.stringify({ paragraphs: sourceText.split(/\n{2,}/).filter(Boolean) }, null, 2);
841
+ } else {
842
+ transformedText = sourceText;
843
+ }
844
+ } else if (variant === 'template') {
845
+ const tpl =
846
+ typeof ctx.input.templateText === 'string' && ctx.input.templateText ? ctx.input.templateText : sourceText;
847
+ const vars = isRecord(ctx.input.variables)
848
+ ? ctx.input.variables
849
+ : isRecord(ctx.input.template)
850
+ ? ctx.input.template
851
+ : {};
852
+ transformedText = mergeTemplateLocally(tpl, vars);
853
+ } else if (variant === 'redact') {
854
+ const rawPatterns = ctx.input.redactPatterns ?? ctx.input.redact_patterns;
855
+ const patterns = Array.isArray(rawPatterns)
856
+ ? rawPatterns.map(String)
857
+ : typeof rawPatterns === 'string'
858
+ ? rawPatterns.split(',').map((s) => s.trim())
859
+ : ['CCCD', 'PHONE_NUMBER', 'EMAIL'];
860
+ transformedText = redactTextLocally(sourceText, patterns);
861
+ if (ctx.input.useAi === true) {
862
+ slot = 'reasoning';
863
+ transformedText = await this.invokeLlm({
864
+ config: ctx.config,
865
+ systemPrompt: `Redact all sensitive PII matching ${JSON.stringify(
866
+ patterns,
867
+ )} by replacing sensitive values with [REDACTED]. Preserve all other text verbatim.`,
868
+ userContent: transformedText,
869
+ usage,
870
+ });
871
+ }
872
+ } else if (variant === 'translate') {
873
+ slot = 'reasoning';
874
+ const targetLang = String(ctx.input.targetLanguage || ctx.input.target_language || 'en');
875
+ const tone = String(ctx.input.tone || 'professional');
876
+ transformedText = await this.invokeLlm({
877
+ config: ctx.config,
878
+ systemPrompt: `Translate the document accurately into "${targetLang}" with a "${tone}" tone. Preserve Markdown structure and numbers.`,
879
+ userContent: sourceText,
880
+ usage,
881
+ });
882
+ } else if (variant === 'rewrite') {
883
+ slot = 'reasoning';
884
+ const style = String(ctx.input.style || 'executive');
885
+ const tone = String(ctx.input.tone || 'clear');
886
+ transformedText = await this.invokeLlm({
887
+ config: ctx.config,
888
+ systemPrompt: `Rewrite the document in "${style}" style and "${tone}" tone while preserving factual accuracy.`,
889
+ userContent: sourceText,
890
+ usage,
891
+ });
892
+ }
893
+
894
+ return {
895
+ kind: 'completed',
896
+ outputPayload: {
897
+ version: 'document-core-result-v1',
898
+ data: {
899
+ transformedText,
900
+ outputFormat,
901
+ },
902
+ provenance: { ...(slot ? { slot } : {}), action: 'transform', variant },
903
+ },
904
+ extraOutputArtifacts: [],
905
+ coverageOutcomes: outcomes,
906
+ usage: usage.toMetrics(),
907
+ warnings,
908
+ };
909
+ }
910
+
911
+ private async executeGenerate(
912
+ ctx: EngineExecutionContext,
913
+ usage: UsageAccumulator,
914
+ warnings: string[],
915
+ ): Promise<EngineExecutionOutcome> {
916
+ const task = String(ctx.input.task || 'summary');
917
+ if (!['summary', 'outline', 'report', 'email', 'minutes', 'qa'].includes(task)) {
918
+ throw new DuHttpError(
919
+ createProblem(422, 'INVALID_SCHEMA', `Invalid generate task "${task}"`, {
920
+ errors: [{ pointer: '/input/task', message: 'Invalid enum value' }],
921
+ }),
922
+ );
923
+ }
924
+
925
+ const inlineText = typeof ctx.input.text === 'string' ? ctx.input.text : '';
926
+ const { docs, outcomes } =
927
+ ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
928
+ const combinedText = [inlineText, ...docs.map((d) => `### File: ${d.fileName}\n${d.markdown || d.text}`)]
929
+ .filter(Boolean)
930
+ .join('\n\n');
931
+
932
+ const prompts: Record<string, string> = {
933
+ summary: `Generate a ${String(ctx.input.format || 'bullets')} summary in at most ${Number(
934
+ ctx.input.maxWords ?? ctx.input.max_words ?? 300,
935
+ )} words${
936
+ ctx.input.audience ? ` for audience "${String(ctx.input.audience)}"` : ''
937
+ }. Return JSON: { "summary": string, "keyPoints": string[] }.`,
938
+ outline:
939
+ 'Extract a hierarchical outline of the document. Return JSON: { "sections": [{ "level": number, "title": string, "summary": string }] }.',
940
+ report: `Generate an executive analytical report (focus: ${String(
941
+ ctx.input.focus || 'comprehensive',
942
+ )}). Return JSON: { "title": string, "markdownReport": string, "highlights": string[] }.`,
943
+ email: `Draft a "${String(
944
+ ctx.input.tone || 'formal',
945
+ )}" email based on the document. Return JSON: { "subject": string, "body": string }.`,
946
+ minutes:
947
+ 'Generate structured meeting minutes. Return JSON: { "title": string, "summary": string, "decisions": string[], "actionItems": [{"task": string, "owner": string, "dueDate": string}] }.',
948
+ qa: `Answer each question grounded strictly in the document with verbatim evidence quotes: ${JSON.stringify(
949
+ ctx.input.questions || [],
950
+ )}. Return JSON: { "answers": [{ "question": string, "answer": string, "evidenceQuote": string, "confidence": number }] }.`,
951
+ };
952
+
953
+ const data = await this.invokeLlmJson({
954
+ config: ctx.config,
955
+ systemPrompt: `You are a grounded Document Understanding generation engine.\n${prompts[task]}`,
956
+ userContent: combinedText,
957
+ usage,
958
+ });
959
+
960
+ return {
961
+ kind: 'completed',
962
+ outputPayload: {
963
+ version: 'document-core-result-v1',
964
+ data,
965
+ provenance: { slot: 'reasoning', action: 'generate', variant: task },
966
+ },
967
+ extraOutputArtifacts: [],
968
+ coverageOutcomes: outcomes,
969
+ usage: usage.toMetrics(),
970
+ warnings,
971
+ };
972
+ }
973
+
974
+ private async executeCompare(
975
+ ctx: EngineExecutionContext,
976
+ usage: UsageAccumulator,
977
+ warnings: string[],
978
+ ): Promise<EngineExecutionOutcome> {
979
+ const mode = String(ctx.input.mode || 'diff');
980
+ if (!['diff', 'semantic', 'version'].includes(mode)) {
981
+ throw new DuHttpError(
982
+ createProblem(422, 'INVALID_SCHEMA', `Invalid compare mode "${mode}"`, {
983
+ errors: [{ pointer: '/input/mode', message: 'Invalid enum value' }],
984
+ }),
985
+ );
986
+ }
987
+
988
+ const { docs, outcomes } =
989
+ ctx.artifacts.length > 0 ? await this.readAndOcrDocuments(ctx, usage) : { docs: [], outcomes: [] };
990
+ const sourceText =
991
+ (isRecord(ctx.input.source) && typeof ctx.input.source.text === 'string' ? ctx.input.source.text : undefined) ??
992
+ docs[0]?.text ??
993
+ '';
994
+ const targetText =
995
+ (isRecord(ctx.input.target) && typeof ctx.input.target.text === 'string' ? ctx.input.target.text : undefined) ??
996
+ docs[1]?.text ??
997
+ '';
998
+
999
+ if (docs.length < 2 && (!sourceText || !targetText)) {
1000
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', 'compare requires two documents (source and target)'));
1001
+ }
1002
+
1003
+ if (mode === 'diff') {
1004
+ const diffData = computeLineDiff(sourceText, targetText);
1005
+ return {
1006
+ kind: 'completed',
1007
+ outputPayload: {
1008
+ version: 'document-core-result-v1',
1009
+ data: diffData,
1010
+ provenance: { action: 'compare', variant: 'diff' },
1011
+ },
1012
+ extraOutputArtifacts: [],
1013
+ coverageOutcomes: outcomes,
1014
+ usage: usage.toMetrics(),
1015
+ warnings,
1016
+ };
1017
+ }
1018
+
1019
+ const prompt =
1020
+ mode === 'semantic'
1021
+ ? `Compare SOURCE vs TARGET clauses${
1022
+ ctx.input.focus ? ` focusing on "${String(ctx.input.focus)}"` : ''
1023
+ }. Return JSON: { "changes": [{ "clauseTitle": string, "sourceExcerpt": string, "targetExcerpt": string, "changeType": "ADDED" | "REMOVED" | "MODIFIED", "legalSignificance": "NEGLIGIBLE" | "MODERATE" | "HIGH", "commentary": string }] }.`
1024
+ : 'Generate a version changelog between SOURCE and TARGET. Return JSON: { "summary": string, "breakingChanges": string[], "additions": string[], "modifications": string[], "removals": string[] }.';
1025
+
1026
+ const data = await this.invokeLlmJson({
1027
+ config: ctx.config,
1028
+ systemPrompt: prompt,
1029
+ userContent: `=== SOURCE ===\n${sourceText}\n\n=== TARGET ===\n${targetText}`,
1030
+ usage,
1031
+ });
1032
+
1033
+ return {
1034
+ kind: 'completed',
1035
+ outputPayload: {
1036
+ version: 'document-core-result-v1',
1037
+ data,
1038
+ provenance: { slot: 'reasoning', action: 'compare', variant: mode },
1039
+ },
1040
+ extraOutputArtifacts: [],
1041
+ coverageOutcomes: outcomes,
1042
+ usage: usage.toMetrics(),
1043
+ warnings,
1044
+ };
1045
+ }
1046
+
1047
+ private async executeDisbursementWorkflow(
1048
+ ctx: EngineExecutionContext,
1049
+ usage: UsageAccumulator,
1050
+ warnings: string[],
1051
+ ): Promise<EngineExecutionOutcome> {
1052
+ const maxConcurrency = Math.min(8, Math.max(1, Number(ctx.input.maxConcurrency) || 4));
1053
+ const requireApproval = ctx.input.requireApproval === true;
1054
+
1055
+ let perFileRecords: Array<{ fileName: string; docType: string; extracted: Record<string, unknown> }> = [];
1056
+ let outcomes: CoverageOutcome[] = [];
1057
+
1058
+ if (ctx.checkpointData && Array.isArray(ctx.checkpointData.perFileRecords)) {
1059
+ perFileRecords = ctx.checkpointData.perFileRecords as typeof perFileRecords;
1060
+ outcomes = (ctx.checkpointData.outcomes as CoverageOutcome[]) || [];
1061
+ } else {
1062
+ await ctx.onProgress?.(20, 'Classifying and extracting disbursement documents');
1063
+ const parsedBundle = await this.readAndOcrDocuments(ctx, usage);
1064
+ outcomes = parsedBundle.outcomes;
1065
+
1066
+ perFileRecords = await mapWithConcurrency(parsedBundle.docs, maxConcurrency, async (doc) => {
1067
+ const res = await this.invokeLlmJson({
1068
+ config: ctx.config,
1069
+ systemPrompt:
1070
+ '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> }.',
1071
+ userContent: `File: ${doc.fileName}\n\n${doc.markdown || doc.text}`,
1072
+ usage,
1073
+ });
1074
+ return {
1075
+ fileName: doc.fileName,
1076
+ docType: typeof res.docType === 'string' ? res.docType : 'supporting_document',
1077
+ extracted: isRecord(res.extracted) ? res.extracted : res,
1078
+ };
1079
+ });
1080
+
1081
+ if (requireApproval && !ctx.resumedInput) {
1082
+ return {
1083
+ kind: 'waiting_input',
1084
+ waitState: {
1085
+ waitId: 'approval-wait',
1086
+ prompt: 'Review extracted disbursement records before cross-checking against credit approval.',
1087
+ inputSchema: {
1088
+ type: 'object',
1089
+ properties: {
1090
+ approved: { type: 'boolean', default: true },
1091
+ approver: { type: 'string' },
1092
+ note: { type: 'string' },
1093
+ },
1094
+ required: ['approved'],
1095
+ },
1096
+ previewData: { perFileRecords },
1097
+ expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString(),
1098
+ },
1099
+ checkpointData: { perFileRecords, outcomes },
1100
+ usage: usage.toMetrics(),
1101
+ };
1102
+ }
1103
+ }
1104
+
1105
+ if (ctx.resumedInput && ctx.resumedInput.approved === false) {
1106
+ throw new DuHttpError(
1107
+ createProblem(
1108
+ 409,
1109
+ 'STATE_CONFLICT',
1110
+ `Disbursement rejected by reviewer: ${String(ctx.resumedInput.note || '')}`,
1111
+ ),
1112
+ );
1113
+ }
1114
+
1115
+ await ctx.onProgress?.(70, 'Cross-checking extracted evidence against referenceData');
1116
+ const referenceData = ctx.input.referenceData ?? ctx.input.resolution_data ?? [];
1117
+ const synthesis = await this.invokeLlmJson({
1118
+ config: ctx.config,
1119
+ systemPrompt:
1120
+ '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 }.',
1121
+ userContent: JSON.stringify({
1122
+ referenceData,
1123
+ extractedDocuments: perFileRecords,
1124
+ reviewerDecision: ctx.resumedInput,
1125
+ }),
1126
+ usage,
1127
+ });
1128
+
1129
+ const findings = Array.isArray(synthesis.findings) ? (synthesis.findings as Array<Record<string, unknown>>) : [];
1130
+ const matchedCount = findings.filter((f) => f.status === 'match').length;
1131
+ const mismatchedCount = findings.filter((f) => f.status === 'mismatch').length;
1132
+
1133
+ return {
1134
+ kind: 'completed',
1135
+ outputPayload: {
1136
+ resultVersion: 'disbursement-result-v1',
1137
+ businessId: 'document-core',
1138
+ businessVersion: '2.0.0',
1139
+ report: typeof synthesis.report === 'string' ? synthesis.report : '# BÁO CÁO ĐỐI CHIẾU HỒ SƠ GIẢI NGÂN',
1140
+ crosscheck: {
1141
+ findings,
1142
+ matchedCount,
1143
+ mismatchedCount,
1144
+ },
1145
+ evidence: {
1146
+ filesAnalyzed: perFileRecords.length,
1147
+ logicalDocumentCount: perFileRecords.length,
1148
+ extractedRecordCount: perFileRecords.length,
1149
+ perFile: perFileRecords.map((r) => ({ fileName: r.fileName, docType: r.docType })),
1150
+ },
1151
+ failedChildren: [],
1152
+ },
1153
+ extraOutputArtifacts: [],
1154
+ coverageOutcomes: outcomes,
1155
+ usage: usage.toMetrics(),
1156
+ warnings,
1157
+ };
1158
+ }
1159
+
1160
+ private async executeDocCompareWorkflow(
1161
+ ctx: EngineExecutionContext,
1162
+ usage: UsageAccumulator,
1163
+ warnings: string[],
1164
+ ): Promise<EngineExecutionOutcome> {
1165
+ let comparisonPayload: Record<string, unknown>;
1166
+ let outcomes: CoverageOutcome[] = [];
1167
+
1168
+ if (ctx.checkpointData && isRecord(ctx.checkpointData.comparisonPayload)) {
1169
+ comparisonPayload = ctx.checkpointData.comparisonPayload;
1170
+ outcomes = (ctx.checkpointData.outcomes as CoverageOutcome[]) || [];
1171
+ } else {
1172
+ const parsedBundle = await this.readAndOcrDocuments(ctx, usage);
1173
+ outcomes = parsedBundle.outcomes;
1174
+ if (parsedBundle.docs.length < 2) {
1175
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', 'doc-compare workflow requires 2 input artifacts'));
1176
+ }
1177
+ const chunkSize = Math.min(200_000, Math.max(200, Number(ctx.input.chunkSizeChars) || 8_000));
1178
+ const src = (parsedBundle.docs[0].markdown || parsedBundle.docs[0].text).slice(0, chunkSize * 4);
1179
+ const tgt = (parsedBundle.docs[1].markdown || parsedBundle.docs[1].text).slice(0, chunkSize * 4);
1180
+
1181
+ comparisonPayload = await this.invokeLlmJson({
1182
+ config: ctx.config,
1183
+ systemPrompt:
1184
+ '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 }.',
1185
+ userContent: `=== SOURCE (${parsedBundle.docs[0].fileName}) ===\n${src}\n\n=== TARGET (${parsedBundle.docs[1].fileName}) ===\n${tgt}`,
1186
+ usage,
1187
+ });
1188
+
1189
+ if (ctx.input.requireHumanReview === true && !ctx.resumedInput) {
1190
+ return {
1191
+ kind: 'waiting_input',
1192
+ waitState: {
1193
+ waitId: 'doc-compare-review',
1194
+ prompt: 'Confirm structural and cross-reference comparison claims before finalizing.',
1195
+ inputSchema: {
1196
+ type: 'object',
1197
+ properties: {
1198
+ approved: { type: 'boolean', default: true },
1199
+ note: { type: 'string' },
1200
+ },
1201
+ required: ['approved'],
1202
+ },
1203
+ previewData: comparisonPayload,
1204
+ },
1205
+ checkpointData: { comparisonPayload, outcomes },
1206
+ usage: usage.toMetrics(),
1207
+ };
1208
+ }
1209
+ }
1210
+
1211
+ return {
1212
+ kind: 'completed',
1213
+ outputPayload: {
1214
+ resultVersion: 'doc-compare-result-v1',
1215
+ businessId: 'document-core',
1216
+ businessVersion: '2.0.0',
1217
+ ...comparisonPayload,
1218
+ reviewerDecision: ctx.resumedInput ?? null,
1219
+ },
1220
+ extraOutputArtifacts: [],
1221
+ coverageOutcomes: outcomes,
1222
+ usage: usage.toMetrics(),
1223
+ warnings,
1224
+ };
1225
+ }
1226
+
1227
+ private async executeSchemaWorkflow(
1228
+ ctx: EngineExecutionContext,
1229
+ usage: UsageAccumulator,
1230
+ warnings: string[],
1231
+ ): Promise<EngineExecutionOutcome> {
1232
+ if (!this.runSchemaPipeline) {
1233
+ throw new DuHttpError(createProblem(501, 'NOT_IMPLEMENTED', 'Dynamic pipeline runner is not attached'));
1234
+ }
1235
+ const pipelineId = typeof ctx.input.pipelineId === 'number' ? ctx.input.pipelineId : undefined;
1236
+ const pipelineName = typeof ctx.input.pipelineName === 'string' ? ctx.input.pipelineName : undefined;
1237
+ const params = isRecord(ctx.input.parameters) ? ctx.input.parameters : ctx.input;
1238
+ const result = await this.runSchemaPipeline({ pipelineId, pipelineName }, params, ctx.userId);
1239
+ return {
1240
+ kind: 'completed',
1241
+ outputPayload: {
1242
+ resultVersion: 'schema-workflow-result-v1',
1243
+ businessId: 'document-core',
1244
+ businessVersion: '2.0.0',
1245
+ data: result,
1246
+ },
1247
+ extraOutputArtifacts: [],
1248
+ coverageOutcomes: [],
1249
+ usage: usage.toMetrics(),
1250
+ warnings,
1251
+ };
1252
+ }
1253
+
1254
+ /**
1255
+ * `lc-checker@1.2.0` — 5-step Trade Finance examination:
1256
+ * 1. ocr -> 2. screen -> 3. visual -> 4. adjudicate (UCP 600 / ISBP 821) -> 5. Vietnamese report
1257
+ */
1258
+ private async executeLcChecker(
1259
+ ctx: EngineExecutionContext,
1260
+ usage: UsageAccumulator,
1261
+ warnings: string[],
1262
+ ): Promise<EngineExecutionOutcome> {
1263
+ if (ctx.artifacts.length === 0) {
1264
+ throw new DuHttpError(
1265
+ createProblem(422, 'INVALID_SCHEMA', 'lc-checker requires at least one L/C presentation document'),
1266
+ );
1267
+ }
1268
+ if (ctx.artifacts.length > 50) {
1269
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', 'lc-checker accepts at most 50 presentation files'));
1270
+ }
1271
+
1272
+ // Step 1: OCR / Parse
1273
+ await ctx.onProgress?.(15, 'Step 1/5: OCR & text extraction');
1274
+ const { docs, outcomes } = await this.readAndOcrDocuments(ctx, usage, { forceVisionOcr: true });
1275
+ const filesWithoutOcrText = docs.filter((d) => !d.text.trim()).map((d) => d.fileName);
1276
+ const totalOcrChars = docs.reduce((sum, d) => sum + d.text.length, 0);
1277
+
1278
+ // Step 2: Screen text & request visual checks (max 24, must cite valid ruleId)
1279
+ await ctx.onProgress?.(35, 'Step 2/5: Screening presentation & identifying visual checks');
1280
+ const rulesCatalogSummary = UCP600_ISBP821_RULES.map((r) => `${r.ruleId}: ${r.title} - ${r.description}`).join(
1281
+ '\n',
1282
+ );
1283
+ const combinedDocsText = docs.map((d) => `=== DOCUMENT: ${d.fileName} ===\n${d.markdown || d.text}`).join('\n\n');
1284
+
1285
+ const screenResult = await this.invokeLlmJson({
1286
+ config: ctx.config,
1287
+ systemPrompt: `You are a Trade Finance L/C examiner screening documents against UCP 600 / ISBP 821.\nAvailable Rule Registry:\n${rulesCatalogSummary}\nReturn JSON: { "documentsPresent": string[], "documentsMissing": string[], "visualRequests": [{ "document": string, "check": string, "ruleId": string }] }. Cite ONLY ruleIds from the registry (max 24 visualRequests).`,
1288
+ userContent: combinedDocsText,
1289
+ usage,
1290
+ });
1291
+
1292
+ const rawVisualRequests = Array.isArray(screenResult.visualRequests)
1293
+ ? (screenResult.visualRequests as Array<Record<string, unknown>>).slice(0, 24)
1294
+ : [];
1295
+ const validVisualRequests = rawVisualRequests.filter(
1296
+ (req) => typeof req.ruleId === 'string' && VALID_LC_RULE_IDS.has(req.ruleId),
1297
+ );
1298
+
1299
+ // Step 3: Visual verification on image artifacts (or text attestation if digital-only)
1300
+ await ctx.onProgress?.(55, 'Step 3/5: Executing visual verification checks');
1301
+ const outstandingVisualChecks: Array<{ document: string; check: string; ruleId: string; reason: string }> = [];
1302
+ let satisfiedVisualCount = 0;
1303
+
1304
+ for (const vReq of validVisualRequests) {
1305
+ const docName = String(vReq.document || '');
1306
+ const checkDesc = String(vReq.check || '');
1307
+ const ruleId = String(vReq.ruleId);
1308
+ const matchedArtifact = ctx.artifacts.find((a) => a.fileName === docName) || ctx.artifacts[0];
1309
+
1310
+ if (matchedArtifact && matchedArtifact.mimeType.startsWith('image/')) {
1311
+ const imgBuf = this.artifactStorage.readArtifactBuffer(matchedArtifact);
1312
+ const vRes = await this.invokeLlmJson({
1313
+ config: ctx.config,
1314
+ vision: true,
1315
+ systemPrompt:
1316
+ 'Verify the requested visual feature (signature, stamp, endorsement) on this document image. Return JSON: { "satisfied": boolean, "observation": string }.',
1317
+ userContent: [
1318
+ { type: 'text', text: `Check "${checkDesc}" under rule ${ruleId}` },
1319
+ {
1320
+ type: 'image_url',
1321
+ image_url: { url: `data:${matchedArtifact.mimeType};base64,${imgBuf.toString('base64')}` },
1322
+ },
1323
+ ],
1324
+ usage,
1325
+ });
1326
+ if (vRes.satisfied === true) {
1327
+ satisfiedVisualCount += 1;
1328
+ } else {
1329
+ outstandingVisualChecks.push({
1330
+ document: docName,
1331
+ check: checkDesc,
1332
+ ruleId,
1333
+ reason: String(vRes.observation || 'Visual element could not be confirmed'),
1334
+ });
1335
+ }
1336
+ } else {
1337
+ // Digital PDF/text without raster image inspection -> record as satisfied if text explicitly attests signature, else outstanding
1338
+ const matchedDoc = docs.find((d) => d.fileName === docName);
1339
+ if (matchedDoc && /sign|stamp|ký|đóng dấu/i.test(matchedDoc.text)) {
1340
+ satisfiedVisualCount += 1;
1341
+ } else {
1342
+ outstandingVisualChecks.push({
1343
+ document: docName || (docs[0]?.fileName ?? 'presentation'),
1344
+ check: checkDesc,
1345
+ ruleId,
1346
+ reason: 'Requires physical/raster visual inspection of signature or endorsement',
1347
+ });
1348
+ }
1349
+ }
1350
+ }
1351
+
1352
+ // Step 4 & 5: Adjudicate against UCP 600 / ISBP 821 + Vietnamese report
1353
+ await ctx.onProgress?.(80, 'Step 4-5/5: Adjudicating UCP 600 / ISBP 821 compliance & generating Vietnamese report');
1354
+ const adjudication = await this.invokeLlmJson({
1355
+ config: ctx.config,
1356
+ systemPrompt: `Adjudicate the L/C presentation strictly under UCP 600 / ISBP 821.\nAllowed ruleIds ONLY:\n${Array.from(
1357
+ VALID_LC_RULE_IDS,
1358
+ ).join(
1359
+ ', ',
1360
+ )}\nReturn 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) }.`,
1361
+ userContent: JSON.stringify({
1362
+ documents: docs.map((d) => ({ fileName: d.fileName, content: d.markdown || d.text })),
1363
+ outstandingVisualChecks,
1364
+ }),
1365
+ usage,
1366
+ });
1367
+
1368
+ const rawDiscrepancies = Array.isArray(adjudication.discrepancies)
1369
+ ? (adjudication.discrepancies as Array<Record<string, unknown>>)
1370
+ : [];
1371
+
1372
+ // Enforce hard invariant: every discrepancy MUST cite a valid registered ruleId
1373
+ const verifiedDiscrepancies = rawDiscrepancies.map((disc, index) => {
1374
+ const cited =
1375
+ typeof disc.ruleId === 'string' && VALID_LC_RULE_IDS.has(disc.ruleId) ? disc.ruleId : 'UCP600-ART14-A';
1376
+ if (cited !== disc.ruleId) {
1377
+ warnings.push(`Normalized unregistered rule citation "${String(disc.ruleId)}" to UCP600-ART14-A.`);
1378
+ }
1379
+ const severityRaw = String(disc.severity || 'MAJOR').toUpperCase();
1380
+ const severity = ['MAJOR', 'MINOR', 'ADVISORY'].includes(severityRaw) ? severityRaw : 'MAJOR';
1381
+ return {
1382
+ id: String(disc.id || `DISC-${String(index + 1).padStart(2, '0')}`),
1383
+ severity,
1384
+ document: String(disc.document || docs[0]?.fileName || 'unknown'),
1385
+ field: String(disc.field || 'General'),
1386
+ issue: String(disc.issue || ''),
1387
+ ruleId: cited,
1388
+ recommendation: String(disc.recommendation || 'Xin ý kiến chấp nhận bất hợp lệ hoặc tu chỉnh chứng từ.'),
1389
+ };
1390
+ });
1391
+
1392
+ const majorDiscrepancies = verifiedDiscrepancies.filter((d) => d.severity === 'MAJOR').length;
1393
+ const minorDiscrepancies = verifiedDiscrepancies.filter((d) => d.severity === 'MINOR').length;
1394
+ const advisoryCount = verifiedDiscrepancies.filter((d) => d.severity === 'ADVISORY').length;
1395
+ const totalDiscrepancies = verifiedDiscrepancies.length;
1396
+
1397
+ // Hard state-machine safety rule from BRD Section 2.4:
1398
+ // Never conclude COMPLIANT if outstandingVisualChecks remain or major/minor discrepancies exist!
1399
+ const canBeCompliant = outstandingVisualChecks.length === 0 && majorDiscrepancies === 0 && minorDiscrepancies === 0;
1400
+ const verdict = canBeCompliant && adjudication.verdict === 'COMPLIANT' ? 'COMPLIANT' : 'DISCREPANT';
1401
+ const citedRuleIds = Array.from(new Set(verifiedDiscrepancies.map((d) => d.ruleId)));
1402
+
1403
+ return {
1404
+ kind: 'completed',
1405
+ outputPayload: {
1406
+ resultVersion: 'lc-checker-result-v1',
1407
+ businessId: 'lc-checker',
1408
+ businessVersion: '1.2.0',
1409
+ verdict,
1410
+ recommendation: verdict === 'COMPLIANT' ? 'PROCEED_TO_HUMAN_SIGN_OFF' : 'RESERVE_FOR_REVIEW',
1411
+ totalDiscrepancies,
1412
+ majorDiscrepancies,
1413
+ minorDiscrepancies,
1414
+ advisoryCount,
1415
+ documentsPresent: Array.isArray(screenResult.documentsPresent)
1416
+ ? screenResult.documentsPresent
1417
+ : docs.map((d) => d.fileName),
1418
+ documentsMissing: Array.isArray(screenResult.documentsMissing) ? screenResult.documentsMissing : [],
1419
+ discrepancies: verifiedDiscrepancies,
1420
+ summary:
1421
+ typeof adjudication.summary === 'string'
1422
+ ? adjudication.summary
1423
+ : `Phát hiện ${totalDiscrepancies} điểm lưu ý/bất hợp lệ.`,
1424
+ report:
1425
+ typeof adjudication.report === 'string'
1426
+ ? adjudication.report
1427
+ : '# BÁO CÁO KIỂM TRA BỘ CHỨNG TỪ TÍN DỤNG THƯ (L/C)',
1428
+ evidence: {
1429
+ filesSubmitted: ctx.artifacts.length,
1430
+ filesOcred: docs.length,
1431
+ filesWithoutOcrText,
1432
+ totalOcrChars,
1433
+ ruleSetId: LC_RULESET_ID,
1434
+ ruleSetVersion: String(ctx.input.ruleSetVersion || LC_RULESET_VERSION),
1435
+ ruleSetStatus: 'PROVISIONAL',
1436
+ citedRuleIds,
1437
+ visualVerification: {
1438
+ requested: validVisualRequests.length,
1439
+ satisfied: satisfiedVisualCount,
1440
+ complete: outstandingVisualChecks.length === 0,
1441
+ },
1442
+ },
1443
+ humanSignOffRequired: true,
1444
+ outstandingVisualChecks,
1445
+ failedChildren: [],
1446
+ },
1447
+ extraOutputArtifacts: [],
1448
+ coverageOutcomes: outcomes,
1449
+ usage: usage.toMetrics(),
1450
+ warnings,
1451
+ };
1452
+ }
1453
+
1454
+ /**
1455
+ * `example-review@1.0.0` — Multi-document compliance review (1..10 files) with optional HITL approval.
1456
+ */
1457
+ private async executeExampleReview(
1458
+ ctx: EngineExecutionContext,
1459
+ usage: UsageAccumulator,
1460
+ warnings: string[],
1461
+ ): Promise<EngineExecutionOutcome> {
1462
+ if (ctx.artifacts.length < 1 || ctx.artifacts.length > 10) {
1463
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', 'example-review requires between 1 and 10 documents'));
1464
+ }
1465
+
1466
+ const reviewId = String(ctx.input.reviewId || ctx.operationId);
1467
+ let itemReviews: Array<Record<string, unknown>> = [];
1468
+ let outcomes: CoverageOutcome[] = [];
1469
+
1470
+ if (ctx.checkpointData && Array.isArray(ctx.checkpointData.itemReviews)) {
1471
+ itemReviews = ctx.checkpointData.itemReviews as Array<Record<string, unknown>>;
1472
+ outcomes = (ctx.checkpointData.outcomes as CoverageOutcome[]) || [];
1473
+ } else {
1474
+ const parsedBundle = await this.readAndOcrDocuments(ctx, usage);
1475
+ outcomes = parsedBundle.outcomes;
1476
+ const useAi = ctx.input.useAi !== false && Boolean(this.resolveAiManager());
1477
+
1478
+ itemReviews = await mapWithConcurrency(parsedBundle.docs, 4, async (doc) => {
1479
+ if (!useAi) {
1480
+ return {
1481
+ fileName: doc.fileName,
1482
+ format: doc.detectedFormat,
1483
+ pageCount: doc.selectedPages.length,
1484
+ charCount: doc.text.length,
1485
+ status: doc.text.length > 0 ? 'PASS' : 'EMPTY',
1486
+ };
1487
+ }
1488
+ const aiItem = await this.invokeLlmJson({
1489
+ config: ctx.config,
1490
+ systemPrompt: `Review this document item against criteria ${JSON.stringify(
1491
+ ctx.input.criteria || ['completeness', 'consistency'],
1492
+ )}. Return JSON: { "status": "PASS" | "REVIEW_REQUIRED", "summary": string, "issues": string[] }.`,
1493
+ userContent: `File: ${doc.fileName}\n\n${doc.markdown || doc.text}`,
1494
+ usage,
1495
+ });
1496
+ return {
1497
+ fileName: doc.fileName,
1498
+ format: doc.detectedFormat,
1499
+ pageCount: doc.selectedPages.length,
1500
+ ...aiItem,
1501
+ };
1502
+ });
1503
+
1504
+ if (ctx.input.requireApproval === true && !ctx.resumedInput) {
1505
+ return {
1506
+ kind: 'waiting_input',
1507
+ waitState: {
1508
+ waitId: 'compliance-officer-approval',
1509
+ prompt: 'Compliance Officer approval required to finalize multi-document review.',
1510
+ inputSchema: {
1511
+ type: 'object',
1512
+ properties: {
1513
+ approved: { type: 'boolean', default: true },
1514
+ approver: { type: 'string' },
1515
+ comment: { type: 'string' },
1516
+ },
1517
+ required: ['approved'],
1518
+ },
1519
+ previewData: { reviewId, items: itemReviews },
1520
+ },
1521
+ checkpointData: { itemReviews, outcomes },
1522
+ usage: usage.toMetrics(),
1523
+ };
1524
+ }
1525
+ }
1526
+
1527
+ return {
1528
+ kind: 'completed',
1529
+ outputPayload: {
1530
+ resultVersion: 'example-review-result-v1',
1531
+ businessId: 'example-review',
1532
+ businessVersion: '1.0.0',
1533
+ reviewId,
1534
+ approved: ctx.resumedInput ? Boolean(ctx.resumedInput.approved) : true,
1535
+ approverDecision: ctx.resumedInput ?? null,
1536
+ items: itemReviews,
1537
+ },
1538
+ extraOutputArtifacts: [],
1539
+ coverageOutcomes: outcomes,
1540
+ usage: usage.toMetrics(),
1541
+ warnings,
1542
+ };
1543
+ }
1544
+ }