yaml-flow 2.1.0 → 2.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { StepMachine as FlowEngine, StepMachine, applyStepResult, checkCircuitBreaker, computeStepInput, createStepMachine as createEngine, createInitialState, createStepMachine, extractReturnData, loadStepFlow, validateStepFlowConfig } from './step-machine/index.cjs';
2
2
  export { C as CircuitBreakerConfig, R as RetryConfig, S as StepConfig, a as StepContext, b as StepEvent, c as StepEventListener, d as StepEventType, e as StepFlowConfig, f as StepFlowSettings, g as StepHandler, h as StepInput, i as StepMachineOptions, j as StepMachineResult, k as StepMachineState, l as StepMachineStore, m as StepReducerResult, n as StepResult, T as TerminalStateConfig } from './types-FZ_eyErS.cjs';
3
- export { A as AgentActionEvent, C as COMPLETION_STRATEGIES, a as CONFLICT_STRATEGIES, b as CompletionResult, c as CompletionStrategy, d as ConflictStrategy, D as DEFAULTS, E as EXECUTION_MODES, e as EXECUTION_STATUS, f as ExecutionConfig, g as ExecutionMode, h as ExecutionState, i as ExecutionStatus, G as GraphConfig, j as GraphEvent, k as GraphSettings, T as GraphTaskConfig, I as InjectTokensEvent, S as SchedulerResult, l as StuckDetection, m as TASK_STATUS, n as TaskCompletedEvent, o as TaskCreationEvent, p as TaskFailedEvent, q as TaskStartedEvent, r as TaskState, s as TaskStatus, t as addDynamicTask, u as apply, v as applyAll, w as computeAvailableOutputs, x as createDefaultTaskState, y as createInitialExecutionState, z as detectStuckState, B as getAllTasks, F as getCandidateTasks, H as getProvides, J as getRequires, K as getTask, L as hasTask, M as isExecutionComplete, N as isNonActiveTask, O as isRepeatableTask, P as isTaskCompleted, Q as isTaskRunning, R as next } from './constants-D1fTEbbM.cjs';
3
+ export { A as AgentActionEvent, C as COMPLETION_STRATEGIES, a as CONFLICT_STRATEGIES, b as CompletionResult, c as CompletionStrategy, d as ConflictStrategy, D as DEFAULTS, E as EXECUTION_MODES, e as EXECUTION_STATUS, f as ExecutionConfig, g as ExecutionMode, h as ExecutionPlan, i as ExecutionState, j as ExecutionStatus, k as ExportOptions, G as GraphConfig, l as GraphEvent, m as GraphIssue, n as GraphSettings, T as GraphTaskConfig, o as GraphValidationResult, I as InjectTokensEvent, p as IssueSeverity, M as MermaidOptions, S as SchedulerResult, q as StuckDetection, r as TASK_STATUS, s as TaskCompletedEvent, t as TaskCreationEvent, u as TaskFailedEvent, v as TaskStartedEvent, w as TaskState, x as TaskStatus, y as addDynamicTask, z as apply, B as applyAll, F as computeAvailableOutputs, H as createDefaultTaskState, J as createInitialExecutionState, K as detectStuckState, L as exportGraphConfig, N as exportGraphConfigToFile, O as flowToMermaid, P as getAllTasks, Q as getCandidateTasks, R as getProvides, U as getRequires, V as getTask, W as graphToMermaid, X as hasTask, Y as isExecutionComplete, Z as isNonActiveTask, _ as isRepeatableTask, $ as isTaskCompleted, a0 as isTaskRunning, a1 as loadGraphConfig, a2 as next, a3 as planExecution, a4 as validateGraph, a5 as validateGraphConfig } from './constants-BftTHiuV.cjs';
4
4
  export { MemoryStore } from './stores/memory.cjs';
5
5
  export { LocalStorageStore } from './stores/localStorage.cjs';
6
6
  export { FileStore } from './stores/file.cjs';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  export { StepMachine as FlowEngine, StepMachine, applyStepResult, checkCircuitBreaker, computeStepInput, createStepMachine as createEngine, createInitialState, createStepMachine, extractReturnData, loadStepFlow, validateStepFlowConfig } from './step-machine/index.js';
2
2
  export { C as CircuitBreakerConfig, R as RetryConfig, S as StepConfig, a as StepContext, b as StepEvent, c as StepEventListener, d as StepEventType, e as StepFlowConfig, f as StepFlowSettings, g as StepHandler, h as StepInput, i as StepMachineOptions, j as StepMachineResult, k as StepMachineState, l as StepMachineStore, m as StepReducerResult, n as StepResult, T as TerminalStateConfig } from './types-FZ_eyErS.js';
3
- export { A as AgentActionEvent, C as COMPLETION_STRATEGIES, a as CONFLICT_STRATEGIES, b as CompletionResult, c as CompletionStrategy, d as ConflictStrategy, D as DEFAULTS, E as EXECUTION_MODES, e as EXECUTION_STATUS, f as ExecutionConfig, g as ExecutionMode, h as ExecutionState, i as ExecutionStatus, G as GraphConfig, j as GraphEvent, k as GraphSettings, T as GraphTaskConfig, I as InjectTokensEvent, S as SchedulerResult, l as StuckDetection, m as TASK_STATUS, n as TaskCompletedEvent, o as TaskCreationEvent, p as TaskFailedEvent, q as TaskStartedEvent, r as TaskState, s as TaskStatus, t as addDynamicTask, u as apply, v as applyAll, w as computeAvailableOutputs, x as createDefaultTaskState, y as createInitialExecutionState, z as detectStuckState, B as getAllTasks, F as getCandidateTasks, H as getProvides, J as getRequires, K as getTask, L as hasTask, M as isExecutionComplete, N as isNonActiveTask, O as isRepeatableTask, P as isTaskCompleted, Q as isTaskRunning, R as next } from './constants-D1fTEbbM.js';
3
+ export { A as AgentActionEvent, C as COMPLETION_STRATEGIES, a as CONFLICT_STRATEGIES, b as CompletionResult, c as CompletionStrategy, d as ConflictStrategy, D as DEFAULTS, E as EXECUTION_MODES, e as EXECUTION_STATUS, f as ExecutionConfig, g as ExecutionMode, h as ExecutionPlan, i as ExecutionState, j as ExecutionStatus, k as ExportOptions, G as GraphConfig, l as GraphEvent, m as GraphIssue, n as GraphSettings, T as GraphTaskConfig, o as GraphValidationResult, I as InjectTokensEvent, p as IssueSeverity, M as MermaidOptions, S as SchedulerResult, q as StuckDetection, r as TASK_STATUS, s as TaskCompletedEvent, t as TaskCreationEvent, u as TaskFailedEvent, v as TaskStartedEvent, w as TaskState, x as TaskStatus, y as addDynamicTask, z as apply, B as applyAll, F as computeAvailableOutputs, H as createDefaultTaskState, J as createInitialExecutionState, K as detectStuckState, L as exportGraphConfig, N as exportGraphConfigToFile, O as flowToMermaid, P as getAllTasks, Q as getCandidateTasks, R as getProvides, U as getRequires, V as getTask, W as graphToMermaid, X as hasTask, Y as isExecutionComplete, Z as isNonActiveTask, _ as isRepeatableTask, $ as isTaskCompleted, a0 as isTaskRunning, a1 as loadGraphConfig, a2 as next, a3 as planExecution, a4 as validateGraph, a5 as validateGraphConfig } from './constants-DMbnp--H.js';
4
4
  export { MemoryStore } from './stores/memory.js';
5
5
  export { LocalStorageStore } from './stores/localStorage.js';
6
6
  export { FileStore } from './stores/file.js';
package/dist/index.js CHANGED
@@ -1331,6 +1331,615 @@ function applyTaskCreation(state, taskName, taskConfig) {
1331
1331
  };
1332
1332
  }
1333
1333
 
1334
+ // src/event-graph/plan.ts
1335
+ function buildProducerMap(tasks) {
1336
+ const map = {};
1337
+ for (const [name, config] of Object.entries(tasks)) {
1338
+ for (const token of getProvides(config)) {
1339
+ if (!map[token]) map[token] = [];
1340
+ map[token].push(name);
1341
+ }
1342
+ if (config.on) {
1343
+ for (const tokens of Object.values(config.on)) {
1344
+ for (const token of tokens) {
1345
+ if (!map[token]) map[token] = [];
1346
+ if (!map[token].includes(name)) map[token].push(name);
1347
+ }
1348
+ }
1349
+ }
1350
+ if (config.on_failure) {
1351
+ for (const token of config.on_failure) {
1352
+ if (!map[token]) map[token] = [];
1353
+ if (!map[token].includes(name)) map[token].push(name);
1354
+ }
1355
+ }
1356
+ }
1357
+ return map;
1358
+ }
1359
+ function buildDependencies(tasks, producerMap) {
1360
+ const deps = {};
1361
+ for (const [name, config] of Object.entries(tasks)) {
1362
+ const required = getRequires(config);
1363
+ const taskDeps = /* @__PURE__ */ new Set();
1364
+ for (const token of required) {
1365
+ const producers = producerMap[token] || [];
1366
+ for (const producer of producers) {
1367
+ if (producer !== name) taskDeps.add(producer);
1368
+ }
1369
+ }
1370
+ deps[name] = [...taskDeps];
1371
+ }
1372
+ return deps;
1373
+ }
1374
+ function computePhases(taskNames, dependencies) {
1375
+ const taskSet = new Set(taskNames);
1376
+ const inDegree = {};
1377
+ const dependents = {};
1378
+ for (const name of taskNames) {
1379
+ inDegree[name] = 0;
1380
+ dependents[name] = [];
1381
+ }
1382
+ for (const name of taskNames) {
1383
+ for (const dep of dependencies[name] || []) {
1384
+ if (taskSet.has(dep)) {
1385
+ inDegree[name]++;
1386
+ dependents[dep].push(name);
1387
+ }
1388
+ }
1389
+ }
1390
+ const phases = [];
1391
+ const remaining = new Set(taskNames);
1392
+ while (remaining.size > 0) {
1393
+ const phase = [];
1394
+ for (const name of remaining) {
1395
+ if (inDegree[name] === 0) {
1396
+ phase.push(name);
1397
+ }
1398
+ }
1399
+ if (phase.length === 0) {
1400
+ phases.push([...remaining]);
1401
+ break;
1402
+ }
1403
+ phase.sort();
1404
+ phases.push(phase);
1405
+ for (const name of phase) {
1406
+ remaining.delete(name);
1407
+ for (const dependent of dependents[name] || []) {
1408
+ if (remaining.has(dependent)) {
1409
+ inDegree[dependent]--;
1410
+ }
1411
+ }
1412
+ }
1413
+ }
1414
+ return phases;
1415
+ }
1416
+ function planExecution(graph) {
1417
+ const tasks = getAllTasks(graph);
1418
+ const taskNames = Object.keys(tasks);
1419
+ if (taskNames.length === 0) {
1420
+ return {
1421
+ phases: [],
1422
+ dependencies: {},
1423
+ conflicts: {},
1424
+ entryPoints: [],
1425
+ leafTasks: [],
1426
+ unreachableTokens: [],
1427
+ blockedTasks: [],
1428
+ depth: 0,
1429
+ maxParallelism: 0
1430
+ };
1431
+ }
1432
+ const producerMap = buildProducerMap(tasks);
1433
+ const dependencies = buildDependencies(tasks, producerMap);
1434
+ const conflicts = {};
1435
+ for (const [token, producers] of Object.entries(producerMap)) {
1436
+ if (producers.length > 1) {
1437
+ conflicts[token] = producers;
1438
+ }
1439
+ }
1440
+ const entryPoints = taskNames.filter((name) => getRequires(tasks[name]).length === 0);
1441
+ const dependedOn = /* @__PURE__ */ new Set();
1442
+ for (const deps of Object.values(dependencies)) {
1443
+ for (const dep of deps) dependedOn.add(dep);
1444
+ }
1445
+ const leafTasks = taskNames.filter((name) => !dependedOn.has(name));
1446
+ const allRequired = /* @__PURE__ */ new Set();
1447
+ for (const config of Object.values(tasks)) {
1448
+ for (const token of getRequires(config)) {
1449
+ allRequired.add(token);
1450
+ }
1451
+ }
1452
+ const unreachableTokens = [...allRequired].filter((token) => !producerMap[token]);
1453
+ const unreachableSet = new Set(unreachableTokens);
1454
+ const blockedTasks = taskNames.filter(
1455
+ (name) => getRequires(tasks[name]).some((token) => unreachableSet.has(token))
1456
+ );
1457
+ const phases = computePhases(taskNames, dependencies);
1458
+ return {
1459
+ phases,
1460
+ dependencies,
1461
+ conflicts,
1462
+ entryPoints,
1463
+ leafTasks: leafTasks.sort(),
1464
+ unreachableTokens: unreachableTokens.sort(),
1465
+ blockedTasks: blockedTasks.sort(),
1466
+ depth: phases.length,
1467
+ maxParallelism: Math.max(0, ...phases.map((p) => p.length))
1468
+ };
1469
+ }
1470
+
1471
+ // src/event-graph/mermaid.ts
1472
+ function sanitizeId(name) {
1473
+ return name.replace(/[^a-zA-Z0-9_]/g, "_");
1474
+ }
1475
+ function graphToMermaid(graph, options = {}) {
1476
+ const { direction = "TD", showTokens = true, title } = options;
1477
+ const tasks = getAllTasks(graph);
1478
+ const taskNames = Object.keys(tasks);
1479
+ if (taskNames.length === 0) {
1480
+ return `graph ${direction}
1481
+ empty[No tasks defined]`;
1482
+ }
1483
+ const producerMap = {};
1484
+ for (const [name, config] of Object.entries(tasks)) {
1485
+ for (const token of getProvides(config)) {
1486
+ if (!producerMap[token]) producerMap[token] = [];
1487
+ producerMap[token].push(name);
1488
+ }
1489
+ if (config.on) {
1490
+ for (const tokens of Object.values(config.on)) {
1491
+ for (const token of tokens) {
1492
+ if (!producerMap[token]) producerMap[token] = [];
1493
+ if (!producerMap[token].includes(name)) producerMap[token].push(name);
1494
+ }
1495
+ }
1496
+ }
1497
+ }
1498
+ const lines = [];
1499
+ const diagramTitle = title || graph.id || "Event Graph";
1500
+ lines.push(`%% ${diagramTitle}`);
1501
+ lines.push(`graph ${direction}`);
1502
+ const allRequired = /* @__PURE__ */ new Set();
1503
+ for (const config of Object.values(tasks)) {
1504
+ for (const token of getRequires(config)) {
1505
+ allRequired.add(token);
1506
+ }
1507
+ }
1508
+ const leafTaskSet = new Set(
1509
+ taskNames.filter((name) => {
1510
+ const prov = getProvides(tasks[name]);
1511
+ return prov.length === 0 || prov.every((token) => !allRequired.has(token));
1512
+ })
1513
+ );
1514
+ for (const name of taskNames) {
1515
+ const id = sanitizeId(name);
1516
+ const req = getRequires(tasks[name]);
1517
+ if (req.length === 0) {
1518
+ lines.push(` ${id}([${name}])`);
1519
+ } else if (leafTaskSet.has(name)) {
1520
+ lines.push(` ${id}[[${name}]]`);
1521
+ } else {
1522
+ lines.push(` ${id}[${name}]`);
1523
+ }
1524
+ }
1525
+ const edgeSet = /* @__PURE__ */ new Set();
1526
+ for (const [name, config] of Object.entries(tasks)) {
1527
+ const required = getRequires(config);
1528
+ for (const token of required) {
1529
+ const producers = producerMap[token] || [];
1530
+ for (const producer of producers) {
1531
+ if (producer === name) continue;
1532
+ const edgeKey = `${producer}->${name}:${token}`;
1533
+ if (edgeSet.has(edgeKey)) continue;
1534
+ edgeSet.add(edgeKey);
1535
+ const fromId = sanitizeId(producer);
1536
+ const toId = sanitizeId(name);
1537
+ if (showTokens) {
1538
+ lines.push(` ${fromId} -->|${token}| ${toId}`);
1539
+ } else {
1540
+ lines.push(` ${fromId} --> ${toId}`);
1541
+ }
1542
+ }
1543
+ }
1544
+ for (const token of required) {
1545
+ if (!producerMap[token]) {
1546
+ const warnId = `warn_${sanitizeId(token)}`;
1547
+ const toId = sanitizeId(name);
1548
+ lines.push(` ${warnId}{{\u26A0 ${token}}} -.->|missing| ${toId}`);
1549
+ }
1550
+ }
1551
+ }
1552
+ return lines.join("\n");
1553
+ }
1554
+ function flowToMermaid(flow, options = {}) {
1555
+ const { direction = "TD", title } = options;
1556
+ const steps = flow.steps;
1557
+ const terminals = flow.terminal_states;
1558
+ const startStep = flow.settings.start_step;
1559
+ const lines = [];
1560
+ const diagramTitle = title || flow.id || "Step Machine";
1561
+ lines.push(`%% ${diagramTitle}`);
1562
+ lines.push(`graph ${direction}`);
1563
+ lines.push(` START(( ))`);
1564
+ lines.push(` START --> ${sanitizeId(startStep)}`);
1565
+ for (const name of Object.keys(steps)) {
1566
+ const id = sanitizeId(name);
1567
+ lines.push(` ${id}[${name}]`);
1568
+ }
1569
+ for (const [name, config] of Object.entries(terminals)) {
1570
+ const id = sanitizeId(name);
1571
+ lines.push(` ${id}([${name}: ${config.return_intent}])`);
1572
+ }
1573
+ for (const [stepName, stepConfig] of Object.entries(steps)) {
1574
+ const fromId = sanitizeId(stepName);
1575
+ for (const [result, target] of Object.entries(stepConfig.transitions)) {
1576
+ const toId = sanitizeId(target);
1577
+ lines.push(` ${fromId} -->|${result}| ${toId}`);
1578
+ }
1579
+ }
1580
+ return lines.join("\n");
1581
+ }
1582
+
1583
+ // src/event-graph/loader.ts
1584
+ function validateGraphConfig(config) {
1585
+ const errors = [];
1586
+ if (!config || typeof config !== "object") {
1587
+ return ["Graph config must be an object"];
1588
+ }
1589
+ const c = config;
1590
+ if (!c.settings || typeof c.settings !== "object") {
1591
+ errors.push('Graph config must have a "settings" object');
1592
+ } else {
1593
+ const settings = c.settings;
1594
+ if (!settings.completion || typeof settings.completion !== "string") {
1595
+ errors.push("settings.completion must be a string");
1596
+ }
1597
+ if (settings.completion === "goal-reached") {
1598
+ if (!Array.isArray(settings.goal) || settings.goal.length === 0) {
1599
+ errors.push('settings.goal must be a non-empty array when completion is "goal-reached"');
1600
+ }
1601
+ }
1602
+ }
1603
+ if (!c.tasks || typeof c.tasks !== "object") {
1604
+ errors.push('Graph config must have a "tasks" object');
1605
+ } else {
1606
+ const tasks = c.tasks;
1607
+ if (Object.keys(tasks).length === 0) {
1608
+ errors.push("Graph config must have at least one task");
1609
+ }
1610
+ for (const [name, task] of Object.entries(tasks)) {
1611
+ if (!task || typeof task !== "object") {
1612
+ errors.push(`Task "${name}" must be an object`);
1613
+ continue;
1614
+ }
1615
+ const t = task;
1616
+ if (!Array.isArray(t.provides)) {
1617
+ errors.push(`Task "${name}" must have a "provides" array`);
1618
+ }
1619
+ if (t.requires !== void 0 && !Array.isArray(t.requires)) {
1620
+ errors.push(`Task "${name}".requires must be an array if present`);
1621
+ }
1622
+ if (t.on !== void 0) {
1623
+ if (typeof t.on !== "object" || Array.isArray(t.on)) {
1624
+ errors.push(`Task "${name}".on must be an object mapping result keys to token arrays`);
1625
+ } else {
1626
+ for (const [key, tokens] of Object.entries(t.on)) {
1627
+ if (!Array.isArray(tokens)) {
1628
+ errors.push(`Task "${name}".on.${key} must be an array of tokens`);
1629
+ }
1630
+ }
1631
+ }
1632
+ }
1633
+ }
1634
+ }
1635
+ return errors;
1636
+ }
1637
+ async function parseGraphYaml(yamlString) {
1638
+ const yaml = await import('yaml');
1639
+ return yaml.parse(yamlString);
1640
+ }
1641
+ async function loadGraphConfig(source) {
1642
+ let config;
1643
+ if (typeof source === "string") {
1644
+ if (source.startsWith("http://") || source.startsWith("https://")) {
1645
+ const response = await fetch(source);
1646
+ if (!response.ok) {
1647
+ throw new Error(`Failed to load graph config from ${source}: ${response.statusText}`);
1648
+ }
1649
+ const text = await response.text();
1650
+ const contentType = response.headers.get("content-type") ?? "";
1651
+ if (contentType.includes("json") || source.endsWith(".json")) {
1652
+ config = JSON.parse(text);
1653
+ } else {
1654
+ config = await parseGraphYaml(text);
1655
+ }
1656
+ } else if (source.includes("{")) {
1657
+ config = JSON.parse(source);
1658
+ } else {
1659
+ const fs = await import('fs/promises');
1660
+ const text = await fs.readFile(source, "utf-8");
1661
+ if (source.endsWith(".json")) {
1662
+ config = JSON.parse(text);
1663
+ } else {
1664
+ config = await parseGraphYaml(text);
1665
+ }
1666
+ }
1667
+ } else {
1668
+ config = source;
1669
+ }
1670
+ const errors = validateGraphConfig(config);
1671
+ if (errors.length > 0) {
1672
+ throw new Error(`Invalid graph configuration:
1673
+ - ${errors.join("\n- ")}`);
1674
+ }
1675
+ return config;
1676
+ }
1677
+ function exportGraphConfig(config, options = {}) {
1678
+ const { format = "json", indent = 2 } = options;
1679
+ if (format === "yaml") {
1680
+ return toYaml(config, indent);
1681
+ }
1682
+ return JSON.stringify(config, null, indent);
1683
+ }
1684
+ async function exportGraphConfigToFile(config, filePath, options = {}) {
1685
+ const format = options.format ?? (filePath.endsWith(".yaml") || filePath.endsWith(".yml") ? "yaml" : "json");
1686
+ const content = exportGraphConfig(config, { ...options, format });
1687
+ const fs = await import('fs/promises');
1688
+ await fs.writeFile(filePath, content, "utf-8");
1689
+ }
1690
+ function toYaml(obj, indent, depth = 0) {
1691
+ const pad = " ".repeat(indent * depth);
1692
+ if (obj === null || obj === void 0) return "null";
1693
+ if (typeof obj === "boolean") return String(obj);
1694
+ if (typeof obj === "number") return String(obj);
1695
+ if (typeof obj === "string") {
1696
+ if (obj.includes(":") || obj.includes("#") || obj.includes("\n") || obj.includes('"') || obj.includes("'") || obj.startsWith(" ") || obj.startsWith("{") || obj.startsWith("[") || obj === "") {
1697
+ return JSON.stringify(obj);
1698
+ }
1699
+ return obj;
1700
+ }
1701
+ if (Array.isArray(obj)) {
1702
+ if (obj.length === 0) return "[]";
1703
+ if (obj.every((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean")) {
1704
+ return `[${obj.map((v) => typeof v === "string" ? toYaml(v, indent, 0) : String(v)).join(", ")}]`;
1705
+ }
1706
+ return obj.map((item) => {
1707
+ const val = toYaml(item, indent, depth + 1);
1708
+ if (typeof item === "object" && item !== null && !Array.isArray(item)) {
1709
+ const lines = val.trimStart().split("\n");
1710
+ return `${pad}- ${lines[0]}
1711
+ ${lines.slice(1).map((l) => `${pad} ${l.trimStart() ? l : ""}`).filter(Boolean).join("\n")}`;
1712
+ }
1713
+ return `${pad}- ${val}`;
1714
+ }).join("\n");
1715
+ }
1716
+ if (typeof obj === "object") {
1717
+ const entries = Object.entries(obj);
1718
+ if (entries.length === 0) return "{}";
1719
+ return entries.map(([key, value]) => {
1720
+ if (value === void 0) return "";
1721
+ const serialized = toYaml(value, indent, depth + 1);
1722
+ if (typeof value === "object" && value !== null && !Array.isArray(value) && Object.keys(value).length > 0) {
1723
+ return `${pad}${key}:
1724
+ ${serialized}`;
1725
+ }
1726
+ if (Array.isArray(value) && value.length > 0 && !value.every((v) => typeof v === "string" || typeof v === "number" || typeof v === "boolean")) {
1727
+ return `${pad}${key}:
1728
+ ${serialized}`;
1729
+ }
1730
+ return `${pad}${key}: ${serialized}`;
1731
+ }).filter(Boolean).join("\n");
1732
+ }
1733
+ return String(obj);
1734
+ }
1735
+
1736
+ // src/event-graph/validate.ts
1737
+ function buildProducerMap2(tasks) {
1738
+ const map = {};
1739
+ for (const [name, config] of Object.entries(tasks)) {
1740
+ for (const token of getProvides(config)) {
1741
+ if (!map[token]) map[token] = [];
1742
+ map[token].push(name);
1743
+ }
1744
+ if (config.on) {
1745
+ for (const tokens of Object.values(config.on)) {
1746
+ for (const token of tokens) {
1747
+ if (!map[token]) map[token] = [];
1748
+ if (!map[token].includes(name)) map[token].push(name);
1749
+ }
1750
+ }
1751
+ }
1752
+ if (config.on_failure) {
1753
+ for (const token of config.on_failure) {
1754
+ if (!map[token]) map[token] = [];
1755
+ if (!map[token].includes(name)) map[token].push(name);
1756
+ }
1757
+ }
1758
+ }
1759
+ return map;
1760
+ }
1761
+ function buildTaskDeps(tasks, producerMap) {
1762
+ const deps = {};
1763
+ for (const [name, config] of Object.entries(tasks)) {
1764
+ deps[name] = /* @__PURE__ */ new Set();
1765
+ for (const token of getRequires(config)) {
1766
+ for (const producer of producerMap[token] || []) {
1767
+ if (producer !== name) deps[name].add(producer);
1768
+ }
1769
+ }
1770
+ }
1771
+ return deps;
1772
+ }
1773
+ function detectCycles(taskNames, deps) {
1774
+ const WHITE = 0, GRAY = 1, BLACK = 2;
1775
+ const color = {};
1776
+ const parent = {};
1777
+ const cycles = [];
1778
+ for (const name of taskNames) {
1779
+ color[name] = WHITE;
1780
+ parent[name] = null;
1781
+ }
1782
+ function dfs(node) {
1783
+ color[node] = GRAY;
1784
+ for (const dep of deps[node] || []) {
1785
+ if (color[dep] === GRAY) {
1786
+ const cycle = [dep];
1787
+ let cur = node;
1788
+ while (cur !== dep) {
1789
+ cycle.push(cur);
1790
+ cur = parent[cur];
1791
+ }
1792
+ cycle.push(dep);
1793
+ cycle.reverse();
1794
+ cycles.push(cycle);
1795
+ } else if (color[dep] === WHITE) {
1796
+ parent[dep] = node;
1797
+ dfs(dep);
1798
+ }
1799
+ }
1800
+ color[node] = BLACK;
1801
+ }
1802
+ for (const name of taskNames) {
1803
+ if (color[name] === WHITE) {
1804
+ dfs(name);
1805
+ }
1806
+ }
1807
+ return cycles;
1808
+ }
1809
+ function validateGraph(graph) {
1810
+ const issues = [];
1811
+ const tasks = getAllTasks(graph);
1812
+ const taskNames = Object.keys(tasks);
1813
+ if (taskNames.length === 0) {
1814
+ issues.push({
1815
+ severity: "error",
1816
+ code: "EMPTY_GRAPH",
1817
+ message: "Graph has no tasks"
1818
+ });
1819
+ return buildResult(issues);
1820
+ }
1821
+ const producerMap = buildProducerMap2(tasks);
1822
+ const deps = buildTaskDeps(tasks, producerMap);
1823
+ for (const [name, config] of Object.entries(tasks)) {
1824
+ for (const token of getRequires(config)) {
1825
+ if (!producerMap[token]) {
1826
+ issues.push({
1827
+ severity: "error",
1828
+ code: "DANGLING_REQUIRES",
1829
+ message: `Task "${name}" requires token "${token}" but no task produces it`,
1830
+ tasks: [name],
1831
+ tokens: [token]
1832
+ });
1833
+ }
1834
+ }
1835
+ }
1836
+ const cycles = detectCycles(taskNames, deps);
1837
+ for (const cycle of cycles) {
1838
+ issues.push({
1839
+ severity: "error",
1840
+ code: "CIRCULAR_DEPENDENCY",
1841
+ message: `Circular dependency: ${cycle.join(" \u2192 ")}`,
1842
+ tasks: cycle.filter((_t, i) => i < cycle.length - 1)
1843
+ // dedupe last = first
1844
+ });
1845
+ }
1846
+ for (const [name, config] of Object.entries(tasks)) {
1847
+ const req = getRequires(config);
1848
+ const prov = getProvides(config);
1849
+ const self = req.filter((token) => prov.includes(token));
1850
+ if (self.length > 0) {
1851
+ issues.push({
1852
+ severity: "error",
1853
+ code: "SELF_DEPENDENCY",
1854
+ message: `Task "${name}" requires tokens it provides itself: [${self.join(", ")}]`,
1855
+ tasks: [name],
1856
+ tokens: self
1857
+ });
1858
+ }
1859
+ }
1860
+ for (const [token, producers] of Object.entries(producerMap)) {
1861
+ if (producers.length > 1) {
1862
+ issues.push({
1863
+ severity: "warning",
1864
+ code: "PROVIDE_CONFLICT",
1865
+ message: `Token "${token}" is produced by multiple tasks: [${producers.join(", ")}]. This requires a conflict strategy.`,
1866
+ tasks: producers,
1867
+ tokens: [token]
1868
+ });
1869
+ }
1870
+ }
1871
+ if (graph.settings.completion === "goal-reached" && graph.settings.goal) {
1872
+ for (const goalToken of graph.settings.goal) {
1873
+ if (!producerMap[goalToken]) {
1874
+ issues.push({
1875
+ severity: "error",
1876
+ code: "UNREACHABLE_GOAL",
1877
+ message: `Goal token "${goalToken}" cannot be produced by any task`,
1878
+ tokens: [goalToken]
1879
+ });
1880
+ }
1881
+ }
1882
+ }
1883
+ if (taskNames.length > 1) {
1884
+ for (const [name, config] of Object.entries(tasks)) {
1885
+ const prov = getProvides(config);
1886
+ const onProv = config.on ? Object.values(config.on).flat() : [];
1887
+ const failProv = config.on_failure || [];
1888
+ if (prov.length === 0 && onProv.length === 0 && failProv.length === 0) {
1889
+ issues.push({
1890
+ severity: "warning",
1891
+ code: "DEAD_END_TASK",
1892
+ message: `Task "${name}" has no provides \u2014 it cannot unblock any downstream task`,
1893
+ tasks: [name]
1894
+ });
1895
+ }
1896
+ }
1897
+ }
1898
+ const allRequired = /* @__PURE__ */ new Set();
1899
+ for (const config of Object.values(tasks)) {
1900
+ for (const token of getRequires(config)) {
1901
+ allRequired.add(token);
1902
+ }
1903
+ }
1904
+ for (const [name, config] of Object.entries(tasks)) {
1905
+ const req = getRequires(config);
1906
+ const prov = getProvides(config);
1907
+ const onProv = config.on ? Object.values(config.on).flat() : [];
1908
+ const allProv = [...prov, ...onProv];
1909
+ const isEntryPoint = req.length === 0;
1910
+ const hasDownstream = allProv.some((token) => allRequired.has(token));
1911
+ if (isEntryPoint && !hasDownstream && taskNames.length > 1) {
1912
+ const isGoalRelevant = graph.settings.completion === "goal-reached" && graph.settings.goal?.some((g) => allProv.includes(g));
1913
+ if (!isGoalRelevant) {
1914
+ issues.push({
1915
+ severity: "info",
1916
+ code: "ISOLATED_TASK",
1917
+ message: `Task "${name}" is disconnected \u2014 it has no requires and nothing depends on its provides`,
1918
+ tasks: [name]
1919
+ });
1920
+ }
1921
+ }
1922
+ }
1923
+ if (graph.settings.completion === "goal-reached" && !graph.settings.goal) {
1924
+ issues.push({
1925
+ severity: "error",
1926
+ code: "MISSING_GOAL",
1927
+ message: 'Completion strategy is "goal-reached" but no goal tokens are defined'
1928
+ });
1929
+ }
1930
+ return buildResult(issues);
1931
+ }
1932
+ function buildResult(issues) {
1933
+ const errors = issues.filter((i) => i.severity === "error");
1934
+ const warnings = issues.filter((i) => i.severity === "warning");
1935
+ return {
1936
+ valid: errors.length === 0,
1937
+ issues,
1938
+ errors,
1939
+ warnings
1940
+ };
1941
+ }
1942
+
1334
1943
  // src/stores/localStorage.ts
1335
1944
  var LocalStorageStore = class {
1336
1945
  prefix;
@@ -1691,6 +2300,6 @@ function resolveConfigTemplates(config) {
1691
2300
  return result;
1692
2301
  }
1693
2302
 
1694
- export { COMPLETION_STRATEGIES, CONFLICT_STRATEGIES, DEFAULTS, EXECUTION_MODES, EXECUTION_STATUS, FileStore, StepMachine as FlowEngine, LocalStorageStore, MemoryStore, StepMachine, TASK_STATUS, addDynamicTask, apply, applyAll, applyStepResult, batch, checkCircuitBreaker, computeAvailableOutputs, computeStepInput, createDefaultTaskState, createStepMachine as createEngine, createInitialExecutionState, createInitialState, createStepMachine, detectStuckState, extractReturnData, getAllTasks, getCandidateTasks, getProvides, getRequires, getTask, hasTask, isExecutionComplete, isNonActiveTask, isRepeatableTask, isTaskCompleted, isTaskRunning, loadStepFlow, next, resolveConfigTemplates, resolveVariables, validateStepFlowConfig };
2303
+ export { COMPLETION_STRATEGIES, CONFLICT_STRATEGIES, DEFAULTS, EXECUTION_MODES, EXECUTION_STATUS, FileStore, StepMachine as FlowEngine, LocalStorageStore, MemoryStore, StepMachine, TASK_STATUS, addDynamicTask, apply, applyAll, applyStepResult, batch, checkCircuitBreaker, computeAvailableOutputs, computeStepInput, createDefaultTaskState, createStepMachine as createEngine, createInitialExecutionState, createInitialState, createStepMachine, detectStuckState, exportGraphConfig, exportGraphConfigToFile, extractReturnData, flowToMermaid, getAllTasks, getCandidateTasks, getProvides, getRequires, getTask, graphToMermaid, hasTask, isExecutionComplete, isNonActiveTask, isRepeatableTask, isTaskCompleted, isTaskRunning, loadGraphConfig, loadStepFlow, next, planExecution, resolveConfigTemplates, resolveVariables, validateGraph, validateGraphConfig, validateStepFlowConfig };
1695
2304
  //# sourceMappingURL=index.js.map
1696
2305
  //# sourceMappingURL=index.js.map