flowcraft 2.9.2 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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<\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,MAA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AAO;;;;;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\ttarget: 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\tNodeDefinition,\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\t/** Used to suppress intermediate failures and fallback triggers when delegating to Queue retries */\n\tisLastAttempt?: boolean\n\t/** Optional attempt tracking metadata */\n\tattempt?: number\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 * Hook called by the execution factory to determine if a node's automatic\n\t * retries should be executed synchronously in-process (true) or delegated\n\t * to the Queue backoff behavior configured by the adapter (false).\n\t */\n\tprotected shouldRetryInProcess(_nodeDef: NodeDefinition): boolean {\n\t\treturn true // Default backward compatible behavior\n\t}\n\n\t/**\n\t * Returns queue-level retry options for enqueuing successor jobs.\n\t * Only used when shouldRetryInProcess() returns false.\n\t */\n\tprotected getQueueRetryOptions(_nodeDef: NodeDefinition): Record<string, any> | undefined {\n\t\treturn undefined\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\t\t\tstate.isLastAttempt = job.isLastAttempt !== false\n\n\t\t\tlet result: NodeResult<any, any>\n\n\t\t\tconst alreadyCompleted = await context.has(`_outputs.${nodeId}` as any)\n\n\t\t\tif (alreadyCompleted) {\n\t\t\t\tthis.logger.info(\n\t\t\t\t\t`[Adapter] Node '${nodeId}' already completed, skipping re-execution.`,\n\t\t\t\t)\n\t\t\t\tresult = { output: await context.get(`_outputs.${nodeId}` as any) }\n\t\t\t} else {\n\t\t\t\tconst nodeDef = blueprint.nodes.find((n) => n.id === nodeId)\n\t\t\t\tif (nodeDef && !this.shouldRetryInProcess(nodeDef)) {\n\t\t\t\t\tif (nodeDef.config?.maxRetries && nodeDef.config.maxRetries > 1) {\n\t\t\t\t\t\tnodeDef.config.maxRetries = 1\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tresult = await this.runtime.executeNode(blueprint, nodeId, state)\n\t\t\t\tawait context.set(`_outputs.${nodeId}` as any, result.output)\n\n\t\t\t\tconst stateContext = state.getContext()\n\t\t\t\tif (stateContext instanceof TrackedAsyncContext) {\n\t\t\t\t\tconst deltas = stateContext.getDeltas()\n\t\t\t\t\tif (deltas.length > 0) {\n\t\t\t\t\t\tawait stateContext.patch(deltas)\n\t\t\t\t\t\tstateContext.clearDeltas()\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait this.handleNodeCompletion({\n\t\t\t\trunId,\n\t\t\t\tblueprintId,\n\t\t\t\tnodeId,\n\t\t\t\tblueprint,\n\t\t\t\tresult,\n\t\t\t\tcontext,\n\t\t\t\tstartTime,\n\t\t\t\theartbeatInterval,\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\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\n\t\t\tif (job.isLastAttempt === false) {\n\t\t\t\tthis.logger.warn(\n\t\t\t\t\t`[Adapter] Job for node '${nodeId}' failed (queue attempt ${job.attempt || 1}), delegating retry to queue.`,\n\t\t\t\t)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tawait this.publishFinalResult(runId, { status: 'failed', reason })\n\t\t\tawait this.writePoisonPillForSuccessors(runId, blueprint, nodeId)\n\t\t} finally {\n\t\t\tclearInterval(heartbeatInterval)\n\t\t}\n\t}\n\n\t/**\n\t * Handles post-execution logic: terminal node checks, successor determination,\n\t * and enqueueing of ready nodes. Extracted to support the idempotency guard.\n\t */\n\tprivate async handleNodeCompletion(params: {\n\t\trunId: string\n\t\tblueprintId: string\n\t\tnodeId: string\n\t\tblueprint: WorkflowBlueprint\n\t\tresult: NodeResult<any, any>\n\t\tcontext: IAsyncContext<Record<string, any>>\n\t\tstartTime: number\n\t\theartbeatInterval: ReturnType<typeof setInterval>\n\t}): Promise<void> {\n\t\tconst {\n\t\t\trunId,\n\t\t\tblueprintId,\n\t\t\tnodeId,\n\t\t\tblueprint,\n\t\t\tresult,\n\t\t\tcontext,\n\t\t\tstartTime,\n\t\t\theartbeatInterval,\n\t\t} = params\n\n\t\tconst analysis = analyzeBlueprint(blueprint)\n\t\tconst isTerminalNode = analysis.terminalNodeIds.includes(nodeId)\n\n\t\tif (isTerminalNode) {\n\t\t\tconst allContextKeys = Object.keys(await context.toJSON())\n\t\t\tconst completedNodes = new Set<string>()\n\t\t\tfor (const key of allContextKeys) {\n\t\t\t\tif (key.startsWith('_outputs.')) {\n\t\t\t\t\tcompletedNodes.add(key.substring('_outputs.'.length))\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst allTerminalNodesCompleted = analysis.terminalNodeIds.every((terminalId) =>\n\t\t\t\tcompletedNodes.has(terminalId),\n\t\t\t)\n\n\t\t\tif (allTerminalNodesCompleted) {\n\t\t\t\tthis.logger.info(\n\t\t\t\t\t`[Adapter] All terminal nodes completed for Run ID: ${runId}. Declaring workflow complete.`,\n\t\t\t\t)\n\t\t\t\tconst finalContext = await context.toJSON()\n\t\t\t\tconst finalResult: WorkflowResult = {\n\t\t\t\t\tcontext: finalContext,\n\t\t\t\t\tserializedContext: this.serializer.serialize(finalContext),\n\t\t\t\t\tstatus: 'completed',\n\t\t\t\t}\n\t\t\t\tawait this.publishFinalResult(runId, {\n\t\t\t\t\tstatus: 'completed',\n\t\t\t\t\tpayload: finalResult,\n\t\t\t\t})\n\t\t\t\tclearInterval(heartbeatInterval)\n\t\t\t\treturn\n\t\t\t} else {\n\t\t\t\tthis.logger.info(\n\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)\n\t\t\t}\n\t\t}\n\n\t\tconst nextNodes = await this.runtime.determineNextNodes(\n\t\t\tblueprint,\n\t\t\tnodeId,\n\t\t\tresult,\n\t\t\tcontext,\n\t\t\trunId,\n\t\t)\n\n\t\t// stop if a branch terminates but it wasn't a terminal node\n\t\tif (nextNodes.length === 0 && !isTerminalNode) {\n\t\t\tthis.logger.info(\n\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)\n\t\t\tclearInterval(heartbeatInterval)\n\t\t\treturn\n\t\t}\n\n\t\tfor (const { node: nextNodeDef, edge } of nextNodes) {\n\t\t\tawait this.runtime.applyEdgeTransform(\n\t\t\t\tedge,\n\t\t\t\tresult,\n\t\t\t\tnextNodeDef,\n\t\t\t\tcontext,\n\t\t\t\tundefined,\n\t\t\t\trunId,\n\t\t\t)\n\t\t\tconst isReady = await this.isReadyForFanIn(runId, blueprint, nextNodeDef.id)\n\t\t\tif (isReady) {\n\t\t\t\tthis.logger.info(`[Adapter] Node '${nextNodeDef.id}' is ready. Enqueuing job.`)\n\t\t\t\tawait this.enqueueJob({ runId, blueprintId, nodeId: nextNodeDef.id })\n\t\t\t\tif (this.eventBus) {\n\t\t\t\t\tawait this.eventBus.emit({\n\t\t\t\t\t\ttype: 'job:enqueued',\n\t\t\t\t\t\tpayload: { runId, blueprintId, nodeId: nextNodeDef.id },\n\t\t\t\t\t})\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthis.logger.info(\n\t\t\t\t\t`[Adapter] Node '${nextNodeDef.id}' is waiting for other predecessors to complete.`,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst duration = Date.now() - startTime\n\t\tif (this.eventBus) {\n\t\t\tawait this.eventBus.emit({\n\t\t\t\ttype: 'job:processed',\n\t\t\t\tpayload: { runId, blueprintId, nodeId, duration, success: true },\n\t\t\t})\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,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CAC9B;GAGD,MAAM,eAAe,gBAAgB,IAAI,KAAK,GAAG,oBAAI,IAAI,KAAK;AAC9D,OAAI,aAAa,SAAS,KAAK,CAAC,eAAe,IAAI,KAAK,GAAG,EAAE;AAC5D,gBAAY,IAAI,KAAK,GAAG;AACxB;;GAGD,MAAM,eAAe,KAAK,QAAQ,gBAAgB;GAClD,MAAM,wBAAwB,CAAC,GAAG,aAAa,CAAC,QAAQ,MAAM,eAAe,IAAI,EAAE,CAAC;AAOpF,OAJC,iBAAiB,QACd,sBAAsB,SAAS,IAC/B,sBAAsB,WAAW,aAAa,KAGjD,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"}
@@ -294,6 +294,23 @@ var PropertyEvaluator = class {
294
294
  }
295
295
  };
296
296
  /**
297
+ * Rewrites an expression so that hyphenated identifiers use bracket notation.
298
+ * E.g. "foo-bar.total" → 'context["foo-bar"].total'
299
+ */
300
+ function rewriteHyphenatedIdentifiers(expression, hyphenatedKeys) {
301
+ let result = expression;
302
+ const sortedKeys = [...hyphenatedKeys].toSorted((a, b) => b.length - a.length);
303
+ for (const key of sortedKeys) {
304
+ if (!key.includes("-")) continue;
305
+ const regex = new RegExp(`(?<![\\w$])${escapeRegex(key)}(?![\\w$-])`, "g");
306
+ result = result.replace(regex, `context["${key}"]`);
307
+ }
308
+ return result;
309
+ }
310
+ function escapeRegex(str) {
311
+ return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
312
+ }
313
+ /**
297
314
  * @warning This evaluator uses `new Function()` and can execute arbitrary
298
315
  * JavaScript code. It poses a significant security risk if the expressions
299
316
  * are not from a trusted source (e.g., user input).
@@ -309,9 +326,12 @@ var UnsafeEvaluator = class {
309
326
  try {
310
327
  const validIdentifierRegex = /^[a-z_$][\w$]*$/i;
311
328
  const validKeys = Object.keys(context).filter((key) => validIdentifierRegex.test(key));
329
+ const hyphenatedKeys = Object.keys(context).filter((key) => !validIdentifierRegex.test(key) && /^[a-zA-Z0-9_$-]+$/.test(key));
312
330
  const validContext = {};
313
331
  for (const key of validKeys) validContext[key] = context[key];
314
- return new Function(...validKeys, `return ${expression}`)(...validKeys.map((k) => validContext[k]));
332
+ for (const key of hyphenatedKeys) validContext[key] = context[key];
333
+ let rewrittenExpression = rewriteHyphenatedIdentifiers(expression, hyphenatedKeys);
334
+ return new Function("context", ...validKeys, `return ${rewrittenExpression}`)(validContext, ...validKeys.map((k) => validContext[k]));
315
335
  } catch (error) {
316
336
  console.error(`Error evaluating expression "${expression}":`, error);
317
337
  return;
@@ -521,6 +541,7 @@ var WorkflowState = class {
521
541
  _isAwaiting = false;
522
542
  _awaitingNodeIds = /* @__PURE__ */ new Set();
523
543
  _awaitingDetails = /* @__PURE__ */ new Map();
544
+ isLastAttempt;
524
545
  constructor(initialData, context) {
525
546
  if (context) this.context = context instanceof TrackedAsyncContext ? context : new TrackedAsyncContext(context);
526
547
  else this.context = new TrackedAsyncContext(new AsyncContextView(new Context(initialData)));
@@ -545,6 +566,7 @@ var WorkflowState = class {
545
566
  async addCompletedNode(nodeId, output) {
546
567
  this._completedNodes.add(nodeId);
547
568
  await this.context.set(`_outputs.${nodeId}`, output);
569
+ await this.context.set(nodeId, output);
548
570
  }
549
571
  addError(nodeId, error) {
550
572
  const flowcraftError = new FlowcraftError(error.message, {
@@ -699,7 +721,7 @@ async function processResults(settledResults, traverser, state, runtime, _bluepr
699
721
  if (executionResult.status === "success") {
700
722
  const result = executionResult.result;
701
723
  if (result) {
702
- state.addCompletedNode(nodeId, result.output);
724
+ await state.addCompletedNode(nodeId, result.output);
703
725
  if (result._fallbackExecuted) state.markFallbackExecuted();
704
726
  if (result.dynamicNodes && result.dynamicNodes.length > 0) {
705
727
  const gatherNodeId = result.output?.gatherNodeId;
@@ -1036,8 +1058,16 @@ var GraphTraverser = class GraphTraverser {
1036
1058
  traverser.clearFrontier();
1037
1059
  const completedNodes = state.getCompletedNodes();
1038
1060
  traverser.completedNodes = new Set(completedNodes);
1061
+ const hasOnlyConditionalIncomingEdges = (nodeId) => {
1062
+ const incomingEdges = blueprint.edges.filter((e) => e.target === nodeId);
1063
+ if (incomingEdges.length === 0) return false;
1064
+ const fromCompletedPredecessors = incomingEdges.filter((e) => completedNodes.has(e.source));
1065
+ if (fromCompletedPredecessors.length === 0) return false;
1066
+ return fromCompletedPredecessors.every((e) => e.condition !== void 0);
1067
+ };
1039
1068
  for (const node of traverser.dynamicBlueprint.nodes) {
1040
1069
  if (traverser.completedNodes.has(node.id)) continue;
1070
+ if (hasOnlyConditionalIncomingEdges(node.id)) continue;
1041
1071
  const requiredPredecessors = traverser.allPredecessors.get(node.id);
1042
1072
  const joinStrategy = traverser.getJoinStrategy(node.id);
1043
1073
  if (!requiredPredecessors || requiredPredecessors.size === 0) {
@@ -1117,6 +1147,7 @@ var GraphTraverser = class GraphTraverser {
1117
1147
  }
1118
1148
  if (nextNodes.length === 0) {
1119
1149
  for (const [potentialNextId, predecessors] of this.allPredecessors) if (predecessors.has(nodeId) && !this.completedNodes.has(potentialNextId)) {
1150
+ if (this.dynamicBlueprint.edges.some((e) => e.target === potentialNextId && e.condition)) continue;
1120
1151
  if (this.getJoinStrategy(potentialNextId) === "any" ? predecessors.has(nodeId) : [...predecessors].every((p) => this.completedNodes.has(p))) {
1121
1152
  this.frontier.add(potentialNextId);
1122
1153
  const node = this.getNode(potentialNextId, this.dynamicBlueprint);
@@ -1450,7 +1481,8 @@ var NodeExecutor = class {
1450
1481
  isFatal: false
1451
1482
  });
1452
1483
  const fallbackNodeId = this.nodeDef.config?.fallback;
1453
- if (fallbackNodeId && !flowcraftError.isFatal) {
1484
+ const isLastAttempt = this.context.state.isLastAttempt ?? true;
1485
+ if (fallbackNodeId && !flowcraftError.isFatal && isLastAttempt) {
1454
1486
  this.context.services.logger.warn(`Node failed, fallback required`, {
1455
1487
  nodeId: this.nodeDef.id,
1456
1488
  fallbackNodeId,
@@ -1579,17 +1611,21 @@ var NodeExecutorFactory = class {
1579
1611
  return new NodeExecutor({
1580
1612
  context,
1581
1613
  nodeDef,
1582
- strategy: this.getExecutionStrategy(nodeDef, context.nodeRegistry)
1614
+ strategy: this.getExecutionStrategy(nodeDef, context)
1583
1615
  });
1584
1616
  }
1585
- getExecutionStrategy(nodeDef, nodeRegistry) {
1586
- const implementation = nodeRegistry.get(nodeDef.uses);
1617
+ getExecutionStrategy(nodeDef, context) {
1618
+ const implementation = context.nodeRegistry.get(nodeDef.uses);
1587
1619
  if (!implementation) throw new FlowcraftError(`Implementation for '${nodeDef.uses}' not found.`, {
1588
1620
  nodeId: nodeDef.id,
1589
1621
  blueprintId: "",
1590
1622
  isFatal: true
1591
1623
  });
1592
- const maxRetries = nodeDef.config?.maxRetries ?? 1;
1624
+ let maxRetries = nodeDef.config?.maxRetries ?? 1;
1625
+ const adapter = context.services.dependencies?.adapter;
1626
+ if (adapter && typeof adapter.shouldRetryInProcess === "function") {
1627
+ if (!adapter.shouldRetryInProcess(nodeDef)) maxRetries = 1;
1628
+ }
1593
1629
  return isNodeClass(implementation) ? new ClassNodeExecutor(implementation, maxRetries, this.eventBus) : new FunctionNodeExecutor(implementation, maxRetries, this.eventBus);
1594
1630
  }
1595
1631
  };
@@ -1750,17 +1786,16 @@ var WorkflowLogicHandler = class {
1750
1786
  async applyEdgeTransform(edge, sourceResult, targetNode, context, allPredecessors, executionId) {
1751
1787
  const asyncContext = context.type === "sync" ? new AsyncContextView(context) : context;
1752
1788
  const predecessors = allPredecessors?.get(targetNode.id);
1753
- const hasSinglePredecessor = predecessors && predecessors.size === 1;
1789
+ predecessors && predecessors.size;
1754
1790
  const hasExplicitInputs = targetNode.inputs !== void 0;
1755
1791
  const hasEdgeTransform = edge.transform !== void 0;
1756
- if (!hasExplicitInputs && !hasSinglePredecessor && !hasEdgeTransform) return;
1757
1792
  let sourceOutput = sourceResult.output;
1758
1793
  if (hasEdgeTransform && hasExplicitInputs && typeof targetNode.inputs === "string") {
1759
1794
  const inputsKey = targetNode.inputs;
1760
1795
  const resolvedKey = inputsKey.startsWith("_") ? inputsKey : `_outputs.${inputsKey}`;
1761
1796
  if (await asyncContext.has(resolvedKey) && inputsKey !== edge.source) sourceOutput = await asyncContext.get(resolvedKey);
1762
1797
  }
1763
- const finalInput = edge.transform ? this.evaluator.evaluate(edge.transform, {
1798
+ const finalInput = hasEdgeTransform ? this.evaluator.evaluate(edge.transform, {
1764
1799
  input: sourceOutput,
1765
1800
  context: await asyncContext.toJSON()
1766
1801
  }) : sourceOutput;
@@ -2218,4 +2253,4 @@ var FlowRuntime = class {
2218
2253
 
2219
2254
  //#endregion
2220
2255
  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-CRwlRW2p.mjs.map
2256
+ //# sourceMappingURL=runtime-ChsWirQN.mjs.map