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.
@@ -0,0 +1,611 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/workflow/index.ts
21
+ var workflow_exports = {};
22
+ __export(workflow_exports, {
23
+ WorkflowAbortSignal: () => WorkflowAbortSignal,
24
+ WorkflowSagaRollbackError: () => WorkflowSagaRollbackError,
25
+ WorkflowValidationError: () => WorkflowValidationError,
26
+ defineWorkflow: () => defineWorkflow,
27
+ executeWorkflow: () => executeWorkflow,
28
+ isWorkflowAbortSignal: () => isWorkflowAbortSignal
29
+ });
30
+ module.exports = __toCommonJS(workflow_exports);
31
+
32
+ // src/agent/errors.ts
33
+ var StepSuspendedError = class extends Error {
34
+ stepId;
35
+ workflowId;
36
+ metadata;
37
+ constructor(stepId, workflowId, metadata) {
38
+ super(`Step execution suspended for human approval: [${workflowId}::${stepId}]`);
39
+ this.name = "StepSuspendedError";
40
+ this.stepId = stepId;
41
+ this.workflowId = workflowId;
42
+ this.metadata = metadata;
43
+ }
44
+ };
45
+ var PiiLeakError = class extends Error {
46
+ toolName;
47
+ maskedCount;
48
+ constructor(toolName, maskedCount) {
49
+ super(`PII leak detected in tool output for "${toolName}" (${maskedCount} occurrences detected).`);
50
+ this.name = "PiiLeakError";
51
+ this.toolName = toolName;
52
+ this.maskedCount = maskedCount;
53
+ }
54
+ };
55
+ var ToolAccessDeniedError = class extends Error {
56
+ toolName;
57
+ requiredRole;
58
+ reason;
59
+ constructor(toolName, reasonOrRole) {
60
+ const isRole = Boolean(reasonOrRole && !reasonOrRole.includes(" "));
61
+ const roleMsg = isRole ? ` (requires role "${reasonOrRole}")` : "";
62
+ const reasonMsg = reasonOrRole && !isRole ? `: ${reasonOrRole}` : "";
63
+ super(`Access denied for tool "${toolName}"${roleMsg}${reasonMsg}.`);
64
+ this.name = "ToolAccessDeniedError";
65
+ this.toolName = toolName;
66
+ if (isRole) {
67
+ this.requiredRole = reasonOrRole;
68
+ } else {
69
+ this.reason = reasonOrRole;
70
+ }
71
+ }
72
+ };
73
+ var DtoValidationError = class extends Error {
74
+ toolName;
75
+ issues;
76
+ constructor(toolName, message, issues = []) {
77
+ super(`LLM DTO validation failed for tool "${toolName}": ${message}`);
78
+ this.name = "DtoValidationError";
79
+ this.toolName = toolName;
80
+ this.issues = issues;
81
+ }
82
+ };
83
+
84
+ // src/sanitizer.ts
85
+ var EMAIL_REGEX = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,7}\b/g;
86
+ var PHONE_FR_REGEX = /\b(?:(?:\+|00)33|0)\s*[1-9](?:[\s.-]*\d{2}){4}\b/g;
87
+ 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;
88
+ 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;
89
+ var SPI_FORMATTED_REGEX = /\b[0-3]\d(?:\s+\d{2}){5}\s+\d\b/g;
90
+ var IBAN_REGEX = /\b[A-Z]{2}\s*[0-9]{2}(?:[\s\r\n.-]*[A-Z0-9]){11,30}\b/g;
91
+ 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;
92
+ function sanitizePII(input) {
93
+ let count = 0;
94
+ let result = input;
95
+ result = result.replace(EMAIL_REGEX, () => {
96
+ count++;
97
+ return "[REDACTED_EMAIL]";
98
+ });
99
+ result = result.replace(PHONE_FR_REGEX, () => {
100
+ count++;
101
+ return "[REDACTED_PHONE]";
102
+ });
103
+ result = result.replace(IBAN_REGEX, (match) => {
104
+ const cleanChars = match.replace(/[\s\r\n.-]/g, "");
105
+ if (cleanChars.length >= 15 && cleanChars.length <= 34) {
106
+ count++;
107
+ return "[REDACTED_IBAN]";
108
+ }
109
+ return match;
110
+ });
111
+ result = result.replace(BIC_LABELLED_REGEX, (_, bicCode) => {
112
+ count++;
113
+ return `[REDACTED_BIC: ${bicCode.slice(0, 4)}****]`;
114
+ });
115
+ result = result.replace(SPI_LABELLED_REGEX, (fullMatch, digits) => {
116
+ count++;
117
+ return fullMatch.replace(digits, "[REDACTED_SPI]");
118
+ });
119
+ result = result.replace(NIR_SSN_REGEX, (match) => {
120
+ const rawDigits = match.replace(/\s+/g, "");
121
+ if (rawDigits.length === 13 || rawDigits.length === 15) {
122
+ count++;
123
+ return "[REDACTED_NIR]";
124
+ }
125
+ return match;
126
+ });
127
+ result = result.replace(SPI_FORMATTED_REGEX, (match) => {
128
+ if (!match.includes("[REDACTED")) {
129
+ count++;
130
+ return "[REDACTED_SPI]";
131
+ }
132
+ return match;
133
+ });
134
+ return { text: result, maskedCount: count };
135
+ }
136
+
137
+ // src/agent/guardrails.ts
138
+ function sanitizeString(value) {
139
+ const result = sanitizePII(value);
140
+ return { text: result.text, count: result.maskedCount };
141
+ }
142
+ function sanitizeArray(items, options, visited) {
143
+ let totalCount = 0;
144
+ const sanitized = items.map((item) => {
145
+ const res = recursivelySanitize(item, options, visited);
146
+ totalCount += res.count;
147
+ return res.sanitized;
148
+ });
149
+ return { sanitized, count: totalCount };
150
+ }
151
+ function sanitizeObject(target, options, visited) {
152
+ let totalCount = 0;
153
+ const copy = {};
154
+ for (const [key, val] of Object.entries(target)) {
155
+ const res = recursivelySanitize(val, options, visited);
156
+ copy[key] = res.sanitized;
157
+ totalCount += res.count;
158
+ }
159
+ return { sanitized: copy, count: totalCount };
160
+ }
161
+ function recursivelySanitize(data, options, visited = /* @__PURE__ */ new WeakSet()) {
162
+ if (typeof data === "string") {
163
+ const res = sanitizeString(data);
164
+ return { sanitized: res.text, count: res.count };
165
+ }
166
+ if (data !== null && typeof data === "object") {
167
+ if (visited.has(data)) {
168
+ return { sanitized: "[CIRCULAR_REFERENCE]", count: 0 };
169
+ }
170
+ visited.add(data);
171
+ if (Array.isArray(data)) {
172
+ return sanitizeArray(data, options, visited);
173
+ }
174
+ return sanitizeObject(data, options, visited);
175
+ }
176
+ return { sanitized: data, count: 0 };
177
+ }
178
+ function auditToolResult(data, options) {
179
+ const { sanitized, count } = recursivelySanitize(data, options);
180
+ if (options.throwOnPii && count > 0) {
181
+ throw new PiiLeakError(options.toolName, count);
182
+ }
183
+ return {
184
+ sanitizedData: sanitized,
185
+ maskedCount: count
186
+ };
187
+ }
188
+
189
+ // src/agent/isolated-tool.ts
190
+ async function verifyDataAccessGuard(guard, args, context, toolIdentifier) {
191
+ if (!guard) {
192
+ return;
193
+ }
194
+ const isAllowed = await guard(args, context);
195
+ if (!isAllowed) {
196
+ throw new ToolAccessDeniedError(toolIdentifier, "Access denied by data access guard");
197
+ }
198
+ }
199
+ async function resolveInvalidationTags(config, args, rawResult, context) {
200
+ if (!config.invalidationTags) {
201
+ return void 0;
202
+ }
203
+ const tags = typeof config.invalidationTags === "function" ? await config.invalidationTags(args, rawResult) : config.invalidationTags;
204
+ if (tags && tags.length > 0 && context?.onInvalidationTags) {
205
+ await context.onInvalidationTags(tags);
206
+ }
207
+ return tags;
208
+ }
209
+ async function dispatchClientData(rawResult, callback) {
210
+ if (!callback) {
211
+ return;
212
+ }
213
+ await callback(rawResult);
214
+ }
215
+ async function produceLlmPayload(rawResult, args, context, transformer) {
216
+ if (transformer) {
217
+ return await transformer(rawResult, args, context);
218
+ }
219
+ return rawResult;
220
+ }
221
+ function validateLlmDto(payload, schema, toolIdentifier) {
222
+ const parseResult = schema.safeParse(payload);
223
+ if (!parseResult.success) {
224
+ const issues = parseResult.error.issues ?? [];
225
+ const errorMessages = issues.map((issue) => `${issue.path.join(".") || "root"}: ${issue.message}`).join(", ");
226
+ throw new DtoValidationError(
227
+ toolIdentifier,
228
+ errorMessages,
229
+ issues
230
+ );
231
+ }
232
+ return parseResult.data;
233
+ }
234
+ function protectLlmPayload(payload, toolIdentifier, sanitizePii = true, throwOnPii = false) {
235
+ if (!sanitizePii) {
236
+ return { sanitized: payload, count: 0 };
237
+ }
238
+ const { sanitizedData, maskedCount } = auditToolResult(payload, {
239
+ toolName: toolIdentifier,
240
+ throwOnPii
241
+ });
242
+ return { sanitized: sanitizedData, count: maskedCount };
243
+ }
244
+ async function processLlmPayload(rawResult, args, context, config, toolIdentifier) {
245
+ let payload = await produceLlmPayload(rawResult, args, context, config.llmDto);
246
+ if (config.llmDtoSchema) {
247
+ payload = validateLlmDto(payload, config.llmDtoSchema, toolIdentifier);
248
+ }
249
+ return protectLlmPayload(
250
+ payload,
251
+ toolIdentifier,
252
+ config.sanitizePii !== false,
253
+ config.throwOnPii === true
254
+ );
255
+ }
256
+ function createIsolatedTool(config) {
257
+ const toolId = config.id || config.name;
258
+ const toolAlias = config.alias;
259
+ const clientCallback = config.clientDto;
260
+ const toolIdentifier = toolAlias || config.name;
261
+ const toolImpact = config.impact ?? "READ_ONLY";
262
+ const requireApproval = config.requireApproval ?? toolImpact === "DESTRUCTIVE";
263
+ const tool = {
264
+ description: config.description,
265
+ parameters: config.parameters,
266
+ _toolId: toolId,
267
+ _toolName: config.name,
268
+ _toolAlias: toolAlias,
269
+ _isIsolated: true,
270
+ _cacheTTL: config.cacheTTL,
271
+ _domain: config.domain,
272
+ _resource: config.resource,
273
+ _roles: config.roles ? Object.freeze([...config.roles]) : void 0,
274
+ _impact: toolImpact,
275
+ _requireApproval: requireApproval,
276
+ _lastPiiFilteredCount: 0,
277
+ _lastInvalidationTags: void 0,
278
+ async execute(args, context) {
279
+ const updatedContext = {
280
+ ...context,
281
+ callChain: context?.callChain ?? Object.freeze([toolId])
282
+ };
283
+ await verifyDataAccessGuard(
284
+ config.dataAccessGuard,
285
+ args,
286
+ updatedContext,
287
+ toolIdentifier
288
+ );
289
+ const rawResult = await config.execute(args, updatedContext);
290
+ const tags = await resolveInvalidationTags(
291
+ config,
292
+ args,
293
+ rawResult,
294
+ updatedContext
295
+ );
296
+ if (tags) {
297
+ tool._lastInvalidationTags = tags;
298
+ }
299
+ await dispatchClientData(rawResult, clientCallback);
300
+ const protection = await processLlmPayload(
301
+ rawResult,
302
+ args,
303
+ updatedContext,
304
+ config,
305
+ toolIdentifier
306
+ );
307
+ tool._lastPiiFilteredCount = protection.count;
308
+ return protection.sanitized;
309
+ }
310
+ };
311
+ return tool;
312
+ }
313
+
314
+ // src/workflow/errors.ts
315
+ var WorkflowSagaRollbackError = class extends Error {
316
+ workflowId;
317
+ failedStepId;
318
+ originalError;
319
+ compensatedSteps;
320
+ failedCompensations;
321
+ constructor(params) {
322
+ const errorDetails = params.originalError instanceof Error ? params.originalError.message : String(params.originalError);
323
+ super(
324
+ `\xC9chec de l'\xE9tape '${params.failedStepId}' dans le workflow '${params.workflowId}'. Rollback Saga ex\xE9cut\xE9 sur [${params.compensatedSteps.join(", ")}]. Cause initiale: ${errorDetails}`
325
+ );
326
+ this.name = "WorkflowSagaRollbackError";
327
+ this.workflowId = params.workflowId;
328
+ this.failedStepId = params.failedStepId;
329
+ this.originalError = params.originalError;
330
+ this.compensatedSteps = params.compensatedSteps;
331
+ this.failedCompensations = params.failedCompensations ?? [];
332
+ }
333
+ };
334
+ var WorkflowValidationError = class extends Error {
335
+ workflowId;
336
+ issues;
337
+ constructor(workflowId, issues) {
338
+ super(`Validation des entr\xE9es \xE9chou\xE9e pour le workflow '${workflowId}'.`);
339
+ this.name = "WorkflowValidationError";
340
+ this.workflowId = workflowId;
341
+ this.issues = issues;
342
+ }
343
+ };
344
+ var WorkflowAbortSignal = class extends Error {
345
+ __isWorkflowAbort = true;
346
+ reason;
347
+ payload;
348
+ constructor(reason, payload) {
349
+ super(`Workflow aborted: ${reason}`);
350
+ this.name = "WorkflowAbortSignal";
351
+ this.reason = reason;
352
+ this.payload = payload;
353
+ }
354
+ };
355
+ var isWorkflowAbortSignal = (value) => {
356
+ return typeof value === "object" && value !== null && value.__isWorkflowAbort === true;
357
+ };
358
+
359
+ // src/workflow/engine.ts
360
+ var generateRunId = (workflowId) => {
361
+ const timestamp = Date.now();
362
+ const randomSuffix = Math.random().toString(36).substring(2, 9);
363
+ return `run_${workflowId}_${timestamp}_${randomSuffix}`;
364
+ };
365
+ var validateInput = (config, input) => {
366
+ const parseResult = config.inputSchema.safeParse(input);
367
+ if (!parseResult.success) {
368
+ throw new WorkflowValidationError(config.id, parseResult.error.issues);
369
+ }
370
+ return parseResult.data;
371
+ };
372
+ var createStepContext = (params) => {
373
+ const { workflowId, stepId, runId, context, stepResults } = params;
374
+ return {
375
+ workflowId,
376
+ stepId,
377
+ runId,
378
+ tenantId: context?.tenantId,
379
+ userId: context?.userId,
380
+ services: context?.services ?? {},
381
+ storage: context?.storage,
382
+ getStepResult: (id) => stepResults[id],
383
+ waitForApproval: async (options) => {
384
+ if (context?.storage) {
385
+ const existing = await context.storage.getStep(workflowId, stepId);
386
+ if (existing && existing.status === "COMPLETED") {
387
+ return existing.result ?? options?.defaultResult;
388
+ }
389
+ const now = (/* @__PURE__ */ new Date()).toISOString();
390
+ await context.storage.saveStep({
391
+ workflowId,
392
+ stepId,
393
+ runId,
394
+ status: "WAITING_APPROVAL",
395
+ metadata: options?.metadata,
396
+ createdAt: now,
397
+ updatedAt: now
398
+ });
399
+ }
400
+ throw new StepSuspendedError(stepId, workflowId, options?.prompt);
401
+ },
402
+ abort: (reason, payload) => {
403
+ throw new WorkflowAbortSignal(reason, payload);
404
+ }
405
+ };
406
+ };
407
+ var rollbackSaga = async (params) => {
408
+ const {
409
+ workflowId,
410
+ failedStepId,
411
+ originalError,
412
+ completedSteps,
413
+ input,
414
+ runId,
415
+ context,
416
+ stepResults
417
+ } = params;
418
+ const compensatedSteps = [];
419
+ const failedCompensations = [];
420
+ for (let i = completedSteps.length - 1; i >= 0; i--) {
421
+ const { step, result } = completedSteps[i];
422
+ if (!step.compensate) {
423
+ continue;
424
+ }
425
+ const stepCtx = createStepContext({
426
+ workflowId,
427
+ stepId: step.id,
428
+ runId,
429
+ context,
430
+ stepResults
431
+ });
432
+ try {
433
+ await step.compensate(result, input, stepCtx);
434
+ compensatedSteps.push(step.id);
435
+ if (context?.storage) {
436
+ await context.storage.updateStepStatus(workflowId, step.id, "FAILED", {
437
+ metadata: { compensated: true }
438
+ });
439
+ }
440
+ } catch (compensationError) {
441
+ failedCompensations.push({ stepId: step.id, error: compensationError });
442
+ }
443
+ }
444
+ throw new WorkflowSagaRollbackError({
445
+ workflowId,
446
+ failedStepId,
447
+ originalError,
448
+ compensatedSteps,
449
+ failedCompensations
450
+ });
451
+ };
452
+ var executeWorkflow = async (config, rawInput, context) => {
453
+ const input = validateInput(config, rawInput);
454
+ const runId = context?.runId ?? generateRunId(config.id);
455
+ const stepResults = {};
456
+ const completedSteps = [];
457
+ const handleAbort = async (stepId, signal) => {
458
+ stepResults[stepId] = {
459
+ aborted: true,
460
+ reason: signal.reason,
461
+ payload: signal.payload
462
+ };
463
+ if (context?.storage) {
464
+ await context.storage.updateStepStatus(config.id, stepId, "ABORTED", {
465
+ result: signal.payload,
466
+ metadata: { abortReason: signal.reason }
467
+ });
468
+ }
469
+ const abortOutput = signal.payload ?? {
470
+ aborted: true,
471
+ reason: signal.reason
472
+ };
473
+ return {
474
+ workflowId: config.id,
475
+ runId,
476
+ status: "ABORTED",
477
+ stepResults,
478
+ abortReason: signal.reason,
479
+ abortPayload: signal.payload,
480
+ output: abortOutput
481
+ };
482
+ };
483
+ for (const step of config.steps) {
484
+ const stepCtx = createStepContext({
485
+ workflowId: config.id,
486
+ stepId: step.id,
487
+ runId,
488
+ context,
489
+ stepResults
490
+ });
491
+ try {
492
+ const result = await step.execute(input, stepCtx);
493
+ if (isWorkflowAbortSignal(result)) {
494
+ return await handleAbort(step.id, result);
495
+ }
496
+ stepResults[step.id] = result;
497
+ completedSteps.push({ step, result });
498
+ if (context?.storage) {
499
+ await context.storage.updateStepStatus(config.id, step.id, "COMPLETED", { result });
500
+ }
501
+ } catch (error) {
502
+ if (error instanceof StepSuspendedError) {
503
+ return {
504
+ workflowId: config.id,
505
+ runId,
506
+ status: "WAITING_APPROVAL",
507
+ stepResults
508
+ };
509
+ }
510
+ if (isWorkflowAbortSignal(error)) {
511
+ return await handleAbort(step.id, error);
512
+ }
513
+ await rollbackSaga({
514
+ workflowId: config.id,
515
+ failedStepId: step.id,
516
+ originalError: error,
517
+ completedSteps,
518
+ input,
519
+ runId,
520
+ context,
521
+ stepResults
522
+ });
523
+ }
524
+ }
525
+ const finalOutput = config.outputDto ? config.outputDto(stepResults, input) : stepResults;
526
+ return {
527
+ workflowId: config.id,
528
+ runId,
529
+ status: "COMPLETED",
530
+ stepResults,
531
+ output: finalOutput
532
+ };
533
+ };
534
+
535
+ // src/workflow/define-workflow.ts
536
+ var resolveWorkflowImpact = (config, options) => {
537
+ if (options?.impact) {
538
+ return options.impact;
539
+ }
540
+ return config.impact ?? "MUTATIVE";
541
+ };
542
+ var resolveRequireApproval = (impact, options) => {
543
+ if (options?.requireApproval !== void 0) {
544
+ return options.requireApproval;
545
+ }
546
+ return impact === "DESTRUCTIVE";
547
+ };
548
+ var buildToolExecutionContext = (options, toolCtx) => {
549
+ const tenantId = typeof toolCtx?.tenantId === "string" ? toolCtx.tenantId : options?.defaultContext?.tenantId;
550
+ const userId = typeof toolCtx?.userId === "string" ? toolCtx.userId : options?.defaultContext?.userId;
551
+ return {
552
+ tenantId,
553
+ userId,
554
+ services: options?.defaultContext?.services ?? {},
555
+ storage: options?.storage ?? options?.defaultContext?.storage
556
+ };
557
+ };
558
+ var defineWorkflow = (config) => {
559
+ const workflowImpact = config.impact ?? "MUTATIVE";
560
+ return {
561
+ id: config.id,
562
+ name: config.name,
563
+ description: config.description,
564
+ impact: workflowImpact,
565
+ roles: config.roles,
566
+ config,
567
+ execute: async (input, context) => {
568
+ return await executeWorkflow(config, input, context);
569
+ },
570
+ asTool: (options) => {
571
+ const impact = resolveWorkflowImpact(config, options);
572
+ const requireApproval = resolveRequireApproval(impact, options);
573
+ const tool = createIsolatedTool({
574
+ name: config.id,
575
+ description: config.description ?? config.name,
576
+ roles: config.roles,
577
+ impact,
578
+ requireApproval,
579
+ parameters: config.inputSchema,
580
+ invalidationTags: typeof config.invalidationTags === "function" ? async (args, res) => {
581
+ const resolver = config.invalidationTags;
582
+ return await resolver(args, res ?? {});
583
+ } : config.invalidationTags,
584
+ execute: async (args, toolCtx) => {
585
+ const executionContext = buildToolExecutionContext(options, toolCtx);
586
+ const result = await executeWorkflow(config, args, executionContext);
587
+ return result.output;
588
+ },
589
+ llmDto: (result) => result
590
+ });
591
+ Object.assign(tool, {
592
+ _isWorkflow: true,
593
+ workflowId: config.id,
594
+ workflowConfig: {
595
+ totalSteps: config.steps.length,
596
+ impact
597
+ }
598
+ });
599
+ return tool;
600
+ }
601
+ };
602
+ };
603
+ // Annotate the CommonJS export names for ESM import in node:
604
+ 0 && (module.exports = {
605
+ WorkflowAbortSignal,
606
+ WorkflowSagaRollbackError,
607
+ WorkflowValidationError,
608
+ defineWorkflow,
609
+ executeWorkflow,
610
+ isWorkflowAbortSignal
611
+ });
@@ -0,0 +1,17 @@
1
+ import {
2
+ WorkflowAbortSignal,
3
+ WorkflowSagaRollbackError,
4
+ WorkflowValidationError,
5
+ defineWorkflow,
6
+ executeWorkflow,
7
+ isWorkflowAbortSignal
8
+ } from "../chunk-4XWO3NZW.mjs";
9
+ import "../chunk-5VA3EKPJ.mjs";
10
+ export {
11
+ WorkflowAbortSignal,
12
+ WorkflowSagaRollbackError,
13
+ WorkflowValidationError,
14
+ defineWorkflow,
15
+ executeWorkflow,
16
+ isWorkflowAbortSignal
17
+ };
@@ -0,0 +1,67 @@
1
+ import type { ZodType } from "zod";
2
+ import type { IsolatedTool, StepApprovalOptions, StepStorageAdapter, ToolImpact } from "../agent/types";
3
+ export interface WorkflowStepContext {
4
+ readonly workflowId: string;
5
+ readonly stepId: string;
6
+ readonly runId?: string;
7
+ readonly tenantId?: string;
8
+ readonly userId?: string;
9
+ readonly services: Record<string, any>;
10
+ readonly storage?: StepStorageAdapter;
11
+ getStepResult<T = unknown>(stepId: string): T | undefined;
12
+ waitForApproval<T = unknown>(options?: StepApprovalOptions<T>): Promise<T>;
13
+ abort<TPayload = unknown>(reason: string, payload?: TPayload): never;
14
+ }
15
+ export interface WorkflowStepConfig<TInput = any, TOutput = any> {
16
+ id: string;
17
+ name: string;
18
+ description?: string;
19
+ impact?: ToolImpact;
20
+ checkpoint?: boolean;
21
+ execute: (input: TInput, ctx: WorkflowStepContext) => Promise<TOutput>;
22
+ compensate?: (stepResult: TOutput, input: TInput, ctx: WorkflowStepContext) => Promise<void>;
23
+ }
24
+ export interface WorkflowConfig<TInput = any, TOutput = any> {
25
+ id: string;
26
+ name: string;
27
+ description?: string;
28
+ inputSchema: ZodType<TInput>;
29
+ roles?: string[];
30
+ impact?: ToolImpact;
31
+ invalidationTags?: string[] | ((input: TInput, results: Record<string, any>) => string[] | Promise<string[]>);
32
+ steps: WorkflowStepConfig<TInput, any>[];
33
+ outputDto?: (results: Record<string, any>, input: TInput) => TOutput;
34
+ }
35
+ export interface WorkflowExecutionContext {
36
+ tenantId?: string;
37
+ userId?: string;
38
+ runId?: string;
39
+ services?: Record<string, any>;
40
+ storage?: StepStorageAdapter;
41
+ }
42
+ export interface WorkflowAsToolOptions {
43
+ storage?: StepStorageAdapter;
44
+ impact?: ToolImpact;
45
+ requireApproval?: boolean;
46
+ defaultContext?: Partial<WorkflowExecutionContext>;
47
+ }
48
+ export interface WorkflowExecutionResult<TOutput = any> {
49
+ workflowId: string;
50
+ runId: string;
51
+ status: "COMPLETED" | "FAILED" | "WAITING_APPROVAL" | "ABORTED";
52
+ stepResults: Record<string, any>;
53
+ output?: TOutput;
54
+ abortReason?: string;
55
+ abortPayload?: unknown;
56
+ }
57
+ export interface WorkflowInstance<TInput = any, TOutput = any> {
58
+ readonly id: string;
59
+ readonly name: string;
60
+ readonly description?: string;
61
+ readonly impact: ToolImpact;
62
+ readonly roles?: string[];
63
+ readonly config: WorkflowConfig<TInput, TOutput>;
64
+ execute(input: TInput, context?: WorkflowExecutionContext): Promise<WorkflowExecutionResult<TOutput>>;
65
+ asTool(options?: WorkflowAsToolOptions): IsolatedTool<TInput, TOutput>;
66
+ }
67
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/workflow/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,KAAK,CAAC;AACnC,OAAO,KAAK,EACV,YAAY,EACZ,mBAAmB,EACnB,kBAAkB,EAClB,UAAU,EACX,MAAM,gBAAgB,CAAC;AAExB,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAC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