plugin-document-understanding 1.1.15 → 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 +10 -8
  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 +24 -8
  44. package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
  45. package/src/client-v2/components/__tests__/PluginSettings.test.tsx +43 -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.e6e484fb1974c3d3.js +0 -10
  82. package/dist/client-v2/345.a8f28526ac21e02a.js +0 -10
@@ -1,9 +1,14 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
1
3
  import { Plugin } from '@nocobase/server';
4
+ import type WorkflowPlugin from '@nocobase/plugin-workflow';
2
5
  import { resolve } from 'path';
3
6
  import { DocumentUnderstandingService } from './services/DocumentUnderstandingService';
4
7
  import { defineActions } from './actions';
5
8
  import { createDynamicPipelineToolsProvider } from './tools/document-understanding-tool';
6
9
  import { seedDugateEndpoints } from './dugate-seed';
10
+ import { createDuDisableBodyParserMiddleware, createDuGatewayRouter } from './routes/du-gateway-router';
11
+ import { DocumentUnderstandingWorkflowInstruction } from './workflow/DocumentUnderstandingInstruction';
7
12
 
8
13
  type DynamicToolsProvider = ReturnType<typeof createDynamicPipelineToolsProvider>;
9
14
 
@@ -37,18 +42,35 @@ export class PluginDocumentUnderstandingServer extends Plugin {
37
42
  }
38
43
 
39
44
  async load() {
40
- // Collections are imported in beforeLoad so database metadata exists before
41
- // resources and runtime services are registered.
42
45
  this.service = new DocumentUnderstandingService(this.app, this.db);
46
+ const runtimeState = this.app as typeof this.app & DocumentToolRuntimeState;
47
+ runtimeState.documentUnderstandingService = this.service;
43
48
 
44
- // Register REST actions
49
+ // 1. Mount `du-rework` compatible Public Gateway (/api/du/v1/* & /api/v1/*) before resourcer
50
+ this.app.use(createDuDisableBodyParserMiddleware(), {
51
+ tag: 'docUnderstandingDisableBodyParser',
52
+ before: 'bodyParser',
53
+ });
54
+ this.app.use(
55
+ createDuGatewayRouter(() => this.service),
56
+ {
57
+ tag: 'docUnderstandingPublicGateway',
58
+ before: 'dataSource',
59
+ after: 'dataWrapping',
60
+ },
61
+ );
62
+
63
+ // 2. Register NocoBase Admin/Operator REST actions
45
64
  this.registerActions();
46
65
 
47
- // 4. Register AI tool (graceful)
66
+ // 3. Register NocoBase Workflow Instruction node (graceful when plugin-workflow is present)
67
+ this.registerWorkflowInstruction();
68
+
69
+ // 4. Register Dynamic AI tools (graceful when plugin-ai is present)
48
70
  this.registerAITools();
49
71
  this.app.on('afterStart', this.registerAIToolsAfterStart);
50
72
 
51
- // 5. ACL
73
+ // 5. ACL snippet for admin settings & operations
52
74
  this.app.acl.registerSnippet({
53
75
  name: `pm.${this.name}`,
54
76
  actions: ['docUnderstanding:*'],
@@ -58,12 +80,24 @@ export class PluginDocumentUnderstandingServer extends Plugin {
58
80
  private registerActions() {
59
81
  const actions = defineActions(this);
60
82
 
61
- const resourceName = 'docUnderstanding';
62
83
  this.app.resource({
63
- name: resourceName,
84
+ name: 'docUnderstanding',
64
85
  actions: {
65
86
  getConfig: actions.getConfig,
66
87
  updateConfig: actions.updateConfig,
88
+ getHealth: actions.getHealth,
89
+ listLlmServices: actions.listLlmServices,
90
+ listCatalog: actions.listCatalog,
91
+ syncCatalog: actions.syncCatalog,
92
+ listApiKeys: actions.listApiKeys,
93
+ issueApiKey: actions.issueApiKey,
94
+ revokeApiKey: actions.revokeApiKey,
95
+ listOperations: actions.listOperations,
96
+ getOperation: actions.getOperation,
97
+ submitOperation: actions.submitOperation,
98
+ cancelOperation: actions.cancelOperation,
99
+ resumeOperation: actions.resumeOperation,
100
+ getUsageSummary: actions.getUsageSummary,
67
101
  listEndpoints: actions.listEndpoints,
68
102
  createEndpoint: actions.createEndpoint,
69
103
  updateEndpoint: actions.updateEndpoint,
@@ -75,17 +109,34 @@ export class PluginDocumentUnderstandingServer extends Plugin {
75
109
  executePipeline: actions.executePipeline,
76
110
  getJobStatus: actions.getJobStatus,
77
111
  listJobs: actions.listJobs,
112
+ cancelJob: actions.cancelJob,
113
+ resumeJob: actions.resumeJob,
78
114
  webhookCallback: actions.webhookCallback,
79
115
  },
80
116
  });
81
117
  }
82
118
 
119
+ private registerWorkflowInstruction() {
120
+ try {
121
+ const workflow = (this.app.pm?.get?.('workflow') || this.app.pm?.get?.('@nocobase/plugin-workflow')) as
122
+ | WorkflowPlugin
123
+ | undefined;
124
+ if (workflow?.registerInstruction) {
125
+ workflow.registerInstruction('document-understanding', new DocumentUnderstandingWorkflowInstruction(workflow));
126
+ }
127
+ } catch (err) {
128
+ this.app.logger.warn('Document Understanding: skipped workflow instruction registration.', err);
129
+ }
130
+ }
131
+
83
132
  private registerAITools() {
84
133
  if (this.aiToolsRegistered) return;
85
134
  try {
86
- const aiManager = (this.app as typeof this.app & { aiManager?: unknown }).aiManager;
135
+ const aiManager =
136
+ (this.app as typeof this.app & { aiManager?: unknown }).aiManager ||
137
+ this.app.pm?.get?.('@nocobase/plugin-ai')?.aiManager ||
138
+ this.app.pm?.get?.('ai')?.aiManager;
87
139
  if (!isAiManagerLike(aiManager)) {
88
- this.app.logger.warn('Document Understanding: plugin-ai not available, skip AI tool registration.');
89
140
  return;
90
141
  }
91
142
  const runtimeState = this.app as typeof this.app & DocumentToolRuntimeState;
@@ -99,7 +150,6 @@ export class PluginDocumentUnderstandingServer extends Plugin {
99
150
  runtimeState.documentUnderstandingToolProviderRegistered = true;
100
151
  }
101
152
  this.aiToolsRegistered = true;
102
- this.app.logger.info('Document Understanding: Dynamic pipeline tools provider registered.');
103
153
  } catch (err) {
104
154
  this.app.logger.warn('Document Understanding: Failed to register AI tools, continue without it.', err);
105
155
  }
@@ -108,18 +158,18 @@ export class PluginDocumentUnderstandingServer extends Plugin {
108
158
  async afterStart() {
109
159
  try {
110
160
  await this.service.initialize({ recoverJobs: true });
161
+ // Automatically migrate/seed canonical `du-rework` v1 endpoints & pipelines on startup
162
+ await seedDugateEndpoints(this.db);
111
163
  } catch (err) {
112
- this.app.logger.warn('Document Understanding plugin not configured yet, skip init.', err);
164
+ this.app.logger.warn('Document Understanding startup initialization / catalog sync warning:', err);
113
165
  }
114
166
  }
115
167
 
116
168
  async install() {
117
- // Seed the DUGate-compatible endpoint/pipeline catalog on first install.
118
- // Subpaths stay relative so they follow the base URL in Service Config.
119
169
  try {
120
170
  await seedDugateEndpoints(this.db);
121
171
  } catch (err) {
122
- this.app.logger.warn('Document Understanding: DUGate seed data could not be installed.', err);
172
+ this.app.logger.warn('Document Understanding: catalog seed data could not be installed.', err);
123
173
  }
124
174
  }
125
175
 
@@ -0,0 +1,465 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import * as crypto from 'crypto';
4
+ import type { Context, Next } from '@nocobase/actions';
5
+ import { koaMulter } from '@nocobase/utils';
6
+ import { createProblem, type SubmissionPayload } from '../contracts/du-contracts';
7
+ import type { DocumentUnderstandingService } from '../services/DocumentUnderstandingService';
8
+ import { DuHttpError } from '../services/ArtifactStorageService';
9
+ import type { ApiKeyAuthPrincipal } from '../services/OperationOrchestrator';
10
+
11
+ type DataWrappingContext = Context & { withoutDataWrapping?: boolean; disableBodyParser?: boolean };
12
+
13
+ const DU_NAMESPACE_PREFIX = '/api/du/v1';
14
+ const CANONICAL_ROOT_PATTERN = /^\/api\/v1\/(health|uploads|businesses|operations|artifacts|usage|docs)(\/.*)?$/;
15
+
16
+ const legacyMultipartUpload = koaMulter({
17
+ storage: koaMulter.memoryStorage(),
18
+ limits: { files: 20, fileSize: 64 * 1024 * 1024, fields: 30, fieldSize: 2 * 1024 * 1024 },
19
+ }).any();
20
+
21
+ function isRecord(value: unknown): value is Record<string, unknown> {
22
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
23
+ }
24
+
25
+ export function matchDuGatewayPath(pathname: string): { matched: boolean; subPath: string; urlPrefix: string } {
26
+ if (pathname === DU_NAMESPACE_PREFIX || pathname.startsWith(`${DU_NAMESPACE_PREFIX}/`)) {
27
+ return {
28
+ matched: true,
29
+ subPath: pathname.slice(DU_NAMESPACE_PREFIX.length) || '/',
30
+ urlPrefix: DU_NAMESPACE_PREFIX,
31
+ };
32
+ }
33
+ if (CANONICAL_ROOT_PATTERN.test(pathname)) {
34
+ return {
35
+ matched: true,
36
+ subPath: pathname.slice('/api/v1'.length) || '/',
37
+ urlPrefix: '/api/v1',
38
+ };
39
+ }
40
+ return { matched: false, subPath: '', urlPrefix: DU_NAMESPACE_PREFIX };
41
+ }
42
+
43
+ async function readStreamBuffer(ctx: Context, maxBytes: number): Promise<Buffer> {
44
+ const chunks: Buffer[] = [];
45
+ let total = 0;
46
+ for await (const chunk of ctx.req) {
47
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
48
+ total += buf.length;
49
+ if (total > maxBytes) {
50
+ throw new DuHttpError(createProblem(413, 'PAYLOAD_TOO_LARGE', `Request body exceeds ${maxBytes} bytes`));
51
+ }
52
+ chunks.push(buf);
53
+ }
54
+ return Buffer.concat(chunks);
55
+ }
56
+
57
+ async function readJsonBody(ctx: Context, maxBytes = 2 * 1024 * 1024): Promise<Record<string, unknown>> {
58
+ if (isRecord(ctx.request.body)) {
59
+ return ctx.request.body;
60
+ }
61
+ const raw = await readStreamBuffer(ctx, maxBytes);
62
+ if (raw.length === 0) return {};
63
+ try {
64
+ const parsed: unknown = JSON.parse(raw.toString('utf8'));
65
+ if (!isRecord(parsed)) {
66
+ throw new Error('Root JSON value must be an object');
67
+ }
68
+ return parsed;
69
+ } catch (err) {
70
+ throw new DuHttpError(
71
+ createProblem(400, 'INVALID_JSON', err instanceof Error ? err.message : 'Malformed JSON body'),
72
+ );
73
+ }
74
+ }
75
+
76
+ async function resolveGatewayPrincipal(
77
+ ctx: Context,
78
+ service: DocumentUnderstandingService,
79
+ ): Promise<ApiKeyAuthPrincipal> {
80
+ const rawApiKey = ctx.get('x-api-key');
81
+ if (rawApiKey) {
82
+ return service.orchestrator.authenticateRawApiKey(rawApiKey);
83
+ }
84
+
85
+ // Also support NocoBase session / Bearer JWT API keys (matching plugin-ai-api conventions)
86
+ if (ctx.state?.currentUser?.id) {
87
+ return {
88
+ kind: 'nocobase_user',
89
+ tenantId: ctx.get('x-tenant-id')?.trim() || 'default',
90
+ userId: Number(ctx.state.currentUser.id),
91
+ allowedBusinesses: ['*'],
92
+ allowedActions: ['*'],
93
+ };
94
+ }
95
+
96
+ const authHeader = ctx.get('Authorization') || '';
97
+ if (authHeader.startsWith('Bearer ')) {
98
+ const token = authHeader.slice(7).trim();
99
+ if (token.startsWith('du_live_')) {
100
+ return service.orchestrator.authenticateRawApiKey(token);
101
+ }
102
+ const jwt = (
103
+ ctx.app as unknown as { authManager?: { jwt?: { decode: (t: string) => Promise<{ userId?: number }> } } }
104
+ ).authManager?.jwt;
105
+ if (jwt && token) {
106
+ try {
107
+ const decoded = await jwt.decode(token);
108
+ if (decoded?.userId) {
109
+ const user = await ctx.db.getRepository('users').findOne({ filterByTk: decoded.userId });
110
+ if (user) {
111
+ return {
112
+ kind: 'nocobase_user',
113
+ tenantId: ctx.get('x-tenant-id')?.trim() || 'default',
114
+ userId: Number(user.id),
115
+ allowedBusinesses: ['*'],
116
+ allowedActions: ['*'],
117
+ };
118
+ }
119
+ }
120
+ } catch {
121
+ // Fall through to 401
122
+ }
123
+ }
124
+ }
125
+
126
+ throw new DuHttpError(
127
+ createProblem(401, 'UNAUTHENTICATED', 'Missing or invalid x-api-key or Authorization Bearer credentials'),
128
+ );
129
+ }
130
+
131
+ export function createDuDisableBodyParserMiddleware() {
132
+ return async (ctx: Context, next: Next) => {
133
+ const matched = matchDuGatewayPath(ctx.path);
134
+ if (matched.matched) {
135
+ if (
136
+ (ctx.method === 'PUT' && /^\/uploads\/[^/]+\/content$/.test(matched.subPath)) ||
137
+ (ctx.method === 'POST' && matched.subPath.startsWith('/docs/'))
138
+ ) {
139
+ (ctx as DataWrappingContext).disableBodyParser = true;
140
+ }
141
+ }
142
+ await next();
143
+ };
144
+ }
145
+
146
+ export function createDuGatewayRouter(getService: () => DocumentUnderstandingService) {
147
+ return async (ctx: Context, next: Next) => {
148
+ const routeMatch = matchDuGatewayPath(ctx.path);
149
+ if (!routeMatch.matched) {
150
+ return next();
151
+ }
152
+
153
+ (ctx as DataWrappingContext).withoutDataWrapping = true;
154
+ const { subPath, urlPrefix } = routeMatch;
155
+ const method = ctx.method.toUpperCase();
156
+ const correlationId = (ctx.get('x-correlation-id') || crypto.randomUUID()).trim();
157
+ ctx.set('x-correlation-id', correlationId);
158
+
159
+ const service = getService();
160
+ await service.ensureInitialized();
161
+ const config = await service.getConfig();
162
+
163
+ if (config.publicGatewayEnabled === false) {
164
+ ctx.status = 503;
165
+ ctx.type = 'application/problem+json';
166
+ ctx.body = createProblem(503, 'TEMPORARY_UNAVAILABLE', 'Document Understanding Public Gateway is disabled', {
167
+ correlationId,
168
+ });
169
+ return;
170
+ }
171
+
172
+ try {
173
+ // 1. Health endpoint (`GET /health`)
174
+ if (method === 'GET' && subPath === '/health') {
175
+ ctx.status = 200;
176
+ ctx.body = await service.getGatewayHealth();
177
+ return;
178
+ }
179
+
180
+ // Authenticate all non-health endpoints (Fail-Closed before reading large payloads)
181
+ const principal = await resolveGatewayPrincipal(ctx, service);
182
+
183
+ // 2. Upload Gateway (`POST /uploads`, `PUT /uploads/:id/content`, `POST /uploads/:id/complete|abort`)
184
+ if (method === 'POST' && subPath === '/uploads') {
185
+ const body = await readJsonBody(ctx);
186
+ const res = await service.orchestrator.artifactStorage.initiateUpload({
187
+ tenantId: principal.tenantId,
188
+ fileName: String(body.fileName || ''),
189
+ mimeType: typeof body.mimeType === 'string' ? body.mimeType : undefined,
190
+ sizeBytes: Number(body.sizeBytes ?? 0),
191
+ uploadToken: typeof body.uploadToken === 'string' ? body.uploadToken : undefined,
192
+ idempotencyKey: ctx.get('Idempotency-Key') || undefined,
193
+ userId: principal.userId,
194
+ urlPrefix,
195
+ });
196
+ ctx.status = res.httpStatus;
197
+ ctx.body = {
198
+ artifactId: res.artifactId,
199
+ state: res.state,
200
+ replayed: res.replayed,
201
+ uploadUrl: res.uploadUrl,
202
+ };
203
+ return;
204
+ }
205
+
206
+ const uploadContentMatch = /^\/uploads\/([^/]+)\/content$/.exec(subPath);
207
+ if (method === 'PUT' && uploadContentMatch) {
208
+ const artifactId = decodeURIComponent(uploadContentMatch[1]);
209
+ const rawBytes = Buffer.isBuffer(ctx.request.body)
210
+ ? ctx.request.body
211
+ : await readStreamBuffer(ctx, 64 * 1024 * 1024);
212
+ const res = await service.orchestrator.artifactStorage.writeUploadContent({
213
+ tenantId: principal.tenantId,
214
+ artifactId,
215
+ buffer: rawBytes,
216
+ expectedSha256: ctx.get('x-content-sha256') || undefined,
217
+ });
218
+ ctx.status = res.httpStatus;
219
+ ctx.body = {
220
+ artifactId: res.artifactId,
221
+ state: res.state,
222
+ sizeBytes: res.sizeBytes,
223
+ replayed: res.replayed,
224
+ };
225
+ return;
226
+ }
227
+
228
+ const uploadLifecycleMatch = /^\/uploads\/([^/]+)\/(complete|abort|part)$/.exec(subPath);
229
+ if (method === 'POST' && uploadLifecycleMatch) {
230
+ const artifactId = decodeURIComponent(uploadLifecycleMatch[1]);
231
+ const subAction = uploadLifecycleMatch[2];
232
+ if (subAction === 'part') {
233
+ throw new DuHttpError(
234
+ createProblem(
235
+ 501,
236
+ 'NOT_IMPLEMENTED',
237
+ 'Direct S3 multipart part URLs are disabled when gateway upload is active',
238
+ ),
239
+ );
240
+ }
241
+ ctx.status = 200;
242
+ ctx.body =
243
+ subAction === 'complete'
244
+ ? await service.orchestrator.artifactStorage.completeUpload(principal.tenantId, artifactId)
245
+ : await service.orchestrator.artifactStorage.abortUpload(principal.tenantId, artifactId);
246
+ return;
247
+ }
248
+
249
+ // 3. Canonical Action Submission (`POST /businesses/:businessId/actions/:action`)
250
+ const bizActionMatch = /^\/businesses\/([^/]+)\/actions\/([^/]+)$/.exec(subPath);
251
+ if (method === 'POST' && bizActionMatch) {
252
+ const businessId = decodeURIComponent(bizActionMatch[1]);
253
+ const action = decodeURIComponent(bizActionMatch[2]);
254
+ const body = (await readJsonBody(ctx)) as unknown as SubmissionPayload;
255
+ const syncRequested = ctx.query.sync === 'true';
256
+ const res = await service.orchestrator.submitOperation({
257
+ principal,
258
+ businessId,
259
+ action,
260
+ submission: body,
261
+ idempotencyKey: ctx.get('Idempotency-Key') || undefined,
262
+ correlationId,
263
+ urlPrefix,
264
+ waitCompletionMs: syncRequested ? Math.min(config.pollTimeout || 30_000, 30_000) : 0,
265
+ });
266
+ ctx.status = res.httpStatus;
267
+ ctx.body = {
268
+ operationId: res.operationId,
269
+ state: res.state,
270
+ stateVersion: res.stateVersion,
271
+ replayed: res.replayed,
272
+ correlationId: res.correlationId,
273
+ links: res.links,
274
+ };
275
+ return;
276
+ }
277
+
278
+ // 4. Operations List (`GET /operations`)
279
+ if (method === 'GET' && subPath === '/operations') {
280
+ ctx.status = 200;
281
+ ctx.body = await service.orchestrator.listOperations({
282
+ tenantId: principal.tenantId,
283
+ state: typeof ctx.query.state === 'string' ? ctx.query.state : undefined,
284
+ businessId: typeof ctx.query.business === 'string' ? ctx.query.business : undefined,
285
+ action: typeof ctx.query.action === 'string' ? ctx.query.action : undefined,
286
+ from: typeof ctx.query.from === 'string' ? ctx.query.from : undefined,
287
+ to: typeof ctx.query.to === 'string' ? ctx.query.to : undefined,
288
+ limit: typeof ctx.query.limit === 'string' ? Number(ctx.query.limit) : undefined,
289
+ cursor: typeof ctx.query.cursor === 'string' ? ctx.query.cursor : undefined,
290
+ urlPrefix,
291
+ });
292
+ return;
293
+ }
294
+
295
+ // 5. Operation Detail / Cancel / Resume / Result
296
+ const opDetailMatch = /^\/operations\/([^/]+)$/.exec(subPath);
297
+ if (method === 'GET' && opDetailMatch) {
298
+ const operationId = decodeURIComponent(opDetailMatch[1]);
299
+ const waitSec = typeof ctx.query.wait === 'string' ? Number(ctx.query.wait) : 0;
300
+ ctx.status = 200;
301
+ ctx.body = await service.orchestrator.waitForOperation(principal.tenantId, operationId, waitSec, urlPrefix);
302
+ return;
303
+ }
304
+
305
+ const opActionMatch = /^\/operations\/([^/]+)\/(cancel|resume|result)$/.exec(subPath);
306
+ if (opActionMatch) {
307
+ const operationId = decodeURIComponent(opActionMatch[1]);
308
+ const subAction = opActionMatch[2];
309
+ if (method === 'POST' && subAction === 'cancel') {
310
+ const res = await service.orchestrator.cancelOperation(principal.tenantId, operationId);
311
+ ctx.status = res.httpStatus;
312
+ ctx.body = {
313
+ operationId: res.operationId,
314
+ state: res.state,
315
+ stateVersion: res.stateVersion,
316
+ replayed: res.replayed,
317
+ };
318
+ return;
319
+ }
320
+ if (method === 'POST' && subAction === 'resume') {
321
+ const body = await readJsonBody(ctx);
322
+ const resumeInput = isRecord(body.input) ? body.input : {};
323
+ const res = await service.orchestrator.resumeOperation({
324
+ tenantId: principal.tenantId,
325
+ operationId,
326
+ waitId: typeof body.waitId === 'string' ? body.waitId : undefined,
327
+ expectedStateVersion:
328
+ body.expectedStateVersion !== undefined ? Number(body.expectedStateVersion) : undefined,
329
+ input: resumeInput,
330
+ urlPrefix,
331
+ });
332
+ ctx.status = res.httpStatus;
333
+ ctx.body = res;
334
+ return;
335
+ }
336
+ if (method === 'GET' && subAction === 'result') {
337
+ ctx.status = 200;
338
+ ctx.body = await service.orchestrator.getOperationResult(principal.tenantId, operationId);
339
+ return;
340
+ }
341
+ }
342
+
343
+ // 6. Artifact Download (`GET /artifacts/:artifactId/download`)
344
+ const artifactDownloadMatch = /^\/artifacts\/([^/]+)\/download$/.exec(subPath);
345
+ if (method === 'GET' && artifactDownloadMatch) {
346
+ const artifactId = decodeURIComponent(artifactDownloadMatch[1]);
347
+ const record = await service.orchestrator.artifactStorage.getArtifactOrThrow(principal.tenantId, artifactId);
348
+ const bytes = service.orchestrator.artifactStorage.readArtifactBuffer(record);
349
+ ctx.status = 200;
350
+ ctx.type = record.mimeType || 'application/octet-stream';
351
+ ctx.set('Content-Length', String(bytes.length));
352
+ ctx.set('Content-Disposition', `inline; filename="${encodeURIComponent(record.fileName)}"`);
353
+ ctx.body = bytes;
354
+ return;
355
+ }
356
+
357
+ // 7. Usage Summary & Events (`GET /usage/summary`, `GET /usage/events`)
358
+ if (method === 'GET' && subPath === '/usage/summary') {
359
+ ctx.status = 200;
360
+ ctx.body = await service.orchestrator.getUsageSummary({
361
+ tenantId: principal.tenantId,
362
+ from: String(ctx.query.from || ''),
363
+ to: String(ctx.query.to || ''),
364
+ });
365
+ return;
366
+ }
367
+
368
+ if (method === 'GET' && subPath === '/usage/events') {
369
+ ctx.status = 200;
370
+ ctx.body = await service.orchestrator.listUsageEvents({
371
+ tenantId: principal.tenantId,
372
+ operationId: typeof ctx.query.operationId === 'string' ? ctx.query.operationId : undefined,
373
+ provider: typeof ctx.query.provider === 'string' ? ctx.query.provider : undefined,
374
+ model: typeof ctx.query.model === 'string' ? ctx.query.model : undefined,
375
+ action: typeof ctx.query.action === 'string' ? ctx.query.action : undefined,
376
+ limit: typeof ctx.query.limit === 'string' ? Number(ctx.query.limit) : undefined,
377
+ });
378
+ return;
379
+ }
380
+
381
+ // 8. Legacy Compatibility Facade (`POST /docs/:action` & `POST /docs/workflows`)
382
+ const legacyDocsMatch = /^\/docs\/([^/]+)$/.exec(subPath);
383
+ if (method === 'POST' && legacyDocsMatch) {
384
+ const target = decodeURIComponent(legacyDocsMatch[1]);
385
+ await legacyMultipartUpload(ctx, async () => undefined);
386
+ const rawFields = isRecord(ctx.request.body) ? ctx.request.body : {};
387
+ const uploadedFiles = Array.isArray((ctx.request as Context['request'] & { files?: unknown }).files)
388
+ ? (ctx.request as Context['request'] & { files: Array<Record<string, unknown>> }).files
389
+ : [];
390
+
391
+ const artifactRefs = [];
392
+ for (const f of uploadedFiles) {
393
+ if (Buffer.isBuffer(f.buffer)) {
394
+ const created = await service.orchestrator.artifactStorage.createReadyArtifactFromBuffer({
395
+ tenantId: principal.tenantId,
396
+ fileName: String(f.originalname || 'upload.bin'),
397
+ mimeType: String(f.mimetype || 'application/octet-stream'),
398
+ buffer: f.buffer,
399
+ userId: principal.userId,
400
+ });
401
+ artifactRefs.push({ artifactId: created.artifactId, role: 'input' as const });
402
+ }
403
+ }
404
+
405
+ const parsedFields: Record<string, unknown> = {};
406
+ for (const [k, v] of Object.entries(rawFields)) {
407
+ if (typeof v === 'string' && (v.startsWith('{') || v.startsWith('['))) {
408
+ try {
409
+ parsedFields[k] = JSON.parse(v);
410
+ continue;
411
+ } catch {
412
+ // Keep string value
413
+ }
414
+ }
415
+ parsedFields[k] = v;
416
+ }
417
+
418
+ const isWorkflowFacade = target === 'workflows';
419
+ const processName = String(parsedFields.process || 'disbursement');
420
+ const businessId = isWorkflowFacade && processName === 'lc-checker' ? 'lc-checker' : 'document-core';
421
+ const actionName = isWorkflowFacade ? processName : target;
422
+ const syncMode = ctx.query.sync === 'true';
423
+
424
+ const submitted = await service.orchestrator.submitOperation({
425
+ principal,
426
+ businessId,
427
+ action: actionName,
428
+ submission: {
429
+ input: parsedFields,
430
+ artifacts: artifactRefs,
431
+ },
432
+ idempotencyKey: ctx.get('Idempotency-Key') || undefined,
433
+ correlationId,
434
+ urlPrefix,
435
+ waitCompletionMs: syncMode ? 30_000 : 0,
436
+ });
437
+
438
+ const latest = await service.orchestrator.getOperationRecordOrThrow(principal.tenantId, submitted.operationId);
439
+ const isDone = latest.state === 'SUCCEEDED';
440
+ ctx.status = isDone ? 200 : 202;
441
+ ctx.body = {
442
+ name: `operations/${submitted.operationId}`,
443
+ done: isDone,
444
+ metadata: {
445
+ processor: actionName,
446
+ state: latest.state,
447
+ createdAt: latest.createdAt,
448
+ },
449
+ ...(isDone ? { result: latest.outputPayload } : {}),
450
+ };
451
+ return;
452
+ }
453
+
454
+ throw new DuHttpError(createProblem(404, 'NOT_FOUND', `Gateway route ${method} ${subPath} not found`));
455
+ } catch (err: unknown) {
456
+ const problem =
457
+ err instanceof DuHttpError
458
+ ? { ...err.problem, correlationId: err.problem.correlationId || correlationId }
459
+ : createProblem(500, 'INTERNAL_ERROR', err instanceof Error ? err.message : String(err), { correlationId });
460
+ ctx.status = problem.status;
461
+ ctx.type = 'application/problem+json';
462
+ ctx.body = problem;
463
+ }
464
+ };
465
+ }