plugin-document-understanding 1.1.12 → 1.1.14

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.
@@ -1,134 +1,143 @@
1
- import { Plugin } from '@nocobase/server';
2
- import { resolve } from 'path';
3
- import { DocumentUnderstandingService } from './services/DocumentUnderstandingService';
4
- import { defineActions } from './actions';
5
- import { createDynamicPipelineToolsProvider } from './tools/document-understanding-tool';
6
-
7
- type DynamicToolsProvider = ReturnType<typeof createDynamicPipelineToolsProvider>;
8
-
9
- interface AiManagerLike {
10
- toolsManager?: {
11
- registerDynamicTools: (provider: DynamicToolsProvider) => void;
12
- };
13
- }
14
-
15
- interface DocumentToolRuntimeState {
16
- documentUnderstandingToolProviderRegistered?: boolean;
17
- documentUnderstandingService?: DocumentUnderstandingService;
18
- }
19
-
20
- const isAiManagerLike = (manager: unknown): manager is AiManagerLike => {
21
- const candidate = manager as AiManagerLike;
22
- return typeof candidate?.toolsManager?.registerDynamicTools === 'function';
23
- };
24
-
25
- export class PluginDocumentUnderstandingServer extends Plugin {
26
- public service!: DocumentUnderstandingService;
27
- private aiToolsRegistered = false;
28
- private readonly registerAIToolsAfterStart = () => this.registerAITools();
29
-
30
- async afterAdd() {}
31
-
32
- async beforeLoad() {
33
- await this.db.import({
34
- directory: resolve(__dirname, 'collections'),
35
- });
36
- }
37
-
38
- async load() {
39
- // Collections are imported in beforeLoad so database metadata exists before
40
- // resources and runtime services are registered.
41
- this.service = new DocumentUnderstandingService(this.app, this.db);
42
-
43
- // Register REST actions
44
- this.registerActions();
45
-
46
- // 4. Register AI tool (graceful)
47
- this.registerAITools();
48
- this.app.on('afterStart', this.registerAIToolsAfterStart);
49
-
50
- // 5. ACL
51
- this.app.acl.registerSnippet({
52
- name: `pm.${this.name}`,
53
- actions: ['docUnderstanding:*'],
54
- });
55
- }
56
-
57
- private registerActions() {
58
- const actions = defineActions(this);
59
-
60
- const resourceName = 'docUnderstanding';
61
- this.app.resource({
62
- name: resourceName,
63
- actions: {
64
- getConfig: actions.getConfig,
65
- updateConfig: actions.updateConfig,
66
- listEndpoints: actions.listEndpoints,
67
- createEndpoint: actions.createEndpoint,
68
- updateEndpoint: actions.updateEndpoint,
69
- deleteEndpoint: actions.deleteEndpoint,
70
- listPipelines: actions.listPipelines,
71
- createPipeline: actions.createPipeline,
72
- updatePipeline: actions.updatePipeline,
73
- deletePipeline: actions.deletePipeline,
74
- executePipeline: actions.executePipeline,
75
- getJobStatus: actions.getJobStatus,
76
- listJobs: actions.listJobs,
77
- webhookCallback: actions.webhookCallback,
78
- },
79
- });
80
- }
81
-
82
- private registerAITools() {
83
- if (this.aiToolsRegistered) return;
84
- try {
85
- const aiManager = (this.app as typeof this.app & { aiManager?: unknown }).aiManager;
86
- if (!isAiManagerLike(aiManager)) {
87
- this.app.logger.warn('Document Understanding: plugin-ai not available, skip AI tool registration.');
88
- return;
89
- }
90
- const runtimeState = this.app as typeof this.app & DocumentToolRuntimeState;
91
- runtimeState.documentUnderstandingService = this.service;
92
- if (!runtimeState.documentUnderstandingToolProviderRegistered) {
93
- aiManager.toolsManager.registerDynamicTools(async (register) => {
94
- const currentService = runtimeState.documentUnderstandingService;
95
- if (!currentService) return;
96
- await createDynamicPipelineToolsProvider(currentService)(register);
97
- });
98
- runtimeState.documentUnderstandingToolProviderRegistered = true;
99
- }
100
- this.aiToolsRegistered = true;
101
- this.app.logger.info('Document Understanding: Dynamic pipeline tools provider registered.');
102
- } catch (err) {
103
- this.app.logger.warn('Document Understanding: Failed to register AI tools, continue without it.', err);
104
- }
105
- }
106
-
107
- async afterStart() {
108
- try {
109
- await this.service.initialize({ recoverJobs: true });
110
- } catch (err) {
111
- this.app.logger.warn('Document Understanding plugin not configured yet, skip init.', err);
112
- }
113
- }
114
-
115
- async install() {}
116
-
117
- async afterEnable() {}
118
-
119
- async afterDisable() {}
120
-
121
- async remove() {}
122
-
123
- async beforeStop() {
124
- this.app.off?.('afterStart', this.registerAIToolsAfterStart);
125
- this.app.removeListener?.('afterStart', this.registerAIToolsAfterStart);
126
- this.service?.destroy();
127
- const runtimeState = this.app as typeof this.app & DocumentToolRuntimeState;
128
- if (runtimeState.documentUnderstandingService === this.service) {
129
- runtimeState.documentUnderstandingService = undefined;
130
- }
131
- }
132
- }
133
-
134
- export default PluginDocumentUnderstandingServer;
1
+ import { Plugin } from '@nocobase/server';
2
+ import { resolve } from 'path';
3
+ import { DocumentUnderstandingService } from './services/DocumentUnderstandingService';
4
+ import { defineActions } from './actions';
5
+ import { createDynamicPipelineToolsProvider } from './tools/document-understanding-tool';
6
+ import { seedDugateEndpoints } from './dugate-seed';
7
+
8
+ type DynamicToolsProvider = ReturnType<typeof createDynamicPipelineToolsProvider>;
9
+
10
+ interface AiManagerLike {
11
+ toolsManager?: {
12
+ registerDynamicTools: (provider: DynamicToolsProvider) => void;
13
+ };
14
+ }
15
+
16
+ interface DocumentToolRuntimeState {
17
+ documentUnderstandingToolProviderRegistered?: boolean;
18
+ documentUnderstandingService?: DocumentUnderstandingService;
19
+ }
20
+
21
+ const isAiManagerLike = (manager: unknown): manager is AiManagerLike => {
22
+ const candidate = manager as AiManagerLike;
23
+ return typeof candidate?.toolsManager?.registerDynamicTools === 'function';
24
+ };
25
+
26
+ export class PluginDocumentUnderstandingServer extends Plugin {
27
+ public service!: DocumentUnderstandingService;
28
+ private aiToolsRegistered = false;
29
+ private readonly registerAIToolsAfterStart = () => this.registerAITools();
30
+
31
+ async afterAdd() {}
32
+
33
+ async beforeLoad() {
34
+ await this.db.import({
35
+ directory: resolve(__dirname, 'collections'),
36
+ });
37
+ }
38
+
39
+ async load() {
40
+ // Collections are imported in beforeLoad so database metadata exists before
41
+ // resources and runtime services are registered.
42
+ this.service = new DocumentUnderstandingService(this.app, this.db);
43
+
44
+ // Register REST actions
45
+ this.registerActions();
46
+
47
+ // 4. Register AI tool (graceful)
48
+ this.registerAITools();
49
+ this.app.on('afterStart', this.registerAIToolsAfterStart);
50
+
51
+ // 5. ACL
52
+ this.app.acl.registerSnippet({
53
+ name: `pm.${this.name}`,
54
+ actions: ['docUnderstanding:*'],
55
+ });
56
+ }
57
+
58
+ private registerActions() {
59
+ const actions = defineActions(this);
60
+
61
+ const resourceName = 'docUnderstanding';
62
+ this.app.resource({
63
+ name: resourceName,
64
+ actions: {
65
+ getConfig: actions.getConfig,
66
+ updateConfig: actions.updateConfig,
67
+ listEndpoints: actions.listEndpoints,
68
+ createEndpoint: actions.createEndpoint,
69
+ updateEndpoint: actions.updateEndpoint,
70
+ deleteEndpoint: actions.deleteEndpoint,
71
+ listPipelines: actions.listPipelines,
72
+ createPipeline: actions.createPipeline,
73
+ updatePipeline: actions.updatePipeline,
74
+ deletePipeline: actions.deletePipeline,
75
+ executePipeline: actions.executePipeline,
76
+ getJobStatus: actions.getJobStatus,
77
+ listJobs: actions.listJobs,
78
+ webhookCallback: actions.webhookCallback,
79
+ },
80
+ });
81
+ }
82
+
83
+ private registerAITools() {
84
+ if (this.aiToolsRegistered) return;
85
+ try {
86
+ const aiManager = (this.app as typeof this.app & { aiManager?: unknown }).aiManager;
87
+ if (!isAiManagerLike(aiManager)) {
88
+ this.app.logger.warn('Document Understanding: plugin-ai not available, skip AI tool registration.');
89
+ return;
90
+ }
91
+ const runtimeState = this.app as typeof this.app & DocumentToolRuntimeState;
92
+ runtimeState.documentUnderstandingService = this.service;
93
+ if (!runtimeState.documentUnderstandingToolProviderRegistered) {
94
+ aiManager.toolsManager.registerDynamicTools(async (register) => {
95
+ const currentService = runtimeState.documentUnderstandingService;
96
+ if (!currentService) return;
97
+ await createDynamicPipelineToolsProvider(currentService)(register);
98
+ });
99
+ runtimeState.documentUnderstandingToolProviderRegistered = true;
100
+ }
101
+ this.aiToolsRegistered = true;
102
+ this.app.logger.info('Document Understanding: Dynamic pipeline tools provider registered.');
103
+ } catch (err) {
104
+ this.app.logger.warn('Document Understanding: Failed to register AI tools, continue without it.', err);
105
+ }
106
+ }
107
+
108
+ async afterStart() {
109
+ try {
110
+ await this.service.initialize({ recoverJobs: true });
111
+ } catch (err) {
112
+ this.app.logger.warn('Document Understanding plugin not configured yet, skip init.', err);
113
+ }
114
+ }
115
+
116
+ async install() {
117
+ // Seed the DUGate-compatible endpoint/pipeline catalog on first install.
118
+ // Subpaths stay relative so they follow the base URL in Service Config.
119
+ try {
120
+ await seedDugateEndpoints(this.db);
121
+ } catch (err) {
122
+ this.app.logger.warn('Document Understanding: DUGate seed data could not be installed.', err);
123
+ }
124
+ }
125
+
126
+ async afterEnable() {}
127
+
128
+ async afterDisable() {}
129
+
130
+ async remove() {}
131
+
132
+ async beforeStop() {
133
+ this.app.off?.('afterStart', this.registerAIToolsAfterStart);
134
+ this.app.removeListener?.('afterStart', this.registerAIToolsAfterStart);
135
+ this.service?.destroy();
136
+ const runtimeState = this.app as typeof this.app & DocumentToolRuntimeState;
137
+ if (runtimeState.documentUnderstandingService === this.service) {
138
+ runtimeState.documentUnderstandingService = undefined;
139
+ }
140
+ }
141
+ }
142
+
143
+ export default PluginDocumentUnderstandingServer;
@@ -295,7 +295,7 @@ export class DocumentUnderstandingService {
295
295
  }
296
296
  }
297
297
 
298
- const taskId = payload.task_id;
298
+ const taskId = payload.task_id ?? payload.operation_id;
299
299
  const result = payload.result;
300
300
  if (!taskId) throw new Error('Webhook missing task_id');
301
301
 
@@ -67,6 +67,36 @@ export class ExternalApiClient {
67
67
  return normalized;
68
68
  }
69
69
 
70
+ /**
71
+ * Appends the endpoint discriminator (if configured) to the request body so
72
+ * DUGate-style gateways can route to the correct sub-case/profile.
73
+ */
74
+ private withDiscriminator(endpoint: EndpointDef, body?: Record<string, any>): Record<string, any> | undefined {
75
+ const field = endpoint.discriminatorField?.trim();
76
+ if (!field || !endpoint.discriminatorValue) {
77
+ return body;
78
+ }
79
+ const merged: Record<string, any> = { ...(body || {}) };
80
+ if (merged[field] !== undefined && merged[field] !== endpoint.discriminatorValue) {
81
+ throw new Error(
82
+ `Discriminator field '${field}' is locked by endpoint configuration (expected '${endpoint.discriminatorValue}', got '${merged[field]}').`,
83
+ );
84
+ }
85
+ merged[field] = endpoint.discriminatorValue;
86
+ return merged;
87
+ }
88
+
89
+ /**
90
+ * Appends the DUGate sync flag (?sync=true) for endpoints configured with
91
+ * `syncQueryParam`. Kept separate from other query parameters so GET/DELETE
92
+ * params in `body` are not polluted by the discriminator logic.
93
+ */
94
+ private syncQueryParams(endpoint: EndpointDef): Record<string, string> {
95
+ const param = endpoint.syncQueryParam?.trim();
96
+ if (!param) return {};
97
+ return { [param]: 'true' };
98
+ }
99
+
70
100
  async call(options: ApiCallOptions): Promise<{ status: number; data: any; headers: any }> {
71
101
  const { endpoint, body, files, overrideHeaders } = options;
72
102
 
@@ -82,8 +112,9 @@ export class ExternalApiClient {
82
112
 
83
113
  if (endpoint.fileInputMode === 'multipart' && files && files.length > 0) {
84
114
  const formData = new FormData();
85
- if (body) {
86
- for (const [key, value] of Object.entries(body)) {
115
+ const bodyWithDiscriminator = this.withDiscriminator(endpoint, body);
116
+ if (bodyWithDiscriminator) {
117
+ for (const [key, value] of Object.entries(bodyWithDiscriminator)) {
87
118
  formData.append(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
88
119
  }
89
120
  }
@@ -107,18 +138,22 @@ export class ExternalApiClient {
107
138
  mimeType: f.mimeType,
108
139
  };
109
140
  }
110
- requestData = { ...body, _files: base64Files };
141
+ requestData = { ...this.withDiscriminator(endpoint, body), _files: base64Files };
111
142
  headers['Content-Type'] = 'application/json';
112
143
  } else {
144
+ requestData = this.withDiscriminator(endpoint, body);
113
145
  headers['Content-Type'] = 'application/json';
114
146
  }
115
147
 
116
148
  try {
149
+ const isBodyless = ['get', 'delete'].includes(method);
117
150
  const response: AxiosResponse = await this.client.request({
118
151
  url,
119
152
  method,
120
- data: ['post', 'put', 'patch'].includes(method) ? requestData : undefined,
121
- params: ['get', 'delete'].includes(method) ? requestData : undefined,
153
+ data: isBodyless ? undefined : requestData,
154
+ params: isBodyless
155
+ ? { ...(requestData || {}), ...this.syncQueryParams(endpoint) }
156
+ : this.syncQueryParams(endpoint),
122
157
  headers,
123
158
  });
124
159
 
@@ -22,6 +22,46 @@ const UPLOAD_ROOTS = [resolve(process.cwd(), 'storage', 'uploads')];
22
22
  const isInsidePath = (basePath: string, targetPath: string) =>
23
23
  targetPath === basePath || targetPath.startsWith(`${basePath}${sep}`);
24
24
 
25
+ /**
26
+ * Extract a task ID from a DUGate-style 202 Accepted response.
27
+ * Priority:
28
+ * 1. `taskIdExtractPath` + optional `taskIdExtractRegex` (e.g. path="name", regex="operations/([^/]+)")
29
+ * 2. `pollTaskIdField` (default "task_id")
30
+ * 3. Raw response body as string fallback
31
+ */
32
+ function extractTaskId(responseData: any, endpoint: EndpointDef): string | null {
33
+ // 1. taskIdExtractPath: navigate to a field, then optionally apply regex
34
+ const extractPath = endpoint.taskIdExtractPath?.trim();
35
+ if (extractPath) {
36
+ const raw = extractPath
37
+ .split('.')
38
+ .reduce((acc: any, k: string) => (acc != null ? acc[k] : undefined), responseData);
39
+ if (raw != null) {
40
+ const regex = endpoint.taskIdExtractRegex?.trim();
41
+ if (regex) {
42
+ try {
43
+ const m = String(raw).match(new RegExp(regex));
44
+ if (m?.[1]) return m[1];
45
+ } catch {
46
+ /* invalid regex, fall through */
47
+ }
48
+ }
49
+ return String(raw);
50
+ }
51
+ }
52
+
53
+ // 2. pollTaskIdField (default "task_id")
54
+ const idField = endpoint.pollTaskIdField || 'task_id';
55
+ const fieldVal = idField.split('.').reduce((acc: any, k: string) => (acc != null ? acc[k] : undefined), responseData);
56
+ if (fieldVal != null) return String(fieldVal);
57
+
58
+ // 3. Raw string fallback
59
+ if (typeof responseData === 'string') return responseData;
60
+ if (typeof responseData === 'number') return String(responseData);
61
+
62
+ return null;
63
+ }
64
+
25
65
  export function resolveUploadFilePath(urlOrPath: string): string | null {
26
66
  if (!urlOrPath || urlOrPath.includes('\0')) return null;
27
67
 
@@ -273,7 +313,10 @@ export class PipelineExecutor {
273
313
  throw new Error(`Endpoint for step ${step.name} is disabled`);
274
314
  }
275
315
 
276
- const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
316
+ const mappedBody =
317
+ step.inputMapping && Object.keys(step.inputMapping).length > 0
318
+ ? this.resolveMapping(step.inputMapping, context)
319
+ : context.input;
277
320
  let retries = step.onError === 'retry' ? step.retryCount || 0 : 0;
278
321
  let success = false;
279
322
  let lastError = null;
@@ -295,14 +338,40 @@ export class PipelineExecutor {
295
338
  });
296
339
 
297
340
  if (step.endpoint.executionMode === 'sync') {
298
- context.stepResults[step.outputAlias || step.stepOrder.toString()] = result.data;
341
+ const responseData = result.data;
342
+ // DUGate sync mode (?sync=true) can still return 202 Accepted with a
343
+ // task id (pipeline/workflow jobs that never run synchronously). In
344
+ // that case we treat the endpoint as an async poll to completion.
345
+ const isAsyncAccepted =
346
+ result.status === 202 ||
347
+ (responseData && typeof responseData === 'object' && responseData.done === false);
348
+ if (isAsyncAccepted) {
349
+ const taskId = extractTaskId(responseData, step.endpoint);
350
+ if (taskId) {
351
+ const externalTaskIds = { ...(job.externalTaskIds || {}) };
352
+ externalTaskIds[step.stepOrder.toString()] = taskId;
353
+
354
+ await jobsRepo.update({
355
+ filterByTk: job.id,
356
+ values: {
357
+ status: 'polling',
358
+ externalTaskIds,
359
+ leaseExpiresAt: new Date(Date.now() + pollLeaseMs(step.endpoint.pollInterval)),
360
+ },
361
+ });
362
+
363
+ await this.jobManager.startPolling(job.id, step.endpoint, taskId);
364
+ return; // Halt execution. Polling callback will resume from next step.
365
+ }
366
+ // No task id: fall through and store the raw 202 body as the step result.
367
+ }
368
+ context.stepResults[step.outputAlias || step.stepOrder.toString()] = responseData;
299
369
  success = true;
300
370
  } else if (step.endpoint.executionMode === 'polling') {
301
- // Extract taskId from result based on pollTaskIdField
302
- const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
303
- const taskId = this.getNestedValue(result.data, taskIdField);
371
+ // Extract taskId from result based on pollTaskIdField / taskIdExtractPath
372
+ const taskId = extractTaskId(result.data, step.endpoint);
304
373
 
305
- if (!taskId) throw new Error(`Polling taskId not found in field ${taskIdField}`);
374
+ if (!taskId) throw new Error('Polling taskId not found in response');
306
375
 
307
376
  const externalTaskIds = job.externalTaskIds || {};
308
377
  externalTaskIds[step.stepOrder.toString()] = taskId;
@@ -323,8 +392,8 @@ export class PipelineExecutor {
323
392
  return;
324
393
  } else if (step.endpoint.executionMode === 'webhook') {
325
394
  // Wait for webhook
326
- const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
327
- const taskId = this.getNestedValue(result.data, taskIdField);
395
+ const taskId = extractTaskId(result.data, step.endpoint);
396
+ if (!taskId) throw new Error('Webhook taskId not found in response');
328
397
  const externalTaskIds = job.externalTaskIds || {};
329
398
  externalTaskIds[step.stepOrder.toString()] = taskId;
330
399
 
@@ -28,6 +28,16 @@ export interface EndpointDef {
28
28
  fileFieldName?: string;
29
29
  maxFiles: number;
30
30
  executionMode: 'sync' | 'polling' | 'webhook';
31
+ /** Discriminator field name sent in the request body/query (e.g. DUGate 'mode'/'type'/'task'/'action'/'process'). */
32
+ discriminatorField?: string;
33
+ /** Discriminator value for this endpoint (e.g. DUGate 'parse', 'invoice', 'disbursement'). */
34
+ discriminatorValue?: string;
35
+ /** When set, the request also appends '?sync=true' (DUGate synchronous mode). */
36
+ 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. */
38
+ taskIdExtractPath?: string;
39
+ /** For 'sync' mode: regex used to extract the task ID from a string field (e.g. 'operations/([^/]+)'). */
40
+ taskIdExtractRegex?: string;
31
41
  pollResultSubpath?: string;
32
42
  pollTaskIdField?: string;
33
43
  pollResultField?: string;