yaml-flow 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +705 -225
  2. package/dist/batch/index.cjs +109 -0
  3. package/dist/batch/index.cjs.map +1 -0
  4. package/dist/batch/index.d.cts +126 -0
  5. package/dist/batch/index.d.ts +126 -0
  6. package/dist/batch/index.js +107 -0
  7. package/dist/batch/index.js.map +1 -0
  8. package/dist/config/index.cjs +80 -0
  9. package/dist/config/index.cjs.map +1 -0
  10. package/dist/config/index.d.cts +71 -0
  11. package/dist/config/index.d.ts +71 -0
  12. package/dist/config/index.js +77 -0
  13. package/dist/config/index.js.map +1 -0
  14. package/dist/constants-D1fTEbbM.d.cts +330 -0
  15. package/dist/constants-D1fTEbbM.d.ts +330 -0
  16. package/dist/event-graph/index.cjs +895 -0
  17. package/dist/event-graph/index.cjs.map +1 -0
  18. package/dist/event-graph/index.d.cts +53 -0
  19. package/dist/event-graph/index.d.ts +53 -0
  20. package/dist/event-graph/index.js +855 -0
  21. package/dist/event-graph/index.js.map +1 -0
  22. package/dist/index.cjs +1309 -312
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +5 -2
  25. package/dist/index.d.ts +5 -2
  26. package/dist/index.js +1271 -306
  27. package/dist/index.js.map +1 -1
  28. package/dist/step-machine/index.cjs +513 -0
  29. package/dist/step-machine/index.cjs.map +1 -0
  30. package/dist/step-machine/index.d.cts +77 -0
  31. package/dist/step-machine/index.d.ts +77 -0
  32. package/dist/step-machine/index.js +502 -0
  33. package/dist/step-machine/index.js.map +1 -0
  34. package/dist/stores/file.cjs.map +1 -1
  35. package/dist/stores/file.d.cts +4 -4
  36. package/dist/stores/file.d.ts +4 -4
  37. package/dist/stores/file.js.map +1 -1
  38. package/dist/stores/index.cjs +232 -0
  39. package/dist/stores/index.cjs.map +1 -0
  40. package/dist/stores/index.d.cts +4 -0
  41. package/dist/stores/index.d.ts +4 -0
  42. package/dist/stores/index.js +228 -0
  43. package/dist/stores/index.js.map +1 -0
  44. package/dist/stores/localStorage.cjs.map +1 -1
  45. package/dist/stores/localStorage.d.cts +4 -4
  46. package/dist/stores/localStorage.d.ts +4 -4
  47. package/dist/stores/localStorage.js.map +1 -1
  48. package/dist/stores/memory.cjs.map +1 -1
  49. package/dist/stores/memory.d.cts +4 -4
  50. package/dist/stores/memory.d.ts +4 -4
  51. package/dist/stores/memory.js.map +1 -1
  52. package/dist/types-FZ_eyErS.d.cts +115 -0
  53. package/dist/types-FZ_eyErS.d.ts +115 -0
  54. package/package.json +26 -6
  55. package/dist/core/index.cjs +0 -557
  56. package/dist/core/index.cjs.map +0 -1
  57. package/dist/core/index.d.cts +0 -102
  58. package/dist/core/index.d.ts +0 -102
  59. package/dist/core/index.js +0 -549
  60. package/dist/core/index.js.map +0 -1
  61. package/dist/types-BoWndaAJ.d.cts +0 -237
  62. package/dist/types-BoWndaAJ.d.ts +0 -237
@@ -0,0 +1,855 @@
1
+ // src/event-graph/constants.ts
2
+ var TASK_STATUS = {
3
+ NOT_STARTED: "not-started",
4
+ RUNNING: "running",
5
+ COMPLETED: "completed",
6
+ FAILED: "failed",
7
+ INACTIVATED: "inactivated"
8
+ };
9
+ var EXECUTION_STATUS = {
10
+ CREATED: "created",
11
+ RUNNING: "running",
12
+ PAUSED: "paused",
13
+ STOPPED: "stopped",
14
+ COMPLETED: "completed",
15
+ FAILED: "failed"
16
+ };
17
+ var COMPLETION_STRATEGIES = {
18
+ ALL_TASKS_DONE: "all-tasks-done",
19
+ ALL_OUTPUTS_DONE: "all-outputs-done",
20
+ ONLY_RESOLVED: "only-resolved",
21
+ GOAL_REACHED: "goal-reached",
22
+ MANUAL: "manual"
23
+ };
24
+ var EXECUTION_MODES = {
25
+ DEPENDENCY_MODE: "dependency-mode",
26
+ ELIGIBILITY_MODE: "eligibility-mode"
27
+ };
28
+ var CONFLICT_STRATEGIES = {
29
+ ALPHABETICAL: "alphabetical",
30
+ PRIORITY_FIRST: "priority-first",
31
+ DURATION_FIRST: "duration-first",
32
+ COST_OPTIMIZED: "cost-optimized",
33
+ RESOURCE_AWARE: "resource-aware",
34
+ RANDOM_SELECT: "random-select",
35
+ USER_CHOICE: "user-choice",
36
+ PARALLEL_ALL: "parallel-all",
37
+ SKIP_CONFLICTS: "skip-conflicts",
38
+ ROUND_ROBIN: "round-robin"
39
+ };
40
+ var DEFAULTS = {
41
+ EXECUTION_MODE: "eligibility-mode",
42
+ CONFLICT_STRATEGY: "alphabetical",
43
+ COMPLETION_STRATEGY: "all-outputs-done",
44
+ MAX_ITERATIONS: 1e3
45
+ };
46
+
47
+ // src/event-graph/graph-helpers.ts
48
+ function getProvides(task) {
49
+ if (!task) return [];
50
+ if (Array.isArray(task.provides)) return task.provides;
51
+ return [];
52
+ }
53
+ function getRequires(task) {
54
+ if (!task) return [];
55
+ if (Array.isArray(task.requires)) return task.requires;
56
+ return [];
57
+ }
58
+ function getAllTasks(graph) {
59
+ return graph.tasks ?? {};
60
+ }
61
+ function getTask(graph, taskName) {
62
+ return graph.tasks[taskName];
63
+ }
64
+ function hasTask(graph, taskName) {
65
+ return taskName in graph.tasks;
66
+ }
67
+ function isNonActiveTask(taskState) {
68
+ if (!taskState) return false;
69
+ return taskState.status === TASK_STATUS.FAILED || taskState.status === TASK_STATUS.INACTIVATED;
70
+ }
71
+ function isTaskCompleted(taskState) {
72
+ return taskState?.status === TASK_STATUS.COMPLETED;
73
+ }
74
+ function isTaskRunning(taskState) {
75
+ return taskState?.status === TASK_STATUS.RUNNING;
76
+ }
77
+ function isRepeatableTask(taskConfig) {
78
+ return taskConfig.repeatable === true || typeof taskConfig.repeatable === "object" && taskConfig.repeatable !== null;
79
+ }
80
+ function getRepeatableMax(taskConfig) {
81
+ if (taskConfig.repeatable === true) return void 0;
82
+ if (typeof taskConfig.repeatable === "object" && taskConfig.repeatable !== null) {
83
+ return taskConfig.repeatable.max;
84
+ }
85
+ return void 0;
86
+ }
87
+ function computeAvailableOutputs(graph, taskStates) {
88
+ const outputs = /* @__PURE__ */ new Set();
89
+ for (const [taskName, taskState] of Object.entries(taskStates)) {
90
+ if (taskState.status === TASK_STATUS.COMPLETED) {
91
+ const taskConfig = graph.tasks[taskName];
92
+ if (taskConfig) {
93
+ const provides = getProvides(taskConfig);
94
+ provides.forEach((output) => outputs.add(output));
95
+ }
96
+ }
97
+ }
98
+ return Array.from(outputs);
99
+ }
100
+ function groupTasksByProvides(candidateTaskNames, tasks) {
101
+ const outputGroups = {};
102
+ candidateTaskNames.forEach((taskName) => {
103
+ const task = tasks[taskName];
104
+ if (!task) return;
105
+ const provides = getProvides(task);
106
+ provides.forEach((output) => {
107
+ if (!outputGroups[output]) {
108
+ outputGroups[output] = [];
109
+ }
110
+ outputGroups[output].push(taskName);
111
+ });
112
+ });
113
+ return outputGroups;
114
+ }
115
+ function hasOutputConflict(taskName, taskProvides, candidates, tasks) {
116
+ for (const otherName of candidates) {
117
+ if (otherName === taskName) continue;
118
+ const otherProvides = getProvides(tasks[otherName]);
119
+ const overlapping = taskProvides.some((output) => otherProvides.includes(output));
120
+ if (overlapping) return true;
121
+ }
122
+ return false;
123
+ }
124
+ function addKeyToProvides(task, key) {
125
+ const current = getProvides(task);
126
+ if (current.includes(key)) return task;
127
+ return { ...task, provides: [...current, key] };
128
+ }
129
+ function removeKeyFromProvides(task, key) {
130
+ const current = getProvides(task);
131
+ return { ...task, provides: current.filter((p) => p !== key) };
132
+ }
133
+ function addKeyToRequires(task, key) {
134
+ const current = getRequires(task);
135
+ if (current.includes(key)) return task;
136
+ return { ...task, requires: [...current, key] };
137
+ }
138
+ function removeKeyFromRequires(task, key) {
139
+ const current = getRequires(task);
140
+ return { ...task, requires: current.filter((r) => r !== key) };
141
+ }
142
+ function addDynamicTask(graph, taskName, taskConfig) {
143
+ return {
144
+ ...graph,
145
+ tasks: {
146
+ ...graph.tasks,
147
+ [taskName]: taskConfig
148
+ }
149
+ };
150
+ }
151
+ function createDefaultTaskState() {
152
+ return {
153
+ status: "not-started",
154
+ executionCount: 0,
155
+ retryCount: 0,
156
+ lastEpoch: 0,
157
+ messages: [],
158
+ progress: null
159
+ };
160
+ }
161
+ function createInitialExecutionState(graph, executionId) {
162
+ const tasks = {};
163
+ for (const taskName of Object.keys(graph.tasks)) {
164
+ tasks[taskName] = createDefaultTaskState();
165
+ }
166
+ return {
167
+ status: "running",
168
+ tasks,
169
+ availableOutputs: [],
170
+ stuckDetection: { is_stuck: false, stuck_description: null, outputs_unresolvable: [], tasks_blocked: [] },
171
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
172
+ executionId,
173
+ executionConfig: {
174
+ executionMode: graph.settings.execution_mode ?? "eligibility-mode",
175
+ conflictStrategy: graph.settings.conflict_strategy ?? "alphabetical",
176
+ completionStrategy: graph.settings.completion
177
+ }
178
+ };
179
+ }
180
+
181
+ // src/event-graph/conflict-resolution.ts
182
+ function selectBestAlternative(alternatives, graphTasks, _executionState, strategy) {
183
+ switch (strategy) {
184
+ case "alphabetical":
185
+ return selectByAlphabetical(alternatives);
186
+ case "priority-first":
187
+ return selectByPriorityFirst(alternatives, graphTasks);
188
+ case "duration-first":
189
+ return selectByDurationFirst(alternatives, graphTasks);
190
+ case "cost-optimized":
191
+ return selectByCostOptimized(alternatives, graphTasks);
192
+ case "resource-aware":
193
+ return selectByResourceAware(alternatives, graphTasks);
194
+ case "round-robin":
195
+ return selectByRoundRobin(alternatives, _executionState);
196
+ default:
197
+ return selectByAlphabetical(alternatives);
198
+ }
199
+ }
200
+ function selectByAlphabetical(alternatives) {
201
+ return [...alternatives].sort((a, b) => a.localeCompare(b))[0];
202
+ }
203
+ function selectByPriorityFirst(alternatives, graphTasks) {
204
+ return [...alternatives].sort((a, b) => {
205
+ const pA = graphTasks[a]?.priority ?? 0;
206
+ const pB = graphTasks[b]?.priority ?? 0;
207
+ if (pA !== pB) return pB - pA;
208
+ const dA = getEstimatedDuration(graphTasks[a]);
209
+ const dB = getEstimatedDuration(graphTasks[b]);
210
+ if (dA !== dB) return dA - dB;
211
+ return a.localeCompare(b);
212
+ })[0];
213
+ }
214
+ function selectByDurationFirst(alternatives, graphTasks) {
215
+ return [...alternatives].sort((a, b) => {
216
+ const dA = getEstimatedDuration(graphTasks[a]);
217
+ const dB = getEstimatedDuration(graphTasks[b]);
218
+ if (dA !== dB) return dA - dB;
219
+ const pA = graphTasks[a]?.priority ?? 0;
220
+ const pB = graphTasks[b]?.priority ?? 0;
221
+ if (pA !== pB) return pB - pA;
222
+ return a.localeCompare(b);
223
+ })[0];
224
+ }
225
+ function selectByCostOptimized(alternatives, graphTasks) {
226
+ return [...alternatives].sort((a, b) => {
227
+ const cA = graphTasks[a]?.estimatedCost ?? 0;
228
+ const cB = graphTasks[b]?.estimatedCost ?? 0;
229
+ if (cA !== cB) return cA - cB;
230
+ const pA = graphTasks[a]?.priority ?? 0;
231
+ const pB = graphTasks[b]?.priority ?? 0;
232
+ if (pA !== pB) return pB - pA;
233
+ return a.localeCompare(b);
234
+ })[0];
235
+ }
236
+ function selectByResourceAware(alternatives, graphTasks) {
237
+ return [...alternatives].sort((a, b) => {
238
+ const rA = graphTasks[a]?.estimatedResources?.cpu ?? 1;
239
+ const rB = graphTasks[b]?.estimatedResources?.cpu ?? 1;
240
+ if (rA !== rB) return rA - rB;
241
+ const pA = graphTasks[a]?.priority ?? 0;
242
+ const pB = graphTasks[b]?.priority ?? 0;
243
+ if (pA !== pB) return pB - pA;
244
+ return a.localeCompare(b);
245
+ })[0];
246
+ }
247
+ function selectByRoundRobin(alternatives, executionState) {
248
+ const totalExecs = Object.values(executionState.tasks).reduce((sum, t) => sum + t.executionCount, 0);
249
+ const sorted = [...alternatives].sort();
250
+ return sorted[totalExecs % sorted.length];
251
+ }
252
+ function getEstimatedDuration(taskConfig) {
253
+ return taskConfig?.estimatedDuration ?? Infinity;
254
+ }
255
+ function getNonConflictingTasks(candidates, graphTasks) {
256
+ return candidates.filter((taskName) => {
257
+ const provides = getProvides(graphTasks[taskName]);
258
+ return !hasOutputConflict(taskName, provides, candidates, graphTasks);
259
+ });
260
+ }
261
+ function selectRandomTasks(candidates, graphTasks) {
262
+ const outputGroups = groupTasksByProvides(candidates, graphTasks);
263
+ const selected = [];
264
+ for (const groupTasks of Object.values(outputGroups)) {
265
+ if (groupTasks.length === 1) {
266
+ selected.push(...groupTasks);
267
+ } else {
268
+ const idx = Math.floor(Math.random() * groupTasks.length);
269
+ selected.push(groupTasks[idx]);
270
+ }
271
+ }
272
+ const nonConflicting = getNonConflictingTasks(candidates, graphTasks);
273
+ nonConflicting.forEach((t) => {
274
+ if (!selected.includes(t)) selected.push(t);
275
+ });
276
+ return selected;
277
+ }
278
+
279
+ // src/event-graph/completion.ts
280
+ function isExecutionComplete(graph, state) {
281
+ const strategy = state.executionConfig.completionStrategy;
282
+ switch (strategy) {
283
+ case "all-tasks-done":
284
+ return checkAllTasksDone(graph, state);
285
+ case "all-outputs-done":
286
+ return checkAllOutputsDone(graph, state);
287
+ case "only-resolved":
288
+ return checkOnlyResolved(graph, state);
289
+ case "goal-reached":
290
+ return checkGoalReached(graph, state);
291
+ case "manual":
292
+ return { isComplete: false, expectedCompletion: { taskNames: [], outputs: [] } };
293
+ default:
294
+ return checkAllOutputsDone(graph, state);
295
+ }
296
+ }
297
+ function checkAllTasksDone(graph, state) {
298
+ const graphTasks = getAllTasks(graph);
299
+ const allTaskNames = Object.keys(graphTasks);
300
+ if (allTaskNames.length === 0) {
301
+ return { isComplete: true, expectedCompletion: { taskNames: [], outputs: [] } };
302
+ }
303
+ const allDone = allTaskNames.every((taskName) => {
304
+ const taskState = state.tasks[taskName];
305
+ return taskState?.status === TASK_STATUS.COMPLETED || isNonActiveTask(taskState);
306
+ });
307
+ return {
308
+ isComplete: allDone,
309
+ expectedCompletion: { taskNames: allTaskNames, outputs: [] }
310
+ };
311
+ }
312
+ function checkAllOutputsDone(graph, state) {
313
+ const graphTasks = getAllTasks(graph);
314
+ const allPossibleOutputs = /* @__PURE__ */ new Set();
315
+ for (const taskConfig of Object.values(graphTasks)) {
316
+ getProvides(taskConfig).forEach((output) => allPossibleOutputs.add(output));
317
+ }
318
+ const availableOutputs = computeAvailableOutputs(graph, state.tasks);
319
+ const allProduced = [...allPossibleOutputs].every((output) => availableOutputs.includes(output));
320
+ return {
321
+ isComplete: allProduced,
322
+ expectedCompletion: { taskNames: [], outputs: [...allPossibleOutputs] }
323
+ };
324
+ }
325
+ function checkOnlyResolved(graph, state) {
326
+ const graphTasks = getAllTasks(graph);
327
+ const availableOutputs = computeAvailableOutputs(graph, state.tasks);
328
+ const allPossibleOutputs = /* @__PURE__ */ new Set();
329
+ const tasksByOutput = {};
330
+ for (const [taskName, taskConfig] of Object.entries(graphTasks)) {
331
+ const provides = getProvides(taskConfig);
332
+ provides.forEach((output) => {
333
+ allPossibleOutputs.add(output);
334
+ if (!tasksByOutput[output]) tasksByOutput[output] = [];
335
+ tasksByOutput[output].push(taskName);
336
+ });
337
+ }
338
+ for (const output of allPossibleOutputs) {
339
+ if (availableOutputs.includes(output)) continue;
340
+ const producers = tasksByOutput[output] ?? [];
341
+ const canStillProduce = producers.some((taskName) => {
342
+ const taskState = state.tasks[taskName];
343
+ if (taskState?.status === TASK_STATUS.COMPLETED || isNonActiveTask(taskState)) {
344
+ return false;
345
+ }
346
+ const taskConfig = graphTasks[taskName];
347
+ const requires = getRequires(taskConfig);
348
+ return requires.every((req) => availableOutputs.includes(req));
349
+ });
350
+ if (canStillProduce) {
351
+ return { isComplete: false, expectedCompletion: { taskNames: [], outputs: [] } };
352
+ }
353
+ }
354
+ const eligibleTasks = getEligibleCandidates(graph, state);
355
+ if (eligibleTasks.length > 0) {
356
+ return { isComplete: false, expectedCompletion: { taskNames: eligibleTasks, outputs: [] } };
357
+ }
358
+ const completedCount = Object.values(state.tasks).filter((t) => t.status === TASK_STATUS.COMPLETED).length;
359
+ return {
360
+ isComplete: completedCount > 0 || availableOutputs.length > 0,
361
+ expectedCompletion: { taskNames: [], outputs: [] }
362
+ };
363
+ }
364
+ function checkGoalReached(graph, state) {
365
+ const goal = graph.settings.goal ?? [];
366
+ if (goal.length === 0) {
367
+ return checkAllOutputsDone(graph, state);
368
+ }
369
+ const availableOutputs = computeAvailableOutputs(graph, state.tasks);
370
+ const goalReached = goal.every((output) => availableOutputs.includes(output));
371
+ return {
372
+ isComplete: goalReached,
373
+ expectedCompletion: { taskNames: [], outputs: goal }
374
+ };
375
+ }
376
+ function getEligibleCandidates(graph, state) {
377
+ const graphTasks = getAllTasks(graph);
378
+ const availableOutputs = computeAvailableOutputs(graph, state.tasks);
379
+ const candidates = [];
380
+ for (const [taskName, taskConfig] of Object.entries(graphTasks)) {
381
+ const taskState = state.tasks[taskName];
382
+ if (taskState?.status === TASK_STATUS.COMPLETED || taskState?.status === TASK_STATUS.RUNNING || isNonActiveTask(taskState)) {
383
+ continue;
384
+ }
385
+ const requires = getRequires(taskConfig);
386
+ if (requires.every((req) => availableOutputs.includes(req))) {
387
+ const provides = getProvides(taskConfig);
388
+ const allAlreadyAvailable = provides.length > 0 && provides.every((output) => availableOutputs.includes(output));
389
+ if (!allAlreadyAvailable) {
390
+ candidates.push(taskName);
391
+ }
392
+ }
393
+ }
394
+ return candidates;
395
+ }
396
+
397
+ // src/event-graph/stuck-detection.ts
398
+ function detectStuckState(params) {
399
+ const { graph, state, eligibleTasks, completionResult } = params;
400
+ const tasks = state.tasks;
401
+ const graphTasks = getAllTasks(graph);
402
+ const availableOutputs = computeAvailableOutputs(graph, tasks);
403
+ if (eligibleTasks.length > 0) {
404
+ return { is_stuck: false, stuck_description: null, outputs_unresolvable: [], tasks_blocked: [] };
405
+ }
406
+ const hasRunningTasks = Object.values(tasks).some((t) => t.status === TASK_STATUS.RUNNING);
407
+ if (hasRunningTasks) {
408
+ return { is_stuck: false, stuck_description: null, outputs_unresolvable: [], tasks_blocked: [] };
409
+ }
410
+ if (completionResult?.expectedCompletion) {
411
+ const { taskNames = [], outputs = [] } = completionResult.expectedCompletion;
412
+ if (taskNames.length > 0) {
413
+ const expectedFailed = taskNames.filter((tn) => isNonActiveTask(tasks[tn]));
414
+ if (expectedFailed.length > 0 && expectedFailed.length === taskNames.length) {
415
+ return {
416
+ is_stuck: true,
417
+ stuck_description: `Completion expects tasks ${taskNames.join(", ")} but all are failed`,
418
+ tasks_blocked: expectedFailed,
419
+ outputs_unresolvable: outputs
420
+ };
421
+ }
422
+ }
423
+ if (outputs.length > 0 && state.executionConfig.completionStrategy !== "only-resolved") {
424
+ const missingOutputs2 = outputs.filter((o) => !availableOutputs.includes(o));
425
+ if (missingOutputs2.length > 0) {
426
+ const unprovidable = [];
427
+ for (const output of missingOutputs2) {
428
+ const providers = Object.entries(graphTasks).filter(([, config]) => getProvides(config).includes(output)).map(([name]) => name);
429
+ const viable = providers.filter((p) => !isNonActiveTask(tasks[p]));
430
+ if (viable.length === 0) {
431
+ unprovidable.push(output);
432
+ }
433
+ }
434
+ if (unprovidable.length > 0) {
435
+ return {
436
+ is_stuck: true,
437
+ stuck_description: `Completion expects outputs '${unprovidable.join("', '")}' but no viable tasks can provide them`,
438
+ tasks_blocked: [],
439
+ outputs_unresolvable: unprovidable
440
+ };
441
+ }
442
+ }
443
+ }
444
+ }
445
+ const blockedTasks = [];
446
+ const missingOutputs = /* @__PURE__ */ new Set();
447
+ for (const [taskName, taskConfig] of Object.entries(graphTasks)) {
448
+ const taskState = tasks[taskName];
449
+ if (taskState?.status === TASK_STATUS.COMPLETED || isNonActiveTask(taskState) || taskState?.status === TASK_STATUS.RUNNING) {
450
+ continue;
451
+ }
452
+ const requires = getRequires(taskConfig);
453
+ const unmet = requires.filter((req) => !availableOutputs.includes(req));
454
+ if (unmet.length > 0) {
455
+ const canBeProvided = unmet.every((req) => {
456
+ const providers = Object.entries(graphTasks).filter(([, config]) => getProvides(config).includes(req)).map(([name]) => name);
457
+ return providers.some((p) => !isNonActiveTask(tasks[p]) && tasks[p]?.status !== TASK_STATUS.COMPLETED);
458
+ });
459
+ if (!canBeProvided) {
460
+ blockedTasks.push(taskName);
461
+ unmet.forEach((u) => missingOutputs.add(u));
462
+ }
463
+ }
464
+ }
465
+ if (blockedTasks.length > 0) {
466
+ return {
467
+ is_stuck: true,
468
+ stuck_description: `Tasks [${blockedTasks.join(", ")}] blocked by unresolvable dependencies: ${[...missingOutputs].join(", ")}`,
469
+ tasks_blocked: blockedTasks,
470
+ outputs_unresolvable: [...missingOutputs]
471
+ };
472
+ }
473
+ return { is_stuck: false, stuck_description: null, outputs_unresolvable: [], tasks_blocked: [] };
474
+ }
475
+
476
+ // src/event-graph/scheduler.ts
477
+ function next(graph, state) {
478
+ const processingLog = [];
479
+ const graphTasks = getAllTasks(graph);
480
+ if (Object.keys(graphTasks).length === 0) {
481
+ return {
482
+ eligibleTasks: [],
483
+ isComplete: true,
484
+ stuckDetection: { is_stuck: false, stuck_description: null, outputs_unresolvable: [], tasks_blocked: [] },
485
+ hasConflicts: false,
486
+ conflicts: {},
487
+ strategy: state.executionConfig.conflictStrategy,
488
+ processingLog: ["No tasks defined"]
489
+ };
490
+ }
491
+ const mode = state.executionConfig.executionMode;
492
+ const conflictStrategy = state.executionConfig.conflictStrategy;
493
+ const candidates = getCandidateTasks(graph, state);
494
+ processingLog.push(`Found ${candidates.length} candidate tasks: ${candidates.join(", ") || "none"}`);
495
+ let eligible;
496
+ let hasConflicts = false;
497
+ let conflicts = {};
498
+ if (mode === "dependency-mode") {
499
+ eligible = candidates;
500
+ } else {
501
+ const selection = selectOptimalTasks(candidates, graph, state, conflictStrategy);
502
+ eligible = selection.eligibleTasks;
503
+ hasConflicts = selection.hasConflicts;
504
+ conflicts = selection.conflicts;
505
+ }
506
+ processingLog.push(`Eligible after conflict resolution: ${eligible.join(", ") || "none"}`);
507
+ const completionResult = isExecutionComplete(graph, state);
508
+ processingLog.push(`Execution complete: ${completionResult.isComplete}`);
509
+ const stuckDetection = detectStuckState({
510
+ graph,
511
+ state,
512
+ eligibleTasks: eligible,
513
+ completionResult
514
+ });
515
+ if (stuckDetection.is_stuck) {
516
+ processingLog.push(`STUCK: ${stuckDetection.stuck_description}`);
517
+ }
518
+ return {
519
+ eligibleTasks: eligible,
520
+ isComplete: completionResult.isComplete,
521
+ stuckDetection,
522
+ hasConflicts,
523
+ conflicts,
524
+ strategy: conflictStrategy,
525
+ processingLog
526
+ };
527
+ }
528
+ function getCandidateTasks(graph, state) {
529
+ const graphTasks = getAllTasks(graph);
530
+ const computedOutputs = computeAvailableOutputs(graph, state.tasks);
531
+ const availableOutputs = [.../* @__PURE__ */ new Set([...computedOutputs, ...state.availableOutputs])];
532
+ const candidates = [];
533
+ for (const [taskName, taskConfig] of Object.entries(graphTasks)) {
534
+ const taskState = state.tasks[taskName];
535
+ if (!isRepeatableTask(taskConfig)) {
536
+ if (taskState?.status === TASK_STATUS.COMPLETED || taskState?.status === TASK_STATUS.RUNNING || isNonActiveTask(taskState)) {
537
+ continue;
538
+ }
539
+ } else {
540
+ if (taskState?.status === TASK_STATUS.RUNNING || isNonActiveTask(taskState)) {
541
+ continue;
542
+ }
543
+ const maxExec = getRepeatableMax(taskConfig);
544
+ if (maxExec !== void 0 && taskState && taskState.executionCount >= maxExec) {
545
+ continue;
546
+ }
547
+ if (taskConfig.circuit_breaker) {
548
+ if (taskState && taskState.executionCount >= taskConfig.circuit_breaker.max_executions) {
549
+ continue;
550
+ }
551
+ }
552
+ if (taskState?.status === TASK_STATUS.COMPLETED) {
553
+ const requires2 = getRequires(taskConfig);
554
+ if (requires2.length > 0) {
555
+ const hasRefreshedInputs = requires2.some((req) => {
556
+ for (const [otherName, otherConfig] of Object.entries(graphTasks)) {
557
+ if (getProvides(otherConfig).includes(req)) {
558
+ const otherState = state.tasks[otherName];
559
+ if (otherState && otherState.executionCount > taskState.lastEpoch) {
560
+ return true;
561
+ }
562
+ }
563
+ }
564
+ return false;
565
+ });
566
+ if (!hasRefreshedInputs) continue;
567
+ } else {
568
+ continue;
569
+ }
570
+ }
571
+ }
572
+ const requires = getRequires(taskConfig);
573
+ if (!requires.every((req) => availableOutputs.includes(req))) {
574
+ continue;
575
+ }
576
+ if (!isRepeatableTask(taskConfig)) {
577
+ const provides = getProvides(taskConfig);
578
+ const allAlreadyAvailable = provides.length > 0 && provides.every((output) => availableOutputs.includes(output));
579
+ if (allAlreadyAvailable) continue;
580
+ }
581
+ candidates.push(taskName);
582
+ }
583
+ return candidates;
584
+ }
585
+ function selectOptimalTasks(candidates, graph, state, conflictStrategy) {
586
+ const result = { eligibleTasks: [], hasConflicts: false, conflicts: {} };
587
+ if (candidates.length === 0) return result;
588
+ const graphTasks = getAllTasks(graph);
589
+ switch (conflictStrategy) {
590
+ case "parallel-all":
591
+ result.eligibleTasks = candidates;
592
+ return result;
593
+ case "user-choice": {
594
+ result.eligibleTasks = candidates;
595
+ if (candidates.length > 1) {
596
+ const outputGroups2 = groupTasksByProvides(candidates, graphTasks);
597
+ for (const [outputKey, groupTasks] of Object.entries(outputGroups2)) {
598
+ if (groupTasks.length > 1) {
599
+ result.conflicts[outputKey] = groupTasks;
600
+ result.hasConflicts = true;
601
+ }
602
+ }
603
+ }
604
+ return result;
605
+ }
606
+ case "skip-conflicts":
607
+ result.eligibleTasks = getNonConflictingTasks(candidates, graphTasks);
608
+ return result;
609
+ case "random-select":
610
+ result.eligibleTasks = selectRandomTasks(candidates, graphTasks);
611
+ return result;
612
+ }
613
+ const outputGroups = groupTasksByProvides(candidates, graphTasks);
614
+ const runningOutputs = /* @__PURE__ */ new Set();
615
+ for (const [taskName, taskState] of Object.entries(state.tasks)) {
616
+ if (taskState.status === TASK_STATUS.RUNNING) {
617
+ const taskConfig = graph.tasks[taskName];
618
+ if (taskConfig) {
619
+ getProvides(taskConfig).forEach((o) => runningOutputs.add(o));
620
+ }
621
+ }
622
+ }
623
+ const selectedTasks = [];
624
+ const tasksInConflictGroups = /* @__PURE__ */ new Set();
625
+ for (const [outputKey, groupTasks] of Object.entries(outputGroups)) {
626
+ if (runningOutputs.has(outputKey)) continue;
627
+ if (groupTasks.length === 1) {
628
+ selectedTasks.push(groupTasks[0]);
629
+ } else {
630
+ const selected = selectBestAlternative(groupTasks, graphTasks, state, conflictStrategy);
631
+ selectedTasks.push(selected);
632
+ }
633
+ groupTasks.forEach((t) => tasksInConflictGroups.add(t));
634
+ }
635
+ const nonConflicting = candidates.filter((t) => !tasksInConflictGroups.has(t));
636
+ nonConflicting.forEach((t) => {
637
+ if (!selectedTasks.includes(t)) selectedTasks.push(t);
638
+ });
639
+ result.eligibleTasks = selectedTasks;
640
+ return result;
641
+ }
642
+
643
+ // src/event-graph/task-transitions.ts
644
+ function applyTaskStart(state, taskName) {
645
+ const existingTask = state.tasks[taskName] ?? createDefaultTaskState2();
646
+ const updatedTask = {
647
+ ...existingTask,
648
+ status: "running",
649
+ startedAt: (/* @__PURE__ */ new Date()).toISOString(),
650
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
651
+ progress: 0,
652
+ error: void 0
653
+ };
654
+ return {
655
+ ...state,
656
+ tasks: { ...state.tasks, [taskName]: updatedTask },
657
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
658
+ };
659
+ }
660
+ function applyTaskCompletion(state, graph, taskName, result) {
661
+ const existingTask = state.tasks[taskName] ?? createDefaultTaskState2();
662
+ const taskConfig = graph.tasks[taskName];
663
+ if (!taskConfig) {
664
+ throw new Error(`Task "${taskName}" not found in graph`);
665
+ }
666
+ let outputTokens;
667
+ if (result && taskConfig.on && taskConfig.on[result]) {
668
+ outputTokens = taskConfig.on[result];
669
+ } else {
670
+ outputTokens = getProvides(taskConfig);
671
+ }
672
+ const updatedTask = {
673
+ ...existingTask,
674
+ status: "completed",
675
+ completedAt: (/* @__PURE__ */ new Date()).toISOString(),
676
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
677
+ executionCount: existingTask.executionCount + 1,
678
+ lastEpoch: existingTask.executionCount + 1,
679
+ error: void 0
680
+ };
681
+ if (isRepeatableTask(taskConfig)) {
682
+ updatedTask.status = "not-started";
683
+ }
684
+ const newOutputs = [.../* @__PURE__ */ new Set([...state.availableOutputs, ...outputTokens])];
685
+ return {
686
+ ...state,
687
+ tasks: { ...state.tasks, [taskName]: updatedTask },
688
+ availableOutputs: newOutputs,
689
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
690
+ };
691
+ }
692
+ function applyTaskFailure(state, graph, taskName, error) {
693
+ const existingTask = state.tasks[taskName] ?? createDefaultTaskState2();
694
+ const taskConfig = graph.tasks[taskName];
695
+ if (taskConfig?.retry) {
696
+ const retryCount = existingTask.retryCount + 1;
697
+ if (retryCount <= taskConfig.retry.max_attempts) {
698
+ const updatedTask2 = {
699
+ ...existingTask,
700
+ status: "not-started",
701
+ retryCount,
702
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
703
+ error
704
+ };
705
+ return {
706
+ ...state,
707
+ tasks: { ...state.tasks, [taskName]: updatedTask2 },
708
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
709
+ };
710
+ }
711
+ }
712
+ const updatedTask = {
713
+ ...existingTask,
714
+ status: "failed",
715
+ failedAt: (/* @__PURE__ */ new Date()).toISOString(),
716
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
717
+ error,
718
+ executionCount: existingTask.executionCount + 1
719
+ };
720
+ let newOutputs = state.availableOutputs;
721
+ if (taskConfig?.on_failure && taskConfig.on_failure.length > 0) {
722
+ newOutputs = [.../* @__PURE__ */ new Set([...state.availableOutputs, ...taskConfig.on_failure])];
723
+ }
724
+ if (taskConfig?.circuit_breaker && updatedTask.executionCount >= taskConfig.circuit_breaker.max_executions) {
725
+ const breakTokens = taskConfig.circuit_breaker.on_break;
726
+ newOutputs = [.../* @__PURE__ */ new Set([...newOutputs, ...breakTokens])];
727
+ }
728
+ return {
729
+ ...state,
730
+ tasks: { ...state.tasks, [taskName]: updatedTask },
731
+ availableOutputs: newOutputs,
732
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
733
+ };
734
+ }
735
+ function applyTaskProgress(state, taskName, message, progress) {
736
+ const existingTask = state.tasks[taskName] ?? createDefaultTaskState2();
737
+ const updatedTask = {
738
+ ...existingTask,
739
+ progress: typeof progress === "number" ? progress : existingTask.progress,
740
+ messages: [
741
+ ...existingTask.messages ?? [],
742
+ ...message ? [{ message, timestamp: (/* @__PURE__ */ new Date()).toISOString(), status: existingTask.status }] : []
743
+ ],
744
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
745
+ };
746
+ return {
747
+ ...state,
748
+ tasks: { ...state.tasks, [taskName]: updatedTask },
749
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
750
+ };
751
+ }
752
+ function createDefaultTaskState2() {
753
+ return {
754
+ status: "not-started",
755
+ executionCount: 0,
756
+ retryCount: 0,
757
+ lastEpoch: 0,
758
+ messages: [],
759
+ progress: null
760
+ };
761
+ }
762
+
763
+ // src/event-graph/reducer.ts
764
+ function apply(state, event, graph) {
765
+ if ("executionId" in event && event.executionId && event.executionId !== state.executionId) {
766
+ return state;
767
+ }
768
+ switch (event.type) {
769
+ case "task-started":
770
+ return applyTaskStart(state, event.taskName);
771
+ case "task-completed":
772
+ return applyTaskCompletion(state, graph, event.taskName, event.result);
773
+ case "task-failed":
774
+ return applyTaskFailure(state, graph, event.taskName, event.error);
775
+ case "task-progress":
776
+ return applyTaskProgress(state, event.taskName, event.message, event.progress);
777
+ case "inject-tokens":
778
+ return applyInjectTokens(state, event.tokens);
779
+ case "agent-action":
780
+ return applyAgentAction(state, event.action, graph, event.config);
781
+ case "task-creation":
782
+ return applyTaskCreation(state, event.taskName, event.taskConfig);
783
+ default:
784
+ return state;
785
+ }
786
+ }
787
+ function applyAll(state, events, graph) {
788
+ return events.reduce((s, e) => apply(s, e, graph), state);
789
+ }
790
+ function applyInjectTokens(state, tokens) {
791
+ return {
792
+ ...state,
793
+ availableOutputs: [.../* @__PURE__ */ new Set([...state.availableOutputs, ...tokens])],
794
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
795
+ };
796
+ }
797
+ function applyAgentAction(state, action, graph, config) {
798
+ const now = (/* @__PURE__ */ new Date()).toISOString();
799
+ switch (action) {
800
+ case "start": {
801
+ const executionId = `exec-${Date.now()}`;
802
+ const fresh = createInitialExecutionState(graph, executionId);
803
+ if (config) {
804
+ if (config.executionMode) {
805
+ fresh.executionConfig.executionMode = config.executionMode;
806
+ }
807
+ if (config.conflictStrategy) {
808
+ fresh.executionConfig.conflictStrategy = config.conflictStrategy;
809
+ }
810
+ if (config.completionStrategy) {
811
+ fresh.executionConfig.completionStrategy = config.completionStrategy;
812
+ }
813
+ }
814
+ return fresh;
815
+ }
816
+ case "stop":
817
+ return {
818
+ ...state,
819
+ status: "stopped",
820
+ executionId: null,
821
+ lastUpdated: now
822
+ };
823
+ case "pause":
824
+ return {
825
+ ...state,
826
+ status: "paused",
827
+ lastUpdated: now
828
+ };
829
+ case "resume":
830
+ return {
831
+ ...state,
832
+ status: "running",
833
+ lastUpdated: now
834
+ };
835
+ default:
836
+ return state;
837
+ }
838
+ }
839
+ function applyTaskCreation(state, taskName, taskConfig) {
840
+ if (!taskName || !taskConfig || !Array.isArray(taskConfig.provides)) {
841
+ return state;
842
+ }
843
+ return {
844
+ ...state,
845
+ tasks: {
846
+ ...state.tasks,
847
+ [taskName]: createDefaultTaskState()
848
+ },
849
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString()
850
+ };
851
+ }
852
+
853
+ export { COMPLETION_STRATEGIES, CONFLICT_STRATEGIES, DEFAULTS, EXECUTION_MODES, EXECUTION_STATUS, TASK_STATUS, addDynamicTask, addKeyToProvides, addKeyToRequires, apply, applyAll, applyTaskCompletion, applyTaskFailure, applyTaskProgress, applyTaskStart, computeAvailableOutputs, createDefaultTaskState, createInitialExecutionState, detectStuckState, getAllTasks, getCandidateTasks, getNonConflictingTasks, getProvides, getRepeatableMax, getRequires, getTask, groupTasksByProvides, hasOutputConflict, hasTask, isExecutionComplete, isNonActiveTask, isRepeatableTask, isTaskCompleted, isTaskRunning, next, removeKeyFromProvides, removeKeyFromRequires, selectBestAlternative, selectRandomTasks };
854
+ //# sourceMappingURL=index.js.map
855
+ //# sourceMappingURL=index.js.map