@defai.digital/agent-execution 13.0.3

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 ADDED
@@ -0,0 +1,214 @@
1
+ AutomatosX Open Source Edition - Apache License 2.0
2
+
3
+ This license applies ONLY to the AutomatosX Open Source Edition code
4
+ published on GitHub at https://github.com/defai-digital/automatosx
5
+
6
+ This license does NOT apply to:
7
+ - AutomatosX Pro Edition (proprietary software - separate EULA)
8
+ - AutomatosX Enterprise Edition (proprietary software - separate agreement)
9
+
10
+ For commercial editions, see COMMERCIAL-LICENSE.md
11
+
12
+ ===============================================================================
13
+
14
+ Apache License
15
+ Version 2.0, January 2004
16
+ http://www.apache.org/licenses/
17
+
18
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
19
+
20
+ 1. Definitions.
21
+
22
+ "License" shall mean the terms and conditions for use, reproduction,
23
+ and distribution as defined by Sections 1 through 9 of this document.
24
+
25
+ "Licensor" shall mean the copyright owner or entity authorized by
26
+ the copyright owner that is granting the License.
27
+
28
+ "Legal Entity" shall mean the union of the acting entity and all
29
+ other entities that control, are controlled by, or are under common
30
+ control with that entity. For the purposes of this definition,
31
+ "control" means (i) the power, direct or indirect, to cause the
32
+ direction or management of such entity, whether by contract or
33
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
34
+ outstanding shares, or (iii) beneficial ownership of such entity.
35
+
36
+ "You" (or "Your") shall mean an individual or Legal Entity
37
+ exercising permissions granted by this License.
38
+
39
+ "Source" form shall mean the preferred form for making modifications,
40
+ including but not limited to software source code, documentation
41
+ source, and configuration files.
42
+
43
+ "Object" form shall mean any form resulting from mechanical
44
+ transformation or translation of a Source form, including but
45
+ not limited to compiled object code, generated documentation,
46
+ and conversions to other media types.
47
+
48
+ "Work" shall mean the work of authorship, whether in Source or
49
+ Object form, made available under the License, as indicated by a
50
+ copyright notice that is included in or attached to the work
51
+ (an example is provided in the Appendix below).
52
+
53
+ "Derivative Works" shall mean any work, whether in Source or Object
54
+ form, that is based on (or derived from) the Work and for which the
55
+ editorial revisions, annotations, elaborations, or other modifications
56
+ represent, as a whole, an original work of authorship. For the purposes
57
+ of this License, Derivative Works shall not include works that remain
58
+ separable from, or merely link (or bind by name) to the interfaces of,
59
+ the Work and Derivative Works thereof.
60
+
61
+ "Contribution" shall mean any work of authorship, including
62
+ the original version of the Work and any modifications or additions
63
+ to that Work or Derivative Works thereof, that is intentionally
64
+ submitted to Licensor for inclusion in the Work by the copyright owner
65
+ or by an individual or Legal Entity authorized to submit on behalf of
66
+ the copyright owner. For the purposes of this definition, "submitted"
67
+ means any form of electronic, verbal, or written communication sent
68
+ to the Licensor or its representatives, including but not limited to
69
+ communication on electronic mailing lists, source code control systems,
70
+ and issue tracking systems that are managed by, or on behalf of, the
71
+ Licensor for the purpose of discussing and improving the Work, but
72
+ excluding communication that is conspicuously marked or otherwise
73
+ designated in writing by the copyright owner as "Not a Contribution."
74
+
75
+ "Contributor" shall mean Licensor and any individual or Legal Entity
76
+ on behalf of whom a Contribution has been received by Licensor and
77
+ subsequently incorporated within the Work.
78
+
79
+ 2. Grant of Copyright License. Subject to the terms and conditions of
80
+ this License, each Contributor hereby grants to You a perpetual,
81
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
82
+ copyright license to reproduce, prepare Derivative Works of,
83
+ publicly display, publicly perform, sublicense, and distribute the
84
+ Work and such Derivative Works in Source or Object form.
85
+
86
+ 3. Grant of Patent License. Subject to the terms and conditions of
87
+ this License, each Contributor hereby grants to You a perpetual,
88
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
89
+ (except as stated in this section) patent license to make, have made,
90
+ use, offer to sell, sell, import, and otherwise transfer the Work,
91
+ where such license applies only to those patent claims licensable
92
+ by such Contributor that are necessarily infringed by their
93
+ Contribution(s) alone or by combination of their Contribution(s)
94
+ with the Work to which such Contribution(s) was submitted. If You
95
+ institute patent litigation against any entity (including a
96
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
97
+ or a Contribution incorporated within the Work constitutes direct
98
+ or contributory patent infringement, then any patent licenses
99
+ granted to You under this License for that Work shall terminate
100
+ as of the date such litigation is filed.
101
+
102
+ 4. Redistribution. You may reproduce and distribute copies of the
103
+ Work or Derivative Works thereof in any medium, with or without
104
+ modifications, and in Source or Object form, provided that You
105
+ meet the following conditions:
106
+
107
+ (a) You must give any other recipients of the Work or
108
+ Derivative Works a copy of this License; and
109
+
110
+ (b) You must cause any modified files to carry prominent notices
111
+ stating that You changed the files; and
112
+
113
+ (c) You must retain, in the Source form of any Derivative Works
114
+ that You distribute, all copyright, patent, trademark, and
115
+ attribution notices from the Source form of the Work,
116
+ excluding those notices that do not pertain to any part of
117
+ the Derivative Works; and
118
+
119
+ (d) If the Work includes a "NOTICE" text file as part of its
120
+ distribution, then any Derivative Works that You distribute must
121
+ include a readable copy of the attribution notices contained
122
+ within such NOTICE file, excluding those notices that do not
123
+ pertain to any part of the Derivative Works, in at least one
124
+ of the following places: within a NOTICE text file distributed
125
+ as part of the Derivative Works; within the Source form or
126
+ documentation, if provided along with the Derivative Works; or,
127
+ within a display generated by the Derivative Works, if and
128
+ wherever such third-party notices normally appear. The contents
129
+ of the NOTICE file are for informational purposes only and
130
+ do not modify the License. You may add Your own attribution
131
+ notices within Derivative Works that You distribute, alongside
132
+ or as an addendum to the NOTICE text from the Work, provided
133
+ that such additional attribution notices cannot be construed
134
+ as modifying the License.
135
+
136
+ You may add Your own copyright statement to Your modifications and
137
+ may provide additional or different license terms and conditions
138
+ for use, reproduction, or distribution of Your modifications, or
139
+ for any such Derivative Works as a whole, provided Your use,
140
+ reproduction, and distribution of the Work otherwise complies with
141
+ the conditions stated in this License.
142
+
143
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
144
+ any Contribution intentionally submitted for inclusion in the Work
145
+ by You to the Licensor shall be under the terms and conditions of
146
+ this License, without any additional terms or conditions.
147
+ Notwithstanding the above, nothing herein shall supersede or modify
148
+ the terms of any separate license agreement you may have executed
149
+ with Licensor regarding such Contributions.
150
+
151
+ 6. Trademarks. This License does not grant permission to use the trade
152
+ names, trademarks, service marks, or product names of the Licensor,
153
+ except as required for reasonable and customary use in describing the
154
+ origin of the Work and reproducing the content of the NOTICE file.
155
+
156
+ 7. Disclaimer of Warranty. Unless required by applicable law or
157
+ agreed to in writing, Licensor provides the Work (and each
158
+ Contributor provides its Contributions) on an "AS IS" BASIS,
159
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
160
+ implied, including, without limitation, any warranties or conditions
161
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
162
+ PARTICULAR PURPOSE. You are solely responsible for determining the
163
+ appropriateness of using or redistributing the Work and assume any
164
+ risks associated with Your exercise of permissions under this License.
165
+
166
+ 8. Limitation of Liability. In no event and under no legal theory,
167
+ whether in tort (including negligence), contract, or otherwise,
168
+ unless required by applicable law (such as deliberate and grossly
169
+ negligent acts) or agreed to in writing, shall any Contributor be
170
+ liable to You for damages, including any direct, indirect, special,
171
+ incidental, or consequential damages of any character arising as a
172
+ result of this License or out of the use or inability to use the
173
+ Work (including but not limited to damages for loss of goodwill,
174
+ work stoppage, computer failure or malfunction, or any and all
175
+ other commercial damages or losses), even if such Contributor
176
+ has been advised of the possibility of such damages.
177
+
178
+ 9. Accepting Warranty or Additional Liability. While redistributing
179
+ the Work or Derivative Works thereof, You may choose to offer,
180
+ and charge a fee for, acceptance of support, warranty, indemnity,
181
+ or other liability obligations and/or rights consistent with this
182
+ License. However, in accepting such obligations, You may act only
183
+ on Your own behalf and on Your sole responsibility, not on behalf
184
+ of any other Contributor, and only if You agree to indemnify,
185
+ defend, and hold each Contributor harmless for any liability
186
+ incurred by, or claims asserted against, such Contributor by reason
187
+ of your accepting any such warranty or additional liability.
188
+
189
+ END OF TERMS AND CONDITIONS
190
+
191
+ APPENDIX: How to apply the Apache License to your work.
192
+
193
+ To apply the Apache License to your work, attach the following
194
+ boilerplate notice, with the fields enclosed by brackets "[]"
195
+ replaced with your own identifying information. (Don't include
196
+ the brackets!) The text should be enclosed in the appropriate
197
+ comment syntax for the file format. We also recommend that a
198
+ file or class name and description of purpose be included on the
199
+ same "printed page" as the copyright notice for easier
200
+ identification within third-party archives.
201
+
202
+ Copyright 2024-2025 DEFAI Private Limited
203
+
204
+ Licensed under the Apache License, Version 2.0 (the "License");
205
+ you may not use this file except in compliance with the License.
206
+ You may obtain a copy of the License at
207
+
208
+ http://www.apache.org/licenses/LICENSE-2.0
209
+
210
+ Unless required by applicable law or agreed to in writing, software
211
+ distributed under the License is distributed on an "AS IS" BASIS,
212
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
213
+ See the License for the specific language governing permissions and
214
+ limitations under the License.
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Checkpoint Manager Implementation
3
+ *
4
+ * Manages agent execution checkpoints for resumable workflows.
5
+ * Enables recovery from failures by persisting execution state.
6
+ *
7
+ * Invariants:
8
+ * - INV-CP-001: Checkpoint contains all data needed to resume
9
+ * - INV-CP-002: Resumed execution starts from step after checkpoint
10
+ */
11
+ import { type Checkpoint, type CheckpointConfig, type ResumeContext, type MemorySnapshotItem } from '@defai.digital/contracts';
12
+ /**
13
+ * Checkpoint storage interface - allows different storage backends
14
+ */
15
+ export interface CheckpointStorage {
16
+ /** Save a checkpoint */
17
+ save(checkpoint: Checkpoint): Promise<void>;
18
+ /** Load a checkpoint by ID */
19
+ load(checkpointId: string): Promise<Checkpoint | null>;
20
+ /** Load latest checkpoint for an agent */
21
+ loadLatest(agentId: string, sessionId?: string): Promise<Checkpoint | null>;
22
+ /** List checkpoints for an agent */
23
+ list(agentId: string, sessionId?: string): Promise<Checkpoint[]>;
24
+ /** Delete a checkpoint */
25
+ delete(checkpointId: string): Promise<boolean>;
26
+ /** Delete expired checkpoints */
27
+ deleteExpired(): Promise<number>;
28
+ }
29
+ /**
30
+ * Checkpoint manager for a single agent
31
+ */
32
+ export interface CheckpointManager {
33
+ /** Get configuration */
34
+ getConfig(): CheckpointConfig;
35
+ /** Create a checkpoint from current execution state */
36
+ createCheckpoint(stepIndex: number, completedStepId: string, stepOutputs: Record<string, unknown>, context: Record<string, unknown>, memorySnapshot?: MemorySnapshotItem[]): Promise<Checkpoint>;
37
+ /** Get resume context from a checkpoint */
38
+ getResumeContext(checkpointId: string): Promise<ResumeContext | null>;
39
+ /** Get latest checkpoint */
40
+ getLatestCheckpoint(): Promise<Checkpoint | null>;
41
+ /** List all checkpoints */
42
+ listCheckpoints(): Promise<Checkpoint[]>;
43
+ /** Delete a checkpoint */
44
+ deleteCheckpoint(checkpointId: string): Promise<boolean>;
45
+ /** Clean up expired checkpoints */
46
+ cleanupExpired(): Promise<number>;
47
+ /** Check if a step should be checkpointed */
48
+ shouldCheckpoint(stepIndex: number): boolean;
49
+ }
50
+ /**
51
+ * In-memory checkpoint storage (for development/testing)
52
+ */
53
+ export declare function createInMemoryCheckpointStorage(): CheckpointStorage;
54
+ /**
55
+ * Creates a checkpoint manager for an agent
56
+ */
57
+ export declare function createCheckpointManager(agentId: string, sessionId: string | undefined, storage: CheckpointStorage, config?: Partial<CheckpointConfig>): CheckpointManager;
58
+ /**
59
+ * Checkpoint manager error
60
+ */
61
+ export declare class CheckpointError extends Error {
62
+ readonly code: string;
63
+ readonly checkpointId?: string | undefined;
64
+ constructor(code: string, checkpointId?: string | undefined, message?: string);
65
+ static notFound(checkpointId: string): CheckpointError;
66
+ static expired(checkpointId: string): CheckpointError;
67
+ static saveFailed(checkpointId?: string): CheckpointError;
68
+ }
69
+ //# sourceMappingURL=checkpoint-manager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkpoint-manager.d.ts","sourceRoot":"","sources":["../src/checkpoint-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,KAAK,UAAU,EACf,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,kBAAkB,EAGxB,MAAM,0BAA0B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CAAC,CAAC;IAEzC,0BAA0B;IAC1B,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAEzD,mCAAmC;IACnC,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAElC,6CAA6C;IAC7C,gBAAgB,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC;CAC9C;AAED;;GAEG;AACH,wBAAgB,+BAA+B,IAAI,iBAAiB,CAgEnE;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,OAAO,EAAE,iBAAiB,EAC1B,MAAM,GAAE,OAAO,CAAC,gBAAgB,CAAM,GACrC,iBAAiB,CAoGnB;AAED;;GAEG;AACH,qBAAa,eAAgB,SAAQ,KAAK;aAEtB,IAAI,EAAE,MAAM;aACZ,YAAY,CAAC,EAAE,MAAM;gBADrB,IAAI,EAAE,MAAM,EACZ,YAAY,CAAC,EAAE,MAAM,YAAA,EACrC,OAAO,CAAC,EAAE,MAAM;IAMlB,MAAM,CAAC,QAAQ,CAAC,YAAY,EAAE,MAAM,GAAG,eAAe;IAQtD,MAAM,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,GAAG,eAAe;IAQrD,MAAM,CAAC,UAAU,CAAC,YAAY,CAAC,EAAE,MAAM,GAAG,eAAe;CAO1D"}
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Checkpoint Manager Implementation
3
+ *
4
+ * Manages agent execution checkpoints for resumable workflows.
5
+ * Enables recovery from failures by persisting execution state.
6
+ *
7
+ * Invariants:
8
+ * - INV-CP-001: Checkpoint contains all data needed to resume
9
+ * - INV-CP-002: Resumed execution starts from step after checkpoint
10
+ */
11
+ import { createDefaultCheckpointConfig, CheckpointErrorCodes, } from '@defai.digital/contracts';
12
+ /**
13
+ * In-memory checkpoint storage (for development/testing)
14
+ */
15
+ export function createInMemoryCheckpointStorage() {
16
+ const checkpoints = new Map();
17
+ return {
18
+ async save(checkpoint) {
19
+ checkpoints.set(checkpoint.checkpointId, checkpoint);
20
+ },
21
+ async load(checkpointId) {
22
+ return checkpoints.get(checkpointId) ?? null;
23
+ },
24
+ async loadLatest(agentId, sessionId) {
25
+ const agentCheckpoints = Array.from(checkpoints.values())
26
+ .filter((cp) => cp.agentId === agentId &&
27
+ (sessionId === undefined || cp.sessionId === sessionId))
28
+ .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
29
+ return agentCheckpoints[0] ?? null;
30
+ },
31
+ async list(agentId, sessionId) {
32
+ return Array.from(checkpoints.values())
33
+ .filter((cp) => cp.agentId === agentId &&
34
+ (sessionId === undefined || cp.sessionId === sessionId))
35
+ .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
36
+ },
37
+ async delete(checkpointId) {
38
+ return checkpoints.delete(checkpointId);
39
+ },
40
+ async deleteExpired() {
41
+ const now = Date.now();
42
+ let deleted = 0;
43
+ for (const [id, checkpoint] of checkpoints) {
44
+ if (checkpoint.expiresAt) {
45
+ const expiresAt = new Date(checkpoint.expiresAt).getTime();
46
+ if (expiresAt < now) {
47
+ checkpoints.delete(id);
48
+ deleted++;
49
+ }
50
+ }
51
+ }
52
+ return deleted;
53
+ },
54
+ };
55
+ }
56
+ /**
57
+ * Creates a checkpoint manager for an agent
58
+ */
59
+ export function createCheckpointManager(agentId, sessionId, storage, config = {}) {
60
+ const cfg = { ...createDefaultCheckpointConfig(), ...config };
61
+ let checkpointCount = 0;
62
+ return {
63
+ getConfig() {
64
+ return { ...cfg };
65
+ },
66
+ async createCheckpoint(stepIndex, completedStepId, stepOutputs, context, memorySnapshot) {
67
+ const now = new Date();
68
+ const expiresAt = new Date(now.getTime() + cfg.retentionHours * 60 * 60 * 1000);
69
+ // INV-CP-001: Checkpoint contains all data needed to resume
70
+ const checkpoint = {
71
+ checkpointId: crypto.randomUUID(),
72
+ agentId,
73
+ sessionId,
74
+ stepIndex,
75
+ completedStepId,
76
+ stepOutputs,
77
+ context,
78
+ memorySnapshot: cfg.includeMemory ? memorySnapshot : undefined,
79
+ createdAt: now.toISOString(),
80
+ expiresAt: expiresAt.toISOString(),
81
+ };
82
+ await storage.save(checkpoint);
83
+ checkpointCount++;
84
+ // Enforce max checkpoints
85
+ if (checkpointCount > cfg.maxCheckpoints) {
86
+ const allCheckpoints = await storage.list(agentId, sessionId);
87
+ const toDelete = allCheckpoints.slice(cfg.maxCheckpoints);
88
+ for (const cp of toDelete) {
89
+ await storage.delete(cp.checkpointId);
90
+ }
91
+ checkpointCount = cfg.maxCheckpoints;
92
+ }
93
+ return checkpoint;
94
+ },
95
+ async getResumeContext(checkpointId) {
96
+ const checkpoint = await storage.load(checkpointId);
97
+ if (!checkpoint) {
98
+ return null;
99
+ }
100
+ // Check if expired
101
+ if (checkpoint.expiresAt) {
102
+ const expiresAt = new Date(checkpoint.expiresAt).getTime();
103
+ if (expiresAt < Date.now()) {
104
+ await storage.delete(checkpointId);
105
+ return null;
106
+ }
107
+ }
108
+ // INV-CP-002: Resumed execution starts from step after checkpoint
109
+ return {
110
+ startFromStep: checkpoint.stepIndex + 1,
111
+ previousOutputs: checkpoint.stepOutputs,
112
+ context: checkpoint.context,
113
+ memorySnapshot: checkpoint.memorySnapshot,
114
+ };
115
+ },
116
+ async getLatestCheckpoint() {
117
+ return storage.loadLatest(agentId, sessionId);
118
+ },
119
+ async listCheckpoints() {
120
+ return storage.list(agentId, sessionId);
121
+ },
122
+ async deleteCheckpoint(checkpointId) {
123
+ const result = await storage.delete(checkpointId);
124
+ if (result)
125
+ checkpointCount--;
126
+ return result;
127
+ },
128
+ async cleanupExpired() {
129
+ return storage.deleteExpired();
130
+ },
131
+ shouldCheckpoint(stepIndex) {
132
+ if (!cfg.enabled)
133
+ return false;
134
+ if (cfg.intervalSteps === 0)
135
+ return true;
136
+ return stepIndex % cfg.intervalSteps === 0;
137
+ },
138
+ };
139
+ }
140
+ /**
141
+ * Checkpoint manager error
142
+ */
143
+ export class CheckpointError extends Error {
144
+ code;
145
+ checkpointId;
146
+ constructor(code, checkpointId, message) {
147
+ super(message ?? `Checkpoint error: ${code}`);
148
+ this.code = code;
149
+ this.checkpointId = checkpointId;
150
+ this.name = 'CheckpointError';
151
+ }
152
+ static notFound(checkpointId) {
153
+ return new CheckpointError(CheckpointErrorCodes.CHECKPOINT_NOT_FOUND, checkpointId, `Checkpoint not found: ${checkpointId}`);
154
+ }
155
+ static expired(checkpointId) {
156
+ return new CheckpointError(CheckpointErrorCodes.CHECKPOINT_EXPIRED, checkpointId, `Checkpoint expired: ${checkpointId}`);
157
+ }
158
+ static saveFailed(checkpointId) {
159
+ return new CheckpointError(CheckpointErrorCodes.CHECKPOINT_SAVE_FAILED, checkpointId, 'Failed to save checkpoint');
160
+ }
161
+ }
162
+ //# sourceMappingURL=checkpoint-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkpoint-manager.js","sourceRoot":"","sources":["../src/checkpoint-manager.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAKL,6BAA6B,EAC7B,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AA4DlC;;GAEG;AACH,MAAM,UAAU,+BAA+B;IAC7C,MAAM,WAAW,GAAG,IAAI,GAAG,EAAsB,CAAC;IAElD,OAAO;QACL,KAAK,CAAC,IAAI,CAAC,UAAsB;YAC/B,WAAW,CAAC,GAAG,CAAC,UAAU,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACvD,CAAC;QAED,KAAK,CAAC,IAAI,CAAC,YAAoB;YAC7B,OAAO,WAAW,CAAC,GAAG,CAAC,YAAY,CAAC,IAAI,IAAI,CAAC;QAC/C,CAAC;QAED,KAAK,CAAC,UAAU,CACd,OAAe,EACf,SAAkB;YAElB,MAAM,gBAAgB,GAAG,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,MAAM,EAAE,CAAC;iBACtD,MAAM,CACL,CAAC,EA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CAAC,kBAAkB,EACvC,YAAY,EACZ,uBAAuB,YAAY,EAAE,CACtC,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,YAAqB;QACrC,OAAO,IAAI,eAAe,CACxB,oBAAoB,CAAC,sBAAsB,EAC3C,YAAY,EACZ,2BAA2B,CAC5B,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Delegation Tracker Implementation
3
+ *
4
+ * Tracks agent delegation chains and validates delegation requests.
5
+ * Prevents circular delegations and enforces depth limits.
6
+ *
7
+ * Invariants:
8
+ * - INV-DT-001: Depth never exceeds maxDepth
9
+ * - INV-DT-002: No circular delegations
10
+ */
11
+ import { type DelegationContext, type DelegationRequest, type DelegationResult, type DelegationCheckResult } from '@defai.digital/contracts';
12
+ /**
13
+ * Delegation tracker for managing delegation chains
14
+ */
15
+ export interface DelegationTracker {
16
+ /** Get current delegation context */
17
+ getContext(): DelegationContext;
18
+ /** Check if delegation to target agent is allowed */
19
+ canDelegate(toAgentId: string): DelegationCheckResult;
20
+ /** Create delegation request */
21
+ createDelegationRequest(toAgentId: string, task: string, input?: unknown, timeout?: number): DelegationRequest | null;
22
+ /** Create child context for delegated agent */
23
+ createChildContext(toAgentId: string): DelegationContext;
24
+ /** Record delegation result */
25
+ recordResult(result: DelegationResult): void;
26
+ /** Get delegation history */
27
+ getHistory(): DelegationResult[];
28
+ /** Check if we're at the root of delegation chain */
29
+ isRoot(): boolean;
30
+ /** Get remaining delegation depth */
31
+ getRemainingDepth(): number;
32
+ }
33
+ /**
34
+ * Creates a delegation tracker
35
+ */
36
+ export declare function createDelegationTracker(agentId: string, parentContext?: DelegationContext, maxDepth?: number): DelegationTracker;
37
+ /**
38
+ * Validates a delegation request
39
+ */
40
+ export declare function validateDelegationRequest(request: DelegationRequest): DelegationCheckResult;
41
+ /**
42
+ * Creates a delegation result for success
43
+ */
44
+ export declare function createSuccessResult(handledBy: string, result: unknown, durationMs: number, finalDepth: number): DelegationResult;
45
+ /**
46
+ * Creates a delegation result for failure
47
+ */
48
+ export declare function createFailureResult(handledBy: string, errorCode: string, errorMessage: string, durationMs: number, finalDepth: number): DelegationResult;
49
+ /**
50
+ * Delegation error
51
+ */
52
+ export declare class DelegationError extends Error {
53
+ readonly code: string;
54
+ readonly targetAgent: string;
55
+ constructor(code: string, targetAgent: string, message?: string);
56
+ static maxDepthExceeded(targetAgent: string, maxDepth: number): DelegationError;
57
+ static circularDelegation(targetAgent: string): DelegationError;
58
+ static timeout(targetAgent: string, timeoutMs: number): DelegationError;
59
+ static targetNotFound(targetAgent: string): DelegationError;
60
+ }
61
+ //# sourceMappingURL=delegation-tracker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation-tracker.d.ts","sourceRoot":"","sources":["../src/delegation-tracker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,iBAAiB,EACtB,KAAK,gBAAgB,EACrB,KAAK,qBAAqB,EAG3B,MAAM,0BAA0B,CAAC;AAElC;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAChC,qCAAqC;IACrC,UAAU,IAAI,iBAAiB,CAAC;IAEhC,qDAAqD;IACrD,WAAW,CAAC,SAAS,EAAE,MAAM,GAAG,qBAAqB,CAAC;IAEtD,gCAAgC;IAChC,uBAAuB,CACrB,SAAS,EAAE,MAAM,EACjB,IAAI,EAAE,MAAM,EACZ,KAAK,CAAC,EAAE,OAAO,EACf,OAAO,CAAC,EAAE,MAAM,GACf,iBAAiB,GAAG,IAAI,CAAC;IAE5B,+CAA+C;IAC/C,kBAAkB,CAAC,SAAS,EAAE,MAAM,GAAG,iBAAiB,CAAC;IAEzD,+BAA+B;IAC/B,YAAY,CAAC,MAAM,EAAE,gBAAgB,GAAG,IAAI,CAAC;IAE7C,6BAA6B;IAC7B,UAAU,IAAI,gBAAgB,EAAE,CAAC;IAEjC,qDAAqD;IACrD,MAAM,IAAI,OAAO,CAAC;IAElB,qCAAqC;IACrC,iBAAiB,IAAI,MAAM,CAAC;CAC7B;AAED;;GAEG;AACH,wBAAgB,uBAAuB,CACrC,OAAO,EAAE,MAAM,EACf,aAAa,CAAC,EAAE,iBAAiB,EACjC,QAAQ,SAAI,GACX,iBAAiB,CAoHnB;AAED;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,EAAE,iBAAiB,GACzB,qBAAqB,CA+BvB;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,OAAO,EACf,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,GACjB,gBAAgB,CAQlB;AAED;;GAEG;AACH,wBAAgB,mBAAmB,CACjC,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,UAAU,EAAE,MAAM,GACjB,gBAAgB,CAYlB;AAED;;GAEG;AACH,qBAAa,eAAgB,SAAQ,KAAK;aAEtB,IAAI,EAAE,MAAM;aACZ,WAAW,EAAE,MAAM;gBADnB,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,EACnC,OAAO,CAAC,EAAE,MAAM;IAMlB,MAAM,CAAC,gBAAgB,CACrB,WAAW,EAAE,MAAM,EACnB,QAAQ,EAAE,MAAM,GACf,eAAe;IAQlB,MAAM,CAAC,kBAAkB,CAAC,WAAW,EAAE,MAAM,GAAG,eAAe;IAQ/D,MAAM,CAAC,OAAO,CAAC,WAAW,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,eAAe;IAQvE,MAAM,CAAC,cAAc,CAAC,WAAW,EAAE,MAAM,GAAG,eAAe;CAO5D"}
@@ -0,0 +1,185 @@
1
+ /**
2
+ * Delegation Tracker Implementation
3
+ *
4
+ * Tracks agent delegation chains and validates delegation requests.
5
+ * Prevents circular delegations and enforces depth limits.
6
+ *
7
+ * Invariants:
8
+ * - INV-DT-001: Depth never exceeds maxDepth
9
+ * - INV-DT-002: No circular delegations
10
+ */
11
+ import { createRootDelegationContext, DelegationErrorCodes, } from '@defai.digital/contracts';
12
+ /**
13
+ * Creates a delegation tracker
14
+ */
15
+ export function createDelegationTracker(agentId, parentContext, maxDepth = 3) {
16
+ // Initialize context - either from parent or create new root
17
+ let context;
18
+ if (parentContext) {
19
+ // Validate parent context
20
+ if (parentContext.currentDepth >= parentContext.maxDepth) {
21
+ throw new DelegationError(DelegationErrorCodes.MAX_DEPTH_EXCEEDED, agentId, `Max delegation depth ${parentContext.maxDepth} exceeded`);
22
+ }
23
+ // Create context for this agent
24
+ context = {
25
+ ...parentContext,
26
+ currentDepth: parentContext.currentDepth + 1,
27
+ delegationChain: [...parentContext.delegationChain, agentId],
28
+ };
29
+ }
30
+ else {
31
+ // Create root context
32
+ context = createRootDelegationContext(agentId, crypto.randomUUID(), maxDepth);
33
+ }
34
+ const delegationHistory = [];
35
+ return {
36
+ getContext() {
37
+ return { ...context };
38
+ },
39
+ canDelegate(toAgentId) {
40
+ // INV-DT-001: Check depth limit
41
+ if (context.currentDepth >= context.maxDepth) {
42
+ return {
43
+ allowed: false,
44
+ reason: DelegationErrorCodes.MAX_DEPTH_EXCEEDED,
45
+ message: `Maximum delegation depth ${context.maxDepth} reached`,
46
+ };
47
+ }
48
+ // INV-DT-002: Check for circular delegation
49
+ if (context.delegationChain.includes(toAgentId)) {
50
+ return {
51
+ allowed: false,
52
+ reason: DelegationErrorCodes.CIRCULAR_DELEGATION,
53
+ message: `Cannot delegate to ${toAgentId} - already in delegation chain`,
54
+ };
55
+ }
56
+ return { allowed: true };
57
+ },
58
+ createDelegationRequest(toAgentId, task, input, timeout) {
59
+ const check = this.canDelegate(toAgentId);
60
+ if (!check.allowed) {
61
+ return null;
62
+ }
63
+ return {
64
+ fromAgentId: agentId,
65
+ toAgentId,
66
+ task,
67
+ context: this.getContext(),
68
+ timeout,
69
+ input,
70
+ };
71
+ },
72
+ createChildContext(toAgentId) {
73
+ // Check first
74
+ const check = this.canDelegate(toAgentId);
75
+ if (!check.allowed) {
76
+ throw new DelegationError(check.reason ?? DelegationErrorCodes.PERMISSION_DENIED, toAgentId, check.message);
77
+ }
78
+ return {
79
+ currentDepth: context.currentDepth + 1,
80
+ maxDepth: context.maxDepth,
81
+ delegationChain: [...context.delegationChain, toAgentId],
82
+ initiatorAgentId: context.initiatorAgentId,
83
+ rootTaskId: context.rootTaskId,
84
+ startedAt: context.startedAt,
85
+ };
86
+ },
87
+ recordResult(result) {
88
+ delegationHistory.push(result);
89
+ },
90
+ getHistory() {
91
+ return [...delegationHistory];
92
+ },
93
+ isRoot() {
94
+ return context.currentDepth === 0;
95
+ },
96
+ getRemainingDepth() {
97
+ return context.maxDepth - context.currentDepth;
98
+ },
99
+ };
100
+ }
101
+ /**
102
+ * Validates a delegation request
103
+ */
104
+ export function validateDelegationRequest(request) {
105
+ const { context, toAgentId, fromAgentId } = request;
106
+ // Check self-delegation
107
+ if (fromAgentId === toAgentId) {
108
+ return {
109
+ allowed: false,
110
+ reason: DelegationErrorCodes.CIRCULAR_DELEGATION,
111
+ message: 'Agent cannot delegate to itself',
112
+ };
113
+ }
114
+ // Check depth limit
115
+ if (context.currentDepth >= context.maxDepth) {
116
+ return {
117
+ allowed: false,
118
+ reason: DelegationErrorCodes.MAX_DEPTH_EXCEEDED,
119
+ message: `Maximum delegation depth ${context.maxDepth} exceeded`,
120
+ };
121
+ }
122
+ // Check circular delegation
123
+ if (context.delegationChain.includes(toAgentId)) {
124
+ return {
125
+ allowed: false,
126
+ reason: DelegationErrorCodes.CIRCULAR_DELEGATION,
127
+ message: `Agent ${toAgentId} already in delegation chain`,
128
+ };
129
+ }
130
+ return { allowed: true };
131
+ }
132
+ /**
133
+ * Creates a delegation result for success
134
+ */
135
+ export function createSuccessResult(handledBy, result, durationMs, finalDepth) {
136
+ return {
137
+ success: true,
138
+ handledBy,
139
+ result,
140
+ durationMs,
141
+ finalDepth,
142
+ };
143
+ }
144
+ /**
145
+ * Creates a delegation result for failure
146
+ */
147
+ export function createFailureResult(handledBy, errorCode, errorMessage, durationMs, finalDepth) {
148
+ return {
149
+ success: false,
150
+ handledBy,
151
+ error: {
152
+ code: errorCode,
153
+ message: errorMessage,
154
+ retryable: false,
155
+ },
156
+ durationMs,
157
+ finalDepth,
158
+ };
159
+ }
160
+ /**
161
+ * Delegation error
162
+ */
163
+ export class DelegationError extends Error {
164
+ code;
165
+ targetAgent;
166
+ constructor(code, targetAgent, message) {
167
+ super(message ?? `Delegation error: ${code}`);
168
+ this.code = code;
169
+ this.targetAgent = targetAgent;
170
+ this.name = 'DelegationError';
171
+ }
172
+ static maxDepthExceeded(targetAgent, maxDepth) {
173
+ return new DelegationError(DelegationErrorCodes.MAX_DEPTH_EXCEEDED, targetAgent, `Maximum delegation depth ${maxDepth} exceeded when delegating to ${targetAgent}`);
174
+ }
175
+ static circularDelegation(targetAgent) {
176
+ return new DelegationError(DelegationErrorCodes.CIRCULAR_DELEGATION, targetAgent, `Circular delegation detected: ${targetAgent} is already in the delegation chain`);
177
+ }
178
+ static timeout(targetAgent, timeoutMs) {
179
+ return new DelegationError(DelegationErrorCodes.TIMEOUT, targetAgent, `Delegation to ${targetAgent} timed out after ${timeoutMs}ms`);
180
+ }
181
+ static targetNotFound(targetAgent) {
182
+ return new DelegationError(DelegationErrorCodes.TARGET_NOT_FOUND, targetAgent, `Delegation target agent not found: ${targetAgent}`);
183
+ }
184
+ }
185
+ //# sourceMappingURL=delegation-tracker.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"delegation-tracker.js","sourceRoot":"","sources":["../src/delegation-tracker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,OAAO,EAKL,2BAA2B,EAC3B,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AAoClC;;GAEG;AACH,MAAM,UAAU,uBAAuB,CACrC,OAAe,EACf,aAAiC,EACjC,QAAQ,GAAG,CAAC;IAEZ,6DAA6D;IAC7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int management, delegation tracking, and parallel execution
7
+ * for resumable, composable agent workflows.
8
+ */
9
+ export { createCheckpointManager, createInMemoryCheckpointStorage, CheckpointError, type CheckpointManager, type CheckpointStorage, } from './checkpoint-manager.js';
10
+ export { createDelegationTracker, validateDelegationRequest, createSuccessResult, createFailureResult, DelegationError, type DelegationTracker, } from './delegation-tracker.js';
11
+ export { createParallelExecutor, identifyParallelGroups, ParallelExecutionError, type ParallelExecutor, type StepExecutor, } from './parallel-executor.js';
12
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAGH,OAAO,EACL,uBAAuB,EACvB,+BAA+B,EAC/B,eAAe,EACf,KAAK,iBAAiB,EACtB,KAAK,iBAAiB,GACvB,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,mBAAmB,EACnB,mBAAmB,EACnB,eAAe,EACf,KAAK,iBAAiB,GACvB,MAAM,yBAAyB,CAAC;AAGjC,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,sBAAsB,EACtB,KAAK,gBAAgB,EACrB,KAAK,YAAY,GAClB,MAAM,wBAAwB,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @defai.digital/agent-execution
3
+ *
4
+ * Agent Execution Domain
5
+ *
6
+ * Provides checkpoint management, delegation tracking, and parallel execution
7
+ * for resumable, composable agent workflows.
8
+ */
9
+ // Checkpoint Manager
10
+ export { createCheckpointManager, createInMemoryCheckpointStorage, CheckpointError, } from './checkpoint-manager.js';
11
+ // Delegation Tracker
12
+ export { createDelegationTracker, validateDelegationRequest, createSuccessResult, createFailureResult, DelegationError, } from './delegation-tracker.js';
13
+ // Parallel Executor
14
+ export { createParallelExecutor, identifyParallelGroups, ParallelExecutionError, } from './parallel-executor.js';
15
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,qBAAqB;AACrB,OAAO,EACL,uBAAuB,EACvB,+BAA+B,EAC/B,eAAe,GAGhB,MAAM,yBAAyB,CAAC;AAEjC,qBAAqB;AACrB,OAAO,EACL,uBAAuB,EACvB,yBAAyB,EACzB,mBAAmB,EACnB,mBAAmB,EACnB,eAAe,GAEhB,MAAM,yBAAyB,CAAC;AAEjC,oBAAoB;AACpB,OAAO,EACL,sBAAsB,EACtB,sBAAsB,EACtB,sBAAsB,GAGvB,MAAM,wBAAwB,CAAC"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Parallel Executor Implementation
3
+ *
4
+ * Executes workflow steps in parallel respecting dependencies.
5
+ * Uses DAG-based execution for optimal concurrency.
6
+ *
7
+ * Invariants:
8
+ * - INV-PE-001: Independent steps execute concurrently
9
+ * - INV-PE-002: Dependencies honored (DAG ordering)
10
+ * - INV-PE-003: Concurrency limit respected
11
+ */
12
+ import { type ParallelExecutionConfig, type ParallelGroupResult, type AgentWorkflowStep } from '@defai.digital/contracts';
13
+ /**
14
+ * Step executor function type
15
+ */
16
+ export type StepExecutor = (step: AgentWorkflowStep, previousOutputs: Record<string, unknown>) => Promise<unknown>;
17
+ /**
18
+ * Parallel executor for workflow steps
19
+ */
20
+ export interface ParallelExecutor {
21
+ /** Get configuration */
22
+ getConfig(): ParallelExecutionConfig;
23
+ /** Execute a group of steps in parallel */
24
+ executeGroup(steps: AgentWorkflowStep[], executor: StepExecutor, previousOutputs?: Record<string, unknown>): Promise<ParallelGroupResult>;
25
+ /** Build execution layers from steps (DAG analysis) */
26
+ buildExecutionLayers(steps: AgentWorkflowStep[]): AgentWorkflowStep[][];
27
+ /** Cancel ongoing execution */
28
+ cancel(): void;
29
+ }
30
+ /**
31
+ * Creates a parallel executor
32
+ */
33
+ export declare function createParallelExecutor(config?: Partial<ParallelExecutionConfig>): ParallelExecutor;
34
+ /**
35
+ * Identifies parallel groups within a workflow
36
+ * Returns array of step groups that can be executed in parallel
37
+ */
38
+ export declare function identifyParallelGroups(steps: AgentWorkflowStep[]): AgentWorkflowStep[][];
39
+ /**
40
+ * Parallel execution error
41
+ */
42
+ export declare class ParallelExecutionError extends Error {
43
+ readonly code: string;
44
+ constructor(code: string, message?: string);
45
+ static groupTimeout(groupId: string, timeoutMs: number): ParallelExecutionError;
46
+ static circularDependency(stepIds: string[]): ParallelExecutionError;
47
+ static stepFailed(stepId: string, error: string): ParallelExecutionError;
48
+ }
49
+ //# sourceMappingURL=parallel-executor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parallel-executor.d.ts","sourceRoot":"","sources":["../src/parallel-executor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EACL,KAAK,uBAAuB,EAE5B,KAAK,mBAAmB,EAExB,KAAK,iBAAiB,EAGvB,MAAM,0BAA0B,CAAC;AAElC;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG,CACzB,IAAI,EAAE,iBAAiB,EACvB,eAAe,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,KACrC,OAAO,CAAC,OAAO,CAAC,CAAC;AAEtB;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAC/B,wBAAwB;IACxB,SAAS,IAAI,uBAAuB,CAAC;IAErC,2CAA2C;IAC3C,YAAY,CACV,KAAK,EAAE,iBAAiB,EAAE,EAC1B,QAAQ,EAAE,YAAY,EACtB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACxC,OAAO,CAAC,mBAAmB,CAAC,CAAC;IAEhC,uDAAuD;IACvD,oBAAoB,CAAC,KAAK,EAAE,iBAAiB,EAAE,GAAG,iBAAiB,EAAE,EAAE,CAAC;IAExE,+BAA+B;IAC/B,MAAM,IAAI,IAAI,CAAC;CAChB;AAED;;GAEG;AACH,wBAAgB,sBAAsB,CACpC,MAAM,GAAE,OAAO,CAAC,uBAAuB,CAAM,GAC5C,gBAAgB,CA6OlB;AAED;;;GAGG;AACH,wBAAgB,sBAAsB,CACpC,KAAK,EAAE,iBAAiB,EAAE,GACzB,iBAAiB,EAAE,EAAE,CAmBvB;AAED;;GAEG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;aAE7B,IAAI,EAAE,MAAM;gBAAZ,IAAI,EAAE,MAAM,EAC5B,OAAO,CAAC,EAAE,MAAM;IAMlB,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,sBAAsB;IAO/E,MAAM,CAAC,kBAAkB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,sBAAsB;IAOpE,MAAM,CAAC,UAAU,CAAC,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,sBAAsB;CAMzE"}
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Parallel Executor Implementation
3
+ *
4
+ * Executes workflow steps in parallel respecting dependencies.
5
+ * Uses DAG-based execution for optimal concurrency.
6
+ *
7
+ * Invariants:
8
+ * - INV-PE-001: Independent steps execute concurrently
9
+ * - INV-PE-002: Dependencies honored (DAG ordering)
10
+ * - INV-PE-003: Concurrency limit respected
11
+ */
12
+ import { createDefaultParallelExecutionConfig, ParallelExecutionErrorCodes, } from '@defai.digital/contracts';
13
+ /**
14
+ * Creates a parallel executor
15
+ */
16
+ export function createParallelExecutor(config = {}) {
17
+ const cfg = { ...createDefaultParallelExecutionConfig(), ...config };
18
+ let cancelled = false;
19
+ /**
20
+ * Build execution layers using topological sort (Kahn's algorithm)
21
+ * INV-PE-002: Dependencies honored (DAG ordering)
22
+ */
23
+ function buildLayers(steps) {
24
+ // Build dependency graph
25
+ const stepMap = new Map();
26
+ const inDegree = new Map();
27
+ const dependents = new Map();
28
+ // Initialize
29
+ for (const step of steps) {
30
+ stepMap.set(step.stepId, step);
31
+ inDegree.set(step.stepId, step.dependencies?.length ?? 0);
32
+ dependents.set(step.stepId, []);
33
+ }
34
+ // Build reverse dependency map
35
+ for (const step of steps) {
36
+ if (step.dependencies) {
37
+ for (const dep of step.dependencies) {
38
+ const depList = dependents.get(dep) ?? [];
39
+ depList.push(step.stepId);
40
+ dependents.set(dep, depList);
41
+ }
42
+ }
43
+ }
44
+ // Build layers using BFS
45
+ const layers = [];
46
+ let currentLayer = steps.filter((s) => inDegree.get(s.stepId) === 0);
47
+ while (currentLayer.length > 0) {
48
+ layers.push(currentLayer);
49
+ const nextLayer = [];
50
+ for (const step of currentLayer) {
51
+ const deps = dependents.get(step.stepId) ?? [];
52
+ for (const depId of deps) {
53
+ const degree = (inDegree.get(depId) ?? 0) - 1;
54
+ inDegree.set(depId, degree);
55
+ if (degree === 0) {
56
+ const depStep = stepMap.get(depId);
57
+ if (depStep) {
58
+ nextLayer.push(depStep);
59
+ }
60
+ }
61
+ }
62
+ }
63
+ currentLayer = nextLayer;
64
+ }
65
+ // Check for circular dependencies
66
+ const processedCount = layers.reduce((sum, l) => sum + l.length, 0);
67
+ if (processedCount !== steps.length) {
68
+ throw new ParallelExecutionError(ParallelExecutionErrorCodes.CIRCULAR_DEPENDENCY, 'Circular dependency detected in workflow steps');
69
+ }
70
+ return layers;
71
+ }
72
+ /**
73
+ * Execute steps with concurrency limit
74
+ * INV-PE-003: Concurrency limit respected
75
+ */
76
+ async function executeWithConcurrency(steps, executor, outputs, failureStrategy) {
77
+ const results = [];
78
+ const pending = [];
79
+ let hasFailure = false;
80
+ async function executeStep(step) {
81
+ if (cancelled) {
82
+ results.push({
83
+ stepId: step.stepId,
84
+ success: false,
85
+ cancelled: true,
86
+ durationMs: 0,
87
+ });
88
+ return;
89
+ }
90
+ // Fail fast check
91
+ if (hasFailure && failureStrategy === 'failFast') {
92
+ results.push({
93
+ stepId: step.stepId,
94
+ success: false,
95
+ cancelled: true,
96
+ durationMs: 0,
97
+ });
98
+ return;
99
+ }
100
+ const startTime = Date.now();
101
+ try {
102
+ const output = await executor(step, outputs);
103
+ const durationMs = Date.now() - startTime;
104
+ outputs[step.stepId] = output;
105
+ results.push({
106
+ stepId: step.stepId,
107
+ success: true,
108
+ output,
109
+ durationMs,
110
+ });
111
+ }
112
+ catch (error) {
113
+ const durationMs = Date.now() - startTime;
114
+ const errorMessage = error instanceof Error ? error.message : 'Unknown error';
115
+ hasFailure = true;
116
+ results.push({
117
+ stepId: step.stepId,
118
+ success: false,
119
+ error: errorMessage,
120
+ durationMs,
121
+ });
122
+ if (failureStrategy === 'failFast') {
123
+ cancelled = true;
124
+ }
125
+ }
126
+ }
127
+ // Execute with concurrency limit
128
+ // INV-PE-001: Independent steps execute concurrently
129
+ let index = 0;
130
+ while (index < steps.length || pending.length > 0) {
131
+ // Start new tasks up to concurrency limit
132
+ while (pending.length < cfg.maxConcurrency && index < steps.length) {
133
+ const step = steps[index];
134
+ if (step) {
135
+ const promise = executeStep(step).then(() => {
136
+ const idx = pending.indexOf(promise);
137
+ if (idx >= 0)
138
+ pending.splice(idx, 1);
139
+ });
140
+ pending.push(promise);
141
+ }
142
+ index++;
143
+ }
144
+ // Wait for at least one to complete
145
+ if (pending.length > 0) {
146
+ await Promise.race(pending);
147
+ }
148
+ }
149
+ return results;
150
+ }
151
+ return {
152
+ getConfig() {
153
+ return { ...cfg };
154
+ },
155
+ buildExecutionLayers(steps) {
156
+ return buildLayers(steps);
157
+ },
158
+ async executeGroup(steps, executor, previousOutputs = {}) {
159
+ cancelled = false;
160
+ const groupId = crypto.randomUUID();
161
+ const startTime = Date.now();
162
+ const outputs = { ...previousOutputs };
163
+ // Build execution layers
164
+ const layers = buildLayers(steps);
165
+ // Execute each layer
166
+ const allResults = [];
167
+ for (const layer of layers) {
168
+ if (cancelled)
169
+ break;
170
+ const layerResults = await executeWithConcurrency(layer, executor, outputs, cfg.failureStrategy);
171
+ allResults.push(...layerResults);
172
+ // Check for failures with failFast
173
+ if (cfg.failureStrategy === 'failFast') {
174
+ const failed = layerResults.some((r) => !r.success && !r.cancelled);
175
+ if (failed) {
176
+ cancelled = true;
177
+ break;
178
+ }
179
+ }
180
+ }
181
+ const totalDurationMs = Date.now() - startTime;
182
+ const failedSteps = allResults
183
+ .filter((r) => !r.success && !r.cancelled)
184
+ .map((r) => r.stepId);
185
+ const cancelledSteps = allResults
186
+ .filter((r) => r.cancelled)
187
+ .map((r) => r.stepId);
188
+ return {
189
+ groupId,
190
+ stepResults: allResults,
191
+ totalDurationMs,
192
+ allSucceeded: failedSteps.length === 0 && cancelledSteps.length === 0,
193
+ failedSteps,
194
+ cancelledSteps: cancelledSteps.length > 0 ? cancelledSteps : undefined,
195
+ stepsExecuted: allResults.filter((r) => !r.cancelled).length,
196
+ stepsSkipped: cancelledSteps.length,
197
+ };
198
+ },
199
+ cancel() {
200
+ cancelled = true;
201
+ },
202
+ };
203
+ }
204
+ /**
205
+ * Identifies parallel groups within a workflow
206
+ * Returns array of step groups that can be executed in parallel
207
+ */
208
+ export function identifyParallelGroups(steps) {
209
+ // Group steps by their dependencies
210
+ // Steps with the same set of dependencies can be grouped
211
+ const groups = [];
212
+ const depKeyToGroup = new Map();
213
+ for (const step of steps) {
214
+ const depKey = (step.dependencies ?? []).sort().join(',');
215
+ const group = depKeyToGroup.get(depKey);
216
+ if (group) {
217
+ group.push(step);
218
+ }
219
+ else {
220
+ const newGroup = [step];
221
+ depKeyToGroup.set(depKey, newGroup);
222
+ groups.push(newGroup);
223
+ }
224
+ }
225
+ return groups;
226
+ }
227
+ /**
228
+ * Parallel execution error
229
+ */
230
+ export class ParallelExecutionError extends Error {
231
+ code;
232
+ constructor(code, message) {
233
+ super(message ?? `Parallel execution error: ${code}`);
234
+ this.code = code;
235
+ this.name = 'ParallelExecutionError';
236
+ }
237
+ static groupTimeout(groupId, timeoutMs) {
238
+ return new ParallelExecutionError(ParallelExecutionErrorCodes.GROUP_TIMEOUT, `Parallel group ${groupId} timed out after ${timeoutMs}ms`);
239
+ }
240
+ static circularDependency(stepIds) {
241
+ return new ParallelExecutionError(ParallelExecutionErrorCodes.CIRCULAR_DEPENDENCY, `Circular dependency detected among steps: ${stepIds.join(', ')}`);
242
+ }
243
+ static stepFailed(stepId, error) {
244
+ return new ParallelExecutionError(ParallelExecutionErrorCodes.STEP_FAILED, `Step ${stepId} failed: ${error}`);
245
+ }
246
+ }
247
+ //# sourceMappingURL=parallel-executor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"parallel-executor.js","sourceRoot":"","sources":["../src/parallel-executor.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH,OAAO,EAML,oCAAoC,EACpC,2BAA2B,GAC5B,MAAM,0BAA0B,CAAC;AA+BlC;;GAEG;AACH,MAAM,UAAU,sBAAsB,CACpC,SAA2C,EAAE;IAE7C,MAAM,GAAG,GAAG,EAAE,GAAG,oCAAoC,EAAE,EAAE,GAAG,MAAM,EAAE,CAAC;IACrE,IAAI,SAAS,GAAG,KAAK,CAAC;IAEtB;;;OAGG;IACH,SAAS,WAAW,CAAC,KAA0B;QAC7C,yBAAyB;QACzB,MAAM,OAAO,GAAG,IAAI,GAAG,EAA6B,CAAC;QACrD,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAkB,CAAC;QAC3C,MAAM,UAAU,GAAG,IAAI,GAAG,EAAoB,CAAC;QAE/C,aAAa;QACb,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC;YAC/B,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,YAAY,EAAE,MAAM,IAAI,CAAC,CAAC,CAAC;YAC1D,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;QAClC,CAAC;QAED,+BAA+B;QAC/B,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;YACzB,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;gBACtB,KAAK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,CAAC,kBAAkB,CAAC,OAAiB;QACzC,OAAO,IAAI,sBAAsB,CAC/B,2BAA2B,CAAC,mBAAmB,EAC/C,6CAA6C,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAClE,CAAC;IACJ,CAAC;IAED,MAAM,CAAC,UAAU,CAAC,MAAc,EAAE,KAAa;QAC7C,OAAO,IAAI,sBAAsB,CAC/B,2BAA2B,CAAC,WAAW,EACvC,QAAQ,MAAM,YAAY,KAAK,EAAE,CAClC,CAAC;IACJ,CAAC;CACF"}
package/package.json ADDED
@@ -0,0 +1,41 @@
1
+ {
2
+ "name": "@defai.digital/agent-execution",
3
+ "version": "13.0.3",
4
+ "type": "module",
5
+ "description": "Agent execution domain for AutomatosX - checkpoints, delegation, parallel execution",
6
+ "license": "Apache-2.0",
7
+ "author": "DEFAI Private Limited",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/defai-digital/automatosx.git",
11
+ "directory": "packages/core/agent-execution"
12
+ },
13
+ "homepage": "https://github.com/defai-digital/automatosx#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/defai-digital/automatosx/issues"
16
+ },
17
+ "main": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "files": [
26
+ "dist"
27
+ ],
28
+ "engines": {
29
+ "node": ">=20.0.0"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ },
34
+ "dependencies": {
35
+ "@defai.digital/contracts": "13.0.3"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc --build",
39
+ "clean": "rm -rf dist *.tsbuildinfo"
40
+ }
41
+ }