plugin-document-understanding 1.1.3 → 1.1.4

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,176 @@
1
+ import type { Context } from '@nocobase/actions';
2
+ import { existsSync, readFileSync } from 'fs';
3
+ import { DocumentUnderstandingService } from './services/DocumentUnderstandingService';
4
+ import { FileInput } from './services/ExternalApiClient';
5
+
6
+ interface LoggerLike {
7
+ warn: (...args: unknown[]) => void;
8
+ }
9
+
10
+ interface DocumentUnderstandingPluginLike {
11
+ service: DocumentUnderstandingService;
12
+ app: {
13
+ logger: LoggerLike;
14
+ };
15
+ }
16
+
17
+ interface UploadedFileLike {
18
+ path?: string;
19
+ filepath?: string;
20
+ name?: string;
21
+ originalFilename?: string;
22
+ type?: string;
23
+ mimetype?: string;
24
+ }
25
+
26
+ interface RequestWithFiles {
27
+ files?: Record<string, UploadedFileLike | UploadedFileLike[]>;
28
+ body?: {
29
+ files?: Record<string, UploadedFileLike | UploadedFileLike[]>;
30
+ };
31
+ headers: Context['request']['headers'];
32
+ }
33
+
34
+ export const defineActions = (plugin: DocumentUnderstandingPluginLike) => {
35
+ const service = plugin.service;
36
+
37
+ return {
38
+ async getConfig(ctx: Context, next: () => Promise<any>) {
39
+ ctx.body = await service.getConfig();
40
+ await next();
41
+ },
42
+
43
+ async updateConfig(ctx: Context, next: () => Promise<any>) {
44
+ const { values } = ctx.action.params;
45
+ await service.updateConfig(values);
46
+ ctx.body = await service.getConfig();
47
+ await next();
48
+ },
49
+
50
+ async listEndpoints(ctx: Context, next: () => Promise<any>) {
51
+ ctx.body = await service.listEndpoints();
52
+ await next();
53
+ },
54
+
55
+ async createEndpoint(ctx: Context, next: () => Promise<any>) {
56
+ const { values } = ctx.action.params;
57
+ ctx.body = await service.createEndpoint(values);
58
+ await next();
59
+ },
60
+
61
+ async updateEndpoint(ctx: Context, next: () => Promise<any>) {
62
+ const { filterByTk, values } = ctx.action.params;
63
+ await service.updateEndpoint(Number(filterByTk), values);
64
+ ctx.body = { message: 'ok' };
65
+ await next();
66
+ },
67
+
68
+ async deleteEndpoint(ctx: Context, next: () => Promise<any>) {
69
+ const { filterByTk } = ctx.action.params;
70
+ await service.deleteEndpoint(Number(filterByTk));
71
+ ctx.body = { message: 'ok' };
72
+ await next();
73
+ },
74
+
75
+ async listPipelines(ctx: Context, next: () => Promise<any>) {
76
+ ctx.body = await service.listPipelines();
77
+ await next();
78
+ },
79
+
80
+ async createPipeline(ctx: Context, next: () => Promise<any>) {
81
+ const { values } = ctx.action.params;
82
+ ctx.body = await service.createPipeline(values);
83
+ await next();
84
+ },
85
+
86
+ async updatePipeline(ctx: Context, next: () => Promise<any>) {
87
+ const { filterByTk, values } = ctx.action.params;
88
+ await service.updatePipeline(Number(filterByTk), values);
89
+ ctx.body = { message: 'ok' };
90
+ await next();
91
+ },
92
+
93
+ async deletePipeline(ctx: Context, next: () => Promise<any>) {
94
+ const { filterByTk } = ctx.action.params;
95
+ await service.deletePipeline(Number(filterByTk));
96
+ ctx.body = { message: 'ok' };
97
+ await next();
98
+ },
99
+
100
+ async executePipeline(ctx: Context, next: () => Promise<any>) {
101
+ const { values } = ctx.action.params;
102
+ const pipelineId = values?.pipelineId;
103
+ const input = values?.input || {};
104
+ const userId = ctx.state?.currentUser?.id;
105
+
106
+ const multipartFiles: FileInput[] = [];
107
+ const request = ctx.request as RequestWithFiles;
108
+ const filesObj = request.files || request.body?.files;
109
+ if (filesObj) {
110
+ const addFile = (key: string, file: UploadedFileLike) => {
111
+ const filePath = file.path || file.filepath;
112
+ const fileName = file.name || file.originalFilename || 'file';
113
+ const mimeType = file.type || file.mimetype || 'application/octet-stream';
114
+ if (filePath && existsSync(filePath)) {
115
+ try {
116
+ multipartFiles.push({
117
+ fieldName: key,
118
+ buffer: readFileSync(filePath),
119
+ filename: fileName,
120
+ mimeType,
121
+ });
122
+ } catch (err) {
123
+ plugin.app.logger.warn('Failed to read uploaded multipart file', err);
124
+ }
125
+ }
126
+ };
127
+
128
+ if (typeof filesObj === 'object') {
129
+ for (const [key, value] of Object.entries(filesObj)) {
130
+ if (Array.isArray(value)) {
131
+ for (const f of value) {
132
+ addFile(key, f);
133
+ }
134
+ } else {
135
+ addFile(key, value);
136
+ }
137
+ }
138
+ }
139
+ }
140
+
141
+ ctx.body = await service.executePipeline(pipelineId, input, multipartFiles, userId);
142
+ await next();
143
+ },
144
+
145
+ async getJobStatus(ctx: Context, next: () => Promise<any>) {
146
+ const { filterByTk } = ctx.action.params;
147
+ ctx.body = await service.getJobStatus(Number(filterByTk));
148
+ await next();
149
+ },
150
+
151
+ async listJobs(ctx: Context, next: () => Promise<any>) {
152
+ const { filter } = ctx.action.params;
153
+ ctx.body = await service.listJobs(filter);
154
+ await next();
155
+ },
156
+
157
+ async webhookCallback(ctx: Context, next: () => Promise<any>) {
158
+ const signature = ctx.request.headers['x-webhook-signature'] as string;
159
+ const { values } = ctx.action.params;
160
+ try {
161
+ await service.handleWebhook(values || ctx.request.body, signature);
162
+ ctx.body = { received: true };
163
+ } catch (err: any) {
164
+ plugin.app.logger.warn(`Webhook callback error: ${err.message}`);
165
+ if (err.message.includes('signature')) {
166
+ ctx.status = 401;
167
+ ctx.body = { error: err.message };
168
+ } else {
169
+ ctx.status = 400;
170
+ ctx.body = { error: err.message };
171
+ }
172
+ }
173
+ await next();
174
+ },
175
+ };
176
+ };
File without changes
@@ -0,0 +1,18 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+
3
+ export default {
4
+ name: 'doc_understanding_config',
5
+ title: 'Document Understanding Config',
6
+ // Model name can be explicitly generated by NocoBase, but we define collection fields.
7
+ fields: [
8
+ { type: 'string', name: 'baseUrl', length: 500 },
9
+ { type: 'string', name: 'authType', length: 20 }, // 'api_key' | 'bearer' | 'custom_header' | 'none'
10
+ { type: 'string', name: 'authKey', length: 500 },
11
+ { type: 'string', name: 'authHeaderName', length: 100 },
12
+ { type: 'integer', name: 'defaultTimeout', defaultValue: 30000 },
13
+ { type: 'integer', name: 'defaultRetries', defaultValue: 2 },
14
+ { type: 'integer', name: 'pollInterval', defaultValue: 5000 },
15
+ { type: 'integer', name: 'pollTimeout', defaultValue: 300000 },
16
+ { type: 'string', name: 'webhookSecret', length: 500 },
17
+ ],
18
+ } as CollectionOptions;
@@ -0,0 +1,28 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+
3
+ export default {
4
+ name: 'doc_understanding_endpoints',
5
+ title: 'Document Endpoints',
6
+ fields: [
7
+ { type: 'string', name: 'name', unique: true, length: 100 },
8
+ { type: 'string', name: 'subpath', length: 500 },
9
+ { type: 'string', name: 'method', length: 10 },
10
+ { type: 'text', name: 'description' },
11
+ { type: 'json', name: 'requestBodySchema' },
12
+ { type: 'json', name: 'responseSchema' },
13
+ { type: 'string', name: 'fileInputMode', length: 20 },
14
+ { type: 'string', name: 'fileFieldName', length: 100, defaultValue: 'file' },
15
+ { type: 'integer', name: 'maxFiles', defaultValue: 1 },
16
+ { type: 'string', name: 'executionMode', length: 20 },
17
+ { type: 'string', name: 'pollResultSubpath', length: 500 },
18
+ { type: 'string', name: 'pollTaskIdField', length: 100, defaultValue: 'task_id' },
19
+ { type: 'string', name: 'pollResultField', length: 100 },
20
+ { type: 'integer', name: 'pollInterval' },
21
+ { type: 'integer', name: 'pollTimeout' },
22
+ { type: 'string', name: 'pollStatusField', length: 100 },
23
+ { type: 'string', name: 'pollCompletedValue', length: 100, defaultValue: 'completed' },
24
+ { type: 'json', name: 'customHeaders' },
25
+ { type: 'boolean', name: 'enabled', defaultValue: true },
26
+ { type: 'integer', name: 'sortOrder', defaultValue: 0 },
27
+ ],
28
+ } as CollectionOptions;
@@ -0,0 +1,29 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+
3
+ export default {
4
+ name: 'doc_understanding_jobs',
5
+ title: 'Document Pipeline Jobs',
6
+ fields: [
7
+ {
8
+ type: 'belongsTo',
9
+ name: 'pipeline',
10
+ target: 'doc_understanding_pipelines',
11
+ foreignKey: 'pipelineId',
12
+ },
13
+ { type: 'string', name: 'status', length: 20, defaultValue: 'pending' },
14
+ { type: 'json', name: 'input' },
15
+ { type: 'integer', name: 'currentStep' },
16
+ { type: 'json', name: 'stepResults' },
17
+ { type: 'json', name: 'finalResult' },
18
+ { type: 'text', name: 'error' },
19
+ { type: 'json', name: 'externalTaskIds' },
20
+ { type: 'date', name: 'startedAt' },
21
+ { type: 'date', name: 'completedAt' },
22
+ {
23
+ type: 'belongsTo',
24
+ name: 'createdBy',
25
+ target: 'users',
26
+ foreignKey: 'createdById',
27
+ },
28
+ ],
29
+ } as CollectionOptions;
@@ -0,0 +1,27 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+
3
+ export default {
4
+ name: 'doc_understanding_pipeline_steps',
5
+ title: 'Pipeline Steps',
6
+ fields: [
7
+ {
8
+ type: 'belongsTo',
9
+ name: 'pipeline',
10
+ target: 'doc_understanding_pipelines',
11
+ foreignKey: 'pipelineId',
12
+ },
13
+ {
14
+ type: 'belongsTo',
15
+ name: 'endpoint',
16
+ target: 'doc_understanding_endpoints',
17
+ foreignKey: 'endpointId',
18
+ },
19
+ { type: 'integer', name: 'stepOrder' },
20
+ { type: 'string', name: 'name', length: 100 },
21
+ { type: 'json', name: 'inputMapping' },
22
+ { type: 'string', name: 'outputAlias', length: 100 },
23
+ { type: 'json', name: 'condition' },
24
+ { type: 'string', name: 'onError', length: 20, defaultValue: 'fail' },
25
+ { type: 'integer', name: 'retryCount', defaultValue: 0 },
26
+ ],
27
+ } as CollectionOptions;
@@ -0,0 +1,19 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+
3
+ export default {
4
+ name: 'doc_understanding_pipelines',
5
+ title: 'Document Pipelines',
6
+ fields: [
7
+ { type: 'string', name: 'name', unique: true, length: 200 },
8
+ { type: 'text', name: 'description' },
9
+ { type: 'json', name: 'inputSchema' },
10
+ { type: 'json', name: 'outputMapping' },
11
+ { type: 'boolean', name: 'enabled', defaultValue: true },
12
+ {
13
+ type: 'hasMany',
14
+ name: 'steps',
15
+ target: 'doc_understanding_pipeline_steps',
16
+ foreignKey: 'pipelineId',
17
+ },
18
+ ],
19
+ } as CollectionOptions;
@@ -0,0 +1,108 @@
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 AiPluginLike {
10
+ ai?: {
11
+ toolsManager?: {
12
+ registerDynamicTools: (provider: DynamicToolsProvider) => void;
13
+ };
14
+ };
15
+ }
16
+
17
+ const isAiPluginLike = (plugin: unknown): plugin is AiPluginLike => {
18
+ const candidate = plugin as AiPluginLike;
19
+ return typeof candidate?.ai?.toolsManager?.registerDynamicTools === 'function';
20
+ };
21
+
22
+ export class PluginDocumentUnderstandingServer extends Plugin {
23
+ public service!: DocumentUnderstandingService;
24
+
25
+ async afterAdd() {}
26
+
27
+ async beforeLoad() {}
28
+
29
+ async load() {
30
+ // 1. Import collections
31
+ await this.db.import({
32
+ directory: resolve(__dirname, 'collections'),
33
+ });
34
+
35
+ // 2. Create service
36
+ this.service = new DocumentUnderstandingService(this.app, this.db);
37
+
38
+ // Defer initialization to after app has loaded database so config exists
39
+ this.app.on('afterStart', async () => {
40
+ try {
41
+ await this.service.initialize({ recoverJobs: true });
42
+ } catch (err) {
43
+ this.app.logger.warn('Document Understanding plugin not configured yet, skip init.', err);
44
+ }
45
+ });
46
+
47
+ // 3. Register REST actions
48
+ this.registerActions();
49
+
50
+ // 4. Register AI tool (graceful)
51
+ this.registerAITools();
52
+
53
+ // 5. ACL
54
+ this.app.acl.registerSnippet({
55
+ name: `pm.${this.name}`,
56
+ actions: ['docUnderstanding:*'],
57
+ });
58
+ }
59
+
60
+ private registerActions() {
61
+ const actions = defineActions(this);
62
+
63
+ const resourceName = 'docUnderstanding';
64
+ this.app.resource({
65
+ name: resourceName,
66
+ actions: {
67
+ getConfig: actions.getConfig,
68
+ updateConfig: actions.updateConfig,
69
+ listEndpoints: actions.listEndpoints,
70
+ createEndpoint: actions.createEndpoint,
71
+ updateEndpoint: actions.updateEndpoint,
72
+ deleteEndpoint: actions.deleteEndpoint,
73
+ listPipelines: actions.listPipelines,
74
+ createPipeline: actions.createPipeline,
75
+ updatePipeline: actions.updatePipeline,
76
+ deletePipeline: actions.deletePipeline,
77
+ executePipeline: actions.executePipeline,
78
+ getJobStatus: actions.getJobStatus,
79
+ listJobs: actions.listJobs,
80
+ webhookCallback: actions.webhookCallback,
81
+ },
82
+ });
83
+ }
84
+
85
+ private registerAITools() {
86
+ try {
87
+ const aiPlugin = this.app.pm.get('@nocobase/plugin-ai');
88
+ if (!isAiPluginLike(aiPlugin)) {
89
+ this.app.logger.warn('Document Understanding: plugin-ai not available, skip AI tool registration.');
90
+ return;
91
+ }
92
+ aiPlugin.ai.toolsManager.registerDynamicTools(createDynamicPipelineToolsProvider(this.service));
93
+ this.app.logger.info('Document Understanding: Dynamic pipeline tools provider registered.');
94
+ } catch (err) {
95
+ this.app.logger.warn('Document Understanding: Failed to register AI tools, continue without it.', err);
96
+ }
97
+ }
98
+
99
+ async install() {}
100
+
101
+ async afterEnable() {}
102
+
103
+ async afterDisable() {}
104
+
105
+ async remove() {}
106
+ }
107
+
108
+ export default PluginDocumentUnderstandingServer;
@@ -0,0 +1,172 @@
1
+ import { Database } from '@nocobase/database';
2
+ import { ExternalApiClient } from './ExternalApiClient';
3
+ import { EndpointDef, JobState } from '../types';
4
+
5
+ interface LoggerLike {
6
+ warn: (...args: unknown[]) => void;
7
+ }
8
+
9
+ export class AsyncJobManager {
10
+ private db: Database;
11
+ private apiClient: ExternalApiClient;
12
+ private intervals: Map<number, NodeJS.Timeout> = new Map();
13
+ private onJobComplete: (jobId: number, result: any) => Promise<void>;
14
+ private onJobError: (jobId: number, error: string) => Promise<void>;
15
+ private logger: LoggerLike;
16
+
17
+ constructor(
18
+ db: Database,
19
+ apiClient: ExternalApiClient,
20
+ callbacks: {
21
+ onJobComplete: (jobId: number, result: any) => Promise<void>;
22
+ onJobError: (jobId: number, error: string) => Promise<void>;
23
+ },
24
+ logger: LoggerLike,
25
+ ) {
26
+ this.db = db;
27
+ this.apiClient = apiClient;
28
+ this.onJobComplete = callbacks.onJobComplete;
29
+ this.onJobError = callbacks.onJobError;
30
+ this.logger = logger;
31
+ }
32
+
33
+ async startPolling(
34
+ jobId: number,
35
+ endpoint: EndpointDef,
36
+ taskId: string,
37
+ customInterval?: number,
38
+ customTimeout?: number,
39
+ ): Promise<void> {
40
+ // Don't start duplicate polling for same job
41
+ if (this.intervals.has(jobId)) return;
42
+
43
+ const interval = customInterval || endpoint.pollInterval || 5000;
44
+ const timeout = customTimeout || endpoint.pollTimeout || 300000;
45
+ const startTime = Date.now();
46
+
47
+ const timer = setInterval(async () => {
48
+ try {
49
+ if (Date.now() - startTime > timeout) {
50
+ this.stopPolling(jobId);
51
+ await this.onJobError(jobId, 'Polling timeout exceeded');
52
+ return;
53
+ }
54
+
55
+ const pollResultSubpath = endpoint.pollResultSubpath;
56
+ if (!pollResultSubpath) {
57
+ await this.onJobError(jobId, 'Polling result subpath is not configured');
58
+ return;
59
+ }
60
+
61
+ const url = pollResultSubpath.replace('{taskId}', taskId);
62
+ const response = await this.apiClient.get(url);
63
+
64
+ // Smart completion check: use pollStatusField if configured
65
+ if (endpoint.pollStatusField) {
66
+ const statusValue = this.getNestedValue(response, endpoint.pollStatusField);
67
+ const completedValue = endpoint.pollCompletedValue || 'completed';
68
+ if (String(statusValue) === completedValue) {
69
+ const resultValue = endpoint.pollResultField
70
+ ? this.getNestedValue(response, endpoint.pollResultField)
71
+ : response;
72
+ this.stopPolling(jobId);
73
+ await this.onJobComplete(jobId, resultValue);
74
+ } else if (statusValue === 'failed' || statusValue === 'error') {
75
+ this.stopPolling(jobId);
76
+ await this.onJobError(jobId, `External task failed with status: ${statusValue}`);
77
+ }
78
+ // Otherwise still pending, continue polling
79
+ } else {
80
+ // Fallback: check if result field has non-null value
81
+ const resultValue = endpoint.pollResultField
82
+ ? this.getNestedValue(response, endpoint.pollResultField)
83
+ : response;
84
+ if (resultValue !== undefined && resultValue !== null) {
85
+ this.stopPolling(jobId);
86
+ await this.onJobComplete(jobId, resultValue);
87
+ }
88
+ }
89
+ } catch (err) {
90
+ const message = err instanceof Error ? err.message : String(err);
91
+ this.logger.warn(`Polling error for job ${jobId}: ${message}`);
92
+ }
93
+ }, interval);
94
+
95
+ this.intervals.set(jobId, timer);
96
+ }
97
+
98
+ /**
99
+ * Transition pending and running jobs to failed state during startup.
100
+ */
101
+ async cleanupStuckJobs(): Promise<void> {
102
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
103
+ const stuckJobs = await jobsRepo.find({
104
+ filter: {
105
+ status: ['pending', 'running'],
106
+ },
107
+ });
108
+
109
+ for (const job of stuckJobs) {
110
+ await jobsRepo.update({
111
+ filterByTk: job.id,
112
+ values: {
113
+ status: 'failed',
114
+ error: 'Server restarted during execution',
115
+ completedAt: new Date(),
116
+ },
117
+ });
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Recover polling jobs that were in-flight when server restarted.
123
+ * Call this during service initialization.
124
+ */
125
+ async recoverPollingJobs(): Promise<void> {
126
+ const jobsRepo = this.db.getRepository<any>('doc_understanding_jobs');
127
+ const stuckJobs = await jobsRepo.find({ filter: { status: 'polling' } });
128
+
129
+ for (const job of stuckJobs) {
130
+ if (!job.externalTaskIds) continue;
131
+
132
+ // Find the current step's endpoint and taskId
133
+ const stepKey = job.currentStep.toString();
134
+ const taskId = job.externalTaskIds[stepKey];
135
+ if (!taskId) continue;
136
+
137
+ // We need the endpoint definition for this step
138
+ const pipelineRepo = this.db.getRepository('doc_understanding_pipelines');
139
+ const pipeline = await pipelineRepo.findOne({
140
+ filter: { id: job.pipelineId },
141
+ appends: ['steps', 'steps.endpoint'],
142
+ });
143
+
144
+ if (!pipeline) continue;
145
+
146
+ const step = (pipeline as any).steps?.find((s: any) => s.stepOrder === job.currentStep);
147
+ if (!step?.endpoint || step.endpoint.executionMode !== 'polling') continue;
148
+
149
+ await this.startPolling(job.id, step.endpoint, taskId);
150
+ }
151
+ }
152
+
153
+ stopPolling(jobId: number) {
154
+ const timer = this.intervals.get(jobId);
155
+ if (timer) {
156
+ clearInterval(timer);
157
+ this.intervals.delete(jobId);
158
+ }
159
+ }
160
+
161
+ destroy() {
162
+ for (const timer of this.intervals.values()) {
163
+ clearInterval(timer);
164
+ }
165
+ this.intervals.clear();
166
+ }
167
+
168
+ private getNestedValue(obj: any, path: string): any {
169
+ if (!obj) return obj;
170
+ return path.split('.').reduce((acc, part) => acc && acc[part], obj);
171
+ }
172
+ }