plugin-document-understanding 1.1.9 → 1.1.11

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,477 +1,477 @@
1
- import { existsSync, realpathSync, readFileSync, statSync } from 'fs';
2
- import { basename, resolve, sep } from 'path';
3
- import { Database } from '@nocobase/database';
4
- import mime from 'mime-types';
5
- import { ExternalApiClient, FileInput } from './ExternalApiClient';
6
- import { AsyncJobManager } from './AsyncJobManager';
7
- import { PipelineDef, PipelineStepDef, JobState, EndpointDef } from '../types';
8
-
9
- interface LoggerLike {
10
- error: (...args: unknown[]) => void;
11
- warn?: (...args: unknown[]) => void;
12
- }
13
-
14
- interface FileReferenceInput {
15
- buffer?: Buffer;
16
- url?: string;
17
- fieldName?: string;
18
- }
19
-
20
- const UPLOAD_ROOTS = [resolve(process.cwd(), 'storage', 'uploads')];
21
-
22
- const isInsidePath = (basePath: string, targetPath: string) =>
23
- targetPath === basePath || targetPath.startsWith(`${basePath}${sep}`);
24
-
25
- export function resolveUploadFilePath(urlOrPath: string): string | null {
26
- if (!urlOrPath || urlOrPath.includes('\0')) return null;
27
-
28
- let pathname = urlOrPath.replace(/\\/g, '/').split(/[?#]/)[0];
29
- try {
30
- if (pathname.startsWith('http://') || pathname.startsWith('https://')) {
31
- pathname = new URL(pathname).pathname;
32
- }
33
- } catch {
34
- return null;
35
- }
36
-
37
- pathname = decodeURIComponent(pathname).replace(/^\/+/, '');
38
- const uploadsIndex = pathname.indexOf('uploads/');
39
- if (pathname.startsWith('storage/uploads/')) {
40
- pathname = pathname.slice('storage/uploads/'.length);
41
- } else if (pathname.startsWith('uploads/')) {
42
- pathname = pathname.slice('uploads/'.length);
43
- } else if (uploadsIndex >= 0) {
44
- pathname = pathname.slice(uploadsIndex + 'uploads/'.length);
45
- } else {
46
- return null;
47
- }
48
-
49
- const parts = pathname.split('/').filter(Boolean);
50
- if (parts.some((part) => part === '..' || part.includes('\0'))) return null;
51
-
52
- for (const root of UPLOAD_ROOTS) {
53
- const candidate = resolve(root, ...parts);
54
- const realRoot = existsSync(root) ? realpathSync(root) : root;
55
- if (!existsSync(candidate)) continue;
56
- const realCandidate = realpathSync(candidate);
57
- if (isInsidePath(realRoot, realCandidate) && statSync(realCandidate).isFile()) {
58
- return realCandidate;
59
- }
60
- }
61
-
62
- return null;
63
- }
64
-
65
- export interface ExecutionContext {
66
- input: Record<string, any>;
67
- files: FileInput[];
68
- stepResults: Record<string, any>;
69
- jobId: number;
70
- }
71
-
72
- export class PipelineExecutor {
73
- private db: Database;
74
- private apiClient: ExternalApiClient;
75
- private jobManager: AsyncJobManager;
76
- private logger: LoggerLike;
77
-
78
- constructor(db: Database, apiClient: ExternalApiClient, jobManager: AsyncJobManager, logger: LoggerLike) {
79
- this.db = db;
80
- this.apiClient = apiClient;
81
- this.jobManager = jobManager;
82
- this.logger = logger;
83
- }
84
-
85
- private async resolveFile(urlOrPath: string, fieldName = 'file'): Promise<FileInput | null> {
86
- if (!urlOrPath || typeof urlOrPath !== 'string') return null;
87
-
88
- try {
89
- const localPath = resolveUploadFilePath(urlOrPath);
90
- if (localPath) {
91
- const buffer = readFileSync(localPath);
92
- const mimeType = mime.lookup(localPath) || 'application/octet-stream';
93
-
94
- return {
95
- fieldName,
96
- buffer,
97
- filename: basename(localPath),
98
- mimeType,
99
- };
100
- }
101
-
102
- // Only files in NocoBase's upload storage are accepted. Fetching arbitrary
103
- // HTTP(S) URLs here would turn a user/AI-provided value into an SSRF primitive.
104
- if (urlOrPath.startsWith('http://') || urlOrPath.startsWith('https://')) {
105
- this.logger.warn?.('Ignoring remote file URL; use a NocoBase upload URL instead.');
106
- }
107
- } catch (err) {
108
- const message = err instanceof Error ? err.message : String(err);
109
- this.logger.warn?.(`Failed to resolve file input: ${message}`);
110
- }
111
-
112
- return null;
113
- }
114
-
115
- async execute(
116
- pipelineId: number,
117
- input: Record<string, any>,
118
- files: FileInput[] = [],
119
- userId?: number,
120
- ): Promise<JobState> {
121
- const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
122
- const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
123
-
124
- const pipeline = await pipelineRepo.findOne({
125
- filter: { id: pipelineId },
126
- appends: ['steps', 'steps.endpoint'],
127
- });
128
-
129
- if (!pipeline) throw new Error(`Pipeline ${pipelineId} not found`);
130
- if (!pipeline.enabled) throw new Error(`Pipeline ${pipelineId} is disabled`);
131
-
132
- // Create Job
133
- const job = await jobsRepo.create({
134
- values: {
135
- pipelineId,
136
- status: 'pending',
137
- input,
138
- currentStep: 1, // 1-based ordering
139
- stepResults: {},
140
- externalTaskIds: {},
141
- startedAt: new Date(),
142
- createdById: userId,
143
- },
144
- });
145
-
146
- const resolvedFiles: FileInput[] = [];
147
-
148
- const tryAddFile = async (urlOrPath: string, fieldName = 'file') => {
149
- const resolved = await this.resolveFile(urlOrPath, fieldName);
150
- if (resolved) {
151
- resolvedFiles.push(resolved);
152
- }
153
- };
154
-
155
- // 1. Process files argument
156
- if (Array.isArray(files)) {
157
- for (const f of files) {
158
- if (f && typeof f === 'object') {
159
- const fileRef = f as FileReferenceInput;
160
- if (fileRef.buffer) {
161
- resolvedFiles.push(f);
162
- } else if (fileRef.url) {
163
- await tryAddFile(fileRef.url, fileRef.fieldName || 'file');
164
- }
165
- }
166
- }
167
- }
168
-
169
- // 2. Scan input for common file URL keys
170
- const urlFields = ['file_url', 'file_urls', 'file', 'files'];
171
- for (const key of urlFields) {
172
- const val = input[key];
173
- if (!val) continue;
174
-
175
- if (typeof val === 'string') {
176
- if (
177
- val.startsWith('http://') ||
178
- val.startsWith('https://') ||
179
- val.startsWith('/') ||
180
- val.startsWith('storage/')
181
- ) {
182
- await tryAddFile(val, 'file');
183
- } else if (val.includes(',')) {
184
- const urls = val.split(',').map((s) => s.trim());
185
- for (const u of urls) {
186
- if (u.startsWith('http://') || u.startsWith('https://') || u.startsWith('/') || u.startsWith('storage/')) {
187
- await tryAddFile(u, 'file');
188
- }
189
- }
190
- }
191
- } else if (Array.isArray(val)) {
192
- for (const item of val) {
193
- if (typeof item === 'string') {
194
- if (
195
- item.startsWith('http://') ||
196
- item.startsWith('https://') ||
197
- item.startsWith('/') ||
198
- item.startsWith('storage/')
199
- ) {
200
- await tryAddFile(item, 'file');
201
- }
202
- } else if (item && typeof item === 'object' && item.url) {
203
- await tryAddFile(item.url, 'file');
204
- }
205
- }
206
- } else if (val && typeof val === 'object' && val.url) {
207
- await tryAddFile(val.url, 'file');
208
- }
209
- }
210
-
211
- if (resolvedFiles.length === 0 && files && files.length > 0) {
212
- for (const f of files) {
213
- if ((f as FileReferenceInput).buffer) {
214
- resolvedFiles.push(f);
215
- }
216
- }
217
- }
218
-
219
- const context: ExecutionContext = {
220
- input,
221
- files: resolvedFiles,
222
- stepResults: {},
223
- jobId: job.id,
224
- };
225
-
226
- // Sorting steps by order
227
- const steps = [...(pipeline.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
228
-
229
- // Run steps (Synchronous part)
230
- this.runSteps(job, steps, context).catch((err) => {
231
- this.logger.error(`Background pipeline error for job ${job.id}`, err);
232
- });
233
-
234
- return job;
235
- }
236
-
237
- private async runSteps(job: JobState, steps: PipelineStepDef[], context: ExecutionContext, startFromOrder = 1) {
238
- const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
239
- let currentOrder = startFromOrder;
240
-
241
- try {
242
- await jobsRepo.update({ filterByTk: job.id, values: { status: 'running' } });
243
-
244
- for (const step of steps) {
245
- if (step.stepOrder < startFromOrder) continue;
246
-
247
- context.jobId = job.id;
248
- currentOrder = step.stepOrder;
249
-
250
- await jobsRepo.update({ filterByTk: job.id, values: { currentStep: currentOrder } });
251
-
252
- if (!this.evaluateCondition(step.condition, context)) {
253
- continue; // Skip step
254
- }
255
-
256
- if (!step.endpoint?.enabled) {
257
- throw new Error(`Endpoint for step ${step.name} is disabled`);
258
- }
259
-
260
- const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
261
- let retries = step.onError === 'retry' ? step.retryCount || 0 : 0;
262
- let success = false;
263
- let lastError = null;
264
-
265
- while (retries >= 0 && !success) {
266
- try {
267
- const fileFieldName = step.endpoint.fileFieldName || 'file';
268
- const mappedFiles = context.files
269
- ? context.files.map((f) => ({
270
- ...f,
271
- fieldName: fileFieldName,
272
- }))
273
- : [];
274
-
275
- const result = await this.apiClient.call({
276
- endpoint: step.endpoint,
277
- body: mappedBody,
278
- files: mappedFiles,
279
- });
280
-
281
- if (step.endpoint.executionMode === 'sync') {
282
- context.stepResults[step.outputAlias || step.stepOrder.toString()] = result.data;
283
- success = true;
284
- } else if (step.endpoint.executionMode === 'polling') {
285
- // Extract taskId from result based on pollTaskIdField
286
- const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
287
- const taskId = this.getNestedValue(result.data, taskIdField);
288
-
289
- if (!taskId) throw new Error(`Polling taskId not found in field ${taskIdField}`);
290
-
291
- const externalTaskIds = job.externalTaskIds || {};
292
- externalTaskIds[step.stepOrder.toString()] = taskId;
293
-
294
- await jobsRepo.update({
295
- filterByTk: job.id,
296
- values: { status: 'polling', externalTaskIds },
297
- });
298
-
299
- await this.jobManager.startPolling(job.id, step.endpoint, taskId);
300
-
301
- // Halt execution. Polling callback will resume from next step.
302
- return;
303
- } else if (step.endpoint.executionMode === 'webhook') {
304
- // Wait for webhook
305
- const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
306
- const taskId = this.getNestedValue(result.data, taskIdField);
307
- const externalTaskIds = job.externalTaskIds || {};
308
- externalTaskIds[step.stepOrder.toString()] = taskId;
309
-
310
- await jobsRepo.update({
311
- filterByTk: job.id,
312
- values: { status: 'polling', externalTaskIds },
313
- });
314
-
315
- // End execution. Webhook will resume.
316
- return;
317
- }
318
- } catch (err: any) {
319
- lastError = err;
320
- retries--;
321
- }
322
- }
323
-
324
- if (!success) {
325
- if (step.onError === 'fail') {
326
- throw lastError || new Error(`Step ${step.name} failed`);
327
- }
328
- // if 'skip', we continue the loop
329
- }
330
- }
331
-
332
- // If loop completes without being halted for async
333
- await this.finishJob(job.id, context);
334
- } catch (err: any) {
335
- await jobsRepo.update({
336
- filterByTk: job.id,
337
- values: { status: 'failed', error: err.message, completedAt: new Date() },
338
- });
339
- }
340
- }
341
-
342
- async resumeFromStep(jobId: number, asyncResult: any) {
343
- const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
344
- const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
345
-
346
- const job = await jobsRepo.findOne({ filterByTk: jobId });
347
- if (!job) throw new Error(`Job ${jobId} not found`);
348
-
349
- const pipeline = await pipelineRepo.findOne({
350
- filter: { id: job.pipelineId },
351
- appends: ['steps', 'steps.endpoint'],
352
- });
353
-
354
- if (!pipeline) throw new Error(`Pipeline not found for job ${jobId}`);
355
-
356
- const steps = [...(pipeline.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
357
- const step = steps.find((s) => s.stepOrder === job.currentStep);
358
-
359
- if (step) {
360
- job.stepResults = job.stepResults || {};
361
- job.stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
362
-
363
- await jobsRepo.update({
364
- filterByTk: jobId,
365
- values: { stepResults: job.stepResults }, // updating stepResults json
366
- });
367
- }
368
-
369
- const context: ExecutionContext = {
370
- input: job.input,
371
- files: [], // Files cannot easily persist across webhook unless stored in bucket. For now assume next steps use only json.
372
- stepResults: job.stepResults,
373
- jobId: job.id,
374
- };
375
-
376
- // resume from next step
377
- this.runSteps(job, steps, context, job.currentStep + 1).catch((err) => {
378
- this.logger.error(`Failed executing step ${job.currentStep + 1} for job ${job.id}`, err);
379
- });
380
- }
381
-
382
- private async finishJob(jobId: number, context: ExecutionContext) {
383
- const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
384
- const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
385
- const job = await jobsRepo.findOne({ filterByTk: jobId });
386
- if (!job) return;
387
-
388
- const pipeline = await pipelineRepo.findOne({ filter: { id: job.pipelineId } });
389
- if (!pipeline) return;
390
-
391
- const finalResult = pipeline.outputMapping
392
- ? this.resolveMapping(pipeline.outputMapping, context)
393
- : context.stepResults;
394
-
395
- await jobsRepo.update({
396
- filterByTk: jobId,
397
- values: {
398
- status: 'completed',
399
- stepResults: context.stepResults,
400
- finalResult,
401
- completedAt: new Date(),
402
- },
403
- });
404
- }
405
-
406
- private resolveMapping(mapping: Record<string, string>, context: ExecutionContext): Record<string, any> {
407
- const result: Record<string, any> = {};
408
- for (const [key, value] of Object.entries(mapping)) {
409
- if (typeof value === 'string') {
410
- if (value.startsWith('$input.')) {
411
- result[key] = this.getNestedValue(context.input, value.replace('$input.', ''));
412
- } else if (value.startsWith('$step[')) {
413
- const match = value.match(/\$step\[(.*?)\]\.response\.(.*)/);
414
- if (match) {
415
- const stepKey = match[1];
416
- const path = match[2];
417
- const stepResult = context.stepResults[stepKey];
418
- result[key] = this.getNestedValue(stepResult, path);
419
- } else {
420
- result[key] = value;
421
- }
422
- } else if (value === '$files') {
423
- // special case: mapping wants files. Not mapped here as form data handles files via input.files.
424
- } else {
425
- result[key] = value;
426
- }
427
- } else {
428
- result[key] = value; // copy raw if not string mapping
429
- }
430
- }
431
- return result;
432
- }
433
-
434
- private evaluateCondition(condition: any, context: ExecutionContext): boolean {
435
- if (!condition) return true;
436
-
437
- const resolveValue = (v: any) => {
438
- if (typeof v === 'string' && v.startsWith('$')) {
439
- // Resolve simple $ expressions
440
- if (v.startsWith('$step[')) {
441
- const match = v.match(/\$step\[(.*?)\]\.response\.(.*)/);
442
- if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
443
- }
444
- }
445
- return v;
446
- };
447
-
448
- const fieldVal = resolveValue(condition.field);
449
- const val = resolveValue(condition.value);
450
-
451
- switch (condition.op) {
452
- case 'eq':
453
- return fieldVal === val;
454
- case 'neq':
455
- return fieldVal !== val;
456
- case 'gt':
457
- return fieldVal > val;
458
- case 'gte':
459
- return fieldVal >= val;
460
- case 'lt':
461
- return fieldVal < val;
462
- case 'lte':
463
- return fieldVal <= val;
464
- case 'in':
465
- return Array.isArray(val) && val.includes(fieldVal);
466
- case 'contains':
467
- return typeof fieldVal === 'string' && fieldVal.includes(String(val));
468
- default:
469
- return false;
470
- }
471
- }
472
-
473
- private getNestedValue(obj: any, path: string): any {
474
- if (!obj) return obj;
475
- return path.split('.').reduce((acc, part) => acc && acc[part], obj);
476
- }
477
- }
1
+ import { existsSync, realpathSync, readFileSync, statSync } from 'fs';
2
+ import { basename, resolve, sep } from 'path';
3
+ import { Database } from '@nocobase/database';
4
+ import mime from 'mime-types';
5
+ import { ExternalApiClient, FileInput } from './ExternalApiClient';
6
+ import { AsyncJobManager } from './AsyncJobManager';
7
+ import { PipelineDef, PipelineStepDef, JobState, EndpointDef } from '../types';
8
+
9
+ interface LoggerLike {
10
+ error: (...args: unknown[]) => void;
11
+ warn?: (...args: unknown[]) => void;
12
+ }
13
+
14
+ interface FileReferenceInput {
15
+ buffer?: Buffer;
16
+ url?: string;
17
+ fieldName?: string;
18
+ }
19
+
20
+ const UPLOAD_ROOTS = [resolve(process.cwd(), 'storage', 'uploads')];
21
+
22
+ const isInsidePath = (basePath: string, targetPath: string) =>
23
+ targetPath === basePath || targetPath.startsWith(`${basePath}${sep}`);
24
+
25
+ export function resolveUploadFilePath(urlOrPath: string): string | null {
26
+ if (!urlOrPath || urlOrPath.includes('\0')) return null;
27
+
28
+ let pathname = urlOrPath.replace(/\\/g, '/').split(/[?#]/)[0];
29
+ try {
30
+ if (pathname.startsWith('http://') || pathname.startsWith('https://')) {
31
+ pathname = new URL(pathname).pathname;
32
+ }
33
+ } catch {
34
+ return null;
35
+ }
36
+
37
+ pathname = decodeURIComponent(pathname).replace(/^\/+/, '');
38
+ const uploadsIndex = pathname.indexOf('uploads/');
39
+ if (pathname.startsWith('storage/uploads/')) {
40
+ pathname = pathname.slice('storage/uploads/'.length);
41
+ } else if (pathname.startsWith('uploads/')) {
42
+ pathname = pathname.slice('uploads/'.length);
43
+ } else if (uploadsIndex >= 0) {
44
+ pathname = pathname.slice(uploadsIndex + 'uploads/'.length);
45
+ } else {
46
+ return null;
47
+ }
48
+
49
+ const parts = pathname.split('/').filter(Boolean);
50
+ if (parts.some((part) => part === '..' || part.includes('\0'))) return null;
51
+
52
+ for (const root of UPLOAD_ROOTS) {
53
+ const candidate = resolve(root, ...parts);
54
+ const realRoot = existsSync(root) ? realpathSync(root) : root;
55
+ if (!existsSync(candidate)) continue;
56
+ const realCandidate = realpathSync(candidate);
57
+ if (isInsidePath(realRoot, realCandidate) && statSync(realCandidate).isFile()) {
58
+ return realCandidate;
59
+ }
60
+ }
61
+
62
+ return null;
63
+ }
64
+
65
+ export interface ExecutionContext {
66
+ input: Record<string, any>;
67
+ files: FileInput[];
68
+ stepResults: Record<string, any>;
69
+ jobId: number;
70
+ }
71
+
72
+ export class PipelineExecutor {
73
+ private db: Database;
74
+ private apiClient: ExternalApiClient;
75
+ private jobManager: AsyncJobManager;
76
+ private logger: LoggerLike;
77
+
78
+ constructor(db: Database, apiClient: ExternalApiClient, jobManager: AsyncJobManager, logger: LoggerLike) {
79
+ this.db = db;
80
+ this.apiClient = apiClient;
81
+ this.jobManager = jobManager;
82
+ this.logger = logger;
83
+ }
84
+
85
+ private async resolveFile(urlOrPath: string, fieldName = 'file'): Promise<FileInput | null> {
86
+ if (!urlOrPath || typeof urlOrPath !== 'string') return null;
87
+
88
+ try {
89
+ const localPath = resolveUploadFilePath(urlOrPath);
90
+ if (localPath) {
91
+ const buffer = readFileSync(localPath);
92
+ const mimeType = mime.lookup(localPath) || 'application/octet-stream';
93
+
94
+ return {
95
+ fieldName,
96
+ buffer,
97
+ filename: basename(localPath),
98
+ mimeType,
99
+ };
100
+ }
101
+
102
+ // Only files in NocoBase's upload storage are accepted. Fetching arbitrary
103
+ // HTTP(S) URLs here would turn a user/AI-provided value into an SSRF primitive.
104
+ if (urlOrPath.startsWith('http://') || urlOrPath.startsWith('https://')) {
105
+ this.logger.warn?.('Ignoring remote file URL; use a NocoBase upload URL instead.');
106
+ }
107
+ } catch (err) {
108
+ const message = err instanceof Error ? err.message : String(err);
109
+ this.logger.warn?.(`Failed to resolve file input: ${message}`);
110
+ }
111
+
112
+ return null;
113
+ }
114
+
115
+ async execute(
116
+ pipelineId: number,
117
+ input: Record<string, any>,
118
+ files: FileInput[] = [],
119
+ userId?: number,
120
+ ): Promise<JobState> {
121
+ const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
122
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
123
+
124
+ const pipeline = await pipelineRepo.findOne({
125
+ filter: { id: pipelineId },
126
+ appends: ['steps', 'steps.endpoint'],
127
+ });
128
+
129
+ if (!pipeline) throw new Error(`Pipeline ${pipelineId} not found`);
130
+ if (!pipeline.enabled) throw new Error(`Pipeline ${pipelineId} is disabled`);
131
+
132
+ // Create Job
133
+ const job = await jobsRepo.create({
134
+ values: {
135
+ pipelineId,
136
+ status: 'pending',
137
+ input,
138
+ currentStep: 1, // 1-based ordering
139
+ stepResults: {},
140
+ externalTaskIds: {},
141
+ startedAt: new Date(),
142
+ createdById: userId,
143
+ },
144
+ });
145
+
146
+ const resolvedFiles: FileInput[] = [];
147
+
148
+ const tryAddFile = async (urlOrPath: string, fieldName = 'file') => {
149
+ const resolved = await this.resolveFile(urlOrPath, fieldName);
150
+ if (resolved) {
151
+ resolvedFiles.push(resolved);
152
+ }
153
+ };
154
+
155
+ // 1. Process files argument
156
+ if (Array.isArray(files)) {
157
+ for (const f of files) {
158
+ if (f && typeof f === 'object') {
159
+ const fileRef = f as FileReferenceInput;
160
+ if (fileRef.buffer) {
161
+ resolvedFiles.push(f);
162
+ } else if (fileRef.url) {
163
+ await tryAddFile(fileRef.url, fileRef.fieldName || 'file');
164
+ }
165
+ }
166
+ }
167
+ }
168
+
169
+ // 2. Scan input for common file URL keys
170
+ const urlFields = ['file_url', 'file_urls', 'file', 'files'];
171
+ for (const key of urlFields) {
172
+ const val = input[key];
173
+ if (!val) continue;
174
+
175
+ if (typeof val === 'string') {
176
+ if (
177
+ val.startsWith('http://') ||
178
+ val.startsWith('https://') ||
179
+ val.startsWith('/') ||
180
+ val.startsWith('storage/')
181
+ ) {
182
+ await tryAddFile(val, 'file');
183
+ } else if (val.includes(',')) {
184
+ const urls = val.split(',').map((s) => s.trim());
185
+ for (const u of urls) {
186
+ if (u.startsWith('http://') || u.startsWith('https://') || u.startsWith('/') || u.startsWith('storage/')) {
187
+ await tryAddFile(u, 'file');
188
+ }
189
+ }
190
+ }
191
+ } else if (Array.isArray(val)) {
192
+ for (const item of val) {
193
+ if (typeof item === 'string') {
194
+ if (
195
+ item.startsWith('http://') ||
196
+ item.startsWith('https://') ||
197
+ item.startsWith('/') ||
198
+ item.startsWith('storage/')
199
+ ) {
200
+ await tryAddFile(item, 'file');
201
+ }
202
+ } else if (item && typeof item === 'object' && item.url) {
203
+ await tryAddFile(item.url, 'file');
204
+ }
205
+ }
206
+ } else if (val && typeof val === 'object' && val.url) {
207
+ await tryAddFile(val.url, 'file');
208
+ }
209
+ }
210
+
211
+ if (resolvedFiles.length === 0 && files && files.length > 0) {
212
+ for (const f of files) {
213
+ if ((f as FileReferenceInput).buffer) {
214
+ resolvedFiles.push(f);
215
+ }
216
+ }
217
+ }
218
+
219
+ const context: ExecutionContext = {
220
+ input,
221
+ files: resolvedFiles,
222
+ stepResults: {},
223
+ jobId: job.id,
224
+ };
225
+
226
+ // Sorting steps by order
227
+ const steps = [...(pipeline.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
228
+
229
+ // Run steps (Synchronous part)
230
+ this.runSteps(job, steps, context).catch((err) => {
231
+ this.logger.error(`Background pipeline error for job ${job.id}`, err);
232
+ });
233
+
234
+ return job;
235
+ }
236
+
237
+ private async runSteps(job: JobState, steps: PipelineStepDef[], context: ExecutionContext, startFromOrder = 1) {
238
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
239
+ let currentOrder = startFromOrder;
240
+
241
+ try {
242
+ await jobsRepo.update({ filterByTk: job.id, values: { status: 'running' } });
243
+
244
+ for (const step of steps) {
245
+ if (step.stepOrder < startFromOrder) continue;
246
+
247
+ context.jobId = job.id;
248
+ currentOrder = step.stepOrder;
249
+
250
+ await jobsRepo.update({ filterByTk: job.id, values: { currentStep: currentOrder } });
251
+
252
+ if (!this.evaluateCondition(step.condition, context)) {
253
+ continue; // Skip step
254
+ }
255
+
256
+ if (!step.endpoint?.enabled) {
257
+ throw new Error(`Endpoint for step ${step.name} is disabled`);
258
+ }
259
+
260
+ const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
261
+ let retries = step.onError === 'retry' ? step.retryCount || 0 : 0;
262
+ let success = false;
263
+ let lastError = null;
264
+
265
+ while (retries >= 0 && !success) {
266
+ try {
267
+ const fileFieldName = step.endpoint.fileFieldName || 'file';
268
+ const mappedFiles = context.files
269
+ ? context.files.map((f) => ({
270
+ ...f,
271
+ fieldName: fileFieldName,
272
+ }))
273
+ : [];
274
+
275
+ const result = await this.apiClient.call({
276
+ endpoint: step.endpoint,
277
+ body: mappedBody,
278
+ files: mappedFiles,
279
+ });
280
+
281
+ if (step.endpoint.executionMode === 'sync') {
282
+ context.stepResults[step.outputAlias || step.stepOrder.toString()] = result.data;
283
+ success = true;
284
+ } else if (step.endpoint.executionMode === 'polling') {
285
+ // Extract taskId from result based on pollTaskIdField
286
+ const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
287
+ const taskId = this.getNestedValue(result.data, taskIdField);
288
+
289
+ if (!taskId) throw new Error(`Polling taskId not found in field ${taskIdField}`);
290
+
291
+ const externalTaskIds = job.externalTaskIds || {};
292
+ externalTaskIds[step.stepOrder.toString()] = taskId;
293
+
294
+ await jobsRepo.update({
295
+ filterByTk: job.id,
296
+ values: { status: 'polling', externalTaskIds },
297
+ });
298
+
299
+ await this.jobManager.startPolling(job.id, step.endpoint, taskId);
300
+
301
+ // Halt execution. Polling callback will resume from next step.
302
+ return;
303
+ } else if (step.endpoint.executionMode === 'webhook') {
304
+ // Wait for webhook
305
+ const taskIdField = step.endpoint.pollTaskIdField || 'task_id';
306
+ const taskId = this.getNestedValue(result.data, taskIdField);
307
+ const externalTaskIds = job.externalTaskIds || {};
308
+ externalTaskIds[step.stepOrder.toString()] = taskId;
309
+
310
+ await jobsRepo.update({
311
+ filterByTk: job.id,
312
+ values: { status: 'polling', externalTaskIds },
313
+ });
314
+
315
+ // End execution. Webhook will resume.
316
+ return;
317
+ }
318
+ } catch (err: any) {
319
+ lastError = err;
320
+ retries--;
321
+ }
322
+ }
323
+
324
+ if (!success) {
325
+ if (step.onError === 'fail') {
326
+ throw lastError || new Error(`Step ${step.name} failed`);
327
+ }
328
+ // if 'skip', we continue the loop
329
+ }
330
+ }
331
+
332
+ // If loop completes without being halted for async
333
+ await this.finishJob(job.id, context);
334
+ } catch (err: any) {
335
+ await jobsRepo.update({
336
+ filterByTk: job.id,
337
+ values: { status: 'failed', error: err.message, completedAt: new Date() },
338
+ });
339
+ }
340
+ }
341
+
342
+ async resumeFromStep(jobId: number, asyncResult: any) {
343
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
344
+ const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
345
+
346
+ const job = await jobsRepo.findOne({ filterByTk: jobId });
347
+ if (!job) throw new Error(`Job ${jobId} not found`);
348
+
349
+ const pipeline = await pipelineRepo.findOne({
350
+ filter: { id: job.pipelineId },
351
+ appends: ['steps', 'steps.endpoint'],
352
+ });
353
+
354
+ if (!pipeline) throw new Error(`Pipeline not found for job ${jobId}`);
355
+
356
+ const steps = [...(pipeline.steps || [])].sort((a, b) => a.stepOrder - b.stepOrder);
357
+ const step = steps.find((s) => s.stepOrder === job.currentStep);
358
+
359
+ if (step) {
360
+ job.stepResults = job.stepResults || {};
361
+ job.stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
362
+
363
+ await jobsRepo.update({
364
+ filterByTk: jobId,
365
+ values: { stepResults: job.stepResults }, // updating stepResults json
366
+ });
367
+ }
368
+
369
+ const context: ExecutionContext = {
370
+ input: job.input,
371
+ files: [], // Files cannot easily persist across webhook unless stored in bucket. For now assume next steps use only json.
372
+ stepResults: job.stepResults,
373
+ jobId: job.id,
374
+ };
375
+
376
+ // resume from next step
377
+ this.runSteps(job, steps, context, job.currentStep + 1).catch((err) => {
378
+ this.logger.error(`Failed executing step ${job.currentStep + 1} for job ${job.id}`, err);
379
+ });
380
+ }
381
+
382
+ private async finishJob(jobId: number, context: ExecutionContext) {
383
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
384
+ const pipelineRepo = this.db.getRepository<any>('doc_understanding_pipelines');
385
+ const job = await jobsRepo.findOne({ filterByTk: jobId });
386
+ if (!job) return;
387
+
388
+ const pipeline = await pipelineRepo.findOne({ filter: { id: job.pipelineId } });
389
+ if (!pipeline) return;
390
+
391
+ const finalResult = pipeline.outputMapping
392
+ ? this.resolveMapping(pipeline.outputMapping, context)
393
+ : context.stepResults;
394
+
395
+ await jobsRepo.update({
396
+ filterByTk: jobId,
397
+ values: {
398
+ status: 'completed',
399
+ stepResults: context.stepResults,
400
+ finalResult,
401
+ completedAt: new Date(),
402
+ },
403
+ });
404
+ }
405
+
406
+ private resolveMapping(mapping: Record<string, string>, context: ExecutionContext): Record<string, any> {
407
+ const result: Record<string, any> = {};
408
+ for (const [key, value] of Object.entries(mapping)) {
409
+ if (typeof value === 'string') {
410
+ if (value.startsWith('$input.')) {
411
+ result[key] = this.getNestedValue(context.input, value.replace('$input.', ''));
412
+ } else if (value.startsWith('$step[')) {
413
+ const match = value.match(/\$step\[(.*?)\]\.response\.(.*)/);
414
+ if (match) {
415
+ const stepKey = match[1];
416
+ const path = match[2];
417
+ const stepResult = context.stepResults[stepKey];
418
+ result[key] = this.getNestedValue(stepResult, path);
419
+ } else {
420
+ result[key] = value;
421
+ }
422
+ } else if (value === '$files') {
423
+ // special case: mapping wants files. Not mapped here as form data handles files via input.files.
424
+ } else {
425
+ result[key] = value;
426
+ }
427
+ } else {
428
+ result[key] = value; // copy raw if not string mapping
429
+ }
430
+ }
431
+ return result;
432
+ }
433
+
434
+ private evaluateCondition(condition: any, context: ExecutionContext): boolean {
435
+ if (!condition) return true;
436
+
437
+ const resolveValue = (v: any) => {
438
+ if (typeof v === 'string' && v.startsWith('$')) {
439
+ // Resolve simple $ expressions
440
+ if (v.startsWith('$step[')) {
441
+ const match = v.match(/\$step\[(.*?)\]\.response\.(.*)/);
442
+ if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
443
+ }
444
+ }
445
+ return v;
446
+ };
447
+
448
+ const fieldVal = resolveValue(condition.field);
449
+ const val = resolveValue(condition.value);
450
+
451
+ switch (condition.op) {
452
+ case 'eq':
453
+ return fieldVal === val;
454
+ case 'neq':
455
+ return fieldVal !== val;
456
+ case 'gt':
457
+ return fieldVal > val;
458
+ case 'gte':
459
+ return fieldVal >= val;
460
+ case 'lt':
461
+ return fieldVal < val;
462
+ case 'lte':
463
+ return fieldVal <= val;
464
+ case 'in':
465
+ return Array.isArray(val) && val.includes(fieldVal);
466
+ case 'contains':
467
+ return typeof fieldVal === 'string' && fieldVal.includes(String(val));
468
+ default:
469
+ return false;
470
+ }
471
+ }
472
+
473
+ private getNestedValue(obj: any, path: string): any {
474
+ if (!obj) return obj;
475
+ return path.split('.').reduce((acc, part) => acc && acc[part], obj);
476
+ }
477
+ }