plugin-document-understanding 1.1.16 → 2.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 (82) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +19 -25
  3. package/dist/client/169.6888909107c553c3.js +10 -0
  4. package/dist/client/379.e29f5ced467ce23d.js +10 -0
  5. package/dist/client/867.3ed3b814115181ca.js +10 -0
  6. package/dist/client/index.js +1 -1
  7. package/dist/client-v2/169.53bf1be2ec192f0c.js +10 -0
  8. package/dist/client-v2/379.e75c4829567cdb89.js +10 -0
  9. package/dist/client-v2/867.66d7291e95f1de78.js +10 -0
  10. package/dist/client-v2/index.js +1 -1
  11. package/dist/externalVersion.js +9 -7
  12. package/dist/locale/en-US.json +126 -0
  13. package/dist/locale/vi-VN.json +130 -2
  14. package/dist/locale/zh-CN.json +127 -1
  15. package/dist/node_modules/form-data/package.json +1 -1
  16. package/dist/node_modules/mime-types/package.json +1 -1
  17. package/dist/server/actions.js +211 -11
  18. package/dist/server/collections/api-keys.js +55 -0
  19. package/dist/server/collections/artifacts.js +59 -0
  20. package/dist/server/collections/config.js +9 -3
  21. package/dist/server/collections/endpoints.js +3 -0
  22. package/dist/server/collections/jobs.js +7 -4
  23. package/dist/server/collections/operations.js +76 -0
  24. package/dist/server/contracts/du-contracts.js +828 -0
  25. package/dist/server/dugate-seed.js +98 -340
  26. package/dist/server/plugin.js +49 -7
  27. package/dist/server/routes/du-gateway-router.js +443 -0
  28. package/dist/server/services/ArtifactStorageService.js +459 -0
  29. package/dist/server/services/AsyncJobManager.js +1 -1
  30. package/dist/server/services/BuiltinBusinessEngine.js +1223 -0
  31. package/dist/server/services/DocumentUnderstandingService.js +151 -25
  32. package/dist/server/services/ExternalDuReworkClient.js +210 -0
  33. package/dist/server/services/OperationOrchestrator.js +1087 -0
  34. package/dist/server/services/PipelineExecutor.js +164 -43
  35. package/dist/server/tools/document-understanding-tool.js +49 -24
  36. package/dist/server/workflow/DocumentUnderstandingInstruction.js +292 -0
  37. package/package.json +8 -4
  38. package/src/client/index.tsx +11 -0
  39. package/src/client-v2/components/ApiKeysTab.tsx +198 -0
  40. package/src/client-v2/components/EndpointsTab.tsx +39 -2
  41. package/src/client-v2/components/JobsTab.tsx +136 -21
  42. package/src/client-v2/components/OperationsTab.tsx +586 -0
  43. package/src/client-v2/components/PluginSettings.tsx +12 -0
  44. package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
  45. package/src/client-v2/components/__tests__/PluginSettings.test.tsx +4 -0
  46. package/src/client-v2/locale.ts +1 -8
  47. package/src/client-v2/models/index.ts +1 -8
  48. package/src/client-v2/plugin.tsx +12 -8
  49. package/src/client-v2/types.ts +13 -1
  50. package/src/client-v2/workflow/DocumentUnderstandingFieldset.tsx +122 -0
  51. package/src/client-v2/workflow/DocumentUnderstandingInstruction.tsx +49 -0
  52. package/src/locale/en-US.json +126 -0
  53. package/src/locale/vi-VN.json +130 -2
  54. package/src/locale/zh-CN.json +127 -1
  55. package/src/server/__tests__/actions.test.ts +1 -8
  56. package/src/server/__tests__/du-rework-gateway.test.ts +462 -0
  57. package/src/server/__tests__/dugate-integration.test.ts +79 -42
  58. package/src/server/__tests__/smoke.test.ts +1 -8
  59. package/src/server/__tests__/upload-security.test.ts +1 -8
  60. package/src/server/actions.ts +252 -36
  61. package/src/server/collections/api-keys.ts +35 -0
  62. package/src/server/collections/artifacts.ts +39 -0
  63. package/src/server/collections/config.ts +18 -2
  64. package/src/server/collections/endpoints.ts +12 -0
  65. package/src/server/collections/jobs.ts +16 -4
  66. package/src/server/collections/operations.ts +56 -0
  67. package/src/server/contracts/du-contracts.ts +1026 -0
  68. package/src/server/dugate-seed.ts +126 -453
  69. package/src/server/plugin.ts +64 -14
  70. package/src/server/routes/du-gateway-router.ts +465 -0
  71. package/src/server/services/ArtifactStorageService.ts +596 -0
  72. package/src/server/services/AsyncJobManager.ts +10 -1
  73. package/src/server/services/BuiltinBusinessEngine.ts +1544 -0
  74. package/src/server/services/DocumentUnderstandingService.ts +186 -44
  75. package/src/server/services/ExternalDuReworkClient.ts +222 -0
  76. package/src/server/services/OperationOrchestrator.ts +1359 -0
  77. package/src/server/services/PipelineExecutor.ts +245 -108
  78. package/src/server/tools/document-understanding-tool.ts +63 -45
  79. package/src/server/types.ts +101 -16
  80. package/src/server/workflow/DocumentUnderstandingInstruction.ts +308 -0
  81. package/dist/client/345.277fbb2b97424db5.js +0 -10
  82. package/dist/client-v2/345.2fa9834b46dd4531.js +0 -10
@@ -1,491 +1,164 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  /**
2
- * DUGate-compatible seed data: pre-configured endpoints and pipelines for all
3
- * 6 core profiles + 3 workflow profiles.
4
+ * Canonical `du-rework` v1 catalog seed & automatic legacy `dugate-*` migration.
5
+ *
6
+ * Seeds all 36 canonical profiles across:
7
+ * - `document-core@2.0.0` (6 core actions / 31 variants + 3 multi-step workflows)
8
+ * - `lc-checker@1.2.0` (UCP 600 / ISBP 821 trade-finance examination)
9
+ * - `example-review@1.0.0` (multi-document compliance review)
4
10
  *
5
- * Endpoint subpaths are RELATIVE to the configured Service Config `baseUrl`
6
- * (e.g. `http://localhost:2023/api/v1/docs`). Workflows route to
7
- * `/api/v1/docs/workflows` automatically. To point at a different gateway,
8
- * change the base URL in the admin UI — the seeded paths stay untouched.
11
+ * Automatically upgrades pre-existing `dugate-*` endpoints and convenience pipelines
12
+ * in-place on plugin startup so existing installations move seamlessly to `du-rework` v1.
9
13
  */
10
14
 
11
15
  import type { Database } from '@nocobase/database';
16
+ import { DU_BUSINESS_CATALOG, type DuCatalogEntry } from './contracts/du-contracts';
12
17
 
13
- interface EndpointSeed {
14
- name: string;
15
- subpath: string;
16
- method: 'POST';
17
- description: string;
18
- fileInputMode: 'none' | 'multipart' | 'base64';
19
- fileFieldName?: string;
20
- maxFiles: number;
21
- executionMode: 'sync' | 'polling' | 'webhook';
22
- discriminatorField?: string;
23
- discriminatorValue?: string;
24
- /** Added for every sync-capable endpoint so DUGate returns immediately. */
25
- syncQueryParam?: string;
26
- /** DUGate 202 response: `{name: "operations/{id}", done: false}` → extract `id` from `name`. */
27
- taskIdExtractPath?: string;
28
- taskIdExtractRegex?: string;
29
- /** Polling: GET /api/v1/operations/{taskId} */
30
- pollResultSubpath?: string;
31
- pollTaskIdField?: string;
32
- pollResultField?: string;
33
- pollStatusField?: string;
34
- pollCompletedValue?: string;
35
- pollInterval?: number;
36
- pollTimeout?: number;
37
- enabled?: boolean;
38
- }
39
-
40
- interface PipelineSeed {
41
- name: string;
42
- description: string;
43
- inputSchema?: any;
44
- outputMapping?: any;
45
- enabled?: boolean;
46
- steps: Array<{
47
- stepOrder: number;
48
- name: string;
49
- endpointName: string;
50
- outputAlias?: string;
51
- inputMapping?: any;
52
- onError?: 'fail' | 'skip' | 'retry';
53
- retryCount?: number;
54
- }>;
55
- }
56
-
57
- const DEFAULT_POLL_INTERVAL = 3000;
18
+ const DEFAULT_POLL_INTERVAL = 3_000;
58
19
  const DEFAULT_POLL_TIMEOUT = 300_000;
59
20
 
60
- /** Shared async config for DUGate endpoints that support async mode. */
61
- const asyncConfig = {
62
- taskIdExtractPath: 'name',
63
- taskIdExtractRegex: 'operations/([^/]+)',
64
- pollResultSubpath: '/api/v1/operations/{taskId}',
65
- pollTaskIdField: 'id',
66
- pollResultField: 'result',
67
- pollStatusField: 'metadata.state',
68
- pollCompletedValue: 'SUCCEEDED',
69
- pollInterval: DEFAULT_POLL_INTERVAL,
70
- pollTimeout: DEFAULT_POLL_TIMEOUT,
71
- };
72
-
73
- function coreEndpoint(
74
- service: string,
75
- discriminatorValue: string,
76
- overrides: Partial<EndpointSeed> & { name: string },
77
- ): EndpointSeed {
78
- const { name, ...rest } = overrides;
21
+ function toEndpointValues(entry: DuCatalogEntry, sortOrder: number) {
79
22
  return {
80
- name,
81
- subpath: `/api/v1/docs/${service}`,
82
- method: 'POST',
83
- fileInputMode: 'multipart',
84
- fileFieldName: 'files[]',
85
- maxFiles: 10,
86
- executionMode: 'sync',
87
- discriminatorField:
88
- discriminatorValue === 'diff' || discriminatorValue === 'semantic' || discriminatorValue === 'version'
89
- ? 'mode'
90
- : ['parse', 'ocr', 'digitize', 'split'].includes(discriminatorValue)
91
- ? 'mode'
92
- : ['invoice', 'contract', 'id-card', 'receipt', 'table', 'custom'].includes(discriminatorValue)
93
- ? 'type'
94
- : ['classify', 'sentiment', 'compliance', 'fact-check', 'quality', 'risk', 'summarize-eval'].includes(
95
- discriminatorValue,
96
- )
97
- ? 'task'
98
- : ['convert', 'translate', 'rewrite', 'redact', 'template'].includes(discriminatorValue)
99
- ? 'action'
100
- : 'mode',
101
- discriminatorValue,
102
- syncQueryParam: 'sync',
103
- ...asyncConfig,
104
- ...rest,
105
- } as EndpointSeed;
23
+ name: entry.endpointName,
24
+ subpath: `/api/v1/businesses/${entry.businessId}/actions/${entry.action}`,
25
+ method: 'POST' as const,
26
+ description: entry.description,
27
+ requestBodySchema: entry.inputSchema,
28
+ fileInputMode: 'multipart' as const,
29
+ fileFieldName: 'files[]',
30
+ maxFiles: entry.maxFiles,
31
+ executionMode: 'sync' as const,
32
+ protocolMode: 'builtin_du' as const,
33
+ businessId: entry.businessId,
34
+ actionName: entry.action,
35
+ discriminatorField: entry.discriminatorField || null,
36
+ discriminatorValue: entry.discriminatorValue || null,
37
+ syncQueryParam: null,
38
+ taskIdExtractPath: 'operationId',
39
+ taskIdExtractRegex: null,
40
+ pollResultSubpath: '/api/v1/operations/{taskId}',
41
+ pollTaskIdField: 'operationId',
42
+ pollResultField: 'data',
43
+ pollStatusField: 'state',
44
+ pollCompletedValue: 'SUCCEEDED',
45
+ pollInterval: DEFAULT_POLL_INTERVAL,
46
+ pollTimeout: DEFAULT_POLL_TIMEOUT,
47
+ enabled: true,
48
+ sortOrder,
49
+ };
106
50
  }
107
51
 
108
- function workflowEndpoint(process: string, overrides: Partial<EndpointSeed> & { name: string }): EndpointSeed {
109
- const { name, ...rest } = overrides;
110
- return {
111
- name,
112
- subpath: '/api/v1/docs/workflows',
113
- method: 'POST',
114
- fileInputMode: 'multipart',
115
- fileFieldName: 'files[]',
116
- maxFiles: 10,
117
- executionMode: 'sync', // Will detect 202 and switch to polling automatically
118
- discriminatorField: 'process',
119
- discriminatorValue: process,
120
- syncQueryParam: 'sync',
121
- ...asyncConfig,
122
- ...rest,
123
- } as EndpointSeed;
52
+ function buildInputMappingFromSchema(entry: DuCatalogEntry): Record<string, string> {
53
+ const props =
54
+ entry.inputSchema && typeof entry.inputSchema.properties === 'object' && entry.inputSchema.properties !== null
55
+ ? (entry.inputSchema.properties as Record<string, unknown>)
56
+ : {};
57
+ const mapping: Record<string, string> = {};
58
+ for (const key of Object.keys(props)) {
59
+ if (key === entry.discriminatorField) continue;
60
+ mapping[key] = `$input.${key}`;
61
+ }
62
+ if (entry.action !== 'ingest' || entry.discriminatorValue !== 'split') {
63
+ mapping.pages = '$input.pages';
64
+ }
65
+ return mapping;
124
66
  }
125
67
 
126
- /**
127
- * ──── CORE PROFILE ENDPOINTS ──────────────────────────────────
128
- * 6 profiles: ingest, extract, analyze, transform, generate, compare
129
- */
130
- const CORE_ENDPOINTS: EndpointSeed[] = [
131
- // ── ingest ──
132
- coreEndpoint('ingest', 'parse', {
133
- name: 'dugate-ingest-parse',
134
- description:
135
- 'Parse digital documents (PDF/DOCX native), preserve headers, footers, tables. Supports output_format (md/json/html/csv) and language.',
136
- fileFieldName: 'files[]',
137
- maxFiles: 5,
138
- }),
139
- coreEndpoint('ingest', 'ocr', {
140
- name: 'dugate-ingest-ocr',
141
- description: 'OCR scanned documents and images. Supports language parameter.',
142
- fileFieldName: 'files[]',
143
- maxFiles: 5,
144
- }),
145
- coreEndpoint('ingest', 'digitize', {
146
- name: 'dugate-ingest-digitize',
147
- description: 'Digitize handwritten forms, checkboxes.',
148
- fileFieldName: 'files[]',
149
- maxFiles: 5,
150
- }),
151
- coreEndpoint('ingest', 'split', {
152
- name: 'dugate-ingest-split',
153
- description: 'Split/merge PDF pages. Use pages parameter (e.g. "1-5").',
154
- fileFieldName: 'file',
155
- maxFiles: 1,
156
- }),
157
-
158
- // ── extract ──
159
- coreEndpoint('extract', 'invoice', {
160
- name: 'dugate-extract-invoice',
161
- description: 'Extract structured data from Vietnamese VAT invoices / general invoices.',
162
- fileFieldName: 'files[]',
163
- maxFiles: 5,
164
- }),
165
- coreEndpoint('extract', 'contract', {
166
- name: 'dugate-extract-contract',
167
- description: 'Extract parties, terms, obligations, penalties, signatures from contracts.',
168
- fileFieldName: 'files[]',
169
- maxFiles: 5,
170
- }),
171
- coreEndpoint('extract', 'id-card', {
172
- name: 'dugate-extract-id-card',
173
- description: 'Extract identity information from CCCD/Passport.',
174
- fileFieldName: 'files[]',
175
- maxFiles: 5,
176
- }),
177
- coreEndpoint('extract', 'receipt', {
178
- name: 'dugate-extract-receipt',
179
- description: 'Extract merchant, items, totals from receipts.',
180
- fileFieldName: 'files[]',
181
- maxFiles: 5,
182
- }),
183
- coreEndpoint('extract', 'table', {
184
- name: 'dugate-extract-table',
185
- description: 'Extract all tables from documents as structured data.',
186
- fileFieldName: 'files[]',
187
- maxFiles: 5,
188
- }),
189
- coreEndpoint('extract', 'custom', {
190
- name: 'dugate-extract-custom',
191
- description:
192
- 'Extract custom fields using dynamic schema. Use fields (comma-separated) or schema (JSON Schema string).',
193
- fileFieldName: 'files[]',
194
- maxFiles: 5,
195
- }),
196
-
197
- // ── analyze ──
198
- coreEndpoint('analyze', 'classify', {
199
- name: 'dugate-analyze-classify',
200
- description: 'Classify documents by taxonomy. Provide categories parameter.',
201
- maxFiles: 5,
202
- }),
203
- coreEndpoint('analyze', 'sentiment', {
204
- name: 'dugate-analyze-sentiment',
205
- description: 'Analyze document sentiment: positive, negative, neutral.',
206
- maxFiles: 5,
207
- }),
208
- coreEndpoint('analyze', 'compliance', {
209
- name: 'dugate-analyze-compliance',
210
- description: 'Check document compliance against criteria. Provide criteria parameter (semicolon-separated rules).',
211
- maxFiles: 5,
212
- }),
213
- coreEndpoint('analyze', 'fact-check', {
214
- name: 'dugate-analyze-fact-check',
215
- description: 'Cross-reference document claims against reference data. Provide reference_data and extract_fields.',
216
- maxFiles: 5,
217
- }),
218
- coreEndpoint('analyze', 'quality', {
219
- name: 'dugate-analyze-quality',
220
- description: 'Score document writing quality against criteria.',
221
- maxFiles: 5,
222
- }),
223
- coreEndpoint('analyze', 'risk', {
224
- name: 'dugate-analyze-risk',
225
- description: 'Assess document risk level.',
226
- maxFiles: 5,
227
- }),
228
- coreEndpoint('analyze', 'summarize-eval', {
229
- name: 'dugate-analyze-summarize-eval',
230
- description: 'Generate expert summary and evaluation of document.',
231
- maxFiles: 5,
232
- }),
233
-
234
- // ── transform ──
235
- coreEndpoint('transform', 'convert', {
236
- name: 'dugate-transform-convert',
237
- description: 'Convert document format (DOCX -> MD/HTML). Use output_format parameter.',
238
- fileFieldName: 'file',
239
- maxFiles: 1,
240
- }),
241
- coreEndpoint('transform', 'translate', {
242
- name: 'dugate-transform-translate',
243
- description: 'Translate document to target language. Use target_language and tone parameters.',
244
- fileFieldName: 'file',
245
- maxFiles: 1,
246
- }),
247
- coreEndpoint('transform', 'rewrite', {
248
- name: 'dugate-transform-rewrite',
249
- description:
250
- 'Rewrite/paraphrase document. Use style (academic/executive/simplified/bullet_points) and tone parameters.',
251
- fileFieldName: 'file',
252
- maxFiles: 1,
253
- }),
254
- coreEndpoint('transform', 'redact', {
255
- name: 'dugate-transform-redact',
256
- description: 'Redact PII from document. Use redact_patterns parameter.',
257
- fileFieldName: 'file',
258
- maxFiles: 1,
259
- }),
260
- coreEndpoint('transform', 'template', {
261
- name: 'dugate-transform-template',
262
- description: 'Mail merge using template. Use template parameter (JSON).',
263
- fileFieldName: 'file',
264
- maxFiles: 1,
265
- }),
266
-
267
- // ── generate ──
268
- coreEndpoint('generate', 'summary', {
269
- name: 'dugate-generate-summary',
270
- description:
271
- 'Generate condensed summary. Parameters: format (paragraph/bullets/numbered/table/mind_map), max_words, audience.',
272
- fileFieldName: 'files[]',
273
- maxFiles: 5,
274
- }),
275
- coreEndpoint('generate', 'outline', {
276
- name: 'dugate-generate-outline',
277
- description: 'Extract H1/H2/H3 table of contents.',
278
- fileFieldName: 'files[]',
279
- maxFiles: 5,
280
- }),
281
- coreEndpoint('generate', 'report', {
282
- name: 'dugate-generate-report',
283
- description: 'Generate expert analysis report.',
284
- fileFieldName: 'files[]',
285
- maxFiles: 5,
286
- }),
287
- coreEndpoint('generate', 'email', {
288
- name: 'dugate-generate-email',
289
- description: 'Draft email response based on document. Use tone parameter.',
290
- fileFieldName: 'files[]',
291
- maxFiles: 5,
292
- }),
293
- coreEndpoint('generate', 'minutes', {
294
- name: 'dugate-generate-minutes',
295
- description: 'Generate meeting minutes with action items. Use format parameter.',
296
- fileFieldName: 'files[]',
297
- maxFiles: 5,
298
- }),
299
- coreEndpoint('generate', 'qa', {
300
- name: 'dugate-generate-qa',
301
- description: 'Ask questions about document content (RAG-like). Use questions parameter (JSON array).',
302
- fileFieldName: 'files[]',
303
- maxFiles: 5,
304
- }),
305
-
306
- // ── compare ──
307
- coreEndpoint('compare', 'diff', {
308
- name: 'dugate-compare-diff',
309
- description: 'Line-by-line text diff (git-diff style). Requires 2 files via files[]. Use output_format parameter.',
310
- fileFieldName: 'files[]',
311
- maxFiles: 2,
312
- }),
313
- coreEndpoint('compare', 'semantic', {
314
- name: 'dugate-compare-semantic',
315
- description: 'Semantic/legal comparison. Requires 2 files. Use focus parameter for specific concerns.',
316
- fileFieldName: 'files[]',
317
- maxFiles: 2,
318
- }),
319
- coreEndpoint('compare', 'version', {
320
- name: 'dugate-compare-version',
321
- description: 'Summarized changelog between versions. Requires 2 files. Use output_format parameter.',
322
- fileFieldName: 'files[]',
323
- maxFiles: 2,
324
- }),
325
- ];
68
+ export async function seedDugateEndpoints(db: Database): Promise<{ endpoints: number; pipelines: number }> {
69
+ const endpointsRepo = db.getRepository('doc_understanding_endpoints');
70
+ const pipelinesRepo = db.getRepository('doc_understanding_pipelines');
71
+ const stepsRepo = db.getRepository('doc_understanding_pipeline_steps');
326
72
 
327
- /**
328
- * ──── WORKFLOW PROFILE ENDPOINTS ──────────────────────────────
329
- * 3 workflow profiles: disbursement, lc-checker, doc-compare
330
- */
331
- const WORKFLOW_ENDPOINTS: EndpointSeed[] = [
332
- workflowEndpoint('disbursement', {
333
- name: 'dugate-workflow-disbursement',
334
- description:
335
- 'Disbursement reconciliation: classify files, extract data, cross-check resolution, generate disbursement memo.',
336
- maxFiles: 10,
337
- }),
338
- workflowEndpoint('lc-checker', {
339
- name: 'dugate-workflow-lc-checker',
340
- description:
341
- 'Letter of Credit document checking: validate documents against LC terms, detect discrepancies per UCP 600.',
342
- maxFiles: 10,
343
- }),
344
- workflowEndpoint('doc-compare', {
345
- name: 'dugate-workflow-doc-compare',
346
- description:
347
- 'Advanced document comparison: OCR, extract TOC, compare sections, generate comparison report. Requires exactly 2 files.',
348
- maxFiles: 2,
349
- }),
350
- ];
351
-
352
- /**
353
- * ──── CONVENIENCE PIPELINES ──────────────────────────────────
354
- * Each pipeline wraps a single endpoint so users can run them via the
355
- * admin UI playground or invoke them as AI tools.
356
- *
357
- * Multi-step pipelines can be added manually from the UI later.
358
- */
359
- function buildPipelines(epNames: string[]): PipelineSeed[] {
360
- return epNames.map((epName) => ({
361
- name: epName
362
- .replace(/^dugate-/, '')
363
- .replace(/-/g, ' ')
364
- .replace(/\b\w/g, (c) => c.toUpperCase()),
365
- description: `Execute the DUGate ${epName.replace(/^dugate-/, '')} profile.`,
366
- enabled: true,
367
- steps: [
368
- {
369
- stepOrder: 1,
370
- name: 'Call DUGate API',
371
- endpointName: epName,
372
- outputAlias: 'result',
373
- inputMapping: {
374
- file_urls: '$input.file_urls',
375
- output_format: '$input.output_format',
376
- language: '$input.language',
377
- categories: '$input.categories',
378
- criteria: '$input.criteria',
379
- reference_data: '$input.reference_data',
380
- fields: '$input.fields',
381
- schema: '$input.schema',
382
- questions: '$input.questions',
383
- target_language: '$input.target_language',
384
- tone: '$input.tone',
385
- style: '$input.style',
386
- redact_patterns: '$input.redact_patterns',
387
- template: '$input.template',
388
- format: '$input.format',
389
- max_words: '$input.max_words',
390
- audience: '$input.audience',
391
- focus: '$input.focus',
392
- pages: '$input.pages',
393
- resolution_data: '$input.resolution_data',
394
- extract_fields: '$input.extract_fields',
395
- },
396
- },
397
- ],
398
- outputMapping: {
399
- content: '$step[result].response.content',
400
- extracted_data: '$step[result].response.extracted_data',
401
- usage: '$step[result].response.usage',
402
- },
403
- }));
404
- }
73
+ const endpointNameToId = new Map<string, number>();
405
74
 
406
- export async function seedDugateEndpoints(db: Database): Promise<void> {
407
- const endpointsRepo = db.getRepository<any>('doc_understanding_endpoints');
408
- const pipelinesRepo = db.getRepository<any>('doc_understanding_pipelines');
409
- const stepsRepo = db.getRepository<any>('doc_understanding_pipeline_steps');
75
+ for (let index = 0; index < DU_BUSINESS_CATALOG.length; index += 1) {
76
+ const entry = DU_BUSINESS_CATALOG[index];
77
+ const values = toEndpointValues(entry, index + 1);
410
78
 
411
- const allEndpoints: EndpointSeed[] = [...CORE_ENDPOINTS, ...WORKFLOW_ENDPOINTS];
79
+ let existing = await endpointsRepo.findOne({ filter: { name: entry.endpointName } });
80
+ if (!existing && entry.legacyEndpointName) {
81
+ existing = await endpointsRepo.findOne({ filter: { name: entry.legacyEndpointName } });
82
+ }
412
83
 
413
- // Upsert each endpoint by name
414
- const endpointNameToId = new Map<string, number>();
415
- for (const ep of allEndpoints) {
416
- const existing = await endpointsRepo.findOne({ filter: { name: ep.name } });
417
- let record;
84
+ let recordId: number;
418
85
  if (existing) {
419
- await endpointsRepo.update({ filterByTk: existing.id, values: ep });
420
- record = await endpointsRepo.findOne({ filter: { name: ep.name } });
86
+ await endpointsRepo.update({ filterByTk: existing.id, values });
87
+ recordId = Number(existing.id);
421
88
  } else {
422
- record = await endpointsRepo.create({ values: ep });
89
+ const created = await endpointsRepo.create({ values });
90
+ recordId = Number(created.id);
423
91
  }
424
- endpointNameToId.set(ep.name, record.id);
92
+ endpointNameToId.set(entry.endpointName, recordId);
425
93
  }
426
94
 
427
- // Build pipelines for all single-step convenience profiles
428
- const pipelineNames = allEndpoints.map((e) => e.name);
429
- const pipelines = buildPipelines(pipelineNames);
95
+ for (const entry of DU_BUSINESS_CATALOG) {
96
+ const endpointId = endpointNameToId.get(entry.endpointName);
97
+ if (!endpointId) continue;
98
+
99
+ const description = `[${entry.businessId}@${entry.businessVersion}] ${entry.description}`;
100
+ const inputMapping = buildInputMappingFromSchema(entry);
101
+ const outputMapping = {
102
+ data: '$step[result].response.data',
103
+ markdown: '$step[result].response.markdown',
104
+ text: '$step[result].response.text',
105
+ report: '$step[result].response.report',
106
+ verdict: '$step[result].response.verdict',
107
+ discrepancies: '$step[result].response.discrepancies',
108
+ usage: '$step[result].response.usage',
109
+ };
430
110
 
431
- for (const pipeline of pipelines) {
432
- const existingPipeline = await pipelinesRepo.findOne({ filter: { name: pipeline.name } });
111
+ const existingPipeline = await pipelinesRepo.findOne({ filter: { name: entry.pipelineName } });
433
112
  if (existingPipeline) {
434
- // Update existing pipeline steps
435
113
  await stepsRepo.destroy({ filter: { pipelineId: existingPipeline.id } });
436
114
  await pipelinesRepo.update({
437
115
  filterByTk: existingPipeline.id,
438
116
  values: {
439
- description: pipeline.description,
440
- enabled: pipeline.enabled,
441
- inputSchema: pipeline.inputSchema,
442
- outputMapping: pipeline.outputMapping,
117
+ description,
118
+ enabled: existingPipeline.enabled ?? true,
119
+ inputSchema: entry.inputSchema,
120
+ outputMapping,
121
+ },
122
+ });
123
+ await stepsRepo.create({
124
+ values: {
125
+ pipelineId: existingPipeline.id,
126
+ stepOrder: 1,
127
+ name: `${entry.businessId}/${entry.action}`,
128
+ endpointId,
129
+ inputMapping,
130
+ outputAlias: 'result',
131
+ onError: 'fail',
132
+ retryCount: 0,
443
133
  },
444
134
  });
445
- for (const step of pipeline.steps) {
446
- const endpointId = endpointNameToId.get(step.endpointName);
447
- if (endpointId) {
448
- await stepsRepo.create({
449
- values: {
450
- pipelineId: existingPipeline.id,
451
- stepOrder: step.stepOrder,
452
- name: step.name,
453
- endpointId,
454
- inputMapping: step.inputMapping || null,
455
- outputAlias: step.outputAlias || null,
456
- onError: step.onError || 'fail',
457
- retryCount: step.retryCount ?? 0,
458
- },
459
- });
460
- }
461
- }
462
135
  } else {
463
136
  const created = await pipelinesRepo.create({
464
137
  values: {
465
- name: pipeline.name,
466
- description: pipeline.description,
467
- enabled: pipeline.enabled,
468
- inputSchema: pipeline.inputSchema || null,
469
- outputMapping: pipeline.outputMapping || null,
138
+ name: entry.pipelineName,
139
+ description,
140
+ enabled: true,
141
+ inputSchema: entry.inputSchema,
142
+ outputMapping,
143
+ },
144
+ });
145
+ await stepsRepo.create({
146
+ values: {
147
+ pipelineId: created.id,
148
+ stepOrder: 1,
149
+ name: `${entry.businessId}/${entry.action}`,
150
+ endpointId,
151
+ inputMapping,
152
+ outputAlias: 'result',
153
+ onError: 'fail',
154
+ retryCount: 0,
470
155
  },
471
156
  });
472
- for (const step of pipeline.steps) {
473
- const endpointId = endpointNameToId.get(step.endpointName);
474
- if (endpointId) {
475
- await stepsRepo.create({
476
- values: {
477
- pipelineId: created.id,
478
- stepOrder: step.stepOrder,
479
- name: step.name,
480
- endpointId,
481
- inputMapping: step.inputMapping || null,
482
- outputAlias: step.outputAlias || null,
483
- onError: step.onError || 'fail',
484
- retryCount: step.retryCount ?? 0,
485
- },
486
- });
487
- }
488
- }
489
157
  }
490
158
  }
159
+
160
+ return {
161
+ endpoints: DU_BUSINESS_CATALOG.length,
162
+ pipelines: DU_BUSINESS_CATALOG.length,
163
+ };
491
164
  }