plugin-document-understanding 1.1.3 → 1.1.6

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 (76) hide show
  1. package/README.md +21 -8
  2. package/client-v2.d.ts +2 -0
  3. package/client-v2.js +1 -0
  4. package/dist/client/index.js +1 -1
  5. package/dist/client-v2/794.9b984a25b2fc7c14.js +10 -0
  6. package/dist/client-v2/index.js +10 -0
  7. package/dist/externalVersion.js +7 -6
  8. package/dist/node_modules/form-data/License +19 -0
  9. package/dist/node_modules/form-data/index.d.ts +62 -0
  10. package/dist/node_modules/form-data/lib/browser.js +4 -0
  11. package/dist/node_modules/form-data/lib/form_data.js +14 -0
  12. package/dist/node_modules/form-data/lib/populate.js +10 -0
  13. package/dist/node_modules/form-data/package.json +1 -0
  14. package/dist/node_modules/mime-types/LICENSE +23 -0
  15. package/dist/node_modules/mime-types/index.js +14 -0
  16. package/dist/node_modules/mime-types/package.json +1 -0
  17. package/dist/server/actions.js +7 -6
  18. package/dist/server/collections/endpoints.js +1 -1
  19. package/dist/server/plugin.js +7 -3
  20. package/dist/server/services/AsyncJobManager.js +14 -5
  21. package/dist/server/services/DocumentUnderstandingService.js +53 -23
  22. package/dist/server/services/PipelineExecutor.js +81 -94
  23. package/package.json +49 -16
  24. package/src/client/index.tsx +9 -0
  25. package/src/client-v2/client.d.ts +249 -0
  26. package/src/client-v2/components/EndpointsTab.tsx +458 -0
  27. package/src/client-v2/components/JobsTab.tsx +259 -0
  28. package/src/client-v2/components/PipelinesTab.tsx +872 -0
  29. package/src/client-v2/components/PluginSettings.tsx +48 -0
  30. package/src/client-v2/components/ServiceConfigTab.tsx +122 -0
  31. package/src/client-v2/locale.ts +21 -0
  32. package/{dist/client/models/index.d.ts → src/client-v2/models/index.ts} +3 -2
  33. package/src/client-v2/plugin.tsx +21 -0
  34. package/src/locale/en-US.json +121 -0
  35. package/src/locale/vi-VN.json +121 -0
  36. package/src/locale/zh-CN.json +1 -0
  37. package/src/server/__tests__/actions.test.ts +98 -0
  38. package/src/server/__tests__/pipeline-executor.test.ts +33 -0
  39. package/src/server/__tests__/smoke.test.ts +55 -0
  40. package/src/server/actions.ts +176 -0
  41. package/src/server/collections/.gitkeep +0 -0
  42. package/src/server/collections/config.ts +18 -0
  43. package/src/server/collections/endpoints.ts +28 -0
  44. package/src/server/collections/jobs.ts +29 -0
  45. package/src/server/collections/pipeline-steps.ts +27 -0
  46. package/src/server/collections/pipelines.ts +19 -0
  47. package/src/server/plugin.ts +108 -0
  48. package/src/server/services/AsyncJobManager.ts +172 -0
  49. package/src/server/services/DocumentUnderstandingService.ts +264 -0
  50. package/src/server/services/ExternalApiClient.ts +143 -0
  51. package/src/server/services/PipelineExecutor.ts +502 -0
  52. package/src/server/tools/document-understanding-tool.ts +181 -0
  53. package/src/server/types.ts +73 -0
  54. package/dist/client/components/EndpointsTab.d.ts +0 -2
  55. package/dist/client/components/JobsTab.d.ts +0 -2
  56. package/dist/client/components/PipelinesTab.d.ts +0 -2
  57. package/dist/client/components/PluginSettings.d.ts +0 -2
  58. package/dist/client/components/ServiceConfigTab.d.ts +0 -2
  59. package/dist/client/locale.d.ts +0 -10
  60. package/dist/client/plugin.d.ts +0 -6
  61. package/dist/server/actions.d.ts +0 -17
  62. package/dist/server/collections/config.d.ts +0 -3
  63. package/dist/server/collections/endpoints.d.ts +0 -3
  64. package/dist/server/collections/jobs.d.ts +0 -3
  65. package/dist/server/collections/pipeline-steps.d.ts +0 -3
  66. package/dist/server/collections/pipelines.d.ts +0 -3
  67. package/dist/server/plugin.d.ts +0 -15
  68. package/dist/server/services/AsyncJobManager.d.ts +0 -27
  69. package/dist/server/services/DocumentUnderstandingService.d.ts +0 -35
  70. package/dist/server/services/ExternalApiClient.d.ts +0 -28
  71. package/dist/server/services/PipelineExecutor.d.ts +0 -24
  72. package/dist/server/tools/document-understanding-tool.d.ts +0 -8
  73. package/dist/server/types.d.ts +0 -69
  74. /package/{dist/client/index.d.ts → src/client-v2/index.tsx} +0 -0
  75. /package/{dist/index.d.ts → src/index.ts} +0 -0
  76. /package/{dist/server/index.d.ts → src/server/index.ts} +0 -0
@@ -0,0 +1,502 @@
1
+ import { existsSync, realpathSync, readFileSync, statSync } from 'fs';
2
+ import { basename, resolve, sep } from 'path';
3
+ import { Database } from '@nocobase/database';
4
+ import axios from 'axios';
5
+ import mime from 'mime-types';
6
+ import { ExternalApiClient, FileInput } from './ExternalApiClient';
7
+ import { AsyncJobManager } from './AsyncJobManager';
8
+ import { PipelineDef, PipelineStepDef, JobState, EndpointDef } from '../types';
9
+
10
+ interface LoggerLike {
11
+ error: (...args: unknown[]) => void;
12
+ warn?: (...args: unknown[]) => void;
13
+ }
14
+
15
+ interface FileReferenceInput {
16
+ buffer?: Buffer;
17
+ url?: string;
18
+ fieldName?: string;
19
+ }
20
+
21
+ const UPLOAD_ROOTS = [resolve(process.cwd(), 'storage', 'uploads')];
22
+
23
+ const isInsidePath = (basePath: string, targetPath: string) =>
24
+ targetPath === basePath || targetPath.startsWith(`${basePath}${sep}`);
25
+
26
+ export function resolveUploadFilePath(urlOrPath: string): string | null {
27
+ if (!urlOrPath || urlOrPath.includes('\0')) return null;
28
+
29
+ let pathname = urlOrPath.replace(/\\/g, '/').split(/[?#]/)[0];
30
+ try {
31
+ if (pathname.startsWith('http://') || pathname.startsWith('https://')) {
32
+ pathname = new URL(pathname).pathname;
33
+ }
34
+ } catch {
35
+ return null;
36
+ }
37
+
38
+ pathname = decodeURIComponent(pathname).replace(/^\/+/, '');
39
+ const uploadsIndex = pathname.indexOf('uploads/');
40
+ if (pathname.startsWith('storage/uploads/')) {
41
+ pathname = pathname.slice('storage/uploads/'.length);
42
+ } else if (pathname.startsWith('uploads/')) {
43
+ pathname = pathname.slice('uploads/'.length);
44
+ } else if (uploadsIndex >= 0) {
45
+ pathname = pathname.slice(uploadsIndex + 'uploads/'.length);
46
+ } else {
47
+ return null;
48
+ }
49
+
50
+ const parts = pathname.split('/').filter(Boolean);
51
+ if (parts.some((part) => part === '..' || part.includes('\0'))) return null;
52
+
53
+ for (const root of UPLOAD_ROOTS) {
54
+ const candidate = resolve(root, ...parts);
55
+ const realRoot = existsSync(root) ? realpathSync(root) : root;
56
+ if (!existsSync(candidate)) continue;
57
+ const realCandidate = realpathSync(candidate);
58
+ if (isInsidePath(realRoot, realCandidate) && statSync(realCandidate).isFile()) {
59
+ return realCandidate;
60
+ }
61
+ }
62
+
63
+ return null;
64
+ }
65
+
66
+ export interface ExecutionContext {
67
+ input: Record<string, any>;
68
+ files: FileInput[];
69
+ stepResults: Record<string, any>;
70
+ jobId: number;
71
+ }
72
+
73
+ export class PipelineExecutor {
74
+ private db: Database;
75
+ private apiClient: ExternalApiClient;
76
+ private jobManager: AsyncJobManager;
77
+ private logger: LoggerLike;
78
+
79
+ constructor(db: Database, apiClient: ExternalApiClient, jobManager: AsyncJobManager, logger: LoggerLike) {
80
+ this.db = db;
81
+ this.apiClient = apiClient;
82
+ this.jobManager = jobManager;
83
+ this.logger = logger;
84
+ }
85
+
86
+ private async resolveFile(urlOrPath: string, fieldName = 'file'): Promise<FileInput | null> {
87
+ if (!urlOrPath || typeof urlOrPath !== 'string') return null;
88
+
89
+ try {
90
+ const localPath = resolveUploadFilePath(urlOrPath);
91
+ if (localPath) {
92
+ const buffer = readFileSync(localPath);
93
+ const mimeType = mime.lookup(localPath) || 'application/octet-stream';
94
+
95
+ return {
96
+ fieldName,
97
+ buffer,
98
+ filename: basename(localPath),
99
+ mimeType,
100
+ };
101
+ }
102
+
103
+ if (urlOrPath.startsWith('http://') || urlOrPath.startsWith('https://')) {
104
+ const response = await axios.get(urlOrPath, { responseType: 'arraybuffer' });
105
+ const buffer = Buffer.from(response.data);
106
+
107
+ let filename = 'file';
108
+ const disposition = response.headers['content-disposition'];
109
+ if (disposition && disposition.includes('filename=')) {
110
+ const match = disposition.match(/filename="?([^";]+)"?/);
111
+ if (match?.[1]) {
112
+ filename = match[1];
113
+ }
114
+ } else {
115
+ const base = basename(new URL(urlOrPath).pathname);
116
+ if (base && base.includes('.')) {
117
+ filename = base;
118
+ }
119
+ }
120
+
121
+ const contentType = response.headers['content-type'] || 'application/octet-stream';
122
+ const mimeType = contentType.split(';')[0].trim();
123
+ if (!filename.includes('.')) {
124
+ const extension = mime.extension(mimeType);
125
+ if (extension) {
126
+ filename = `${filename}.${extension}`;
127
+ }
128
+ }
129
+
130
+ return {
131
+ fieldName,
132
+ buffer,
133
+ filename,
134
+ mimeType,
135
+ };
136
+ }
137
+ } catch (err) {
138
+ const message = err instanceof Error ? err.message : String(err);
139
+ this.logger.warn?.(`Failed to resolve file input: ${message}`);
140
+ }
141
+
142
+ return null;
143
+ }
144
+
145
+ async execute(
146
+ pipelineId: number,
147
+ input: Record<string, any>,
148
+ files: FileInput[] = [],
149
+ userId?: number,
150
+ ): Promise<JobState> {
151
+ const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
152
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
153
+
154
+ const pipeline = await pipelineRepo.findOne({
155
+ filter: { id: pipelineId },
156
+ appends: ['steps', 'steps.endpoint'],
157
+ });
158
+
159
+ if (!pipeline) throw new Error(`Pipeline ${pipelineId} not found`);
160
+
161
+ // Create Job
162
+ const job = await jobsRepo.create({
163
+ values: {
164
+ pipelineId,
165
+ status: 'pending',
166
+ input,
167
+ currentStep: 1, // 1-based ordering
168
+ stepResults: {},
169
+ externalTaskIds: {},
170
+ startedAt: new Date(),
171
+ createdById: userId,
172
+ },
173
+ });
174
+
175
+ const resolvedFiles: FileInput[] = [];
176
+
177
+ const tryAddFile = async (urlOrPath: string, fieldName = 'file') => {
178
+ const resolved = await this.resolveFile(urlOrPath, fieldName);
179
+ if (resolved) {
180
+ resolvedFiles.push(resolved);
181
+ }
182
+ };
183
+
184
+ // 1. Process files argument
185
+ if (Array.isArray(files)) {
186
+ for (const f of files) {
187
+ if (f && typeof f === 'object') {
188
+ const fileRef = f as FileReferenceInput;
189
+ if (fileRef.buffer) {
190
+ resolvedFiles.push(f);
191
+ } else if (fileRef.url) {
192
+ await tryAddFile(fileRef.url, fileRef.fieldName || 'file');
193
+ }
194
+ }
195
+ }
196
+ }
197
+
198
+ // 2. Scan input for common file URL keys
199
+ const urlFields = ['file_url', 'file_urls', 'file', 'files'];
200
+ for (const key of urlFields) {
201
+ const val = input[key];
202
+ if (!val) continue;
203
+
204
+ if (typeof val === 'string') {
205
+ if (
206
+ val.startsWith('http://') ||
207
+ val.startsWith('https://') ||
208
+ val.startsWith('/') ||
209
+ val.startsWith('storage/')
210
+ ) {
211
+ await tryAddFile(val, 'file');
212
+ } else if (val.includes(',')) {
213
+ const urls = val.split(',').map((s) => s.trim());
214
+ for (const u of urls) {
215
+ if (u.startsWith('http://') || u.startsWith('https://') || u.startsWith('/') || u.startsWith('storage/')) {
216
+ await tryAddFile(u, 'file');
217
+ }
218
+ }
219
+ }
220
+ } else if (Array.isArray(val)) {
221
+ for (const item of val) {
222
+ if (typeof item === 'string') {
223
+ if (
224
+ item.startsWith('http://') ||
225
+ item.startsWith('https://') ||
226
+ item.startsWith('/') ||
227
+ item.startsWith('storage/')
228
+ ) {
229
+ await tryAddFile(item, 'file');
230
+ }
231
+ } else if (item && typeof item === 'object' && item.url) {
232
+ await tryAddFile(item.url, 'file');
233
+ }
234
+ }
235
+ } else if (val && typeof val === 'object' && val.url) {
236
+ await tryAddFile(val.url, 'file');
237
+ }
238
+ }
239
+
240
+ if (resolvedFiles.length === 0 && files && files.length > 0) {
241
+ for (const f of files) {
242
+ if ((f as FileReferenceInput).buffer) {
243
+ resolvedFiles.push(f);
244
+ }
245
+ }
246
+ }
247
+
248
+ const context: ExecutionContext = {
249
+ input,
250
+ files: resolvedFiles,
251
+ stepResults: {},
252
+ jobId: job.id,
253
+ };
254
+
255
+ // Sorting steps by order
256
+ const steps = [...(pipeline.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
257
+
258
+ // Run steps (Synchronous part)
259
+ this.runSteps(job, steps, context).catch((err) => {
260
+ this.logger.error(`Background pipeline error for job ${job.id}`, err);
261
+ });
262
+
263
+ return job;
264
+ }
265
+
266
+ private async runSteps(job: JobState, steps: PipelineStepDef[], context: ExecutionContext, startFromOrder = 1) {
267
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
268
+ let currentOrder = startFromOrder;
269
+
270
+ try {
271
+ await jobsRepo.update({ filterByTk: job.id, values: { status: 'running' } });
272
+
273
+ for (const step of steps) {
274
+ if (step.stepOrder < startFromOrder) continue;
275
+
276
+ context.jobId = job.id;
277
+ currentOrder = step.stepOrder;
278
+
279
+ await jobsRepo.update({ filterByTk: job.id, values: { currentStep: currentOrder } });
280
+
281
+ if (!this.evaluateCondition(step.condition, context)) {
282
+ continue; // Skip step
283
+ }
284
+
285
+ const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
286
+ let retries = step.onError === 'retry' ? step.retryCount || 0 : 0;
287
+ let success = false;
288
+ let lastError = null;
289
+
290
+ while (retries >= 0 && !success) {
291
+ try {
292
+ const fileFieldName = step.endpoint.fileFieldName || 'file';
293
+ const mappedFiles = context.files
294
+ ? context.files.map((f) => ({
295
+ ...f,
296
+ fieldName: fileFieldName,
297
+ }))
298
+ : [];
299
+
300
+ const result = await this.apiClient.call({
301
+ endpoint: step.endpoint,
302
+ body: mappedBody,
303
+ files: mappedFiles,
304
+ });
305
+
306
+ if (step.endpoint.executionMode === 'sync') {
307
+ context.stepResults[step.outputAlias || step.stepOrder.toString()] = result.data;
308
+ success = true;
309
+ } else if (step.endpoint.executionMode === 'polling') {
310
+ // Extract taskId from result based on pollTaskIdField
311
+ const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
312
+ const taskId = this.getNestedValue(result.data, taskIdField);
313
+
314
+ if (!taskId) throw new Error(`Polling taskId not found in field ${taskIdField}`);
315
+
316
+ const externalTaskIds = job.externalTaskIds || {};
317
+ externalTaskIds[step.stepOrder.toString()] = taskId;
318
+
319
+ await jobsRepo.update({
320
+ filterByTk: job.id,
321
+ values: { status: 'polling', externalTaskIds },
322
+ });
323
+
324
+ await this.jobManager.startPolling(job.id, step.endpoint, taskId);
325
+
326
+ // Halt execution. Polling callback will resume from next step.
327
+ return;
328
+ } else if (step.endpoint.executionMode === 'webhook') {
329
+ // Wait for webhook
330
+ const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
331
+ const taskId = this.getNestedValue(result.data, taskIdField);
332
+ const externalTaskIds = job.externalTaskIds || {};
333
+ externalTaskIds[step.stepOrder.toString()] = taskId;
334
+
335
+ await jobsRepo.update({
336
+ filterByTk: job.id,
337
+ values: { status: 'polling', externalTaskIds },
338
+ });
339
+
340
+ // End execution. Webhook will resume.
341
+ return;
342
+ }
343
+ } catch (err: any) {
344
+ lastError = err;
345
+ retries--;
346
+ }
347
+ }
348
+
349
+ if (!success) {
350
+ if (step.onError === 'fail') {
351
+ throw lastError || new Error(`Step ${step.name} failed`);
352
+ }
353
+ // if 'skip', we continue the loop
354
+ }
355
+ }
356
+
357
+ // If loop completes without being halted for async
358
+ await this.finishJob(job.id, context);
359
+ } catch (err: any) {
360
+ await jobsRepo.update({
361
+ filterByTk: job.id,
362
+ values: { status: 'failed', error: err.message, completedAt: new Date() },
363
+ });
364
+ }
365
+ }
366
+
367
+ async resumeFromStep(jobId: number, asyncResult: any) {
368
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
369
+ const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
370
+
371
+ const job = await jobsRepo.findOne({ filterByTk: jobId });
372
+ if (!job) throw new Error(`Job ${jobId} not found`);
373
+
374
+ const pipeline = await pipelineRepo.findOne({
375
+ filter: { id: job.pipelineId },
376
+ appends: ['steps', 'steps.endpoint'],
377
+ });
378
+
379
+ if (!pipeline) throw new Error(`Pipeline not found for job ${jobId}`);
380
+
381
+ const steps = [...(pipeline.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
382
+ const step = steps.find((s) => s.stepOrder === job.currentStep);
383
+
384
+ if (step) {
385
+ job.stepResults = job.stepResults || {};
386
+ job.stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
387
+
388
+ await jobsRepo.update({
389
+ filterByTk: jobId,
390
+ values: { stepResults: job.stepResults }, // updating stepResults json
391
+ });
392
+ }
393
+
394
+ const context: ExecutionContext = {
395
+ input: job.input,
396
+ files: [], // Files cannot easily persist across webhook unless stored in bucket. For now assume next steps use only json.
397
+ stepResults: job.stepResults,
398
+ jobId: job.id,
399
+ };
400
+
401
+ // resume from next step
402
+ this.runSteps(job, steps, context, job.currentStep + 1).catch((err) => {
403
+ this.logger.error(`Failed executing step ${job.currentStep + 1} for job ${job.id}`, err);
404
+ });
405
+ }
406
+
407
+ private async finishJob(jobId: number, context: ExecutionContext) {
408
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
409
+ const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
410
+ const job = await jobsRepo.findOne({ filterByTk: jobId });
411
+ if (!job) return;
412
+
413
+ const pipeline = await pipelineRepo.findOne({ filter: { id: job.pipelineId } });
414
+ if (!pipeline) return;
415
+
416
+ const finalResult = pipeline.outputMapping
417
+ ? this.resolveMapping(pipeline.outputMapping, context)
418
+ : context.stepResults;
419
+
420
+ await jobsRepo.update({
421
+ filterByTk: jobId,
422
+ values: {
423
+ status: 'completed',
424
+ stepResults: context.stepResults,
425
+ finalResult,
426
+ completedAt: new Date(),
427
+ },
428
+ });
429
+ }
430
+
431
+ private resolveMapping(mapping: Record<string, string>, context: ExecutionContext): Record<string, any> {
432
+ const result: Record<string, any> = {};
433
+ for (const [key, value] of Object.entries(mapping)) {
434
+ if (typeof value === 'string') {
435
+ if (value.startsWith('$input.')) {
436
+ result[key] = this.getNestedValue(context.input, value.replace('$input.', ''));
437
+ } else if (value.startsWith('$step[')) {
438
+ const match = value.match(/\$step\[(.*?)\]\.response\.(.*)/);
439
+ if (match) {
440
+ const stepKey = match[1];
441
+ const path = match[2];
442
+ const stepResult = context.stepResults[stepKey];
443
+ result[key] = this.getNestedValue(stepResult, path);
444
+ } else {
445
+ result[key] = value;
446
+ }
447
+ } else if (value === '$files') {
448
+ // special case: mapping wants files. Not mapped here as form data handles files via input.files.
449
+ } else {
450
+ result[key] = value;
451
+ }
452
+ } else {
453
+ result[key] = value; // copy raw if not string mapping
454
+ }
455
+ }
456
+ return result;
457
+ }
458
+
459
+ private evaluateCondition(condition: any, context: ExecutionContext): boolean {
460
+ if (!condition) return true;
461
+
462
+ const resolveValue = (v: any) => {
463
+ if (typeof v === 'string' && v.startsWith('$')) {
464
+ // Resolve simple $ expressions
465
+ if (v.startsWith('$step[')) {
466
+ const match = v.match(/\$step\[(.*?)\]\.response\.(.*)/);
467
+ if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
468
+ }
469
+ }
470
+ return v;
471
+ };
472
+
473
+ const fieldVal = resolveValue(condition.field);
474
+ const val = resolveValue(condition.value);
475
+
476
+ switch (condition.op) {
477
+ case 'eq':
478
+ return fieldVal === val;
479
+ case 'neq':
480
+ return fieldVal !== val;
481
+ case 'gt':
482
+ return fieldVal > val;
483
+ case 'gte':
484
+ return fieldVal >= val;
485
+ case 'lt':
486
+ return fieldVal < val;
487
+ case 'lte':
488
+ return fieldVal <= val;
489
+ case 'in':
490
+ return Array.isArray(val) && val.includes(fieldVal);
491
+ case 'contains':
492
+ return typeof fieldVal === 'string' && fieldVal.includes(String(val));
493
+ default:
494
+ return false;
495
+ }
496
+ }
497
+
498
+ private getNestedValue(obj: any, path: string): any {
499
+ if (!obj) return obj;
500
+ return path.split('.').reduce((acc, part) => acc && acc[part], obj);
501
+ }
502
+ }
@@ -0,0 +1,181 @@
1
+ import { DocumentUnderstandingService } from '../services/DocumentUnderstandingService';
2
+ import { PipelineDef, JobState } from '../types';
3
+
4
+ function cloneJson<T>(value: T): T {
5
+ if (value === undefined || value === null) {
6
+ return value;
7
+ }
8
+ return JSON.parse(JSON.stringify(value));
9
+ }
10
+
11
+ /**
12
+ * Build tool name from pipeline name.
13
+ * Convention: doc_understanding.pipeline.<sanitized_name>
14
+ */
15
+ function buildToolName(pipelineName: string): string {
16
+ const sanitized = pipelineName
17
+ .toLowerCase()
18
+ .replace(/[^a-z0-9_]/g, '_')
19
+ .replace(/_+/g, '_')
20
+ .replace(/^_|_$/g, '');
21
+ return `doc_understanding.${sanitized}`;
22
+ }
23
+
24
+ function buildSchema(pipeline: PipelineDef) {
25
+ const baseSchema =
26
+ pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0
27
+ ? cloneJson(pipeline.inputSchema)
28
+ : {
29
+ type: 'object',
30
+ properties: {
31
+ input: {
32
+ type: 'object',
33
+ description: 'Dữ liệu đầu vào cho pipeline (JSON)',
34
+ },
35
+ },
36
+ };
37
+
38
+ // Add file_urls to allow AI to pass uploaded files
39
+ if (baseSchema.type === 'object' && baseSchema.properties) {
40
+ baseSchema.properties.file_urls = {
41
+ type: 'array',
42
+ items: { type: 'string' },
43
+ description: 'Danh sách các URL của file/ảnh đính kèm trong chat',
44
+ };
45
+ }
46
+
47
+ return baseSchema;
48
+ }
49
+
50
+ function applySchemaDefaults(value: any, schema: any): any {
51
+ if (!schema || typeof schema !== 'object') {
52
+ return value;
53
+ }
54
+
55
+ if (value === undefined && Object.prototype.hasOwnProperty.call(schema, 'default')) {
56
+ return cloneJson(schema.default);
57
+ }
58
+
59
+ const isObjectSchema = schema.type === 'object' || schema.properties;
60
+ if (isObjectSchema) {
61
+ const source = value && typeof value === 'object' && !Array.isArray(value) ? { ...value } : {};
62
+
63
+ for (const [key, propertySchema] of Object.entries(schema.properties || {})) {
64
+ const currentValue = source[key];
65
+ const nextValue = applySchemaDefaults(currentValue, propertySchema);
66
+ if (nextValue !== undefined) {
67
+ source[key] = nextValue;
68
+ }
69
+ }
70
+ return source;
71
+ }
72
+
73
+ if (Array.isArray(value) && schema.items) {
74
+ return value.map((item) => applySchemaDefaults(item, schema.items));
75
+ }
76
+
77
+ return value;
78
+ }
79
+
80
+ /**
81
+ * Create a single tool definition for one pipeline.
82
+ */
83
+ function createToolForPipeline(service: DocumentUnderstandingService, pipeline: PipelineDef) {
84
+ const stepNames = (pipeline.steps || [])
85
+ .sort((a, b) => a.stepOrder - b.stepOrder)
86
+ .map((s) => s.name)
87
+ .join(' → ');
88
+
89
+ const description = [
90
+ pipeline.description || `Thực thi pipeline "${pipeline.name}".`,
91
+ stepNames ? `Steps: ${stepNames}` : '',
92
+ 'Trả về kết quả phân tích JSON hoặc Job ID nếu chạy async.',
93
+ ]
94
+ .filter(Boolean)
95
+ .join(' ');
96
+
97
+ return {
98
+ scope: 'CUSTOM' as const,
99
+ execution: 'backend' as const,
100
+ defaultPermission: 'ASK' as const,
101
+
102
+ introduction: {
103
+ title: `Document: ${pipeline.name}`,
104
+ about: pipeline.description || `Xử lý tài liệu qua pipeline "${pipeline.name}".`,
105
+ },
106
+
107
+ definition: {
108
+ name: buildToolName(pipeline.name),
109
+ description,
110
+ schema: buildSchema(pipeline),
111
+ },
112
+
113
+ invoke: async (ctx: any, args: any) => {
114
+ try {
115
+ const config = await service.getConfig();
116
+ const pollInterval = Math.max(config.pollInterval || 2000, 1000);
117
+ const maxWait = Math.min(config.pollTimeout || 30000, 30000);
118
+
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;
131
+ }
132
+ if (hasInputSchema) {
133
+ input = applySchemaDefaults(input, pipeline.inputSchema);
134
+ }
135
+
136
+ const { jobId } = await service.executePipeline(pipeline.id, input, files);
137
+ const start = Date.now();
138
+
139
+ while (Date.now() - start < maxWait) {
140
+ const job: JobState = await service.getJobStatus(jobId);
141
+ if (job.status === 'completed') {
142
+ return { status: 'completed', result: job.finalResult };
143
+ } else if (job.status === 'failed' || job.status === 'timeout') {
144
+ return { status: job.status, error: job.error };
145
+ }
146
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
147
+ }
148
+
149
+ return {
150
+ status: 'polling',
151
+ message: `Pipeline "${pipeline.name}" đang chạy, trả về job ID để theo dõi.`,
152
+ jobId,
153
+ };
154
+ } catch (err: any) {
155
+ return { error: err.message };
156
+ }
157
+ },
158
+ };
159
+ }
160
+
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
+ export function createDynamicPipelineToolsProvider(service: DocumentUnderstandingService) {
166
+ return async (register: { registerTools: (options: any) => void }) => {
167
+ try {
168
+ if (!service.isReady()) return;
169
+
170
+ const pipelines = await service.listPipelines();
171
+ const enabledPipelines = pipelines.filter((p) => p.enabled);
172
+
173
+ if (enabledPipelines.length === 0) return;
174
+
175
+ const tools = enabledPipelines.map((pipeline) => createToolForPipeline(service, pipeline));
176
+ register.registerTools(tools);
177
+ } catch {
178
+ // Silently skip — service may not be initialized yet
179
+ }
180
+ };
181
+ }