@holoscript/engine 6.0.3 → 6.0.4

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.
Files changed (192) hide show
  1. package/dist/AutoMesher-CK47F6AV.js +17 -0
  2. package/dist/GPUBuffers-2LHBCD7X.js +9 -0
  3. package/dist/WebGPUContext-TNEUYU2Y.js +11 -0
  4. package/dist/animation/index.cjs +38 -38
  5. package/dist/animation/index.d.cts +1 -1
  6. package/dist/animation/index.d.ts +1 -1
  7. package/dist/animation/index.js +1 -1
  8. package/dist/audio/index.cjs +16 -6
  9. package/dist/audio/index.d.cts +1 -1
  10. package/dist/audio/index.d.ts +1 -1
  11. package/dist/audio/index.js +1 -1
  12. package/dist/camera/index.cjs +23 -23
  13. package/dist/camera/index.d.cts +1 -1
  14. package/dist/camera/index.d.ts +1 -1
  15. package/dist/camera/index.js +1 -1
  16. package/dist/character/index.cjs +6 -4
  17. package/dist/character/index.js +1 -1
  18. package/dist/choreography/index.cjs +1194 -0
  19. package/dist/choreography/index.d.cts +687 -0
  20. package/dist/choreography/index.d.ts +687 -0
  21. package/dist/choreography/index.js +1156 -0
  22. package/dist/chunk-2CSNRI2N.js +217 -0
  23. package/dist/chunk-33T2WINR.js +266 -0
  24. package/dist/chunk-35R73OFM.js +1257 -0
  25. package/dist/chunk-4MMDSUNP.js +1256 -0
  26. package/dist/chunk-5V6HOU72.js +319 -0
  27. package/dist/chunk-6QOP6PYF.js +1038 -0
  28. package/dist/chunk-7KMJVHIL.js +8944 -0
  29. package/dist/chunk-7VPUC62U.js +1106 -0
  30. package/dist/chunk-A2Y6RCAT.js +1878 -0
  31. package/dist/chunk-AHM42MK6.js +8944 -0
  32. package/dist/chunk-BL7IDTHE.js +218 -0
  33. package/dist/chunk-CITOMSWL.js +10462 -0
  34. package/dist/chunk-CXDPKW2K.js +8944 -0
  35. package/dist/chunk-CXZPLD4S.js +223 -0
  36. package/dist/chunk-CZYJE7IH.js +5169 -0
  37. package/dist/chunk-D2OP7YC7.js +6325 -0
  38. package/dist/chunk-EDRVQHUU.js +1544 -0
  39. package/dist/chunk-EJSLOOW2.js +3589 -0
  40. package/dist/chunk-F53SFGW5.js +1878 -0
  41. package/dist/chunk-HCFPELPY.js +919 -0
  42. package/dist/chunk-HNEE36PY.js +93 -0
  43. package/dist/chunk-HYXNV36F.js +1256 -0
  44. package/dist/chunk-IB7KHVFY.js +821 -0
  45. package/dist/chunk-IBBO7YYG.js +690 -0
  46. package/dist/chunk-ILIBGINU.js +5470 -0
  47. package/dist/chunk-IS4MHLKN.js +5479 -0
  48. package/dist/chunk-JT2PFKWD.js +5479 -0
  49. package/dist/chunk-K4CUB4NY.js +1038 -0
  50. package/dist/chunk-KATDQXRJ.js +10462 -0
  51. package/dist/chunk-KBQE6ZFJ.js +8944 -0
  52. package/dist/chunk-KBVD5K7E.js +560 -0
  53. package/dist/chunk-KCDPVQRY.js +4088 -0
  54. package/dist/chunk-KN4QJPKN.js +8944 -0
  55. package/dist/chunk-KWJ3ROSI.js +8944 -0
  56. package/dist/chunk-L45VF6DD.js +919 -0
  57. package/dist/chunk-LY4T37YK.js +307 -0
  58. package/dist/chunk-MDN5WZXA.js +1544 -0
  59. package/dist/chunk-MGCDP6VU.js +928 -0
  60. package/dist/chunk-NCX7X6G2.js +8681 -0
  61. package/dist/chunk-OF54BPVD.js +913 -0
  62. package/dist/chunk-OWSN2Q3Q.js +690 -0
  63. package/dist/chunk-PRRB5TTA.js +406 -0
  64. package/dist/chunk-PXWVQF76.js +4086 -0
  65. package/dist/chunk-PYCOIDT2.js +812 -0
  66. package/dist/chunk-PZCSADOV.js +928 -0
  67. package/dist/chunk-Q2XBVS2K.js +1038 -0
  68. package/dist/chunk-QDZRXWN5.js +1776 -0
  69. package/dist/chunk-RNWOZ6WQ.js +913 -0
  70. package/dist/chunk-ROLFT4CJ.js +1693 -0
  71. package/dist/chunk-SLTJRZ2N.js +266 -0
  72. package/dist/chunk-SRUS5XSU.js +4088 -0
  73. package/dist/chunk-TKCA3WZ5.js +5409 -0
  74. package/dist/chunk-TNRMXYI2.js +1650 -0
  75. package/dist/chunk-TQB3GJGM.js +9763 -0
  76. package/dist/chunk-TUFGXG6K.js +510 -0
  77. package/dist/chunk-U6KMTGQJ.js +632 -0
  78. package/dist/chunk-VMGJQST6.js +8681 -0
  79. package/dist/chunk-X4F4TCG4.js +5470 -0
  80. package/dist/chunk-ZIFROE75.js +1544 -0
  81. package/dist/chunk-ZIJQYHSQ.js +1204 -0
  82. package/dist/combat/index.cjs +4 -4
  83. package/dist/combat/index.d.cts +1 -1
  84. package/dist/combat/index.d.ts +1 -1
  85. package/dist/combat/index.js +1 -1
  86. package/dist/ecs/index.cjs +1 -1
  87. package/dist/ecs/index.js +1 -1
  88. package/dist/environment/index.cjs +14 -14
  89. package/dist/environment/index.d.cts +1 -1
  90. package/dist/environment/index.d.ts +1 -1
  91. package/dist/environment/index.js +1 -1
  92. package/dist/gpu/index.cjs +4810 -0
  93. package/dist/gpu/index.js +3714 -0
  94. package/dist/hologram/index.cjs +27 -1
  95. package/dist/hologram/index.js +1 -1
  96. package/dist/index-B2PIsAmR.d.cts +2180 -0
  97. package/dist/index-B2PIsAmR.d.ts +2180 -0
  98. package/dist/index-BHySEPX7.d.cts +2921 -0
  99. package/dist/index-BJV21zuy.d.cts +341 -0
  100. package/dist/index-BJV21zuy.d.ts +341 -0
  101. package/dist/index-BQutTphC.d.cts +790 -0
  102. package/dist/index-ByIq2XrS.d.cts +3910 -0
  103. package/dist/index-BysHjDSO.d.cts +224 -0
  104. package/dist/index-BysHjDSO.d.ts +224 -0
  105. package/dist/index-CKwAJGck.d.ts +455 -0
  106. package/dist/index-CUl3QstQ.d.cts +3006 -0
  107. package/dist/index-CUl3QstQ.d.ts +3006 -0
  108. package/dist/index-CmYtNiI-.d.cts +953 -0
  109. package/dist/index-CmYtNiI-.d.ts +953 -0
  110. package/dist/index-CnRzWxi_.d.cts +522 -0
  111. package/dist/index-CnRzWxi_.d.ts +522 -0
  112. package/dist/index-CwRWbSC7.d.ts +2921 -0
  113. package/dist/index-CxKIBstO.d.ts +790 -0
  114. package/dist/index-DJ6-R8vh.d.cts +455 -0
  115. package/dist/index-DQKisbcI.d.cts +4968 -0
  116. package/dist/index-DQKisbcI.d.ts +4968 -0
  117. package/dist/index-DRT2zJez.d.ts +3910 -0
  118. package/dist/index-DfNLiAka.d.cts +192 -0
  119. package/dist/index-DfNLiAka.d.ts +192 -0
  120. package/dist/index-nMvkoRm8.d.cts +405 -0
  121. package/dist/index-nMvkoRm8.d.ts +405 -0
  122. package/dist/index-s9yOFU37.d.cts +604 -0
  123. package/dist/index-s9yOFU37.d.ts +604 -0
  124. package/dist/index.cjs +22966 -6960
  125. package/dist/index.d.cts +864 -20
  126. package/dist/index.d.ts +864 -20
  127. package/dist/index.js +3062 -48
  128. package/dist/input/index.cjs +1 -1
  129. package/dist/input/index.js +1 -1
  130. package/dist/orbital/index.cjs +3 -3
  131. package/dist/orbital/index.d.cts +1 -1
  132. package/dist/orbital/index.d.ts +1 -1
  133. package/dist/orbital/index.js +1 -1
  134. package/dist/particles/index.cjs +16 -16
  135. package/dist/particles/index.d.cts +1 -1
  136. package/dist/particles/index.d.ts +1 -1
  137. package/dist/particles/index.js +1 -1
  138. package/dist/physics/index.cjs +2377 -21
  139. package/dist/physics/index.d.cts +1 -1
  140. package/dist/physics/index.d.ts +1 -1
  141. package/dist/physics/index.js +35 -1
  142. package/dist/postfx/index.cjs +3491 -0
  143. package/dist/postfx/index.js +93 -0
  144. package/dist/procedural/index.cjs +1 -1
  145. package/dist/procedural/index.js +1 -1
  146. package/dist/puppeteer-5VF6KDVO.js +52197 -0
  147. package/dist/puppeteer-IZVZ3SG4.js +52197 -0
  148. package/dist/rendering/index.cjs +33 -32
  149. package/dist/rendering/index.d.cts +1 -1
  150. package/dist/rendering/index.d.ts +1 -1
  151. package/dist/rendering/index.js +8 -6
  152. package/dist/runtime/index.cjs +23 -13
  153. package/dist/runtime/index.d.cts +1 -1
  154. package/dist/runtime/index.d.ts +1 -1
  155. package/dist/runtime/index.js +8 -6
  156. package/dist/runtime/protocols/index.cjs +349 -0
  157. package/dist/runtime/protocols/index.js +15 -0
  158. package/dist/scene/index.cjs +8 -8
  159. package/dist/scene/index.d.cts +1 -1
  160. package/dist/scene/index.d.ts +1 -1
  161. package/dist/scene/index.js +1 -1
  162. package/dist/shader/index.cjs +3087 -0
  163. package/dist/shader/index.js +3044 -0
  164. package/dist/simulation/index.cjs +10680 -0
  165. package/dist/simulation/index.d.cts +3 -0
  166. package/dist/simulation/index.d.ts +3 -0
  167. package/dist/simulation/index.js +307 -0
  168. package/dist/spatial/index.cjs +2443 -0
  169. package/dist/spatial/index.d.cts +1545 -0
  170. package/dist/spatial/index.d.ts +1545 -0
  171. package/dist/spatial/index.js +2400 -0
  172. package/dist/terrain/index.cjs +1 -1
  173. package/dist/terrain/index.d.cts +1 -1
  174. package/dist/terrain/index.d.ts +1 -1
  175. package/dist/terrain/index.js +1 -1
  176. package/dist/transformers.node-4NKAPD5U.js +45620 -0
  177. package/dist/vm/index.cjs +7 -8
  178. package/dist/vm/index.d.cts +1 -1
  179. package/dist/vm/index.d.ts +1 -1
  180. package/dist/vm/index.js +1 -1
  181. package/dist/vm-bridge/index.cjs +2 -2
  182. package/dist/vm-bridge/index.d.cts +2 -2
  183. package/dist/vm-bridge/index.d.ts +2 -2
  184. package/dist/vm-bridge/index.js +1 -1
  185. package/dist/vr/index.cjs +6 -6
  186. package/dist/vr/index.js +1 -1
  187. package/dist/world/index.cjs +3 -3
  188. package/dist/world/index.d.cts +1 -1
  189. package/dist/world/index.d.ts +1 -1
  190. package/dist/world/index.js +1 -1
  191. package/package.json +53 -21
  192. package/LICENSE +0 -21
@@ -0,0 +1,1194 @@
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/choreography/index.ts
21
+ var choreography_exports = {};
22
+ __export(choreography_exports, {
23
+ ChoreographyEngine: () => ChoreographyEngine,
24
+ ChoreographyPlanner: () => ChoreographyPlanner,
25
+ Constraints: () => Constraints,
26
+ DEFAULT_ENGINE_CONFIG: () => DEFAULT_ENGINE_CONFIG,
27
+ DEFAULT_EXECUTOR_CONFIG: () => DEFAULT_EXECUTOR_CONFIG,
28
+ DEFAULT_RETRY_CONFIG: () => DEFAULT_RETRY_CONFIG,
29
+ PlanBuilder: () => PlanBuilder,
30
+ StepExecutor: () => StepExecutor,
31
+ getDefaultEngine: () => getDefaultEngine,
32
+ getDefaultExecutor: () => getDefaultExecutor,
33
+ getDefaultPlanner: () => getDefaultPlanner,
34
+ plan: () => plan,
35
+ resetDefaultEngine: () => resetDefaultEngine,
36
+ resetDefaultExecutor: () => resetDefaultExecutor
37
+ });
38
+ module.exports = __toCommonJS(choreography_exports);
39
+
40
+ // src/choreography/ChoreographyTypes.ts
41
+ var DEFAULT_RETRY_CONFIG = {
42
+ strategy: "exponential",
43
+ maxRetries: 3,
44
+ delay: 1e3,
45
+ backoffMultiplier: 2,
46
+ maxDelay: 3e4
47
+ };
48
+ var Constraints = {
49
+ timeout(ms, hard = true) {
50
+ return { type: "timeout", value: ms, hard, description: `Max ${ms}ms execution time` };
51
+ },
52
+ concurrency(max) {
53
+ return { type: "concurrency", value: max, description: `Max ${max} concurrent steps` };
54
+ },
55
+ trust(minLevel) {
56
+ return { type: "trust", value: minLevel, hard: true, description: `Min trust: ${minLevel}` };
57
+ }
58
+ };
59
+
60
+ // src/choreography/StepExecutor.ts
61
+ var import_events = require("events");
62
+ var DEFAULT_EXECUTOR_CONFIG = {
63
+ defaultTimeout: 3e4,
64
+ defaultRetry: DEFAULT_RETRY_CONFIG,
65
+ verbose: false
66
+ };
67
+ var StepExecutor = class extends import_events.EventEmitter {
68
+ config;
69
+ actionHandler = null;
70
+ runningSteps = /* @__PURE__ */ new Map();
71
+ constructor(config = {}) {
72
+ super();
73
+ this.config = { ...DEFAULT_EXECUTOR_CONFIG, ...config };
74
+ }
75
+ /**
76
+ * Register the action handler for executing agent actions
77
+ */
78
+ setActionHandler(handler) {
79
+ this.actionHandler = handler;
80
+ }
81
+ /**
82
+ * Execute a single step
83
+ */
84
+ async execute(step, context) {
85
+ const startTime = Date.now();
86
+ if (this.shouldSkip(step, context)) {
87
+ const reason = "Condition not met";
88
+ this.emit("step:skipped", step, reason);
89
+ return {
90
+ stepId: step.id,
91
+ success: true,
92
+ outputs: {},
93
+ duration: 0,
94
+ error: void 0
95
+ };
96
+ }
97
+ const agent = context.agents.get(step.agentId);
98
+ if (!agent) {
99
+ throw new Error(`Agent not found: ${step.agentId}`);
100
+ }
101
+ const resolvedInputs = this.resolveInputs(step.inputs, context);
102
+ this.emit("step:inputs:resolved", step, resolvedInputs);
103
+ const retryConfig = {
104
+ ...this.config.defaultRetry,
105
+ ...step.retry || {}
106
+ };
107
+ let lastError = null;
108
+ let attempt = 0;
109
+ while (attempt <= retryConfig.maxRetries) {
110
+ try {
111
+ step.status = "running";
112
+ step.startedAt = Date.now();
113
+ step.retryAttempt = attempt;
114
+ this.emit("step:executing", step, agent);
115
+ const abortController = new AbortController();
116
+ this.runningSteps.set(step.id, abortController);
117
+ const timeout = step.timeout || this.config.defaultTimeout;
118
+ const outputs = await this.executeWithTimeout(
119
+ step,
120
+ agent,
121
+ resolvedInputs,
122
+ context,
123
+ timeout,
124
+ abortController.signal
125
+ );
126
+ this.runningSteps.delete(step.id);
127
+ step.status = "completed";
128
+ step.completedAt = Date.now();
129
+ step.duration = step.completedAt - step.startedAt;
130
+ const result = {
131
+ stepId: step.id,
132
+ success: true,
133
+ outputs,
134
+ duration: step.duration,
135
+ retries: attempt
136
+ };
137
+ this.emit("step:completed", step, result);
138
+ return result;
139
+ } catch (error) {
140
+ lastError = error instanceof Error ? error : new Error(String(error));
141
+ this.runningSteps.delete(step.id);
142
+ if (lastError.message.includes("cancelled")) {
143
+ step.status = "failed";
144
+ step.completedAt = Date.now();
145
+ step.duration = step.completedAt - (step.startedAt || startTime);
146
+ step.error = lastError.message;
147
+ return {
148
+ stepId: step.id,
149
+ success: false,
150
+ outputs: {},
151
+ duration: step.duration,
152
+ error: step.error,
153
+ retries: attempt
154
+ };
155
+ }
156
+ if (attempt < retryConfig.maxRetries) {
157
+ if (retryConfig.condition && !retryConfig.condition(lastError, attempt)) {
158
+ break;
159
+ }
160
+ const delay = this.calculateDelay(retryConfig, attempt);
161
+ this.emit("step:retrying", step, attempt + 1, delay);
162
+ await this.sleep(delay);
163
+ }
164
+ attempt++;
165
+ }
166
+ }
167
+ step.status = "failed";
168
+ step.completedAt = Date.now();
169
+ step.duration = step.completedAt - (step.startedAt || startTime);
170
+ step.error = lastError?.message || "Unknown error";
171
+ this.emit("step:failed", step, lastError || new Error("Unknown error"));
172
+ return {
173
+ stepId: step.id,
174
+ success: false,
175
+ outputs: {},
176
+ duration: step.duration,
177
+ error: step.error,
178
+ retries: attempt - 1
179
+ };
180
+ }
181
+ /**
182
+ * Cancel a running step
183
+ */
184
+ cancel(stepId) {
185
+ const controller = this.runningSteps.get(stepId);
186
+ if (controller) {
187
+ controller.abort();
188
+ this.runningSteps.delete(stepId);
189
+ return true;
190
+ }
191
+ return false;
192
+ }
193
+ /**
194
+ * Check if any steps are running
195
+ */
196
+ isRunning(stepId) {
197
+ if (stepId) {
198
+ return this.runningSteps.has(stepId);
199
+ }
200
+ return this.runningSteps.size > 0;
201
+ }
202
+ // ==========================================================================
203
+ // PRIVATE METHODS
204
+ // ==========================================================================
205
+ /**
206
+ * Check if step should be skipped
207
+ */
208
+ shouldSkip(step, context) {
209
+ if (!step.condition) return false;
210
+ if (typeof step.condition === "function") {
211
+ return !step.condition(context);
212
+ }
213
+ try {
214
+ return !this.evaluateCondition(step.condition, context);
215
+ } catch {
216
+ return false;
217
+ }
218
+ }
219
+ /**
220
+ * Evaluate a string condition
221
+ */
222
+ evaluateCondition(condition, context) {
223
+ const stepRefRegex = /step#(\w+)\.outputs\.(\w+)/g;
224
+ let evaluated = condition;
225
+ evaluated = evaluated.replace(stepRefRegex, (_, stepId, outputKey) => {
226
+ const outputs = context.stepOutputs.get(stepId);
227
+ if (outputs && outputKey in outputs) {
228
+ const value2 = outputs[outputKey];
229
+ if (typeof value2 === "string") {
230
+ return `"${value2}"`;
231
+ }
232
+ return String(value2);
233
+ }
234
+ return "undefined";
235
+ });
236
+ const eqMatch = evaluated.match(/^(.+)\s*==\s*(.+)$/);
237
+ if (eqMatch) {
238
+ const [, left, right] = eqMatch;
239
+ return this.parseValue(left.trim()) === this.parseValue(right.trim());
240
+ }
241
+ const value = this.parseValue(evaluated.trim());
242
+ return Boolean(value);
243
+ }
244
+ /**
245
+ * Parse a string value
246
+ */
247
+ parseValue(str) {
248
+ if (str === "true") return true;
249
+ if (str === "false") return false;
250
+ if (str === "null") return null;
251
+ if (str === "undefined") return void 0;
252
+ if (/^-?\d+$/.test(str)) return parseInt(str, 10);
253
+ if (/^-?\d+\.\d+$/.test(str)) return parseFloat(str);
254
+ if (str.startsWith('"') && str.endsWith('"')) {
255
+ return str.slice(1, -1);
256
+ }
257
+ return str;
258
+ }
259
+ /**
260
+ * Resolve input references
261
+ */
262
+ resolveInputs(inputs, context) {
263
+ const resolved = {};
264
+ for (const [key, value] of Object.entries(inputs)) {
265
+ if (typeof value === "string") {
266
+ const templateRef = value.match(/^\$\{([\w-]+)\.([\w-]+)\}$/);
267
+ if (templateRef) {
268
+ const [, stepName, outputKey] = templateRef;
269
+ let outputs = context.stepOutputs.get(stepName);
270
+ if (!outputs && context.plan?.steps) {
271
+ const referencedStep = context.plan.steps.find(
272
+ (s) => s.name === stepName || s.id === stepName
273
+ );
274
+ if (referencedStep) {
275
+ outputs = context.stepOutputs.get(referencedStep.id);
276
+ }
277
+ }
278
+ if (outputs) {
279
+ resolved[key] = outputs[outputKey];
280
+ continue;
281
+ }
282
+ }
283
+ const stepRef = value.match(/^step#(\w+)\.outputs\.(\w+)$/);
284
+ if (stepRef) {
285
+ const [, stepId, outputKey] = stepRef;
286
+ const outputs = context.stepOutputs.get(stepId);
287
+ resolved[key] = outputs?.[outputKey];
288
+ continue;
289
+ }
290
+ const stateRef = value.match(/^state\.(\w+)$/);
291
+ if (stateRef) {
292
+ resolved[key] = context.variables[stateRef[1]];
293
+ continue;
294
+ }
295
+ }
296
+ resolved[key] = value;
297
+ }
298
+ return resolved;
299
+ }
300
+ /**
301
+ * Execute with timeout
302
+ */
303
+ async executeWithTimeout(step, agent, inputs, context, timeout, signal) {
304
+ if (!this.actionHandler) {
305
+ throw new Error("No action handler registered");
306
+ }
307
+ return new Promise((resolve, reject) => {
308
+ const timer = setTimeout(() => {
309
+ this.emit("step:timeout", step, timeout);
310
+ reject(new Error(`Step timed out after ${timeout}ms`));
311
+ }, timeout);
312
+ signal.addEventListener("abort", () => {
313
+ clearTimeout(timer);
314
+ reject(new Error("Step was cancelled"));
315
+ });
316
+ this.actionHandler(agent, step.action, inputs, context).then((outputs) => {
317
+ clearTimeout(timer);
318
+ resolve(outputs);
319
+ }).catch((error) => {
320
+ clearTimeout(timer);
321
+ reject(error);
322
+ });
323
+ });
324
+ }
325
+ /**
326
+ * Calculate retry delay
327
+ */
328
+ calculateDelay(config, attempt) {
329
+ let delay = config.delay;
330
+ switch (config.strategy) {
331
+ case "none":
332
+ return 0;
333
+ case "immediate":
334
+ return 0;
335
+ case "fixed":
336
+ return delay;
337
+ case "exponential":
338
+ delay = delay * Math.pow(config.backoffMultiplier || 2, attempt);
339
+ break;
340
+ }
341
+ if (config.maxDelay && delay > config.maxDelay) {
342
+ delay = config.maxDelay;
343
+ }
344
+ const jitter = delay * 0.1 * (Math.random() * 2 - 1);
345
+ return Math.round(delay + jitter);
346
+ }
347
+ /**
348
+ * Sleep helper
349
+ */
350
+ sleep(ms) {
351
+ return new Promise((resolve) => setTimeout(resolve, ms));
352
+ }
353
+ };
354
+ var defaultExecutor = null;
355
+ function getDefaultExecutor() {
356
+ if (!defaultExecutor) {
357
+ defaultExecutor = new StepExecutor();
358
+ }
359
+ return defaultExecutor;
360
+ }
361
+ function resetDefaultExecutor() {
362
+ defaultExecutor = null;
363
+ }
364
+
365
+ // src/choreography/ChoreographyPlanner.ts
366
+ var import_agents = require("@holoscript/framework/agents");
367
+ function generateId() {
368
+ return `${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
369
+ }
370
+ var ChoreographyPlanner = class {
371
+ matcher = new import_agents.CapabilityMatcher();
372
+ /**
373
+ * Create a choreography plan from definition
374
+ */
375
+ createPlan(definition) {
376
+ const planId = generateId();
377
+ const _agents = new Map(definition.agents.map((a) => [a.id, a]));
378
+ const steps = definition.steps.map((stepDef) => {
379
+ const agentId = this.resolveAgent(stepDef.agent, definition.agents);
380
+ if (!agentId) {
381
+ throw new Error(
382
+ `No agent found for step ${stepDef.id || stepDef.name}: ${JSON.stringify(stepDef.agent)}`
383
+ );
384
+ }
385
+ const outputs = {};
386
+ if (stepDef.outputs) {
387
+ for (const [key, value] of Object.entries(stepDef.outputs)) {
388
+ if (typeof value === "string") {
389
+ outputs[key] = { key, type: "unknown" };
390
+ } else {
391
+ outputs[key] = value;
392
+ }
393
+ }
394
+ }
395
+ const step = {
396
+ id: stepDef.id || `step_${generateId()}`,
397
+ name: stepDef.name,
398
+ description: stepDef.description,
399
+ agentId,
400
+ action: stepDef.action,
401
+ inputs: stepDef.inputs || {},
402
+ outputs,
403
+ dependencies: stepDef.dependencies || stepDef.dependsOn || [],
404
+ parallelGroup: stepDef.parallelGroup,
405
+ status: "pending",
406
+ timeout: stepDef.timeout,
407
+ retry: stepDef.retries !== void 0 ? { maxRetries: stepDef.retries } : void 0,
408
+ condition: stepDef.condition,
409
+ hitlGate: stepDef.hitlGate,
410
+ fallbackStepId: stepDef.fallbackStepId
411
+ };
412
+ return step;
413
+ });
414
+ const stepNameToId = /* @__PURE__ */ new Map();
415
+ for (const step of steps) {
416
+ if (step.name) {
417
+ stepNameToId.set(step.name, step.id);
418
+ }
419
+ stepNameToId.set(step.id, step.id);
420
+ }
421
+ for (const step of steps) {
422
+ step.dependencies = step.dependencies.map((dep) => {
423
+ const resolvedId = stepNameToId.get(dep);
424
+ if (!resolvedId) {
425
+ throw new Error(`Unknown step dependency "${dep}" in step "${step.name || step.id}"`);
426
+ }
427
+ return resolvedId;
428
+ });
429
+ }
430
+ let fallback;
431
+ if (definition.fallback) {
432
+ fallback = this.createPlan(definition.fallback);
433
+ }
434
+ const plan2 = {
435
+ id: planId,
436
+ name: definition.name,
437
+ goal: definition.goal,
438
+ steps,
439
+ participants: definition.agents,
440
+ constraints: definition.constraints || [],
441
+ fallback,
442
+ status: "draft",
443
+ createdAt: Date.now(),
444
+ priority: definition.priority,
445
+ tags: definition.tags,
446
+ metadata: definition.metadata
447
+ };
448
+ return plan2;
449
+ }
450
+ /**
451
+ * Validate a choreography plan
452
+ */
453
+ validate(plan2) {
454
+ const errors = [];
455
+ const warnings = [];
456
+ const stepIds = new Set(plan2.steps.map((s) => s.id));
457
+ const agentIds = new Set(plan2.participants.map((a) => a.id));
458
+ if (plan2.steps.length === 0) {
459
+ errors.push("Plan has no steps");
460
+ }
461
+ for (const step of plan2.steps) {
462
+ if (!agentIds.has(step.agentId)) {
463
+ errors.push(`Step '${step.id}': Agent '${step.agentId}' not in participants`);
464
+ }
465
+ if (!step.action) {
466
+ errors.push(`Step '${step.id}': No action specified`);
467
+ }
468
+ for (const depId of step.dependencies) {
469
+ if (!stepIds.has(depId)) {
470
+ errors.push(`Step '${step.id}': Dependency '${depId}' does not exist`);
471
+ }
472
+ if (depId === step.id) {
473
+ errors.push(`Step '${step.id}': Cannot depend on itself`);
474
+ }
475
+ }
476
+ }
477
+ const cycleCheck = this.detectCycles(plan2.steps);
478
+ if (cycleCheck) {
479
+ errors.push(`Circular dependency detected: ${cycleCheck.join(" -> ")}`);
480
+ }
481
+ if (!plan2.constraints.some((c) => c.type === "timeout")) {
482
+ warnings.push("No timeout constraint specified");
483
+ }
484
+ if (plan2.steps.some((s) => s.hitlGate) && !plan2.participants.some((a) => a.capabilities?.some((c) => c.type === "approve"))) {
485
+ warnings.push("HITL gate present but no approval agent in participants");
486
+ }
487
+ return {
488
+ valid: errors.length === 0,
489
+ errors,
490
+ warnings
491
+ };
492
+ }
493
+ /**
494
+ * Calculate execution order
495
+ */
496
+ calculateExecutionOrder(plan2) {
497
+ const graph = /* @__PURE__ */ new Map();
498
+ const inDegree = /* @__PURE__ */ new Map();
499
+ for (const step of plan2.steps) {
500
+ graph.set(step.id, step.dependencies);
501
+ inDegree.set(step.id, step.dependencies.length);
502
+ }
503
+ const flatOrder = [];
504
+ const parallelGroups = [];
505
+ const queue = [];
506
+ for (const [stepId, degree] of inDegree.entries()) {
507
+ if (degree === 0) {
508
+ queue.push(stepId);
509
+ }
510
+ }
511
+ while (queue.length > 0) {
512
+ const currentGroup = [...queue];
513
+ parallelGroups.push(currentGroup);
514
+ queue.length = 0;
515
+ for (const stepId of currentGroup) {
516
+ flatOrder.push(stepId);
517
+ for (const [otherId, deps] of graph.entries()) {
518
+ if (deps.includes(stepId)) {
519
+ const newDegree = (inDegree.get(otherId) || 0) - 1;
520
+ inDegree.set(otherId, newDegree);
521
+ if (newDegree === 0) {
522
+ queue.push(otherId);
523
+ }
524
+ }
525
+ }
526
+ }
527
+ }
528
+ return {
529
+ parallelGroups,
530
+ flatOrder,
531
+ graph
532
+ };
533
+ }
534
+ /**
535
+ * Clone and reset a plan for re-execution
536
+ */
537
+ resetPlan(plan2) {
538
+ return {
539
+ ...plan2,
540
+ id: generateId(),
541
+ status: "draft",
542
+ createdAt: Date.now(),
543
+ startedAt: void 0,
544
+ completedAt: void 0,
545
+ duration: void 0,
546
+ steps: plan2.steps.map((step) => ({
547
+ ...step,
548
+ status: "pending",
549
+ startedAt: void 0,
550
+ completedAt: void 0,
551
+ duration: void 0,
552
+ error: void 0,
553
+ retryAttempt: void 0
554
+ }))
555
+ };
556
+ }
557
+ // ==========================================================================
558
+ // PRIVATE METHODS
559
+ // ==========================================================================
560
+ /**
561
+ * Resolve agent from ID or capability query
562
+ */
563
+ resolveAgent(agentRef, agents) {
564
+ if (typeof agentRef === "string") {
565
+ const agent = agents.find((a) => a.id === agentRef || a.name === agentRef);
566
+ return agent?.id || null;
567
+ }
568
+ const matches = this.matcher.findMatches(agents, agentRef);
569
+ if (matches.length > 0) {
570
+ return matches[0].manifest.id;
571
+ }
572
+ return null;
573
+ }
574
+ /**
575
+ * Detect circular dependencies
576
+ */
577
+ detectCycles(steps) {
578
+ const visited = /* @__PURE__ */ new Set();
579
+ const recursionStack = /* @__PURE__ */ new Set();
580
+ const stepMap = new Map(steps.map((s) => [s.id, s]));
581
+ const dfs = (stepId, path) => {
582
+ if (recursionStack.has(stepId)) {
583
+ return [...path, stepId];
584
+ }
585
+ if (visited.has(stepId)) {
586
+ return null;
587
+ }
588
+ visited.add(stepId);
589
+ recursionStack.add(stepId);
590
+ const step = stepMap.get(stepId);
591
+ if (step) {
592
+ for (const depId of step.dependencies) {
593
+ const cycle = dfs(depId, [...path, stepId]);
594
+ if (cycle) return cycle;
595
+ }
596
+ }
597
+ recursionStack.delete(stepId);
598
+ return null;
599
+ };
600
+ for (const step of steps) {
601
+ const cycle = dfs(step.id, []);
602
+ if (cycle) return cycle;
603
+ }
604
+ return null;
605
+ }
606
+ };
607
+ var PlanBuilder = class {
608
+ definition;
609
+ planner = new ChoreographyPlanner();
610
+ constructor(goal) {
611
+ this.definition = {
612
+ goal,
613
+ agents: [],
614
+ steps: [],
615
+ constraints: []
616
+ };
617
+ }
618
+ /**
619
+ * Set plan name
620
+ */
621
+ name(name) {
622
+ this.definition.name = name;
623
+ return this;
624
+ }
625
+ /**
626
+ * Add an agent to the plan
627
+ */
628
+ agent(manifest) {
629
+ this.definition.agents.push(manifest);
630
+ return this;
631
+ }
632
+ /**
633
+ * Add multiple agents
634
+ */
635
+ agents(manifests) {
636
+ this.definition.agents.push(...manifests);
637
+ return this;
638
+ }
639
+ /**
640
+ * Add a step to the plan
641
+ */
642
+ step(definition) {
643
+ this.definition.steps.push(definition);
644
+ return this;
645
+ }
646
+ /**
647
+ * Add a constraint
648
+ */
649
+ constraint(constraint) {
650
+ this.definition.constraints.push(constraint);
651
+ return this;
652
+ }
653
+ /**
654
+ * Set timeout constraint
655
+ */
656
+ timeout(ms) {
657
+ this.definition.constraints.push({
658
+ type: "timeout",
659
+ value: ms,
660
+ hard: true,
661
+ description: `Maximum ${ms}ms execution time`
662
+ });
663
+ return this;
664
+ }
665
+ /**
666
+ * Set concurrency constraint
667
+ */
668
+ concurrency(max) {
669
+ this.definition.constraints.push({
670
+ type: "concurrency",
671
+ value: max,
672
+ description: `Maximum ${max} concurrent steps`
673
+ });
674
+ return this;
675
+ }
676
+ /**
677
+ * Set fallback plan
678
+ */
679
+ fallback(fallbackPlan) {
680
+ this.definition.fallback = fallbackPlan;
681
+ return this;
682
+ }
683
+ /**
684
+ * Set priority
685
+ */
686
+ priority(priority) {
687
+ this.definition.priority = priority;
688
+ return this;
689
+ }
690
+ /**
691
+ * Add tags
692
+ */
693
+ tags(...tags) {
694
+ this.definition.tags = [...this.definition.tags || [], ...tags];
695
+ return this;
696
+ }
697
+ /**
698
+ * Set metadata
699
+ */
700
+ metadata(meta) {
701
+ this.definition.metadata = { ...this.definition.metadata || {}, ...meta };
702
+ return this;
703
+ }
704
+ /**
705
+ * Build and validate the plan
706
+ */
707
+ build() {
708
+ const plan2 = this.planner.createPlan(this.definition);
709
+ const validation = this.planner.validate(plan2);
710
+ if (!validation.valid) {
711
+ throw new Error(`Plan validation failed:
712
+ ${validation.errors.join("\n")}`);
713
+ }
714
+ return plan2;
715
+ }
716
+ /**
717
+ * Build without validation (for testing)
718
+ */
719
+ buildUnsafe() {
720
+ return this.planner.createPlan(this.definition);
721
+ }
722
+ };
723
+ function plan(goal) {
724
+ return new PlanBuilder(goal);
725
+ }
726
+ var defaultPlanner = null;
727
+ function getDefaultPlanner() {
728
+ if (!defaultPlanner) {
729
+ defaultPlanner = new ChoreographyPlanner();
730
+ }
731
+ return defaultPlanner;
732
+ }
733
+
734
+ // src/choreography/ChoreographyEngine.ts
735
+ var import_events2 = require("events");
736
+ var DEFAULT_ENGINE_CONFIG = {
737
+ maxConcurrency: 4,
738
+ defaultTimeout: 3e4,
739
+ executeFallback: true,
740
+ autoHitlPause: true,
741
+ verbose: false
742
+ };
743
+ var ChoreographyEngine = class extends import_events2.EventEmitter {
744
+ config;
745
+ planner;
746
+ executor;
747
+ registry = null;
748
+ activePlans = /* @__PURE__ */ new Map();
749
+ actionHandler = null;
750
+ constructor(config = {}) {
751
+ super();
752
+ this.config = { ...DEFAULT_ENGINE_CONFIG, ...config };
753
+ this.planner = getDefaultPlanner();
754
+ this.executor = getDefaultExecutor();
755
+ this.executor.on("step:completed", (step, result) => {
756
+ const state = this.findPlanWithStep(step.id);
757
+ if (state) {
758
+ this.emit("step:completed", result, state.plan);
759
+ }
760
+ });
761
+ this.executor.on("step:failed", (step, error) => {
762
+ const state = this.findPlanWithStep(step.id);
763
+ if (state) {
764
+ this.emit("step:failed", step, error, state.plan);
765
+ }
766
+ });
767
+ this.executor.on("step:retrying", (step, attempt, _delay) => {
768
+ const state = this.findPlanWithStep(step.id);
769
+ if (state) {
770
+ this.emit("step:retrying", step, attempt, state.plan);
771
+ }
772
+ });
773
+ }
774
+ /**
775
+ * Set the agent registry
776
+ */
777
+ setRegistry(registry) {
778
+ this.registry = registry;
779
+ }
780
+ /**
781
+ * Set the action handler for executing agent actions
782
+ */
783
+ setActionHandler(handler) {
784
+ this.actionHandler = handler;
785
+ this.executor.setActionHandler(handler);
786
+ }
787
+ /**
788
+ * Create a new choreography plan
789
+ */
790
+ createPlan(goal, agents, steps) {
791
+ const plan2 = {
792
+ id: this.generateId(),
793
+ goal,
794
+ steps: [...steps],
795
+ participants: [...agents],
796
+ constraints: [],
797
+ status: "draft",
798
+ createdAt: Date.now()
799
+ };
800
+ this.emit("plan:created", plan2);
801
+ return plan2;
802
+ }
803
+ /**
804
+ * Execute a choreography plan
805
+ */
806
+ async execute(plan2, variables = {}) {
807
+ if (!this.actionHandler) {
808
+ throw new Error("No action handler registered. Call setActionHandler first.");
809
+ }
810
+ const validation = this.planner.validate(plan2);
811
+ if (!validation.valid) {
812
+ throw new Error(`Plan validation failed: ${validation.errors.join(", ")}`);
813
+ }
814
+ const executionOrder = this.planner.calculateExecutionOrder(plan2);
815
+ const state = {
816
+ plan: plan2,
817
+ stepResults: /* @__PURE__ */ new Map(),
818
+ stepOutputs: /* @__PURE__ */ new Map(),
819
+ executionOrder,
820
+ currentGroup: 0,
821
+ paused: false,
822
+ cancelled: false,
823
+ hitlPending: /* @__PURE__ */ new Set(),
824
+ startTime: Date.now(),
825
+ variables
826
+ };
827
+ this.activePlans.set(plan2.id, state);
828
+ plan2.status = "running";
829
+ plan2.startedAt = state.startTime;
830
+ this.emit("plan:started", plan2);
831
+ try {
832
+ const result = await this.executePlan(state);
833
+ if (!result.success && plan2.fallback && this.config.executeFallback) {
834
+ this.emit("plan:failed", plan2, new Error(result.error || "Unknown error"));
835
+ const fallbackResult = await this.execute(plan2.fallback, variables);
836
+ return {
837
+ ...fallbackResult,
838
+ usedFallback: true
839
+ };
840
+ }
841
+ plan2.status = result.success ? "completed" : "failed";
842
+ plan2.completedAt = Date.now();
843
+ plan2.duration = plan2.completedAt - (plan2.startedAt || state.startTime);
844
+ this.emit("plan:completed", result);
845
+ return result;
846
+ } catch (error) {
847
+ plan2.status = "failed";
848
+ plan2.completedAt = Date.now();
849
+ plan2.duration = plan2.completedAt - (plan2.startedAt || state.startTime);
850
+ const err = error instanceof Error ? error : new Error(String(error));
851
+ this.emit("plan:failed", plan2, err);
852
+ return {
853
+ planId: plan2.id,
854
+ success: false,
855
+ status: "failed",
856
+ stepResults: Array.from(state.stepResults.values()),
857
+ duration: plan2.duration,
858
+ stepsCompleted: state.stepResults.size,
859
+ stepsFailed: Array.from(state.stepResults.values()).filter((r) => !r.success).length,
860
+ stepsSkipped: 0,
861
+ error: err.message,
862
+ finalOutputs: {}
863
+ };
864
+ } finally {
865
+ this.activePlans.delete(plan2.id);
866
+ }
867
+ }
868
+ /**
869
+ * Pause a running plan
870
+ */
871
+ async pause(planId) {
872
+ const state = this.activePlans.get(planId);
873
+ if (!state) {
874
+ return;
875
+ }
876
+ state.paused = true;
877
+ state.plan.status = "paused";
878
+ this.emit("plan:paused", state.plan);
879
+ }
880
+ /**
881
+ * Resume a paused plan
882
+ */
883
+ async resume(planId) {
884
+ const state = this.activePlans.get(planId);
885
+ if (!state) {
886
+ return;
887
+ }
888
+ if (!state.paused) {
889
+ return;
890
+ }
891
+ state.paused = false;
892
+ state.plan.status = "running";
893
+ this.emit("plan:resumed", state.plan);
894
+ }
895
+ /**
896
+ * Cancel a running plan
897
+ */
898
+ async cancel(planId) {
899
+ const state = this.activePlans.get(planId);
900
+ if (!state) {
901
+ return;
902
+ }
903
+ state.cancelled = true;
904
+ state.plan.status = "cancelled";
905
+ for (const step of state.plan.steps) {
906
+ if (step.status === "running") {
907
+ this.executor.cancel(step.id);
908
+ step.status = "cancelled";
909
+ }
910
+ }
911
+ this.emit("plan:cancelled", state.plan);
912
+ }
913
+ /**
914
+ * Approve a HITL gate
915
+ */
916
+ approveHitl(planId, stepId) {
917
+ const state = this.activePlans.get(planId);
918
+ if (!state) {
919
+ throw new Error(`Plan not found: ${planId}`);
920
+ }
921
+ if (!state.hitlPending.has(stepId)) {
922
+ throw new Error(`Step ${stepId} is not pending HITL approval`);
923
+ }
924
+ state.hitlPending.delete(stepId);
925
+ const step = state.plan.steps.find((s) => s.id === stepId);
926
+ if (step) {
927
+ this.emit("hitl:approved", step, state.plan);
928
+ }
929
+ }
930
+ /**
931
+ * Reject a HITL gate
932
+ */
933
+ rejectHitl(planId, stepId, reason) {
934
+ const state = this.activePlans.get(planId);
935
+ if (!state) {
936
+ throw new Error(`Plan not found: ${planId}`);
937
+ }
938
+ if (!state.hitlPending.has(stepId)) {
939
+ throw new Error(`Step ${stepId} is not pending HITL approval`);
940
+ }
941
+ state.hitlPending.delete(stepId);
942
+ const step = state.plan.steps.find((s) => s.id === stepId);
943
+ if (step) {
944
+ step.status = "failed";
945
+ step.error = `HITL rejected: ${reason}`;
946
+ this.emit("hitl:rejected", step, reason, state.plan);
947
+ }
948
+ }
949
+ /**
950
+ * Get active plan IDs
951
+ */
952
+ getActivePlans() {
953
+ return Array.from(this.activePlans.keys());
954
+ }
955
+ /**
956
+ * Get plan status
957
+ */
958
+ getPlanStatus(planId) {
959
+ const state = this.activePlans.get(planId);
960
+ return state?.plan.status || null;
961
+ }
962
+ // ==========================================================================
963
+ // PRIVATE METHODS
964
+ // ==========================================================================
965
+ /**
966
+ * Execute the plan
967
+ */
968
+ async executePlan(state) {
969
+ const { plan: _plan, executionOrder } = state;
970
+ for (const group of executionOrder.parallelGroups) {
971
+ while (state.paused && !state.cancelled) {
972
+ await this.sleep(100);
973
+ }
974
+ if (state.cancelled) {
975
+ break;
976
+ }
977
+ await this.executeGroup(state, group);
978
+ const failed = group.some((stepId) => {
979
+ const result = state.stepResults.get(stepId);
980
+ return result && !result.success;
981
+ });
982
+ if (failed) {
983
+ break;
984
+ }
985
+ state.currentGroup++;
986
+ }
987
+ return this.buildResult(state);
988
+ }
989
+ /**
990
+ * Execute a group of steps (potentially in parallel)
991
+ */
992
+ async executeGroup(state, stepIds) {
993
+ const steps = stepIds.map((id) => state.plan.steps.find((s) => s.id === id)).filter((s) => s !== void 0);
994
+ const concurrency = this.getConcurrencyLimit(state.plan);
995
+ const batches = this.chunk(steps, concurrency);
996
+ for (const batch of batches) {
997
+ if (state.cancelled) break;
998
+ const promises = batch.map((step) => this.executeStep(state, step));
999
+ await Promise.all(promises);
1000
+ }
1001
+ }
1002
+ /**
1003
+ * Execute a single step
1004
+ */
1005
+ async executeStep(state, step) {
1006
+ if (step.hitlGate && this.config.autoHitlPause) {
1007
+ state.hitlPending.add(step.id);
1008
+ this.emit("hitl:required", step, state.plan);
1009
+ while (state.hitlPending.has(step.id) && !state.cancelled) {
1010
+ await this.sleep(100);
1011
+ }
1012
+ if (state.cancelled) {
1013
+ step.status = "cancelled";
1014
+ return;
1015
+ }
1016
+ if (step.status === "failed") {
1017
+ state.stepResults.set(step.id, {
1018
+ stepId: step.id,
1019
+ success: false,
1020
+ outputs: {},
1021
+ duration: 0,
1022
+ error: step.error
1023
+ });
1024
+ return;
1025
+ }
1026
+ }
1027
+ const context = this.buildStepContext(state, step);
1028
+ this.emit("step:started", step, state.plan);
1029
+ const result = await this.executor.execute(step, context);
1030
+ if (!result.success && step.fallbackStepId && this.config.executeFallback) {
1031
+ const fallbackStep = state.plan.steps.find(
1032
+ (s) => s.id === step.fallbackStepId || s.name === step.fallbackStepId
1033
+ );
1034
+ if (fallbackStep) {
1035
+ let fallbackResult = state.stepResults.get(fallbackStep.id);
1036
+ if (!fallbackResult && fallbackStep.status === "running") {
1037
+ while (!state.stepResults.has(fallbackStep.id) && !state.cancelled) {
1038
+ await this.sleep(50);
1039
+ }
1040
+ fallbackResult = state.stepResults.get(fallbackStep.id);
1041
+ }
1042
+ if (!fallbackResult && fallbackStep.status === "pending") {
1043
+ await this.executeStep(state, fallbackStep);
1044
+ fallbackResult = state.stepResults.get(fallbackStep.id);
1045
+ }
1046
+ if (fallbackResult?.success) {
1047
+ state.stepResults.set(step.id, {
1048
+ stepId: step.id,
1049
+ success: true,
1050
+ outputs: fallbackResult.outputs,
1051
+ duration: result.duration,
1052
+ usedFallback: true
1053
+ });
1054
+ state.stepOutputs.set(step.id, fallbackResult.outputs);
1055
+ return;
1056
+ }
1057
+ }
1058
+ }
1059
+ state.stepResults.set(step.id, result);
1060
+ if (result.success) {
1061
+ state.stepOutputs.set(step.id, result.outputs);
1062
+ }
1063
+ }
1064
+ /**
1065
+ * Build step context
1066
+ */
1067
+ buildStepContext(state, step) {
1068
+ const agents = new Map(state.plan.participants.map((a) => [a.id, a]));
1069
+ return {
1070
+ plan: state.plan,
1071
+ currentStep: step,
1072
+ agents,
1073
+ stepOutputs: state.stepOutputs,
1074
+ variables: state.variables,
1075
+ startTime: state.startTime,
1076
+ elapsedTime: Date.now() - state.startTime
1077
+ };
1078
+ }
1079
+ /**
1080
+ * Build final result
1081
+ */
1082
+ buildResult(state) {
1083
+ const stepResults = Array.from(state.stepResults.values());
1084
+ const completed = stepResults.filter((r) => r.success).length;
1085
+ const failed = stepResults.filter((r) => !r.success).length;
1086
+ const skipped = state.plan.steps.length - stepResults.length;
1087
+ const completedSteps = state.plan.steps.filter((step) => {
1088
+ const result = state.stepResults.get(step.id);
1089
+ return result?.success;
1090
+ });
1091
+ const failedSteps = state.plan.steps.filter((step) => {
1092
+ const result = state.stepResults.get(step.id);
1093
+ return result && !result.success;
1094
+ });
1095
+ const terminalSteps = state.plan.steps.filter(
1096
+ (s) => !state.plan.steps.some((other) => other.dependencies.includes(s.id))
1097
+ );
1098
+ const finalOutputs = {};
1099
+ for (const step of terminalSteps) {
1100
+ const outputs = state.stepOutputs.get(step.id);
1101
+ if (outputs) {
1102
+ Object.assign(finalOutputs, outputs);
1103
+ }
1104
+ }
1105
+ const success = !state.cancelled && failed === 0 && skipped === 0;
1106
+ return {
1107
+ planId: state.plan.id,
1108
+ success,
1109
+ status: state.cancelled ? "cancelled" : success ? "completed" : "failed",
1110
+ stepResults,
1111
+ duration: Date.now() - state.startTime,
1112
+ stepsCompleted: completed,
1113
+ stepsFailed: failed,
1114
+ stepsSkipped: skipped,
1115
+ completedSteps,
1116
+ failedSteps,
1117
+ error: failed > 0 ? `${failed} step(s) failed` : void 0,
1118
+ finalOutputs,
1119
+ metrics: {
1120
+ peakConcurrency: this.getConcurrencyLimit(state.plan)
1121
+ }
1122
+ };
1123
+ }
1124
+ /**
1125
+ * Get concurrency limit from constraints
1126
+ */
1127
+ getConcurrencyLimit(plan2) {
1128
+ const constraint = plan2.constraints.find((c) => c.type === "concurrency");
1129
+ if (constraint && typeof constraint.value === "number") {
1130
+ return constraint.value;
1131
+ }
1132
+ return this.config.maxConcurrency;
1133
+ }
1134
+ /**
1135
+ * Find plan containing a step
1136
+ */
1137
+ findPlanWithStep(stepId) {
1138
+ for (const state of this.activePlans.values()) {
1139
+ if (state.plan.steps.some((s) => s.id === stepId)) {
1140
+ return state;
1141
+ }
1142
+ }
1143
+ return void 0;
1144
+ }
1145
+ /**
1146
+ * Generate unique ID
1147
+ */
1148
+ generateId() {
1149
+ return `plan_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`;
1150
+ }
1151
+ /**
1152
+ * Chunk array into batches
1153
+ */
1154
+ chunk(array, size) {
1155
+ const chunks = [];
1156
+ for (let i = 0; i < array.length; i += size) {
1157
+ chunks.push(array.slice(i, i + size));
1158
+ }
1159
+ return chunks;
1160
+ }
1161
+ /**
1162
+ * Sleep helper
1163
+ */
1164
+ sleep(ms) {
1165
+ return new Promise((resolve) => setTimeout(resolve, ms));
1166
+ }
1167
+ };
1168
+ var defaultEngine = null;
1169
+ function getDefaultEngine() {
1170
+ if (!defaultEngine) {
1171
+ defaultEngine = new ChoreographyEngine();
1172
+ }
1173
+ return defaultEngine;
1174
+ }
1175
+ function resetDefaultEngine() {
1176
+ defaultEngine = null;
1177
+ }
1178
+ // Annotate the CommonJS export names for ESM import in node:
1179
+ 0 && (module.exports = {
1180
+ ChoreographyEngine,
1181
+ ChoreographyPlanner,
1182
+ Constraints,
1183
+ DEFAULT_ENGINE_CONFIG,
1184
+ DEFAULT_EXECUTOR_CONFIG,
1185
+ DEFAULT_RETRY_CONFIG,
1186
+ PlanBuilder,
1187
+ StepExecutor,
1188
+ getDefaultEngine,
1189
+ getDefaultExecutor,
1190
+ getDefaultPlanner,
1191
+ plan,
1192
+ resetDefaultEngine,
1193
+ resetDefaultExecutor
1194
+ });