plugin-document-understanding 1.0.2 → 1.1.1

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 (34) hide show
  1. package/README.md +16 -366
  2. package/dist/client/components/EndpointsTab.d.ts +2 -0
  3. package/dist/client/components/JobsTab.d.ts +2 -0
  4. package/dist/client/components/PipelinesTab.d.ts +2 -0
  5. package/dist/client/components/PluginSettings.d.ts +2 -0
  6. package/dist/client/components/ServiceConfigTab.d.ts +2 -0
  7. package/dist/client/index.d.ts +1 -0
  8. package/dist/client/index.js +1 -1
  9. package/dist/client/locale.d.ts +10 -0
  10. package/dist/client/models/index.d.ts +11 -0
  11. package/dist/client/plugin.d.ts +6 -0
  12. package/dist/externalVersion.js +6 -6
  13. package/dist/index.d.ts +2 -0
  14. package/dist/locale/en-US.json +121 -121
  15. package/dist/locale/vi-VN.json +121 -121
  16. package/dist/server/actions.d.ts +17 -0
  17. package/dist/server/collections/config.d.ts +3 -0
  18. package/dist/server/collections/endpoints.d.ts +3 -0
  19. package/dist/server/collections/jobs.d.ts +3 -0
  20. package/dist/server/collections/pipeline-steps.d.ts +3 -0
  21. package/dist/server/collections/pipelines.d.ts +3 -0
  22. package/dist/server/index.d.ts +1 -0
  23. package/dist/server/plugin.d.ts +18 -0
  24. package/dist/server/plugin.js +3 -1
  25. package/dist/server/services/AsyncJobManager.d.ts +23 -0
  26. package/dist/server/services/DocumentUnderstandingService.d.ts +35 -0
  27. package/dist/server/services/DocumentUnderstandingService.js +37 -5
  28. package/dist/server/services/ExternalApiClient.d.ts +28 -0
  29. package/dist/server/services/ExternalApiClient.js +20 -3
  30. package/dist/server/services/PipelineExecutor.d.ts +23 -0
  31. package/dist/server/tools/document-understanding-tool.d.ts +8 -0
  32. package/dist/server/tools/document-understanding-tool.js +37 -3
  33. package/dist/server/types.d.ts +68 -0
  34. package/package.json +1 -1
@@ -1,121 +1,121 @@
1
- {
2
- "Document Understanding": "Hiểu Tài Liệu",
3
- "Document Understanding - Pipeline Orchestrator": "Hiểu Tài Liệu - Bộ Điều Phối Pipeline",
4
- "Service Connection": "Kết nối dịch vụ",
5
- "Service Config": "Cấu hình dịch vụ",
6
- "Endpoints": "Endpoints",
7
- "Pipelines": "Pipelines",
8
- "Jobs history": "Lịch sử công việc",
9
- "Base URL": "URL gốc",
10
- "Authentication Type": "Loại xác thực",
11
- "Auth Type": "Loại xác thực",
12
- "None": "Không",
13
- "API Key": "Khóa API",
14
- "Bearer Token": "Token Bearer",
15
- "Custom Header": "Header tùy chỉnh",
16
- "Custom Header Name": "Tên Header tùy chỉnh",
17
- "API Key / Token": "Khóa API / Token",
18
- "Request Timeout (ms)": "Timeout request (ms)",
19
- "Default Retries": "Số lần thử lại mặc định",
20
- "Poll Interval (ms)": "Khoảng thời gian poll (ms)",
21
- "Poll Timeout (ms)": "Timeout poll (ms)",
22
- "Webhook Secret": "Mã bí mật Webhook",
23
- "Save Configuration": "Lưu cấu hình",
24
- "Configuration saved successfully": "Đã lưu cấu hình thành công",
25
- "Failed to save config": "Lưu cấu hình thất bại",
26
- "Add Endpoint": "Thêm Endpoint",
27
- "Edit Endpoint": "Sửa Endpoint",
28
- "Basic": "Cơ bản",
29
- "File Input": "File đầu vào",
30
- "Async Config": "Cấu hình bất đồng bộ",
31
- "Schema": "Schema",
32
- "Custom Headers": "Headers tùy chỉnh",
33
- "Unique Name": "Tên duy nhất",
34
- "Subpath": "Đường dẫn con",
35
- "HTTP Method": "Phương thức HTTP",
36
- "Execution Mode": "Chế độ thực thi",
37
- "Synchronous": "Đồng bộ",
38
- "Polling": "Polling",
39
- "Webhook": "Webhook",
40
- "File Input Mode": "Chế độ nhập file",
41
- "Multipart Upload": "Upload Multipart",
42
- "Base64 in JSON": "Base64 trong JSON",
43
- "Max Files": "Số file tối đa",
44
- "Task ID Field": "Trường Task ID",
45
- "Poll Result Subpath": "Đường dẫn poll kết quả",
46
- "Result Field": "Trường kết quả",
47
- "Status Field": "Trường trạng thái",
48
- "Completed Value": "Giá trị hoàn thành",
49
- "Poll Task ID Field": "Trường Task ID khi poll",
50
- "Poll Result Field": "Trường kết quả khi poll",
51
- "Poll Status Field": "Trường trạng thái khi poll",
52
- "Poll Completed Value": "Giá trị hoàn thành khi poll",
53
- "Request Body Schema (JSON Schema)": "Schema body request (JSON Schema)",
54
- "Response Schema (JSON Schema)": "Schema response (JSON Schema)",
55
- "Additional Headers": "Headers bổ sung",
56
- "Add Header": "Thêm Header",
57
- "Enabled": "Bật",
58
- "Action": "Hành động",
59
- "Edit": "Sửa",
60
- "Delete": "Xóa",
61
- "Deleted": "Đã xóa",
62
- "Saved": "Đã lưu",
63
- "Add Pipeline": "Thêm Pipeline",
64
- "Edit Pipeline": "Sửa Pipeline",
65
- "New Pipeline": "Pipeline mới",
66
- "Pipeline Name": "Tên Pipeline",
67
- "Description": "Mô tả",
68
- "Pipeline Steps": "Các bước Pipeline",
69
- "Add Step": "Thêm bước",
70
- "Add First Step": "Thêm bước đầu tiên",
71
- "No steps yet": "Chưa có bước nào",
72
- "Step Name": "Tên bước",
73
- "Endpoint": "Endpoint",
74
- "Output Alias": "Alias đầu ra",
75
- "On Error": "Khi lỗi",
76
- "Fail": "Dừng",
77
- "Skip": "Bỏ qua",
78
- "Retry": "Thử lại",
79
- "Input Mapping (JSON)": "Ánh xạ đầu vào (JSON)",
80
- "Condition (optional JSON)": "Điều kiện (JSON, tùy chọn)",
81
- "Input Schema (JSON Schema)": "Schema đầu vào (JSON Schema)",
82
- "Output Mapping (JSON)": "Ánh xạ đầu ra (JSON)",
83
- "Advanced: Input Schema & Output Mapping": "Nâng cao: Schema đầu vào & Ánh xạ đầu ra",
84
- "AI Tool": "Công cụ AI",
85
- "Active": "Đang hoạt động",
86
- "Inactive": "Không hoạt động",
87
- "Steps": "Các bước",
88
- "Job Details": "Chi tiết công việc",
89
- "Status": "Trạng thái",
90
- "Current Step": "Bước hiện tại",
91
- "Started": "Bắt đầu",
92
- "Completed": "Hoàn thành",
93
- "Error": "Lỗi",
94
- "Input": "Dữ liệu đầu vào",
95
- "Step Results": "Kết quả từng bước",
96
- "Final Result": "Kết quả cuối cùng",
97
- "External Task IDs": "ID tác vụ ngoài",
98
- "View": "Xem",
99
- "Refresh": "Làm mới",
100
- "Filter by status": "Lọc theo trạng thái",
101
- "Filter by pipeline": "Lọc theo pipeline",
102
- "Pipeline": "Pipeline",
103
- "ID": "ID",
104
- "Name": "Tên",
105
- "Method": "Phương thức",
106
- "Execution": "Thực thi",
107
- "File": "File",
108
- "Done": "Xong",
109
- "Pending": "Đang chờ",
110
- "Running": "Đang chạy",
111
- "Failed": "Thất bại",
112
- "Timeout": "Hết thời gian",
113
- "All steps must have a name": "Tất cả các bước phải có tên",
114
- "Step output aliases must be unique": "Alias đầu ra của các bước phải khác nhau",
115
- "Delete this endpoint?": "Xóa endpoint này?",
116
- "Delete this pipeline?": "Xóa pipeline này?",
117
- "Remove step?": "Xóa bước này?",
118
- "skip on error": "bỏ qua khi lỗi",
119
- "conditional": "có điều kiện",
120
- "Invalid JSON": "JSON không hợp lệ"
121
- }
1
+ {
2
+ "Document Understanding": "Hiểu Tài Liệu",
3
+ "Document Understanding - Pipeline Orchestrator": "Hiểu Tài Liệu - Bộ Điều Phối Pipeline",
4
+ "Service Connection": "Kết nối dịch vụ",
5
+ "Service Config": "Cấu hình dịch vụ",
6
+ "Endpoints": "Endpoints",
7
+ "Pipelines": "Pipelines",
8
+ "Jobs history": "Lịch sử công việc",
9
+ "Base URL": "URL gốc",
10
+ "Authentication Type": "Loại xác thực",
11
+ "Auth Type": "Loại xác thực",
12
+ "None": "Không",
13
+ "API Key": "Khóa API",
14
+ "Bearer Token": "Token Bearer",
15
+ "Custom Header": "Header tùy chỉnh",
16
+ "Custom Header Name": "Tên Header tùy chỉnh",
17
+ "API Key / Token": "Khóa API / Token",
18
+ "Request Timeout (ms)": "Timeout request (ms)",
19
+ "Default Retries": "Số lần thử lại mặc định",
20
+ "Poll Interval (ms)": "Khoảng thời gian poll (ms)",
21
+ "Poll Timeout (ms)": "Timeout poll (ms)",
22
+ "Webhook Secret": "Mã bí mật Webhook",
23
+ "Save Configuration": "Lưu cấu hình",
24
+ "Configuration saved successfully": "Đã lưu cấu hình thành công",
25
+ "Failed to save config": "Lưu cấu hình thất bại",
26
+ "Add Endpoint": "Thêm Endpoint",
27
+ "Edit Endpoint": "Sửa Endpoint",
28
+ "Basic": "Cơ bản",
29
+ "File Input": "File đầu vào",
30
+ "Async Config": "Cấu hình bất đồng bộ",
31
+ "Schema": "Schema",
32
+ "Custom Headers": "Headers tùy chỉnh",
33
+ "Unique Name": "Tên duy nhất",
34
+ "Subpath": "Đường dẫn con",
35
+ "HTTP Method": "Phương thức HTTP",
36
+ "Execution Mode": "Chế độ thực thi",
37
+ "Synchronous": "Đồng bộ",
38
+ "Polling": "Polling",
39
+ "Webhook": "Webhook",
40
+ "File Input Mode": "Chế độ nhập file",
41
+ "Multipart Upload": "Upload Multipart",
42
+ "Base64 in JSON": "Base64 trong JSON",
43
+ "Max Files": "Số file tối đa",
44
+ "Task ID Field": "Trường Task ID",
45
+ "Poll Result Subpath": "Đường dẫn poll kết quả",
46
+ "Result Field": "Trường kết quả",
47
+ "Status Field": "Trường trạng thái",
48
+ "Completed Value": "Giá trị hoàn thành",
49
+ "Poll Task ID Field": "Trường Task ID khi poll",
50
+ "Poll Result Field": "Trường kết quả khi poll",
51
+ "Poll Status Field": "Trường trạng thái khi poll",
52
+ "Poll Completed Value": "Giá trị hoàn thành khi poll",
53
+ "Request Body Schema (JSON Schema)": "Schema body request (JSON Schema)",
54
+ "Response Schema (JSON Schema)": "Schema response (JSON Schema)",
55
+ "Additional Headers": "Headers bổ sung",
56
+ "Add Header": "Thêm Header",
57
+ "Enabled": "Bật",
58
+ "Action": "Hành động",
59
+ "Edit": "Sửa",
60
+ "Delete": "Xóa",
61
+ "Deleted": "Đã xóa",
62
+ "Saved": "Đã lưu",
63
+ "Add Pipeline": "Thêm Pipeline",
64
+ "Edit Pipeline": "Sửa Pipeline",
65
+ "New Pipeline": "Pipeline mới",
66
+ "Pipeline Name": "Tên Pipeline",
67
+ "Description": "Mô tả",
68
+ "Pipeline Steps": "Các bước Pipeline",
69
+ "Add Step": "Thêm bước",
70
+ "Add First Step": "Thêm bước đầu tiên",
71
+ "No steps yet": "Chưa có bước nào",
72
+ "Step Name": "Tên bước",
73
+ "Endpoint": "Endpoint",
74
+ "Output Alias": "Alias đầu ra",
75
+ "On Error": "Khi lỗi",
76
+ "Fail": "Dừng",
77
+ "Skip": "Bỏ qua",
78
+ "Retry": "Thử lại",
79
+ "Input Mapping (JSON)": "Ánh xạ đầu vào (JSON)",
80
+ "Condition (optional JSON)": "Điều kiện (JSON, tùy chọn)",
81
+ "Input Schema (JSON Schema)": "Schema đầu vào (JSON Schema)",
82
+ "Output Mapping (JSON)": "Ánh xạ đầu ra (JSON)",
83
+ "Advanced: Input Schema & Output Mapping": "Nâng cao: Schema đầu vào & Ánh xạ đầu ra",
84
+ "AI Tool": "Công cụ AI",
85
+ "Active": "Đang hoạt động",
86
+ "Inactive": "Không hoạt động",
87
+ "Steps": "Các bước",
88
+ "Job Details": "Chi tiết công việc",
89
+ "Status": "Trạng thái",
90
+ "Current Step": "Bước hiện tại",
91
+ "Started": "Bắt đầu",
92
+ "Completed": "Hoàn thành",
93
+ "Error": "Lỗi",
94
+ "Input": "Dữ liệu đầu vào",
95
+ "Step Results": "Kết quả từng bước",
96
+ "Final Result": "Kết quả cuối cùng",
97
+ "External Task IDs": "ID tác vụ ngoài",
98
+ "View": "Xem",
99
+ "Refresh": "Làm mới",
100
+ "Filter by status": "Lọc theo trạng thái",
101
+ "Filter by pipeline": "Lọc theo pipeline",
102
+ "Pipeline": "Pipeline",
103
+ "ID": "ID",
104
+ "Name": "Tên",
105
+ "Method": "Phương thức",
106
+ "Execution": "Thực thi",
107
+ "File": "File",
108
+ "Done": "Xong",
109
+ "Pending": "Đang chờ",
110
+ "Running": "Đang chạy",
111
+ "Failed": "Thất bại",
112
+ "Timeout": "Hết thời gian",
113
+ "All steps must have a name": "Tất cả các bước phải có tên",
114
+ "Step output aliases must be unique": "Alias đầu ra của các bước phải khác nhau",
115
+ "Delete this endpoint?": "Xóa endpoint này?",
116
+ "Delete this pipeline?": "Xóa pipeline này?",
117
+ "Remove step?": "Xóa bước này?",
118
+ "skip on error": "bỏ qua khi lỗi",
119
+ "conditional": "có điều kiện",
120
+ "Invalid JSON": "JSON không hợp lệ"
121
+ }
@@ -0,0 +1,17 @@
1
+ import type { Context } from '@nocobase/actions';
2
+ export declare const defineActions: (plugin: any) => {
3
+ getConfig(ctx: Context, next: () => Promise<any>): Promise<void>;
4
+ updateConfig(ctx: Context, next: () => Promise<any>): Promise<void>;
5
+ listEndpoints(ctx: Context, next: () => Promise<any>): Promise<void>;
6
+ createEndpoint(ctx: Context, next: () => Promise<any>): Promise<void>;
7
+ updateEndpoint(ctx: Context, next: () => Promise<any>): Promise<void>;
8
+ deleteEndpoint(ctx: Context, next: () => Promise<any>): Promise<void>;
9
+ listPipelines(ctx: Context, next: () => Promise<any>): Promise<void>;
10
+ createPipeline(ctx: Context, next: () => Promise<any>): Promise<void>;
11
+ updatePipeline(ctx: Context, next: () => Promise<any>): Promise<void>;
12
+ deletePipeline(ctx: Context, next: () => Promise<any>): Promise<void>;
13
+ executePipeline(ctx: Context, next: () => Promise<any>): Promise<void>;
14
+ getJobStatus(ctx: Context, next: () => Promise<any>): Promise<void>;
15
+ listJobs(ctx: Context, next: () => Promise<any>): Promise<void>;
16
+ webhookCallback(ctx: Context, next: () => Promise<any>): Promise<void>;
17
+ };
@@ -0,0 +1,3 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+ declare const _default: CollectionOptions;
3
+ export default _default;
@@ -0,0 +1,3 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+ declare const _default: CollectionOptions;
3
+ export default _default;
@@ -0,0 +1,3 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+ declare const _default: CollectionOptions;
3
+ export default _default;
@@ -0,0 +1,3 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+ declare const _default: CollectionOptions;
3
+ export default _default;
@@ -0,0 +1,3 @@
1
+ import { CollectionOptions } from '@nocobase/database';
2
+ declare const _default: CollectionOptions;
3
+ export default _default;
@@ -0,0 +1 @@
1
+ export { default } from './plugin';
@@ -0,0 +1,18 @@
1
+ import { Plugin } from '@nocobase/server';
2
+ import { DocumentUnderstandingService } from './services/DocumentUnderstandingService';
3
+ export declare class PluginDocumentUnderstandingServer extends Plugin {
4
+ app: any;
5
+ db: any;
6
+ name: string;
7
+ service: DocumentUnderstandingService;
8
+ afterAdd(): Promise<void>;
9
+ beforeLoad(): Promise<void>;
10
+ load(): Promise<void>;
11
+ private registerActions;
12
+ private registerAITools;
13
+ install(): Promise<void>;
14
+ afterEnable(): Promise<void>;
15
+ afterDisable(): Promise<void>;
16
+ remove(): Promise<void>;
17
+ }
18
+ export default PluginDocumentUnderstandingServer;
@@ -42,7 +42,9 @@ class PluginDocumentUnderstandingServer extends import_server.Plugin {
42
42
  async beforeLoad() {
43
43
  }
44
44
  async load() {
45
- await this.importCollections((0, import_path.resolve)(__dirname, "collections"));
45
+ await this.db.import({
46
+ directory: (0, import_path.resolve)(__dirname, "collections")
47
+ });
46
48
  this.service = new import_DocumentUnderstandingService.DocumentUnderstandingService(this.app, this.db);
47
49
  this.app.on("afterStart", async () => {
48
50
  try {
@@ -0,0 +1,23 @@
1
+ import { Database } from '@nocobase/database';
2
+ import { ExternalApiClient } from './ExternalApiClient';
3
+ import { EndpointDef } from '../types';
4
+ export declare class AsyncJobManager {
5
+ private db;
6
+ private apiClient;
7
+ private intervals;
8
+ private onJobComplete;
9
+ private onJobError;
10
+ constructor(db: Database, apiClient: ExternalApiClient, callbacks: {
11
+ onJobComplete: (jobId: number, result: any) => Promise<void>;
12
+ onJobError: (jobId: number, error: string) => Promise<void>;
13
+ });
14
+ startPolling(jobId: number, endpoint: EndpointDef, taskId: string, customInterval?: number, customTimeout?: number): Promise<void>;
15
+ /**
16
+ * Recover polling jobs that were in-flight when server restarted.
17
+ * Call this during service initialization.
18
+ */
19
+ recoverPollingJobs(): Promise<void>;
20
+ stopPolling(jobId: number): void;
21
+ destroy(): void;
22
+ private getNestedValue;
23
+ }
@@ -0,0 +1,35 @@
1
+ import { Application } from '@nocobase/server';
2
+ import { Database } from '@nocobase/database';
3
+ import { FileInput } from './ExternalApiClient';
4
+ import { ServiceConfig, EndpointDef, PipelineDef, JobState } from '../types';
5
+ export declare class DocumentUnderstandingService {
6
+ private app;
7
+ private db;
8
+ private apiClient;
9
+ private pipelineExecutor;
10
+ private jobManager;
11
+ private initialized;
12
+ private static readonly HEADER_NAME_RE;
13
+ constructor(app: Application, db: Database);
14
+ initialize(): Promise<void>;
15
+ isReady(): boolean;
16
+ getConfig(): Promise<ServiceConfig>;
17
+ updateConfig(data: Partial<ServiceConfig>): Promise<void>;
18
+ listEndpoints(): Promise<EndpointDef[]>;
19
+ createEndpoint(data: Partial<EndpointDef>): Promise<EndpointDef>;
20
+ updateEndpoint(id: number, data: Partial<EndpointDef>): Promise<void>;
21
+ private normalizeEndpoint;
22
+ private normalizeHeaders;
23
+ deleteEndpoint(id: number): Promise<void>;
24
+ listPipelines(): Promise<PipelineDef[]>;
25
+ createPipeline(data: Partial<PipelineDef>): Promise<PipelineDef>;
26
+ updatePipeline(id: number, data: Partial<PipelineDef>): Promise<void>;
27
+ private validateStepAliases;
28
+ deletePipeline(id: number): Promise<void>;
29
+ executePipeline(pipelineId: number, input: Record<string, any>, files?: FileInput[], userId?: number): Promise<{
30
+ jobId: number;
31
+ }>;
32
+ getJobStatus(jobId: number): Promise<JobState>;
33
+ listJobs(filters?: any): Promise<JobState[]>;
34
+ handleWebhook(payload: any, signature?: string): Promise<void>;
35
+ }
@@ -50,6 +50,7 @@ class DocumentUnderstandingService {
50
50
  pipelineExecutor;
51
51
  jobManager;
52
52
  initialized = false;
53
+ static HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
53
54
  constructor(app, db) {
54
55
  this.app = app;
55
56
  this.db = db;
@@ -107,10 +108,38 @@ class DocumentUnderstandingService {
107
108
  return this.db.getRepository("doc_understanding_endpoints").find({ sort: "sortOrder" });
108
109
  }
109
110
  async createEndpoint(data) {
110
- return this.db.getRepository("doc_understanding_endpoints").create({ values: data });
111
+ return this.db.getRepository("doc_understanding_endpoints").create({ values: this.normalizeEndpoint(data) });
111
112
  }
112
113
  async updateEndpoint(id, data) {
113
- await this.db.getRepository("doc_understanding_endpoints").update({ filterByTk: id, values: data });
114
+ await this.db.getRepository("doc_understanding_endpoints").update({
115
+ filterByTk: id,
116
+ values: this.normalizeEndpoint(data)
117
+ });
118
+ }
119
+ normalizeEndpoint(data = {}) {
120
+ if (!Object.prototype.hasOwnProperty.call(data, "customHeaders")) {
121
+ return data;
122
+ }
123
+ return {
124
+ ...data,
125
+ customHeaders: this.normalizeHeaders(data.customHeaders)
126
+ };
127
+ }
128
+ normalizeHeaders(headers) {
129
+ const normalized = {};
130
+ if (!headers || typeof headers !== "object" || Array.isArray(headers)) {
131
+ return normalized;
132
+ }
133
+ for (const [rawName, rawValue] of Object.entries(headers)) {
134
+ const name = rawName.trim();
135
+ if (!name) continue;
136
+ if (!DocumentUnderstandingService.HEADER_NAME_RE.test(name)) {
137
+ throw new Error(`Invalid HTTP header name: ${rawName}`);
138
+ }
139
+ if (rawValue === void 0 || rawValue === null) continue;
140
+ normalized[name] = String(rawValue);
141
+ }
142
+ return normalized;
114
143
  }
115
144
  async deleteEndpoint(id) {
116
145
  await this.db.getRepository("doc_understanding_endpoints").destroy({ filterByTk: id });
@@ -173,7 +202,8 @@ class DocumentUnderstandingService {
173
202
  const jobsRepo = this.db.getRepository("doc_understanding_jobs");
174
203
  const PAGE_SIZE = 100;
175
204
  let offset = 0;
176
- while (true) {
205
+ let hasMoreJobs = true;
206
+ while (hasMoreJobs) {
177
207
  const jobs = await jobsRepo.find({
178
208
  filter: { status: "polling" },
179
209
  limit: PAGE_SIZE,
@@ -186,8 +216,10 @@ class DocumentUnderstandingService {
186
216
  return;
187
217
  }
188
218
  }
189
- if (jobs.length < PAGE_SIZE) break;
190
- offset += PAGE_SIZE;
219
+ hasMoreJobs = jobs.length >= PAGE_SIZE;
220
+ if (hasMoreJobs) {
221
+ offset += PAGE_SIZE;
222
+ }
191
223
  }
192
224
  throw new Error(`Job not found for webhook task ${taskId}`);
193
225
  }
@@ -0,0 +1,28 @@
1
+ /// <reference types="node" />
2
+ import { ServiceConfig, EndpointDef } from '../types';
3
+ export interface FileInput {
4
+ fieldName: string;
5
+ buffer: Buffer;
6
+ filename: string;
7
+ mimeType: string;
8
+ }
9
+ export interface ApiCallOptions {
10
+ endpoint: EndpointDef;
11
+ body?: Record<string, any>;
12
+ files?: FileInput[];
13
+ overrideHeaders?: Record<string, string>;
14
+ }
15
+ export declare class ExternalApiClient {
16
+ private config;
17
+ private client;
18
+ private static readonly HEADER_NAME_RE;
19
+ constructor(config: ServiceConfig);
20
+ private buildAuthHeaders;
21
+ private sanitizeHeaders;
22
+ call(options: ApiCallOptions): Promise<{
23
+ status: number;
24
+ data: any;
25
+ headers: any;
26
+ }>;
27
+ get(url: string, overrideHeaders?: Record<string, string>): Promise<any>;
28
+ }
@@ -44,6 +44,7 @@ var import_form_data = __toESM(require("form-data"));
44
44
  class ExternalApiClient {
45
45
  config;
46
46
  client;
47
+ static HEADER_NAME_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
47
48
  constructor(config) {
48
49
  this.config = config;
49
50
  this.client = import_axios.default.create({
@@ -66,15 +67,31 @@ class ExternalApiClient {
66
67
  }
67
68
  return headers;
68
69
  }
70
+ sanitizeHeaders(headers) {
71
+ const normalized = {};
72
+ if (!headers || typeof headers !== "object" || Array.isArray(headers)) {
73
+ return normalized;
74
+ }
75
+ for (const [rawName, rawValue] of Object.entries(headers)) {
76
+ const name = rawName.trim();
77
+ if (!name) continue;
78
+ if (!ExternalApiClient.HEADER_NAME_RE.test(name)) {
79
+ throw new Error(`Invalid HTTP header name: ${rawName}`);
80
+ }
81
+ if (rawValue === void 0 || rawValue === null) continue;
82
+ normalized[name] = String(rawValue);
83
+ }
84
+ return normalized;
85
+ }
69
86
  async call(options) {
70
87
  const { endpoint, body, files, overrideHeaders } = options;
71
88
  const url = endpoint.subpath;
72
89
  const method = endpoint.method.toLowerCase();
73
90
  let requestData = body;
74
91
  let headers = {
75
- ...this.buildAuthHeaders(),
76
- ...endpoint.customHeaders || {},
77
- ...overrideHeaders || {}
92
+ ...this.sanitizeHeaders(this.buildAuthHeaders()),
93
+ ...this.sanitizeHeaders(endpoint.customHeaders),
94
+ ...this.sanitizeHeaders(overrideHeaders)
78
95
  };
79
96
  if (endpoint.fileInputMode === "multipart" && files && files.length > 0) {
80
97
  const formData = new import_form_data.default();
@@ -0,0 +1,23 @@
1
+ import { Database } from '@nocobase/database';
2
+ import { ExternalApiClient, FileInput } from './ExternalApiClient';
3
+ import { AsyncJobManager } from './AsyncJobManager';
4
+ import { JobState } from '../types';
5
+ export interface ExecutionContext {
6
+ input: Record<string, any>;
7
+ files: FileInput[];
8
+ stepResults: Record<string, any>;
9
+ jobId: number;
10
+ }
11
+ export declare class PipelineExecutor {
12
+ private db;
13
+ private apiClient;
14
+ private jobManager;
15
+ constructor(db: Database, apiClient: ExternalApiClient, jobManager: AsyncJobManager);
16
+ execute(pipelineId: number, input: Record<string, any>, files?: FileInput[], userId?: number): Promise<JobState>;
17
+ private runSteps;
18
+ resumeFromStep(jobId: number, asyncResult: any): Promise<void>;
19
+ private finishJob;
20
+ private resolveMapping;
21
+ private evaluateCondition;
22
+ private getNestedValue;
23
+ }
@@ -0,0 +1,8 @@
1
+ import { DocumentUnderstandingService } from '../services/DocumentUnderstandingService';
2
+ /**
3
+ * Dynamic tools provider: queries all enabled pipelines and registers one tool per pipeline.
4
+ * Called on-demand by the AI tools manager each time tools are listed.
5
+ */
6
+ export declare function createDynamicPipelineToolsProvider(service: DocumentUnderstandingService): (register: {
7
+ registerTools: (options: any) => void;
8
+ }) => Promise<void>;
@@ -29,12 +29,18 @@ __export(document_understanding_tool_exports, {
29
29
  createDynamicPipelineToolsProvider: () => createDynamicPipelineToolsProvider
30
30
  });
31
31
  module.exports = __toCommonJS(document_understanding_tool_exports);
32
+ function cloneJson(value) {
33
+ if (value === void 0 || value === null) {
34
+ return value;
35
+ }
36
+ return JSON.parse(JSON.stringify(value));
37
+ }
32
38
  function buildToolName(pipelineName) {
33
39
  const sanitized = pipelineName.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
34
40
  return `doc_understanding.${sanitized}`;
35
41
  }
36
42
  function buildSchema(pipeline) {
37
- const baseSchema = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0 ? pipeline.inputSchema : {
43
+ const baseSchema = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0 ? cloneJson(pipeline.inputSchema) : {
38
44
  type: "object",
39
45
  properties: {
40
46
  input: {
@@ -52,6 +58,30 @@ function buildSchema(pipeline) {
52
58
  }
53
59
  return baseSchema;
54
60
  }
61
+ function applySchemaDefaults(value, schema) {
62
+ if (!schema || typeof schema !== "object") {
63
+ return value;
64
+ }
65
+ if (value === void 0 && Object.prototype.hasOwnProperty.call(schema, "default")) {
66
+ return cloneJson(schema.default);
67
+ }
68
+ const isObjectSchema = schema.type === "object" || schema.properties;
69
+ if (isObjectSchema) {
70
+ const source = value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
71
+ for (const [key, propertySchema] of Object.entries(schema.properties || {})) {
72
+ const currentValue = source[key];
73
+ const nextValue = applySchemaDefaults(currentValue, propertySchema);
74
+ if (nextValue !== void 0) {
75
+ source[key] = nextValue;
76
+ }
77
+ }
78
+ return source;
79
+ }
80
+ if (Array.isArray(value) && schema.items) {
81
+ return value.map((item) => applySchemaDefaults(item, schema.items));
82
+ }
83
+ return value;
84
+ }
55
85
  function createToolForPipeline(service, pipeline) {
56
86
  const stepNames = (pipeline.steps || []).sort((a, b) => a.stepOrder - b.stepOrder).map((s) => s.name).join(" \u2192 ");
57
87
  const description = [
@@ -81,11 +111,15 @@ function createToolForPipeline(service, pipeline) {
81
111
  if (args.file_urls && Array.isArray(args.file_urls)) {
82
112
  files = args.file_urls.map((url) => ({ url }));
83
113
  }
84
- let input = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0 ? args : args.input || args;
114
+ const hasInputSchema = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0;
115
+ let input = hasInputSchema ? args : args.input || args;
85
116
  if (input === args) {
86
117
  input = { ...args };
87
118
  delete input.file_urls;
88
119
  }
120
+ if (hasInputSchema) {
121
+ input = applySchemaDefaults(input, pipeline.inputSchema);
122
+ }
89
123
  const { jobId } = await service.executePipeline(pipeline.id, input, files);
90
124
  const start = Date.now();
91
125
  while (Date.now() - start < maxWait) {
@@ -95,7 +129,7 @@ function createToolForPipeline(service, pipeline) {
95
129
  } else if (job.status === "failed" || job.status === "timeout") {
96
130
  return { status: job.status, error: job.error };
97
131
  }
98
- await new Promise((r) => setTimeout(r, pollInterval));
132
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
99
133
  }
100
134
  return {
101
135
  status: "polling",