avantgate 1.3.0 → 1.4.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/README.md +8 -3
- package/dist/agent/index.mjs +12 -279
- package/dist/agent/types.d.ts +4 -0
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/chunk-5VA3EKPJ.mjs +344 -0
- package/dist/chunk-DTM2OLCG.mjs +252 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +478 -0
- package/dist/index.mjs +13 -3
- package/dist/workflow/define-workflow.d.ts +3 -0
- package/dist/workflow/define-workflow.d.ts.map +1 -0
- package/dist/workflow/engine.d.ts +3 -0
- package/dist/workflow/engine.d.ts.map +1 -0
- package/dist/workflow/errors.d.ts +24 -0
- package/dist/workflow/errors.d.ts.map +1 -0
- package/dist/workflow/index.d.ts +5 -0
- package/dist/workflow/index.d.ts.map +1 -0
- package/dist/workflow/index.js +558 -0
- package/dist/workflow/index.mjs +13 -0
- package/dist/workflow/types.d.ts +64 -0
- package/dist/workflow/types.d.ts.map +1 -0
- package/package.json +9 -3
- package/dist/chunk-DVCF4CSV.mjs +0 -56
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
// src/sanitizer.ts
|
|
2
|
+
var EMAIL_REGEX = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b/g;
|
|
3
|
+
var PHONE_FR_REGEX = /\b(?:(?:\+|00)33|0)\s*[1-9](?:[\s.-]*\d{2}){4}\b/g;
|
|
4
|
+
var NIR_SSN_REGEX = /\b[12]\s*\d{2}\s*(?:0[1-9]|1[0-2]|[2-9]\d)\s*(?:0[1-9]|[1-8]\d|9[0-8]|2[ABab])\s*(?!000)\d{3}\s*(?!000)\d{3}(?:\s*\d{2})?\b/g;
|
|
5
|
+
var SPI_LABELLED_REGEX = /(?:(?:num[ée]ro\s+fiscal|spi|n[°o]\s*fiscal|d[ée]clarant(?: fiscal)?)\s*[:=]?\s*)\b(\d{2}(?:[\s.-]?\d{2}){5}[\s.-]?\d|\d{13})\b/gi;
|
|
6
|
+
var SPI_FORMATTED_REGEX = /\b[0-3]\d(?:\s+\d{2}){5}\s+\d\b/g;
|
|
7
|
+
var IBAN_REGEX = /\b[A-Z]{2}\s*[0-9]{2}(?:[\s\r\n.-]*[A-Z0-9]){11,30}\b/g;
|
|
8
|
+
var BIC_LABELLED_REGEX = /(?:(?:bic|swift)\s*[:=]?\s*)\b([A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?)\b/gi;
|
|
9
|
+
function sanitizePII(input) {
|
|
10
|
+
let count = 0;
|
|
11
|
+
let result = input;
|
|
12
|
+
result = result.replace(EMAIL_REGEX, () => {
|
|
13
|
+
count++;
|
|
14
|
+
return "[REDACTED_EMAIL]";
|
|
15
|
+
});
|
|
16
|
+
result = result.replace(PHONE_FR_REGEX, () => {
|
|
17
|
+
count++;
|
|
18
|
+
return "[REDACTED_PHONE]";
|
|
19
|
+
});
|
|
20
|
+
result = result.replace(IBAN_REGEX, (match) => {
|
|
21
|
+
const cleanChars = match.replace(/[\s\r\n.-]/g, "");
|
|
22
|
+
if (cleanChars.length >= 15 && cleanChars.length <= 34) {
|
|
23
|
+
count++;
|
|
24
|
+
return "[REDACTED_IBAN]";
|
|
25
|
+
}
|
|
26
|
+
return match;
|
|
27
|
+
});
|
|
28
|
+
result = result.replace(BIC_LABELLED_REGEX, (_, bicCode) => {
|
|
29
|
+
count++;
|
|
30
|
+
return `[REDACTED_BIC: ${bicCode.slice(0, 4)}****]`;
|
|
31
|
+
});
|
|
32
|
+
result = result.replace(SPI_LABELLED_REGEX, (fullMatch, digits) => {
|
|
33
|
+
count++;
|
|
34
|
+
return fullMatch.replace(digits, "[REDACTED_SPI]");
|
|
35
|
+
});
|
|
36
|
+
result = result.replace(NIR_SSN_REGEX, (match) => {
|
|
37
|
+
const rawDigits = match.replace(/\s+/g, "");
|
|
38
|
+
if (rawDigits.length === 13 || rawDigits.length === 15) {
|
|
39
|
+
count++;
|
|
40
|
+
return "[REDACTED_NIR]";
|
|
41
|
+
}
|
|
42
|
+
return match;
|
|
43
|
+
});
|
|
44
|
+
result = result.replace(SPI_FORMATTED_REGEX, (match) => {
|
|
45
|
+
if (!match.includes("[REDACTED")) {
|
|
46
|
+
count++;
|
|
47
|
+
return "[REDACTED_SPI]";
|
|
48
|
+
}
|
|
49
|
+
return match;
|
|
50
|
+
});
|
|
51
|
+
return { text: result, maskedCount: count };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// src/agent/errors.ts
|
|
55
|
+
var StepSuspendedError = class extends Error {
|
|
56
|
+
stepId;
|
|
57
|
+
workflowId;
|
|
58
|
+
metadata;
|
|
59
|
+
constructor(stepId, workflowId, metadata) {
|
|
60
|
+
super(`Step execution suspended for human approval: [${workflowId}::${stepId}]`);
|
|
61
|
+
this.name = "StepSuspendedError";
|
|
62
|
+
this.stepId = stepId;
|
|
63
|
+
this.workflowId = workflowId;
|
|
64
|
+
this.metadata = metadata;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
var PiiLeakError = class extends Error {
|
|
68
|
+
toolName;
|
|
69
|
+
maskedCount;
|
|
70
|
+
constructor(toolName, maskedCount) {
|
|
71
|
+
super(`PII leak detected in tool output for "${toolName}" (${maskedCount} occurrences detected).`);
|
|
72
|
+
this.name = "PiiLeakError";
|
|
73
|
+
this.toolName = toolName;
|
|
74
|
+
this.maskedCount = maskedCount;
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
var StepExecutionError = class extends Error {
|
|
78
|
+
stepId;
|
|
79
|
+
workflowId;
|
|
80
|
+
originalError;
|
|
81
|
+
constructor(stepId, workflowId, message, originalError) {
|
|
82
|
+
super(`Execution failed at step [${workflowId}::${stepId}]: ${message}`);
|
|
83
|
+
this.name = "StepExecutionError";
|
|
84
|
+
this.stepId = stepId;
|
|
85
|
+
this.workflowId = workflowId;
|
|
86
|
+
this.originalError = originalError;
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
var ToolAccessDeniedError = class extends Error {
|
|
90
|
+
toolName;
|
|
91
|
+
requiredRole;
|
|
92
|
+
reason;
|
|
93
|
+
constructor(toolName, reasonOrRole) {
|
|
94
|
+
const isRole = Boolean(reasonOrRole && !reasonOrRole.includes(" "));
|
|
95
|
+
const roleMsg = isRole ? ` (requires role "${reasonOrRole}")` : "";
|
|
96
|
+
const reasonMsg = reasonOrRole && !isRole ? `: ${reasonOrRole}` : "";
|
|
97
|
+
super(`Access denied for tool "${toolName}"${roleMsg}${reasonMsg}.`);
|
|
98
|
+
this.name = "ToolAccessDeniedError";
|
|
99
|
+
this.toolName = toolName;
|
|
100
|
+
if (isRole) {
|
|
101
|
+
this.requiredRole = reasonOrRole;
|
|
102
|
+
} else {
|
|
103
|
+
this.reason = reasonOrRole;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
var CircularToolCallError = class extends Error {
|
|
108
|
+
cycle;
|
|
109
|
+
constructor(cycle) {
|
|
110
|
+
super(`Circular tool call detected: ${cycle.join(" -> ")}`);
|
|
111
|
+
this.name = "CircularToolCallError";
|
|
112
|
+
this.cycle = cycle;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
var ToolCallDepthExceededError = class extends Error {
|
|
116
|
+
depth;
|
|
117
|
+
maxDepth;
|
|
118
|
+
constructor(depth, maxDepth) {
|
|
119
|
+
super(`Tool call depth limit exceeded: depth ${depth} exceeds max allowed depth of ${maxDepth}.`);
|
|
120
|
+
this.name = "ToolCallDepthExceededError";
|
|
121
|
+
this.depth = depth;
|
|
122
|
+
this.maxDepth = maxDepth;
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
var ToolSubCallQuotaError = class extends Error {
|
|
126
|
+
totalCalls;
|
|
127
|
+
maxCalls;
|
|
128
|
+
constructor(totalCalls, maxCalls) {
|
|
129
|
+
super(`Tool sub-call quota exceeded: ${totalCalls} calls exceeds session quota of ${maxCalls}.`);
|
|
130
|
+
this.name = "ToolSubCallQuotaError";
|
|
131
|
+
this.totalCalls = totalCalls;
|
|
132
|
+
this.maxCalls = maxCalls;
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
var ToolNotFoundError = class extends Error {
|
|
136
|
+
toolId;
|
|
137
|
+
constructor(toolId) {
|
|
138
|
+
super(`Tool not found in registry: "${toolId}".`);
|
|
139
|
+
this.name = "ToolNotFoundError";
|
|
140
|
+
this.toolId = toolId;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
var DtoValidationError = class extends Error {
|
|
144
|
+
toolName;
|
|
145
|
+
issues;
|
|
146
|
+
constructor(toolName, message, issues = []) {
|
|
147
|
+
super(`LLM DTO validation failed for tool "${toolName}": ${message}`);
|
|
148
|
+
this.name = "DtoValidationError";
|
|
149
|
+
this.toolName = toolName;
|
|
150
|
+
this.issues = issues;
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
// src/agent/guardrails.ts
|
|
155
|
+
function sanitizeString(value) {
|
|
156
|
+
const result = sanitizePII(value);
|
|
157
|
+
return { text: result.text, count: result.maskedCount };
|
|
158
|
+
}
|
|
159
|
+
function sanitizeArray(items, options, visited) {
|
|
160
|
+
let totalCount = 0;
|
|
161
|
+
const sanitized = items.map((item) => {
|
|
162
|
+
const res = recursivelySanitize(item, options, visited);
|
|
163
|
+
totalCount += res.count;
|
|
164
|
+
return res.sanitized;
|
|
165
|
+
});
|
|
166
|
+
return { sanitized, count: totalCount };
|
|
167
|
+
}
|
|
168
|
+
function sanitizeObject(target, options, visited) {
|
|
169
|
+
let totalCount = 0;
|
|
170
|
+
const copy = {};
|
|
171
|
+
for (const [key, val] of Object.entries(target)) {
|
|
172
|
+
const res = recursivelySanitize(val, options, visited);
|
|
173
|
+
copy[key] = res.sanitized;
|
|
174
|
+
totalCount += res.count;
|
|
175
|
+
}
|
|
176
|
+
return { sanitized: copy, count: totalCount };
|
|
177
|
+
}
|
|
178
|
+
function recursivelySanitize(data, options, visited = /* @__PURE__ */ new WeakSet()) {
|
|
179
|
+
if (typeof data === "string") {
|
|
180
|
+
const res = sanitizeString(data);
|
|
181
|
+
return { sanitized: res.text, count: res.count };
|
|
182
|
+
}
|
|
183
|
+
if (data !== null && typeof data === "object") {
|
|
184
|
+
if (visited.has(data)) {
|
|
185
|
+
return { sanitized: "[CIRCULAR_REFERENCE]", count: 0 };
|
|
186
|
+
}
|
|
187
|
+
visited.add(data);
|
|
188
|
+
if (Array.isArray(data)) {
|
|
189
|
+
return sanitizeArray(data, options, visited);
|
|
190
|
+
}
|
|
191
|
+
return sanitizeObject(data, options, visited);
|
|
192
|
+
}
|
|
193
|
+
return { sanitized: data, count: 0 };
|
|
194
|
+
}
|
|
195
|
+
function auditToolResult(data, options) {
|
|
196
|
+
const { sanitized, count } = recursivelySanitize(data, options);
|
|
197
|
+
if (options.throwOnPii && count > 0) {
|
|
198
|
+
throw new PiiLeakError(options.toolName, count);
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
sanitizedData: sanitized,
|
|
202
|
+
maskedCount: count
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
// src/agent/isolated-tool.ts
|
|
207
|
+
async function verifyDataAccessGuard(guard, args, context, toolIdentifier) {
|
|
208
|
+
if (!guard) {
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
const isAllowed = await guard(args, context);
|
|
212
|
+
if (!isAllowed) {
|
|
213
|
+
throw new ToolAccessDeniedError(toolIdentifier, "Access denied by data access guard");
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
async function resolveInvalidationTags(config, args, rawResult, context) {
|
|
217
|
+
if (!config.invalidationTags) {
|
|
218
|
+
return void 0;
|
|
219
|
+
}
|
|
220
|
+
const tags = typeof config.invalidationTags === "function" ? await config.invalidationTags(args, rawResult) : config.invalidationTags;
|
|
221
|
+
if (tags && tags.length > 0 && context?.onInvalidationTags) {
|
|
222
|
+
await context.onInvalidationTags(tags);
|
|
223
|
+
}
|
|
224
|
+
return tags;
|
|
225
|
+
}
|
|
226
|
+
async function dispatchClientData(rawResult, callback) {
|
|
227
|
+
if (!callback) {
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
await callback(rawResult);
|
|
231
|
+
}
|
|
232
|
+
async function produceLlmPayload(rawResult, args, context, transformer) {
|
|
233
|
+
if (transformer) {
|
|
234
|
+
return await transformer(rawResult, args, context);
|
|
235
|
+
}
|
|
236
|
+
return rawResult;
|
|
237
|
+
}
|
|
238
|
+
function validateLlmDto(payload, schema, toolIdentifier) {
|
|
239
|
+
const parseResult = schema.safeParse(payload);
|
|
240
|
+
if (!parseResult.success) {
|
|
241
|
+
const issues = parseResult.error.issues ?? [];
|
|
242
|
+
const errorMessages = issues.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`).join(", ");
|
|
243
|
+
throw new DtoValidationError(
|
|
244
|
+
toolIdentifier,
|
|
245
|
+
errorMessages,
|
|
246
|
+
issues
|
|
247
|
+
);
|
|
248
|
+
}
|
|
249
|
+
return parseResult.data;
|
|
250
|
+
}
|
|
251
|
+
function protectLlmPayload(payload, toolIdentifier, sanitizePii = true, throwOnPii = false) {
|
|
252
|
+
if (!sanitizePii) {
|
|
253
|
+
return { sanitized: payload, count: 0 };
|
|
254
|
+
}
|
|
255
|
+
const { sanitizedData, maskedCount } = auditToolResult(payload, {
|
|
256
|
+
toolName: toolIdentifier,
|
|
257
|
+
throwOnPii
|
|
258
|
+
});
|
|
259
|
+
return { sanitized: sanitizedData, count: maskedCount };
|
|
260
|
+
}
|
|
261
|
+
async function processLlmPayload(rawResult, args, context, config, toolIdentifier) {
|
|
262
|
+
let payload = await produceLlmPayload(rawResult, args, context, config.llmDto);
|
|
263
|
+
if (config.llmDtoSchema) {
|
|
264
|
+
payload = validateLlmDto(payload, config.llmDtoSchema, toolIdentifier);
|
|
265
|
+
}
|
|
266
|
+
return protectLlmPayload(
|
|
267
|
+
payload,
|
|
268
|
+
toolIdentifier,
|
|
269
|
+
config.sanitizePii !== false,
|
|
270
|
+
config.throwOnPii === true
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
function createIsolatedTool(config) {
|
|
274
|
+
const toolId = config.id || config.name;
|
|
275
|
+
const toolAlias = config.alias;
|
|
276
|
+
const clientCallback = config.clientDto;
|
|
277
|
+
const toolIdentifier = toolAlias || config.name;
|
|
278
|
+
const toolImpact = config.impact ?? "READ_ONLY";
|
|
279
|
+
const requireApproval = config.requireApproval ?? toolImpact === "DESTRUCTIVE";
|
|
280
|
+
const tool = {
|
|
281
|
+
description: config.description,
|
|
282
|
+
parameters: config.parameters,
|
|
283
|
+
_toolId: toolId,
|
|
284
|
+
_toolName: config.name,
|
|
285
|
+
_toolAlias: toolAlias,
|
|
286
|
+
_isIsolated: true,
|
|
287
|
+
_cacheTTL: config.cacheTTL,
|
|
288
|
+
_domain: config.domain,
|
|
289
|
+
_resource: config.resource,
|
|
290
|
+
_roles: config.roles ? Object.freeze([...config.roles]) : void 0,
|
|
291
|
+
_impact: toolImpact,
|
|
292
|
+
_requireApproval: requireApproval,
|
|
293
|
+
_lastPiiFilteredCount: 0,
|
|
294
|
+
_lastInvalidationTags: void 0,
|
|
295
|
+
async execute(args, context) {
|
|
296
|
+
const updatedContext = {
|
|
297
|
+
...context,
|
|
298
|
+
callChain: context?.callChain ?? Object.freeze([toolId])
|
|
299
|
+
};
|
|
300
|
+
await verifyDataAccessGuard(
|
|
301
|
+
config.dataAccessGuard,
|
|
302
|
+
args,
|
|
303
|
+
updatedContext,
|
|
304
|
+
toolIdentifier
|
|
305
|
+
);
|
|
306
|
+
const rawResult = await config.execute(args, updatedContext);
|
|
307
|
+
const tags = await resolveInvalidationTags(
|
|
308
|
+
config,
|
|
309
|
+
args,
|
|
310
|
+
rawResult,
|
|
311
|
+
updatedContext
|
|
312
|
+
);
|
|
313
|
+
if (tags) {
|
|
314
|
+
tool._lastInvalidationTags = tags;
|
|
315
|
+
}
|
|
316
|
+
await dispatchClientData(rawResult, clientCallback);
|
|
317
|
+
const protection = await processLlmPayload(
|
|
318
|
+
rawResult,
|
|
319
|
+
args,
|
|
320
|
+
updatedContext,
|
|
321
|
+
config,
|
|
322
|
+
toolIdentifier
|
|
323
|
+
);
|
|
324
|
+
tool._lastPiiFilteredCount = protection.count;
|
|
325
|
+
return protection.sanitized;
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
return tool;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
export {
|
|
332
|
+
sanitizePII,
|
|
333
|
+
StepSuspendedError,
|
|
334
|
+
PiiLeakError,
|
|
335
|
+
StepExecutionError,
|
|
336
|
+
ToolAccessDeniedError,
|
|
337
|
+
CircularToolCallError,
|
|
338
|
+
ToolCallDepthExceededError,
|
|
339
|
+
ToolSubCallQuotaError,
|
|
340
|
+
ToolNotFoundError,
|
|
341
|
+
DtoValidationError,
|
|
342
|
+
auditToolResult,
|
|
343
|
+
createIsolatedTool
|
|
344
|
+
};
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
import {
|
|
2
|
+
StepSuspendedError,
|
|
3
|
+
createIsolatedTool
|
|
4
|
+
} from "./chunk-5VA3EKPJ.mjs";
|
|
5
|
+
|
|
6
|
+
// src/workflow/errors.ts
|
|
7
|
+
var WorkflowSagaRollbackError = class extends Error {
|
|
8
|
+
workflowId;
|
|
9
|
+
failedStepId;
|
|
10
|
+
originalError;
|
|
11
|
+
compensatedSteps;
|
|
12
|
+
failedCompensations;
|
|
13
|
+
constructor(params) {
|
|
14
|
+
const errorDetails = params.originalError instanceof Error ? params.originalError.message : String(params.originalError);
|
|
15
|
+
super(
|
|
16
|
+
`\xC9chec de l'\xE9tape '${params.failedStepId}' dans le workflow '${params.workflowId}'. Rollback Saga ex\xE9cut\xE9 sur [${params.compensatedSteps.join(", ")}]. Cause initiale: ${errorDetails}`
|
|
17
|
+
);
|
|
18
|
+
this.name = "WorkflowSagaRollbackError";
|
|
19
|
+
this.workflowId = params.workflowId;
|
|
20
|
+
this.failedStepId = params.failedStepId;
|
|
21
|
+
this.originalError = params.originalError;
|
|
22
|
+
this.compensatedSteps = params.compensatedSteps;
|
|
23
|
+
this.failedCompensations = params.failedCompensations ?? [];
|
|
24
|
+
}
|
|
25
|
+
};
|
|
26
|
+
var WorkflowValidationError = class extends Error {
|
|
27
|
+
workflowId;
|
|
28
|
+
issues;
|
|
29
|
+
constructor(workflowId, issues) {
|
|
30
|
+
super(`Validation des entr\xE9es \xE9chou\xE9e pour le workflow '${workflowId}'.`);
|
|
31
|
+
this.name = "WorkflowValidationError";
|
|
32
|
+
this.workflowId = workflowId;
|
|
33
|
+
this.issues = issues;
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/workflow/engine.ts
|
|
38
|
+
function generateRunId(workflowId) {
|
|
39
|
+
const timestamp = Date.now();
|
|
40
|
+
const randomSuffix = Math.random().toString(36).substring(2, 9);
|
|
41
|
+
return `run_${workflowId}_${timestamp}_${randomSuffix}`;
|
|
42
|
+
}
|
|
43
|
+
function validateInput(config, input) {
|
|
44
|
+
const parseResult = config.inputSchema.safeParse(input);
|
|
45
|
+
if (!parseResult.success) {
|
|
46
|
+
throw new WorkflowValidationError(config.id, parseResult.error.issues);
|
|
47
|
+
}
|
|
48
|
+
return parseResult.data;
|
|
49
|
+
}
|
|
50
|
+
function createStepContext(params) {
|
|
51
|
+
const { workflowId, stepId, runId, context, stepResults } = params;
|
|
52
|
+
return {
|
|
53
|
+
workflowId,
|
|
54
|
+
stepId,
|
|
55
|
+
runId,
|
|
56
|
+
tenantId: context?.tenantId,
|
|
57
|
+
userId: context?.userId,
|
|
58
|
+
services: context?.services ?? {},
|
|
59
|
+
storage: context?.storage,
|
|
60
|
+
getStepResult: (id) => stepResults[id],
|
|
61
|
+
waitForApproval: async (options) => {
|
|
62
|
+
if (context?.storage) {
|
|
63
|
+
const existing = await context.storage.getStep(workflowId, stepId);
|
|
64
|
+
if (existing && existing.status === "COMPLETED") {
|
|
65
|
+
return existing.result ?? options?.defaultResult;
|
|
66
|
+
}
|
|
67
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
68
|
+
await context.storage.saveStep({
|
|
69
|
+
workflowId,
|
|
70
|
+
stepId,
|
|
71
|
+
runId,
|
|
72
|
+
status: "WAITING_APPROVAL",
|
|
73
|
+
metadata: options?.metadata,
|
|
74
|
+
createdAt: now,
|
|
75
|
+
updatedAt: now
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
throw new StepSuspendedError(stepId, workflowId, options?.prompt);
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
async function rollbackSaga(params) {
|
|
83
|
+
const {
|
|
84
|
+
workflowId,
|
|
85
|
+
failedStepId,
|
|
86
|
+
originalError,
|
|
87
|
+
completedSteps,
|
|
88
|
+
input,
|
|
89
|
+
runId,
|
|
90
|
+
context,
|
|
91
|
+
stepResults
|
|
92
|
+
} = params;
|
|
93
|
+
const compensatedSteps = [];
|
|
94
|
+
const failedCompensations = [];
|
|
95
|
+
for (let i = completedSteps.length - 1; i >= 0; i--) {
|
|
96
|
+
const { step, result } = completedSteps[i];
|
|
97
|
+
if (!step.compensate) {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const stepCtx = createStepContext({
|
|
101
|
+
workflowId,
|
|
102
|
+
stepId: step.id,
|
|
103
|
+
runId,
|
|
104
|
+
context,
|
|
105
|
+
stepResults
|
|
106
|
+
});
|
|
107
|
+
try {
|
|
108
|
+
await step.compensate(result, input, stepCtx);
|
|
109
|
+
compensatedSteps.push(step.id);
|
|
110
|
+
if (context?.storage) {
|
|
111
|
+
await context.storage.updateStepStatus(workflowId, step.id, "FAILED", {
|
|
112
|
+
metadata: { compensated: true }
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
} catch (compensationError) {
|
|
116
|
+
failedCompensations.push({ stepId: step.id, error: compensationError });
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
throw new WorkflowSagaRollbackError({
|
|
120
|
+
workflowId,
|
|
121
|
+
failedStepId,
|
|
122
|
+
originalError,
|
|
123
|
+
compensatedSteps,
|
|
124
|
+
failedCompensations
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
async function executeWorkflow(config, rawInput, context) {
|
|
128
|
+
const input = validateInput(config, rawInput);
|
|
129
|
+
const runId = context?.runId ?? generateRunId(config.id);
|
|
130
|
+
const stepResults = {};
|
|
131
|
+
const completedSteps = [];
|
|
132
|
+
for (const step of config.steps) {
|
|
133
|
+
const stepCtx = createStepContext({
|
|
134
|
+
workflowId: config.id,
|
|
135
|
+
stepId: step.id,
|
|
136
|
+
runId,
|
|
137
|
+
context,
|
|
138
|
+
stepResults
|
|
139
|
+
});
|
|
140
|
+
try {
|
|
141
|
+
const result = await step.execute(input, stepCtx);
|
|
142
|
+
stepResults[step.id] = result;
|
|
143
|
+
completedSteps.push({ step, result });
|
|
144
|
+
if (context?.storage) {
|
|
145
|
+
await context.storage.updateStepStatus(config.id, step.id, "COMPLETED", { result });
|
|
146
|
+
}
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (error instanceof StepSuspendedError) {
|
|
149
|
+
return {
|
|
150
|
+
workflowId: config.id,
|
|
151
|
+
runId,
|
|
152
|
+
status: "WAITING_APPROVAL",
|
|
153
|
+
stepResults
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
await rollbackSaga({
|
|
157
|
+
workflowId: config.id,
|
|
158
|
+
failedStepId: step.id,
|
|
159
|
+
originalError: error,
|
|
160
|
+
completedSteps,
|
|
161
|
+
input,
|
|
162
|
+
runId,
|
|
163
|
+
context,
|
|
164
|
+
stepResults
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const finalOutput = config.outputDto ? config.outputDto(stepResults, input) : stepResults;
|
|
169
|
+
return {
|
|
170
|
+
workflowId: config.id,
|
|
171
|
+
runId,
|
|
172
|
+
status: "COMPLETED",
|
|
173
|
+
stepResults,
|
|
174
|
+
output: finalOutput
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// src/workflow/define-workflow.ts
|
|
179
|
+
function resolveWorkflowImpact(config, options) {
|
|
180
|
+
if (options?.impact) {
|
|
181
|
+
return options.impact;
|
|
182
|
+
}
|
|
183
|
+
return config.impact ?? "MUTATIVE";
|
|
184
|
+
}
|
|
185
|
+
function resolveRequireApproval(impact, options) {
|
|
186
|
+
if (options?.requireApproval !== void 0) {
|
|
187
|
+
return options.requireApproval;
|
|
188
|
+
}
|
|
189
|
+
return impact === "DESTRUCTIVE";
|
|
190
|
+
}
|
|
191
|
+
function buildToolExecutionContext(options, toolCtx) {
|
|
192
|
+
const tenantId = typeof toolCtx?.tenantId === "string" ? toolCtx.tenantId : options?.defaultContext?.tenantId;
|
|
193
|
+
const userId = typeof toolCtx?.userId === "string" ? toolCtx.userId : options?.defaultContext?.userId;
|
|
194
|
+
return {
|
|
195
|
+
tenantId,
|
|
196
|
+
userId,
|
|
197
|
+
services: options?.defaultContext?.services ?? {},
|
|
198
|
+
storage: options?.storage ?? options?.defaultContext?.storage
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
function defineWorkflow(config) {
|
|
202
|
+
const workflowImpact = config.impact ?? "MUTATIVE";
|
|
203
|
+
return {
|
|
204
|
+
id: config.id,
|
|
205
|
+
name: config.name,
|
|
206
|
+
description: config.description,
|
|
207
|
+
impact: workflowImpact,
|
|
208
|
+
roles: config.roles,
|
|
209
|
+
config,
|
|
210
|
+
execute: async (input, context) => {
|
|
211
|
+
return await executeWorkflow(config, input, context);
|
|
212
|
+
},
|
|
213
|
+
asTool: (options) => {
|
|
214
|
+
const impact = resolveWorkflowImpact(config, options);
|
|
215
|
+
const requireApproval = resolveRequireApproval(impact, options);
|
|
216
|
+
const tool = createIsolatedTool({
|
|
217
|
+
name: config.id,
|
|
218
|
+
description: config.description ?? config.name,
|
|
219
|
+
roles: config.roles,
|
|
220
|
+
impact,
|
|
221
|
+
requireApproval,
|
|
222
|
+
parameters: config.inputSchema,
|
|
223
|
+
invalidationTags: typeof config.invalidationTags === "function" ? async (args, res) => {
|
|
224
|
+
const resolver = config.invalidationTags;
|
|
225
|
+
return await resolver(args, res ?? {});
|
|
226
|
+
} : config.invalidationTags,
|
|
227
|
+
execute: async (args, toolCtx) => {
|
|
228
|
+
const executionContext = buildToolExecutionContext(options, toolCtx);
|
|
229
|
+
const result = await executeWorkflow(config, args, executionContext);
|
|
230
|
+
return result.output;
|
|
231
|
+
},
|
|
232
|
+
llmDto: (result) => result
|
|
233
|
+
});
|
|
234
|
+
Object.assign(tool, {
|
|
235
|
+
_isWorkflow: true,
|
|
236
|
+
workflowId: config.id,
|
|
237
|
+
workflowConfig: {
|
|
238
|
+
totalSteps: config.steps.length,
|
|
239
|
+
impact
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
return tool;
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export {
|
|
248
|
+
WorkflowSagaRollbackError,
|
|
249
|
+
WorkflowValidationError,
|
|
250
|
+
executeWorkflow,
|
|
251
|
+
defineWorkflow
|
|
252
|
+
};
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC;AACrC,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC;AAC1B,cAAc,yBAAyB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,WAAW,CAAC;AAC1B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC;AAC9B,cAAc,sBAAsB,CAAC;AACrC,cAAc,iBAAiB,CAAC;AAChC,cAAc,WAAW,CAAC;AAC1B,cAAc,yBAAyB,CAAC;AACxC,cAAc,YAAY,CAAC"}
|