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.
- package/LICENSE +201 -0
- package/README.md +19 -25
- package/dist/client/169.6888909107c553c3.js +10 -0
- package/dist/client/379.e29f5ced467ce23d.js +10 -0
- package/dist/client/867.3ed3b814115181ca.js +10 -0
- package/dist/client/index.js +1 -1
- package/dist/client-v2/169.53bf1be2ec192f0c.js +10 -0
- package/dist/client-v2/379.e75c4829567cdb89.js +10 -0
- package/dist/client-v2/867.66d7291e95f1de78.js +10 -0
- package/dist/client-v2/index.js +1 -1
- package/dist/externalVersion.js +10 -8
- package/dist/locale/en-US.json +126 -0
- package/dist/locale/vi-VN.json +130 -2
- package/dist/locale/zh-CN.json +127 -1
- package/dist/node_modules/form-data/package.json +1 -1
- package/dist/node_modules/mime-types/package.json +1 -1
- package/dist/server/actions.js +211 -11
- package/dist/server/collections/api-keys.js +55 -0
- package/dist/server/collections/artifacts.js +59 -0
- package/dist/server/collections/config.js +9 -3
- package/dist/server/collections/endpoints.js +3 -0
- package/dist/server/collections/jobs.js +7 -4
- package/dist/server/collections/operations.js +76 -0
- package/dist/server/contracts/du-contracts.js +828 -0
- package/dist/server/dugate-seed.js +98 -340
- package/dist/server/plugin.js +49 -7
- package/dist/server/routes/du-gateway-router.js +443 -0
- package/dist/server/services/ArtifactStorageService.js +459 -0
- package/dist/server/services/AsyncJobManager.js +1 -1
- package/dist/server/services/BuiltinBusinessEngine.js +1223 -0
- package/dist/server/services/DocumentUnderstandingService.js +151 -25
- package/dist/server/services/ExternalDuReworkClient.js +210 -0
- package/dist/server/services/OperationOrchestrator.js +1087 -0
- package/dist/server/services/PipelineExecutor.js +164 -43
- package/dist/server/tools/document-understanding-tool.js +49 -24
- package/dist/server/workflow/DocumentUnderstandingInstruction.js +292 -0
- package/package.json +8 -4
- package/src/client/index.tsx +11 -0
- package/src/client-v2/components/ApiKeysTab.tsx +198 -0
- package/src/client-v2/components/EndpointsTab.tsx +39 -2
- package/src/client-v2/components/JobsTab.tsx +136 -21
- package/src/client-v2/components/OperationsTab.tsx +586 -0
- package/src/client-v2/components/PluginSettings.tsx +24 -8
- package/src/client-v2/components/ServiceConfigTab.tsx +225 -65
- package/src/client-v2/components/__tests__/PluginSettings.test.tsx +43 -0
- package/src/client-v2/locale.ts +1 -8
- package/src/client-v2/models/index.ts +1 -8
- package/src/client-v2/plugin.tsx +12 -8
- package/src/client-v2/types.ts +13 -1
- package/src/client-v2/workflow/DocumentUnderstandingFieldset.tsx +122 -0
- package/src/client-v2/workflow/DocumentUnderstandingInstruction.tsx +49 -0
- package/src/locale/en-US.json +126 -0
- package/src/locale/vi-VN.json +130 -2
- package/src/locale/zh-CN.json +127 -1
- package/src/server/__tests__/actions.test.ts +1 -8
- package/src/server/__tests__/du-rework-gateway.test.ts +462 -0
- package/src/server/__tests__/dugate-integration.test.ts +79 -42
- package/src/server/__tests__/smoke.test.ts +1 -8
- package/src/server/__tests__/upload-security.test.ts +1 -8
- package/src/server/actions.ts +252 -36
- package/src/server/collections/api-keys.ts +35 -0
- package/src/server/collections/artifacts.ts +39 -0
- package/src/server/collections/config.ts +18 -2
- package/src/server/collections/endpoints.ts +12 -0
- package/src/server/collections/jobs.ts +16 -4
- package/src/server/collections/operations.ts +56 -0
- package/src/server/contracts/du-contracts.ts +1026 -0
- package/src/server/dugate-seed.ts +126 -453
- package/src/server/plugin.ts +64 -14
- package/src/server/routes/du-gateway-router.ts +465 -0
- package/src/server/services/ArtifactStorageService.ts +596 -0
- package/src/server/services/AsyncJobManager.ts +10 -1
- package/src/server/services/BuiltinBusinessEngine.ts +1544 -0
- package/src/server/services/DocumentUnderstandingService.ts +186 -44
- package/src/server/services/ExternalDuReworkClient.ts +222 -0
- package/src/server/services/OperationOrchestrator.ts +1359 -0
- package/src/server/services/PipelineExecutor.ts +245 -108
- package/src/server/tools/document-understanding-tool.ts +63 -45
- package/src/server/types.ts +101 -16
- package/src/server/workflow/DocumentUnderstandingInstruction.ts +308 -0
- package/dist/client/345.e6e484fb1974c3d3.js +0 -10
- package/dist/client-v2/345.a8f28526ac21e02a.js +0 -10
|
@@ -0,0 +1,1087 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
var __create = Object.create;
|
|
11
|
+
var __defProp = Object.defineProperty;
|
|
12
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
13
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
14
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
15
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
16
|
+
var __export = (target, all) => {
|
|
17
|
+
for (var name in all)
|
|
18
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
19
|
+
};
|
|
20
|
+
var __copyProps = (to, from, except, desc) => {
|
|
21
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
22
|
+
for (let key of __getOwnPropNames(from))
|
|
23
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
24
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
25
|
+
}
|
|
26
|
+
return to;
|
|
27
|
+
};
|
|
28
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
29
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
30
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
31
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
32
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
33
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
34
|
+
mod
|
|
35
|
+
));
|
|
36
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
37
|
+
var OperationOrchestrator_exports = {};
|
|
38
|
+
__export(OperationOrchestrator_exports, {
|
|
39
|
+
OperationOrchestrator: () => OperationOrchestrator
|
|
40
|
+
});
|
|
41
|
+
module.exports = __toCommonJS(OperationOrchestrator_exports);
|
|
42
|
+
var crypto = __toESM(require("crypto"));
|
|
43
|
+
var import_events = require("events");
|
|
44
|
+
var import_net = require("net");
|
|
45
|
+
var import_axios = __toESM(require("axios"));
|
|
46
|
+
var import_du_contracts = require("../contracts/du-contracts");
|
|
47
|
+
var import_ArtifactStorageService = require("./ArtifactStorageService");
|
|
48
|
+
var import_ExternalDuReworkClient = require("./ExternalDuReworkClient");
|
|
49
|
+
const OPERATIONS_COLLECTION = "doc_understanding_operations";
|
|
50
|
+
const API_KEYS_COLLECTION = "doc_understanding_api_keys";
|
|
51
|
+
const ARTIFACTS_COLLECTION = "doc_understanding_artifacts";
|
|
52
|
+
const MAX_INLINE_WEBHOOK_RESULT_BYTES = 256 * 1024;
|
|
53
|
+
function isRecord(value) {
|
|
54
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
55
|
+
}
|
|
56
|
+
function toPlain(row) {
|
|
57
|
+
if (row && typeof row === "object" && typeof row.toJSON === "function") {
|
|
58
|
+
return row.toJSON();
|
|
59
|
+
}
|
|
60
|
+
return row;
|
|
61
|
+
}
|
|
62
|
+
function sha256String(input) {
|
|
63
|
+
return crypto.createHash("sha256").update(input, "utf8").digest("hex");
|
|
64
|
+
}
|
|
65
|
+
function isPrivateOrBlockedHost(hostname) {
|
|
66
|
+
const lower = hostname.toLowerCase();
|
|
67
|
+
if (lower === "localhost" || lower.endsWith(".localhost") || lower.endsWith(".internal")) {
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
const ipVer = (0, import_net.isIP)(lower);
|
|
71
|
+
if (ipVer === 4) {
|
|
72
|
+
const parts = lower.split(".").map(Number);
|
|
73
|
+
if (parts[0] === 127 || parts[0] === 10 || parts[0] === 0) return true;
|
|
74
|
+
if (parts[0] === 169 && parts[1] === 254) return true;
|
|
75
|
+
if (parts[0] === 172 && parts[1] >= 16 && parts[1] <= 31) return true;
|
|
76
|
+
if (parts[0] === 192 && parts[1] === 168) return true;
|
|
77
|
+
if (parts[0] === 100 && parts[1] >= 64 && parts[1] <= 127) return true;
|
|
78
|
+
} else if (ipVer === 6) {
|
|
79
|
+
if (lower === "::1" || lower.startsWith("fe80:") || lower.startsWith("fc") || lower.startsWith("fd")) {
|
|
80
|
+
return true;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return false;
|
|
84
|
+
}
|
|
85
|
+
function assertSafeOutboundCallbackUrl(rawUrl) {
|
|
86
|
+
let parsed;
|
|
87
|
+
try {
|
|
88
|
+
parsed = new URL(rawUrl);
|
|
89
|
+
} catch {
|
|
90
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
91
|
+
(0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "Invalid callback.url", {
|
|
92
|
+
errors: [{ pointer: "/callback/url", message: "Must be a valid HTTP(S) URL" }]
|
|
93
|
+
})
|
|
94
|
+
);
|
|
95
|
+
}
|
|
96
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
97
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "callback.url must use https:// or http://"));
|
|
98
|
+
}
|
|
99
|
+
if (parsed.username || parsed.password) {
|
|
100
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "callback.url must not embed credentials"));
|
|
101
|
+
}
|
|
102
|
+
if (isPrivateOrBlockedHost(parsed.hostname)) {
|
|
103
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
104
|
+
(0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "callback.url target host is blocked by egress SSRF policy")
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
return parsed.toString();
|
|
108
|
+
}
|
|
109
|
+
function resolveBusinessVersion(businessId) {
|
|
110
|
+
if (businessId === "document-core") return "2.0.0";
|
|
111
|
+
if (businessId === "lc-checker") return "1.2.0";
|
|
112
|
+
if (businessId === "example-review") return "1.0.0";
|
|
113
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(404, "NOT_FOUND", `Business "${businessId}" is not registered`));
|
|
114
|
+
}
|
|
115
|
+
function resolveVariantFromInput(action, input) {
|
|
116
|
+
if (action === "ingest" || action === "compare") return typeof input.mode === "string" ? input.mode : void 0;
|
|
117
|
+
if (action === "extract") return typeof input.type === "string" ? input.type : void 0;
|
|
118
|
+
if (action === "analyze" || action === "generate") return typeof input.task === "string" ? input.task : void 0;
|
|
119
|
+
if (action === "transform") {
|
|
120
|
+
return typeof input.variant === "string" ? input.variant : typeof input.action === "string" ? input.action : void 0;
|
|
121
|
+
}
|
|
122
|
+
return void 0;
|
|
123
|
+
}
|
|
124
|
+
class OperationOrchestrator {
|
|
125
|
+
app;
|
|
126
|
+
db;
|
|
127
|
+
artifactStorage;
|
|
128
|
+
builtinEngine;
|
|
129
|
+
getConfig;
|
|
130
|
+
nodeId;
|
|
131
|
+
stateEvents = new import_events.EventEmitter();
|
|
132
|
+
constructor(params) {
|
|
133
|
+
this.app = params.app;
|
|
134
|
+
this.db = params.db;
|
|
135
|
+
this.artifactStorage = params.artifactStorage;
|
|
136
|
+
this.builtinEngine = params.builtinEngine;
|
|
137
|
+
this.getConfig = params.getConfig;
|
|
138
|
+
this.nodeId = params.nodeId;
|
|
139
|
+
this.stateEvents.setMaxListeners(200);
|
|
140
|
+
}
|
|
141
|
+
/* ─── Gateway API Key Management (Profile-scoped, SHA-256 hashed) ─── */
|
|
142
|
+
async issueApiKey(params) {
|
|
143
|
+
if (!params.name || !params.name.trim()) {
|
|
144
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "API key name is required"));
|
|
145
|
+
}
|
|
146
|
+
const rawRandom = crypto.randomBytes(24).toString("hex");
|
|
147
|
+
const rawKey = `du_live_${rawRandom}`;
|
|
148
|
+
const keyPrefix = rawKey.slice(0, 16);
|
|
149
|
+
const keyHash = sha256String(rawKey);
|
|
150
|
+
const tenantId = (params.tenantId || "default").trim() || "default";
|
|
151
|
+
const allowedBusinesses = Array.isArray(params.allowedBusinesses) && params.allowedBusinesses.length > 0 ? params.allowedBusinesses.map(String) : ["*"];
|
|
152
|
+
const allowedActions = Array.isArray(params.allowedActions) && params.allowedActions.length > 0 ? params.allowedActions.map(String) : ["*"];
|
|
153
|
+
const created = await this.db.getRepository(API_KEYS_COLLECTION).create({
|
|
154
|
+
values: {
|
|
155
|
+
name: params.name.trim(),
|
|
156
|
+
keyPrefix,
|
|
157
|
+
keyHash,
|
|
158
|
+
tenantId,
|
|
159
|
+
allowedBusinesses,
|
|
160
|
+
allowedActions,
|
|
161
|
+
requestDefaults: params.requestDefaults ?? null,
|
|
162
|
+
lockedFields: params.lockedFields ?? null,
|
|
163
|
+
status: "active",
|
|
164
|
+
expiresAt: params.expiresAt ?? null,
|
|
165
|
+
createdById: params.userId ?? null
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
const record = toPlain(created);
|
|
169
|
+
return {
|
|
170
|
+
id: record.id,
|
|
171
|
+
name: record.name,
|
|
172
|
+
keyPrefix,
|
|
173
|
+
tenantId,
|
|
174
|
+
allowedBusinesses,
|
|
175
|
+
allowedActions,
|
|
176
|
+
requestDefaults: record.requestDefaults ?? null,
|
|
177
|
+
lockedFields: record.lockedFields ?? null,
|
|
178
|
+
status: "active",
|
|
179
|
+
expiresAt: record.expiresAt ?? null,
|
|
180
|
+
lastUsedAt: null,
|
|
181
|
+
createdAt: record.createdAt,
|
|
182
|
+
rawKey
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
async listApiKeys() {
|
|
186
|
+
const rows = await this.db.getRepository(API_KEYS_COLLECTION).find({
|
|
187
|
+
sort: ["-createdAt"]
|
|
188
|
+
});
|
|
189
|
+
return rows.map((row) => {
|
|
190
|
+
const plain = toPlain(row);
|
|
191
|
+
const { keyHash: _omitted, ...safe } = plain;
|
|
192
|
+
return safe;
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
async revokeApiKey(id) {
|
|
196
|
+
await this.db.getRepository(API_KEYS_COLLECTION).update({
|
|
197
|
+
filterByTk: id,
|
|
198
|
+
values: { status: "revoked" }
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
async authenticateRawApiKey(rawKey) {
|
|
202
|
+
const trimmed = rawKey.trim();
|
|
203
|
+
if (!trimmed) {
|
|
204
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(401, "UNAUTHENTICATED", "Missing x-api-key header"));
|
|
205
|
+
}
|
|
206
|
+
const keyHash = sha256String(trimmed);
|
|
207
|
+
const repo = this.db.getRepository(API_KEYS_COLLECTION);
|
|
208
|
+
const row = await repo.findOne({ filter: { keyHash } });
|
|
209
|
+
if (!row) {
|
|
210
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(401, "UNAUTHENTICATED", "Invalid API key"));
|
|
211
|
+
}
|
|
212
|
+
const record = toPlain(row);
|
|
213
|
+
if (record.status !== "active") {
|
|
214
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(401, "UNAUTHENTICATED", "API key has been revoked"));
|
|
215
|
+
}
|
|
216
|
+
if (record.expiresAt && new Date(record.expiresAt).getTime() <= Date.now()) {
|
|
217
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(401, "UNAUTHENTICATED", "API key has expired"));
|
|
218
|
+
}
|
|
219
|
+
try {
|
|
220
|
+
await repo.update({
|
|
221
|
+
filterByTk: record.id,
|
|
222
|
+
values: { lastUsedAt: /* @__PURE__ */ new Date() }
|
|
223
|
+
});
|
|
224
|
+
} catch {
|
|
225
|
+
}
|
|
226
|
+
return {
|
|
227
|
+
kind: "du_api_key",
|
|
228
|
+
apiKeyId: record.id,
|
|
229
|
+
tenantId: record.tenantId || "default",
|
|
230
|
+
userId: record.createdById ?? void 0,
|
|
231
|
+
allowedBusinesses: Array.isArray(record.allowedBusinesses) ? record.allowedBusinesses : ["*"],
|
|
232
|
+
allowedActions: Array.isArray(record.allowedActions) ? record.allowedActions : ["*"],
|
|
233
|
+
requestDefaults: record.requestDefaults ?? null,
|
|
234
|
+
lockedFields: record.lockedFields ?? null
|
|
235
|
+
};
|
|
236
|
+
}
|
|
237
|
+
assertActionPermitted(principal, businessId, action) {
|
|
238
|
+
const bizOk = principal.allowedBusinesses.includes("*") || principal.allowedBusinesses.includes(businessId);
|
|
239
|
+
const actOk = principal.allowedActions.includes("*") || principal.allowedActions.includes(action) || principal.allowedActions.includes(`${businessId}:${action}`);
|
|
240
|
+
if (!bizOk || !actOk) {
|
|
241
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
242
|
+
(0, import_du_contracts.createProblem)(
|
|
243
|
+
403,
|
|
244
|
+
"PERMISSION_DENIED",
|
|
245
|
+
`API key profile does not grant permission for ${businessId}/${action}`
|
|
246
|
+
)
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
applyProfilePolicyToInput(principal, callerInput) {
|
|
251
|
+
const defaults = isRecord(principal.requestDefaults) ? principal.requestDefaults : {};
|
|
252
|
+
const locked = Array.isArray(principal.lockedFields) ? principal.lockedFields : [];
|
|
253
|
+
for (const lockedKey of locked) {
|
|
254
|
+
if (Object.prototype.hasOwnProperty.call(callerInput, lockedKey) && Object.prototype.hasOwnProperty.call(defaults, lockedKey) && JSON.stringify(callerInput[lockedKey]) !== JSON.stringify(defaults[lockedKey])) {
|
|
255
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
256
|
+
(0, import_du_contracts.createProblem)(403, "PERMISSION_DENIED", `Parameter "${lockedKey}" is locked by profile policy`)
|
|
257
|
+
);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
return {
|
|
261
|
+
...defaults,
|
|
262
|
+
...callerInput
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
/* ─── Canonical Operation Submission & Execution ─────────────────── */
|
|
266
|
+
async submitOperation(params) {
|
|
267
|
+
var _a;
|
|
268
|
+
const { principal, businessId, action, submission, idempotencyKey, urlPrefix = "/api/du/v1" } = params;
|
|
269
|
+
const businessVersion = resolveBusinessVersion(businessId);
|
|
270
|
+
this.assertActionPermitted(principal, businessId, action);
|
|
271
|
+
if (!isRecord(submission) || !isRecord(submission.input)) {
|
|
272
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
273
|
+
(0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", 'Request body must include an "input" object', {
|
|
274
|
+
errors: [{ pointer: "/input", message: "Expected object" }]
|
|
275
|
+
})
|
|
276
|
+
);
|
|
277
|
+
}
|
|
278
|
+
if ((_a = submission.callback) == null ? void 0 : _a.url) {
|
|
279
|
+
assertSafeOutboundCallbackUrl(submission.callback.url);
|
|
280
|
+
}
|
|
281
|
+
const effectiveInput = this.applyProfilePolicyToInput(principal, submission.input);
|
|
282
|
+
const correlationId = (params.correlationId || crypto.randomUUID()).trim();
|
|
283
|
+
const fingerprint = sha256String(
|
|
284
|
+
JSON.stringify({
|
|
285
|
+
businessId,
|
|
286
|
+
action,
|
|
287
|
+
input: effectiveInput,
|
|
288
|
+
artifacts: submission.artifacts || [],
|
|
289
|
+
documentSelection: submission.documentSelection || null,
|
|
290
|
+
sourceUrl: submission.sourceUrl || null
|
|
291
|
+
})
|
|
292
|
+
);
|
|
293
|
+
const opsRepo = this.db.getRepository(OPERATIONS_COLLECTION);
|
|
294
|
+
if (idempotencyKey && idempotencyKey.trim()) {
|
|
295
|
+
const existingRow = await opsRepo.findOne({
|
|
296
|
+
filter: { tenantId: principal.tenantId, idempotencyKey: idempotencyKey.trim() }
|
|
297
|
+
});
|
|
298
|
+
if (existingRow) {
|
|
299
|
+
const existing = toPlain(existingRow);
|
|
300
|
+
if (existing.requestFingerprint && existing.requestFingerprint !== fingerprint) {
|
|
301
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
302
|
+
(0, import_du_contracts.createProblem)(
|
|
303
|
+
409,
|
|
304
|
+
"IDEMPOTENCY_CONFLICT",
|
|
305
|
+
"Idempotency-Key was already used with a different request payload",
|
|
306
|
+
{ correlationId }
|
|
307
|
+
)
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
return {
|
|
311
|
+
httpStatus: 200,
|
|
312
|
+
operationId: existing.operationId,
|
|
313
|
+
state: existing.state,
|
|
314
|
+
stateVersion: existing.stateVersion,
|
|
315
|
+
replayed: true,
|
|
316
|
+
correlationId: existing.correlationId || correlationId,
|
|
317
|
+
links: {
|
|
318
|
+
self: `${urlPrefix}/operations/${existing.operationId}`,
|
|
319
|
+
result: `${urlPrefix}/operations/${existing.operationId}/result`
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
const config = await this.getConfig();
|
|
325
|
+
const maxFiles = config.maxFilesPerRequest ?? 20;
|
|
326
|
+
const maxBytes = config.maxFileSizeBytes ?? 10 * 1024 * 1024;
|
|
327
|
+
const artifactRefs = Array.isArray(submission.artifacts) ? submission.artifacts : [];
|
|
328
|
+
if (artifactRefs.length > maxFiles) {
|
|
329
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
330
|
+
(0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", `Too many input artifacts (${artifactRefs.length} > max ${maxFiles})`, {
|
|
331
|
+
correlationId
|
|
332
|
+
})
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
const resolvedArtifacts = [];
|
|
336
|
+
for (const ref of artifactRefs) {
|
|
337
|
+
if (!ref || typeof ref.artifactId !== "string") {
|
|
338
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
339
|
+
(0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", "Each artifact reference must specify artifactId", { correlationId })
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
const record = await this.artifactStorage.getArtifactOrThrow(principal.tenantId, ref.artifactId);
|
|
343
|
+
if (record.state !== "READY") {
|
|
344
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
345
|
+
(0, import_du_contracts.createProblem)(409, "STATE_CONFLICT", `Artifact ${ref.artifactId} is not READY (state=${record.state})`, {
|
|
346
|
+
correlationId
|
|
347
|
+
})
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
if (record.sizeBytes > maxBytes) {
|
|
351
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
352
|
+
(0, import_du_contracts.createProblem)(
|
|
353
|
+
413,
|
|
354
|
+
"PAYLOAD_TOO_LARGE",
|
|
355
|
+
`Artifact ${ref.artifactId} (${record.sizeBytes} bytes) exceeds documentInput policy limit (${maxBytes} bytes)`,
|
|
356
|
+
{ correlationId }
|
|
357
|
+
)
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
resolvedArtifacts.push(record);
|
|
361
|
+
}
|
|
362
|
+
const documentInputPlan = this.buildDocumentInputPlan(resolvedArtifacts, submission);
|
|
363
|
+
const operationId = crypto.randomUUID();
|
|
364
|
+
const deadlineMs = config.pollTimeout || 3e5;
|
|
365
|
+
const deadlineAt = new Date(Date.now() + deadlineMs);
|
|
366
|
+
await opsRepo.create({
|
|
367
|
+
values: {
|
|
368
|
+
operationId,
|
|
369
|
+
tenantId: principal.tenantId,
|
|
370
|
+
businessId,
|
|
371
|
+
businessVersion,
|
|
372
|
+
action,
|
|
373
|
+
variant: resolveVariantFromInput(action, effectiveInput) ?? null,
|
|
374
|
+
state: "ACCEPTED",
|
|
375
|
+
stateVersion: 1,
|
|
376
|
+
correlationId,
|
|
377
|
+
clientReference: submission.clientReference ?? null,
|
|
378
|
+
idempotencyKey: (idempotencyKey == null ? void 0 : idempotencyKey.trim()) || null,
|
|
379
|
+
requestFingerprint: fingerprint,
|
|
380
|
+
submission: {
|
|
381
|
+
...submission,
|
|
382
|
+
input: effectiveInput
|
|
383
|
+
},
|
|
384
|
+
progress: { percent: 0, message: "ACCEPTED" },
|
|
385
|
+
documentInputPlan,
|
|
386
|
+
deadlineAt,
|
|
387
|
+
ownedBy: this.nodeId,
|
|
388
|
+
leaseExpiresAt: new Date(Date.now() + 10 * 60 * 1e3),
|
|
389
|
+
createdById: principal.userId ?? null
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
if (resolvedArtifacts.length > 0) {
|
|
393
|
+
await this.db.getRepository(ARTIFACTS_COLLECTION).update({
|
|
394
|
+
filter: {
|
|
395
|
+
tenantId: principal.tenantId,
|
|
396
|
+
artifactId: { $in: resolvedArtifacts.map((a) => a.artifactId) },
|
|
397
|
+
operationId: null
|
|
398
|
+
},
|
|
399
|
+
values: { operationId }
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
const executionPromise = this.runOperationInBackground(operationId, resolvedArtifacts, urlPrefix);
|
|
403
|
+
executionPromise.catch((err) => {
|
|
404
|
+
var _a2, _b;
|
|
405
|
+
(_b = (_a2 = this.app.logger) == null ? void 0 : _a2.error) == null ? void 0 : _b.call(_a2, `Document Understanding operation ${operationId} background failure`, err);
|
|
406
|
+
});
|
|
407
|
+
if (params.waitCompletionMs && params.waitCompletionMs > 0) {
|
|
408
|
+
await this.waitForOperation(
|
|
409
|
+
principal.tenantId,
|
|
410
|
+
operationId,
|
|
411
|
+
Math.ceil(params.waitCompletionMs / 1e3),
|
|
412
|
+
urlPrefix
|
|
413
|
+
);
|
|
414
|
+
const latest = await this.getOperationRecordOrThrow(principal.tenantId, operationId);
|
|
415
|
+
return {
|
|
416
|
+
httpStatus: 202,
|
|
417
|
+
operationId,
|
|
418
|
+
state: latest.state,
|
|
419
|
+
stateVersion: latest.stateVersion,
|
|
420
|
+
replayed: false,
|
|
421
|
+
correlationId,
|
|
422
|
+
links: {
|
|
423
|
+
self: `${urlPrefix}/operations/${operationId}`,
|
|
424
|
+
result: `${urlPrefix}/operations/${operationId}/result`
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
return {
|
|
429
|
+
httpStatus: 202,
|
|
430
|
+
operationId,
|
|
431
|
+
state: "ACCEPTED",
|
|
432
|
+
stateVersion: 1,
|
|
433
|
+
replayed: false,
|
|
434
|
+
correlationId,
|
|
435
|
+
links: {
|
|
436
|
+
self: `${urlPrefix}/operations/${operationId}`,
|
|
437
|
+
result: `${urlPrefix}/operations/${operationId}/result`
|
|
438
|
+
}
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
buildDocumentInputPlan(artifacts, submission) {
|
|
442
|
+
const sel = submission.documentSelection;
|
|
443
|
+
let selectedArtifacts = artifacts;
|
|
444
|
+
if ((sel == null ? void 0 : sel.artifactIds) && sel.artifactIds.length > 0) {
|
|
445
|
+
const allowedSet = new Set(sel.artifactIds);
|
|
446
|
+
selectedArtifacts = artifacts.filter((a) => allowedSet.has(a.artifactId));
|
|
447
|
+
}
|
|
448
|
+
const items = selectedArtifacts.map((artifact) => {
|
|
449
|
+
var _a;
|
|
450
|
+
const explicitPageSel = (_a = sel == null ? void 0 : sel.pageSelections) == null ? void 0 : _a.find((p) => p.artifactId === artifact.artifactId);
|
|
451
|
+
const selection = explicitPageSel ? explicitPageSel.selection : { kind: "all" };
|
|
452
|
+
return {
|
|
453
|
+
artifactId: artifact.artifactId,
|
|
454
|
+
fileName: artifact.fileName,
|
|
455
|
+
mimeType: artifact.mimeType,
|
|
456
|
+
selection
|
|
457
|
+
};
|
|
458
|
+
});
|
|
459
|
+
return {
|
|
460
|
+
kind: "documentInputPlan",
|
|
461
|
+
schemaVersion: 1,
|
|
462
|
+
items
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
async runOperationInBackground(operationId, preloadedArtifacts, urlPrefix = "/api/du/v1", resumedInput) {
|
|
466
|
+
var _a;
|
|
467
|
+
const opsRepo = this.db.getRepository(OPERATIONS_COLLECTION);
|
|
468
|
+
const row = await opsRepo.findOne({ filter: { operationId } });
|
|
469
|
+
if (!row) return;
|
|
470
|
+
const op = toPlain(row);
|
|
471
|
+
if (import_du_contracts.TERMINAL_OPERATION_STATES.has(op.state)) return;
|
|
472
|
+
if (op.state === "CANCEL_REQUESTED") {
|
|
473
|
+
await this.transitionOperation(operationId, {
|
|
474
|
+
state: "CANCELLED",
|
|
475
|
+
progress: { percent: 100, message: "CANCELLED" },
|
|
476
|
+
completedAt: /* @__PURE__ */ new Date()
|
|
477
|
+
});
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
await this.transitionOperation(operationId, {
|
|
481
|
+
state: "RUNNING",
|
|
482
|
+
progress: { percent: 10, message: "RUNNING" },
|
|
483
|
+
ownedBy: this.nodeId,
|
|
484
|
+
leaseExpiresAt: new Date(Date.now() + 10 * 60 * 1e3)
|
|
485
|
+
});
|
|
486
|
+
const config = await this.getConfig();
|
|
487
|
+
const artifacts = preloadedArtifacts ?? await Promise.all(
|
|
488
|
+
(op.submission.artifacts || []).map(
|
|
489
|
+
(ref) => this.artifactStorage.getArtifactOrThrow(op.tenantId, ref.artifactId)
|
|
490
|
+
)
|
|
491
|
+
);
|
|
492
|
+
try {
|
|
493
|
+
const shouldUseExternalGateway = config.engineMode === "du_rework" || config.engineMode === "hybrid" && !this.builtinEngine.resolveAiManager() && Boolean(config.baseUrl) && config.baseUrl !== "http://localhost:8000";
|
|
494
|
+
if (shouldUseExternalGateway) {
|
|
495
|
+
await this.executeViaExternalGateway(op, artifacts, config, urlPrefix, resumedInput);
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
const planItems = ((_a = op.documentInputPlan) == null ? void 0 : _a.items) || [];
|
|
499
|
+
const outcome = await this.builtinEngine.execute({
|
|
500
|
+
operationId,
|
|
501
|
+
tenantId: op.tenantId,
|
|
502
|
+
businessId: op.businessId,
|
|
503
|
+
action: op.action,
|
|
504
|
+
input: op.submission.input,
|
|
505
|
+
artifacts,
|
|
506
|
+
planItems,
|
|
507
|
+
config,
|
|
508
|
+
resumedInput,
|
|
509
|
+
checkpointData: op.submission._checkpoint,
|
|
510
|
+
userId: op.createdById ?? void 0,
|
|
511
|
+
onProgress: async (percent, message) => {
|
|
512
|
+
await opsRepo.update({
|
|
513
|
+
filter: { operationId },
|
|
514
|
+
values: { progress: { percent, message } }
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
const refreshedRow = await opsRepo.findOne({ filter: { operationId } });
|
|
519
|
+
const refreshed = refreshedRow ? toPlain(refreshedRow) : op;
|
|
520
|
+
if (refreshed.state === "CANCEL_REQUESTED") {
|
|
521
|
+
await this.transitionOperation(operationId, {
|
|
522
|
+
state: "CANCELLED",
|
|
523
|
+
progress: { percent: 100, message: "CANCELLED" },
|
|
524
|
+
completedAt: /* @__PURE__ */ new Date()
|
|
525
|
+
});
|
|
526
|
+
await this.dispatchCallbackIfConfigured(operationId, urlPrefix);
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
if (outcome.kind === "waiting_input") {
|
|
530
|
+
await this.transitionOperation(operationId, {
|
|
531
|
+
state: "WAITING_INPUT",
|
|
532
|
+
progress: { percent: 50, message: "WAITING_INPUT" },
|
|
533
|
+
waitState: outcome.waitState,
|
|
534
|
+
usage: outcome.usage,
|
|
535
|
+
submission: {
|
|
536
|
+
...op.submission,
|
|
537
|
+
_checkpoint: outcome.checkpointData
|
|
538
|
+
},
|
|
539
|
+
leaseExpiresAt: null
|
|
540
|
+
});
|
|
541
|
+
await this.dispatchCallbackIfConfigured(operationId, urlPrefix);
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
const outputArtifact = await this.artifactStorage.createJsonOutputArtifact({
|
|
545
|
+
tenantId: op.tenantId,
|
|
546
|
+
operationId,
|
|
547
|
+
payload: outcome.outputPayload,
|
|
548
|
+
userId: op.createdById ?? void 0
|
|
549
|
+
});
|
|
550
|
+
const planDigest = `sha256:${sha256String(JSON.stringify(op.documentInputPlan || {}))}`;
|
|
551
|
+
const coverageOutcomes = outcome.coverageOutcomes.map((item) => ({
|
|
552
|
+
...item,
|
|
553
|
+
outputRefs: item.outputRefs.length > 0 ? item.outputRefs : [outputArtifact.artifactId]
|
|
554
|
+
}));
|
|
555
|
+
const coverageStatus = coverageOutcomes.some((c) => c.status === "failed") ? "failed" : "complete";
|
|
556
|
+
const documentInputCoverage = {
|
|
557
|
+
kind: "coverageReport",
|
|
558
|
+
schemaVersion: 1,
|
|
559
|
+
planDigest,
|
|
560
|
+
status: coverageStatus,
|
|
561
|
+
outcomes: coverageOutcomes
|
|
562
|
+
};
|
|
563
|
+
if (coverageStatus === "failed") {
|
|
564
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
565
|
+
(0, import_du_contracts.createProblem)(422, "INCOMPLETE_DOCUMENT_COVERAGE", "One or more selected document pages failed processing")
|
|
566
|
+
);
|
|
567
|
+
}
|
|
568
|
+
const envelopeArtifacts = [
|
|
569
|
+
...artifacts.map((a) => ({
|
|
570
|
+
artifactId: a.artifactId,
|
|
571
|
+
role: a.role,
|
|
572
|
+
fileName: a.fileName,
|
|
573
|
+
mimeType: a.mimeType,
|
|
574
|
+
sizeBytes: a.sizeBytes,
|
|
575
|
+
hashSha256: a.hashSha256 || "",
|
|
576
|
+
download: `${urlPrefix}/artifacts/${a.artifactId}/download`
|
|
577
|
+
})),
|
|
578
|
+
{
|
|
579
|
+
artifactId: outputArtifact.artifactId,
|
|
580
|
+
role: "output",
|
|
581
|
+
fileName: outputArtifact.fileName,
|
|
582
|
+
mimeType: outputArtifact.mimeType,
|
|
583
|
+
sizeBytes: outputArtifact.sizeBytes,
|
|
584
|
+
hashSha256: outputArtifact.hashSha256 || "",
|
|
585
|
+
download: `${urlPrefix}/artifacts/${outputArtifact.artifactId}/download`
|
|
586
|
+
},
|
|
587
|
+
...outcome.extraOutputArtifacts.map((extra) => ({
|
|
588
|
+
artifactId: extra.artifactId,
|
|
589
|
+
role: "output",
|
|
590
|
+
fileName: extra.fileName,
|
|
591
|
+
mimeType: extra.mimeType,
|
|
592
|
+
sizeBytes: extra.sizeBytes,
|
|
593
|
+
hashSha256: extra.hashSha256 || "",
|
|
594
|
+
download: `${urlPrefix}/artifacts/${extra.artifactId}/download`
|
|
595
|
+
}))
|
|
596
|
+
];
|
|
597
|
+
const resultEnvelope = {
|
|
598
|
+
schemaVersion: "1",
|
|
599
|
+
data: {
|
|
600
|
+
resultRef: `artifact://${outputArtifact.artifactId}`
|
|
601
|
+
},
|
|
602
|
+
artifacts: envelopeArtifacts,
|
|
603
|
+
usage: outcome.usage,
|
|
604
|
+
warnings: outcome.warnings
|
|
605
|
+
};
|
|
606
|
+
await this.transitionOperation(operationId, {
|
|
607
|
+
state: "SUCCEEDED",
|
|
608
|
+
progress: { percent: 100, message: "SUCCEEDED" },
|
|
609
|
+
documentInputCoverage,
|
|
610
|
+
resultEnvelope,
|
|
611
|
+
outputPayload: outcome.outputPayload,
|
|
612
|
+
usage: outcome.usage,
|
|
613
|
+
warnings: outcome.warnings,
|
|
614
|
+
waitState: null,
|
|
615
|
+
completedAt: /* @__PURE__ */ new Date(),
|
|
616
|
+
leaseExpiresAt: null
|
|
617
|
+
});
|
|
618
|
+
await this.dispatchCallbackIfConfigured(operationId, urlPrefix);
|
|
619
|
+
} catch (err) {
|
|
620
|
+
const problem = err instanceof import_ArtifactStorageService.DuHttpError ? err.problem : (0, import_du_contracts.createProblem)(500, "INTERNAL_ERROR", err instanceof Error ? err.message : String(err), {
|
|
621
|
+
correlationId: op.correlationId ?? void 0
|
|
622
|
+
});
|
|
623
|
+
await this.transitionOperation(operationId, {
|
|
624
|
+
state: "FAILED",
|
|
625
|
+
progress: { percent: 100, message: problem.title },
|
|
626
|
+
errorProblem: problem,
|
|
627
|
+
completedAt: /* @__PURE__ */ new Date(),
|
|
628
|
+
leaseExpiresAt: null
|
|
629
|
+
});
|
|
630
|
+
await this.dispatchCallbackIfConfigured(operationId, urlPrefix);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
async executeViaExternalGateway(op, artifacts, config, urlPrefix, resumedInput) {
|
|
634
|
+
const client = new import_ExternalDuReworkClient.ExternalDuReworkClient(config);
|
|
635
|
+
let remoteOpId = op.externalOperationId || void 0;
|
|
636
|
+
if (!remoteOpId) {
|
|
637
|
+
const remoteRefs = [];
|
|
638
|
+
for (const art of artifacts) {
|
|
639
|
+
const buf = this.artifactStorage.readArtifactBuffer(art);
|
|
640
|
+
const remoteArtId = await client.uploadArtifact(art, buf);
|
|
641
|
+
remoteRefs.push({ artifactId: remoteArtId, role: art.role });
|
|
642
|
+
}
|
|
643
|
+
const submitted = await client.submitAction({
|
|
644
|
+
businessId: op.businessId,
|
|
645
|
+
action: op.action,
|
|
646
|
+
input: op.submission.input,
|
|
647
|
+
artifacts: remoteRefs,
|
|
648
|
+
documentSelection: op.submission.documentSelection,
|
|
649
|
+
sourceUrl: op.submission.sourceUrl,
|
|
650
|
+
clientReference: op.clientReference ?? void 0,
|
|
651
|
+
correlationId: op.correlationId ?? void 0,
|
|
652
|
+
idempotencyKey: `proxy-${op.operationId}`
|
|
653
|
+
});
|
|
654
|
+
remoteOpId = submitted.operationId;
|
|
655
|
+
await this.db.getRepository(OPERATIONS_COLLECTION).update({
|
|
656
|
+
filter: { operationId: op.operationId },
|
|
657
|
+
values: { externalOperationId: remoteOpId }
|
|
658
|
+
});
|
|
659
|
+
} else if (resumedInput && op.waitState) {
|
|
660
|
+
await client.resumeOperation(remoteOpId, {
|
|
661
|
+
waitId: op.waitState.waitId,
|
|
662
|
+
expectedStateVersion: op.stateVersion,
|
|
663
|
+
input: resumedInput
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
const startTime = Date.now();
|
|
667
|
+
const timeoutMs = config.pollTimeout || 3e5;
|
|
668
|
+
const pollIntervalMs = config.pollInterval || 3e3;
|
|
669
|
+
while (Date.now() - startTime < timeoutMs) {
|
|
670
|
+
const remoteView = await client.getOperation(remoteOpId);
|
|
671
|
+
if (remoteView.state === "WAITING_INPUT") {
|
|
672
|
+
await this.transitionOperation(op.operationId, {
|
|
673
|
+
state: "WAITING_INPUT",
|
|
674
|
+
progress: remoteView.progress || { percent: 50, message: "WAITING_INPUT" },
|
|
675
|
+
waitState: remoteView.wait || { waitId: "external-wait" },
|
|
676
|
+
leaseExpiresAt: null
|
|
677
|
+
});
|
|
678
|
+
await this.dispatchCallbackIfConfigured(op.operationId, urlPrefix);
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
if (remoteView.state === "SUCCEEDED") {
|
|
682
|
+
const { envelope, outputPayload } = await client.fetchResultAndPayload(remoteOpId);
|
|
683
|
+
const localOutputArtifact = await this.artifactStorage.createJsonOutputArtifact({
|
|
684
|
+
tenantId: op.tenantId,
|
|
685
|
+
operationId: op.operationId,
|
|
686
|
+
payload: outputPayload,
|
|
687
|
+
userId: op.createdById ?? void 0
|
|
688
|
+
});
|
|
689
|
+
const localEnvelope = {
|
|
690
|
+
schemaVersion: "1",
|
|
691
|
+
data: { resultRef: `artifact://${localOutputArtifact.artifactId}` },
|
|
692
|
+
artifacts: [
|
|
693
|
+
{
|
|
694
|
+
artifactId: localOutputArtifact.artifactId,
|
|
695
|
+
role: "output",
|
|
696
|
+
fileName: localOutputArtifact.fileName,
|
|
697
|
+
mimeType: localOutputArtifact.mimeType,
|
|
698
|
+
sizeBytes: localOutputArtifact.sizeBytes,
|
|
699
|
+
hashSha256: localOutputArtifact.hashSha256 || "",
|
|
700
|
+
download: `${urlPrefix}/artifacts/${localOutputArtifact.artifactId}/download`
|
|
701
|
+
}
|
|
702
|
+
],
|
|
703
|
+
usage: envelope.usage,
|
|
704
|
+
warnings: envelope.warnings || []
|
|
705
|
+
};
|
|
706
|
+
await this.transitionOperation(op.operationId, {
|
|
707
|
+
state: "SUCCEEDED",
|
|
708
|
+
progress: { percent: 100, message: "SUCCEEDED" },
|
|
709
|
+
documentInputCoverage: remoteView.documentInputCoverage ?? null,
|
|
710
|
+
resultEnvelope: localEnvelope,
|
|
711
|
+
outputPayload,
|
|
712
|
+
usage: envelope.usage,
|
|
713
|
+
warnings: envelope.warnings || [],
|
|
714
|
+
completedAt: /* @__PURE__ */ new Date(),
|
|
715
|
+
leaseExpiresAt: null
|
|
716
|
+
});
|
|
717
|
+
await this.dispatchCallbackIfConfigured(op.operationId, urlPrefix);
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
if (["FAILED", "CANCELLED", "TIMED_OUT"].includes(remoteView.state)) {
|
|
721
|
+
await this.transitionOperation(op.operationId, {
|
|
722
|
+
state: remoteView.state,
|
|
723
|
+
progress: { percent: 100, message: remoteView.state },
|
|
724
|
+
errorProblem: remoteView.error || (0, import_du_contracts.createProblem)(500, remoteView.state, `Remote operation ended as ${remoteView.state}`),
|
|
725
|
+
completedAt: /* @__PURE__ */ new Date(),
|
|
726
|
+
leaseExpiresAt: null
|
|
727
|
+
});
|
|
728
|
+
await this.dispatchCallbackIfConfigured(op.operationId, urlPrefix);
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
732
|
+
}
|
|
733
|
+
await this.transitionOperation(op.operationId, {
|
|
734
|
+
state: "TIMED_OUT",
|
|
735
|
+
progress: { percent: 100, message: "TIMED_OUT" },
|
|
736
|
+
errorProblem: (0, import_du_contracts.createProblem)(504, "TIMED_OUT", "External gateway polling timed out"),
|
|
737
|
+
completedAt: /* @__PURE__ */ new Date(),
|
|
738
|
+
leaseExpiresAt: null
|
|
739
|
+
});
|
|
740
|
+
}
|
|
741
|
+
async transitionOperation(operationId, patch) {
|
|
742
|
+
const repo = this.db.getRepository(OPERATIONS_COLLECTION);
|
|
743
|
+
const currentRow = await repo.findOne({ filter: { operationId } });
|
|
744
|
+
if (!currentRow) return;
|
|
745
|
+
const current = toPlain(currentRow);
|
|
746
|
+
const nextVersion = (current.stateVersion || 1) + 1;
|
|
747
|
+
await repo.update({
|
|
748
|
+
filter: { operationId },
|
|
749
|
+
values: {
|
|
750
|
+
...patch,
|
|
751
|
+
stateVersion: nextVersion
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
this.stateEvents.emit(`op:${operationId}`, patch.state || current.state);
|
|
755
|
+
}
|
|
756
|
+
async dispatchCallbackIfConfigured(operationId, urlPrefix) {
|
|
757
|
+
var _a, _b, _c, _d, _e;
|
|
758
|
+
const row = await this.db.getRepository(OPERATIONS_COLLECTION).findOne({ filter: { operationId } });
|
|
759
|
+
if (!row) return;
|
|
760
|
+
const op = toPlain(row);
|
|
761
|
+
const callbackUrl = (_b = (_a = op.submission) == null ? void 0 : _a.callback) == null ? void 0 : _b.url;
|
|
762
|
+
if (!callbackUrl) return;
|
|
763
|
+
try {
|
|
764
|
+
const safeUrl = assertSafeOutboundCallbackUrl(callbackUrl);
|
|
765
|
+
const config = await this.getConfig();
|
|
766
|
+
const deliveryId = crypto.randomUUID();
|
|
767
|
+
const timestamp = Math.floor(Date.now() / 1e3).toString();
|
|
768
|
+
const mode = ((_c = op.submission.callback) == null ? void 0 : _c.mode) || "notification_only";
|
|
769
|
+
const payload = {
|
|
770
|
+
deliveryId,
|
|
771
|
+
operationId: op.operationId,
|
|
772
|
+
state: op.state,
|
|
773
|
+
stateVersion: op.stateVersion,
|
|
774
|
+
businessId: op.businessId,
|
|
775
|
+
action: op.action,
|
|
776
|
+
correlationId: op.correlationId,
|
|
777
|
+
clientReference: op.clientReference,
|
|
778
|
+
...op.state === "WAITING_INPUT" && op.waitState ? { wait: op.waitState } : {},
|
|
779
|
+
links: {
|
|
780
|
+
self: `${urlPrefix}/operations/${op.operationId}`,
|
|
781
|
+
result: `${urlPrefix}/operations/${op.operationId}/result`
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
if (mode === "notification_with_result" && op.state === "SUCCEEDED" && op.outputPayload) {
|
|
785
|
+
const serializedResult = JSON.stringify(op.outputPayload);
|
|
786
|
+
if (Buffer.byteLength(serializedResult, "utf8") <= MAX_INLINE_WEBHOOK_RESULT_BYTES) {
|
|
787
|
+
payload.result = op.outputPayload;
|
|
788
|
+
payload.usage = op.usage;
|
|
789
|
+
} else {
|
|
790
|
+
payload.resultTruncatedToLink = true;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
const rawBody = JSON.stringify(payload);
|
|
794
|
+
const headers = {
|
|
795
|
+
"Content-Type": "application/json",
|
|
796
|
+
"x-du-delivery-id": deliveryId,
|
|
797
|
+
"x-du-timestamp": timestamp
|
|
798
|
+
};
|
|
799
|
+
if (config.webhookSecret) {
|
|
800
|
+
const hmac = crypto.createHmac("sha256", config.webhookSecret).update(`${timestamp}.${rawBody}`).digest("hex");
|
|
801
|
+
headers["x-du-signature"] = `sha256=${hmac}`;
|
|
802
|
+
}
|
|
803
|
+
await import_axios.default.post(safeUrl, rawBody, {
|
|
804
|
+
headers,
|
|
805
|
+
timeout: 1e4,
|
|
806
|
+
maxRedirects: 0
|
|
807
|
+
// CALLBACK_REDIRECTS_ALLOWED = false per BRD Section 4.4
|
|
808
|
+
});
|
|
809
|
+
} catch (err) {
|
|
810
|
+
(_e = (_d = this.app.logger) == null ? void 0 : _d.warn) == null ? void 0 : _e.call(_d, `Outbound webhook delivery failed for operation ${operationId}`, err);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
/* ─── Query, Wait, Resume, Cancel, Result & Usage APIs ──────────── */
|
|
814
|
+
async getOperationRecordOrThrow(tenantId, operationId) {
|
|
815
|
+
const filter = tenantId === "*" ? { operationId } : { tenantId, operationId };
|
|
816
|
+
const row = await this.db.getRepository(OPERATIONS_COLLECTION).findOne({ filter });
|
|
817
|
+
if (!row) {
|
|
818
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(404, "NOT_FOUND", `Operation ${operationId} not found`));
|
|
819
|
+
}
|
|
820
|
+
return toPlain(row);
|
|
821
|
+
}
|
|
822
|
+
toOperationView(op, urlPrefix = "/api/du/v1") {
|
|
823
|
+
return {
|
|
824
|
+
id: op.operationId,
|
|
825
|
+
name: `operations/${op.operationId}`,
|
|
826
|
+
businessId: op.businessId,
|
|
827
|
+
businessVersion: op.businessVersion,
|
|
828
|
+
action: op.action,
|
|
829
|
+
state: op.state,
|
|
830
|
+
stateVersion: op.stateVersion,
|
|
831
|
+
...op.correlationId ? { correlationId: op.correlationId } : {},
|
|
832
|
+
...op.clientReference ? { clientReference: op.clientReference } : {},
|
|
833
|
+
createdAt: op.createdAt ? new Date(op.createdAt).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
|
|
834
|
+
updatedAt: op.updatedAt ? new Date(op.updatedAt).toISOString() : (/* @__PURE__ */ new Date()).toISOString(),
|
|
835
|
+
...op.deadlineAt ? { deadlineAt: new Date(op.deadlineAt).toISOString() } : {},
|
|
836
|
+
progress: op.progress || { percent: 0, message: op.state },
|
|
837
|
+
...op.state === "WAITING_INPUT" && op.waitState ? { wait: op.waitState } : {},
|
|
838
|
+
...op.documentInputCoverage ? { documentInputCoverage: op.documentInputCoverage } : {},
|
|
839
|
+
...op.usage ? { usage: op.usage } : {},
|
|
840
|
+
...op.errorProblem ? { error: op.errorProblem } : {},
|
|
841
|
+
links: {
|
|
842
|
+
self: `${urlPrefix}/operations/${op.operationId}`,
|
|
843
|
+
result: `${urlPrefix}/operations/${op.operationId}/result`
|
|
844
|
+
}
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
async waitForOperation(tenantId, operationId, waitSeconds = 0, urlPrefix = "/api/du/v1") {
|
|
848
|
+
const boundedSeconds = Math.max(0, Math.min(30, Number(waitSeconds) || 0));
|
|
849
|
+
const initial = await this.getOperationRecordOrThrow(tenantId, operationId);
|
|
850
|
+
if (boundedSeconds === 0 || import_du_contracts.TERMINAL_OPERATION_STATES.has(initial.state) || initial.state === "WAITING_INPUT") {
|
|
851
|
+
return this.toOperationView(initial, urlPrefix);
|
|
852
|
+
}
|
|
853
|
+
await new Promise((resolve) => {
|
|
854
|
+
const channel = `op:${operationId}`;
|
|
855
|
+
const timer = setTimeout(() => {
|
|
856
|
+
this.stateEvents.removeListener(channel, onState);
|
|
857
|
+
resolve();
|
|
858
|
+
}, boundedSeconds * 1e3);
|
|
859
|
+
function onState(nextState) {
|
|
860
|
+
if (import_du_contracts.TERMINAL_OPERATION_STATES.has(nextState) || nextState === "WAITING_INPUT") {
|
|
861
|
+
clearTimeout(timer);
|
|
862
|
+
resolve();
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
this.stateEvents.on(channel, onState);
|
|
866
|
+
});
|
|
867
|
+
const latest = await this.getOperationRecordOrThrow(tenantId, operationId);
|
|
868
|
+
return this.toOperationView(latest, urlPrefix);
|
|
869
|
+
}
|
|
870
|
+
async listOperations(params) {
|
|
871
|
+
const filter = {};
|
|
872
|
+
if (params.tenantId !== "*") filter.tenantId = params.tenantId;
|
|
873
|
+
if (params.state) filter.state = params.state;
|
|
874
|
+
if (params.businessId) filter.businessId = params.businessId;
|
|
875
|
+
if (params.action) filter.action = params.action;
|
|
876
|
+
if (params.from || params.to) {
|
|
877
|
+
const createdFilter = {};
|
|
878
|
+
if (params.from) createdFilter.$gte = new Date(params.from);
|
|
879
|
+
if (params.to) createdFilter.$lt = new Date(params.to);
|
|
880
|
+
filter.createdAt = createdFilter;
|
|
881
|
+
}
|
|
882
|
+
if (params.cursor && Number.isFinite(Number(params.cursor))) {
|
|
883
|
+
filter.id = { $lt: Number(params.cursor) };
|
|
884
|
+
}
|
|
885
|
+
const limit = Math.max(1, Math.min(100, Number(params.limit) || 20));
|
|
886
|
+
const rows = await this.db.getRepository(OPERATIONS_COLLECTION).find({
|
|
887
|
+
filter,
|
|
888
|
+
sort: ["-id"],
|
|
889
|
+
limit: limit + 1
|
|
890
|
+
});
|
|
891
|
+
const plains = rows.map((r) => toPlain(r));
|
|
892
|
+
const hasMore = plains.length > limit;
|
|
893
|
+
const slice = hasMore ? plains.slice(0, limit) : plains;
|
|
894
|
+
const lastId = slice.length > 0 ? slice[slice.length - 1].id : void 0;
|
|
895
|
+
return {
|
|
896
|
+
items: slice.map((op) => this.toOperationView(op, params.urlPrefix || "/api/du/v1")),
|
|
897
|
+
nextCursor: hasMore && lastId != null ? String(lastId) : null
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
async cancelOperation(tenantId, operationId) {
|
|
901
|
+
const op = await this.getOperationRecordOrThrow(tenantId, operationId);
|
|
902
|
+
if (op.state === "CANCELLED" || op.state === "CANCEL_REQUESTED") {
|
|
903
|
+
return {
|
|
904
|
+
httpStatus: 200,
|
|
905
|
+
operationId,
|
|
906
|
+
state: op.state,
|
|
907
|
+
stateVersion: op.stateVersion,
|
|
908
|
+
replayed: true
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
if (import_du_contracts.TERMINAL_OPERATION_STATES.has(op.state)) {
|
|
912
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
913
|
+
(0, import_du_contracts.createProblem)(409, "STATE_CONFLICT", `Cannot cancel terminal operation in state ${op.state}`)
|
|
914
|
+
);
|
|
915
|
+
}
|
|
916
|
+
if (op.externalOperationId) {
|
|
917
|
+
const config = await this.getConfig();
|
|
918
|
+
const ext = new import_ExternalDuReworkClient.ExternalDuReworkClient(config);
|
|
919
|
+
ext.cancelOperation(op.externalOperationId).catch(() => void 0);
|
|
920
|
+
}
|
|
921
|
+
const nextState = op.state === "WAITING_INPUT" || op.state === "ACCEPTED" || op.state === "QUEUED" ? "CANCELLED" : "CANCEL_REQUESTED";
|
|
922
|
+
await this.transitionOperation(operationId, {
|
|
923
|
+
state: nextState,
|
|
924
|
+
progress: { percent: 100, message: nextState },
|
|
925
|
+
...nextState === "CANCELLED" ? { completedAt: /* @__PURE__ */ new Date(), leaseExpiresAt: null } : {}
|
|
926
|
+
});
|
|
927
|
+
const updated = await this.getOperationRecordOrThrow(tenantId, operationId);
|
|
928
|
+
return {
|
|
929
|
+
httpStatus: 202,
|
|
930
|
+
operationId,
|
|
931
|
+
state: updated.state,
|
|
932
|
+
stateVersion: updated.stateVersion,
|
|
933
|
+
replayed: false
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
async resumeOperation(params) {
|
|
937
|
+
const op = await this.getOperationRecordOrThrow(params.tenantId, params.operationId);
|
|
938
|
+
if (op.state !== "WAITING_INPUT" || !op.waitState) {
|
|
939
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
940
|
+
(0, import_du_contracts.createProblem)(
|
|
941
|
+
409,
|
|
942
|
+
"STATE_CONFLICT",
|
|
943
|
+
`Operation ${params.operationId} is in state ${op.state}, expected WAITING_INPUT`
|
|
944
|
+
)
|
|
945
|
+
);
|
|
946
|
+
}
|
|
947
|
+
if (params.waitId && params.waitId !== op.waitState.waitId) {
|
|
948
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
949
|
+
(0, import_du_contracts.createProblem)(
|
|
950
|
+
409,
|
|
951
|
+
"STATE_CONFLICT",
|
|
952
|
+
`waitId mismatch (expected "${op.waitState.waitId}", got "${params.waitId}")`
|
|
953
|
+
)
|
|
954
|
+
);
|
|
955
|
+
}
|
|
956
|
+
if (params.expectedStateVersion !== void 0 && Number(params.expectedStateVersion) !== Number(op.stateVersion)) {
|
|
957
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
958
|
+
(0, import_du_contracts.createProblem)(
|
|
959
|
+
409,
|
|
960
|
+
"STATE_CONFLICT",
|
|
961
|
+
`expectedStateVersion mismatch (expected ${op.stateVersion}, got ${params.expectedStateVersion})`
|
|
962
|
+
)
|
|
963
|
+
);
|
|
964
|
+
}
|
|
965
|
+
const enrichedInput = {
|
|
966
|
+
...params.input,
|
|
967
|
+
...params.resumedBy && !params.input.approver ? { approver: params.resumedBy } : {}
|
|
968
|
+
};
|
|
969
|
+
await this.transitionOperation(params.operationId, {
|
|
970
|
+
state: "QUEUED",
|
|
971
|
+
progress: { percent: 60, message: "RESUMED" },
|
|
972
|
+
waitState: {
|
|
973
|
+
...op.waitState,
|
|
974
|
+
resumedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
975
|
+
resumedBy: params.resumedBy,
|
|
976
|
+
resumedInput: enrichedInput
|
|
977
|
+
}
|
|
978
|
+
});
|
|
979
|
+
const refreshed = await this.getOperationRecordOrThrow(params.tenantId, params.operationId);
|
|
980
|
+
this.runOperationInBackground(params.operationId, void 0, params.urlPrefix || "/api/du/v1", enrichedInput).catch(
|
|
981
|
+
(err) => {
|
|
982
|
+
var _a, _b;
|
|
983
|
+
(_b = (_a = this.app.logger) == null ? void 0 : _a.error) == null ? void 0 : _b.call(_a, `Failed resuming operation ${params.operationId}`, err);
|
|
984
|
+
}
|
|
985
|
+
);
|
|
986
|
+
return {
|
|
987
|
+
httpStatus: 202,
|
|
988
|
+
operationId: params.operationId,
|
|
989
|
+
state: refreshed.state,
|
|
990
|
+
stateVersion: refreshed.stateVersion,
|
|
991
|
+
replayed: false
|
|
992
|
+
};
|
|
993
|
+
}
|
|
994
|
+
async getOperationResult(tenantId, operationId) {
|
|
995
|
+
const op = await this.getOperationRecordOrThrow(tenantId, operationId);
|
|
996
|
+
if (op.state === "TIMED_OUT") {
|
|
997
|
+
throw new import_ArtifactStorageService.DuHttpError((0, import_du_contracts.createProblem)(410, "GONE", `Operation ${operationId} timed out`));
|
|
998
|
+
}
|
|
999
|
+
if (op.state !== "SUCCEEDED" || !op.resultEnvelope) {
|
|
1000
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
1001
|
+
(0, import_du_contracts.createProblem)(409, "STATE_CONFLICT", `Operation ${operationId} result is not ready (state=${op.state})`)
|
|
1002
|
+
);
|
|
1003
|
+
}
|
|
1004
|
+
return op.resultEnvelope;
|
|
1005
|
+
}
|
|
1006
|
+
async getUsageSummary(params) {
|
|
1007
|
+
const fromDate = new Date(params.from);
|
|
1008
|
+
const toDate = new Date(params.to);
|
|
1009
|
+
if (Number.isNaN(fromDate.getTime()) || Number.isNaN(toDate.getTime()) || fromDate >= toDate) {
|
|
1010
|
+
throw new import_ArtifactStorageService.DuHttpError(
|
|
1011
|
+
(0, import_du_contracts.createProblem)(422, "INVALID_SCHEMA", 'Query parameters "from" and "to" must be valid ISO dates with from < to')
|
|
1012
|
+
);
|
|
1013
|
+
}
|
|
1014
|
+
const filter = {
|
|
1015
|
+
createdAt: { $gte: fromDate, $lt: toDate }
|
|
1016
|
+
};
|
|
1017
|
+
if (params.tenantId !== "*") filter.tenantId = params.tenantId;
|
|
1018
|
+
const rows = await this.db.getRepository(OPERATIONS_COLLECTION).find({ filter });
|
|
1019
|
+
const plains = rows.map((r) => toPlain(r));
|
|
1020
|
+
let totalInput = 0;
|
|
1021
|
+
let totalOutput = 0;
|
|
1022
|
+
let totalCost = 0;
|
|
1023
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
1024
|
+
for (const op of plains) {
|
|
1025
|
+
const u = op.usage;
|
|
1026
|
+
const inTok = (u == null ? void 0 : u.inputTokens) || 0;
|
|
1027
|
+
const outTok = (u == null ? void 0 : u.outputTokens) || 0;
|
|
1028
|
+
const cost = (u == null ? void 0 : u.costMicrousd) || 0;
|
|
1029
|
+
totalInput += inTok;
|
|
1030
|
+
totalOutput += outTok;
|
|
1031
|
+
totalCost += cost;
|
|
1032
|
+
const key = `${op.businessId}:${op.action}`;
|
|
1033
|
+
const bucket = grouped.get(key) || {
|
|
1034
|
+
businessId: op.businessId,
|
|
1035
|
+
action: op.action,
|
|
1036
|
+
operations: 0,
|
|
1037
|
+
inputTokens: 0,
|
|
1038
|
+
outputTokens: 0,
|
|
1039
|
+
costMicrousd: 0
|
|
1040
|
+
};
|
|
1041
|
+
bucket.operations += 1;
|
|
1042
|
+
bucket.inputTokens += inTok;
|
|
1043
|
+
bucket.outputTokens += outTok;
|
|
1044
|
+
bucket.costMicrousd += cost;
|
|
1045
|
+
grouped.set(key, bucket);
|
|
1046
|
+
}
|
|
1047
|
+
return {
|
|
1048
|
+
from: fromDate.toISOString(),
|
|
1049
|
+
to: toDate.toISOString(),
|
|
1050
|
+
totalOperations: plains.length,
|
|
1051
|
+
inputTokens: totalInput,
|
|
1052
|
+
outputTokens: totalOutput,
|
|
1053
|
+
costMicrousd: totalCost,
|
|
1054
|
+
byBusiness: Array.from(grouped.values())
|
|
1055
|
+
};
|
|
1056
|
+
}
|
|
1057
|
+
async listUsageEvents(params) {
|
|
1058
|
+
const filter = {};
|
|
1059
|
+
if (params.tenantId !== "*") filter.tenantId = params.tenantId;
|
|
1060
|
+
if (params.operationId) filter.operationId = params.operationId;
|
|
1061
|
+
if (params.action) filter.action = params.action;
|
|
1062
|
+
const limit = Math.max(1, Math.min(200, Number(params.limit) || 50));
|
|
1063
|
+
const rows = await this.db.getRepository(OPERATIONS_COLLECTION).find({
|
|
1064
|
+
filter,
|
|
1065
|
+
sort: ["-createdAt"],
|
|
1066
|
+
limit
|
|
1067
|
+
});
|
|
1068
|
+
const items = rows.map((r) => toPlain(r)).filter((op) => {
|
|
1069
|
+
if (!op.usage) return false;
|
|
1070
|
+
if (params.model && op.usage.model !== params.model) return false;
|
|
1071
|
+
if (params.provider && op.usage.provider !== params.provider) return false;
|
|
1072
|
+
return true;
|
|
1073
|
+
}).map((op) => ({
|
|
1074
|
+
operationId: op.operationId,
|
|
1075
|
+
businessId: op.businessId,
|
|
1076
|
+
action: op.action,
|
|
1077
|
+
state: op.state,
|
|
1078
|
+
createdAt: op.createdAt,
|
|
1079
|
+
...op.usage
|
|
1080
|
+
}));
|
|
1081
|
+
return { items };
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1085
|
+
0 && (module.exports = {
|
|
1086
|
+
OperationOrchestrator
|
|
1087
|
+
});
|