avantgate 1.3.0 → 1.5.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 +5 -1
- package/dist/agent/types.d.ts.map +1 -1
- package/dist/chunk-4XWO3NZW.mjs +303 -0
- package/dist/chunk-5VA3EKPJ.mjs +344 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +531 -0
- package/dist/index.mjs +17 -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 +31 -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 +611 -0
- package/dist/workflow/index.mjs +17 -0
- package/dist/workflow/types.d.ts +67 -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,303 @@
|
|
|
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
|
+
var WorkflowAbortSignal = class extends Error {
|
|
37
|
+
__isWorkflowAbort = true;
|
|
38
|
+
reason;
|
|
39
|
+
payload;
|
|
40
|
+
constructor(reason, payload) {
|
|
41
|
+
super(`Workflow aborted: ${reason}`);
|
|
42
|
+
this.name = "WorkflowAbortSignal";
|
|
43
|
+
this.reason = reason;
|
|
44
|
+
this.payload = payload;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
var isWorkflowAbortSignal = (value) => {
|
|
48
|
+
return typeof value === "object" && value !== null && value.__isWorkflowAbort === true;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
// src/workflow/engine.ts
|
|
52
|
+
var generateRunId = (workflowId) => {
|
|
53
|
+
const timestamp = Date.now();
|
|
54
|
+
const randomSuffix = Math.random().toString(36).substring(2, 9);
|
|
55
|
+
return `run_${workflowId}_${timestamp}_${randomSuffix}`;
|
|
56
|
+
};
|
|
57
|
+
var validateInput = (config, input) => {
|
|
58
|
+
const parseResult = config.inputSchema.safeParse(input);
|
|
59
|
+
if (!parseResult.success) {
|
|
60
|
+
throw new WorkflowValidationError(config.id, parseResult.error.issues);
|
|
61
|
+
}
|
|
62
|
+
return parseResult.data;
|
|
63
|
+
};
|
|
64
|
+
var createStepContext = (params) => {
|
|
65
|
+
const { workflowId, stepId, runId, context, stepResults } = params;
|
|
66
|
+
return {
|
|
67
|
+
workflowId,
|
|
68
|
+
stepId,
|
|
69
|
+
runId,
|
|
70
|
+
tenantId: context?.tenantId,
|
|
71
|
+
userId: context?.userId,
|
|
72
|
+
services: context?.services ?? {},
|
|
73
|
+
storage: context?.storage,
|
|
74
|
+
getStepResult: (id) => stepResults[id],
|
|
75
|
+
waitForApproval: async (options) => {
|
|
76
|
+
if (context?.storage) {
|
|
77
|
+
const existing = await context.storage.getStep(workflowId, stepId);
|
|
78
|
+
if (existing && existing.status === "COMPLETED") {
|
|
79
|
+
return existing.result ?? options?.defaultResult;
|
|
80
|
+
}
|
|
81
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
82
|
+
await context.storage.saveStep({
|
|
83
|
+
workflowId,
|
|
84
|
+
stepId,
|
|
85
|
+
runId,
|
|
86
|
+
status: "WAITING_APPROVAL",
|
|
87
|
+
metadata: options?.metadata,
|
|
88
|
+
createdAt: now,
|
|
89
|
+
updatedAt: now
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
throw new StepSuspendedError(stepId, workflowId, options?.prompt);
|
|
93
|
+
},
|
|
94
|
+
abort: (reason, payload) => {
|
|
95
|
+
throw new WorkflowAbortSignal(reason, payload);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
};
|
|
99
|
+
var rollbackSaga = async (params) => {
|
|
100
|
+
const {
|
|
101
|
+
workflowId,
|
|
102
|
+
failedStepId,
|
|
103
|
+
originalError,
|
|
104
|
+
completedSteps,
|
|
105
|
+
input,
|
|
106
|
+
runId,
|
|
107
|
+
context,
|
|
108
|
+
stepResults
|
|
109
|
+
} = params;
|
|
110
|
+
const compensatedSteps = [];
|
|
111
|
+
const failedCompensations = [];
|
|
112
|
+
for (let i = completedSteps.length - 1; i >= 0; i--) {
|
|
113
|
+
const { step, result } = completedSteps[i];
|
|
114
|
+
if (!step.compensate) {
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
const stepCtx = createStepContext({
|
|
118
|
+
workflowId,
|
|
119
|
+
stepId: step.id,
|
|
120
|
+
runId,
|
|
121
|
+
context,
|
|
122
|
+
stepResults
|
|
123
|
+
});
|
|
124
|
+
try {
|
|
125
|
+
await step.compensate(result, input, stepCtx);
|
|
126
|
+
compensatedSteps.push(step.id);
|
|
127
|
+
if (context?.storage) {
|
|
128
|
+
await context.storage.updateStepStatus(workflowId, step.id, "FAILED", {
|
|
129
|
+
metadata: { compensated: true }
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
} catch (compensationError) {
|
|
133
|
+
failedCompensations.push({ stepId: step.id, error: compensationError });
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
throw new WorkflowSagaRollbackError({
|
|
137
|
+
workflowId,
|
|
138
|
+
failedStepId,
|
|
139
|
+
originalError,
|
|
140
|
+
compensatedSteps,
|
|
141
|
+
failedCompensations
|
|
142
|
+
});
|
|
143
|
+
};
|
|
144
|
+
var executeWorkflow = async (config, rawInput, context) => {
|
|
145
|
+
const input = validateInput(config, rawInput);
|
|
146
|
+
const runId = context?.runId ?? generateRunId(config.id);
|
|
147
|
+
const stepResults = {};
|
|
148
|
+
const completedSteps = [];
|
|
149
|
+
const handleAbort = async (stepId, signal) => {
|
|
150
|
+
stepResults[stepId] = {
|
|
151
|
+
aborted: true,
|
|
152
|
+
reason: signal.reason,
|
|
153
|
+
payload: signal.payload
|
|
154
|
+
};
|
|
155
|
+
if (context?.storage) {
|
|
156
|
+
await context.storage.updateStepStatus(config.id, stepId, "ABORTED", {
|
|
157
|
+
result: signal.payload,
|
|
158
|
+
metadata: { abortReason: signal.reason }
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
const abortOutput = signal.payload ?? {
|
|
162
|
+
aborted: true,
|
|
163
|
+
reason: signal.reason
|
|
164
|
+
};
|
|
165
|
+
return {
|
|
166
|
+
workflowId: config.id,
|
|
167
|
+
runId,
|
|
168
|
+
status: "ABORTED",
|
|
169
|
+
stepResults,
|
|
170
|
+
abortReason: signal.reason,
|
|
171
|
+
abortPayload: signal.payload,
|
|
172
|
+
output: abortOutput
|
|
173
|
+
};
|
|
174
|
+
};
|
|
175
|
+
for (const step of config.steps) {
|
|
176
|
+
const stepCtx = createStepContext({
|
|
177
|
+
workflowId: config.id,
|
|
178
|
+
stepId: step.id,
|
|
179
|
+
runId,
|
|
180
|
+
context,
|
|
181
|
+
stepResults
|
|
182
|
+
});
|
|
183
|
+
try {
|
|
184
|
+
const result = await step.execute(input, stepCtx);
|
|
185
|
+
if (isWorkflowAbortSignal(result)) {
|
|
186
|
+
return await handleAbort(step.id, result);
|
|
187
|
+
}
|
|
188
|
+
stepResults[step.id] = result;
|
|
189
|
+
completedSteps.push({ step, result });
|
|
190
|
+
if (context?.storage) {
|
|
191
|
+
await context.storage.updateStepStatus(config.id, step.id, "COMPLETED", { result });
|
|
192
|
+
}
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (error instanceof StepSuspendedError) {
|
|
195
|
+
return {
|
|
196
|
+
workflowId: config.id,
|
|
197
|
+
runId,
|
|
198
|
+
status: "WAITING_APPROVAL",
|
|
199
|
+
stepResults
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
if (isWorkflowAbortSignal(error)) {
|
|
203
|
+
return await handleAbort(step.id, error);
|
|
204
|
+
}
|
|
205
|
+
await rollbackSaga({
|
|
206
|
+
workflowId: config.id,
|
|
207
|
+
failedStepId: step.id,
|
|
208
|
+
originalError: error,
|
|
209
|
+
completedSteps,
|
|
210
|
+
input,
|
|
211
|
+
runId,
|
|
212
|
+
context,
|
|
213
|
+
stepResults
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const finalOutput = config.outputDto ? config.outputDto(stepResults, input) : stepResults;
|
|
218
|
+
return {
|
|
219
|
+
workflowId: config.id,
|
|
220
|
+
runId,
|
|
221
|
+
status: "COMPLETED",
|
|
222
|
+
stepResults,
|
|
223
|
+
output: finalOutput
|
|
224
|
+
};
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
// src/workflow/define-workflow.ts
|
|
228
|
+
var resolveWorkflowImpact = (config, options) => {
|
|
229
|
+
if (options?.impact) {
|
|
230
|
+
return options.impact;
|
|
231
|
+
}
|
|
232
|
+
return config.impact ?? "MUTATIVE";
|
|
233
|
+
};
|
|
234
|
+
var resolveRequireApproval = (impact, options) => {
|
|
235
|
+
if (options?.requireApproval !== void 0) {
|
|
236
|
+
return options.requireApproval;
|
|
237
|
+
}
|
|
238
|
+
return impact === "DESTRUCTIVE";
|
|
239
|
+
};
|
|
240
|
+
var buildToolExecutionContext = (options, toolCtx) => {
|
|
241
|
+
const tenantId = typeof toolCtx?.tenantId === "string" ? toolCtx.tenantId : options?.defaultContext?.tenantId;
|
|
242
|
+
const userId = typeof toolCtx?.userId === "string" ? toolCtx.userId : options?.defaultContext?.userId;
|
|
243
|
+
return {
|
|
244
|
+
tenantId,
|
|
245
|
+
userId,
|
|
246
|
+
services: options?.defaultContext?.services ?? {},
|
|
247
|
+
storage: options?.storage ?? options?.defaultContext?.storage
|
|
248
|
+
};
|
|
249
|
+
};
|
|
250
|
+
var defineWorkflow = (config) => {
|
|
251
|
+
const workflowImpact = config.impact ?? "MUTATIVE";
|
|
252
|
+
return {
|
|
253
|
+
id: config.id,
|
|
254
|
+
name: config.name,
|
|
255
|
+
description: config.description,
|
|
256
|
+
impact: workflowImpact,
|
|
257
|
+
roles: config.roles,
|
|
258
|
+
config,
|
|
259
|
+
execute: async (input, context) => {
|
|
260
|
+
return await executeWorkflow(config, input, context);
|
|
261
|
+
},
|
|
262
|
+
asTool: (options) => {
|
|
263
|
+
const impact = resolveWorkflowImpact(config, options);
|
|
264
|
+
const requireApproval = resolveRequireApproval(impact, options);
|
|
265
|
+
const tool = createIsolatedTool({
|
|
266
|
+
name: config.id,
|
|
267
|
+
description: config.description ?? config.name,
|
|
268
|
+
roles: config.roles,
|
|
269
|
+
impact,
|
|
270
|
+
requireApproval,
|
|
271
|
+
parameters: config.inputSchema,
|
|
272
|
+
invalidationTags: typeof config.invalidationTags === "function" ? async (args, res) => {
|
|
273
|
+
const resolver = config.invalidationTags;
|
|
274
|
+
return await resolver(args, res ?? {});
|
|
275
|
+
} : config.invalidationTags,
|
|
276
|
+
execute: async (args, toolCtx) => {
|
|
277
|
+
const executionContext = buildToolExecutionContext(options, toolCtx);
|
|
278
|
+
const result = await executeWorkflow(config, args, executionContext);
|
|
279
|
+
return result.output;
|
|
280
|
+
},
|
|
281
|
+
llmDto: (result) => result
|
|
282
|
+
});
|
|
283
|
+
Object.assign(tool, {
|
|
284
|
+
_isWorkflow: true,
|
|
285
|
+
workflowId: config.id,
|
|
286
|
+
workflowConfig: {
|
|
287
|
+
totalSteps: config.steps.length,
|
|
288
|
+
impact
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
return tool;
|
|
292
|
+
}
|
|
293
|
+
};
|
|
294
|
+
};
|
|
295
|
+
|
|
296
|
+
export {
|
|
297
|
+
WorkflowSagaRollbackError,
|
|
298
|
+
WorkflowValidationError,
|
|
299
|
+
WorkflowAbortSignal,
|
|
300
|
+
isWorkflowAbortSignal,
|
|
301
|
+
executeWorkflow,
|
|
302
|
+
defineWorkflow
|
|
303
|
+
};
|
|
@@ -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
|
+
};
|
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"}
|