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
@@ -1,17 +1,19 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  import { DocumentUnderstandingService } from '../services/DocumentUnderstandingService';
2
4
  import { PipelineDef, JobState } from '../types';
3
5
 
6
+ function isRecord(value: unknown): value is Record<string, unknown> {
7
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
8
+ }
9
+
4
10
  function cloneJson<T>(value: T): T {
5
11
  if (value === undefined || value === null) {
6
12
  return value;
7
13
  }
8
- return JSON.parse(JSON.stringify(value));
14
+ return JSON.parse(JSON.stringify(value)) as T;
9
15
  }
10
16
 
11
- /**
12
- * Build tool name from pipeline name.
13
- * Convention: doc_understanding.pipeline.<sanitized_name>
14
- */
15
17
  function buildToolName(pipelineName: string): string {
16
18
  const sanitized = pipelineName
17
19
  .toLowerCase()
@@ -21,8 +23,8 @@ function buildToolName(pipelineName: string): string {
21
23
  return `doc_understanding.${sanitized}`;
22
24
  }
23
25
 
24
- function buildSchema(pipeline: PipelineDef) {
25
- const baseSchema =
26
+ function buildSchema(pipeline: PipelineDef): Record<string, unknown> {
27
+ const baseSchema: Record<string, unknown> =
26
28
  pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0
27
29
  ? cloneJson(pipeline.inputSchema)
28
30
  : {
@@ -35,20 +37,25 @@ function buildSchema(pipeline: PipelineDef) {
35
37
  },
36
38
  };
37
39
 
38
- // Add file_urls to allow AI to pass uploaded files
39
- if (baseSchema.type === 'object' && baseSchema.properties) {
40
+ if (baseSchema.type === 'object' && isRecord(baseSchema.properties)) {
40
41
  baseSchema.properties.file_urls = {
41
42
  type: 'array',
42
43
  items: { type: 'string' },
43
- description: 'Danh sách các URL của file/ảnh đính kèm trong chat',
44
+ description: 'Danh sách đường dẫn tệp/ảnh đính kèm trong NocoBase uploads',
44
45
  };
46
+ if (!baseSchema.properties.pages) {
47
+ baseSchema.properties.pages = {
48
+ type: 'string',
49
+ description: 'Dải trang chọn lọc cần xử lý (ví dụ: "1-3, 5")',
50
+ };
51
+ }
45
52
  }
46
53
 
47
54
  return baseSchema;
48
55
  }
49
56
 
50
- function applySchemaDefaults(value: any, schema: any): any {
51
- if (!schema || typeof schema !== 'object') {
57
+ function applySchemaDefaults(value: unknown, schema: unknown): unknown {
58
+ if (!isRecord(schema)) {
52
59
  return value;
53
60
  }
54
61
 
@@ -56,11 +63,12 @@ function applySchemaDefaults(value: any, schema: any): any {
56
63
  return cloneJson(schema.default);
57
64
  }
58
65
 
59
- const isObjectSchema = schema.type === 'object' || schema.properties;
66
+ const isObjectSchema = schema.type === 'object' || isRecord(schema.properties);
60
67
  if (isObjectSchema) {
61
- const source = value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};
68
+ const source: Record<string, unknown> = isRecord(value) ? { ...value } : {};
69
+ const props = isRecord(schema.properties) ? schema.properties : {};
62
70
 
63
- for (const [key, propertySchema] of Object.entries(schema.properties || {})) {
71
+ for (const [key, propertySchema] of Object.entries(props)) {
64
72
  const currentValue = source[key];
65
73
  const nextValue = applySchemaDefaults(currentValue, propertySchema);
66
74
  if (nextValue !== undefined) {
@@ -77,9 +85,6 @@ function applySchemaDefaults(value: any, schema: any): any {
77
85
  return value;
78
86
  }
79
87
 
80
- /**
81
- * Create a single tool definition for one pipeline.
82
- */
83
88
  function createToolForPipeline(service: DocumentUnderstandingService, pipeline: PipelineDef) {
84
89
  const stepNames = (pipeline.steps || [])
85
90
  .sort((a, b) => a.stepOrder - b.stepOrder)
@@ -89,7 +94,7 @@ function createToolForPipeline(service: DocumentUnderstandingService, pipeline:
89
94
  const description = [
90
95
  pipeline.description || `Thực thi pipeline "${pipeline.name}".`,
91
96
  stepNames ? `Steps: ${stepNames}` : '',
92
- 'Trả về kết quả phân tích JSON hoặc Job ID nếu chạy async.',
97
+ 'Trả về kết quả phân tích JSON, trạng thái chờ phê duyệt (WAITING_INPUT), hoặc Job ID.',
93
98
  ]
94
99
  .filter(Boolean)
95
100
  .join(' ');
@@ -110,37 +115,54 @@ function createToolForPipeline(service: DocumentUnderstandingService, pipeline:
110
115
  schema: buildSchema(pipeline),
111
116
  },
112
117
 
113
- invoke: async (ctx: any, args: any) => {
118
+ invoke: async (_ctx: unknown, rawArgs: Record<string, unknown>) => {
114
119
  try {
120
+ const args = isRecord(rawArgs) ? rawArgs : {};
115
121
  const config = await service.getConfig();
116
- const pollInterval = Math.max(config.pollInterval || 2000, 1000);
122
+ const pollInterval = Math.max(config.pollInterval || 2000, 500);
117
123
  const maxWait = Math.min(config.pollTimeout || 30000, 30000);
118
124
 
119
- // Extract file URLs
120
- let files: any[] = [];
121
- if (args.file_urls && Array.isArray(args.file_urls)) {
122
- files = args.file_urls.map((url: string) => ({ url }));
123
- }
124
-
125
- // Clean up args if using default schema
126
- const hasInputSchema = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0;
127
- let input = hasInputSchema ? args : args.input || args;
128
- if (input === args) {
129
- input = { ...args };
130
- delete input.file_urls;
125
+ const files = Array.isArray(args.file_urls)
126
+ ? args.file_urls
127
+ .filter((u): u is string => typeof u === 'string' && Boolean(u.trim()))
128
+ .map((url) => ({
129
+ url,
130
+ fieldName: 'file',
131
+ buffer: undefined as unknown as Buffer,
132
+ filename: '',
133
+ mimeType: '',
134
+ }))
135
+ : [];
136
+
137
+ const hasInputSchema = Boolean(pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0);
138
+ let inputValue: unknown = hasInputSchema ? args : isRecord(args.input) ? args.input : args;
139
+ if (inputValue === args) {
140
+ const copy = { ...args };
141
+ delete copy.file_urls;
142
+ inputValue = copy;
131
143
  }
132
144
  if (hasInputSchema) {
133
- input = applySchemaDefaults(input, pipeline.inputSchema);
145
+ inputValue = applySchemaDefaults(inputValue, pipeline.inputSchema);
134
146
  }
135
147
 
136
- const { jobId } = await service.executePipeline(pipeline.id, input, files);
148
+ const { jobId } = await service.executePipeline(pipeline.id, isRecord(inputValue) ? inputValue : {}, files);
137
149
  const start = Date.now();
138
150
 
139
151
  while (Date.now() - start < maxWait) {
140
152
  const job: JobState = await service.getJobStatus(jobId);
141
153
  if (job.status === 'completed') {
142
- return { status: 'completed', result: job.finalResult };
143
- } else if (job.status === 'failed' || job.status === 'timeout') {
154
+ return { status: 'completed', result: job.finalResult, usage: job.usage ?? undefined };
155
+ }
156
+ if (job.status === 'waiting_input') {
157
+ return {
158
+ status: 'waiting_input',
159
+ jobId,
160
+ operationId: job.operationId,
161
+ wait: job.waitState,
162
+ message: `Tác vụ đang tạm dừng chờ người phê duyệt (WAITING_INPUT).`,
163
+ };
164
+ }
165
+ if (job.status === 'failed' || job.status === 'timeout' || job.status === 'cancelled') {
144
166
  return { status: job.status, error: job.error };
145
167
  }
146
168
  await new Promise((resolve) => setTimeout(resolve, pollInterval));
@@ -148,22 +170,18 @@ function createToolForPipeline(service: DocumentUnderstandingService, pipeline:
148
170
 
149
171
  return {
150
172
  status: 'polling',
151
- message: `Pipeline "${pipeline.name}" đang chạy, trả về job ID để theo dõi.`,
173
+ message: `Pipeline "${pipeline.name}" đang chạy bất đồng bộ, dùng jobId để theo dõi.`,
152
174
  jobId,
153
175
  };
154
- } catch (err: any) {
155
- return { error: err.message };
176
+ } catch (err: unknown) {
177
+ return { error: err instanceof Error ? err.message : String(err) };
156
178
  }
157
179
  },
158
180
  };
159
181
  }
160
182
 
161
- /**
162
- * Dynamic tools provider: queries all enabled pipelines and registers one tool per pipeline.
163
- * Called on-demand by the AI tools manager each time tools are listed.
164
- */
165
183
  export function createDynamicPipelineToolsProvider(service: DocumentUnderstandingService) {
166
- return async (register: { registerTools: (options: any) => void }) => {
184
+ return async (register: { registerTools: (options: unknown) => void }) => {
167
185
  try {
168
186
  if (!service.isReady()) return;
169
187
 
@@ -1,3 +1,18 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import type {
4
+ DocumentInputCoverage,
5
+ DuOperationState,
6
+ OperationProgress,
7
+ OperationView,
8
+ ProblemDetails,
9
+ UsageMetrics,
10
+ WaitState,
11
+ } from './contracts/du-contracts';
12
+
13
+ export type EngineMode = 'builtin' | 'du_rework' | 'hybrid';
14
+ export type ProtocolMode = 'builtin_du' | 'du_rework_v1' | 'legacy_rest';
15
+
1
16
  export interface ServiceConfig {
2
17
  id?: number;
3
18
  baseUrl: string;
@@ -9,6 +24,14 @@ export interface ServiceConfig {
9
24
  pollInterval: number;
10
25
  pollTimeout: number;
11
26
  webhookSecret?: string;
27
+ engineMode?: EngineMode;
28
+ llmService?: string;
29
+ llmModel?: string;
30
+ visionLlmService?: string;
31
+ visionLlmModel?: string;
32
+ maxFileSizeBytes?: number;
33
+ maxFilesPerRequest?: number;
34
+ publicGatewayEnabled?: boolean;
12
35
  }
13
36
 
14
37
  export type ClientServiceConfig = Omit<ServiceConfig, 'authKey' | 'webhookSecret'> & {
@@ -22,21 +45,24 @@ export interface EndpointDef {
22
45
  subpath: string;
23
46
  method: 'GET' | 'POST' | 'PUT';
24
47
  description?: string;
25
- requestBodySchema?: any;
26
- responseSchema?: any;
48
+ requestBodySchema?: Record<string, unknown> | null;
49
+ responseSchema?: Record<string, unknown> | null;
27
50
  fileInputMode: 'none' | 'multipart' | 'base64';
28
51
  fileFieldName?: string;
29
52
  maxFiles: number;
30
53
  executionMode: 'sync' | 'polling' | 'webhook';
31
- /** Discriminator field name sent in the request body/query (e.g. DUGate 'mode'/'type'/'task'/'action'/'process'). */
54
+ protocolMode?: ProtocolMode;
55
+ businessId?: string;
56
+ actionName?: string;
57
+ /** Discriminator field name sent in the request body/query (e.g. 'mode'/'type'/'task'/'variant'/'process'). */
32
58
  discriminatorField?: string;
33
- /** Discriminator value for this endpoint (e.g. DUGate 'parse', 'invoice', 'disbursement'). */
59
+ /** Discriminator value for this endpoint (e.g. 'parse', 'invoice', 'disbursement'). */
34
60
  discriminatorValue?: string;
35
- /** When set, the request also appends '?sync=true' (DUGate synchronous mode). */
61
+ /** When set, the request also appends '?sync=true' (legacy synchronous mode). */
36
62
  syncQueryParam?: string;
37
- /** For 'sync' mode: DUGate returns 202 with a task ID. Extract the task ID with this path (e.g. 'name') or regex. */
63
+ /** Extract the async task ID with this path (e.g. 'operationId' or 'name') or regex. */
38
64
  taskIdExtractPath?: string;
39
- /** For 'sync' mode: regex used to extract the task ID from a string field (e.g. 'operations/([^/]+)'). */
65
+ /** Regex used to extract the task ID from a string field (e.g. 'operations/([^/]+)'). */
40
66
  taskIdExtractRegex?: string;
41
67
  pollResultSubpath?: string;
42
68
  pollTaskIdField?: string;
@@ -55,36 +81,95 @@ export interface PipelineStepDef {
55
81
  endpointId: number;
56
82
  stepOrder: number;
57
83
  name: string;
58
- inputMapping?: Record<string, any>;
84
+ inputMapping?: Record<string, unknown>;
59
85
  outputAlias?: string;
60
- condition?: any;
86
+ condition?: Record<string, unknown> | null;
61
87
  onError: 'fail' | 'skip' | 'retry';
62
88
  retryCount: number;
63
- endpoint: EndpointDef; // Associated endpoint
89
+ endpoint: EndpointDef;
64
90
  }
65
91
 
66
92
  export interface PipelineDef {
67
93
  id: number;
68
94
  name: string;
69
95
  description?: string;
70
- inputSchema?: any;
71
- outputMapping?: Record<string, any>;
96
+ inputSchema?: Record<string, unknown> | null;
97
+ outputMapping?: Record<string, unknown> | null;
72
98
  enabled: boolean;
73
99
  steps: PipelineStepDef[];
74
100
  }
75
101
 
102
+ export type JobStatus =
103
+ | 'pending'
104
+ | 'running'
105
+ | 'polling'
106
+ | 'waiting_input'
107
+ | 'completed'
108
+ | 'failed'
109
+ | 'cancelled'
110
+ | 'timeout';
111
+
76
112
  export interface JobState {
77
113
  id: number;
78
114
  pipelineId: number;
79
- status: 'pending' | 'running' | 'polling' | 'completed' | 'failed' | 'timeout';
80
- input: any;
115
+ status: JobStatus;
116
+ input: Record<string, unknown>;
81
117
  currentStep: number;
82
- stepResults: Record<string, any>;
83
- finalResult?: any;
118
+ stepResults: Record<string, unknown>;
119
+ finalResult?: unknown;
84
120
  error?: string;
85
121
  externalTaskIds: Record<string, string>;
122
+ operationId?: string;
123
+ waitState?: WaitState | null;
124
+ usage?: UsageMetrics | null;
86
125
  startedAt?: Date;
87
126
  completedAt?: Date;
88
127
  ownedBy?: string;
89
128
  leaseExpiresAt?: Date | null;
90
129
  }
130
+
131
+ export interface DuApiKeySummary {
132
+ id: number;
133
+ name: string;
134
+ keyPrefix: string;
135
+ tenantId: string;
136
+ allowedBusinesses: string[];
137
+ allowedActions: string[];
138
+ requestDefaults?: Record<string, unknown> | null;
139
+ lockedFields?: string[] | null;
140
+ status: 'active' | 'revoked';
141
+ expiresAt?: string | Date | null;
142
+ lastUsedAt?: string | Date | null;
143
+ createdAt?: string | Date;
144
+ }
145
+
146
+ export interface IssuedDuApiKey extends DuApiKeySummary {
147
+ rawKey: string;
148
+ }
149
+
150
+ export interface UsageSummaryView {
151
+ from: string;
152
+ to: string;
153
+ totalOperations: number;
154
+ inputTokens: number;
155
+ outputTokens: number;
156
+ costMicrousd: number;
157
+ byBusiness: Array<{
158
+ businessId: string;
159
+ action: string;
160
+ operations: number;
161
+ inputTokens: number;
162
+ outputTokens: number;
163
+ costMicrousd: number;
164
+ }>;
165
+ }
166
+
167
+ export type {
168
+ DocumentInputCoverage,
169
+ DuOperationState,
170
+ OperationProgress,
171
+ OperationView,
172
+ ProblemDetails,
173
+ UsageMetrics,
174
+ WaitState,
175
+ };
@@ -0,0 +1,308 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import { readFileSync } from 'fs';
4
+ import { basename } from 'path';
5
+ import mime from 'mime-types';
6
+ import {
7
+ EXECUTION_STATUS,
8
+ Instruction,
9
+ JOB_STATUS,
10
+ type FlowNodeModel,
11
+ type IJob,
12
+ type JobModel,
13
+ type Processor,
14
+ } from '@nocobase/plugin-workflow';
15
+ import { parsePageRangeString, type DocumentSelection } from '../contracts/du-contracts';
16
+ import type { DocumentUnderstandingService } from '../services/DocumentUnderstandingService';
17
+ import { resolveUploadFilePath } from '../services/PipelineExecutor';
18
+
19
+ export interface DocumentUnderstandingNodeConfig {
20
+ mode?: 'business_action' | 'pipeline';
21
+ businessId?: 'document-core' | 'lc-checker' | 'example-review';
22
+ action?: string;
23
+ variant?: string;
24
+ pipelineId?: number;
25
+ files?: unknown;
26
+ pages?: string;
27
+ inputJson?: Record<string, unknown> | string;
28
+ ignoreFail?: boolean;
29
+ }
30
+
31
+ function isRecord(value: unknown): value is Record<string, unknown> {
32
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
33
+ }
34
+
35
+ function collectFileUrlStrings(rawFiles: unknown): string[] {
36
+ if (!rawFiles) return [];
37
+ if (typeof rawFiles === 'string') {
38
+ return rawFiles
39
+ .split(',')
40
+ .map((s) => s.trim())
41
+ .filter(Boolean);
42
+ }
43
+ if (Array.isArray(rawFiles)) {
44
+ const urls: string[] = [];
45
+ for (const item of rawFiles) {
46
+ urls.push(...collectFileUrlStrings(item));
47
+ }
48
+ return urls;
49
+ }
50
+ if (isRecord(rawFiles)) {
51
+ if (typeof rawFiles.url === 'string') return [rawFiles.url];
52
+ if (typeof rawFiles.filename === 'string') return [`uploads/${rawFiles.filename}`];
53
+ }
54
+ return [];
55
+ }
56
+
57
+ function applyVariantToInput(action: string, variant: string | undefined, target: Record<string, unknown>): void {
58
+ if (!variant || !variant.trim()) return;
59
+ const v = variant.trim();
60
+ if (action === 'ingest' || action === 'compare') {
61
+ if (target.mode === undefined) target.mode = v;
62
+ } else if (action === 'extract') {
63
+ if (target.type === undefined) target.type = v;
64
+ } else if (action === 'analyze' || action === 'generate') {
65
+ if (target.task === undefined) target.task = v;
66
+ } else if (action === 'transform') {
67
+ if (target.variant === undefined) target.variant = v;
68
+ }
69
+ }
70
+
71
+ export class DocumentUnderstandingWorkflowInstruction extends Instruction {
72
+ private getService(): DocumentUnderstandingService {
73
+ const appWithService = this.workflow.app as typeof this.workflow.app & {
74
+ documentUnderstandingService?: DocumentUnderstandingService;
75
+ };
76
+ const pluginInstance = (this.workflow.app.pm?.get?.('plugin-document-understanding') ||
77
+ this.workflow.app.pm?.get?.('document-understanding')) as { service?: DocumentUnderstandingService } | undefined;
78
+
79
+ const service = pluginInstance?.service || appWithService.documentUnderstandingService;
80
+ if (!service) {
81
+ throw new Error('Document Understanding service is not available');
82
+ }
83
+ return service;
84
+ }
85
+
86
+ private async executeConfig(
87
+ config: DocumentUnderstandingNodeConfig,
88
+ signal?: AbortSignal,
89
+ ): Promise<Record<string, unknown>> {
90
+ const service = this.getService();
91
+ await service.ensureInitialized();
92
+
93
+ let parsedInput: Record<string, unknown> = {};
94
+ if (typeof config.inputJson === 'string' && config.inputJson.trim()) {
95
+ const parsed: unknown = JSON.parse(config.inputJson);
96
+ if (isRecord(parsed)) parsedInput = { ...parsed };
97
+ } else if (isRecord(config.inputJson)) {
98
+ parsedInput = { ...config.inputJson };
99
+ }
100
+
101
+ const fileUrls = collectFileUrlStrings(config.files);
102
+
103
+ if (config.mode === 'pipeline') {
104
+ const pipelineId = Number(config.pipelineId);
105
+ if (!Number.isSafeInteger(pipelineId) || pipelineId <= 0) {
106
+ throw new Error('Workflow node in pipeline mode requires a valid pipelineId');
107
+ }
108
+ if (config.pages && !parsedInput.pages) {
109
+ parsedInput.pages = config.pages;
110
+ }
111
+ const fileRefs = fileUrls.map((url) => ({
112
+ url,
113
+ fieldName: 'file',
114
+ buffer: undefined as unknown as Buffer,
115
+ filename: '',
116
+ mimeType: '',
117
+ }));
118
+
119
+ const { jobId } = await service.executePipeline(pipelineId, parsedInput, fileRefs);
120
+ const serviceConf = await service.getConfig();
121
+ const deadline = Date.now() + (serviceConf.pollTimeout || 300_000);
122
+
123
+ while (Date.now() < deadline) {
124
+ if (signal?.aborted) {
125
+ await service.cancelJob(jobId).catch(() => undefined);
126
+ throw new Error('Workflow execution aborted');
127
+ }
128
+ const job = await service.getJobStatus(jobId);
129
+ if (job.status === 'completed') {
130
+ const finalObj = isRecord(job.finalResult) ? job.finalResult : { data: job.finalResult };
131
+ return {
132
+ jobId,
133
+ operationId: job.operationId ?? null,
134
+ state: 'SUCCEEDED',
135
+ ...finalObj,
136
+ usage: job.usage ?? finalObj.usage ?? null,
137
+ };
138
+ }
139
+ if (['failed', 'cancelled', 'timeout'].includes(job.status)) {
140
+ throw new Error(job.error || `Document pipeline job #${jobId} ended with status ${job.status}`);
141
+ }
142
+ await new Promise((resolve) => setTimeout(resolve, 500));
143
+ }
144
+ throw new Error(`Document pipeline job #${jobId} timed out`);
145
+ }
146
+
147
+ // Default: Canonical `du-rework` Business Action execution
148
+ const businessId = config.businessId || 'document-core';
149
+ const action = config.action || 'extract';
150
+ applyVariantToInput(action, config.variant, parsedInput);
151
+
152
+ const artifactIds: string[] = [];
153
+ for (const rawUrl of fileUrls) {
154
+ const localPath = resolveUploadFilePath(rawUrl);
155
+ if (!localPath) continue;
156
+ const bytes = readFileSync(localPath);
157
+ const fileName = basename(localPath);
158
+ const mimeType = String(mime.lookup(localPath) || 'application/octet-stream');
159
+ const created = await service.orchestrator.artifactStorage.createReadyArtifactFromBuffer({
160
+ tenantId: 'default',
161
+ fileName,
162
+ mimeType,
163
+ buffer: bytes,
164
+ });
165
+ artifactIds.push(created.artifactId);
166
+ }
167
+
168
+ let documentSelection: DocumentSelection | undefined;
169
+ if (config.pages && config.pages.trim() && artifactIds.length > 0) {
170
+ const ranges = parsePageRangeString(config.pages, 500);
171
+ if (ranges.length > 0) {
172
+ documentSelection = {
173
+ kind: 'requestSelection',
174
+ schemaVersion: 1,
175
+ mode: 'combined',
176
+ artifactIds,
177
+ pageSelections: artifactIds.map((artifactId) => ({
178
+ artifactId,
179
+ selection: { kind: 'ranges', ranges },
180
+ })),
181
+ };
182
+ }
183
+ }
184
+
185
+ const submitted = await service.orchestrator.submitOperation({
186
+ principal: {
187
+ kind: 'nocobase_user',
188
+ tenantId: 'default',
189
+ allowedBusinesses: ['*'],
190
+ allowedActions: ['*'],
191
+ },
192
+ businessId,
193
+ action,
194
+ submission: {
195
+ input: parsedInput,
196
+ artifacts: artifactIds.map((artifactId) => ({ artifactId, role: 'input' })),
197
+ documentSelection,
198
+ },
199
+ });
200
+
201
+ const serviceConf = await service.getConfig();
202
+ const deadline = Date.now() + (serviceConf.pollTimeout || 300_000);
203
+
204
+ while (Date.now() < deadline) {
205
+ if (signal?.aborted) {
206
+ await service.orchestrator.cancelOperation('default', submitted.operationId).catch(() => undefined);
207
+ throw new Error('Workflow execution aborted');
208
+ }
209
+ const view = await service.orchestrator.waitForOperation('default', submitted.operationId, 5);
210
+ if (view.state === 'SUCCEEDED') {
211
+ const opRecord = await service.orchestrator.getOperationRecordOrThrow('default', submitted.operationId);
212
+ const payload = opRecord.outputPayload || {};
213
+ return {
214
+ operationId: submitted.operationId,
215
+ state: 'SUCCEEDED',
216
+ data: payload.data ?? payload,
217
+ markdown: payload.markdown ?? null,
218
+ text: payload.text ?? null,
219
+ report: payload.report ?? null,
220
+ verdict: payload.verdict ?? null,
221
+ discrepancies: payload.discrepancies ?? null,
222
+ usage: opRecord.usage ?? null,
223
+ };
224
+ }
225
+ if (['FAILED', 'CANCELLED', 'TIMED_OUT'].includes(view.state)) {
226
+ throw new Error(view.error?.detail || view.error?.title || `Operation ended in state ${view.state}`);
227
+ }
228
+ // If WAITING_INPUT, keep waiting cleanly until human reviewer resumes or deadline expires
229
+ if (view.state === 'WAITING_INPUT') {
230
+ await new Promise((resolve) => setTimeout(resolve, 1000));
231
+ }
232
+ }
233
+
234
+ throw new Error(`Document Understanding operation ${submitted.operationId} timed out`);
235
+ }
236
+
237
+ async run(node: FlowNodeModel, prevJob: JobModel, processor: Processor, options?: { signal?: AbortSignal }) {
238
+ const config = processor.getParsedValue(node.config, node.id) as DocumentUnderstandingNodeConfig;
239
+ const sync = processor.isInstructionSync(node);
240
+
241
+ if (sync) {
242
+ try {
243
+ const result = await this.executeConfig(config, options?.signal);
244
+ return { status: JOB_STATUS.RESOLVED, result };
245
+ } catch (err: unknown) {
246
+ const message = err instanceof Error ? err.message : String(err);
247
+ return {
248
+ status: config.ignoreFail ? JOB_STATUS.RESOLVED : JOB_STATUS.ERROR,
249
+ result: { error: message },
250
+ };
251
+ }
252
+ }
253
+
254
+ const { id } = processor.saveJob({
255
+ status: JOB_STATUS.PENDING,
256
+ nodeId: node.id,
257
+ nodeKey: node.key,
258
+ upstreamId: prevJob?.id ?? null,
259
+ });
260
+
261
+ await processor.exit();
262
+ const abortHandle = processor.createBackgroundAbortHandle();
263
+ const jobDone: IJob = { status: JOB_STATUS.PENDING };
264
+
265
+ const settle = async () => {
266
+ try {
267
+ const result = await this.executeConfig(config, abortHandle.signal);
268
+ jobDone.status = JOB_STATUS.RESOLVED;
269
+ jobDone.result = result;
270
+ } catch (err: unknown) {
271
+ const message = err instanceof Error ? err.message : String(err);
272
+ jobDone.status = abortHandle.signal.aborted
273
+ ? JOB_STATUS.ABORTED
274
+ : config.ignoreFail
275
+ ? JOB_STATUS.RESOLVED
276
+ : JOB_STATUS.ERROR;
277
+ jobDone.result = { error: message };
278
+ } finally {
279
+ abortHandle.dispose();
280
+ const job = await this.workflow.app.db.getRepository('jobs').findOne({ filterByTk: id });
281
+ if (job) {
282
+ const execution = await job.getExecution();
283
+ const aborted = await this.workflow.abortExecutionIfExpired(execution);
284
+ if (!aborted) {
285
+ await execution.reload();
286
+ await job.reload();
287
+ }
288
+ if (!aborted && execution.status === EXECUTION_STATUS.STARTED && job.status === JOB_STATUS.PENDING) {
289
+ job.set(jobDone);
290
+ await this.workflow.resume(job);
291
+ }
292
+ }
293
+ }
294
+ };
295
+
296
+ settle().catch((err) => {
297
+ processor.logger.error(`Document Understanding workflow node (#${node.id}) settling failed`, err);
298
+ });
299
+ }
300
+
301
+ async resume(node: FlowNodeModel, job: JobModel) {
302
+ const config = (node.config || {}) as DocumentUnderstandingNodeConfig;
303
+ if (config.ignoreFail) {
304
+ job.set('status', JOB_STATUS.RESOLVED);
305
+ }
306
+ return job;
307
+ }
308
+ }