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
@@ -0,0 +1,1359 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+
3
+ import * as crypto from 'crypto';
4
+ import { EventEmitter } from 'events';
5
+ import { isIP } from 'net';
6
+ import axios from 'axios';
7
+ import type { Application } from '@nocobase/server';
8
+ import type { Database } from '@nocobase/database';
9
+ import {
10
+ createProblem,
11
+ TERMINAL_OPERATION_STATES,
12
+ type ArtifactEnvelopeItem,
13
+ type DocumentInputCoverage,
14
+ type DocumentInputPlan,
15
+ type DocumentInputPlanItem,
16
+ type DuOperationState,
17
+ type OperationProgress,
18
+ type OperationView,
19
+ type PageSelectionSpec,
20
+ type ProblemDetails,
21
+ type ResultEnvelope,
22
+ type SubmissionPayload,
23
+ type UsageMetrics,
24
+ type WaitState,
25
+ } from '../contracts/du-contracts';
26
+ import type { DuApiKeySummary, IssuedDuApiKey, ServiceConfig, UsageSummaryView } from '../types';
27
+ import { ArtifactStorageService, DuHttpError, type ArtifactRecord } from './ArtifactStorageService';
28
+ import { BuiltinBusinessEngine } from './BuiltinBusinessEngine';
29
+ import { ExternalDuReworkClient } from './ExternalDuReworkClient';
30
+
31
+ const OPERATIONS_COLLECTION = 'doc_understanding_operations';
32
+ const API_KEYS_COLLECTION = 'doc_understanding_api_keys';
33
+ const ARTIFACTS_COLLECTION = 'doc_understanding_artifacts';
34
+ const MAX_INLINE_WEBHOOK_RESULT_BYTES = 256 * 1024; // 256 KiB per BRD Section 4.4
35
+
36
+ export interface OperationRecord {
37
+ id?: number;
38
+ operationId: string;
39
+ tenantId: string;
40
+ businessId: string;
41
+ businessVersion: string;
42
+ action: string;
43
+ variant?: string | null;
44
+ state: DuOperationState;
45
+ stateVersion: number;
46
+ correlationId?: string | null;
47
+ clientReference?: string | null;
48
+ idempotencyKey?: string | null;
49
+ requestFingerprint?: string | null;
50
+ submission: SubmissionPayload & { _checkpoint?: Record<string, unknown> };
51
+ progress?: OperationProgress | null;
52
+ waitState?: WaitState | null;
53
+ documentInputPlan?: DocumentInputPlan | null;
54
+ documentInputCoverage?: DocumentInputCoverage | null;
55
+ resultEnvelope?: ResultEnvelope | null;
56
+ outputPayload?: Record<string, unknown> | null;
57
+ usage?: UsageMetrics | null;
58
+ warnings?: string[] | null;
59
+ errorProblem?: ProblemDetails | null;
60
+ externalOperationId?: string | null;
61
+ deadlineAt?: Date | string | null;
62
+ completedAt?: Date | string | null;
63
+ createdAt?: Date | string;
64
+ updatedAt?: Date | string;
65
+ ownedBy?: string | null;
66
+ leaseExpiresAt?: Date | string | null;
67
+ createdById?: number | null;
68
+ }
69
+
70
+ export interface ApiKeyAuthPrincipal {
71
+ kind: 'du_api_key' | 'nocobase_user';
72
+ tenantId: string;
73
+ userId?: number;
74
+ apiKeyId?: number;
75
+ allowedBusinesses: string[];
76
+ allowedActions: string[];
77
+ requestDefaults?: Record<string, unknown> | null;
78
+ lockedFields?: string[] | null;
79
+ }
80
+
81
+ function isRecord(value: unknown): value is Record<string, unknown> {
82
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
83
+ }
84
+
85
+ function toPlain<T>(row: unknown): T {
86
+ if (row && typeof row === 'object' && typeof (row as { toJSON?: () => T }).toJSON === 'function') {
87
+ return (row as { toJSON: () => T }).toJSON();
88
+ }
89
+ return row as T;
90
+ }
91
+
92
+ function sha256String(input: string): string {
93
+ return crypto.createHash('sha256').update(input, 'utf8').digest('hex');
94
+ }
95
+
96
+ function isPrivateOrBlockedHost(hostname: string): boolean {
97
+ const lower = hostname.toLowerCase();
98
+ if (lower === 'localhost' || lower.endsWith('.localhost') || lower.endsWith('.internal')) {
99
+ return true;
100
+ }
101
+ const ipVer = isIP(lower);
102
+ if (ipVer === 4) {
103
+ const parts = lower.split('.').map(Number);
104
+ if (parts[0] === 127 || parts[0] === 10 || parts[0] === 0) return true;
105
+ if (parts[0] === 169 && parts[1] === 254) return true;
106
+ if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
107
+ if (parts[0] === 192 && parts[1] === 168) return true;
108
+ if (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) return true;
109
+ } else if (ipVer === 6) {
110
+ if (lower === '::1' || lower.startsWith('fe80:') || lower.startsWith('fc') || lower.startsWith('fd')) {
111
+ return true;
112
+ }
113
+ }
114
+ return false;
115
+ }
116
+
117
+ function assertSafeOutboundCallbackUrl(rawUrl: string): string {
118
+ let parsed: URL;
119
+ try {
120
+ parsed = new URL(rawUrl);
121
+ } catch {
122
+ throw new DuHttpError(
123
+ createProblem(422, 'INVALID_SCHEMA', 'Invalid callback.url', {
124
+ errors: [{ pointer: '/callback/url', message: 'Must be a valid HTTP(S) URL' }],
125
+ }),
126
+ );
127
+ }
128
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
129
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', 'callback.url must use https:// or http://'));
130
+ }
131
+ if (parsed.username || parsed.password) {
132
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', 'callback.url must not embed credentials'));
133
+ }
134
+ if (isPrivateOrBlockedHost(parsed.hostname)) {
135
+ throw new DuHttpError(
136
+ createProblem(422, 'INVALID_SCHEMA', 'callback.url target host is blocked by egress SSRF policy'),
137
+ );
138
+ }
139
+ return parsed.toString();
140
+ }
141
+
142
+ function resolveBusinessVersion(businessId: string): string {
143
+ if (businessId === 'document-core') return '2.0.0';
144
+ if (businessId === 'lc-checker') return '1.2.0';
145
+ if (businessId === 'example-review') return '1.0.0';
146
+ throw new DuHttpError(createProblem(404, 'NOT_FOUND', `Business "${businessId}" is not registered`));
147
+ }
148
+
149
+ function resolveVariantFromInput(action: string, input: Record<string, unknown>): string | undefined {
150
+ if (action === 'ingest' || action === 'compare') return typeof input.mode === 'string' ? input.mode : undefined;
151
+ if (action === 'extract') return typeof input.type === 'string' ? input.type : undefined;
152
+ if (action === 'analyze' || action === 'generate') return typeof input.task === 'string' ? input.task : undefined;
153
+ if (action === 'transform') {
154
+ return typeof input.variant === 'string'
155
+ ? input.variant
156
+ : typeof input.action === 'string'
157
+ ? input.action
158
+ : undefined;
159
+ }
160
+ return undefined;
161
+ }
162
+
163
+ export class OperationOrchestrator {
164
+ private readonly app: Application;
165
+ private readonly db: Database;
166
+ public readonly artifactStorage: ArtifactStorageService;
167
+ public readonly builtinEngine: BuiltinBusinessEngine;
168
+ private readonly getConfig: () => Promise<ServiceConfig>;
169
+ private readonly nodeId: string;
170
+ private readonly stateEvents = new EventEmitter();
171
+
172
+ constructor(params: {
173
+ app: Application;
174
+ db: Database;
175
+ artifactStorage: ArtifactStorageService;
176
+ builtinEngine: BuiltinBusinessEngine;
177
+ getConfig: () => Promise<ServiceConfig>;
178
+ nodeId: string;
179
+ }) {
180
+ this.app = params.app;
181
+ this.db = params.db;
182
+ this.artifactStorage = params.artifactStorage;
183
+ this.builtinEngine = params.builtinEngine;
184
+ this.getConfig = params.getConfig;
185
+ this.nodeId = params.nodeId;
186
+ this.stateEvents.setMaxListeners(200);
187
+ }
188
+
189
+ /* ─── Gateway API Key Management (Profile-scoped, SHA-256 hashed) ─── */
190
+
191
+ async issueApiKey(params: {
192
+ name: string;
193
+ tenantId?: string;
194
+ allowedBusinesses?: string[];
195
+ allowedActions?: string[];
196
+ requestDefaults?: Record<string, unknown> | null;
197
+ lockedFields?: string[] | null;
198
+ expiresAt?: string | Date | null;
199
+ userId?: number;
200
+ }): Promise<IssuedDuApiKey> {
201
+ if (!params.name || !params.name.trim()) {
202
+ throw new DuHttpError(createProblem(422, 'INVALID_SCHEMA', 'API key name is required'));
203
+ }
204
+ const rawRandom = crypto.randomBytes(24).toString('hex');
205
+ const rawKey = `du_live_${rawRandom}`;
206
+ const keyPrefix = rawKey.slice(0, 16);
207
+ const keyHash = sha256String(rawKey);
208
+ const tenantId = (params.tenantId || 'default').trim() || 'default';
209
+ const allowedBusinesses =
210
+ Array.isArray(params.allowedBusinesses) && params.allowedBusinesses.length > 0
211
+ ? params.allowedBusinesses.map(String)
212
+ : ['*'];
213
+ const allowedActions =
214
+ Array.isArray(params.allowedActions) && params.allowedActions.length > 0
215
+ ? params.allowedActions.map(String)
216
+ : ['*'];
217
+
218
+ const created = await this.db.getRepository(API_KEYS_COLLECTION).create({
219
+ values: {
220
+ name: params.name.trim(),
221
+ keyPrefix,
222
+ keyHash,
223
+ tenantId,
224
+ allowedBusinesses,
225
+ allowedActions,
226
+ requestDefaults: params.requestDefaults ?? null,
227
+ lockedFields: params.lockedFields ?? null,
228
+ status: 'active',
229
+ expiresAt: params.expiresAt ?? null,
230
+ createdById: params.userId ?? null,
231
+ },
232
+ });
233
+ const record = toPlain<DuApiKeySummary & { id: number }>(created);
234
+ return {
235
+ id: record.id,
236
+ name: record.name,
237
+ keyPrefix,
238
+ tenantId,
239
+ allowedBusinesses,
240
+ allowedActions,
241
+ requestDefaults: record.requestDefaults ?? null,
242
+ lockedFields: record.lockedFields ?? null,
243
+ status: 'active',
244
+ expiresAt: record.expiresAt ?? null,
245
+ lastUsedAt: null,
246
+ createdAt: record.createdAt,
247
+ rawKey,
248
+ };
249
+ }
250
+
251
+ async listApiKeys(): Promise<DuApiKeySummary[]> {
252
+ const rows = await this.db.getRepository(API_KEYS_COLLECTION).find({
253
+ sort: ['-createdAt'],
254
+ });
255
+ return rows.map((row: unknown) => {
256
+ const plain = toPlain<DuApiKeySummary & { keyHash?: string }>(row);
257
+ const { keyHash: _omitted, ...safe } = plain;
258
+ return safe;
259
+ });
260
+ }
261
+
262
+ async revokeApiKey(id: number): Promise<void> {
263
+ await this.db.getRepository(API_KEYS_COLLECTION).update({
264
+ filterByTk: id,
265
+ values: { status: 'revoked' },
266
+ });
267
+ }
268
+
269
+ async authenticateRawApiKey(rawKey: string): Promise<ApiKeyAuthPrincipal> {
270
+ const trimmed = rawKey.trim();
271
+ if (!trimmed) {
272
+ throw new DuHttpError(createProblem(401, 'UNAUTHENTICATED', 'Missing x-api-key header'));
273
+ }
274
+ const keyHash = sha256String(trimmed);
275
+ const repo = this.db.getRepository(API_KEYS_COLLECTION);
276
+ const row = await repo.findOne({ filter: { keyHash } });
277
+ if (!row) {
278
+ throw new DuHttpError(createProblem(401, 'UNAUTHENTICATED', 'Invalid API key'));
279
+ }
280
+ const record = toPlain<{
281
+ id: number;
282
+ tenantId: string;
283
+ status: string;
284
+ expiresAt?: string | Date | null;
285
+ allowedBusinesses?: string[];
286
+ allowedActions?: string[];
287
+ requestDefaults?: Record<string, unknown> | null;
288
+ lockedFields?: string[] | null;
289
+ createdById?: number | null;
290
+ }>(row);
291
+
292
+ if (record.status !== 'active') {
293
+ throw new DuHttpError(createProblem(401, 'UNAUTHENTICATED', 'API key has been revoked'));
294
+ }
295
+ if (record.expiresAt && new Date(record.expiresAt).getTime() <= Date.now()) {
296
+ throw new DuHttpError(createProblem(401, 'UNAUTHENTICATED', 'API key has expired'));
297
+ }
298
+
299
+ try {
300
+ await repo.update({
301
+ filterByTk: record.id,
302
+ values: { lastUsedAt: new Date() },
303
+ });
304
+ } catch {
305
+ // Non-fatal metadata update
306
+ }
307
+
308
+ return {
309
+ kind: 'du_api_key',
310
+ apiKeyId: record.id,
311
+ tenantId: record.tenantId || 'default',
312
+ userId: record.createdById ?? undefined,
313
+ allowedBusinesses: Array.isArray(record.allowedBusinesses) ? record.allowedBusinesses : ['*'],
314
+ allowedActions: Array.isArray(record.allowedActions) ? record.allowedActions : ['*'],
315
+ requestDefaults: record.requestDefaults ?? null,
316
+ lockedFields: record.lockedFields ?? null,
317
+ };
318
+ }
319
+
320
+ private assertActionPermitted(principal: ApiKeyAuthPrincipal, businessId: string, action: string): void {
321
+ const bizOk = principal.allowedBusinesses.includes('*') || principal.allowedBusinesses.includes(businessId);
322
+ const actOk =
323
+ principal.allowedActions.includes('*') ||
324
+ principal.allowedActions.includes(action) ||
325
+ principal.allowedActions.includes(`${businessId}:${action}`);
326
+ if (!bizOk || !actOk) {
327
+ throw new DuHttpError(
328
+ createProblem(
329
+ 403,
330
+ 'PERMISSION_DENIED',
331
+ `API key profile does not grant permission for ${businessId}/${action}`,
332
+ ),
333
+ );
334
+ }
335
+ }
336
+
337
+ private applyProfilePolicyToInput(
338
+ principal: ApiKeyAuthPrincipal,
339
+ callerInput: Record<string, unknown>,
340
+ ): Record<string, unknown> {
341
+ const defaults = isRecord(principal.requestDefaults) ? principal.requestDefaults : {};
342
+ const locked = Array.isArray(principal.lockedFields) ? principal.lockedFields : [];
343
+
344
+ for (const lockedKey of locked) {
345
+ if (
346
+ Object.prototype.hasOwnProperty.call(callerInput, lockedKey) &&
347
+ Object.prototype.hasOwnProperty.call(defaults, lockedKey) &&
348
+ JSON.stringify(callerInput[lockedKey]) !== JSON.stringify(defaults[lockedKey])
349
+ ) {
350
+ throw new DuHttpError(
351
+ createProblem(403, 'PERMISSION_DENIED', `Parameter "${lockedKey}" is locked by profile policy`),
352
+ );
353
+ }
354
+ }
355
+
356
+ return {
357
+ ...defaults,
358
+ ...callerInput,
359
+ };
360
+ }
361
+
362
+ /* ─── Canonical Operation Submission & Execution ─────────────────── */
363
+
364
+ async submitOperation(params: {
365
+ principal: ApiKeyAuthPrincipal;
366
+ businessId: string;
367
+ action: string;
368
+ submission: SubmissionPayload;
369
+ idempotencyKey?: string;
370
+ correlationId?: string;
371
+ urlPrefix?: string;
372
+ waitCompletionMs?: number;
373
+ }): Promise<{
374
+ httpStatus: 200 | 202;
375
+ operationId: string;
376
+ state: DuOperationState;
377
+ stateVersion: number;
378
+ replayed: boolean;
379
+ correlationId: string;
380
+ links: { self: string; result: string };
381
+ }> {
382
+ const { principal, businessId, action, submission, idempotencyKey, urlPrefix = '/api/du/v1' } = params;
383
+ const businessVersion = resolveBusinessVersion(businessId);
384
+ this.assertActionPermitted(principal, businessId, action);
385
+
386
+ if (!isRecord(submission) || !isRecord(submission.input)) {
387
+ throw new DuHttpError(
388
+ createProblem(422, 'INVALID_SCHEMA', 'Request body must include an "input" object', {
389
+ errors: [{ pointer: '/input', message: 'Expected object' }],
390
+ }),
391
+ );
392
+ }
393
+
394
+ if (submission.callback?.url) {
395
+ assertSafeOutboundCallbackUrl(submission.callback.url);
396
+ }
397
+
398
+ const effectiveInput = this.applyProfilePolicyToInput(principal, submission.input);
399
+ const correlationId = (params.correlationId || crypto.randomUUID()).trim();
400
+ const fingerprint = sha256String(
401
+ JSON.stringify({
402
+ businessId,
403
+ action,
404
+ input: effectiveInput,
405
+ artifacts: submission.artifacts || [],
406
+ documentSelection: submission.documentSelection || null,
407
+ sourceUrl: submission.sourceUrl || null,
408
+ }),
409
+ );
410
+
411
+ const opsRepo = this.db.getRepository(OPERATIONS_COLLECTION);
412
+ if (idempotencyKey && idempotencyKey.trim()) {
413
+ const existingRow = await opsRepo.findOne({
414
+ filter: { tenantId: principal.tenantId, idempotencyKey: idempotencyKey.trim() },
415
+ });
416
+ if (existingRow) {
417
+ const existing = toPlain<OperationRecord>(existingRow);
418
+ if (existing.requestFingerprint && existing.requestFingerprint !== fingerprint) {
419
+ throw new DuHttpError(
420
+ createProblem(
421
+ 409,
422
+ 'IDEMPOTENCY_CONFLICT',
423
+ 'Idempotency-Key was already used with a different request payload',
424
+ { correlationId },
425
+ ),
426
+ );
427
+ }
428
+ return {
429
+ httpStatus: 200,
430
+ operationId: existing.operationId,
431
+ state: existing.state,
432
+ stateVersion: existing.stateVersion,
433
+ replayed: true,
434
+ correlationId: existing.correlationId || correlationId,
435
+ links: {
436
+ self: `${urlPrefix}/operations/${existing.operationId}`,
437
+ result: `${urlPrefix}/operations/${existing.operationId}/result`,
438
+ },
439
+ };
440
+ }
441
+ }
442
+
443
+ const config = await this.getConfig();
444
+ const maxFiles = config.maxFilesPerRequest ?? 20;
445
+ const maxBytes = config.maxFileSizeBytes ?? 10 * 1024 * 1024;
446
+ const artifactRefs = Array.isArray(submission.artifacts) ? submission.artifacts : [];
447
+
448
+ if (artifactRefs.length > maxFiles) {
449
+ throw new DuHttpError(
450
+ createProblem(422, 'INVALID_SCHEMA', `Too many input artifacts (${artifactRefs.length} > max ${maxFiles})`, {
451
+ correlationId,
452
+ }),
453
+ );
454
+ }
455
+
456
+ // Validate all input artifacts belong to tenant & are READY, and build DI-06 DocumentInputPlan
457
+ const resolvedArtifacts: ArtifactRecord[] = [];
458
+ for (const ref of artifactRefs) {
459
+ if (!ref || typeof ref.artifactId !== 'string') {
460
+ throw new DuHttpError(
461
+ createProblem(422, 'INVALID_SCHEMA', 'Each artifact reference must specify artifactId', { correlationId }),
462
+ );
463
+ }
464
+ const record = await this.artifactStorage.getArtifactOrThrow(principal.tenantId, ref.artifactId);
465
+ if (record.state !== 'READY') {
466
+ throw new DuHttpError(
467
+ createProblem(409, 'STATE_CONFLICT', `Artifact ${ref.artifactId} is not READY (state=${record.state})`, {
468
+ correlationId,
469
+ }),
470
+ );
471
+ }
472
+ if (record.sizeBytes > maxBytes) {
473
+ throw new DuHttpError(
474
+ createProblem(
475
+ 413,
476
+ 'PAYLOAD_TOO_LARGE',
477
+ `Artifact ${ref.artifactId} (${record.sizeBytes} bytes) exceeds documentInput policy limit (${maxBytes} bytes)`,
478
+ { correlationId },
479
+ ),
480
+ );
481
+ }
482
+ resolvedArtifacts.push(record);
483
+ }
484
+
485
+ const documentInputPlan = this.buildDocumentInputPlan(resolvedArtifacts, submission);
486
+ const operationId = crypto.randomUUID();
487
+ const deadlineMs = config.pollTimeout || 300_000;
488
+ const deadlineAt = new Date(Date.now() + deadlineMs);
489
+
490
+ await opsRepo.create({
491
+ values: {
492
+ operationId,
493
+ tenantId: principal.tenantId,
494
+ businessId,
495
+ businessVersion,
496
+ action,
497
+ variant: resolveVariantFromInput(action, effectiveInput) ?? null,
498
+ state: 'ACCEPTED',
499
+ stateVersion: 1,
500
+ correlationId,
501
+ clientReference: submission.clientReference ?? null,
502
+ idempotencyKey: idempotencyKey?.trim() || null,
503
+ requestFingerprint: fingerprint,
504
+ submission: {
505
+ ...submission,
506
+ input: effectiveInput,
507
+ },
508
+ progress: { percent: 0, message: 'ACCEPTED' },
509
+ documentInputPlan,
510
+ deadlineAt,
511
+ ownedBy: this.nodeId,
512
+ leaseExpiresAt: new Date(Date.now() + 10 * 60 * 1000),
513
+ createdById: principal.userId ?? null,
514
+ },
515
+ });
516
+
517
+ // Attach operationId to input artifacts that don't have one yet
518
+ if (resolvedArtifacts.length > 0) {
519
+ await this.db.getRepository(ARTIFACTS_COLLECTION).update({
520
+ filter: {
521
+ tenantId: principal.tenantId,
522
+ artifactId: { $in: resolvedArtifacts.map((a) => a.artifactId) },
523
+ operationId: null,
524
+ },
525
+ values: { operationId },
526
+ });
527
+ }
528
+
529
+ const executionPromise = this.runOperationInBackground(operationId, resolvedArtifacts, urlPrefix);
530
+ executionPromise.catch((err) => {
531
+ this.app.logger?.error?.(`Document Understanding operation ${operationId} background failure`, err);
532
+ });
533
+
534
+ if (params.waitCompletionMs && params.waitCompletionMs > 0) {
535
+ await this.waitForOperation(
536
+ principal.tenantId,
537
+ operationId,
538
+ Math.ceil(params.waitCompletionMs / 1000),
539
+ urlPrefix,
540
+ );
541
+ const latest = await this.getOperationRecordOrThrow(principal.tenantId, operationId);
542
+ return {
543
+ httpStatus: 202,
544
+ operationId,
545
+ state: latest.state,
546
+ stateVersion: latest.stateVersion,
547
+ replayed: false,
548
+ correlationId,
549
+ links: {
550
+ self: `${urlPrefix}/operations/${operationId}`,
551
+ result: `${urlPrefix}/operations/${operationId}/result`,
552
+ },
553
+ };
554
+ }
555
+
556
+ return {
557
+ httpStatus: 202,
558
+ operationId,
559
+ state: 'ACCEPTED',
560
+ stateVersion: 1,
561
+ replayed: false,
562
+ correlationId,
563
+ links: {
564
+ self: `${urlPrefix}/operations/${operationId}`,
565
+ result: `${urlPrefix}/operations/${operationId}/result`,
566
+ },
567
+ };
568
+ }
569
+
570
+ private buildDocumentInputPlan(artifacts: ArtifactRecord[], submission: SubmissionPayload): DocumentInputPlan {
571
+ const sel = submission.documentSelection;
572
+ let selectedArtifacts = artifacts;
573
+ if (sel?.artifactIds && sel.artifactIds.length > 0) {
574
+ const allowedSet = new Set(sel.artifactIds);
575
+ selectedArtifacts = artifacts.filter((a) => allowedSet.has(a.artifactId));
576
+ }
577
+
578
+ const items: DocumentInputPlanItem[] = selectedArtifacts.map((artifact) => {
579
+ const explicitPageSel = sel?.pageSelections?.find((p) => p.artifactId === artifact.artifactId);
580
+ const selection: PageSelectionSpec = explicitPageSel ? explicitPageSel.selection : { kind: 'all' };
581
+ return {
582
+ artifactId: artifact.artifactId,
583
+ fileName: artifact.fileName,
584
+ mimeType: artifact.mimeType,
585
+ selection,
586
+ };
587
+ });
588
+
589
+ return {
590
+ kind: 'documentInputPlan',
591
+ schemaVersion: 1,
592
+ items,
593
+ };
594
+ }
595
+
596
+ private async runOperationInBackground(
597
+ operationId: string,
598
+ preloadedArtifacts?: ArtifactRecord[],
599
+ urlPrefix = '/api/du/v1',
600
+ resumedInput?: Record<string, unknown>,
601
+ ): Promise<void> {
602
+ const opsRepo = this.db.getRepository(OPERATIONS_COLLECTION);
603
+ const row = await opsRepo.findOne({ filter: { operationId } });
604
+ if (!row) return;
605
+ const op = toPlain<OperationRecord>(row);
606
+
607
+ if (TERMINAL_OPERATION_STATES.has(op.state)) return;
608
+ if (op.state === 'CANCEL_REQUESTED') {
609
+ await this.transitionOperation(operationId, {
610
+ state: 'CANCELLED',
611
+ progress: { percent: 100, message: 'CANCELLED' },
612
+ completedAt: new Date(),
613
+ });
614
+ return;
615
+ }
616
+
617
+ await this.transitionOperation(operationId, {
618
+ state: 'RUNNING',
619
+ progress: { percent: 10, message: 'RUNNING' },
620
+ ownedBy: this.nodeId,
621
+ leaseExpiresAt: new Date(Date.now() + 10 * 60 * 1000),
622
+ });
623
+
624
+ const config = await this.getConfig();
625
+ const artifacts =
626
+ preloadedArtifacts ??
627
+ (await Promise.all(
628
+ (op.submission.artifacts || []).map((ref) =>
629
+ this.artifactStorage.getArtifactOrThrow(op.tenantId, ref.artifactId),
630
+ ),
631
+ ));
632
+
633
+ try {
634
+ const shouldUseExternalGateway =
635
+ config.engineMode === 'du_rework' ||
636
+ (config.engineMode === 'hybrid' &&
637
+ !this.builtinEngine.resolveAiManager() &&
638
+ Boolean(config.baseUrl) &&
639
+ config.baseUrl !== 'http://localhost:8000');
640
+
641
+ if (shouldUseExternalGateway) {
642
+ await this.executeViaExternalGateway(op, artifacts, config, urlPrefix, resumedInput);
643
+ return;
644
+ }
645
+
646
+ const planItems = op.documentInputPlan?.items || [];
647
+ const outcome = await this.builtinEngine.execute({
648
+ operationId,
649
+ tenantId: op.tenantId,
650
+ businessId: op.businessId,
651
+ action: op.action,
652
+ input: op.submission.input,
653
+ artifacts,
654
+ planItems,
655
+ config,
656
+ resumedInput,
657
+ checkpointData: op.submission._checkpoint,
658
+ userId: op.createdById ?? undefined,
659
+ onProgress: async (percent, message) => {
660
+ await opsRepo.update({
661
+ filter: { operationId },
662
+ values: { progress: { percent, message } },
663
+ });
664
+ },
665
+ });
666
+
667
+ // Re-read to check if cancel was requested mid-flight
668
+ const refreshedRow = await opsRepo.findOne({ filter: { operationId } });
669
+ const refreshed = refreshedRow ? toPlain<OperationRecord>(refreshedRow) : op;
670
+ if (refreshed.state === 'CANCEL_REQUESTED') {
671
+ await this.transitionOperation(operationId, {
672
+ state: 'CANCELLED',
673
+ progress: { percent: 100, message: 'CANCELLED' },
674
+ completedAt: new Date(),
675
+ });
676
+ await this.dispatchCallbackIfConfigured(operationId, urlPrefix);
677
+ return;
678
+ }
679
+
680
+ if (outcome.kind === 'waiting_input') {
681
+ await this.transitionOperation(operationId, {
682
+ state: 'WAITING_INPUT',
683
+ progress: { percent: 50, message: 'WAITING_INPUT' },
684
+ waitState: outcome.waitState,
685
+ usage: outcome.usage,
686
+ submission: {
687
+ ...op.submission,
688
+ _checkpoint: outcome.checkpointData,
689
+ },
690
+ leaseExpiresAt: null,
691
+ });
692
+ await this.dispatchCallbackIfConfigured(operationId, urlPrefix);
693
+ return;
694
+ }
695
+
696
+ const outputArtifact = await this.artifactStorage.createJsonOutputArtifact({
697
+ tenantId: op.tenantId,
698
+ operationId,
699
+ payload: outcome.outputPayload,
700
+ userId: op.createdById ?? undefined,
701
+ });
702
+
703
+ const planDigest = `sha256:${sha256String(JSON.stringify(op.documentInputPlan || {}))}`;
704
+ const coverageOutcomes = outcome.coverageOutcomes.map((item) => ({
705
+ ...item,
706
+ outputRefs: item.outputRefs.length > 0 ? item.outputRefs : [outputArtifact.artifactId],
707
+ }));
708
+ const coverageStatus = coverageOutcomes.some((c) => c.status === 'failed') ? 'failed' : 'complete';
709
+ const documentInputCoverage: DocumentInputCoverage = {
710
+ kind: 'coverageReport',
711
+ schemaVersion: 1,
712
+ planDigest,
713
+ status: coverageStatus,
714
+ outcomes: coverageOutcomes,
715
+ };
716
+
717
+ // DI-06 strict invariant: partial coverage failure fails the operation
718
+ if (coverageStatus === 'failed') {
719
+ throw new DuHttpError(
720
+ createProblem(422, 'INCOMPLETE_DOCUMENT_COVERAGE', 'One or more selected document pages failed processing'),
721
+ );
722
+ }
723
+
724
+ const envelopeArtifacts: ArtifactEnvelopeItem[] = [
725
+ ...artifacts.map((a) => ({
726
+ artifactId: a.artifactId,
727
+ role: a.role,
728
+ fileName: a.fileName,
729
+ mimeType: a.mimeType,
730
+ sizeBytes: a.sizeBytes,
731
+ hashSha256: a.hashSha256 || '',
732
+ download: `${urlPrefix}/artifacts/${a.artifactId}/download`,
733
+ })),
734
+ {
735
+ artifactId: outputArtifact.artifactId,
736
+ role: 'output',
737
+ fileName: outputArtifact.fileName,
738
+ mimeType: outputArtifact.mimeType,
739
+ sizeBytes: outputArtifact.sizeBytes,
740
+ hashSha256: outputArtifact.hashSha256 || '',
741
+ download: `${urlPrefix}/artifacts/${outputArtifact.artifactId}/download`,
742
+ },
743
+ ...outcome.extraOutputArtifacts.map((extra) => ({
744
+ artifactId: extra.artifactId,
745
+ role: 'output' as const,
746
+ fileName: extra.fileName,
747
+ mimeType: extra.mimeType,
748
+ sizeBytes: extra.sizeBytes,
749
+ hashSha256: extra.hashSha256 || '',
750
+ download: `${urlPrefix}/artifacts/${extra.artifactId}/download`,
751
+ })),
752
+ ];
753
+
754
+ const resultEnvelope: ResultEnvelope = {
755
+ schemaVersion: '1',
756
+ data: {
757
+ resultRef: `artifact://${outputArtifact.artifactId}`,
758
+ },
759
+ artifacts: envelopeArtifacts,
760
+ usage: outcome.usage,
761
+ warnings: outcome.warnings,
762
+ };
763
+
764
+ await this.transitionOperation(operationId, {
765
+ state: 'SUCCEEDED',
766
+ progress: { percent: 100, message: 'SUCCEEDED' },
767
+ documentInputCoverage,
768
+ resultEnvelope,
769
+ outputPayload: outcome.outputPayload,
770
+ usage: outcome.usage,
771
+ warnings: outcome.warnings,
772
+ waitState: null,
773
+ completedAt: new Date(),
774
+ leaseExpiresAt: null,
775
+ });
776
+
777
+ await this.dispatchCallbackIfConfigured(operationId, urlPrefix);
778
+ } catch (err: unknown) {
779
+ const problem =
780
+ err instanceof DuHttpError
781
+ ? err.problem
782
+ : createProblem(500, 'INTERNAL_ERROR', err instanceof Error ? err.message : String(err), {
783
+ correlationId: op.correlationId ?? undefined,
784
+ });
785
+ await this.transitionOperation(operationId, {
786
+ state: 'FAILED',
787
+ progress: { percent: 100, message: problem.title },
788
+ errorProblem: problem,
789
+ completedAt: new Date(),
790
+ leaseExpiresAt: null,
791
+ });
792
+ await this.dispatchCallbackIfConfigured(operationId, urlPrefix);
793
+ }
794
+ }
795
+
796
+ private async executeViaExternalGateway(
797
+ op: OperationRecord,
798
+ artifacts: ArtifactRecord[],
799
+ config: ServiceConfig,
800
+ urlPrefix: string,
801
+ resumedInput?: Record<string, unknown>,
802
+ ): Promise<void> {
803
+ const client = new ExternalDuReworkClient(config);
804
+ let remoteOpId = op.externalOperationId || undefined;
805
+
806
+ if (!remoteOpId) {
807
+ const remoteRefs = [];
808
+ for (const art of artifacts) {
809
+ const buf = this.artifactStorage.readArtifactBuffer(art);
810
+ const remoteArtId = await client.uploadArtifact(art, buf);
811
+ remoteRefs.push({ artifactId: remoteArtId, role: art.role });
812
+ }
813
+ const submitted = await client.submitAction({
814
+ businessId: op.businessId,
815
+ action: op.action,
816
+ input: op.submission.input,
817
+ artifacts: remoteRefs,
818
+ documentSelection: op.submission.documentSelection,
819
+ sourceUrl: op.submission.sourceUrl,
820
+ clientReference: op.clientReference ?? undefined,
821
+ correlationId: op.correlationId ?? undefined,
822
+ idempotencyKey: `proxy-${op.operationId}`,
823
+ });
824
+ remoteOpId = submitted.operationId;
825
+ await this.db.getRepository(OPERATIONS_COLLECTION).update({
826
+ filter: { operationId: op.operationId },
827
+ values: { externalOperationId: remoteOpId },
828
+ });
829
+ } else if (resumedInput && op.waitState) {
830
+ await client.resumeOperation(remoteOpId, {
831
+ waitId: op.waitState.waitId,
832
+ expectedStateVersion: op.stateVersion,
833
+ input: resumedInput,
834
+ });
835
+ }
836
+
837
+ const startTime = Date.now();
838
+ const timeoutMs = config.pollTimeout || 300_000;
839
+ const pollIntervalMs = config.pollInterval || 3_000;
840
+
841
+ while (Date.now() - startTime < timeoutMs) {
842
+ const remoteView = await client.getOperation(remoteOpId);
843
+ if (remoteView.state === 'WAITING_INPUT') {
844
+ await this.transitionOperation(op.operationId, {
845
+ state: 'WAITING_INPUT',
846
+ progress: remoteView.progress || { percent: 50, message: 'WAITING_INPUT' },
847
+ waitState: remoteView.wait || { waitId: 'external-wait' },
848
+ leaseExpiresAt: null,
849
+ });
850
+ await this.dispatchCallbackIfConfigured(op.operationId, urlPrefix);
851
+ return;
852
+ }
853
+ if (remoteView.state === 'SUCCEEDED') {
854
+ const { envelope, outputPayload } = await client.fetchResultAndPayload(remoteOpId);
855
+ const localOutputArtifact = await this.artifactStorage.createJsonOutputArtifact({
856
+ tenantId: op.tenantId,
857
+ operationId: op.operationId,
858
+ payload: outputPayload,
859
+ userId: op.createdById ?? undefined,
860
+ });
861
+ const localEnvelope: ResultEnvelope = {
862
+ schemaVersion: '1',
863
+ data: { resultRef: `artifact://${localOutputArtifact.artifactId}` },
864
+ artifacts: [
865
+ {
866
+ artifactId: localOutputArtifact.artifactId,
867
+ role: 'output',
868
+ fileName: localOutputArtifact.fileName,
869
+ mimeType: localOutputArtifact.mimeType,
870
+ sizeBytes: localOutputArtifact.sizeBytes,
871
+ hashSha256: localOutputArtifact.hashSha256 || '',
872
+ download: `${urlPrefix}/artifacts/${localOutputArtifact.artifactId}/download`,
873
+ },
874
+ ],
875
+ usage: envelope.usage,
876
+ warnings: envelope.warnings || [],
877
+ };
878
+ await this.transitionOperation(op.operationId, {
879
+ state: 'SUCCEEDED',
880
+ progress: { percent: 100, message: 'SUCCEEDED' },
881
+ documentInputCoverage: remoteView.documentInputCoverage ?? null,
882
+ resultEnvelope: localEnvelope,
883
+ outputPayload,
884
+ usage: envelope.usage,
885
+ warnings: envelope.warnings || [],
886
+ completedAt: new Date(),
887
+ leaseExpiresAt: null,
888
+ });
889
+ await this.dispatchCallbackIfConfigured(op.operationId, urlPrefix);
890
+ return;
891
+ }
892
+ if (['FAILED', 'CANCELLED', 'TIMED_OUT'].includes(remoteView.state)) {
893
+ await this.transitionOperation(op.operationId, {
894
+ state: remoteView.state,
895
+ progress: { percent: 100, message: remoteView.state },
896
+ errorProblem:
897
+ remoteView.error || createProblem(500, remoteView.state, `Remote operation ended as ${remoteView.state}`),
898
+ completedAt: new Date(),
899
+ leaseExpiresAt: null,
900
+ });
901
+ await this.dispatchCallbackIfConfigured(op.operationId, urlPrefix);
902
+ return;
903
+ }
904
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
905
+ }
906
+
907
+ await this.transitionOperation(op.operationId, {
908
+ state: 'TIMED_OUT',
909
+ progress: { percent: 100, message: 'TIMED_OUT' },
910
+ errorProblem: createProblem(504, 'TIMED_OUT', 'External gateway polling timed out'),
911
+ completedAt: new Date(),
912
+ leaseExpiresAt: null,
913
+ });
914
+ }
915
+
916
+ private async transitionOperation(operationId: string, patch: Partial<OperationRecord>): Promise<void> {
917
+ const repo = this.db.getRepository(OPERATIONS_COLLECTION);
918
+ const currentRow = await repo.findOne({ filter: { operationId } });
919
+ if (!currentRow) return;
920
+ const current = toPlain<OperationRecord>(currentRow);
921
+ const nextVersion = (current.stateVersion || 1) + 1;
922
+
923
+ await repo.update({
924
+ filter: { operationId },
925
+ values: {
926
+ ...patch,
927
+ stateVersion: nextVersion,
928
+ },
929
+ });
930
+
931
+ this.stateEvents.emit(`op:${operationId}`, patch.state || current.state);
932
+ }
933
+
934
+ private async dispatchCallbackIfConfigured(operationId: string, urlPrefix: string): Promise<void> {
935
+ const row = await this.db.getRepository(OPERATIONS_COLLECTION).findOne({ filter: { operationId } });
936
+ if (!row) return;
937
+ const op = toPlain<OperationRecord>(row);
938
+ const callbackUrl = op.submission?.callback?.url;
939
+ if (!callbackUrl) return;
940
+
941
+ try {
942
+ const safeUrl = assertSafeOutboundCallbackUrl(callbackUrl);
943
+ const config = await this.getConfig();
944
+ const deliveryId = crypto.randomUUID();
945
+ const timestamp = Math.floor(Date.now() / 1000).toString();
946
+ const mode = op.submission.callback?.mode || 'notification_only';
947
+
948
+ const payload: Record<string, unknown> = {
949
+ deliveryId,
950
+ operationId: op.operationId,
951
+ state: op.state,
952
+ stateVersion: op.stateVersion,
953
+ businessId: op.businessId,
954
+ action: op.action,
955
+ correlationId: op.correlationId,
956
+ clientReference: op.clientReference,
957
+ ...(op.state === 'WAITING_INPUT' && op.waitState ? { wait: op.waitState } : {}),
958
+ links: {
959
+ self: `${urlPrefix}/operations/${op.operationId}`,
960
+ result: `${urlPrefix}/operations/${op.operationId}/result`,
961
+ },
962
+ };
963
+
964
+ if (mode === 'notification_with_result' && op.state === 'SUCCEEDED' && op.outputPayload) {
965
+ const serializedResult = JSON.stringify(op.outputPayload);
966
+ if (Buffer.byteLength(serializedResult, 'utf8') <= MAX_INLINE_WEBHOOK_RESULT_BYTES) {
967
+ payload.result = op.outputPayload;
968
+ payload.usage = op.usage;
969
+ } else {
970
+ payload.resultTruncatedToLink = true;
971
+ }
972
+ }
973
+
974
+ const rawBody = JSON.stringify(payload);
975
+ const headers: Record<string, string> = {
976
+ 'Content-Type': 'application/json',
977
+ 'x-du-delivery-id': deliveryId,
978
+ 'x-du-timestamp': timestamp,
979
+ };
980
+ if (config.webhookSecret) {
981
+ const hmac = crypto.createHmac('sha256', config.webhookSecret).update(`${timestamp}.${rawBody}`).digest('hex');
982
+ headers['x-du-signature'] = `sha256=${hmac}`;
983
+ }
984
+
985
+ await axios.post(safeUrl, rawBody, {
986
+ headers,
987
+ timeout: 10_000,
988
+ maxRedirects: 0, // CALLBACK_REDIRECTS_ALLOWED = false per BRD Section 4.4
989
+ });
990
+ } catch (err) {
991
+ this.app.logger?.warn?.(`Outbound webhook delivery failed for operation ${operationId}`, err);
992
+ }
993
+ }
994
+
995
+ /* ─── Query, Wait, Resume, Cancel, Result & Usage APIs ──────────── */
996
+
997
+ async getOperationRecordOrThrow(tenantId: string, operationId: string): Promise<OperationRecord> {
998
+ const filter = tenantId === '*' ? { operationId } : { tenantId, operationId };
999
+ const row = await this.db.getRepository(OPERATIONS_COLLECTION).findOne({ filter });
1000
+ if (!row) {
1001
+ // Fail-closed 404 prevents cross-tenant ID enumeration per BRD Section 1.3
1002
+ throw new DuHttpError(createProblem(404, 'NOT_FOUND', `Operation ${operationId} not found`));
1003
+ }
1004
+ return toPlain<OperationRecord>(row);
1005
+ }
1006
+
1007
+ toOperationView(op: OperationRecord, urlPrefix = '/api/du/v1'): OperationView {
1008
+ return {
1009
+ id: op.operationId,
1010
+ name: `operations/${op.operationId}`,
1011
+ businessId: op.businessId,
1012
+ businessVersion: op.businessVersion,
1013
+ action: op.action,
1014
+ state: op.state,
1015
+ stateVersion: op.stateVersion,
1016
+ ...(op.correlationId ? { correlationId: op.correlationId } : {}),
1017
+ ...(op.clientReference ? { clientReference: op.clientReference } : {}),
1018
+ createdAt: op.createdAt ? new Date(op.createdAt).toISOString() : new Date().toISOString(),
1019
+ updatedAt: op.updatedAt ? new Date(op.updatedAt).toISOString() : new Date().toISOString(),
1020
+ ...(op.deadlineAt ? { deadlineAt: new Date(op.deadlineAt).toISOString() } : {}),
1021
+ progress: op.progress || { percent: 0, message: op.state },
1022
+ ...(op.state === 'WAITING_INPUT' && op.waitState ? { wait: op.waitState } : {}),
1023
+ ...(op.documentInputCoverage ? { documentInputCoverage: op.documentInputCoverage } : {}),
1024
+ ...(op.usage ? { usage: op.usage } : {}),
1025
+ ...(op.errorProblem ? { error: op.errorProblem } : {}),
1026
+ links: {
1027
+ self: `${urlPrefix}/operations/${op.operationId}`,
1028
+ result: `${urlPrefix}/operations/${op.operationId}/result`,
1029
+ },
1030
+ };
1031
+ }
1032
+
1033
+ async waitForOperation(
1034
+ tenantId: string,
1035
+ operationId: string,
1036
+ waitSeconds = 0,
1037
+ urlPrefix = '/api/du/v1',
1038
+ ): Promise<OperationView> {
1039
+ const boundedSeconds = Math.max(0, Math.min(30, Number(waitSeconds) || 0));
1040
+ const initial = await this.getOperationRecordOrThrow(tenantId, operationId);
1041
+ if (boundedSeconds === 0 || TERMINAL_OPERATION_STATES.has(initial.state) || initial.state === 'WAITING_INPUT') {
1042
+ return this.toOperationView(initial, urlPrefix);
1043
+ }
1044
+
1045
+ await new Promise<void>((resolve) => {
1046
+ const channel = `op:${operationId}`;
1047
+ const timer = setTimeout(() => {
1048
+ this.stateEvents.removeListener(channel, onState);
1049
+ resolve();
1050
+ }, boundedSeconds * 1000);
1051
+
1052
+ function onState(nextState: DuOperationState) {
1053
+ if (TERMINAL_OPERATION_STATES.has(nextState) || nextState === 'WAITING_INPUT') {
1054
+ clearTimeout(timer);
1055
+ resolve();
1056
+ }
1057
+ }
1058
+
1059
+ this.stateEvents.on(channel, onState);
1060
+ });
1061
+
1062
+ const latest = await this.getOperationRecordOrThrow(tenantId, operationId);
1063
+ return this.toOperationView(latest, urlPrefix);
1064
+ }
1065
+
1066
+ async listOperations(params: {
1067
+ tenantId: string;
1068
+ state?: string;
1069
+ businessId?: string;
1070
+ action?: string;
1071
+ from?: string;
1072
+ to?: string;
1073
+ limit?: number;
1074
+ cursor?: string;
1075
+ urlPrefix?: string;
1076
+ }): Promise<{ items: OperationView[]; nextCursor: string | null }> {
1077
+ const filter: Record<string, unknown> = {};
1078
+ if (params.tenantId !== '*') filter.tenantId = params.tenantId;
1079
+ if (params.state) filter.state = params.state;
1080
+ if (params.businessId) filter.businessId = params.businessId;
1081
+ if (params.action) filter.action = params.action;
1082
+ if (params.from || params.to) {
1083
+ const createdFilter: Record<string, unknown> = {};
1084
+ if (params.from) createdFilter.$gte = new Date(params.from);
1085
+ if (params.to) createdFilter.$lt = new Date(params.to);
1086
+ filter.createdAt = createdFilter;
1087
+ }
1088
+ if (params.cursor && Number.isFinite(Number(params.cursor))) {
1089
+ filter.id = { $lt: Number(params.cursor) };
1090
+ }
1091
+
1092
+ const limit = Math.max(1, Math.min(100, Number(params.limit) || 20));
1093
+ const rows = await this.db.getRepository(OPERATIONS_COLLECTION).find({
1094
+ filter,
1095
+ sort: ['-id'],
1096
+ limit: limit + 1,
1097
+ });
1098
+
1099
+ const plains = rows.map((r: unknown) => toPlain<OperationRecord>(r));
1100
+ const hasMore = plains.length > limit;
1101
+ const slice = hasMore ? plains.slice(0, limit) : plains;
1102
+ const lastId = slice.length > 0 ? slice[slice.length - 1].id : undefined;
1103
+
1104
+ return {
1105
+ items: slice.map((op: OperationRecord) => this.toOperationView(op, params.urlPrefix || '/api/du/v1')),
1106
+ nextCursor: hasMore && lastId != null ? String(lastId) : null,
1107
+ };
1108
+ }
1109
+
1110
+ async cancelOperation(
1111
+ tenantId: string,
1112
+ operationId: string,
1113
+ ): Promise<{
1114
+ httpStatus: 200 | 202;
1115
+ operationId: string;
1116
+ state: DuOperationState;
1117
+ stateVersion: number;
1118
+ replayed: boolean;
1119
+ }> {
1120
+ const op = await this.getOperationRecordOrThrow(tenantId, operationId);
1121
+ if (op.state === 'CANCELLED' || op.state === 'CANCEL_REQUESTED') {
1122
+ return {
1123
+ httpStatus: 200,
1124
+ operationId,
1125
+ state: op.state,
1126
+ stateVersion: op.stateVersion,
1127
+ replayed: true,
1128
+ };
1129
+ }
1130
+ if (TERMINAL_OPERATION_STATES.has(op.state)) {
1131
+ throw new DuHttpError(
1132
+ createProblem(409, 'STATE_CONFLICT', `Cannot cancel terminal operation in state ${op.state}`),
1133
+ );
1134
+ }
1135
+
1136
+ if (op.externalOperationId) {
1137
+ const config = await this.getConfig();
1138
+ const ext = new ExternalDuReworkClient(config);
1139
+ ext.cancelOperation(op.externalOperationId).catch(() => undefined);
1140
+ }
1141
+
1142
+ const nextState: DuOperationState =
1143
+ op.state === 'WAITING_INPUT' || op.state === 'ACCEPTED' || op.state === 'QUEUED'
1144
+ ? 'CANCELLED'
1145
+ : 'CANCEL_REQUESTED';
1146
+
1147
+ await this.transitionOperation(operationId, {
1148
+ state: nextState,
1149
+ progress: { percent: 100, message: nextState },
1150
+ ...(nextState === 'CANCELLED' ? { completedAt: new Date(), leaseExpiresAt: null } : {}),
1151
+ });
1152
+
1153
+ const updated = await this.getOperationRecordOrThrow(tenantId, operationId);
1154
+ return {
1155
+ httpStatus: 202,
1156
+ operationId,
1157
+ state: updated.state,
1158
+ stateVersion: updated.stateVersion,
1159
+ replayed: false,
1160
+ };
1161
+ }
1162
+
1163
+ async resumeOperation(params: {
1164
+ tenantId: string;
1165
+ operationId: string;
1166
+ waitId?: string;
1167
+ expectedStateVersion?: number;
1168
+ input: Record<string, unknown>;
1169
+ resumedBy?: string;
1170
+ urlPrefix?: string;
1171
+ }): Promise<{
1172
+ httpStatus: 202;
1173
+ operationId: string;
1174
+ state: DuOperationState;
1175
+ stateVersion: number;
1176
+ replayed: false;
1177
+ }> {
1178
+ const op = await this.getOperationRecordOrThrow(params.tenantId, params.operationId);
1179
+ if (op.state !== 'WAITING_INPUT' || !op.waitState) {
1180
+ throw new DuHttpError(
1181
+ createProblem(
1182
+ 409,
1183
+ 'STATE_CONFLICT',
1184
+ `Operation ${params.operationId} is in state ${op.state}, expected WAITING_INPUT`,
1185
+ ),
1186
+ );
1187
+ }
1188
+ if (params.waitId && params.waitId !== op.waitState.waitId) {
1189
+ throw new DuHttpError(
1190
+ createProblem(
1191
+ 409,
1192
+ 'STATE_CONFLICT',
1193
+ `waitId mismatch (expected "${op.waitState.waitId}", got "${params.waitId}")`,
1194
+ ),
1195
+ );
1196
+ }
1197
+ if (params.expectedStateVersion !== undefined && Number(params.expectedStateVersion) !== Number(op.stateVersion)) {
1198
+ throw new DuHttpError(
1199
+ createProblem(
1200
+ 409,
1201
+ 'STATE_CONFLICT',
1202
+ `expectedStateVersion mismatch (expected ${op.stateVersion}, got ${params.expectedStateVersion})`,
1203
+ ),
1204
+ );
1205
+ }
1206
+
1207
+ const enrichedInput = {
1208
+ ...params.input,
1209
+ ...(params.resumedBy && !params.input.approver ? { approver: params.resumedBy } : {}),
1210
+ };
1211
+
1212
+ await this.transitionOperation(params.operationId, {
1213
+ state: 'QUEUED',
1214
+ progress: { percent: 60, message: 'RESUMED' },
1215
+ waitState: {
1216
+ ...op.waitState,
1217
+ resumedAt: new Date().toISOString(),
1218
+ resumedBy: params.resumedBy,
1219
+ resumedInput: enrichedInput,
1220
+ },
1221
+ });
1222
+
1223
+ const refreshed = await this.getOperationRecordOrThrow(params.tenantId, params.operationId);
1224
+ this.runOperationInBackground(params.operationId, undefined, params.urlPrefix || '/api/du/v1', enrichedInput).catch(
1225
+ (err) => {
1226
+ this.app.logger?.error?.(`Failed resuming operation ${params.operationId}`, err);
1227
+ },
1228
+ );
1229
+
1230
+ return {
1231
+ httpStatus: 202,
1232
+ operationId: params.operationId,
1233
+ state: refreshed.state,
1234
+ stateVersion: refreshed.stateVersion,
1235
+ replayed: false,
1236
+ };
1237
+ }
1238
+
1239
+ async getOperationResult(tenantId: string, operationId: string): Promise<ResultEnvelope> {
1240
+ const op = await this.getOperationRecordOrThrow(tenantId, operationId);
1241
+ if (op.state === 'TIMED_OUT') {
1242
+ throw new DuHttpError(createProblem(410, 'GONE', `Operation ${operationId} timed out`));
1243
+ }
1244
+ if (op.state !== 'SUCCEEDED' || !op.resultEnvelope) {
1245
+ throw new DuHttpError(
1246
+ createProblem(409, 'STATE_CONFLICT', `Operation ${operationId} result is not ready (state=${op.state})`),
1247
+ );
1248
+ }
1249
+ return op.resultEnvelope;
1250
+ }
1251
+
1252
+ async getUsageSummary(params: { tenantId: string; from: string; to: string }): Promise<UsageSummaryView> {
1253
+ const fromDate = new Date(params.from);
1254
+ const toDate = new Date(params.to);
1255
+ if (Number.isNaN(fromDate.getTime()) || Number.isNaN(toDate.getTime()) || fromDate >= toDate) {
1256
+ throw new DuHttpError(
1257
+ createProblem(422, 'INVALID_SCHEMA', 'Query parameters "from" and "to" must be valid ISO dates with from < to'),
1258
+ );
1259
+ }
1260
+
1261
+ const filter: Record<string, unknown> = {
1262
+ createdAt: { $gte: fromDate, $lt: toDate },
1263
+ };
1264
+ if (params.tenantId !== '*') filter.tenantId = params.tenantId;
1265
+
1266
+ const rows = await this.db.getRepository(OPERATIONS_COLLECTION).find({ filter });
1267
+ const plains = rows.map((r: unknown) => toPlain<OperationRecord>(r));
1268
+
1269
+ let totalInput = 0;
1270
+ let totalOutput = 0;
1271
+ let totalCost = 0;
1272
+ const grouped = new Map<
1273
+ string,
1274
+ {
1275
+ businessId: string;
1276
+ action: string;
1277
+ operations: number;
1278
+ inputTokens: number;
1279
+ outputTokens: number;
1280
+ costMicrousd: number;
1281
+ }
1282
+ >();
1283
+
1284
+ for (const op of plains) {
1285
+ const u = op.usage;
1286
+ const inTok = u?.inputTokens || 0;
1287
+ const outTok = u?.outputTokens || 0;
1288
+ const cost = u?.costMicrousd || 0;
1289
+ totalInput += inTok;
1290
+ totalOutput += outTok;
1291
+ totalCost += cost;
1292
+
1293
+ const key = `${op.businessId}:${op.action}`;
1294
+ const bucket = grouped.get(key) || {
1295
+ businessId: op.businessId,
1296
+ action: op.action,
1297
+ operations: 0,
1298
+ inputTokens: 0,
1299
+ outputTokens: 0,
1300
+ costMicrousd: 0,
1301
+ };
1302
+ bucket.operations += 1;
1303
+ bucket.inputTokens += inTok;
1304
+ bucket.outputTokens += outTok;
1305
+ bucket.costMicrousd += cost;
1306
+ grouped.set(key, bucket);
1307
+ }
1308
+
1309
+ return {
1310
+ from: fromDate.toISOString(),
1311
+ to: toDate.toISOString(),
1312
+ totalOperations: plains.length,
1313
+ inputTokens: totalInput,
1314
+ outputTokens: totalOutput,
1315
+ costMicrousd: totalCost,
1316
+ byBusiness: Array.from(grouped.values()),
1317
+ };
1318
+ }
1319
+
1320
+ async listUsageEvents(params: {
1321
+ tenantId: string;
1322
+ operationId?: string;
1323
+ provider?: string;
1324
+ model?: string;
1325
+ action?: string;
1326
+ limit?: number;
1327
+ }): Promise<{ items: Array<Record<string, unknown>> }> {
1328
+ const filter: Record<string, unknown> = {};
1329
+ if (params.tenantId !== '*') filter.tenantId = params.tenantId;
1330
+ if (params.operationId) filter.operationId = params.operationId;
1331
+ if (params.action) filter.action = params.action;
1332
+
1333
+ const limit = Math.max(1, Math.min(200, Number(params.limit) || 50));
1334
+ const rows = await this.db.getRepository(OPERATIONS_COLLECTION).find({
1335
+ filter,
1336
+ sort: ['-createdAt'],
1337
+ limit,
1338
+ });
1339
+
1340
+ const items = rows
1341
+ .map((r: unknown) => toPlain<OperationRecord>(r))
1342
+ .filter((op: OperationRecord) => {
1343
+ if (!op.usage) return false;
1344
+ if (params.model && op.usage.model !== params.model) return false;
1345
+ if (params.provider && op.usage.provider !== params.provider) return false;
1346
+ return true;
1347
+ })
1348
+ .map((op: OperationRecord) => ({
1349
+ operationId: op.operationId,
1350
+ businessId: op.businessId,
1351
+ action: op.action,
1352
+ state: op.state,
1353
+ createdAt: op.createdAt,
1354
+ ...op.usage,
1355
+ }));
1356
+
1357
+ return { items };
1358
+ }
1359
+ }