plugin-document-understanding 1.0.0

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 (50) hide show
  1. package/README.md +366 -0
  2. package/client.d.ts +2 -0
  3. package/client.js +1 -0
  4. package/dist/client/components/EndpointsTab.d.ts +2 -0
  5. package/dist/client/components/JobsTab.d.ts +2 -0
  6. package/dist/client/components/PipelinesTab.d.ts +2 -0
  7. package/dist/client/components/PluginSettings.d.ts +2 -0
  8. package/dist/client/components/ServiceConfigTab.d.ts +2 -0
  9. package/dist/client/index.d.ts +1 -0
  10. package/dist/client/index.js +1 -0
  11. package/dist/client/locale.d.ts +10 -0
  12. package/dist/client/models/index.d.ts +11 -0
  13. package/dist/client/plugin.d.ts +5 -0
  14. package/dist/externalVersion.js +10 -0
  15. package/dist/index.d.ts +2 -0
  16. package/dist/index.js +39 -0
  17. package/dist/locale/en-US.json +121 -0
  18. package/dist/locale/vi-VN.json +121 -0
  19. package/dist/locale/zh-CN.json +1 -0
  20. package/dist/server/actions.d.ts +16 -0
  21. package/dist/server/actions.js +109 -0
  22. package/dist/server/collections/config.d.ts +2 -0
  23. package/dist/server/collections/config.js +39 -0
  24. package/dist/server/collections/endpoints.d.ts +2 -0
  25. package/dist/server/collections/endpoints.js +47 -0
  26. package/dist/server/collections/jobs.d.ts +2 -0
  27. package/dist/server/collections/jobs.js +49 -0
  28. package/dist/server/collections/pipeline-steps.d.ts +2 -0
  29. package/dist/server/collections/pipeline-steps.js +47 -0
  30. package/dist/server/collections/pipelines.d.ts +2 -0
  31. package/dist/server/collections/pipelines.js +39 -0
  32. package/dist/server/index.d.ts +1 -0
  33. package/dist/server/index.js +33 -0
  34. package/dist/server/plugin.d.ts +15 -0
  35. package/dist/server/plugin.js +102 -0
  36. package/dist/server/services/AsyncJobManager.d.ts +23 -0
  37. package/dist/server/services/AsyncJobManager.js +117 -0
  38. package/dist/server/services/DocumentUnderstandingService.d.ts +32 -0
  39. package/dist/server/services/DocumentUnderstandingService.js +189 -0
  40. package/dist/server/services/ExternalApiClient.d.ts +26 -0
  41. package/dist/server/services/ExternalApiClient.js +128 -0
  42. package/dist/server/services/PipelineExecutor.d.ts +23 -0
  43. package/dist/server/services/PipelineExecutor.js +252 -0
  44. package/dist/server/tools/document-understanding-tool.d.ts +8 -0
  45. package/dist/server/tools/document-understanding-tool.js +105 -0
  46. package/dist/server/types.d.ts +68 -0
  47. package/dist/server/types.js +15 -0
  48. package/package.json +16 -0
  49. package/server.d.ts +2 -0
  50. package/server.js +1 -0
@@ -0,0 +1,252 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var PipelineExecutor_exports = {};
19
+ __export(PipelineExecutor_exports, {
20
+ PipelineExecutor: () => PipelineExecutor
21
+ });
22
+ module.exports = __toCommonJS(PipelineExecutor_exports);
23
+ class PipelineExecutor {
24
+ db;
25
+ apiClient;
26
+ jobManager;
27
+ constructor(db, apiClient, jobManager) {
28
+ this.db = db;
29
+ this.apiClient = apiClient;
30
+ this.jobManager = jobManager;
31
+ }
32
+ async execute(pipelineId, input, files = [], userId) {
33
+ const pipelineRepo = this.db.getRepository("doc_understanding_pipelines");
34
+ const jobsRepo = this.db.getRepository("doc_understanding_jobs");
35
+ const pipeline = await pipelineRepo.findOne({
36
+ filter: { id: pipelineId },
37
+ appends: ["steps", "steps.endpoint"]
38
+ });
39
+ if (!pipeline) throw new Error(`Pipeline ${pipelineId} not found`);
40
+ const job = await jobsRepo.create({
41
+ values: {
42
+ pipelineId,
43
+ status: "pending",
44
+ input,
45
+ currentStep: 1,
46
+ // 1-based ordering
47
+ stepResults: {},
48
+ externalTaskIds: {},
49
+ startedAt: /* @__PURE__ */ new Date(),
50
+ createdById: userId
51
+ }
52
+ });
53
+ const context = {
54
+ input,
55
+ files,
56
+ stepResults: {},
57
+ jobId: job.id
58
+ };
59
+ const steps = [...pipeline.steps || []].sort((a, b) => a.stepOrder - b.stepOrder);
60
+ this.runSteps(job, steps, context).catch((err) => {
61
+ console.error(`Background pipeline error for job ${job.id}`, err);
62
+ });
63
+ return job;
64
+ }
65
+ async runSteps(job, steps, context, startFromOrder = 1) {
66
+ const jobsRepo = this.db.getRepository("doc_understanding_jobs");
67
+ let currentOrder = startFromOrder;
68
+ try {
69
+ await jobsRepo.update({ filterByTk: job.id, values: { status: "running" } });
70
+ for (const step of steps) {
71
+ if (step.stepOrder < startFromOrder) continue;
72
+ context.jobId = job.id;
73
+ currentOrder = step.stepOrder;
74
+ await jobsRepo.update({ filterByTk: job.id, values: { currentStep: currentOrder } });
75
+ if (!this.evaluateCondition(step.condition, context)) {
76
+ continue;
77
+ }
78
+ const mappedBody = this.resolveMapping(step.inputMapping || {}, context);
79
+ let retries = step.onError === "retry" ? step.retryCount || 0 : 0;
80
+ let success = false;
81
+ let lastError = null;
82
+ while (retries >= 0 && !success) {
83
+ try {
84
+ const result = await this.apiClient.call({
85
+ endpoint: step.endpoint,
86
+ body: mappedBody,
87
+ files: context.files
88
+ });
89
+ if (step.endpoint.executionMode === "sync") {
90
+ context.stepResults[step.outputAlias || step.stepOrder.toString()] = result.data;
91
+ success = true;
92
+ } else if (step.endpoint.executionMode === "polling") {
93
+ const taskIdField = step.endpoint.pollTaskIdField || "task_id";
94
+ const taskId = this.getNestedValue(result.data, taskIdField);
95
+ if (!taskId) throw new Error(`Polling taskId not found in field ${taskIdField}`);
96
+ let externalTaskIds = job.externalTaskIds || {};
97
+ externalTaskIds[step.stepOrder.toString()] = taskId;
98
+ await jobsRepo.update({
99
+ filterByTk: job.id,
100
+ values: { status: "polling", externalTaskIds }
101
+ });
102
+ await this.jobManager.startPolling(job.id, step.endpoint, taskId);
103
+ return;
104
+ } else if (step.endpoint.executionMode === "webhook") {
105
+ const taskIdField = step.endpoint.pollTaskIdField || "task_id";
106
+ const taskId = this.getNestedValue(result.data, taskIdField);
107
+ let externalTaskIds = job.externalTaskIds || {};
108
+ externalTaskIds[step.stepOrder.toString()] = taskId;
109
+ await jobsRepo.update({
110
+ filterByTk: job.id,
111
+ values: { status: "polling", externalTaskIds }
112
+ });
113
+ return;
114
+ }
115
+ } catch (err) {
116
+ lastError = err;
117
+ retries--;
118
+ }
119
+ }
120
+ if (!success) {
121
+ if (step.onError === "fail") {
122
+ throw lastError || new Error(`Step ${step.name} failed`);
123
+ }
124
+ }
125
+ }
126
+ await this.finishJob(job.id, context);
127
+ } catch (err) {
128
+ await jobsRepo.update({
129
+ filterByTk: job.id,
130
+ values: { status: "failed", error: err.message, completedAt: /* @__PURE__ */ new Date() }
131
+ });
132
+ }
133
+ }
134
+ async resumeFromStep(jobId, asyncResult) {
135
+ const jobsRepo = this.db.getRepository("doc_understanding_jobs");
136
+ const pipelineRepo = this.db.getRepository("doc_understanding_pipelines");
137
+ const job = await jobsRepo.findOne({ filterByTk: jobId });
138
+ if (!job) throw new Error(`Job ${jobId} not found`);
139
+ const pipeline = await pipelineRepo.findOne({
140
+ filter: { id: job.pipelineId },
141
+ appends: ["steps", "steps.endpoint"]
142
+ });
143
+ if (!pipeline) throw new Error(`Pipeline not found for job ${jobId}`);
144
+ const steps = [...pipeline.steps || []].sort((a, b) => a.stepOrder - b.stepOrder);
145
+ const step = steps.find((s) => s.stepOrder === job.currentStep);
146
+ if (step) {
147
+ job.stepResults = job.stepResults || {};
148
+ job.stepResults[step.outputAlias || step.stepOrder.toString()] = asyncResult;
149
+ await jobsRepo.update({
150
+ filterByTk: jobId,
151
+ values: { stepResults: job.stepResults }
152
+ // updating stepResults json
153
+ });
154
+ }
155
+ const context = {
156
+ input: job.input,
157
+ files: [],
158
+ // Files cannot easily persist across webhook unless stored in bucket. For now assume next steps use only json.
159
+ stepResults: job.stepResults,
160
+ jobId: job.id
161
+ };
162
+ this.runSteps(job, steps, context, job.currentStep + 1).catch((err) => {
163
+ console.error(`Failed executing step ${job.currentStep + 1} for job ${job.id}`, err);
164
+ });
165
+ }
166
+ async finishJob(jobId, context) {
167
+ const jobsRepo = this.db.getRepository("doc_understanding_jobs");
168
+ const pipelineRepo = this.db.getRepository("doc_understanding_pipelines");
169
+ const job = await jobsRepo.findOne({ filterByTk: jobId });
170
+ if (!job) return;
171
+ const pipeline = await pipelineRepo.findOne({ filter: { id: job.pipelineId } });
172
+ if (!pipeline) return;
173
+ const finalResult = pipeline.outputMapping ? this.resolveMapping(pipeline.outputMapping, context) : context.stepResults;
174
+ await jobsRepo.update({
175
+ filterByTk: jobId,
176
+ values: {
177
+ status: "completed",
178
+ stepResults: context.stepResults,
179
+ finalResult,
180
+ completedAt: /* @__PURE__ */ new Date()
181
+ }
182
+ });
183
+ }
184
+ resolveMapping(mapping, context) {
185
+ const result = {};
186
+ for (const [key, value] of Object.entries(mapping)) {
187
+ if (typeof value === "string") {
188
+ if (value.startsWith("$input.")) {
189
+ result[key] = this.getNestedValue(context.input, value.replace("$input.", ""));
190
+ } else if (value.startsWith("$step[")) {
191
+ const match = value.match(/\$step\[(.*?)\]\.response\.(.*)/);
192
+ if (match) {
193
+ const stepKey = match[1];
194
+ const path = match[2];
195
+ const stepResult = context.stepResults[stepKey];
196
+ result[key] = this.getNestedValue(stepResult, path);
197
+ } else {
198
+ result[key] = value;
199
+ }
200
+ } else if (value === "$files") {
201
+ } else {
202
+ result[key] = value;
203
+ }
204
+ } else {
205
+ result[key] = value;
206
+ }
207
+ }
208
+ return result;
209
+ }
210
+ evaluateCondition(condition, context) {
211
+ if (!condition) return true;
212
+ const resolveValue = (v) => {
213
+ if (typeof v === "string" && v.startsWith("$")) {
214
+ if (v.startsWith("$step[")) {
215
+ const match = v.match(/\$step\[(.*?)\]\.response\.(.*)/);
216
+ if (match) return this.getNestedValue(context.stepResults[match[1]], match[2]);
217
+ }
218
+ }
219
+ return v;
220
+ };
221
+ const fieldVal = resolveValue(condition.field);
222
+ const val = resolveValue(condition.value);
223
+ switch (condition.op) {
224
+ case "eq":
225
+ return fieldVal === val;
226
+ case "neq":
227
+ return fieldVal !== val;
228
+ case "gt":
229
+ return fieldVal > val;
230
+ case "gte":
231
+ return fieldVal >= val;
232
+ case "lt":
233
+ return fieldVal < val;
234
+ case "lte":
235
+ return fieldVal <= val;
236
+ case "in":
237
+ return Array.isArray(val) && val.includes(fieldVal);
238
+ case "contains":
239
+ return typeof fieldVal === "string" && fieldVal.includes(String(val));
240
+ default:
241
+ return false;
242
+ }
243
+ }
244
+ getNestedValue(obj, path) {
245
+ if (!obj) return obj;
246
+ return path.split(".").reduce((acc, part) => acc && acc[part], obj);
247
+ }
248
+ }
249
+ // Annotate the CommonJS export names for ESM import in node:
250
+ 0 && (module.exports = {
251
+ PipelineExecutor
252
+ });
@@ -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>;
@@ -0,0 +1,105 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var document_understanding_tool_exports = {};
19
+ __export(document_understanding_tool_exports, {
20
+ createDynamicPipelineToolsProvider: () => createDynamicPipelineToolsProvider
21
+ });
22
+ module.exports = __toCommonJS(document_understanding_tool_exports);
23
+ function buildToolName(pipelineName) {
24
+ const sanitized = pipelineName.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_+/g, "_").replace(/^_|_$/g, "");
25
+ return `doc_understanding.${sanitized}`;
26
+ }
27
+ function buildSchema(pipeline) {
28
+ if (pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0) {
29
+ return pipeline.inputSchema;
30
+ }
31
+ return {
32
+ type: "object",
33
+ properties: {
34
+ input: {
35
+ type: "object",
36
+ description: "D\u1EEF li\u1EC7u \u0111\u1EA7u v\xE0o cho pipeline (JSON)"
37
+ }
38
+ }
39
+ };
40
+ }
41
+ function createToolForPipeline(service, pipeline) {
42
+ const stepNames = (pipeline.steps || []).sort((a, b) => a.stepOrder - b.stepOrder).map((s) => s.name).join(" \u2192 ");
43
+ const description = [
44
+ pipeline.description || `Th\u1EF1c thi pipeline "${pipeline.name}".`,
45
+ stepNames ? `Steps: ${stepNames}` : "",
46
+ "Tr\u1EA3 v\u1EC1 k\u1EBFt qu\u1EA3 ph\xE2n t\xEDch JSON ho\u1EB7c Job ID n\u1EBFu ch\u1EA1y async."
47
+ ].filter(Boolean).join(" ");
48
+ return {
49
+ scope: "CUSTOM",
50
+ execution: "backend",
51
+ defaultPermission: "ASK",
52
+ introduction: {
53
+ title: `Document: ${pipeline.name}`,
54
+ about: pipeline.description || `X\u1EED l\xFD t\xE0i li\u1EC7u qua pipeline "${pipeline.name}".`
55
+ },
56
+ definition: {
57
+ name: buildToolName(pipeline.name),
58
+ description,
59
+ schema: buildSchema(pipeline)
60
+ },
61
+ invoke: async (ctx, args) => {
62
+ try {
63
+ const config = await service.getConfig();
64
+ const pollInterval = Math.max(config.pollInterval || 2e3, 1e3);
65
+ const maxWait = Math.min(config.pollTimeout || 3e4, 3e4);
66
+ const input = pipeline.inputSchema && Object.keys(pipeline.inputSchema).length > 0 ? args : args.input || args;
67
+ const { jobId } = await service.executePipeline(pipeline.id, input, []);
68
+ const start = Date.now();
69
+ while (Date.now() - start < maxWait) {
70
+ const job = await service.getJobStatus(jobId);
71
+ if (job.status === "completed") {
72
+ return { status: "completed", result: job.finalResult };
73
+ } else if (job.status === "failed" || job.status === "timeout") {
74
+ return { status: job.status, error: job.error };
75
+ }
76
+ await new Promise((r) => setTimeout(r, pollInterval));
77
+ }
78
+ return {
79
+ status: "polling",
80
+ message: `Pipeline "${pipeline.name}" \u0111ang ch\u1EA1y, tr\u1EA3 v\u1EC1 job ID \u0111\u1EC3 theo d\xF5i.`,
81
+ jobId
82
+ };
83
+ } catch (err) {
84
+ return { error: err.message };
85
+ }
86
+ }
87
+ };
88
+ }
89
+ function createDynamicPipelineToolsProvider(service) {
90
+ return async (register) => {
91
+ try {
92
+ if (!service.isReady()) return;
93
+ const pipelines = await service.listPipelines();
94
+ const enabledPipelines = pipelines.filter((p) => p.enabled);
95
+ if (enabledPipelines.length === 0) return;
96
+ const tools = enabledPipelines.map((pipeline) => createToolForPipeline(service, pipeline));
97
+ register.registerTools(tools);
98
+ } catch {
99
+ }
100
+ };
101
+ }
102
+ // Annotate the CommonJS export names for ESM import in node:
103
+ 0 && (module.exports = {
104
+ createDynamicPipelineToolsProvider
105
+ });
@@ -0,0 +1,68 @@
1
+ export interface ServiceConfig {
2
+ id?: number;
3
+ baseUrl: string;
4
+ authType: 'api_key' | 'bearer' | 'custom_header' | 'none';
5
+ authKey?: string;
6
+ authHeaderName?: string;
7
+ defaultTimeout: number;
8
+ defaultRetries: number;
9
+ pollInterval: number;
10
+ pollTimeout: number;
11
+ webhookSecret?: string;
12
+ }
13
+ export interface EndpointDef {
14
+ id: number;
15
+ name: string;
16
+ subpath: string;
17
+ method: 'GET' | 'POST' | 'PUT';
18
+ description?: string;
19
+ requestBodySchema?: any;
20
+ responseSchema?: any;
21
+ fileInputMode: 'none' | 'multipart' | 'base64';
22
+ maxFiles: number;
23
+ executionMode: 'sync' | 'polling' | 'webhook';
24
+ pollResultSubpath?: string;
25
+ pollTaskIdField?: string;
26
+ pollResultField?: string;
27
+ pollInterval?: number;
28
+ pollTimeout?: number;
29
+ pollStatusField?: string;
30
+ pollCompletedValue?: string;
31
+ customHeaders?: Record<string, string>;
32
+ enabled: boolean;
33
+ }
34
+ export interface PipelineStepDef {
35
+ id: number;
36
+ pipelineId: number;
37
+ endpointId: number;
38
+ stepOrder: number;
39
+ name: string;
40
+ inputMapping?: Record<string, any>;
41
+ outputAlias?: string;
42
+ condition?: any;
43
+ onError: 'fail' | 'skip' | 'retry';
44
+ retryCount: number;
45
+ endpoint: EndpointDef;
46
+ }
47
+ export interface PipelineDef {
48
+ id: number;
49
+ name: string;
50
+ description?: string;
51
+ inputSchema?: any;
52
+ outputMapping?: Record<string, any>;
53
+ enabled: boolean;
54
+ steps: PipelineStepDef[];
55
+ }
56
+ export interface JobState {
57
+ id: number;
58
+ pipelineId: number;
59
+ status: 'pending' | 'running' | 'polling' | 'completed' | 'failed' | 'timeout';
60
+ input: any;
61
+ currentStep: number;
62
+ stepResults: Record<string, any>;
63
+ finalResult?: any;
64
+ error?: string;
65
+ externalTaskIds: Record<string, string>;
66
+ startedAt?: Date;
67
+ completedAt?: Date;
68
+ }
@@ -0,0 +1,15 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __copyProps = (to, from, except, desc) => {
6
+ if (from && typeof from === "object" || typeof from === "function") {
7
+ for (let key of __getOwnPropNames(from))
8
+ if (!__hasOwnProp.call(to, key) && key !== except)
9
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
+ }
11
+ return to;
12
+ };
13
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
14
+ var types_exports = {};
15
+ module.exports = __toCommonJS(types_exports);
package/package.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "name": "plugin-document-understanding",
3
+ "version": "1.0.0",
4
+ "main": "dist/server/index.js",
5
+ "dependencies": {
6
+ "axios": "^1.6.0"
7
+ },
8
+ "peerDependencies": {
9
+ "@nocobase/client": "2.x",
10
+ "@nocobase/server": "2.x",
11
+ "@nocobase/database": "2.x",
12
+ "@nocobase/test": "2.x",
13
+ "@nocobase/plugin-ai": "2.x",
14
+ "@langchain/core": "^0.3.0"
15
+ }
16
+ }
package/server.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export * from './dist/server';
2
+ export { default } from './dist/server';
package/server.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require('./dist/server/index.js');