flowcraft 2.9.1 → 2.9.2
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/README.md +30 -29
- package/dist/{index-BzLn8lCA.d.mts → index-DUPpyNvU.d.mts} +2 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/dist/replay-BB11M6K1.mjs.map +1 -1
- package/dist/{runtime-gjjfM1q1.mjs → runtime-CRwlRW2p.mjs} +2 -2
- package/dist/runtime-CRwlRW2p.mjs.map +1 -0
- package/dist/testing/index.d.mts +2 -2
- package/dist/testing/index.mjs +2 -2
- package/dist/testing/index.mjs.map +1 -1
- package/package.json +12 -12
- package/dist/runtime-gjjfM1q1.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -8,15 +8,15 @@ Build complex, multi-step processes with a lightweight, composable, and type-saf
|
|
|
8
8
|
|
|
9
9
|
## Key Features
|
|
10
10
|
|
|
11
|
-
-
|
|
12
|
-
-
|
|
13
|
-
-
|
|
14
|
-
-
|
|
15
|
-
-
|
|
16
|
-
-
|
|
17
|
-
-
|
|
18
|
-
-
|
|
19
|
-
-
|
|
11
|
+
- **Zero Dependencies**: Lightweight and dependency-free, ensuring easy integration in any runtime.
|
|
12
|
+
- **Declarative Workflows**: Define workflows as [serializable](https://flowcraft.js.org/guide/core-concepts#workflow-blueprint) objects with [nodes and edges](https://flowcraft.js.org/guide/core-concepts#nodes-edges).
|
|
13
|
+
- **Unopinionated Logic**: Nodes can be simple [functions](https://flowcraft.js.org/guide/core-concepts#function-based-nodes) or structured [classes](https://flowcraft.js.org/guide/core-concepts#class-based-nodes), supporting any logic.
|
|
14
|
+
- **Progressive Scalability**: Run [in-memory](https://flowcraft.js.org/guide/fluent) or scale to [distributed systems](https://flowcraft.js.org/guide/distributed-execution) using the same blueprint.
|
|
15
|
+
- **Resilient Execution**: Built-in support for [retries](https://flowcraft.js.org/guide/error-handling#retries), [fallbacks](https://flowcraft.js.org/guide/error-handling#fallbacks), [timeouts](https://flowcraft.js.org/guide/core-concepts#config), and [cancellation](https://flowcraft.js.org/guide/core-concepts#cancellation).
|
|
16
|
+
- **Advanced Patterns**: Includes [batches](https://flowcraft.js.org/guide/batches), [loops](https://flowcraft.js.org/guide/loops), [subflows](https://flowcraft.js.org/guide/subflows), and [HITL](https://flowcraft.js.org/guide/hitl) constructs for complex workflows.
|
|
17
|
+
- **Extensibility**: Pluggable [loggers](https://flowcraft.js.org/guide/loggers), [evaluators](https://flowcraft.js.org/guide/evaluators), [serializers](https://flowcraft.js.org/guide/serializers), and [middleware](https://flowcraft.js.org/guide/middleware) for custom behavior.
|
|
18
|
+
- **Static Analysis**: Tools to [detect cycles](https://flowcraft.js.org/guide/static-analysis#detecting-cycles), [validate blueprints](https://flowcraft.js.org/guide/static-analysis#linting-a-blueprint), and [generate visual diagrams](https://flowcraft.js.org/guide/visualizing-workflows#generatemermaid).
|
|
19
|
+
- **Type-Safe API**: [Fully typed](https://flowcraft.js.org/guide/core-concepts#context) with TypeScript for a robust developer experience.
|
|
20
20
|
|
|
21
21
|
## Installation
|
|
22
22
|
|
|
@@ -24,21 +24,22 @@ Build complex, multi-step processes with a lightweight, composable, and type-saf
|
|
|
24
24
|
npm install flowcraft
|
|
25
25
|
```
|
|
26
26
|
|
|
27
|
-
|
|
28
27
|
## Usage
|
|
29
28
|
|
|
30
29
|
Define and run a simple workflow in a few lines of code.
|
|
31
30
|
|
|
32
31
|
```typescript
|
|
33
|
-
import { createFlow, FlowRuntime } from 'flowcraft'
|
|
32
|
+
import { createFlow, FlowRuntime, type NodeContext } from 'flowcraft'
|
|
34
33
|
|
|
35
34
|
// 1. Define your functions for the nodes
|
|
36
35
|
async function startNode({ context }: NodeContext) {
|
|
37
36
|
const output = await context.get('value')
|
|
38
37
|
return { output }
|
|
39
38
|
}
|
|
40
|
-
async function doubleNode({ input }: NodeContext) {
|
|
41
|
-
|
|
39
|
+
async function doubleNode({ input, context }: NodeContext) {
|
|
40
|
+
const output = input * 2
|
|
41
|
+
context.set('double', output)
|
|
42
|
+
return { output }
|
|
42
43
|
}
|
|
43
44
|
|
|
44
45
|
// 2. Define the workflow structure
|
|
@@ -52,7 +53,7 @@ const runtime = new FlowRuntime()
|
|
|
52
53
|
|
|
53
54
|
// 4. Execute the workflow
|
|
54
55
|
async function run() {
|
|
55
|
-
const result = await
|
|
56
|
+
const result = await flow.run(runtime, { value: 42 })
|
|
56
57
|
console.log(result.context) // { start: 42, double: 84 }
|
|
57
58
|
console.log(result.status) // 'completed'
|
|
58
59
|
}
|
|
@@ -62,18 +63,18 @@ run()
|
|
|
62
63
|
|
|
63
64
|
## Core Concepts
|
|
64
65
|
|
|
65
|
-
-
|
|
66
|
-
-
|
|
67
|
-
-
|
|
68
|
-
-
|
|
69
|
-
-
|
|
66
|
+
- **Blueprint**: A serializable object that represents the structure of your workflow. It contains all the nodes and edges and can be stored as JSON or YAML. This is the single source of truth for a workflow's logic.
|
|
67
|
+
- **Node**: A single unit of work. Node logic can be implemented as a simple async function or a structured class that extends `BaseNode` for more complex lifecycle management.
|
|
68
|
+
- **Edge**: A connection between two nodes that defines the direction of the flow. Edges can be conditional, allowing you to create branching logic based on the output or `action` of a source node.
|
|
69
|
+
- **Runtime**: The `FlowRuntime` is the engine that interprets a blueprint and executes its nodes in the correct order. It manages state, handles resiliency, and coordinates the entire process.
|
|
70
|
+
- **Context**: An object that holds the state of a single workflow execution. The outputs of completed nodes are stored in the context and can be accessed by subsequent nodes.
|
|
70
71
|
|
|
71
72
|
## Resiliency and Error Handling
|
|
72
73
|
|
|
73
74
|
Design robust workflows with built-in resiliency features.
|
|
74
75
|
|
|
75
|
-
-
|
|
76
|
-
-
|
|
76
|
+
- **Retries**: Configure the `maxRetries` property on a node to automatically retry it on failure.
|
|
77
|
+
- **Fallbacks**: Specify a `fallback` node ID in a node's configuration. If the node fails all its retry attempts, the fallback node will be executed instead, preventing the entire workflow from failing.
|
|
77
78
|
|
|
78
79
|
For more granular control, you can implement a node using the `BaseNode` class, which provides `prep`, `exec`, `post`, `fallback`, and `recover` lifecycle methods.
|
|
79
80
|
|
|
@@ -81,19 +82,19 @@ For more granular control, you can implement a node using the `BaseNode` class,
|
|
|
81
82
|
|
|
82
83
|
Flowcraft includes tools to help you validate and visualize your workflows.
|
|
83
84
|
|
|
84
|
-
-
|
|
85
|
-
-
|
|
86
|
-
-
|
|
85
|
+
- **Linter (`lintBlueprint`)**: Statically analyze a blueprint to find common errors, such as orphan nodes, invalid edges, or nodes with missing implementations.
|
|
86
|
+
- **Analysis (`analyzeBlueprint`)**: Programmatically inspect a blueprint to detect cycles, find start/terminal nodes, and get other graph metrics.
|
|
87
|
+
- **Diagram Generation (`generateMermaid`)**: Automatically generate a [Mermaid](https://mermaid-js.github.io/mermaid/#/) syntax string from a blueprint to easily visualize your workflow's structure.
|
|
87
88
|
|
|
88
89
|
## Extensibility and Customization
|
|
89
90
|
|
|
90
91
|
The `FlowRuntime` can be configured with pluggable components to tailor its behavior to your specific needs:
|
|
91
92
|
|
|
92
|
-
-
|
|
93
|
-
-
|
|
94
|
-
-
|
|
95
|
-
-
|
|
96
|
-
-
|
|
93
|
+
- **Logger**: Provide a custom `ILogger` implementation (e.g., Pino, Winston) to integrate with your existing logging infrastructure.
|
|
94
|
+
- **Serializer**: Replace the default `JsonSerializer` with a more robust one (e.g., `superjson`) to handle complex data types like `Date`, `Map`, and `Set` in the workflow context.
|
|
95
|
+
- **Evaluator**: Swap the default `PropertyEvaluator` for a more powerful expression engine (like `jsep` or `govaluate`) to enable complex logic in edge conditions. For trusted environments, an `UnsafeEvaluator` is also available.
|
|
96
|
+
- **Middleware**: Wrap node execution with custom logic for cross-cutting concerns like distributed tracing, performance monitoring, or advanced authorization.
|
|
97
|
+
- **Event Bus**: An event emitter for monitoring workflow and node lifecycle events (`workflow:start`, `node:finish`, etc.).
|
|
97
98
|
|
|
98
99
|
## Distributed Execution
|
|
99
100
|
|
|
@@ -285,6 +285,7 @@ declare class FlowRuntime<TContext extends Record<string, any>, TDependencies ex
|
|
|
285
285
|
private readonly executorFactory;
|
|
286
286
|
scheduler: WorkflowScheduler;
|
|
287
287
|
getBlueprint(id: string): WorkflowBlueprint | undefined;
|
|
288
|
+
constructor();
|
|
288
289
|
constructor(container: DIContainer, options?: RuntimeOptions<TDependencies>);
|
|
289
290
|
constructor(options: RuntimeOptions<TDependencies>);
|
|
290
291
|
private _setupExecutionContext;
|
|
@@ -1322,4 +1323,4 @@ declare class JsonSerializer implements ISerializer {
|
|
|
1322
1323
|
}
|
|
1323
1324
|
//#endregion
|
|
1324
1325
|
export { NodeConfig as $, TrackedAsyncContext as A, DIContainer as At, InMemoryEventStore as B, FlowBuilder as C, ClassNodeExecutor as Ct, createErrorMapper as D, NodeExecutor as Dt, UnsafeEvaluator as E, NodeExecutionResult as Et, analyzeBlueprint as F, FlowcraftError as Ft, IAsyncContext as G, ContextImplementation as H, checkForCycles as I, ILogger as J, IEvaluator as K, generateMermaid as L, createDefaultContainer as M, ServiceTokens as Mt, BlueprintAnalysis as N, BaseNode as Nt, AsyncContextView as O, NodeExecutorConfig as Ot, Cycles as P, isNodeClass as Pt, NodeClass as Q, generateMermaidForRun as R, lintBlueprint as S, ReadyNode as St, PropertyEvaluator as T, FunctionNodeExecutor as Tt, EdgeDefinition as U, PersistentEventBusAdapter as V, FlowcraftEvent as W, ISyncContext as X, ISerializer as Y, Middleware as Z, ConsoleLogger as _, ExecutionServices as _t, ReplayOrchestrator as a, NodeResult as at, LinterIssueCode as b, NodeExecutorFactory as bt, BaseDistributedAdapter as c, RuntimeOptions as ct, WebhookNode as d, WorkflowBlueprint as dt, NodeContext as et, WaitNode as f, WorkflowBlueprintMetadata as ft, BatchGatherNode as g, FlowRuntime as gt, BatchScatterNode as h, WorkflowStatus as ht, processResults as i, NodeRegistry as it, ContainerOptions as j, ServiceToken as jt, Context as k, WorkflowState as kt, ICoordinationStore as l, SourceLocation as lt, SleepNode as m, WorkflowResult as mt, sanitizeBlueprint as n, NodeFunction as nt, DefaultOrchestrator as o, PatchOperation as ot, SubflowNode as p, WorkflowError as pt, IEventBus as q, executeBatch as r, NodeImplementation as rt, AdapterOptions as s, RuntimeDependencies as st, JsonSerializer as t, NodeDefinition as tt, JobPayload as u, UIGraph as ut, NullLogger as v, IOrchestrator as vt, createFlow as w, ExecutionStrategy as wt, LinterResult as x, GraphTraverser as xt, LinterIssue as y, IRuntime as yt, IEventStore as z };
|
|
1325
|
-
//# sourceMappingURL=index-
|
|
1326
|
+
//# sourceMappingURL=index-DUPpyNvU.d.mts.map
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as NodeConfig, A as TrackedAsyncContext, At as DIContainer, B as InMemoryEventStore, C as FlowBuilder, Ct as ClassNodeExecutor, D as createErrorMapper, Dt as NodeExecutor, E as UnsafeEvaluator, Et as NodeExecutionResult, F as analyzeBlueprint, Ft as FlowcraftError, G as IAsyncContext, H as ContextImplementation, I as checkForCycles, J as ILogger, K as IEvaluator, L as generateMermaid, M as createDefaultContainer, Mt as ServiceTokens, N as BlueprintAnalysis, Nt as BaseNode, O as AsyncContextView, Ot as NodeExecutorConfig, P as Cycles, Pt as isNodeClass, Q as NodeClass, R as generateMermaidForRun, S as lintBlueprint, St as ReadyNode, T as PropertyEvaluator, Tt as FunctionNodeExecutor, U as EdgeDefinition, V as PersistentEventBusAdapter, W as FlowcraftEvent, X as ISyncContext, Y as ISerializer, Z as Middleware, _ as ConsoleLogger, _t as ExecutionServices, a as ReplayOrchestrator, at as NodeResult, b as LinterIssueCode, bt as NodeExecutorFactory, c as BaseDistributedAdapter, ct as RuntimeOptions, d as WebhookNode, dt as WorkflowBlueprint, et as NodeContext, f as WaitNode, ft as WorkflowBlueprintMetadata, g as BatchGatherNode, gt as FlowRuntime, h as BatchScatterNode, ht as WorkflowStatus, i as processResults, it as NodeRegistry, j as ContainerOptions, jt as ServiceToken, k as Context, kt as WorkflowState, l as ICoordinationStore, lt as SourceLocation, m as SleepNode, mt as WorkflowResult, n as sanitizeBlueprint, nt as NodeFunction, o as DefaultOrchestrator, ot as PatchOperation, p as SubflowNode, pt as WorkflowError, q as IEventBus, r as executeBatch, rt as NodeImplementation, s as AdapterOptions, st as RuntimeDependencies, t as JsonSerializer, tt as NodeDefinition, u as JobPayload, ut as UIGraph, v as NullLogger, vt as IOrchestrator, w as createFlow, wt as ExecutionStrategy, x as LinterResult, xt as GraphTraverser, y as LinterIssue, yt as IRuntime, z as IEventStore } from "./index-
|
|
1
|
+
import { $ as NodeConfig, A as TrackedAsyncContext, At as DIContainer, B as InMemoryEventStore, C as FlowBuilder, Ct as ClassNodeExecutor, D as createErrorMapper, Dt as NodeExecutor, E as UnsafeEvaluator, Et as NodeExecutionResult, F as analyzeBlueprint, Ft as FlowcraftError, G as IAsyncContext, H as ContextImplementation, I as checkForCycles, J as ILogger, K as IEvaluator, L as generateMermaid, M as createDefaultContainer, Mt as ServiceTokens, N as BlueprintAnalysis, Nt as BaseNode, O as AsyncContextView, Ot as NodeExecutorConfig, P as Cycles, Pt as isNodeClass, Q as NodeClass, R as generateMermaidForRun, S as lintBlueprint, St as ReadyNode, T as PropertyEvaluator, Tt as FunctionNodeExecutor, U as EdgeDefinition, V as PersistentEventBusAdapter, W as FlowcraftEvent, X as ISyncContext, Y as ISerializer, Z as Middleware, _ as ConsoleLogger, _t as ExecutionServices, a as ReplayOrchestrator, at as NodeResult, b as LinterIssueCode, bt as NodeExecutorFactory, c as BaseDistributedAdapter, ct as RuntimeOptions, d as WebhookNode, dt as WorkflowBlueprint, et as NodeContext, f as WaitNode, ft as WorkflowBlueprintMetadata, g as BatchGatherNode, gt as FlowRuntime, h as BatchScatterNode, ht as WorkflowStatus, i as processResults, it as NodeRegistry, j as ContainerOptions, jt as ServiceToken, k as Context, kt as WorkflowState, l as ICoordinationStore, lt as SourceLocation, m as SleepNode, mt as WorkflowResult, n as sanitizeBlueprint, nt as NodeFunction, o as DefaultOrchestrator, ot as PatchOperation, p as SubflowNode, pt as WorkflowError, q as IEventBus, r as executeBatch, rt as NodeImplementation, s as AdapterOptions, st as RuntimeDependencies, t as JsonSerializer, tt as NodeDefinition, u as JobPayload, ut as UIGraph, v as NullLogger, vt as IOrchestrator, w as createFlow, wt as ExecutionStrategy, x as LinterResult, xt as GraphTraverser, y as LinterIssue, yt as IRuntime, z as IEventStore } from "./index-DUPpyNvU.mjs";
|
|
2
2
|
export { AdapterOptions, AsyncContextView, BaseDistributedAdapter, BaseNode, BatchGatherNode, BatchScatterNode, BlueprintAnalysis, ClassNodeExecutor, ConsoleLogger, ContainerOptions, Context, ContextImplementation, Cycles, DIContainer, DefaultOrchestrator, EdgeDefinition, ExecutionServices, ExecutionStrategy, FlowBuilder, FlowRuntime, FlowcraftError, FlowcraftEvent, FunctionNodeExecutor, GraphTraverser, IAsyncContext, ICoordinationStore, IEvaluator, IEventBus, IEventStore, ILogger, IOrchestrator, IRuntime, ISerializer, ISyncContext, InMemoryEventStore, JobPayload, JsonSerializer, LinterIssue, LinterIssueCode, LinterResult, Middleware, NodeClass, NodeConfig, NodeContext, NodeDefinition, NodeExecutionResult, NodeExecutor, NodeExecutorConfig, NodeExecutorFactory, NodeFunction, NodeImplementation, NodeRegistry, NodeResult, NullLogger, PatchOperation, PersistentEventBusAdapter, PropertyEvaluator, ReadyNode, ReplayOrchestrator, RuntimeDependencies, RuntimeOptions, ServiceToken, ServiceTokens, SleepNode, SourceLocation, SubflowNode, TrackedAsyncContext, UIGraph, UnsafeEvaluator, WaitNode, WebhookNode, WorkflowBlueprint, WorkflowBlueprintMetadata, WorkflowError, WorkflowResult, WorkflowState, WorkflowStatus, analyzeBlueprint, checkForCycles, createDefaultContainer, createErrorMapper, createFlow, executeBatch, generateMermaid, generateMermaidForRun, isNodeClass, lintBlueprint, processResults, sanitizeBlueprint };
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as ReplayOrchestrator } from "./replay-BB11M6K1.mjs";
|
|
2
|
-
import { A as ServiceTokens, C as TrackedAsyncContext, D as PropertyEvaluator, E as NullLogger, F as InMemoryEventStore, I as PersistentEventBusAdapter, M as checkForCycles, N as generateMermaid, O as UnsafeEvaluator, P as generateMermaidForRun, S as Context, T as ConsoleLogger, _ as executeBatch, a as sanitizeBlueprint, b as WorkflowState, c as SubflowNode, d as BatchScatterNode, f as BatchGatherNode, g as DefaultOrchestrator, h as JsonSerializer, i as NodeExecutor, j as analyzeBlueprint, k as DIContainer, l as GraphTraverser, m as isNodeClass, n as ClassNodeExecutor, o as WebhookNode, p as BaseNode, r as FunctionNodeExecutor, s as WaitNode, t as FlowRuntime, u as SleepNode, v as processResults, w as FlowcraftError, x as AsyncContextView } from "./runtime-
|
|
2
|
+
import { A as ServiceTokens, C as TrackedAsyncContext, D as PropertyEvaluator, E as NullLogger, F as InMemoryEventStore, I as PersistentEventBusAdapter, M as checkForCycles, N as generateMermaid, O as UnsafeEvaluator, P as generateMermaidForRun, S as Context, T as ConsoleLogger, _ as executeBatch, a as sanitizeBlueprint, b as WorkflowState, c as SubflowNode, d as BatchScatterNode, f as BatchGatherNode, g as DefaultOrchestrator, h as JsonSerializer, i as NodeExecutor, j as analyzeBlueprint, k as DIContainer, l as GraphTraverser, m as isNodeClass, n as ClassNodeExecutor, o as WebhookNode, p as BaseNode, r as FunctionNodeExecutor, s as WaitNode, t as FlowRuntime, u as SleepNode, v as processResults, w as FlowcraftError, x as AsyncContextView } from "./runtime-CRwlRW2p.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/container-factory.ts
|
|
5
5
|
function createDefaultContainer(options = {}) {
|
|
@@ -432,7 +432,7 @@ function lintBlueprint(blueprint, registry, blueprints) {
|
|
|
432
432
|
if (!currentId || visited.has(currentId)) continue;
|
|
433
433
|
visited.add(currentId);
|
|
434
434
|
connectedNodes.add(currentId);
|
|
435
|
-
for (const
|
|
435
|
+
for (const targetEdge of blueprint.edges.filter((e) => e.source === currentId)) nodesToVisit.push(targetEdge.target);
|
|
436
436
|
}
|
|
437
437
|
for (const nodeId of nodeIds) if (!connectedNodes.has(nodeId)) issues.push({
|
|
438
438
|
code: "ORPHAN_NODE",
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/container-factory.ts","../src/error-mapper.ts","../src/flow.ts","../src/linter.ts","../src/runtime/adapter.ts"],"sourcesContent":["import { DIContainer, ServiceTokens } from './container'\nimport { PropertyEvaluator } from './evaluator'\nimport { NullLogger } from './logger'\nimport { DefaultOrchestrator } from './runtime/orchestrator'\nimport { JsonSerializer } from './serializer'\nimport type {\n\tIEvaluator,\n\tIEventBus,\n\tILogger,\n\tISerializer,\n\tMiddleware,\n\tNodeClass,\n\tNodeFunction,\n\tRuntimeDependencies,\n\tWorkflowBlueprint,\n} from './types'\n\nexport interface ContainerOptions<TDependencies extends RuntimeDependencies = RuntimeDependencies> {\n\tlogger?: ILogger\n\tserializer?: ISerializer\n\tevaluator?: IEvaluator\n\teventBus?: IEventBus\n\tmiddleware?: Middleware[]\n\tregistry?: Record<string, NodeFunction | NodeClass>\n\tblueprints?: Record<string, WorkflowBlueprint>\n\tdependencies?: TDependencies\n}\n\nexport function createDefaultContainer<TDependencies extends RuntimeDependencies = RuntimeDependencies>(\n\toptions: ContainerOptions<TDependencies> = {},\n): DIContainer {\n\tconst container = new DIContainer()\n\n\tcontainer.register(ServiceTokens.Logger, options.logger || new NullLogger())\n\tcontainer.register(ServiceTokens.Serializer, options.serializer || new JsonSerializer())\n\tcontainer.register(ServiceTokens.Evaluator, options.evaluator || new PropertyEvaluator())\n\tcontainer.register(ServiceTokens.EventBus, options.eventBus || { emit: async () => {} })\n\tcontainer.register(ServiceTokens.Middleware, options.middleware || [])\n\tcontainer.register(ServiceTokens.NodeRegistry, options.registry || {})\n\tcontainer.register(ServiceTokens.BlueprintRegistry, options.blueprints || {})\n\tcontainer.register(ServiceTokens.Dependencies, options.dependencies || ({} as TDependencies))\n\n\tcontainer.registerFactory(ServiceTokens.Orchestrator, () => new DefaultOrchestrator())\n\n\treturn container\n}\n","import { FlowcraftError } from './errors'\nimport type { SourceLocation, WorkflowBlueprint } from './types'\n\n/**\n * Creates an error mapper function that enhances runtime errors with source location information.\n * The mapper looks up node IDs in the provided manifest blueprints and returns enhanced errors\n * that point to the original TypeScript source code.\n *\n * @param manifestBlueprints - The compiled blueprint manifest containing source location data\n * @returns A function that maps errors to enhanced errors with source location information\n */\nexport function createErrorMapper(manifestBlueprints: Record<string, WorkflowBlueprint>) {\n\tconst locationMap = new Map<string, SourceLocation>()\n\n\t// build a quick lookup map\n\tfor (const blueprint of Object.values(manifestBlueprints)) {\n\t\tfor (const node of blueprint.nodes) {\n\t\t\tif (node._sourceLocation) {\n\t\t\t\tlocationMap.set(node.id, node._sourceLocation)\n\t\t\t}\n\t\t}\n\t\tfor (const edge of blueprint.edges) {\n\t\t\tif (edge._sourceLocation) {\n\t\t\t\tconst edgeKey = `${edge.source}-${edge.target}`\n\t\t\t\tlocationMap.set(edgeKey, edge._sourceLocation)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn function mapError(error: Error): Error {\n\t\tif (error instanceof FlowcraftError && error.nodeId) {\n\t\t\tconst location = locationMap.get(error.nodeId)\n\t\t\tif (location) {\n\t\t\t\treturn new Error(\n\t\t\t\t\t`Workflow error at ${location.file}:${location.line}:${location.column}. Original error: ${error.message}`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// try to extract nodeId from error message\n\t\tconst nodeIdMatch = error.message.match(/nodeId[:\\s]+([^\\s,]+)/i)\n\t\tif (nodeIdMatch) {\n\t\t\tconst nodeId = nodeIdMatch[1]\n\t\t\tconst location = locationMap.get(nodeId)\n\t\t\tif (location) {\n\t\t\t\treturn new Error(\n\t\t\t\t\t`Workflow error at ${location.file}:${location.line}:${location.column}. Original error: ${error.message}`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\treturn error\n\t}\n}\n","import { isNodeClass } from './node'\nimport type { FlowRuntime } from './runtime/runtime'\nimport type {\n\tEdgeDefinition,\n\tNodeClass,\n\tNodeDefinition,\n\tNodeFunction,\n\tUIGraph,\n\tWorkflowBlueprint,\n\tWorkflowResult,\n} from './types'\n\n/**\n * Generates a deterministic hash for a function based on its source code and a unique counter.\n */\nlet hashCounter = 0\nfunction _hashFunction(fn: NodeFunction<any, any, any, any, any> | NodeClass<any, any, any, any, any>): string {\n\tconst source = fn.toString()\n\tlet hash = 0\n\tfor (let i = 0; i < source.length; i++) {\n\t\tconst char = source.charCodeAt(i)\n\t\thash = (hash << 5) - hash + char\n\t\thash = hash & hash // Convert to 32-bit integer\n\t}\n\t// Add counter to ensure uniqueness even for identical functions\n\treturn (Math.abs(hash) + hashCounter++).toString(16)\n}\n\n/**\n * A fluent API for programmatically constructing a WorkflowBlueprint.\n */\nexport class FlowBuilder<\n\tTContext extends Record<string, any> = Record<string, any>,\n\tTDependencies extends Record<string, any> = Record<string, any>,\n> {\n\tprivate blueprint: Partial<WorkflowBlueprint>\n\tprivate functionRegistry: Map<string, NodeFunction | NodeClass>\n\tprivate loopDefinitions: Array<{\n\t\tid: string\n\t\tstartNodeId: string\n\t\tendNodeId: string\n\t\tcondition: string\n\t}>\n\tprivate batchDefinitions: Array<{\n\t\tid: string\n\t\tscatterId: string\n\t\tgatherId: string\n\t}>\n\tprivate cycleEntryPoints: Map<string, string>\n\n\tconstructor(id: string) {\n\t\tthis.blueprint = { id, nodes: [], edges: [] }\n\t\tthis.functionRegistry = new Map()\n\t\tthis.loopDefinitions = []\n\t\tthis.batchDefinitions = []\n\t\tthis.cycleEntryPoints = new Map()\n\t}\n\n\tnode<TInput = any, TOutput = any, TAction extends string = string>(\n\t\tid: string,\n\t\timplementation:\n\t\t\t| NodeFunction<TContext, TDependencies, TInput, TOutput, TAction>\n\t\t\t| NodeClass<TContext, TDependencies, TInput, TOutput, TAction>,\n\t\toptions?: Omit<NodeDefinition, 'id' | 'uses'>,\n\t): this {\n\t\tlet usesKey: string\n\n\t\tif (isNodeClass(implementation)) {\n\t\t\tusesKey =\n\t\t\t\timplementation.name && implementation.name !== 'BaseNode'\n\t\t\t\t\t? implementation.name\n\t\t\t\t\t: `class_${_hashFunction(implementation)}`\n\t\t\tthis.functionRegistry.set(usesKey, implementation)\n\t\t} else {\n\t\t\tusesKey = `fn_${_hashFunction(implementation)}`\n\t\t\tthis.functionRegistry.set(usesKey, implementation as unknown as NodeFunction)\n\t\t}\n\n\t\tconst nodeDef: NodeDefinition = { id, uses: usesKey, ...options }\n\t\tthis.blueprint.nodes?.push(nodeDef)\n\t\treturn this\n\t}\n\n\tedge(source: string, target: string, options?: Omit<EdgeDefinition, 'source' | 'target'>): this {\n\t\tconst edgeDef: EdgeDefinition = { source, target, ...options }\n\t\tthis.blueprint.edges?.push(edgeDef)\n\t\treturn this\n\t}\n\n\t/**\n\t * Creates a batch processing pattern.\n\t * It takes an input array, runs a worker node on each item in parallel, and gathers the results.\n\t * This method augments the Flow's TContext with a new key for the output array.\n\t *\n\t * @param id The base ID for this batch operation.\n\t * @param worker The node implementation to run on each item.\n\t * @param options Configuration for the batch operation.\n\t * @returns The Flow instance with an updated context type for chaining.\n\t */\n\tbatch<TWorkerInput, TWorkerOutput, TWorkerAction extends string, TOutputKey extends string>(\n\t\tid: string,\n\t\tworker:\n\t\t\t| NodeFunction<TContext, TDependencies, TWorkerInput, TWorkerOutput, TWorkerAction>\n\t\t\t| NodeClass<TContext, TDependencies, TWorkerInput, TWorkerOutput, TWorkerAction>,\n\t\toptions: {\n\t\t\t/** The key in the context that holds the input array for the batch. */\n\t\t\tinputKey: keyof TContext\n\t\t\t/** The key in the context where the array of results will be stored. */\n\t\t\toutputKey: TOutputKey\n\t\t\t/** The number of items to process in each chunk to limit memory usage. */\n\t\t\tchunkSize?: number\n\t\t},\n\t): FlowBuilder<TContext & { [K in TOutputKey]: TWorkerOutput[] }, TDependencies> {\n\t\tconst { inputKey, outputKey } = options\n\t\tconst scatterId = `${id}_scatter`\n\t\tconst gatherId = `${id}_gather`\n\n\t\tthis.batchDefinitions.push({ id, scatterId, gatherId })\n\n\t\tlet workerUsesKey: string\n\t\tif (isNodeClass(worker)) {\n\t\t\tworkerUsesKey =\n\t\t\t\tworker.name && worker.name !== 'BaseNode' ? worker.name : `class_batch_worker_${_hashFunction(worker)}`\n\t\t\tthis.functionRegistry.set(workerUsesKey, worker)\n\t\t} else {\n\t\t\tworkerUsesKey = `fn_batch_worker_${_hashFunction(worker)}`\n\t\t\tthis.functionRegistry.set(workerUsesKey, worker as unknown as NodeFunction)\n\t\t}\n\n\t\tthis.blueprint.nodes?.push({\n\t\t\tid: scatterId,\n\t\t\tuses: 'batch-scatter',\n\t\t\tinputs: inputKey as string,\n\t\t\tparams: { workerUsesKey, outputKey: outputKey as string, gatherNodeId: gatherId, chunkSize: options.chunkSize },\n\t\t})\n\n\t\tthis.blueprint.nodes?.push({\n\t\t\tid: gatherId,\n\t\t\tuses: 'batch-gather',\n\t\t\tparams: { outputKey, gatherNodeId: gatherId },\n\t\t\tconfig: { joinStrategy: 'all' },\n\t\t})\n\n\t\tthis.edge(scatterId, gatherId)\n\n\t\treturn this as unknown as FlowBuilder<TContext & { [K in TOutputKey]: TWorkerOutput[] }, TDependencies>\n\t}\n\n\t/**\n\t * Creates a sleep node that pauses workflow execution for a specified duration.\n\t * @param id A unique identifier for the sleep node.\n\t * @param options Configuration for the sleep duration.\n\t */\n\tsleep(\n\t\tid: string,\n\t\toptions: {\n\t\t\t/** The duration to sleep in milliseconds or a string like '5s', '1m', '2h', '1d'. */\n\t\t\tduration: number | string\n\t\t},\n\t): this {\n\t\tconst nodeDef: NodeDefinition = {\n\t\t\tid,\n\t\t\tuses: 'sleep',\n\t\t\tparams: { duration: options.duration },\n\t\t}\n\t\tthis.blueprint.nodes?.push(nodeDef)\n\t\treturn this\n\t}\n\n\t/**\n\t * Creates a wait node that pauses workflow execution for external input.\n\t * @param id A unique identifier for the wait node.\n\t * @param options Optional configuration for the wait node.\n\t */\n\twait(id: string, options?: Omit<NodeDefinition, 'id' | 'uses'>): this {\n\t\tconst nodeDef: NodeDefinition = { id, uses: 'wait', ...options }\n\t\tthis.blueprint.nodes?.push(nodeDef)\n\t\treturn this\n\t}\n\n\t/**\n\t * Creates a loop pattern in the workflow graph.\n\t * @param id A unique identifier for the loop construct.\n\t * @param options Defines the start, end, and continuation condition of the loop.\n\t * @param options.startNodeId The ID of the first node inside the loop body.\n\t * @param options.endNodeId The ID of the last node inside the loop body.\n\t * @param options.condition An expression that, if true, causes the loop to run again.\n\t */\n\tloop(\n\t\tid: string,\n\t\toptions: {\n\t\t\t/** The ID of the first node inside the loop body. */\n\t\t\tstartNodeId: string\n\t\t\t/** The ID of the last node inside the loop body. */\n\t\t\tendNodeId: string\n\t\t\t/** An expression that, if true, causes the loop to run again. */\n\t\t\tcondition: string\n\t\t},\n\t): this {\n\t\tconst { startNodeId, endNodeId, condition } = options\n\t\tthis.loopDefinitions.push({ id, startNodeId, endNodeId, condition })\n\n\t\tthis.blueprint.nodes?.push({\n\t\t\tid,\n\t\t\tuses: 'loop-controller',\n\t\t\tparams: { condition },\n\t\t\tconfig: { joinStrategy: 'any' },\n\t\t})\n\n\t\tthis.edge(endNodeId, id)\n\t\tthis.edge(id, startNodeId, {\n\t\t\taction: 'continue',\n\t\t\ttransform: `context.${endNodeId}`,\n\t\t})\n\n\t\treturn this\n\t}\n\n\t/**\n\t * Sets the preferred entry point for a cycle in non-DAG workflows.\n\t * This helps remove ambiguity when the runtime needs to choose a starting node for cycles.\n\t * @param nodeId The ID of the node to use as the entry point for cycles containing this node.\n\t */\n\tsetCycleEntryPoint(nodeId: string): this {\n\t\tthis.cycleEntryPoints.set(nodeId, nodeId)\n\t\treturn this\n\t}\n\n\ttoBlueprint(): WorkflowBlueprint {\n\t\tif (!this.blueprint.nodes || this.blueprint.nodes.length === 0) {\n\t\t\tthrow new Error('Cannot build a blueprint with no nodes.')\n\t\t}\n\t\tconst finalEdges: EdgeDefinition[] = []\n\t\tconst processedOriginalEdges = new Set<EdgeDefinition>()\n\t\tconst allOriginalEdges = this.blueprint.edges || []\n\n\t\t// loop edge re-wiring\n\t\tfor (const loopDef of this.loopDefinitions) {\n\t\t\tconst edgesToRewire = allOriginalEdges.filter((e) => e.source === loopDef.id && e.target !== loopDef.startNodeId)\n\t\t\tfor (const edge of edgesToRewire) {\n\t\t\t\tfinalEdges.push({ ...edge, action: edge.action || 'break', transform: `context.${loopDef.endNodeId}` })\n\t\t\t\tprocessedOriginalEdges.add(edge)\n\t\t\t}\n\t\t}\n\n\t\t// batch edge re-wiring\n\t\tfor (const batchDef of this.batchDefinitions) {\n\t\t\tconst incomingEdges = allOriginalEdges.filter((e) => e.target === batchDef.id)\n\t\t\tfor (const edge of incomingEdges) {\n\t\t\t\tfinalEdges.push({ ...edge, target: batchDef.scatterId })\n\t\t\t\tprocessedOriginalEdges.add(edge)\n\t\t\t}\n\n\t\t\tconst outgoingEdges = allOriginalEdges.filter((e) => e.source === batchDef.id)\n\t\t\tfor (const edge of outgoingEdges) {\n\t\t\t\tfinalEdges.push({ ...edge, source: batchDef.gatherId })\n\t\t\t\tprocessedOriginalEdges.add(edge)\n\t\t\t}\n\t\t}\n\n\t\t// all remaining edges\n\t\tfor (const edge of allOriginalEdges) {\n\t\t\tif (!processedOriginalEdges.has(edge)) {\n\t\t\t\tfinalEdges.push(edge)\n\t\t\t}\n\t\t}\n\t\tthis.blueprint.edges = finalEdges\n\n\t\tfor (const loopDef of this.loopDefinitions) {\n\t\t\tconst startNode = this.blueprint.nodes?.find((n) => n.id === loopDef.startNodeId)\n\t\t\tconst endNode = this.blueprint.nodes?.find((n) => n.id === loopDef.endNodeId)\n\n\t\t\tif (!startNode) {\n\t\t\t\tthrow new Error(`Loop '${loopDef.id}' references non-existent start node '${loopDef.startNodeId}'.`)\n\t\t\t}\n\t\t\tif (!endNode) {\n\t\t\t\tthrow new Error(`Loop '${loopDef.id}' references non-existent end node '${loopDef.endNodeId}'.`)\n\t\t\t}\n\t\t}\n\n\t\tif (this.cycleEntryPoints.size > 0) {\n\t\t\tthis.blueprint.metadata = {\n\t\t\t\t...this.blueprint.metadata,\n\t\t\t\tcycleEntryPoints: Array.from(this.cycleEntryPoints.keys()),\n\t\t\t}\n\t\t}\n\n\t\treturn this.blueprint as WorkflowBlueprint\n\t}\n\n\tgetFunctionRegistry() {\n\t\treturn this.functionRegistry\n\t}\n\n\t/**\n\t * Runs this flow on the given runtime, automatically passing the function registry.\n\t * Convenience wrapper around `runtime.run(blueprint, initialState, { functionRegistry })`.\n\t */\n\tasync run(\n\t\truntime: FlowRuntime<TContext, TDependencies>,\n\t\tinitialState: Partial<TContext> | string = {},\n\t\toptions?: {\n\t\t\tstrict?: boolean\n\t\t\tsignal?: AbortSignal\n\t\t\tconcurrency?: number\n\t\t},\n\t): Promise<WorkflowResult<TContext>> {\n\t\treturn runtime.run(this.toBlueprint(), initialState, {\n\t\t\t...options,\n\t\t\tfunctionRegistry: this.functionRegistry,\n\t\t})\n\t}\n\n\t/**\n\t * Resumes this flow on the given runtime, automatically passing the function registry.\n\t * Convenience wrapper around `runtime.resume(blueprint, ...)`.\n\t */\n\tasync resume(\n\t\truntime: FlowRuntime<TContext, TDependencies>,\n\t\tserializedContext: string,\n\t\tresumeData: { output?: any; action?: string },\n\t\tnodeId?: string,\n\t\toptions?: {\n\t\t\tstrict?: boolean\n\t\t\tsignal?: AbortSignal\n\t\t\tconcurrency?: number\n\t\t},\n\t): Promise<WorkflowResult<TContext>> {\n\t\treturn runtime.resume(this.toBlueprint(), serializedContext, resumeData, nodeId, {\n\t\t\t...options,\n\t\t\tfunctionRegistry: this.functionRegistry,\n\t\t})\n\t}\n\n\ttoGraphRepresentation(): UIGraph {\n\t\tconst blueprint = this.toBlueprint()\n\t\tconst uiNodes: UIGraph['nodes'] = []\n\t\tconst uiEdges: UIGraph['edges'] = []\n\n\t\tconst ignoredNodeIds = new Set<string>()\n\n\t\t// replace loop-controllers with direct, cyclical edges\n\t\tfor (const loopDef of this.loopDefinitions) {\n\t\t\tconst id = loopDef.id\n\t\t\tignoredNodeIds.add(id)\n\n\t\t\t// direct edge from the end of loop to start\n\t\t\tuiEdges.push({\n\t\t\t\tsource: loopDef.endNodeId,\n\t\t\t\ttarget: loopDef.startNodeId,\n\t\t\t\tdata: {\n\t\t\t\t\tisLoopback: true,\n\t\t\t\t\tcondition: loopDef.condition,\n\t\t\t\t\tlabel: `continue if: ${loopDef.condition}`,\n\t\t\t\t},\n\t\t\t})\n\n\t\t\t// re-wire any 'break' edges\n\t\t\tconst breakEdges = blueprint.edges.filter((edge) => edge.source === id && edge.action === 'break')\n\t\t\tfor (const breakEdge of breakEdges) {\n\t\t\t\tuiEdges.push({\n\t\t\t\t\t...breakEdge,\n\t\t\t\t\tsource: loopDef.endNodeId,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// re-wire any 'incoming' edges\n\t\t\tconst incomingEdges = blueprint.edges.filter((edge) => edge.target === id && edge.source !== loopDef.endNodeId)\n\t\t\tfor (const incomingEdge of incomingEdges) {\n\t\t\t\tuiEdges.push({\n\t\t\t\t\t...incomingEdge,\n\t\t\t\t\tsource: loopDef.startNodeId,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// replace scatter/gather pairs with a single representative worker node\n\t\tconst scatterNodes = blueprint.nodes.filter((n) => n.uses === 'batch-scatter')\n\t\tfor (const scatterNode of scatterNodes) {\n\t\t\tconst gatherNodeId = scatterNode.params?.gatherNodeId\n\t\t\tif (!gatherNodeId) continue\n\n\t\t\tignoredNodeIds.add(scatterNode.id)\n\t\t\tignoredNodeIds.add(gatherNodeId)\n\n\t\t\t// single node to represent parallel work\n\t\t\tconst batchId = scatterNode.id.replace('_scatter', '')\n\t\t\tconst gatherNode = blueprint.nodes.find((n) => n.id === gatherNodeId)\n\n\t\t\tuiNodes.push({\n\t\t\t\tid: batchId,\n\t\t\t\tuses: scatterNode.params?.workerUsesKey,\n\t\t\t\ttype: 'batch-worker',\n\t\t\t\tdata: {\n\t\t\t\t\tlabel: `Batch: ${batchId}`,\n\t\t\t\t\tisBatchPlaceholder: true,\n\t\t\t\t\tworkerUsesKey: scatterNode.params?.workerUsesKey,\n\t\t\t\t\tinputKey: scatterNode.inputs,\n\t\t\t\t\toutputKey: gatherNode?.params?.outputKey,\n\t\t\t\t},\n\t\t\t})\n\n\t\t\t// re-wire incoming edges\n\t\t\tconst incomingEdges = blueprint.edges.filter((e) => e.target === scatterNode.id)\n\t\t\tfor (const edge of incomingEdges) {\n\t\t\t\tuiEdges.push({ ...edge, target: batchId })\n\t\t\t}\n\n\t\t\t// re-wire outgoing edges\n\t\t\tconst outgoingEdges = blueprint.edges.filter((e) => e.source === gatherNodeId)\n\t\t\tfor (const edge of outgoingEdges) {\n\t\t\t\tuiEdges.push({ ...edge, source: batchId })\n\t\t\t}\n\t\t}\n\n\t\tfor (const node of blueprint.nodes) {\n\t\t\tif (!ignoredNodeIds.has(node.id)) {\n\t\t\t\tuiNodes.push(node)\n\t\t\t}\n\t\t}\n\n\t\tfor (const edge of blueprint.edges) {\n\t\t\tif (!ignoredNodeIds.has(edge.source) && !ignoredNodeIds.has(edge.target)) {\n\t\t\t\tconst alreadyAdded = uiEdges.some(\n\t\t\t\t\t(e) => e.source === edge.source && e.target === edge.target && e.action === edge.action,\n\t\t\t\t)\n\t\t\t\tif (!alreadyAdded) {\n\t\t\t\t\tuiEdges.push(edge)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { nodes: uiNodes, edges: uiEdges }\n\t}\n}\n\n/**\n * Helper function to create a new Flow builder instance.\n */\nexport function createFlow<\n\tTContext extends Record<string, any> = Record<string, any>,\n\tTDependencies extends Record<string, any> = Record<string, any>,\n>(id: string): FlowBuilder<TContext, TDependencies> {\n\treturn new FlowBuilder(id)\n}\n","import { analyzeBlueprint } from './analysis'\nimport type { NodeClass, NodeFunction, WorkflowBlueprint } from './types'\n\nexport type LinterIssueCode =\n\t| 'INVALID_EDGE_SOURCE'\n\t| 'INVALID_EDGE_TARGET'\n\t| 'MISSING_NODE_IMPLEMENTATION'\n\t| 'ORPHAN_NODE'\n\t| 'INVALID_BATCH_WORKER_KEY'\n\t| 'INVALID_SUBFLOW_BLUEPRINT_ID'\n\nexport interface LinterIssue {\n\tcode: LinterIssueCode\n\tmessage: string\n\tnodeId?: string\n\trelatedId?: string\n}\n\nexport interface LinterResult {\n\tisValid: boolean\n\tissues: LinterIssue[]\n}\n\n/**\n * Statically analyzes a workflow blueprint against a registry of implementations\n * to find common errors before runtime.\n *\n * @param blueprint The WorkflowBlueprint to analyze.\n * @param registry A map of node implementations (functions or classes) to check against.\n * @returns A LinterResult object containing any issues found.\n */\nexport function lintBlueprint(\n\tblueprint: WorkflowBlueprint,\n\tregistry: Map<string, NodeFunction | NodeClass> | Record<string, NodeFunction | NodeClass>,\n\tblueprints?: Record<string, WorkflowBlueprint>,\n): LinterResult {\n\tconst issues: LinterIssue[] = []\n\tconst nodeIds = new Set(blueprint.nodes.map((n) => n.id))\n\tconst registryKeys = registry instanceof Map ? new Set(registry.keys()) : new Set(Object.keys(registry))\n\n\t// check for missing node implementations\n\tfor (const node of blueprint.nodes) {\n\t\tif (!node.uses.startsWith('batch-') && !node.uses.startsWith('loop-') && !registryKeys.has(node.uses)) {\n\t\t\tissues.push({\n\t\t\t\tcode: 'MISSING_NODE_IMPLEMENTATION',\n\t\t\t\tmessage: `Node implementation key '${node.uses}' is not found in the provided registry.`,\n\t\t\t\tnodeId: node.id,\n\t\t\t})\n\t\t}\n\t}\n\n\t// check for dynamic node validation\n\tfor (const node of blueprint.nodes) {\n\t\tif (node.uses.startsWith('batch-') && node.params?.workerUsesKey) {\n\t\t\tif (!registryKeys.has(node.params.workerUsesKey)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: 'INVALID_BATCH_WORKER_KEY',\n\t\t\t\t\tmessage: `Batch node '${node.id}' references workerUsesKey '${node.params.workerUsesKey}' which is not found in the registry.`,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif (node.uses === 'subflow' && node.params?.blueprintId) {\n\t\t\tif (!blueprints?.[node.params.blueprintId]) {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: 'INVALID_SUBFLOW_BLUEPRINT_ID',\n\t\t\t\t\tmessage: `Subflow node '${node.id}' references blueprintId '${node.params.blueprintId}' which is not found in the blueprints registry.`,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\t// check for graph integrity (edges must point to valid nodes)\n\tfor (const edge of blueprint.edges || []) {\n\t\tif (!nodeIds.has(edge.source)) {\n\t\t\tissues.push({\n\t\t\t\tcode: 'INVALID_EDGE_SOURCE',\n\t\t\t\tmessage: `Edge source '${edge.source}' does not correspond to a valid node ID.`,\n\t\t\t\trelatedId: edge.target,\n\t\t\t})\n\t\t}\n\t\tif (!nodeIds.has(edge.target)) {\n\t\t\tissues.push({\n\t\t\t\tcode: 'INVALID_EDGE_TARGET',\n\t\t\t\tmessage: `Edge target '${edge.target}' does not correspond to a valid node ID.`,\n\t\t\t\trelatedId: edge.source,\n\t\t\t})\n\t\t}\n\t}\n\n\t// check for orphan nodes (not connected to the main graph)\n\tif (blueprint.nodes.length > 1) {\n\t\tconst analysis = analyzeBlueprint(blueprint)\n\t\tconst connectedNodes = new Set<string>()\n\t\tconst nodesToVisit = [...analysis.startNodeIds]\n\t\tconst visited = new Set<string>()\n\n\t\twhile (nodesToVisit.length > 0) {\n\t\t\tconst currentId = nodesToVisit.pop()\n\t\t\tif (!currentId || visited.has(currentId)) continue\n\n\t\t\tvisited.add(currentId)\n\t\t\tconnectedNodes.add(currentId)\n\n\t\t\tfor (const e of blueprint.edges.filter((e) => e.source === currentId)) {\n\t\t\t\tnodesToVisit.push(e.target)\n\t\t\t}\n\t\t}\n\n\t\tfor (const nodeId of nodeIds) {\n\t\t\tif (!connectedNodes.has(nodeId)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: 'ORPHAN_NODE',\n\t\t\t\t\tmessage: `Node '${nodeId}' is not reachable from any start node.`,\n\t\t\t\t\tnodeId,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tisValid: issues.length === 0,\n\t\tissues,\n\t}\n}\n","import { analyzeBlueprint } from '../analysis'\nimport { TrackedAsyncContext } from '../context'\nimport { ConsoleLogger } from '../logger'\nimport { JsonSerializer } from '../serializer'\nimport type {\n\tIAsyncContext,\n\tIEventBus,\n\tILogger,\n\tISerializer,\n\tNodeResult,\n\tRuntimeOptions,\n\tWorkflowBlueprint,\n\tWorkflowResult,\n} from '../types'\nimport { FlowRuntime } from './runtime'\nimport { WorkflowState } from './state'\n\n/**\n * Defines the contract for an atomic, distributed key-value store required by\n * the adapter for coordination tasks like fan-in joins and locking.\n */\nexport interface ICoordinationStore {\n\t/** Atomically increments a key and returns the new value. Ideal for 'all' joins. */\n\tincrement: (key: string, ttlSeconds: number) => Promise<number>\n\t/** Sets a key only if it does not already exist. Ideal for 'any' joins (locking). */\n\tsetIfNotExist: (key: string, value: string, ttlSeconds: number) => Promise<boolean>\n\t/** Extends the TTL of an existing key. Used for heartbeat mechanism in long-running jobs. */\n\textendTTL: (key: string, ttlSeconds: number) => Promise<boolean>\n\t/** Deletes a key. Used for cleanup. */\n\tdelete: (key: string) => Promise<void>\n\t/** Gets the value of a key. */\n\tget: (key: string) => Promise<string | undefined>\n}\n\n/** Configuration options for constructing a BaseDistributedAdapter. */\nexport interface AdapterOptions {\n\truntimeOptions: RuntimeOptions<any>\n\tcoordinationStore: ICoordinationStore\n\teventBus?: IEventBus\n}\n\n/** The data payload expected for a job in the queue. */\nexport interface JobPayload {\n\trunId: string\n\tblueprintId: string\n\tnodeId: string\n}\n\n/**\n * The base class for all distributed adapters. It handles the technology-agnostic\n * orchestration logic and leaves queue-specific implementation to subclasses.\n */\nexport abstract class BaseDistributedAdapter {\n\tprotected readonly runtime: FlowRuntime<any, any>\n\tprotected readonly store: ICoordinationStore\n\tprotected readonly serializer: ISerializer\n\tprotected readonly logger: ILogger\n\tprotected readonly eventBus?: IEventBus\n\n\tconstructor(options: AdapterOptions) {\n\t\tconst runtimeOptions = {\n\t\t\t...options.runtimeOptions,\n\t\t\tdependencies: {\n\t\t\t\t...options.runtimeOptions.dependencies,\n\t\t\t\tadapter: this,\n\t\t\t} as any,\n\t\t}\n\t\tthis.runtime = new FlowRuntime(runtimeOptions)\n\t\tthis.store = options.coordinationStore\n\t\tthis.serializer = options.runtimeOptions.serializer || new JsonSerializer()\n\t\tthis.logger = options.runtimeOptions.logger || new ConsoleLogger()\n\t\tthis.eventBus = options.eventBus\n\t\tthis.logger.info('[Adapter] BaseDistributedAdapter initialized.')\n\t}\n\n\t/**\n\t * Starts the worker, which begins listening for and processing jobs from the queue.\n\t */\n\tpublic start(): void {\n\t\tthis.logger.info('[Adapter] Starting worker...')\n\t\tthis.processJobs(this.handleJob.bind(this))\n\t}\n\n\t/**\n\t * Creates a technology-specific distributed context for a given workflow run.\n\t * @param runId The unique ID for the workflow execution.\n\t */\n\tprotected abstract createContext(runId: string): IAsyncContext<Record<string, any>>\n\t/**\n\t * Sets up the listener for the message queue. The implementation should call the\n\t * provided `handler` function for each new job received.\n\t * @param handler The core logic to execute for each job.\n\t */\n\tprotected abstract processJobs(handler: (job: JobPayload) => Promise<void>): void\n\n\t/**\n\t * Enqueues a new job onto the message queue.\n\t * @param job The payload for the job to be enqueued.\n\t */\n\tprotected abstract enqueueJob(job: JobPayload): Promise<void>\n\n\t/**\n\t * Publishes the final result of a completed or failed workflow run.\n\t * @param runId The unique ID of the workflow run.\n\t * @param result The final status and payload of the workflow.\n\t */\n\tprotected abstract publishFinalResult(\n\t\trunId: string,\n\t\tresult: {\n\t\t\tstatus: 'completed' | 'failed'\n\t\t\tpayload?: WorkflowResult\n\t\t\treason?: string\n\t\t},\n\t): Promise<void>\n\n\t/**\n\t * Registers a webhook endpoint for a specific node in a workflow run.\n\t * @param runId The unique ID of the workflow run.\n\t * @param nodeId The ID of the node that will wait for the webhook.\n\t * @returns The URL and event name for the webhook.\n\t */\n\tpublic abstract registerWebhookEndpoint(runId: string, nodeId: string): Promise<{ url: string; event: string }>\n\n\t/**\n\t * Hook called at the start of job processing. Subclasses can override this\n\t * to perform additional setup (e.g., timestamp tracking for reconciliation).\n\t */\n\tprotected async onJobStart(_runId: string, _blueprintId: string, _nodeId: string): Promise<void> {\n\t\t// default implementation does nothing\n\t}\n\n\t/**\n\t * The main handler for processing a single job from the queue.\n\t */\n\tprotected async handleJob(job: JobPayload): Promise<void> {\n\t\tconst { runId, blueprintId, nodeId } = job\n\t\tconst startTime = Date.now()\n\n\t\tawait this.onJobStart(runId, blueprintId, nodeId)\n\n\t\tconst blueprint = this.runtime.options.blueprints?.[blueprintId]\n\t\tif (!blueprint) {\n\t\t\tconst reason = `Blueprint with ID '${blueprintId}' not found in the worker's runtime registry.`\n\t\t\tthis.logger.error(`[Adapter] FATAL: ${reason}`)\n\t\t\tawait this.publishFinalResult(runId, { status: 'failed', reason })\n\t\t\treturn\n\t\t}\n\n\t\tconst context = this.createContext(runId)\n\n\t\tconst storedVersion = await context.get('blueprintVersion' as any)\n\t\tconst currentVersion = blueprint.metadata?.version || null\n\t\tif (storedVersion !== currentVersion) {\n\t\t\tconst reason = `Blueprint version mismatch: stored version '${storedVersion}', current version '${currentVersion}'. Rejecting job to prevent state corruption.`\n\t\t\tthis.logger.warn(`[Adapter] Version mismatch for run ${runId}, node ${nodeId}: ${reason}`)\n\t\t\treturn\n\t\t}\n\n\t\t// persist the blueprintId and version for the reconcile method to find later\n\t\tconst hasBlueprintId = await context.has('blueprintId' as any)\n\t\tif (!hasBlueprintId) {\n\t\t\tawait context.set('blueprintId' as any, blueprintId)\n\t\t\tawait context.set('blueprintVersion' as any, blueprint.metadata?.version || null)\n\t\t\t// also store in coordination store as fallback\n\t\t\tconst blueprintKey = `flowcraft:blueprint:${runId}`\n\t\t\tawait this.store.setIfNotExist(blueprintKey, blueprintId, 3600)\n\t\t}\n\n\t\t// heartbeat to extend TTLs of coordination keys for long-running jobs\n\t\tconst joinLockKey = `flowcraft:joinlock:${runId}:${nodeId}`\n\t\tconst fanInKey = `flowcraft:fanin:${runId}:${nodeId}`\n\t\tconst blueprintKey = `flowcraft:blueprint:${runId}`\n\t\tconst heartbeatInterval = setInterval(async () => {\n\t\t\tawait this.store.extendTTL(joinLockKey, 3600)\n\t\t\tawait this.store.extendTTL(fanInKey, 3600)\n\t\t\tawait this.store.extendTTL(blueprintKey, 3600)\n\t\t\tthis.logger.debug(`[Adapter] Extended TTLs for run ${runId}, node ${nodeId}`)\n\t\t}, 1800000) // 30 minutes\n\n\t\ttry {\n\t\t\tconst contextData = await context.toJSON()\n\t\t\tconst state = new WorkflowState(contextData, context)\n\n\t\t\tconst result: NodeResult<any, any> = await this.runtime.executeNode(blueprint, nodeId, state)\n\t\t\tawait context.set(`_outputs.${nodeId}` as any, result.output)\n\n\t\t\tconst stateContext = state.getContext()\n\t\t\tif (stateContext instanceof TrackedAsyncContext) {\n\t\t\t\tconst deltas = stateContext.getDeltas()\n\t\t\t\tif (deltas.length > 0) {\n\t\t\t\t\tawait stateContext.patch(deltas)\n\t\t\t\t\tstateContext.clearDeltas()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst analysis = analyzeBlueprint(blueprint)\n\t\t\tconst isTerminalNode = analysis.terminalNodeIds.includes(nodeId)\n\n\t\t\tif (isTerminalNode) {\n\t\t\t\tconst allContextKeys = Object.keys(await context.toJSON())\n\t\t\t\tconst completedNodes = new Set<string>()\n\t\t\t\tfor (const key of allContextKeys) {\n\t\t\t\t\tif (key.startsWith('_outputs.')) {\n\t\t\t\t\t\tcompletedNodes.add(key.substring('_outputs.'.length))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst allTerminalNodesCompleted = analysis.terminalNodeIds.every((terminalId) => completedNodes.has(terminalId))\n\n\t\t\t\tif (allTerminalNodesCompleted) {\n\t\t\t\t\tthis.logger.info(`[Adapter] All terminal nodes completed for Run ID: ${runId}. Declaring workflow complete.`)\n\t\t\t\t\tconst finalContext = await context.toJSON()\n\t\t\t\t\tconst finalResult: WorkflowResult = {\n\t\t\t\t\t\tcontext: finalContext,\n\t\t\t\t\t\tserializedContext: this.serializer.serialize(finalContext),\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t}\n\t\t\t\t\tawait this.publishFinalResult(runId, {\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\tpayload: finalResult,\n\t\t\t\t\t})\n\t\t\t\t\tclearInterval(heartbeatInterval)\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Terminal node '${nodeId}' completed for Run ID '${runId}', but other terminal nodes are still running.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst nextNodes = await this.runtime.determineNextNodes(blueprint, nodeId, result, context, runId)\n\n\t\t\t// stop if a branch terminates but it wasn't a terminal node\n\t\t\tif (nextNodes.length === 0 && !isTerminalNode) {\n\t\t\t\tthis.logger.info(\n\t\t\t\t\t`[Adapter] Non-terminal node '${nodeId}' reached end of branch for Run ID '${runId}'. This branch will now terminate.`,\n\t\t\t\t)\n\t\t\t\tclearInterval(heartbeatInterval)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor (const { node: nextNodeDef, edge } of nextNodes) {\n\t\t\t\tawait this.runtime.applyEdgeTransform(edge, result, nextNodeDef, context, undefined, runId)\n\t\t\t\tconst isReady = await this.isReadyForFanIn(runId, blueprint, nextNodeDef.id)\n\t\t\t\tif (isReady) {\n\t\t\t\t\tthis.logger.info(`[Adapter] Node '${nextNodeDef.id}' is ready. Enqueuing job.`)\n\t\t\t\t\tawait this.enqueueJob({ runId, blueprintId, nodeId: nextNodeDef.id })\n\t\t\t\t\tif (this.eventBus) {\n\t\t\t\t\t\tawait this.eventBus.emit({\n\t\t\t\t\t\t\ttype: 'job:enqueued',\n\t\t\t\t\t\t\tpayload: { runId, blueprintId, nodeId: nextNodeDef.id },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.info(`[Adapter] Node '${nextNodeDef.id}' is waiting for other predecessors to complete.`)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst duration = Date.now() - startTime\n\t\t\tif (this.eventBus) {\n\t\t\t\tawait this.eventBus.emit({\n\t\t\t\t\ttype: 'job:processed',\n\t\t\t\t\tpayload: { runId, blueprintId, nodeId, duration, success: true },\n\t\t\t\t})\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\tconst reason = error.message || 'Unknown execution error'\n\t\t\tthis.logger.error(`[Adapter] FATAL: Job for node '${nodeId}' failed for Run ID '${runId}': ${reason}`)\n\t\t\tawait this.publishFinalResult(runId, { status: 'failed', reason })\n\t\t\tawait this.writePoisonPillForSuccessors(runId, blueprint, nodeId)\n\n\t\t\tif (this.eventBus) {\n\t\t\t\tawait this.eventBus.emit({\n\t\t\t\t\ttype: 'job:failed',\n\t\t\t\t\tpayload: { runId, blueprintId, nodeId, error },\n\t\t\t\t})\n\t\t\t}\n\t\t} finally {\n\t\t\tclearInterval(heartbeatInterval)\n\t\t}\n\t}\n\n\t/**\n\t * Encapsulates the fan-in join logic using the coordination store.\n\t */\n\tprotected async isReadyForFanIn(runId: string, blueprint: WorkflowBlueprint, targetNodeId: string): Promise<boolean> {\n\t\tconst targetNode = blueprint.nodes.find((n) => n.id === targetNodeId)\n\t\tif (!targetNode) {\n\t\t\tthrow new Error(`Node '${targetNodeId}' not found in blueprint`)\n\t\t}\n\t\tconst joinStrategy = targetNode.config?.joinStrategy || 'all'\n\t\tconst predecessors = blueprint.edges.filter((e) => e.target === targetNodeId)\n\n\t\tif (predecessors.length <= 1) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst poisonKey = `flowcraft:fanin:poison:${runId}:${targetNodeId}`\n\t\tconst isPoisoned = await this.store.get(poisonKey)\n\t\tif (isPoisoned) {\n\t\t\tthis.logger.info(`[Adapter] Node '${targetNodeId}' is poisoned due to failed predecessor. Failing immediately.`)\n\t\t\tthrow new Error(`Node '${targetNodeId}' failed due to poisoned predecessor in run '${runId}'`)\n\t\t}\n\n\t\tif (joinStrategy === 'any') {\n\t\t\tconst lockKey = `flowcraft:joinlock:${runId}:${targetNodeId}`\n\t\t\tconst isLocked = await this.store.setIfNotExist(lockKey, 'locked', 3600)\n\t\t\tif (!isLocked) {\n\t\t\t\t// check if cancelled\n\t\t\t\tconst cancelKey = `flowcraft:fanin:cancel:${runId}:${targetNodeId}`\n\t\t\t\tconst isCancelled = !(await this.store.setIfNotExist(cancelKey, 'cancelled', 3600))\n\t\t\t\tif (isCancelled) {\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Node '${targetNodeId}' is cancelled due to failed predecessor. Failing immediately.`,\n\t\t\t\t\t)\n\t\t\t\t\tthrow new Error(`Node '${targetNodeId}' failed due to cancelled predecessor in run '${runId}'`)\n\t\t\t\t}\n\t\t\t\treturn false // already locked by another predecessor\n\t\t\t}\n\t\t\treturn true\n\t\t} else {\n\t\t\tconst fanInKey = `flowcraft:fanin:${runId}:${targetNodeId}`\n\t\t\tconst readyCount = await this.store.increment(fanInKey, 3600)\n\t\t\tif (readyCount >= predecessors.length) {\n\t\t\t\tawait this.store.delete(fanInKey)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * Reconciles the state of a workflow run. It inspects the persisted\n\t * context to find completed nodes, determines the next set of executable\n\t * nodes (the frontier), and enqueues jobs for them if they aren't\n\t * already running. This is the core of the resume functionality.\n\t *\n\t * @param runId The unique ID of the workflow execution to reconcile.\n\t * @returns The set of node IDs that were enqueued for execution.\n\t */\n\tpublic async reconcile(runId: string): Promise<Set<string>> {\n\t\tconst context = this.createContext(runId)\n\t\tlet blueprintId = (await context.get('blueprintId' as any)) as string | undefined\n\n\t\tif (!blueprintId) {\n\t\t\t// fallback to coordination store\n\t\t\tconst blueprintKey = `flowcraft:blueprint:${runId}`\n\t\t\tblueprintId = await this.store.get(blueprintKey)\n\t\t\tif (blueprintId) {\n\t\t\t\t// set it back in context for future use\n\t\t\t\tawait context.set('blueprintId' as any, blueprintId)\n\t\t\t} else {\n\t\t\t\tthrow new Error(`Cannot reconcile runId '${runId}': blueprintId not found in context or coordination store.`)\n\t\t\t}\n\t\t}\n\t\tconst blueprint = this.runtime.options.blueprints?.[blueprintId]\n\t\tif (blueprint && !(await context.has('blueprintVersion' as any))) {\n\t\t\tawait context.set('blueprintVersion' as any, blueprint.metadata?.version || null)\n\t\t}\n\t\tif (!blueprint) {\n\t\t\tthrow new Error(`Cannot reconcile runId '${runId}': Blueprint with ID '${blueprintId}' not found.`)\n\t\t}\n\n\t\tconst state = await context.toJSON()\n\t\tconst completedNodes = new Set<string>()\n\t\tfor (const key of Object.keys(state)) {\n\t\t\tif (key.startsWith('_outputs.')) {\n\t\t\t\tcompletedNodes.add(key.substring('_outputs.'.length))\n\t\t\t}\n\t\t}\n\n\t\tconst frontier = this.calculateResumedFrontier(blueprint, completedNodes)\n\n\t\tconst enqueuedNodes = new Set<string>()\n\t\tfor (const nodeId of frontier) {\n\t\t\tconst nodeDef = blueprint.nodes.find((n) => n.id === nodeId)\n\t\t\tconst joinStrategy = nodeDef?.config?.joinStrategy || 'all'\n\n\t\t\tconst poisonKey = `flowcraft:fanin:poison:${runId}:${nodeId}`\n\t\t\tconst isPoisoned = await this.store.get(poisonKey)\n\t\t\tif (isPoisoned) {\n\t\t\t\tthis.logger.info(`[Adapter] Reconciling: Node '${nodeId}' is poisoned, skipping.`, { runId })\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlet shouldEnqueue = false\n\n\t\t\tif (joinStrategy === 'any') {\n\t\t\t\t// acquire the permanent join lock\n\t\t\t\tconst lockKey = `flowcraft:joinlock:${runId}:${nodeId}`\n\t\t\t\tif (await this.store.setIfNotExist(lockKey, 'locked-by-reconcile', 3600)) {\n\t\t\t\t\tshouldEnqueue = true\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.info(`[Adapter] Reconciling: Node '${nodeId}' is an 'any' join and is already locked.`, { runId })\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// 'all' joins and single-predecessor nodes use a temporary lock\n\t\t\t\tconst lockKey = `flowcraft:nodelock:${runId}:${nodeId}`\n\t\t\t\tif (await this.store.setIfNotExist(lockKey, 'locked', 120)) {\n\t\t\t\t\tshouldEnqueue = true\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.info(`[Adapter] Reconciling: Node '${nodeId}' is already locked.`, { runId })\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (shouldEnqueue) {\n\t\t\t\tthis.logger.info(`[Adapter] Reconciling: Enqueuing ready job for node '${nodeId}'`, { runId })\n\t\t\t\tawait this.enqueueJob({ runId, blueprintId: blueprint.id, nodeId })\n\t\t\t\tenqueuedNodes.add(nodeId)\n\t\t\t}\n\t\t}\n\n\t\treturn enqueuedNodes\n\t}\n\n\tprivate calculateResumedFrontier(blueprint: WorkflowBlueprint, completedNodes: Set<string>): Set<string> {\n\t\tconst newFrontier = new Set<string>()\n\t\tconst allPredecessors = new Map<string, Set<string>>()\n\t\t// (logic extracted from the GraphTraverser)\n\t\tfor (const node of blueprint.nodes) {\n\t\t\tallPredecessors.set(node.id, new Set())\n\t\t}\n\t\tfor (const edge of blueprint.edges) {\n\t\t\tallPredecessors.get(edge.target)?.add(edge.source)\n\t\t}\n\n\t\tfor (const node of blueprint.nodes) {\n\t\t\tif (completedNodes.has(node.id)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst predecessors = allPredecessors.get(node.id) ?? new Set()\n\t\t\tif (predecessors.size === 0 && !completedNodes.has(node.id)) {\n\t\t\t\tnewFrontier.add(node.id)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst joinStrategy = node.config?.joinStrategy || 'all'\n\t\t\tconst completedPredecessors = [...predecessors].filter((p) => completedNodes.has(p))\n\n\t\t\tconst isReady =\n\t\t\t\tjoinStrategy === 'any' ? completedPredecessors.length > 0 : completedPredecessors.length === predecessors.size\n\n\t\t\tif (isReady) {\n\t\t\t\tnewFrontier.add(node.id)\n\t\t\t}\n\t\t}\n\t\treturn newFrontier\n\t}\n\n\t/**\n\t * Writes a poison pill for 'all' join successors and a cancellation pill for 'any' join successors of a failed node to prevent stalling or ambiguous states.\n\t */\n\tprivate async writePoisonPillForSuccessors(\n\t\trunId: string,\n\t\tblueprint: WorkflowBlueprint,\n\t\tfailedNodeId: string,\n\t): Promise<void> {\n\t\tconst successors = blueprint.edges\n\t\t\t.filter((edge) => edge.source === failedNodeId)\n\t\t\t.map((edge) => edge.target)\n\t\t\t.map((targetId) => blueprint.nodes.find((node) => node.id === targetId))\n\t\t\t.filter((node) => node)\n\n\t\tfor (const successor of successors) {\n\t\t\tif (successor) {\n\t\t\t\tconst joinStrategy = successor.config?.joinStrategy || 'all'\n\t\t\t\tif (joinStrategy === 'all') {\n\t\t\t\t\tconst poisonKey = `flowcraft:fanin:poison:${runId}:${successor.id}`\n\t\t\t\t\tawait this.store.setIfNotExist(poisonKey, 'poisoned', 3600)\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Wrote poison pill for 'all' join node '${successor.id}' due to failed predecessor '${failedNodeId}'`,\n\t\t\t\t\t)\n\t\t\t\t} else if (joinStrategy === 'any') {\n\t\t\t\t\tconst cancelKey = `flowcraft:fanin:cancel:${runId}:${successor.id}`\n\t\t\t\t\tawait this.store.setIfNotExist(cancelKey, 'cancelled', 3600)\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Wrote cancellation pill for 'any' join node '${successor.id}' due to failed predecessor '${failedNodeId}'`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"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GAClD,MAAM,wBAAwB,CAAC,GAAG,aAAa,CAAC,QAAQ,MAAM,eAAe,IAAI,EAAE,CAAC;AAKpF,OAFC,iBAAiB,QAAQ,sBAAsB,SAAS,IAAI,sBAAsB,WAAW,aAAa,KAG1G,aAAY,IAAI,KAAK,GAAG;;AAG1B,SAAO;;;;;CAMR,MAAc,6BACb,OACA,WACA,cACgB;EAChB,MAAM,aAAa,UAAU,MAC3B,QAAQ,SAAS,KAAK,WAAW,aAAa,CAC9C,KAAK,SAAS,KAAK,OAAO,CAC1B,KAAK,aAAa,UAAU,MAAM,MAAM,SAAS,KAAK,OAAO,SAAS,CAAC,CACvE,QAAQ,SAAS,KAAK;AAExB,OAAK,MAAM,aAAa,WACvB,KAAI,WAAW;GACd,MAAM,eAAe,UAAU,QAAQ,gBAAgB;AACvD,OAAI,iBAAiB,OAAO;IAC3B,MAAM,YAAY,0BAA0B,MAAM,GAAG,UAAU;AAC/D,UAAM,KAAK,MAAM,cAAc,WAAW,YAAY,KAAK;AAC3D,SAAK,OAAO,KACX,oDAAoD,UAAU,GAAG,+BAA+B,aAAa,GAC7G;cACS,iBAAiB,OAAO;IAClC,MAAM,YAAY,0BAA0B,MAAM,GAAG,UAAU;AAC/D,UAAM,KAAK,MAAM,cAAc,WAAW,aAAa,KAAK;AAC5D,SAAK,OAAO,KACX,0DAA0D,UAAU,GAAG,+BAA+B,aAAa,GACnH"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/container-factory.ts","../src/error-mapper.ts","../src/flow.ts","../src/linter.ts","../src/runtime/adapter.ts"],"sourcesContent":["import { DIContainer, ServiceTokens } from './container'\nimport { PropertyEvaluator } from './evaluator'\nimport { NullLogger } from './logger'\nimport { DefaultOrchestrator } from './runtime/orchestrator'\nimport { JsonSerializer } from './serializer'\nimport type {\n\tIEvaluator,\n\tIEventBus,\n\tILogger,\n\tISerializer,\n\tMiddleware,\n\tNodeClass,\n\tNodeFunction,\n\tRuntimeDependencies,\n\tWorkflowBlueprint,\n} from './types'\n\nexport interface ContainerOptions<TDependencies extends RuntimeDependencies = RuntimeDependencies> {\n\tlogger?: ILogger\n\tserializer?: ISerializer\n\tevaluator?: IEvaluator\n\teventBus?: IEventBus\n\tmiddleware?: Middleware[]\n\tregistry?: Record<string, NodeFunction | NodeClass>\n\tblueprints?: Record<string, WorkflowBlueprint>\n\tdependencies?: TDependencies\n}\n\nexport function createDefaultContainer<\n\tTDependencies extends RuntimeDependencies = RuntimeDependencies,\n>(options: ContainerOptions<TDependencies> = {}): DIContainer {\n\tconst container = new DIContainer()\n\n\tcontainer.register(ServiceTokens.Logger, options.logger || new NullLogger())\n\tcontainer.register(ServiceTokens.Serializer, options.serializer || new JsonSerializer())\n\tcontainer.register(ServiceTokens.Evaluator, options.evaluator || new PropertyEvaluator())\n\tcontainer.register(ServiceTokens.EventBus, options.eventBus || { emit: async () => {} })\n\tcontainer.register(ServiceTokens.Middleware, options.middleware || [])\n\tcontainer.register(ServiceTokens.NodeRegistry, options.registry || {})\n\tcontainer.register(ServiceTokens.BlueprintRegistry, options.blueprints || {})\n\tcontainer.register(ServiceTokens.Dependencies, options.dependencies || ({} as TDependencies))\n\n\tcontainer.registerFactory(ServiceTokens.Orchestrator, () => new DefaultOrchestrator())\n\n\treturn container\n}\n","import { FlowcraftError } from './errors'\nimport type { SourceLocation, WorkflowBlueprint } from './types'\n\n/**\n * Creates an error mapper function that enhances runtime errors with source location information.\n * The mapper looks up node IDs in the provided manifest blueprints and returns enhanced errors\n * that point to the original TypeScript source code.\n *\n * @param manifestBlueprints - The compiled blueprint manifest containing source location data\n * @returns A function that maps errors to enhanced errors with source location information\n */\nexport function createErrorMapper(manifestBlueprints: Record<string, WorkflowBlueprint>) {\n\tconst locationMap = new Map<string, SourceLocation>()\n\n\t// build a quick lookup map\n\tfor (const blueprint of Object.values(manifestBlueprints)) {\n\t\tfor (const node of blueprint.nodes) {\n\t\t\tif (node._sourceLocation) {\n\t\t\t\tlocationMap.set(node.id, node._sourceLocation)\n\t\t\t}\n\t\t}\n\t\tfor (const edge of blueprint.edges) {\n\t\t\tif (edge._sourceLocation) {\n\t\t\t\tconst edgeKey = `${edge.source}-${edge.target}`\n\t\t\t\tlocationMap.set(edgeKey, edge._sourceLocation)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn function mapError(error: Error): Error {\n\t\tif (error instanceof FlowcraftError && error.nodeId) {\n\t\t\tconst location = locationMap.get(error.nodeId)\n\t\t\tif (location) {\n\t\t\t\treturn new Error(\n\t\t\t\t\t`Workflow error at ${location.file}:${location.line}:${location.column}. Original error: ${error.message}`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// try to extract nodeId from error message\n\t\tconst nodeIdMatch = error.message.match(/nodeId[:\\s]+([^\\s,]+)/i)\n\t\tif (nodeIdMatch) {\n\t\t\tconst nodeId = nodeIdMatch[1]\n\t\t\tconst location = locationMap.get(nodeId)\n\t\t\tif (location) {\n\t\t\t\treturn new Error(\n\t\t\t\t\t`Workflow error at ${location.file}:${location.line}:${location.column}. Original error: ${error.message}`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\treturn error\n\t}\n}\n","import { isNodeClass } from './node'\nimport type { FlowRuntime } from './runtime/runtime'\nimport type {\n\tEdgeDefinition,\n\tNodeClass,\n\tNodeDefinition,\n\tNodeFunction,\n\tUIGraph,\n\tWorkflowBlueprint,\n\tWorkflowResult,\n} from './types'\n\n/**\n * Generates a deterministic hash for a function based on its source code and a unique counter.\n */\nlet hashCounter = 0\nfunction _hashFunction(\n\tfn: NodeFunction<any, any, any, any, any> | NodeClass<any, any, any, any, any>,\n): string {\n\tconst source = fn.toString()\n\tlet hash = 0\n\tfor (let i = 0; i < source.length; i++) {\n\t\tconst char = source.charCodeAt(i)\n\t\thash = (hash << 5) - hash + char\n\t\thash = hash & hash // Convert to 32-bit integer\n\t}\n\t// Add counter to ensure uniqueness even for identical functions\n\treturn (Math.abs(hash) + hashCounter++).toString(16)\n}\n\n/**\n * A fluent API for programmatically constructing a WorkflowBlueprint.\n */\nexport class FlowBuilder<\n\tTContext extends Record<string, any> = Record<string, any>,\n\tTDependencies extends Record<string, any> = Record<string, any>,\n> {\n\tprivate blueprint: Partial<WorkflowBlueprint>\n\tprivate functionRegistry: Map<string, NodeFunction | NodeClass>\n\tprivate loopDefinitions: Array<{\n\t\tid: string\n\t\tstartNodeId: string\n\t\tendNodeId: string\n\t\tcondition: string\n\t}>\n\tprivate batchDefinitions: Array<{\n\t\tid: string\n\t\tscatterId: string\n\t\tgatherId: string\n\t}>\n\tprivate cycleEntryPoints: Map<string, string>\n\n\tconstructor(id: string) {\n\t\tthis.blueprint = { id, nodes: [], edges: [] }\n\t\tthis.functionRegistry = new Map()\n\t\tthis.loopDefinitions = []\n\t\tthis.batchDefinitions = []\n\t\tthis.cycleEntryPoints = new Map()\n\t}\n\n\tnode<TInput = any, TOutput = any, TAction extends string = string>(\n\t\tid: string,\n\t\timplementation:\n\t\t\t| NodeFunction<TContext, TDependencies, TInput, TOutput, TAction>\n\t\t\t| NodeClass<TContext, TDependencies, TInput, TOutput, TAction>,\n\t\toptions?: Omit<NodeDefinition, 'id' | 'uses'>,\n\t): this {\n\t\tlet usesKey: string\n\n\t\tif (isNodeClass(implementation)) {\n\t\t\tusesKey =\n\t\t\t\timplementation.name && implementation.name !== 'BaseNode'\n\t\t\t\t\t? implementation.name\n\t\t\t\t\t: `class_${_hashFunction(implementation)}`\n\t\t\tthis.functionRegistry.set(usesKey, implementation)\n\t\t} else {\n\t\t\tusesKey = `fn_${_hashFunction(implementation)}`\n\t\t\tthis.functionRegistry.set(usesKey, implementation as unknown as NodeFunction)\n\t\t}\n\n\t\tconst nodeDef: NodeDefinition = { id, uses: usesKey, ...options }\n\t\tthis.blueprint.nodes?.push(nodeDef)\n\t\treturn this\n\t}\n\n\tedge(\n\t\tsource: string,\n\t\ttarget: string,\n\t\toptions?: Omit<EdgeDefinition, 'source' | 'target'>,\n\t): this {\n\t\tconst edgeDef: EdgeDefinition = { source, target, ...options }\n\t\tthis.blueprint.edges?.push(edgeDef)\n\t\treturn this\n\t}\n\n\t/**\n\t * Creates a batch processing pattern.\n\t * It takes an input array, runs a worker node on each item in parallel, and gathers the results.\n\t * This method augments the Flow's TContext with a new key for the output array.\n\t *\n\t * @param id The base ID for this batch operation.\n\t * @param worker The node implementation to run on each item.\n\t * @param options Configuration for the batch operation.\n\t * @returns The Flow instance with an updated context type for chaining.\n\t */\n\tbatch<TWorkerInput, TWorkerOutput, TWorkerAction extends string, TOutputKey extends string>(\n\t\tid: string,\n\t\tworker:\n\t\t\t| NodeFunction<TContext, TDependencies, TWorkerInput, TWorkerOutput, TWorkerAction>\n\t\t\t| NodeClass<TContext, TDependencies, TWorkerInput, TWorkerOutput, TWorkerAction>,\n\t\toptions: {\n\t\t\t/** The key in the context that holds the input array for the batch. */\n\t\t\tinputKey: keyof TContext\n\t\t\t/** The key in the context where the array of results will be stored. */\n\t\t\toutputKey: TOutputKey\n\t\t\t/** The number of items to process in each chunk to limit memory usage. */\n\t\t\tchunkSize?: number\n\t\t},\n\t): FlowBuilder<TContext & { [K in TOutputKey]: TWorkerOutput[] }, TDependencies> {\n\t\tconst { inputKey, outputKey } = options\n\t\tconst scatterId = `${id}_scatter`\n\t\tconst gatherId = `${id}_gather`\n\n\t\tthis.batchDefinitions.push({ id, scatterId, gatherId })\n\n\t\tlet workerUsesKey: string\n\t\tif (isNodeClass(worker)) {\n\t\t\tworkerUsesKey =\n\t\t\t\tworker.name && worker.name !== 'BaseNode'\n\t\t\t\t\t? worker.name\n\t\t\t\t\t: `class_batch_worker_${_hashFunction(worker)}`\n\t\t\tthis.functionRegistry.set(workerUsesKey, worker)\n\t\t} else {\n\t\t\tworkerUsesKey = `fn_batch_worker_${_hashFunction(worker)}`\n\t\t\tthis.functionRegistry.set(workerUsesKey, worker as unknown as NodeFunction)\n\t\t}\n\n\t\tthis.blueprint.nodes?.push({\n\t\t\tid: scatterId,\n\t\t\tuses: 'batch-scatter',\n\t\t\tinputs: inputKey as string,\n\t\t\tparams: {\n\t\t\t\tworkerUsesKey,\n\t\t\t\toutputKey: outputKey as string,\n\t\t\t\tgatherNodeId: gatherId,\n\t\t\t\tchunkSize: options.chunkSize,\n\t\t\t},\n\t\t})\n\n\t\tthis.blueprint.nodes?.push({\n\t\t\tid: gatherId,\n\t\t\tuses: 'batch-gather',\n\t\t\tparams: { outputKey, gatherNodeId: gatherId },\n\t\t\tconfig: { joinStrategy: 'all' },\n\t\t})\n\n\t\tthis.edge(scatterId, gatherId)\n\n\t\treturn this as unknown as FlowBuilder<\n\t\t\tTContext & { [K in TOutputKey]: TWorkerOutput[] },\n\t\t\tTDependencies\n\t\t>\n\t}\n\n\t/**\n\t * Creates a sleep node that pauses workflow execution for a specified duration.\n\t * @param id A unique identifier for the sleep node.\n\t * @param options Configuration for the sleep duration.\n\t */\n\tsleep(\n\t\tid: string,\n\t\toptions: {\n\t\t\t/** The duration to sleep in milliseconds or a string like '5s', '1m', '2h', '1d'. */\n\t\t\tduration: number | string\n\t\t},\n\t): this {\n\t\tconst nodeDef: NodeDefinition = {\n\t\t\tid,\n\t\t\tuses: 'sleep',\n\t\t\tparams: { duration: options.duration },\n\t\t}\n\t\tthis.blueprint.nodes?.push(nodeDef)\n\t\treturn this\n\t}\n\n\t/**\n\t * Creates a wait node that pauses workflow execution for external input.\n\t * @param id A unique identifier for the wait node.\n\t * @param options Optional configuration for the wait node.\n\t */\n\twait(id: string, options?: Omit<NodeDefinition, 'id' | 'uses'>): this {\n\t\tconst nodeDef: NodeDefinition = { id, uses: 'wait', ...options }\n\t\tthis.blueprint.nodes?.push(nodeDef)\n\t\treturn this\n\t}\n\n\t/**\n\t * Creates a loop pattern in the workflow graph.\n\t * @param id A unique identifier for the loop construct.\n\t * @param options Defines the start, end, and continuation condition of the loop.\n\t * @param options.startNodeId The ID of the first node inside the loop body.\n\t * @param options.endNodeId The ID of the last node inside the loop body.\n\t * @param options.condition An expression that, if true, causes the loop to run again.\n\t */\n\tloop(\n\t\tid: string,\n\t\toptions: {\n\t\t\t/** The ID of the first node inside the loop body. */\n\t\t\tstartNodeId: string\n\t\t\t/** The ID of the last node inside the loop body. */\n\t\t\tendNodeId: string\n\t\t\t/** An expression that, if true, causes the loop to run again. */\n\t\t\tcondition: string\n\t\t},\n\t): this {\n\t\tconst { startNodeId, endNodeId, condition } = options\n\t\tthis.loopDefinitions.push({ id, startNodeId, endNodeId, condition })\n\n\t\tthis.blueprint.nodes?.push({\n\t\t\tid,\n\t\t\tuses: 'loop-controller',\n\t\t\tparams: { condition },\n\t\t\tconfig: { joinStrategy: 'any' },\n\t\t})\n\n\t\tthis.edge(endNodeId, id)\n\t\tthis.edge(id, startNodeId, {\n\t\t\taction: 'continue',\n\t\t\ttransform: `context.${endNodeId}`,\n\t\t})\n\n\t\treturn this\n\t}\n\n\t/**\n\t * Sets the preferred entry point for a cycle in non-DAG workflows.\n\t * This helps remove ambiguity when the runtime needs to choose a starting node for cycles.\n\t * @param nodeId The ID of the node to use as the entry point for cycles containing this node.\n\t */\n\tsetCycleEntryPoint(nodeId: string): this {\n\t\tthis.cycleEntryPoints.set(nodeId, nodeId)\n\t\treturn this\n\t}\n\n\ttoBlueprint(): WorkflowBlueprint {\n\t\tif (!this.blueprint.nodes || this.blueprint.nodes.length === 0) {\n\t\t\tthrow new Error('Cannot build a blueprint with no nodes.')\n\t\t}\n\t\tconst finalEdges: EdgeDefinition[] = []\n\t\tconst processedOriginalEdges = new Set<EdgeDefinition>()\n\t\tconst allOriginalEdges = this.blueprint.edges || []\n\n\t\t// loop edge re-wiring\n\t\tfor (const loopDef of this.loopDefinitions) {\n\t\t\tconst edgesToRewire = allOriginalEdges.filter(\n\t\t\t\t(e) => e.source === loopDef.id && e.target !== loopDef.startNodeId,\n\t\t\t)\n\t\t\tfor (const edge of edgesToRewire) {\n\t\t\t\tfinalEdges.push({\n\t\t\t\t\t...edge,\n\t\t\t\t\taction: edge.action || 'break',\n\t\t\t\t\ttransform: `context.${loopDef.endNodeId}`,\n\t\t\t\t})\n\t\t\t\tprocessedOriginalEdges.add(edge)\n\t\t\t}\n\t\t}\n\n\t\t// batch edge re-wiring\n\t\tfor (const batchDef of this.batchDefinitions) {\n\t\t\tconst incomingEdges = allOriginalEdges.filter((e) => e.target === batchDef.id)\n\t\t\tfor (const edge of incomingEdges) {\n\t\t\t\tfinalEdges.push({ ...edge, target: batchDef.scatterId })\n\t\t\t\tprocessedOriginalEdges.add(edge)\n\t\t\t}\n\n\t\t\tconst outgoingEdges = allOriginalEdges.filter((e) => e.source === batchDef.id)\n\t\t\tfor (const edge of outgoingEdges) {\n\t\t\t\tfinalEdges.push({ ...edge, source: batchDef.gatherId })\n\t\t\t\tprocessedOriginalEdges.add(edge)\n\t\t\t}\n\t\t}\n\n\t\t// all remaining edges\n\t\tfor (const edge of allOriginalEdges) {\n\t\t\tif (!processedOriginalEdges.has(edge)) {\n\t\t\t\tfinalEdges.push(edge)\n\t\t\t}\n\t\t}\n\t\tthis.blueprint.edges = finalEdges\n\n\t\tfor (const loopDef of this.loopDefinitions) {\n\t\t\tconst startNode = this.blueprint.nodes?.find((n) => n.id === loopDef.startNodeId)\n\t\t\tconst endNode = this.blueprint.nodes?.find((n) => n.id === loopDef.endNodeId)\n\n\t\t\tif (!startNode) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Loop '${loopDef.id}' references non-existent start node '${loopDef.startNodeId}'.`,\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!endNode) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Loop '${loopDef.id}' references non-existent end node '${loopDef.endNodeId}'.`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tif (this.cycleEntryPoints.size > 0) {\n\t\t\tthis.blueprint.metadata = {\n\t\t\t\t...this.blueprint.metadata,\n\t\t\t\tcycleEntryPoints: Array.from(this.cycleEntryPoints.keys()),\n\t\t\t}\n\t\t}\n\n\t\treturn this.blueprint as WorkflowBlueprint\n\t}\n\n\tgetFunctionRegistry() {\n\t\treturn this.functionRegistry\n\t}\n\n\t/**\n\t * Runs this flow on the given runtime, automatically passing the function registry.\n\t * Convenience wrapper around `runtime.run(blueprint, initialState, { functionRegistry })`.\n\t */\n\tasync run(\n\t\truntime: FlowRuntime<TContext, TDependencies>,\n\t\tinitialState: Partial<TContext> | string = {},\n\t\toptions?: {\n\t\t\tstrict?: boolean\n\t\t\tsignal?: AbortSignal\n\t\t\tconcurrency?: number\n\t\t},\n\t): Promise<WorkflowResult<TContext>> {\n\t\treturn runtime.run(this.toBlueprint(), initialState, {\n\t\t\t...options,\n\t\t\tfunctionRegistry: this.functionRegistry,\n\t\t})\n\t}\n\n\t/**\n\t * Resumes this flow on the given runtime, automatically passing the function registry.\n\t * Convenience wrapper around `runtime.resume(blueprint, ...)`.\n\t */\n\tasync resume(\n\t\truntime: FlowRuntime<TContext, TDependencies>,\n\t\tserializedContext: string,\n\t\tresumeData: { output?: any; action?: string },\n\t\tnodeId?: string,\n\t\toptions?: {\n\t\t\tstrict?: boolean\n\t\t\tsignal?: AbortSignal\n\t\t\tconcurrency?: number\n\t\t},\n\t): Promise<WorkflowResult<TContext>> {\n\t\treturn runtime.resume(this.toBlueprint(), serializedContext, resumeData, nodeId, {\n\t\t\t...options,\n\t\t\tfunctionRegistry: this.functionRegistry,\n\t\t})\n\t}\n\n\ttoGraphRepresentation(): UIGraph {\n\t\tconst blueprint = this.toBlueprint()\n\t\tconst uiNodes: UIGraph['nodes'] = []\n\t\tconst uiEdges: UIGraph['edges'] = []\n\n\t\tconst ignoredNodeIds = new Set<string>()\n\n\t\t// replace loop-controllers with direct, cyclical edges\n\t\tfor (const loopDef of this.loopDefinitions) {\n\t\t\tconst id = loopDef.id\n\t\t\tignoredNodeIds.add(id)\n\n\t\t\t// direct edge from the end of loop to start\n\t\t\tuiEdges.push({\n\t\t\t\tsource: loopDef.endNodeId,\n\t\t\t\ttarget: loopDef.startNodeId,\n\t\t\t\tdata: {\n\t\t\t\t\tisLoopback: true,\n\t\t\t\t\tcondition: loopDef.condition,\n\t\t\t\t\tlabel: `continue if: ${loopDef.condition}`,\n\t\t\t\t},\n\t\t\t})\n\n\t\t\t// re-wire any 'break' edges\n\t\t\tconst breakEdges = blueprint.edges.filter(\n\t\t\t\t(edge) => edge.source === id && edge.action === 'break',\n\t\t\t)\n\t\t\tfor (const breakEdge of breakEdges) {\n\t\t\t\tuiEdges.push({\n\t\t\t\t\t...breakEdge,\n\t\t\t\t\tsource: loopDef.endNodeId,\n\t\t\t\t})\n\t\t\t}\n\n\t\t\t// re-wire any 'incoming' edges\n\t\t\tconst incomingEdges = blueprint.edges.filter(\n\t\t\t\t(edge) => edge.target === id && edge.source !== loopDef.endNodeId,\n\t\t\t)\n\t\t\tfor (const incomingEdge of incomingEdges) {\n\t\t\t\tuiEdges.push({\n\t\t\t\t\t...incomingEdge,\n\t\t\t\t\tsource: loopDef.startNodeId,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// replace scatter/gather pairs with a single representative worker node\n\t\tconst scatterNodes = blueprint.nodes.filter((n) => n.uses === 'batch-scatter')\n\t\tfor (const scatterNode of scatterNodes) {\n\t\t\tconst gatherNodeId = scatterNode.params?.gatherNodeId\n\t\t\tif (!gatherNodeId) continue\n\n\t\t\tignoredNodeIds.add(scatterNode.id)\n\t\t\tignoredNodeIds.add(gatherNodeId)\n\n\t\t\t// single node to represent parallel work\n\t\t\tconst batchId = scatterNode.id.replace('_scatter', '')\n\t\t\tconst gatherNode = blueprint.nodes.find((n) => n.id === gatherNodeId)\n\n\t\t\tuiNodes.push({\n\t\t\t\tid: batchId,\n\t\t\t\tuses: scatterNode.params?.workerUsesKey,\n\t\t\t\ttype: 'batch-worker',\n\t\t\t\tdata: {\n\t\t\t\t\tlabel: `Batch: ${batchId}`,\n\t\t\t\t\tisBatchPlaceholder: true,\n\t\t\t\t\tworkerUsesKey: scatterNode.params?.workerUsesKey,\n\t\t\t\t\tinputKey: scatterNode.inputs,\n\t\t\t\t\toutputKey: gatherNode?.params?.outputKey,\n\t\t\t\t},\n\t\t\t})\n\n\t\t\t// re-wire incoming edges\n\t\t\tconst incomingEdges = blueprint.edges.filter((e) => e.target === scatterNode.id)\n\t\t\tfor (const edge of incomingEdges) {\n\t\t\t\tuiEdges.push({ ...edge, target: batchId })\n\t\t\t}\n\n\t\t\t// re-wire outgoing edges\n\t\t\tconst outgoingEdges = blueprint.edges.filter((e) => e.source === gatherNodeId)\n\t\t\tfor (const edge of outgoingEdges) {\n\t\t\t\tuiEdges.push({ ...edge, source: batchId })\n\t\t\t}\n\t\t}\n\n\t\tfor (const node of blueprint.nodes) {\n\t\t\tif (!ignoredNodeIds.has(node.id)) {\n\t\t\t\tuiNodes.push(node)\n\t\t\t}\n\t\t}\n\n\t\tfor (const edge of blueprint.edges) {\n\t\t\tif (!ignoredNodeIds.has(edge.source) && !ignoredNodeIds.has(edge.target)) {\n\t\t\t\tconst alreadyAdded = uiEdges.some(\n\t\t\t\t\t(e) =>\n\t\t\t\t\t\te.source === edge.source &&\n\t\t\t\t\t\te.target === edge.target &&\n\t\t\t\t\t\te.action === edge.action,\n\t\t\t\t)\n\t\t\t\tif (!alreadyAdded) {\n\t\t\t\t\tuiEdges.push(edge)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn { nodes: uiNodes, edges: uiEdges }\n\t}\n}\n\n/**\n * Helper function to create a new Flow builder instance.\n */\nexport function createFlow<\n\tTContext extends Record<string, any> = Record<string, any>,\n\tTDependencies extends Record<string, any> = Record<string, any>,\n>(id: string): FlowBuilder<TContext, TDependencies> {\n\treturn new FlowBuilder(id)\n}\n","import { analyzeBlueprint } from './analysis'\nimport type { NodeClass, NodeFunction, WorkflowBlueprint } from './types'\n\nexport type LinterIssueCode =\n\t| 'INVALID_EDGE_SOURCE'\n\t| 'INVALID_EDGE_TARGET'\n\t| 'MISSING_NODE_IMPLEMENTATION'\n\t| 'ORPHAN_NODE'\n\t| 'INVALID_BATCH_WORKER_KEY'\n\t| 'INVALID_SUBFLOW_BLUEPRINT_ID'\n\nexport interface LinterIssue {\n\tcode: LinterIssueCode\n\tmessage: string\n\tnodeId?: string\n\trelatedId?: string\n}\n\nexport interface LinterResult {\n\tisValid: boolean\n\tissues: LinterIssue[]\n}\n\n/**\n * Statically analyzes a workflow blueprint against a registry of implementations\n * to find common errors before runtime.\n *\n * @param blueprint The WorkflowBlueprint to analyze.\n * @param registry A map of node implementations (functions or classes) to check against.\n * @returns A LinterResult object containing any issues found.\n */\nexport function lintBlueprint(\n\tblueprint: WorkflowBlueprint,\n\tregistry: Map<string, NodeFunction | NodeClass> | Record<string, NodeFunction | NodeClass>,\n\tblueprints?: Record<string, WorkflowBlueprint>,\n): LinterResult {\n\tconst issues: LinterIssue[] = []\n\tconst nodeIds = new Set(blueprint.nodes.map((n) => n.id))\n\tconst registryKeys =\n\t\tregistry instanceof Map ? new Set(registry.keys()) : new Set(Object.keys(registry))\n\n\t// check for missing node implementations\n\tfor (const node of blueprint.nodes) {\n\t\tif (\n\t\t\t!node.uses.startsWith('batch-') &&\n\t\t\t!node.uses.startsWith('loop-') &&\n\t\t\t!registryKeys.has(node.uses)\n\t\t) {\n\t\t\tissues.push({\n\t\t\t\tcode: 'MISSING_NODE_IMPLEMENTATION',\n\t\t\t\tmessage: `Node implementation key '${node.uses}' is not found in the provided registry.`,\n\t\t\t\tnodeId: node.id,\n\t\t\t})\n\t\t}\n\t}\n\n\t// check for dynamic node validation\n\tfor (const node of blueprint.nodes) {\n\t\tif (node.uses.startsWith('batch-') && node.params?.workerUsesKey) {\n\t\t\tif (!registryKeys.has(node.params.workerUsesKey)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: 'INVALID_BATCH_WORKER_KEY',\n\t\t\t\t\tmessage: `Batch node '${node.id}' references workerUsesKey '${node.params.workerUsesKey}' which is not found in the registry.`,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\tif (node.uses === 'subflow' && node.params?.blueprintId) {\n\t\t\tif (!blueprints?.[node.params.blueprintId]) {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: 'INVALID_SUBFLOW_BLUEPRINT_ID',\n\t\t\t\t\tmessage: `Subflow node '${node.id}' references blueprintId '${node.params.blueprintId}' which is not found in the blueprints registry.`,\n\t\t\t\t\tnodeId: node.id,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\t// check for graph integrity (edges must point to valid nodes)\n\tfor (const edge of blueprint.edges || []) {\n\t\tif (!nodeIds.has(edge.source)) {\n\t\t\tissues.push({\n\t\t\t\tcode: 'INVALID_EDGE_SOURCE',\n\t\t\t\tmessage: `Edge source '${edge.source}' does not correspond to a valid node ID.`,\n\t\t\t\trelatedId: edge.target,\n\t\t\t})\n\t\t}\n\t\tif (!nodeIds.has(edge.target)) {\n\t\t\tissues.push({\n\t\t\t\tcode: 'INVALID_EDGE_TARGET',\n\t\t\t\tmessage: `Edge target '${edge.target}' does not correspond to a valid node ID.`,\n\t\t\t\trelatedId: edge.source,\n\t\t\t})\n\t\t}\n\t}\n\n\t// check for orphan nodes (not connected to the main graph)\n\tif (blueprint.nodes.length > 1) {\n\t\tconst analysis = analyzeBlueprint(blueprint)\n\t\tconst connectedNodes = new Set<string>()\n\t\tconst nodesToVisit = [...analysis.startNodeIds]\n\t\tconst visited = new Set<string>()\n\n\t\twhile (nodesToVisit.length > 0) {\n\t\t\tconst currentId = nodesToVisit.pop()\n\t\t\tif (!currentId || visited.has(currentId)) continue\n\n\t\t\tvisited.add(currentId)\n\t\t\tconnectedNodes.add(currentId)\n\n\t\t\tfor (const targetEdge of blueprint.edges.filter((e) => e.source === currentId)) {\n\t\t\t\tnodesToVisit.push(targetEdge.target)\n\t\t\t}\n\t\t}\n\n\t\tfor (const nodeId of nodeIds) {\n\t\t\tif (!connectedNodes.has(nodeId)) {\n\t\t\t\tissues.push({\n\t\t\t\t\tcode: 'ORPHAN_NODE',\n\t\t\t\t\tmessage: `Node '${nodeId}' is not reachable from any start node.`,\n\t\t\t\t\tnodeId,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\tisValid: issues.length === 0,\n\t\tissues,\n\t}\n}\n","import { analyzeBlueprint } from '../analysis'\nimport { TrackedAsyncContext } from '../context'\nimport { ConsoleLogger } from '../logger'\nimport { JsonSerializer } from '../serializer'\nimport type {\n\tIAsyncContext,\n\tIEventBus,\n\tILogger,\n\tISerializer,\n\tNodeResult,\n\tRuntimeOptions,\n\tWorkflowBlueprint,\n\tWorkflowResult,\n} from '../types'\nimport { FlowRuntime } from './runtime'\nimport { WorkflowState } from './state'\n\n/**\n * Defines the contract for an atomic, distributed key-value store required by\n * the adapter for coordination tasks like fan-in joins and locking.\n */\nexport interface ICoordinationStore {\n\t/** Atomically increments a key and returns the new value. Ideal for 'all' joins. */\n\tincrement: (key: string, ttlSeconds: number) => Promise<number>\n\t/** Sets a key only if it does not already exist. Ideal for 'any' joins (locking). */\n\tsetIfNotExist: (key: string, value: string, ttlSeconds: number) => Promise<boolean>\n\t/** Extends the TTL of an existing key. Used for heartbeat mechanism in long-running jobs. */\n\textendTTL: (key: string, ttlSeconds: number) => Promise<boolean>\n\t/** Deletes a key. Used for cleanup. */\n\tdelete: (key: string) => Promise<void>\n\t/** Gets the value of a key. */\n\tget: (key: string) => Promise<string | undefined>\n}\n\n/** Configuration options for constructing a BaseDistributedAdapter. */\nexport interface AdapterOptions {\n\truntimeOptions: RuntimeOptions<any>\n\tcoordinationStore: ICoordinationStore\n\teventBus?: IEventBus\n}\n\n/** The data payload expected for a job in the queue. */\nexport interface JobPayload {\n\trunId: string\n\tblueprintId: string\n\tnodeId: string\n}\n\n/**\n * The base class for all distributed adapters. It handles the technology-agnostic\n * orchestration logic and leaves queue-specific implementation to subclasses.\n */\nexport abstract class BaseDistributedAdapter {\n\tprotected readonly runtime: FlowRuntime<any, any>\n\tprotected readonly store: ICoordinationStore\n\tprotected readonly serializer: ISerializer\n\tprotected readonly logger: ILogger\n\tprotected readonly eventBus?: IEventBus\n\n\tconstructor(options: AdapterOptions) {\n\t\tconst runtimeOptions = {\n\t\t\t...options.runtimeOptions,\n\t\t\tdependencies: {\n\t\t\t\t...options.runtimeOptions.dependencies,\n\t\t\t\tadapter: this,\n\t\t\t} as any,\n\t\t}\n\t\tthis.runtime = new FlowRuntime(runtimeOptions)\n\t\tthis.store = options.coordinationStore\n\t\tthis.serializer = options.runtimeOptions.serializer || new JsonSerializer()\n\t\tthis.logger = options.runtimeOptions.logger || new ConsoleLogger()\n\t\tthis.eventBus = options.eventBus\n\t\tthis.logger.info('[Adapter] BaseDistributedAdapter initialized.')\n\t}\n\n\t/**\n\t * Starts the worker, which begins listening for and processing jobs from the queue.\n\t */\n\tpublic start(): void {\n\t\tthis.logger.info('[Adapter] Starting worker...')\n\t\tthis.processJobs(this.handleJob.bind(this))\n\t}\n\n\t/**\n\t * Creates a technology-specific distributed context for a given workflow run.\n\t * @param runId The unique ID for the workflow execution.\n\t */\n\tprotected abstract createContext(runId: string): IAsyncContext<Record<string, any>>\n\t/**\n\t * Sets up the listener for the message queue. The implementation should call the\n\t * provided `handler` function for each new job received.\n\t * @param handler The core logic to execute for each job.\n\t */\n\tprotected abstract processJobs(handler: (job: JobPayload) => Promise<void>): void\n\n\t/**\n\t * Enqueues a new job onto the message queue.\n\t * @param job The payload for the job to be enqueued.\n\t */\n\tprotected abstract enqueueJob(job: JobPayload): Promise<void>\n\n\t/**\n\t * Publishes the final result of a completed or failed workflow run.\n\t * @param runId The unique ID of the workflow run.\n\t * @param result The final status and payload of the workflow.\n\t */\n\tprotected abstract publishFinalResult(\n\t\trunId: string,\n\t\tresult: {\n\t\t\tstatus: 'completed' | 'failed'\n\t\t\tpayload?: WorkflowResult\n\t\t\treason?: string\n\t\t},\n\t): Promise<void>\n\n\t/**\n\t * Registers a webhook endpoint for a specific node in a workflow run.\n\t * @param runId The unique ID of the workflow run.\n\t * @param nodeId The ID of the node that will wait for the webhook.\n\t * @returns The URL and event name for the webhook.\n\t */\n\tpublic abstract registerWebhookEndpoint(\n\t\trunId: string,\n\t\tnodeId: string,\n\t): Promise<{ url: string; event: string }>\n\n\t/**\n\t * Hook called at the start of job processing. Subclasses can override this\n\t * to perform additional setup (e.g., timestamp tracking for reconciliation).\n\t */\n\tprotected async onJobStart(\n\t\t_runId: string,\n\t\t_blueprintId: string,\n\t\t_nodeId: string,\n\t): Promise<void> {\n\t\t// default implementation does nothing\n\t}\n\n\t/**\n\t * The main handler for processing a single job from the queue.\n\t */\n\tprotected async handleJob(job: JobPayload): Promise<void> {\n\t\tconst { runId, blueprintId, nodeId } = job\n\t\tconst startTime = Date.now()\n\n\t\tawait this.onJobStart(runId, blueprintId, nodeId)\n\n\t\tconst blueprint = this.runtime.options.blueprints?.[blueprintId]\n\t\tif (!blueprint) {\n\t\t\tconst reason = `Blueprint with ID '${blueprintId}' not found in the worker's runtime registry.`\n\t\t\tthis.logger.error(`[Adapter] FATAL: ${reason}`)\n\t\t\tawait this.publishFinalResult(runId, { status: 'failed', reason })\n\t\t\treturn\n\t\t}\n\n\t\tconst context = this.createContext(runId)\n\n\t\tconst storedVersion = await context.get('blueprintVersion' as any)\n\t\tconst currentVersion = blueprint.metadata?.version || null\n\t\tif (storedVersion !== currentVersion) {\n\t\t\tconst reason = `Blueprint version mismatch: stored version '${storedVersion}', current version '${currentVersion}'. Rejecting job to prevent state corruption.`\n\t\t\tthis.logger.warn(\n\t\t\t\t`[Adapter] Version mismatch for run ${runId}, node ${nodeId}: ${reason}`,\n\t\t\t)\n\t\t\treturn\n\t\t}\n\n\t\t// persist the blueprintId and version for the reconcile method to find later\n\t\tconst hasBlueprintId = await context.has('blueprintId' as any)\n\t\tif (!hasBlueprintId) {\n\t\t\tawait context.set('blueprintId' as any, blueprintId)\n\t\t\tawait context.set('blueprintVersion' as any, blueprint.metadata?.version || null)\n\t\t\t// also store in coordination store as fallback\n\t\t\tconst blueprintKey = `flowcraft:blueprint:${runId}`\n\t\t\tawait this.store.setIfNotExist(blueprintKey, blueprintId, 3600)\n\t\t}\n\n\t\t// heartbeat to extend TTLs of coordination keys for long-running jobs\n\t\tconst joinLockKey = `flowcraft:joinlock:${runId}:${nodeId}`\n\t\tconst fanInKey = `flowcraft:fanin:${runId}:${nodeId}`\n\t\tconst blueprintKey = `flowcraft:blueprint:${runId}`\n\t\tconst heartbeatInterval = setInterval(async () => {\n\t\t\tawait this.store.extendTTL(joinLockKey, 3600)\n\t\t\tawait this.store.extendTTL(fanInKey, 3600)\n\t\t\tawait this.store.extendTTL(blueprintKey, 3600)\n\t\t\tthis.logger.debug(`[Adapter] Extended TTLs for run ${runId}, node ${nodeId}`)\n\t\t}, 1800000) // 30 minutes\n\n\t\ttry {\n\t\t\tconst contextData = await context.toJSON()\n\t\t\tconst state = new WorkflowState(contextData, context)\n\n\t\t\tconst result: NodeResult<any, any> = await this.runtime.executeNode(\n\t\t\t\tblueprint,\n\t\t\t\tnodeId,\n\t\t\t\tstate,\n\t\t\t)\n\t\t\tawait context.set(`_outputs.${nodeId}` as any, result.output)\n\n\t\t\tconst stateContext = state.getContext()\n\t\t\tif (stateContext instanceof TrackedAsyncContext) {\n\t\t\t\tconst deltas = stateContext.getDeltas()\n\t\t\t\tif (deltas.length > 0) {\n\t\t\t\t\tawait stateContext.patch(deltas)\n\t\t\t\t\tstateContext.clearDeltas()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst analysis = analyzeBlueprint(blueprint)\n\t\t\tconst isTerminalNode = analysis.terminalNodeIds.includes(nodeId)\n\n\t\t\tif (isTerminalNode) {\n\t\t\t\tconst allContextKeys = Object.keys(await context.toJSON())\n\t\t\t\tconst completedNodes = new Set<string>()\n\t\t\t\tfor (const key of allContextKeys) {\n\t\t\t\t\tif (key.startsWith('_outputs.')) {\n\t\t\t\t\t\tcompletedNodes.add(key.substring('_outputs.'.length))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst allTerminalNodesCompleted = analysis.terminalNodeIds.every((terminalId) =>\n\t\t\t\t\tcompletedNodes.has(terminalId),\n\t\t\t\t)\n\n\t\t\t\tif (allTerminalNodesCompleted) {\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] All terminal nodes completed for Run ID: ${runId}. Declaring workflow complete.`,\n\t\t\t\t\t)\n\t\t\t\t\tconst finalContext = await context.toJSON()\n\t\t\t\t\tconst finalResult: WorkflowResult = {\n\t\t\t\t\t\tcontext: finalContext,\n\t\t\t\t\t\tserializedContext: this.serializer.serialize(finalContext),\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t}\n\t\t\t\t\tawait this.publishFinalResult(runId, {\n\t\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\t\tpayload: finalResult,\n\t\t\t\t\t})\n\t\t\t\t\tclearInterval(heartbeatInterval)\n\t\t\t\t\treturn\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Terminal node '${nodeId}' completed for Run ID '${runId}', but other terminal nodes are still running.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst nextNodes = await this.runtime.determineNextNodes(\n\t\t\t\tblueprint,\n\t\t\t\tnodeId,\n\t\t\t\tresult,\n\t\t\t\tcontext,\n\t\t\t\trunId,\n\t\t\t)\n\n\t\t\t// stop if a branch terminates but it wasn't a terminal node\n\t\t\tif (nextNodes.length === 0 && !isTerminalNode) {\n\t\t\t\tthis.logger.info(\n\t\t\t\t\t`[Adapter] Non-terminal node '${nodeId}' reached end of branch for Run ID '${runId}'. This branch will now terminate.`,\n\t\t\t\t)\n\t\t\t\tclearInterval(heartbeatInterval)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor (const { node: nextNodeDef, edge } of nextNodes) {\n\t\t\t\tawait this.runtime.applyEdgeTransform(\n\t\t\t\t\tedge,\n\t\t\t\t\tresult,\n\t\t\t\t\tnextNodeDef,\n\t\t\t\t\tcontext,\n\t\t\t\t\tundefined,\n\t\t\t\t\trunId,\n\t\t\t\t)\n\t\t\t\tconst isReady = await this.isReadyForFanIn(runId, blueprint, nextNodeDef.id)\n\t\t\t\tif (isReady) {\n\t\t\t\t\tthis.logger.info(`[Adapter] Node '${nextNodeDef.id}' is ready. Enqueuing job.`)\n\t\t\t\t\tawait this.enqueueJob({ runId, blueprintId, nodeId: nextNodeDef.id })\n\t\t\t\t\tif (this.eventBus) {\n\t\t\t\t\t\tawait this.eventBus.emit({\n\t\t\t\t\t\t\ttype: 'job:enqueued',\n\t\t\t\t\t\t\tpayload: { runId, blueprintId, nodeId: nextNodeDef.id },\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Node '${nextNodeDef.id}' is waiting for other predecessors to complete.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst duration = Date.now() - startTime\n\t\t\tif (this.eventBus) {\n\t\t\t\tawait this.eventBus.emit({\n\t\t\t\t\ttype: 'job:processed',\n\t\t\t\t\tpayload: { runId, blueprintId, nodeId, duration, success: true },\n\t\t\t\t})\n\t\t\t}\n\t\t} catch (error: any) {\n\t\t\tconst reason = error.message || 'Unknown execution error'\n\t\t\tthis.logger.error(\n\t\t\t\t`[Adapter] FATAL: Job for node '${nodeId}' failed for Run ID '${runId}': ${reason}`,\n\t\t\t)\n\t\t\tawait this.publishFinalResult(runId, { status: 'failed', reason })\n\t\t\tawait this.writePoisonPillForSuccessors(runId, blueprint, nodeId)\n\n\t\t\tif (this.eventBus) {\n\t\t\t\tawait this.eventBus.emit({\n\t\t\t\t\ttype: 'job:failed',\n\t\t\t\t\tpayload: { runId, blueprintId, nodeId, error },\n\t\t\t\t})\n\t\t\t}\n\t\t} finally {\n\t\t\tclearInterval(heartbeatInterval)\n\t\t}\n\t}\n\n\t/**\n\t * Encapsulates the fan-in join logic using the coordination store.\n\t */\n\tprotected async isReadyForFanIn(\n\t\trunId: string,\n\t\tblueprint: WorkflowBlueprint,\n\t\ttargetNodeId: string,\n\t): Promise<boolean> {\n\t\tconst targetNode = blueprint.nodes.find((n) => n.id === targetNodeId)\n\t\tif (!targetNode) {\n\t\t\tthrow new Error(`Node '${targetNodeId}' not found in blueprint`)\n\t\t}\n\t\tconst joinStrategy = targetNode.config?.joinStrategy || 'all'\n\t\tconst predecessors = blueprint.edges.filter((e) => e.target === targetNodeId)\n\n\t\tif (predecessors.length <= 1) {\n\t\t\treturn true\n\t\t}\n\n\t\tconst poisonKey = `flowcraft:fanin:poison:${runId}:${targetNodeId}`\n\t\tconst isPoisoned = await this.store.get(poisonKey)\n\t\tif (isPoisoned) {\n\t\t\tthis.logger.info(\n\t\t\t\t`[Adapter] Node '${targetNodeId}' is poisoned due to failed predecessor. Failing immediately.`,\n\t\t\t)\n\t\t\tthrow new Error(\n\t\t\t\t`Node '${targetNodeId}' failed due to poisoned predecessor in run '${runId}'`,\n\t\t\t)\n\t\t}\n\n\t\tif (joinStrategy === 'any') {\n\t\t\tconst lockKey = `flowcraft:joinlock:${runId}:${targetNodeId}`\n\t\t\tconst isLocked = await this.store.setIfNotExist(lockKey, 'locked', 3600)\n\t\t\tif (!isLocked) {\n\t\t\t\t// check if cancelled\n\t\t\t\tconst cancelKey = `flowcraft:fanin:cancel:${runId}:${targetNodeId}`\n\t\t\t\tconst isCancelled = !(await this.store.setIfNotExist(cancelKey, 'cancelled', 3600))\n\t\t\t\tif (isCancelled) {\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Node '${targetNodeId}' is cancelled due to failed predecessor. Failing immediately.`,\n\t\t\t\t\t)\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Node '${targetNodeId}' failed due to cancelled predecessor in run '${runId}'`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn false // already locked by another predecessor\n\t\t\t}\n\t\t\treturn true\n\t\t} else {\n\t\t\tconst fanInKey = `flowcraft:fanin:${runId}:${targetNodeId}`\n\t\t\tconst readyCount = await this.store.increment(fanInKey, 3600)\n\t\t\tif (readyCount >= predecessors.length) {\n\t\t\t\tawait this.store.delete(fanInKey)\n\t\t\t\treturn true\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * Reconciles the state of a workflow run. It inspects the persisted\n\t * context to find completed nodes, determines the next set of executable\n\t * nodes (the frontier), and enqueues jobs for them if they aren't\n\t * already running. This is the core of the resume functionality.\n\t *\n\t * @param runId The unique ID of the workflow execution to reconcile.\n\t * @returns The set of node IDs that were enqueued for execution.\n\t */\n\tpublic async reconcile(runId: string): Promise<Set<string>> {\n\t\tconst context = this.createContext(runId)\n\t\tlet blueprintId = (await context.get('blueprintId' as any)) as string | undefined\n\n\t\tif (!blueprintId) {\n\t\t\t// fallback to coordination store\n\t\t\tconst blueprintKey = `flowcraft:blueprint:${runId}`\n\t\t\tblueprintId = await this.store.get(blueprintKey)\n\t\t\tif (blueprintId) {\n\t\t\t\t// set it back in context for future use\n\t\t\t\tawait context.set('blueprintId' as any, blueprintId)\n\t\t\t} else {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Cannot reconcile runId '${runId}': blueprintId not found in context or coordination store.`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tconst blueprint = this.runtime.options.blueprints?.[blueprintId]\n\t\tif (blueprint && !(await context.has('blueprintVersion' as any))) {\n\t\t\tawait context.set('blueprintVersion' as any, blueprint.metadata?.version || null)\n\t\t}\n\t\tif (!blueprint) {\n\t\t\tthrow new Error(\n\t\t\t\t`Cannot reconcile runId '${runId}': Blueprint with ID '${blueprintId}' not found.`,\n\t\t\t)\n\t\t}\n\n\t\tconst state = await context.toJSON()\n\t\tconst completedNodes = new Set<string>()\n\t\tfor (const key of Object.keys(state)) {\n\t\t\tif (key.startsWith('_outputs.')) {\n\t\t\t\tcompletedNodes.add(key.substring('_outputs.'.length))\n\t\t\t}\n\t\t}\n\n\t\tconst frontier = this.calculateResumedFrontier(blueprint, completedNodes)\n\n\t\tconst enqueuedNodes = new Set<string>()\n\t\tfor (const nodeId of frontier) {\n\t\t\tconst nodeDef = blueprint.nodes.find((n) => n.id === nodeId)\n\t\t\tconst joinStrategy = nodeDef?.config?.joinStrategy || 'all'\n\n\t\t\tconst poisonKey = `flowcraft:fanin:poison:${runId}:${nodeId}`\n\t\t\tconst isPoisoned = await this.store.get(poisonKey)\n\t\t\tif (isPoisoned) {\n\t\t\t\tthis.logger.info(`[Adapter] Reconciling: Node '${nodeId}' is poisoned, skipping.`, {\n\t\t\t\t\trunId,\n\t\t\t\t})\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tlet shouldEnqueue = false\n\n\t\t\tif (joinStrategy === 'any') {\n\t\t\t\t// acquire the permanent join lock\n\t\t\t\tconst lockKey = `flowcraft:joinlock:${runId}:${nodeId}`\n\t\t\t\tif (await this.store.setIfNotExist(lockKey, 'locked-by-reconcile', 3600)) {\n\t\t\t\t\tshouldEnqueue = true\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Reconciling: Node '${nodeId}' is an 'any' join and is already locked.`,\n\t\t\t\t\t\t{ runId },\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// 'all' joins and single-predecessor nodes use a temporary lock\n\t\t\t\tconst lockKey = `flowcraft:nodelock:${runId}:${nodeId}`\n\t\t\t\tif (await this.store.setIfNotExist(lockKey, 'locked', 120)) {\n\t\t\t\t\tshouldEnqueue = true\n\t\t\t\t} else {\n\t\t\t\t\tthis.logger.info(`[Adapter] Reconciling: Node '${nodeId}' is already locked.`, {\n\t\t\t\t\t\trunId,\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (shouldEnqueue) {\n\t\t\t\tthis.logger.info(\n\t\t\t\t\t`[Adapter] Reconciling: Enqueuing ready job for node '${nodeId}'`,\n\t\t\t\t\t{ runId },\n\t\t\t\t)\n\t\t\t\tawait this.enqueueJob({ runId, blueprintId: blueprint.id, nodeId })\n\t\t\t\tenqueuedNodes.add(nodeId)\n\t\t\t}\n\t\t}\n\n\t\treturn enqueuedNodes\n\t}\n\n\tprivate calculateResumedFrontier(\n\t\tblueprint: WorkflowBlueprint,\n\t\tcompletedNodes: Set<string>,\n\t): Set<string> {\n\t\tconst newFrontier = new Set<string>()\n\t\tconst allPredecessors = new Map<string, Set<string>>()\n\t\t// (logic extracted from the GraphTraverser)\n\t\tfor (const node of blueprint.nodes) {\n\t\t\tallPredecessors.set(node.id, new Set())\n\t\t}\n\t\tfor (const edge of blueprint.edges) {\n\t\t\tallPredecessors.get(edge.target)?.add(edge.source)\n\t\t}\n\n\t\tfor (const node of blueprint.nodes) {\n\t\t\tif (completedNodes.has(node.id)) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst predecessors = allPredecessors.get(node.id) ?? new Set()\n\t\t\tif (predecessors.size === 0 && !completedNodes.has(node.id)) {\n\t\t\t\tnewFrontier.add(node.id)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tconst joinStrategy = node.config?.joinStrategy || 'all'\n\t\t\tconst completedPredecessors = [...predecessors].filter((p) => completedNodes.has(p))\n\n\t\t\tconst isReady =\n\t\t\t\tjoinStrategy === 'any'\n\t\t\t\t\t? completedPredecessors.length > 0\n\t\t\t\t\t: completedPredecessors.length === predecessors.size\n\n\t\t\tif (isReady) {\n\t\t\t\tnewFrontier.add(node.id)\n\t\t\t}\n\t\t}\n\t\treturn newFrontier\n\t}\n\n\t/**\n\t * Writes a poison pill for 'all' join successors and a cancellation pill for 'any' join successors of a failed node to prevent stalling or ambiguous states.\n\t */\n\tprivate async writePoisonPillForSuccessors(\n\t\trunId: string,\n\t\tblueprint: WorkflowBlueprint,\n\t\tfailedNodeId: string,\n\t): Promise<void> {\n\t\tconst successors = blueprint.edges\n\t\t\t.filter((edge) => edge.source === failedNodeId)\n\t\t\t.map((edge) => edge.target)\n\t\t\t.map((targetId) => blueprint.nodes.find((node) => node.id === targetId))\n\t\t\t.filter((node) => node)\n\n\t\tfor (const successor of successors) {\n\t\t\tif (successor) {\n\t\t\t\tconst joinStrategy = successor.config?.joinStrategy || 'all'\n\t\t\t\tif (joinStrategy === 'all') {\n\t\t\t\t\tconst poisonKey = `flowcraft:fanin:poison:${runId}:${successor.id}`\n\t\t\t\t\tawait this.store.setIfNotExist(poisonKey, 'poisoned', 3600)\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Wrote poison pill for 'all' join node '${successor.id}' due to failed predecessor '${failedNodeId}'`,\n\t\t\t\t\t)\n\t\t\t\t} else if (joinStrategy === 'any') {\n\t\t\t\t\tconst cancelKey = `flowcraft:fanin:cancel:${runId}:${successor.id}`\n\t\t\t\t\tawait this.store.setIfNotExist(cancelKey, 'cancelled', 3600)\n\t\t\t\t\tthis.logger.info(\n\t\t\t\t\t\t`[Adapter] Wrote cancellation pill for 'any' join node '${successor.id}' due to failed predecessor '${failedNodeId}'`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n"],"mappings":";;;;AA4BA,SAAgB,uBAEd,UAA2C,EAAE,EAAe;CAC7D,MAAM,YAAY,IAAI,aAAa;AAEnC,WAAU,SAAS,cAAc,QAAQ,QAAQ,UAAU,IAAI,YAAY,CAAC;AAC5E,WAAU,SAAS,cAAc,YAAY,QAAQ,cAAc,IAAI,gBAAgB,CAAC;AACxF,WAAU,SAAS,cAAc,WAAW,QAAQ,aAAa,IAAI,mBAAmB,CAAC;AACzF,WAAU,SAAS,cAAc,UAAU,QAAQ,YAAY,EAAE,MAAM,YAAY,IAAI,CAAC;AACxF,WAAU,SAAS,cAAc,YAAY,QAAQ,cAAc,EAAE,CAAC;AACtE,WAAU,SAAS,cAAc,cAAc,QAAQ,YAAY,EAAE,CAAC;AACtE,WAAU,SAAS,cAAc,mBAAmB,QAAQ,cAAc,EAAE,CAAC;AAC7E,WAAU,SAAS,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G,+BAA+B,aAAa,GAC7G;cACS,iBAAiB,OAAO;IAClC,MAAM,YAAY,0BAA0B,MAAM,GAAG,UAAU;AAC/D,UAAM,KAAK,MAAM,cAAc,WAAW,aAAa,KAAK;AAC5D,SAAK,OAAO,KACX,0DAA0D,UAAU,GAAG,+BAA+B,aAAa,GACnH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"replay-BB11M6K1.mjs","names":[],"sources":["../src/runtime/orchestrators/replay.ts"],"sourcesContent":["import type { FlowcraftEvent, WorkflowResult } from '../../types'\nimport type { ExecutionContext } from '../execution-context'\nimport type { GraphTraverser } from '../traverser'\nimport type { IOrchestrator } from '../types'\n\n/**\n * An orchestrator that replays a pre-recorded sequence of workflow events\n * to reconstruct the workflow state without executing any node logic.\n *\n * This enables time-travel debugging by allowing developers to inspect\n * the exact state of a workflow at any point in its execution history.\n */\nexport class ReplayOrchestrator implements IOrchestrator {\n\t/**\n\t * Creates a new ReplayOrchestrator with a sequence of recorded workflow events.\n\t *\n\t * @param events - Array of FlowcraftEvent objects representing the recorded workflow execution\n\t */\n\tconstructor(private events: FlowcraftEvent[]) {}\n\n\t/**\n\t * Replays the recorded workflow events to reconstruct the workflow state.\n\t *\n\t * This method filters events for the specific execution, applies each event in sequence\n\t * to rebuild the context state, and returns the final reconstructed workflow result.\n\t * Replayed executions always have a \"completed\" status since they reconstruct the final state.\n\t *\n\t * @param context - The execution context containing state and services\n\t * @param _traverser - Graph traverser (unused in replay mode)\n\t * @returns Promise resolving to the reconstructed workflow result\n\t */\n\tasync run(
|
|
1
|
+
{"version":3,"file":"replay-BB11M6K1.mjs","names":[],"sources":["../src/runtime/orchestrators/replay.ts"],"sourcesContent":["import type { FlowcraftEvent, WorkflowResult } from '../../types'\nimport type { ExecutionContext } from '../execution-context'\nimport type { GraphTraverser } from '../traverser'\nimport type { IOrchestrator } from '../types'\n\n/**\n * An orchestrator that replays a pre-recorded sequence of workflow events\n * to reconstruct the workflow state without executing any node logic.\n *\n * This enables time-travel debugging by allowing developers to inspect\n * the exact state of a workflow at any point in its execution history.\n */\nexport class ReplayOrchestrator implements IOrchestrator {\n\t/**\n\t * Creates a new ReplayOrchestrator with a sequence of recorded workflow events.\n\t *\n\t * @param events - Array of FlowcraftEvent objects representing the recorded workflow execution\n\t */\n\tconstructor(private events: FlowcraftEvent[]) {}\n\n\t/**\n\t * Replays the recorded workflow events to reconstruct the workflow state.\n\t *\n\t * This method filters events for the specific execution, applies each event in sequence\n\t * to rebuild the context state, and returns the final reconstructed workflow result.\n\t * Replayed executions always have a \"completed\" status since they reconstruct the final state.\n\t *\n\t * @param context - The execution context containing state and services\n\t * @param _traverser - Graph traverser (unused in replay mode)\n\t * @returns Promise resolving to the reconstructed workflow result\n\t */\n\tasync run(\n\t\tcontext: ExecutionContext<any, any>,\n\t\t_traverser: GraphTraverser,\n\t): Promise<WorkflowResult<any>> {\n\t\tconst executionEvents = this.events.filter((event) => {\n\t\t\tif ('executionId' in event.payload) {\n\t\t\t\treturn event.payload.executionId === context.executionId\n\t\t\t}\n\t\t\treturn false\n\t\t})\n\n\t\tconst fallbackMap = new Map<string, string>()\n\n\t\tfor (const event of executionEvents) {\n\t\t\tawait this.applyEvent(event, context, fallbackMap)\n\t\t}\n\n\t\tconst includeExecutionId = executionEvents.length > 0\n\t\tconst result = await context.state.toResult(\n\t\t\tcontext.services.serializer,\n\t\t\tincludeExecutionId ? context.executionId : undefined,\n\t\t)\n\t\tresult.status = 'completed'\n\t\treturn result\n\t}\n\n\t/**\n\t * Applies a single workflow event to reconstruct the execution state.\n\t *\n\t * This method handles different event types by updating the workflow state accordingly,\n\t * including node completions, context changes, errors, fallbacks, and workflow control events.\n\t *\n\t * @param event - The workflow event to apply\n\t * @param context - The execution context to update\n\t * @param fallbackMap - Map tracking fallback node relationships (fallbackNodeId -> originalNodeId)\n\t */\n\tprivate async applyEvent(\n\t\tevent: FlowcraftEvent,\n\t\tcontext: ExecutionContext<any, any>,\n\t\tfallbackMap: Map<string, string>,\n\t): Promise<void> {\n\t\tconst { type, payload } = event\n\n\t\tswitch (type) {\n\t\t\tcase 'node:start':\n\t\t\t\tbreak\n\n\t\t\tcase 'node:finish': {\n\t\t\t\tconst originalNodeId = fallbackMap.get(payload.nodeId)\n\t\t\t\tif (originalNodeId) {\n\t\t\t\t\tawait context.state.addCompletedNode(originalNodeId, payload.result.output)\n\t\t\t\t} else {\n\t\t\t\t\tawait context.state.addCompletedNode(payload.nodeId, payload.result.output)\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tcase 'context:change':\n\t\t\t\tif (payload.op === 'set') {\n\t\t\t\t\tawait context.state.getContext().set(payload.key, payload.value)\n\t\t\t\t} else if (payload.op === 'delete') {\n\t\t\t\t\tawait context.state.getContext().delete(payload.key)\n\t\t\t\t}\n\t\t\t\tbreak\n\n\t\t\tcase 'node:error':\n\t\t\t\tcontext.state.addError(payload.nodeId, payload.error)\n\t\t\t\tbreak\n\n\t\t\tcase 'node:fallback':\n\t\t\t\tfallbackMap.set(payload.fallback, payload.nodeId)\n\t\t\t\tcontext.state.markFallbackExecuted()\n\t\t\t\tbreak\n\n\t\t\tcase 'node:retry':\n\t\t\t\tbreak\n\n\t\t\tcase 'edge:evaluate':\n\t\t\t\tbreak\n\n\t\t\tcase 'workflow:stall':\n\t\t\tcase 'workflow:pause':\n\t\t\t\tif ('remainingNodes' in payload) {\n\t\t\t\t\tfor (let i = 0; i < payload.remainingNodes; i++) {\n\t\t\t\t\t\tawait context.state.markAsAwaiting(`node-${i}`)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\n\t\t\tcase 'batch:start':\n\t\t\t\tbreak\n\n\t\t\tcase 'batch:finish':\n\t\t\t\tfor (const _result of payload.results) {\n\t\t\t\t\t// TODO?\n\t\t\t\t}\n\t\t\t\tbreak\n\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t}\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;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AK;AACJ,QAAI,oBAAoB,QACvB,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,gBAAgB,IAC3C,OAAM,QAAQ,MAAM,eAAe,QAAQ,IAAI;AAGjD;GAED,KAAK,cACJ;GAED,KAAK;AACJ,SAAK,MAAM,WAAW,QAAQ;AAG9B;GAED,QACC"}
|
|
@@ -1850,7 +1850,7 @@ var FlowRuntime = class {
|
|
|
1850
1850
|
this.orchestrator = this.container.resolve(ServiceTokens.Orchestrator);
|
|
1851
1851
|
this.scheduler = new WorkflowScheduler(this);
|
|
1852
1852
|
} else {
|
|
1853
|
-
const options = containerOrOptions;
|
|
1853
|
+
const options = containerOrOptions || {};
|
|
1854
1854
|
this.logger = options.logger || new NullLogger();
|
|
1855
1855
|
this.serializer = options.serializer || new JsonSerializer();
|
|
1856
1856
|
this.evaluator = options.evaluator || new PropertyEvaluator();
|
|
@@ -2218,4 +2218,4 @@ var FlowRuntime = class {
|
|
|
2218
2218
|
|
|
2219
2219
|
//#endregion
|
|
2220
2220
|
export { ServiceTokens as A, TrackedAsyncContext as C, PropertyEvaluator as D, NullLogger as E, InMemoryEventStore as F, PersistentEventBusAdapter as I, checkForCycles as M, generateMermaid as N, UnsafeEvaluator as O, generateMermaidForRun as P, Context as S, ConsoleLogger as T, executeBatch as _, sanitizeBlueprint as a, WorkflowState as b, SubflowNode as c, BatchScatterNode as d, BatchGatherNode as f, DefaultOrchestrator as g, JsonSerializer as h, NodeExecutor as i, analyzeBlueprint as j, DIContainer as k, GraphTraverser as l, isNodeClass as m, ClassNodeExecutor as n, WebhookNode as o, BaseNode as p, FunctionNodeExecutor as r, WaitNode as s, FlowRuntime as t, SleepNode as u, processResults as v, FlowcraftError as w, AsyncContextView as x, ExecutionContext as y };
|
|
2221
|
-
//# sourceMappingURL=runtime-
|
|
2221
|
+
//# sourceMappingURL=runtime-CRwlRW2p.mjs.map
|