@valerypopoff/rivet2-core 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (523) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +15 -0
  3. package/dist/cjs/bundle.cjs +28772 -0
  4. package/dist/cjs/bundle.cjs.map +7 -0
  5. package/dist/esm/api/createProcessor.js +116 -0
  6. package/dist/esm/api/looseDataValue.js +16 -0
  7. package/dist/esm/api/processSettings.js +16 -0
  8. package/dist/esm/api/streaming.js +116 -0
  9. package/dist/esm/exports.js +48 -0
  10. package/dist/esm/index.js +2 -0
  11. package/dist/esm/integrations/AudioProvider.js +1 -0
  12. package/dist/esm/integrations/CodeRunner.js +44 -0
  13. package/dist/esm/integrations/DatasetProvider.js +92 -0
  14. package/dist/esm/integrations/EmbeddingGenerator.js +1 -0
  15. package/dist/esm/integrations/GptTokenizerTokenizer.js +67 -0
  16. package/dist/esm/integrations/LLMProvider.js +1 -0
  17. package/dist/esm/integrations/Tokenizer.js +1 -0
  18. package/dist/esm/integrations/VectorDatabase.js +1 -0
  19. package/dist/esm/integrations/enableIntegrations.js +3 -0
  20. package/dist/esm/integrations/integrations.js +19 -0
  21. package/dist/esm/integrations/mcp/MCPBase.js +87 -0
  22. package/dist/esm/integrations/mcp/MCPProvider.js +23 -0
  23. package/dist/esm/integrations/mcp/MCPUtils.js +33 -0
  24. package/dist/esm/integrations/openai/OpenAIEmbeddingGenerator.js +23 -0
  25. package/dist/esm/model/CycleDetector.js +43 -0
  26. package/dist/esm/model/DataValue.js +188 -0
  27. package/dist/esm/model/Dataset.js +1 -0
  28. package/dist/esm/model/EditorDefinition.js +1 -0
  29. package/dist/esm/model/ExecutorProtocol.js +1 -0
  30. package/dist/esm/model/GraphPreprocessor.js +97 -0
  31. package/dist/esm/model/GraphProcessor.js +1136 -0
  32. package/dist/esm/model/NodeBase.js +11 -0
  33. package/dist/esm/model/NodeBodySpec.js +1 -0
  34. package/dist/esm/model/NodeDefinition.js +12 -0
  35. package/dist/esm/model/NodeExecutionPlanner.js +82 -0
  36. package/dist/esm/model/NodeGraph.js +14 -0
  37. package/dist/esm/model/NodeImpl.js +57 -0
  38. package/dist/esm/model/NodeRegistration.js +146 -0
  39. package/dist/esm/model/Nodes.js +279 -0
  40. package/dist/esm/model/PluginLoadSpec.js +1 -0
  41. package/dist/esm/model/ProcessContext.js +1 -0
  42. package/dist/esm/model/ProcessContextBuilder.js +33 -0
  43. package/dist/esm/model/Project.js +2 -0
  44. package/dist/esm/model/ProjectReferenceLoader.js +1 -0
  45. package/dist/esm/model/RecordingPlayer.js +262 -0
  46. package/dist/esm/model/RegistryAssembly.js +53 -0
  47. package/dist/esm/model/RivetPlugin.js +1 -0
  48. package/dist/esm/model/RivetUIContext.js +1 -0
  49. package/dist/esm/model/Settings.js +1 -0
  50. package/dist/esm/model/SplitRunProcessor.js +98 -0
  51. package/dist/esm/model/SubprocessorBridge.js +82 -0
  52. package/dist/esm/model/chat/aiSdkMessages.js +105 -0
  53. package/dist/esm/model/chat/aiSdkStreaming.js +38 -0
  54. package/dist/esm/model/chat/aiSdkTools.js +10 -0
  55. package/dist/esm/model/chat/chatCost.js +33 -0
  56. package/dist/esm/model/chat/chatMessages.js +47 -0
  57. package/dist/esm/model/chat/openAIChatRequest.js +110 -0
  58. package/dist/esm/model/chat/openAIChatRuntime.js +220 -0
  59. package/dist/esm/model/chat/streamChatResponse.js +97 -0
  60. package/dist/esm/model/chat/tokenBudget.js +16 -0
  61. package/dist/esm/model/chat-v2/aiSdkBridge.js +88 -0
  62. package/dist/esm/model/chat-v2/chatV2EditorCache.js +107 -0
  63. package/dist/esm/model/chat-v2/chatV2Errors.js +255 -0
  64. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +16 -0
  65. package/dist/esm/model/chat-v2/chatV2Pipeline.js +387 -0
  66. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +57 -0
  67. package/dist/esm/model/chat-v2/chatV2Retry.js +41 -0
  68. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +242 -0
  69. package/dist/esm/model/chat-v2/chatV2Shared.js +285 -0
  70. package/dist/esm/model/chat-v2/chatV2Types.js +1 -0
  71. package/dist/esm/model/chat-v2/index.js +10 -0
  72. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +56 -0
  73. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +475 -0
  74. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +90 -0
  75. package/dist/esm/model/chat-v2/messageConverter.js +173 -0
  76. package/dist/esm/model/chat-v2/modelRegistry.js +23 -0
  77. package/dist/esm/model/chat-v2/providerOptions.js +202 -0
  78. package/dist/esm/model/chat-v2/toolContinuation.js +108 -0
  79. package/dist/esm/model/chat-v2/toolConverter.js +4 -0
  80. package/dist/esm/model/interpolationInputDefinition.js +36 -0
  81. package/dist/esm/model/loopControllerBreak.js +4 -0
  82. package/dist/esm/model/nodes/AbortGraphNode.js +100 -0
  83. package/dist/esm/model/nodes/AppendToDatasetNode.js +115 -0
  84. package/dist/esm/model/nodes/ArrayNode.js +144 -0
  85. package/dist/esm/model/nodes/AssembleMessageNode.js +209 -0
  86. package/dist/esm/model/nodes/AssemblePromptNode.js +151 -0
  87. package/dist/esm/model/nodes/AudioNode.js +101 -0
  88. package/dist/esm/model/nodes/BooleanNode.js +74 -0
  89. package/dist/esm/model/nodes/CallGraphNode.js +135 -0
  90. package/dist/esm/model/nodes/ChatLoopNode.js +150 -0
  91. package/dist/esm/model/nodes/ChatNode.js +56 -0
  92. package/dist/esm/model/nodes/ChatNodeBase.js +912 -0
  93. package/dist/esm/model/nodes/ChunkNode.js +166 -0
  94. package/dist/esm/model/nodes/CoalesceNode.js +104 -0
  95. package/dist/esm/model/nodes/CodeNode.js +197 -0
  96. package/dist/esm/model/nodes/CommentNode.js +71 -0
  97. package/dist/esm/model/nodes/CompareNode.js +144 -0
  98. package/dist/esm/model/nodes/ContextNode.js +99 -0
  99. package/dist/esm/model/nodes/CreateDatasetNode.js +71 -0
  100. package/dist/esm/model/nodes/CronNode.js +248 -0
  101. package/dist/esm/model/nodes/DatasetNearestNeigborsNode.js +97 -0
  102. package/dist/esm/model/nodes/DelayNode.js +105 -0
  103. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +175 -0
  104. package/dist/esm/model/nodes/DestructureNode.js +110 -0
  105. package/dist/esm/model/nodes/DocumentNode.js +183 -0
  106. package/dist/esm/model/nodes/EvaluateNode.js +141 -0
  107. package/dist/esm/model/nodes/ExpressionNode.js +143 -0
  108. package/dist/esm/model/nodes/ExternalCallNode.js +162 -0
  109. package/dist/esm/model/nodes/ExtractJsonNode.js +122 -0
  110. package/dist/esm/model/nodes/ExtractMarkdownCodeBlocksNode.js +100 -0
  111. package/dist/esm/model/nodes/ExtractObjectPathNode.js +159 -0
  112. package/dist/esm/model/nodes/ExtractRegexNode.js +200 -0
  113. package/dist/esm/model/nodes/ExtractYamlNode.js +214 -0
  114. package/dist/esm/model/nodes/FilterNode.js +73 -0
  115. package/dist/esm/model/nodes/GetAllDatasetsNode.js +53 -0
  116. package/dist/esm/model/nodes/GetDatasetRowNode.js +99 -0
  117. package/dist/esm/model/nodes/GetEmbeddingNode.js +130 -0
  118. package/dist/esm/model/nodes/GetGlobalNode.js +139 -0
  119. package/dist/esm/model/nodes/GraphInputNode.js +132 -0
  120. package/dist/esm/model/nodes/GraphOutputNode.js +104 -0
  121. package/dist/esm/model/nodes/GraphReferenceNode.js +128 -0
  122. package/dist/esm/model/nodes/HashNode.js +97 -0
  123. package/dist/esm/model/nodes/HttpCallNode.js +592 -0
  124. package/dist/esm/model/nodes/IfElseNode.js +138 -0
  125. package/dist/esm/model/nodes/IfNode.js +129 -0
  126. package/dist/esm/model/nodes/ImageNode.js +107 -0
  127. package/dist/esm/model/nodes/JSFilterNode.js +69 -0
  128. package/dist/esm/model/nodes/JSMapNode.js +69 -0
  129. package/dist/esm/model/nodes/JoinNode.js +135 -0
  130. package/dist/esm/model/nodes/LLMChatV2Node.js +234 -0
  131. package/dist/esm/model/nodes/ListGraphsNode.js +61 -0
  132. package/dist/esm/model/nodes/LoadDatasetNode.js +83 -0
  133. package/dist/esm/model/nodes/LoopControllerNode.js +206 -0
  134. package/dist/esm/model/nodes/LoopUntilNode.js +214 -0
  135. package/dist/esm/model/nodes/MCPDiscoveryNode.js +214 -0
  136. package/dist/esm/model/nodes/MCPGetPromptNode.js +234 -0
  137. package/dist/esm/model/nodes/MCPToolCallNode.js +262 -0
  138. package/dist/esm/model/nodes/MatchNode.js +160 -0
  139. package/dist/esm/model/nodes/NumberNode.js +86 -0
  140. package/dist/esm/model/nodes/ObjectNode.js +152 -0
  141. package/dist/esm/model/nodes/PassthroughNode.js +78 -0
  142. package/dist/esm/model/nodes/PlayAudioNode.js +61 -0
  143. package/dist/esm/model/nodes/PopNode.js +89 -0
  144. package/dist/esm/model/nodes/PromptNode.js +248 -0
  145. package/dist/esm/model/nodes/RaceInputsNode.js +85 -0
  146. package/dist/esm/model/nodes/RaiseEventNode.js +84 -0
  147. package/dist/esm/model/nodes/RandomNumberNode.js +117 -0
  148. package/dist/esm/model/nodes/ReadAllFilesNode.js +210 -0
  149. package/dist/esm/model/nodes/ReadDirectoryNode.js +171 -0
  150. package/dist/esm/model/nodes/ReadFileNode.js +114 -0
  151. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +199 -0
  152. package/dist/esm/model/nodes/ReplaceDatasetNode.js +118 -0
  153. package/dist/esm/model/nodes/SetGlobalNode.js +124 -0
  154. package/dist/esm/model/nodes/ShuffleNode.js +64 -0
  155. package/dist/esm/model/nodes/SliceNode.js +99 -0
  156. package/dist/esm/model/nodes/SplitNode.js +101 -0
  157. package/dist/esm/model/nodes/SubGraphNode.js +180 -0
  158. package/dist/esm/model/nodes/TextNode.js +125 -0
  159. package/dist/esm/model/nodes/ToJsonNode.js +78 -0
  160. package/dist/esm/model/nodes/ToMarkdownTableNode.js +119 -0
  161. package/dist/esm/model/nodes/ToTreeNode.js +133 -0
  162. package/dist/esm/model/nodes/ToYamlNode.js +68 -0
  163. package/dist/esm/model/nodes/ToolNode.js +172 -0
  164. package/dist/esm/model/nodes/TrimChatMessagesNode.js +120 -0
  165. package/dist/esm/model/nodes/URLReferenceNode.js +79 -0
  166. package/dist/esm/model/nodes/UserInputNode.js +109 -0
  167. package/dist/esm/model/nodes/VectorNearestNeighborsNode.js +127 -0
  168. package/dist/esm/model/nodes/VectorStoreNode.js +124 -0
  169. package/dist/esm/model/nodes/WaitForEventNode.js +88 -0
  170. package/dist/esm/model/nodes/codeNodeErrorDiagnostics.js +104 -0
  171. package/dist/esm/model/nodes/jsListCallbackHelpers.js +196 -0
  172. package/dist/esm/model/nodes/jsValueInterpolation.js +163 -0
  173. package/dist/esm/model/nodes/toolCallDelegation.js +159 -0
  174. package/dist/esm/native/BaseDir.js +32 -0
  175. package/dist/esm/native/BrowserNativeApi.js +19 -0
  176. package/dist/esm/native/NativeApi.js +1 -0
  177. package/dist/esm/plugins/anthropic/anthropic.js +208 -0
  178. package/dist/esm/plugins/anthropic/fetchEventSource.js +107 -0
  179. package/dist/esm/plugins/anthropic/index.js +2 -0
  180. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +767 -0
  181. package/dist/esm/plugins/anthropic/plugin.js +26 -0
  182. package/dist/esm/plugins/assemblyAi/LemurActionItemsNode.js +75 -0
  183. package/dist/esm/plugins/assemblyAi/LemurQaNode.js +155 -0
  184. package/dist/esm/plugins/assemblyAi/LemurSummaryNode.js +79 -0
  185. package/dist/esm/plugins/assemblyAi/LemurTaskNode.js +82 -0
  186. package/dist/esm/plugins/assemblyAi/TranscribeAudioNode.js +126 -0
  187. package/dist/esm/plugins/assemblyAi/index.js +2 -0
  188. package/dist/esm/plugins/assemblyAi/lemurHelpers.js +114 -0
  189. package/dist/esm/plugins/assemblyAi/plugin.js +32 -0
  190. package/dist/esm/plugins/autoevals/AutoEvalsNode.js +223 -0
  191. package/dist/esm/plugins/autoevals/index.js +2 -0
  192. package/dist/esm/plugins/autoevals/plugin.js +8 -0
  193. package/dist/esm/plugins/gentrace/index.js +3 -0
  194. package/dist/esm/plugins/gentrace/plugin.js +195 -0
  195. package/dist/esm/plugins/google/google.js +165 -0
  196. package/dist/esm/plugins/google/index.js +2 -0
  197. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +584 -0
  198. package/dist/esm/plugins/google/plugin.js +39 -0
  199. package/dist/esm/plugins/huggingface/index.js +2 -0
  200. package/dist/esm/plugins/huggingface/nodes/ChatHuggingFace.js +243 -0
  201. package/dist/esm/plugins/huggingface/nodes/TextToImageHuggingFace.js +189 -0
  202. package/dist/esm/plugins/huggingface/plugin.js +26 -0
  203. package/dist/esm/plugins/openai/handleOpenaiError.js +17 -0
  204. package/dist/esm/plugins/openai/index.js +2 -0
  205. package/dist/esm/plugins/openai/nodes/AttachAssistantFileNode.js +123 -0
  206. package/dist/esm/plugins/openai/nodes/CreateAssistantNode.js +289 -0
  207. package/dist/esm/plugins/openai/nodes/CreateThreadMessageNode.js +176 -0
  208. package/dist/esm/plugins/openai/nodes/CreateThreadNode.js +157 -0
  209. package/dist/esm/plugins/openai/nodes/DeleteAssistantNode.js +104 -0
  210. package/dist/esm/plugins/openai/nodes/DeleteThreadNode.js +97 -0
  211. package/dist/esm/plugins/openai/nodes/GetAssistantNode.js +118 -0
  212. package/dist/esm/plugins/openai/nodes/GetOpenAIFileNode.js +100 -0
  213. package/dist/esm/plugins/openai/nodes/GetThreadNode.js +108 -0
  214. package/dist/esm/plugins/openai/nodes/ListAssistantsNode.js +202 -0
  215. package/dist/esm/plugins/openai/nodes/ListOpenAIFilesNode.js +94 -0
  216. package/dist/esm/plugins/openai/nodes/ListThreadMessagesNode.js +224 -0
  217. package/dist/esm/plugins/openai/nodes/RunThreadNode.js +630 -0
  218. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +143 -0
  219. package/dist/esm/plugins/openai/nodes/UploadFileNode.js +121 -0
  220. package/dist/esm/plugins/openai/plugin.js +44 -0
  221. package/dist/esm/plugins/pinecone/PineconeVectorDatabase.js +88 -0
  222. package/dist/esm/plugins/pinecone/index.js +2 -0
  223. package/dist/esm/plugins/pinecone/plugin.js +19 -0
  224. package/dist/esm/plugins.js +29 -0
  225. package/dist/esm/recording/ExecutionRecorder.js +273 -0
  226. package/dist/esm/recording/RecordedEvents.js +1 -0
  227. package/dist/esm/utils/assertNever.js +3 -0
  228. package/dist/esm/utils/base64.js +38 -0
  229. package/dist/esm/utils/chatMessageToOpenAIChatCompletionMessage.js +73 -0
  230. package/dist/esm/utils/coerceType.js +326 -0
  231. package/dist/esm/utils/compatibility.js +27 -0
  232. package/dist/esm/utils/copyToClipboard.js +10 -0
  233. package/dist/esm/utils/defaults.js +2 -0
  234. package/dist/esm/utils/emitDetached.js +12 -0
  235. package/dist/esm/utils/errors.js +7 -0
  236. package/dist/esm/utils/expectType.js +34 -0
  237. package/dist/esm/utils/fetchEventSource.js +120 -0
  238. package/dist/esm/utils/genericUtilFunctions.js +25 -0
  239. package/dist/esm/utils/getPluginConfig.js +23 -0
  240. package/dist/esm/utils/handleEscapeCharacters.js +11 -0
  241. package/dist/esm/utils/index.js +17 -0
  242. package/dist/esm/utils/inputs.js +16 -0
  243. package/dist/esm/utils/interpolation.js +286 -0
  244. package/dist/esm/utils/misc.js +1 -0
  245. package/dist/esm/utils/newId.js +4 -0
  246. package/dist/esm/utils/openai.js +206 -0
  247. package/dist/esm/utils/orderedStringPortIds.js +27 -0
  248. package/dist/esm/utils/outputs.js +14 -0
  249. package/dist/esm/utils/pQueueCompat.js +12 -0
  250. package/dist/esm/utils/paths.js +80 -0
  251. package/dist/esm/utils/providerStreamParsing.js +14 -0
  252. package/dist/esm/utils/runtimeLogging.js +121 -0
  253. package/dist/esm/utils/serialization/serialization.js +77 -0
  254. package/dist/esm/utils/serialization/serializationHelpers.js +63 -0
  255. package/dist/esm/utils/serialization/serializationUtils.js +112 -0
  256. package/dist/esm/utils/serialization/serialization_v1.js +19 -0
  257. package/dist/esm/utils/serialization/serialization_v2.js +24 -0
  258. package/dist/esm/utils/serialization/serialization_v3.js +100 -0
  259. package/dist/esm/utils/serialization/serialization_v4.js +156 -0
  260. package/dist/esm/utils/symbols.js +2 -0
  261. package/dist/esm/utils/time.js +14 -0
  262. package/dist/esm/utils/typeSafety.js +42 -0
  263. package/dist/esm/vendor/fnv1a.js +80 -0
  264. package/dist/types/api/createProcessor.d.ts +56 -0
  265. package/dist/types/api/looseDataValue.d.ts +4 -0
  266. package/dist/types/api/processSettings.d.ts +4 -0
  267. package/dist/types/api/streaming.d.ts +56 -0
  268. package/dist/types/exports.d.ts +49 -0
  269. package/dist/types/index.d.ts +4 -0
  270. package/dist/types/integrations/AudioProvider.d.ts +4 -0
  271. package/dist/types/integrations/CodeRunner.d.ts +19 -0
  272. package/dist/types/integrations/DatasetProvider.d.ts +33 -0
  273. package/dist/types/integrations/EmbeddingGenerator.d.ts +3 -0
  274. package/dist/types/integrations/GptTokenizerTokenizer.d.ts +20 -0
  275. package/dist/types/integrations/LLMProvider.d.ts +7 -0
  276. package/dist/types/integrations/Tokenizer.d.ts +11 -0
  277. package/dist/types/integrations/VectorDatabase.d.ts +7 -0
  278. package/dist/types/integrations/enableIntegrations.d.ts +1 -0
  279. package/dist/types/integrations/integrations.d.ts +12 -0
  280. package/dist/types/integrations/mcp/MCPBase.d.ts +18 -0
  281. package/dist/types/integrations/mcp/MCPProvider.d.ts +153 -0
  282. package/dist/types/integrations/mcp/MCPUtils.d.ts +9 -0
  283. package/dist/types/integrations/openai/OpenAIEmbeddingGenerator.d.ts +10 -0
  284. package/dist/types/model/CycleDetector.d.ts +2 -0
  285. package/dist/types/model/DataValue.d.ts +160 -0
  286. package/dist/types/model/Dataset.d.ts +19 -0
  287. package/dist/types/model/EditorDefinition.d.ts +176 -0
  288. package/dist/types/model/ExecutorProtocol.d.ts +216 -0
  289. package/dist/types/model/GraphPreprocessor.d.ts +24 -0
  290. package/dist/types/model/GraphProcessor.d.ts +210 -0
  291. package/dist/types/model/NodeBase.d.ts +116 -0
  292. package/dist/types/model/NodeBodySpec.d.ts +19 -0
  293. package/dist/types/model/NodeDefinition.d.ts +13 -0
  294. package/dist/types/model/NodeExecutionPlanner.d.ts +28 -0
  295. package/dist/types/model/NodeGraph.d.ts +15 -0
  296. package/dist/types/model/NodeImpl.d.ts +56 -0
  297. package/dist/types/model/NodeRegistration.d.ts +29 -0
  298. package/dist/types/model/Nodes.d.ts +112 -0
  299. package/dist/types/model/PluginLoadSpec.d.ts +17 -0
  300. package/dist/types/model/ProcessContext.d.ts +110 -0
  301. package/dist/types/model/ProcessContextBuilder.d.ts +41 -0
  302. package/dist/types/model/Project.d.ts +31 -0
  303. package/dist/types/model/ProjectReferenceLoader.d.ts +5 -0
  304. package/dist/types/model/RecordingPlayer.d.ts +27 -0
  305. package/dist/types/model/RegistryAssembly.d.ts +42 -0
  306. package/dist/types/model/RivetPlugin.d.ts +51 -0
  307. package/dist/types/model/RivetUIContext.d.ts +27 -0
  308. package/dist/types/model/Settings.d.ts +20 -0
  309. package/dist/types/model/SplitRunProcessor.d.ts +31 -0
  310. package/dist/types/model/SubprocessorBridge.d.ts +13 -0
  311. package/dist/types/model/chat/aiSdkMessages.d.ts +3 -0
  312. package/dist/types/model/chat/aiSdkStreaming.d.ts +9 -0
  313. package/dist/types/model/chat/aiSdkTools.d.ts +3 -0
  314. package/dist/types/model/chat/chatCost.d.ts +30 -0
  315. package/dist/types/model/chat/chatMessages.d.ts +5 -0
  316. package/dist/types/model/chat/openAIChatRequest.d.ts +39 -0
  317. package/dist/types/model/chat/openAIChatRuntime.d.ts +61 -0
  318. package/dist/types/model/chat/streamChatResponse.d.ts +27 -0
  319. package/dist/types/model/chat/tokenBudget.d.ts +3 -0
  320. package/dist/types/model/chat-v2/aiSdkBridge.d.ts +2 -0
  321. package/dist/types/model/chat-v2/chatV2EditorCache.d.ts +25 -0
  322. package/dist/types/model/chat-v2/chatV2Errors.d.ts +23 -0
  323. package/dist/types/model/chat-v2/chatV2FeatureCompatibility.d.ts +12 -0
  324. package/dist/types/model/chat-v2/chatV2Pipeline.d.ts +2 -0
  325. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +24 -0
  326. package/dist/types/model/chat-v2/chatV2Retry.d.ts +5 -0
  327. package/dist/types/model/chat-v2/chatV2RuntimeOptions.d.ts +12 -0
  328. package/dist/types/model/chat-v2/chatV2Shared.d.ts +56 -0
  329. package/dist/types/model/chat-v2/chatV2Types.d.ts +110 -0
  330. package/dist/types/model/chat-v2/index.d.ts +10 -0
  331. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +73 -0
  332. package/dist/types/model/chat-v2/llmChatV2NodeEditors.d.ts +4 -0
  333. package/dist/types/model/chat-v2/llmChatV2NodeRuntime.d.ts +23 -0
  334. package/dist/types/model/chat-v2/messageConverter.d.ts +8 -0
  335. package/dist/types/model/chat-v2/modelRegistry.d.ts +296 -0
  336. package/dist/types/model/chat-v2/providerOptions.d.ts +59 -0
  337. package/dist/types/model/chat-v2/toolContinuation.d.ts +15 -0
  338. package/dist/types/model/chat-v2/toolConverter.d.ts +3 -0
  339. package/dist/types/model/interpolationInputDefinition.d.ts +16 -0
  340. package/dist/types/model/loopControllerBreak.d.ts +3 -0
  341. package/dist/types/model/nodes/AbortGraphNode.d.ts +22 -0
  342. package/dist/types/model/nodes/AppendToDatasetNode.d.ts +21 -0
  343. package/dist/types/model/nodes/ArrayNode.d.ts +20 -0
  344. package/dist/types/model/nodes/AssembleMessageNode.d.ts +23 -0
  345. package/dist/types/model/nodes/AssemblePromptNode.d.ts +23 -0
  346. package/dist/types/model/nodes/AudioNode.d.ts +20 -0
  347. package/dist/types/model/nodes/BooleanNode.d.ts +19 -0
  348. package/dist/types/model/nodes/CallGraphNode.d.ts +16 -0
  349. package/dist/types/model/nodes/ChatLoopNode.d.ts +21 -0
  350. package/dist/types/model/nodes/ChatNode.d.ts +17 -0
  351. package/dist/types/model/nodes/ChatNodeBase.d.ts +85 -0
  352. package/dist/types/model/nodes/ChunkNode.d.ts +22 -0
  353. package/dist/types/model/nodes/CoalesceNode.d.ts +14 -0
  354. package/dist/types/model/nodes/CodeNode.d.ts +27 -0
  355. package/dist/types/model/nodes/CommentNode.d.ts +20 -0
  356. package/dist/types/model/nodes/CompareNode.d.ts +19 -0
  357. package/dist/types/model/nodes/ContextNode.d.ts +24 -0
  358. package/dist/types/model/nodes/CreateDatasetNode.d.ts +13 -0
  359. package/dist/types/model/nodes/CronNode.d.ts +34 -0
  360. package/dist/types/model/nodes/DatasetNearestNeigborsNode.d.ts +19 -0
  361. package/dist/types/model/nodes/DelayNode.d.ts +20 -0
  362. package/dist/types/model/nodes/DelegateFunctionCallNode.d.ts +28 -0
  363. package/dist/types/model/nodes/DestructureNode.d.ts +19 -0
  364. package/dist/types/model/nodes/DocumentNode.d.ts +28 -0
  365. package/dist/types/model/nodes/EvaluateNode.d.ts +19 -0
  366. package/dist/types/model/nodes/ExpressionNode.d.ts +21 -0
  367. package/dist/types/model/nodes/ExternalCallNode.d.ts +22 -0
  368. package/dist/types/model/nodes/ExtractJsonNode.d.ts +13 -0
  369. package/dist/types/model/nodes/ExtractMarkdownCodeBlocksNode.d.ts +12 -0
  370. package/dist/types/model/nodes/ExtractObjectPathNode.d.ts +22 -0
  371. package/dist/types/model/nodes/ExtractRegexNode.d.ts +22 -0
  372. package/dist/types/model/nodes/ExtractYamlNode.d.ts +21 -0
  373. package/dist/types/model/nodes/FilterNode.d.ts +13 -0
  374. package/dist/types/model/nodes/GetAllDatasetsNode.d.ts +14 -0
  375. package/dist/types/model/nodes/GetDatasetRowNode.d.ts +19 -0
  376. package/dist/types/model/nodes/GetEmbeddingNode.d.ts +24 -0
  377. package/dist/types/model/nodes/GetGlobalNode.d.ts +29 -0
  378. package/dist/types/model/nodes/GraphInputNode.d.ts +24 -0
  379. package/dist/types/model/nodes/GraphOutputNode.d.ts +22 -0
  380. package/dist/types/model/nodes/GraphReferenceNode.d.ts +22 -0
  381. package/dist/types/model/nodes/HashNode.d.ts +17 -0
  382. package/dist/types/model/nodes/HttpCallNode.d.ts +32 -0
  383. package/dist/types/model/nodes/IfElseNode.d.ts +18 -0
  384. package/dist/types/model/nodes/IfNode.d.ts +17 -0
  385. package/dist/types/model/nodes/ImageNode.d.ts +20 -0
  386. package/dist/types/model/nodes/JSFilterNode.d.ts +19 -0
  387. package/dist/types/model/nodes/JSMapNode.d.ts +19 -0
  388. package/dist/types/model/nodes/JoinNode.d.ts +21 -0
  389. package/dist/types/model/nodes/LLMChatV2Node.d.ts +20 -0
  390. package/dist/types/model/nodes/ListGraphsNode.d.ts +14 -0
  391. package/dist/types/model/nodes/LoadDatasetNode.d.ts +17 -0
  392. package/dist/types/model/nodes/LoopControllerNode.d.ts +20 -0
  393. package/dist/types/model/nodes/LoopUntilNode.d.ts +32 -0
  394. package/dist/types/model/nodes/MCPDiscoveryNode.d.ts +9 -0
  395. package/dist/types/model/nodes/MCPGetPromptNode.d.ts +23 -0
  396. package/dist/types/model/nodes/MCPToolCallNode.d.ts +26 -0
  397. package/dist/types/model/nodes/MatchNode.d.ts +20 -0
  398. package/dist/types/model/nodes/NumberNode.d.ts +21 -0
  399. package/dist/types/model/nodes/ObjectNode.d.ts +19 -0
  400. package/dist/types/model/nodes/PassthroughNode.d.ts +14 -0
  401. package/dist/types/model/nodes/PlayAudioNode.d.ts +15 -0
  402. package/dist/types/model/nodes/PopNode.d.ts +19 -0
  403. package/dist/types/model/nodes/PromptNode.d.ts +25 -0
  404. package/dist/types/model/nodes/RaceInputsNode.d.ts +16 -0
  405. package/dist/types/model/nodes/RaiseEventNode.d.ts +22 -0
  406. package/dist/types/model/nodes/RandomNumberNode.d.ts +23 -0
  407. package/dist/types/model/nodes/ReadAllFilesNode.d.ts +30 -0
  408. package/dist/types/model/nodes/ReadDirectoryNode.d.ts +30 -0
  409. package/dist/types/model/nodes/ReadFileNode.d.ts +23 -0
  410. package/dist/types/model/nodes/ReferencedGraphAliasNode.d.ts +31 -0
  411. package/dist/types/model/nodes/ReplaceDatasetNode.d.ts +21 -0
  412. package/dist/types/model/nodes/SetGlobalNode.d.ts +23 -0
  413. package/dist/types/model/nodes/ShuffleNode.d.ts +12 -0
  414. package/dist/types/model/nodes/SliceNode.d.ts +22 -0
  415. package/dist/types/model/nodes/SplitNode.d.ts +19 -0
  416. package/dist/types/model/nodes/SubGraphNode.d.ts +29 -0
  417. package/dist/types/model/nodes/TextNode.d.ts +19 -0
  418. package/dist/types/model/nodes/ToJsonNode.d.ts +18 -0
  419. package/dist/types/model/nodes/ToMarkdownTableNode.d.ts +19 -0
  420. package/dist/types/model/nodes/ToTreeNode.d.ts +21 -0
  421. package/dist/types/model/nodes/ToYamlNode.d.ts +13 -0
  422. package/dist/types/model/nodes/ToolNode.d.ts +25 -0
  423. package/dist/types/model/nodes/TrimChatMessagesNode.d.ts +20 -0
  424. package/dist/types/model/nodes/URLReferenceNode.d.ts +19 -0
  425. package/dist/types/model/nodes/UserInputNode.d.ts +20 -0
  426. package/dist/types/model/nodes/VectorNearestNeighborsNode.d.ts +24 -0
  427. package/dist/types/model/nodes/VectorStoreNode.d.ts +22 -0
  428. package/dist/types/model/nodes/WaitForEventNode.d.ts +21 -0
  429. package/dist/types/model/nodes/codeNodeErrorDiagnostics.d.ts +9 -0
  430. package/dist/types/model/nodes/jsListCallbackHelpers.d.ts +23 -0
  431. package/dist/types/model/nodes/jsValueInterpolation.d.ts +11 -0
  432. package/dist/types/model/nodes/toolCallDelegation.d.ts +29 -0
  433. package/dist/types/native/BaseDir.d.ts +29 -0
  434. package/dist/types/native/BrowserNativeApi.d.ts +9 -0
  435. package/dist/types/native/NativeApi.d.ts +17 -0
  436. package/dist/types/plugins/anthropic/anthropic.d.ts +315 -0
  437. package/dist/types/plugins/anthropic/fetchEventSource.d.ts +11 -0
  438. package/dist/types/plugins/anthropic/index.d.ts +2 -0
  439. package/dist/types/plugins/anthropic/nodes/ChatAnthropicNode.d.ts +40 -0
  440. package/dist/types/plugins/anthropic/plugin.d.ts +2 -0
  441. package/dist/types/plugins/assemblyAi/LemurActionItemsNode.d.ts +6 -0
  442. package/dist/types/plugins/assemblyAi/LemurQaNode.d.ts +22 -0
  443. package/dist/types/plugins/assemblyAi/LemurSummaryNode.d.ts +8 -0
  444. package/dist/types/plugins/assemblyAi/LemurTaskNode.d.ts +8 -0
  445. package/dist/types/plugins/assemblyAi/TranscribeAudioNode.d.ts +7 -0
  446. package/dist/types/plugins/assemblyAi/index.d.ts +2 -0
  447. package/dist/types/plugins/assemblyAi/lemurHelpers.d.ts +67 -0
  448. package/dist/types/plugins/assemblyAi/plugin.d.ts +2 -0
  449. package/dist/types/plugins/autoevals/AutoEvalsNode.d.ts +8 -0
  450. package/dist/types/plugins/autoevals/index.d.ts +2 -0
  451. package/dist/types/plugins/autoevals/plugin.d.ts +2 -0
  452. package/dist/types/plugins/gentrace/index.d.ts +2 -0
  453. package/dist/types/plugins/gentrace/plugin.d.ts +10 -0
  454. package/dist/types/plugins/google/google.d.ts +129 -0
  455. package/dist/types/plugins/google/index.d.ts +2 -0
  456. package/dist/types/plugins/google/nodes/ChatGoogleNode.d.ts +35 -0
  457. package/dist/types/plugins/google/plugin.d.ts +2 -0
  458. package/dist/types/plugins/huggingface/index.d.ts +2 -0
  459. package/dist/types/plugins/huggingface/nodes/ChatHuggingFace.d.ts +24 -0
  460. package/dist/types/plugins/huggingface/nodes/TextToImageHuggingFace.d.ts +20 -0
  461. package/dist/types/plugins/huggingface/plugin.d.ts +2 -0
  462. package/dist/types/plugins/openai/handleOpenaiError.d.ts +1 -0
  463. package/dist/types/plugins/openai/index.d.ts +2 -0
  464. package/dist/types/plugins/openai/nodes/AttachAssistantFileNode.d.ts +10 -0
  465. package/dist/types/plugins/openai/nodes/CreateAssistantNode.d.ts +26 -0
  466. package/dist/types/plugins/openai/nodes/CreateThreadMessageNode.d.ts +15 -0
  467. package/dist/types/plugins/openai/nodes/CreateThreadNode.d.ts +13 -0
  468. package/dist/types/plugins/openai/nodes/DeleteAssistantNode.d.ts +8 -0
  469. package/dist/types/plugins/openai/nodes/DeleteThreadNode.d.ts +8 -0
  470. package/dist/types/plugins/openai/nodes/GetAssistantNode.d.ts +8 -0
  471. package/dist/types/plugins/openai/nodes/GetOpenAIFileNode.d.ts +8 -0
  472. package/dist/types/plugins/openai/nodes/GetThreadNode.d.ts +8 -0
  473. package/dist/types/plugins/openai/nodes/ListAssistantsNode.d.ts +14 -0
  474. package/dist/types/plugins/openai/nodes/ListOpenAIFilesNode.d.ts +8 -0
  475. package/dist/types/plugins/openai/nodes/ListThreadMessagesNode.d.ts +16 -0
  476. package/dist/types/plugins/openai/nodes/RunThreadNode.d.ts +28 -0
  477. package/dist/types/plugins/openai/nodes/ThreadMessageNode.d.ts +14 -0
  478. package/dist/types/plugins/openai/nodes/UploadFileNode.d.ts +7 -0
  479. package/dist/types/plugins/openai/plugin.d.ts +2 -0
  480. package/dist/types/plugins/pinecone/PineconeVectorDatabase.d.ts +9 -0
  481. package/dist/types/plugins/pinecone/index.d.ts +2 -0
  482. package/dist/types/plugins/pinecone/plugin.d.ts +2 -0
  483. package/dist/types/plugins.d.ts +22 -0
  484. package/dist/types/recording/ExecutionRecorder.d.ts +27 -0
  485. package/dist/types/recording/RecordedEvents.d.ts +114 -0
  486. package/dist/types/utils/assertNever.d.ts +1 -0
  487. package/dist/types/utils/base64.d.ts +3 -0
  488. package/dist/types/utils/chatMessageToOpenAIChatCompletionMessage.d.ts +5 -0
  489. package/dist/types/utils/coerceType.d.ts +6 -0
  490. package/dist/types/utils/compatibility.d.ts +3 -0
  491. package/dist/types/utils/copyToClipboard.d.ts +1 -0
  492. package/dist/types/utils/defaults.d.ts +2 -0
  493. package/dist/types/utils/emitDetached.d.ts +11 -0
  494. package/dist/types/utils/errors.d.ts +2 -0
  495. package/dist/types/utils/expectType.d.ts +3 -0
  496. package/dist/types/utils/fetchEventSource.d.ts +12 -0
  497. package/dist/types/utils/genericUtilFunctions.d.ts +21 -0
  498. package/dist/types/utils/getPluginConfig.d.ts +2 -0
  499. package/dist/types/utils/handleEscapeCharacters.d.ts +2 -0
  500. package/dist/types/utils/index.d.ts +17 -0
  501. package/dist/types/utils/inputs.d.ts +3 -0
  502. package/dist/types/utils/interpolation.d.ts +26 -0
  503. package/dist/types/utils/misc.d.ts +1 -0
  504. package/dist/types/utils/newId.d.ts +1 -0
  505. package/dist/types/utils/openai.d.ts +784 -0
  506. package/dist/types/utils/orderedStringPortIds.d.ts +10 -0
  507. package/dist/types/utils/outputs.d.ts +3 -0
  508. package/dist/types/utils/pQueueCompat.d.ts +10 -0
  509. package/dist/types/utils/paths.d.ts +8 -0
  510. package/dist/types/utils/providerStreamParsing.d.ts +1 -0
  511. package/dist/types/utils/runtimeLogging.d.ts +10 -0
  512. package/dist/types/utils/serialization/serialization.d.ts +12 -0
  513. package/dist/types/utils/serialization/serializationHelpers.d.ts +27 -0
  514. package/dist/types/utils/serialization/serializationUtils.d.ts +16 -0
  515. package/dist/types/utils/serialization/serialization_v1.d.ts +3 -0
  516. package/dist/types/utils/serialization/serialization_v2.d.ts +3 -0
  517. package/dist/types/utils/serialization/serialization_v3.d.ts +19 -0
  518. package/dist/types/utils/serialization/serialization_v4.d.ts +9 -0
  519. package/dist/types/utils/symbols.d.ts +3 -0
  520. package/dist/types/utils/time.d.ts +22 -0
  521. package/dist/types/utils/typeSafety.d.ts +37 -0
  522. package/dist/types/vendor/fnv1a.d.ts +9 -0
  523. package/package.json +77 -0
@@ -0,0 +1,1136 @@
1
+ import { getScalarTypeOf, } from './DataValue.js';
2
+ import { IF_PORT, } from './NodeBase.js';
3
+ import PQueue from '../utils/pQueueCompat.js';
4
+ import { getError } from '../utils/errors.js';
5
+ import Emittery from 'emittery';
6
+ import { entries } from '../utils/typeSafety.js';
7
+ import {} from './Project.js';
8
+ import { nanoid } from 'nanoid/non-secure';
9
+ import { coerceTypeOptional } from '../utils/coerceType.js';
10
+ import { getPluginConfig } from '../utils/index.js';
11
+ import { preprocessGraphState } from './GraphPreprocessor.js';
12
+ import { replayExecutionRecording } from './RecordingPlayer.js';
13
+ import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
14
+ import { buildNodeProcessContext } from './ProcessContextBuilder.js';
15
+ import { processSplitRunNode } from './SplitRunProcessor.js';
16
+ import { areRequiredInputsConnected, getInputNodesTo, getOutputNodesFrom, getStartNodes, getWaitingForInputNode, hasErroredInputNode, } from './NodeExecutionPlanner.js';
17
+ import { wireSubprocessorEvents, wireSubprocessorLifecycle } from './SubprocessorBridge.js';
18
+ import { emitDetached } from '../utils/emitDetached.js';
19
+ // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
20
+ import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
21
+ const DEFAULT_NODE_CONCURRENCY = 8;
22
+ export const DEFAULT_SPLIT_RUN_CONCURRENCY = 4;
23
+ function normalizeConcurrencyValue(value, fallback) {
24
+ return typeof value === 'number' && Number.isFinite(value) && value >= 1 ? Math.floor(value) : fallback;
25
+ }
26
+ function resolveGraphProcessorConcurrency(concurrency) {
27
+ return {
28
+ nodeConcurrency: normalizeConcurrencyValue(concurrency?.nodeConcurrency, DEFAULT_NODE_CONCURRENCY),
29
+ splitRunConcurrency: normalizeConcurrencyValue(concurrency?.splitRunConcurrency, DEFAULT_SPLIT_RUN_CONCURRENCY),
30
+ };
31
+ }
32
+ export class GraphProcessor {
33
+ // Per-instance state
34
+ #graph;
35
+ #project;
36
+ #nodesById;
37
+ #nodeInstances;
38
+ #connections;
39
+ #emitter = new Emittery();
40
+ #running = false;
41
+ #isSubProcessor = false;
42
+ #externalFunctions = {};
43
+ slowMode = false;
44
+ #isPaused = false;
45
+ #parent;
46
+ #registry;
47
+ #concurrency;
48
+ id = nanoid();
49
+ #includeTrace = true;
50
+ executor;
51
+ /** If set, specifies the node(s) that the graph will run TO, instead of the nodes without any dependents. */
52
+ runToNodeIds;
53
+ /** If set, specifies the node that the graph will run FROM, instead of the start nodes. Requires preloading data. */
54
+ runFromNodeId;
55
+ /** The node that is executing this graph, almost always a subgraph node. Undefined for root. */
56
+ #executor;
57
+ #rootRunId = undefined;
58
+ #graphRunId = undefined;
59
+ #parentGraphRunId = undefined;
60
+ /** The interval between nodeFinish events when playing back a recording. I.e. how fast the playback is. */
61
+ recordingPlaybackChatLatency = 1000;
62
+ warnOnInvalidGraph = false;
63
+ // Per-process state
64
+ #erroredNodes = undefined; // Values are strings in recordings
65
+ #remainingNodes = undefined;
66
+ #visitedNodes = undefined;
67
+ #currentlyProcessing = undefined;
68
+ #context = undefined;
69
+ #nodeResults = undefined;
70
+ #abortController = undefined;
71
+ #processingQueue = undefined;
72
+ #graphInputs = undefined;
73
+ #graphOutputs = undefined;
74
+ #executionCache = undefined;
75
+ #queuedNodes = undefined;
76
+ #loopControllersSeen = undefined;
77
+ #subprocessors = undefined;
78
+ #contextValues = undefined;
79
+ #globals = undefined;
80
+ #attachedNodeData = undefined;
81
+ #aborted = false;
82
+ #abortSuccessfully = false;
83
+ #abortError = undefined;
84
+ #totalCost = 0;
85
+ #ignoreNodes = undefined;
86
+ #hasPreloadedData = false;
87
+ #loadedProjects = undefined;
88
+ #definitions = undefined;
89
+ #scc = undefined;
90
+ // @ts-expect-error
91
+ #nodesNotInCycle = undefined;
92
+ #nodeAbortControllers = new Map();
93
+ #graphInputNodeValues = {};
94
+ /** User input nodes that are pending user input. */
95
+ #pendingUserInputs = undefined;
96
+ #finishEmitted = false;
97
+ #unsubscribeTokenizerError;
98
+ get isRunning() {
99
+ return this.#running;
100
+ }
101
+ constructor(project, graphId, registry, includeTrace, options) {
102
+ this.#project = project;
103
+ const graph = graphId
104
+ ? project.graphs[graphId]
105
+ : project.metadata.mainGraphId
106
+ ? project.graphs[project.metadata.mainGraphId]
107
+ : undefined;
108
+ if (!graph) {
109
+ throw new Error(`Graph ${graphId} not found in project`);
110
+ }
111
+ this.#graph = graph;
112
+ this.#includeTrace = includeTrace;
113
+ this.#nodeInstances = {};
114
+ this.#connections = {};
115
+ this.#nodesById = {};
116
+ this.#registry = registry;
117
+ this.#concurrency = resolveGraphProcessorConcurrency(options?.concurrency);
118
+ this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
119
+ this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
120
+ this.#emitter.on('globalSet', ({ id, value }) => {
121
+ emitDetached(this.#emitter, `globalSet:${id}`, value);
122
+ });
123
+ }
124
+ #preprocessGraph() {
125
+ const preprocessedGraph = preprocessGraphState({
126
+ graph: this.#graph,
127
+ loadedProjects: this.#loadedProjects,
128
+ project: this.#project,
129
+ registry: this.#registry,
130
+ warnOnInvalidGraph: this.warnOnInvalidGraph,
131
+ });
132
+ Object.assign(this.#nodeInstances, preprocessedGraph.nodeInstances);
133
+ Object.assign(this.#nodesById, preprocessedGraph.nodesById);
134
+ Object.assign(this.#connections, preprocessedGraph.connections);
135
+ this.#definitions = preprocessedGraph.definitions;
136
+ this.#scc = preprocessedGraph.stronglyConnectedComponents;
137
+ this.#nodesNotInCycle = preprocessedGraph.nodesNotInCycle;
138
+ }
139
+ #emitTraceEvent(eventData) {
140
+ if (this.#includeTrace) {
141
+ emitDetached(this.#emitter, 'trace', eventData);
142
+ }
143
+ }
144
+ #buildExecutionMetadata() {
145
+ return {
146
+ rootRunId: this.#rootRunId,
147
+ graphRunId: this.#graphRunId,
148
+ graphId: this.#graph.metadata.id,
149
+ parentGraphRunId: this.#parentGraphRunId,
150
+ executor: this.#executor
151
+ ? {
152
+ nodeId: this.#executor.nodeId,
153
+ parentGraphId: this.#executor.parentGraphId,
154
+ processId: this.#executor.processId,
155
+ splitIndex: this.#executor.index,
156
+ }
157
+ : undefined,
158
+ };
159
+ }
160
+ #withExecution(data, execution = this.#buildExecutionMetadata()) {
161
+ return {
162
+ ...data,
163
+ execution,
164
+ };
165
+ }
166
+ on = undefined;
167
+ off = undefined;
168
+ once = undefined;
169
+ onAny = undefined;
170
+ offAny = undefined;
171
+ #onUserEventHandlers = new Map();
172
+ onUserEvent(onEvent, listener) {
173
+ const handler = (event, value) => {
174
+ if (event === `userEvent:${onEvent}`) {
175
+ listener(value);
176
+ }
177
+ };
178
+ this.#onUserEventHandlers.set(listener, handler);
179
+ this.#emitter.onAny(handler);
180
+ }
181
+ offUserEvent(listener) {
182
+ const internalHandler = this.#onUserEventHandlers.get(listener);
183
+ if (internalHandler) {
184
+ this.#emitter.offAny(internalHandler);
185
+ }
186
+ }
187
+ userInput(nodeId, values) {
188
+ const pending = this.#pendingUserInputs[nodeId];
189
+ if (pending) {
190
+ pending.resolve(values);
191
+ delete this.#pendingUserInputs[nodeId];
192
+ }
193
+ for (const processor of this.#subprocessors) {
194
+ processor.userInput(nodeId, values);
195
+ }
196
+ }
197
+ setExternalFunction(name, fn) {
198
+ this.#externalFunctions[name] = fn;
199
+ }
200
+ async abort(successful = false, error) {
201
+ if (!this.#running || this.#aborted) {
202
+ return Promise.resolve();
203
+ }
204
+ this.#abortSuccessfully = successful;
205
+ this.#abortError = error;
206
+ this.#abortController.abort();
207
+ emitDetached(this.#emitter, 'graphAbort', this.#withExecution({ successful, error, graph: this.#graph }));
208
+ if (!this.#isSubProcessor) {
209
+ emitDetached(this.#emitter, 'abort', { successful, error });
210
+ }
211
+ await this.#processingQueue.onIdle();
212
+ }
213
+ pause() {
214
+ if (this.#isPaused === false) {
215
+ this.#isPaused = true;
216
+ emitDetached(this.#emitter, 'pause', void 0);
217
+ }
218
+ }
219
+ resume() {
220
+ if (this.#isPaused) {
221
+ this.#isPaused = false;
222
+ emitDetached(this.#emitter, 'resume', void 0);
223
+ }
224
+ }
225
+ setSlowMode(slowMode) {
226
+ this.slowMode = slowMode;
227
+ }
228
+ async #waitUntilUnpaused() {
229
+ if (!this.#isPaused) {
230
+ return;
231
+ }
232
+ if (this.#abortController.signal.aborted) {
233
+ throw this.#getAbortError();
234
+ }
235
+ await new Promise((resolve, reject) => {
236
+ const abortListener = () => {
237
+ cleanup();
238
+ reject(this.#getAbortError());
239
+ };
240
+ const unsubscribeResume = this.#emitter.on('resume', () => {
241
+ cleanup();
242
+ resolve();
243
+ });
244
+ const cleanup = () => {
245
+ this.#abortController.signal.removeEventListener('abort', abortListener);
246
+ unsubscribeResume();
247
+ };
248
+ this.#abortController.signal.addEventListener('abort', abortListener, { once: true });
249
+ });
250
+ }
251
+ #getAbortError() {
252
+ if (typeof this.#abortError === 'string') {
253
+ return new Error(this.#abortError);
254
+ }
255
+ return this.#abortError ?? new Error('Processing aborted');
256
+ }
257
+ async *events() {
258
+ for await (const [event, data] of this.#emitter.anyEvent()) {
259
+ yield {
260
+ type: event,
261
+ ...(typeof data === 'object' && data != null ? data : {}),
262
+ };
263
+ if (event === 'finish') {
264
+ break;
265
+ }
266
+ }
267
+ }
268
+ preloadNodeData(nodeId, data) {
269
+ this.#nodeResults ??= new Map();
270
+ this.#visitedNodes ??= new Set();
271
+ for (const value of Object.values(data)) {
272
+ if (!value || !('type' in value) || !value.type) {
273
+ throw new Error(`Invalid data value for node ${nodeId}, must be a DataValue`);
274
+ }
275
+ }
276
+ this.#nodeResults.set(nodeId, data);
277
+ this.#visitedNodes.add(nodeId);
278
+ this.#hasPreloadedData = true;
279
+ }
280
+ /** Gets all node IDs that a given node ID depends on being complete before the given node ID can start. */
281
+ getDependencyNodesDeep(nodeId) {
282
+ this.#ensureGraphPreprocessed();
283
+ const dependencyNodes = new Set();
284
+ this.#collectDependencyNodesDeep(nodeId, dependencyNodes);
285
+ return [...dependencyNodes];
286
+ }
287
+ #ensureGraphPreprocessed() {
288
+ if (this.#definitions != null) {
289
+ return;
290
+ }
291
+ this.#loadedProjects ??= {};
292
+ this.#preprocessGraph();
293
+ }
294
+ #collectDependencyNodesDeep(nodeId, dependencyNodes) {
295
+ if (dependencyNodes.has(nodeId)) {
296
+ return;
297
+ }
298
+ const node = this.#nodesById[nodeId];
299
+ if (!node) {
300
+ return;
301
+ }
302
+ dependencyNodes.add(nodeId);
303
+ const connections = this.#connections[nodeId] ?? [];
304
+ for (const connection of connections) {
305
+ if (connection.inputNodeId === nodeId) {
306
+ this.#collectDependencyNodesDeep(connection.outputNodeId, dependencyNodes);
307
+ }
308
+ }
309
+ }
310
+ async replayRecording(recorder) {
311
+ this.#initProcessState();
312
+ this.#graphOutputs = await replayExecutionRecording({
313
+ emitter: this.#emitter,
314
+ erroredNodes: this.#erroredNodes,
315
+ graphInputs: this.#graphInputs,
316
+ graphOutputs: this.#graphOutputs,
317
+ isAborted: () => this.#aborted,
318
+ nodeResults: this.#nodeResults,
319
+ project: this.#project,
320
+ recorder,
321
+ recordingPlaybackChatLatency: this.recordingPlaybackChatLatency,
322
+ setContextValues: (contextValues) => {
323
+ this.#contextValues = contextValues;
324
+ },
325
+ setGraphInputs: (graphInputs) => {
326
+ this.#graphInputs = graphInputs;
327
+ },
328
+ setGraphOutputs: (graphOutputs) => {
329
+ this.#graphOutputs = graphOutputs;
330
+ },
331
+ setRunning: (running) => {
332
+ this.#running = running;
333
+ },
334
+ visitedNodes: this.#visitedNodes,
335
+ waitUntilUnpaused: () => this.#waitUntilUnpaused(),
336
+ });
337
+ return this.#graphOutputs;
338
+ }
339
+ #initProcessState() {
340
+ this.#running = true;
341
+ this.#finishEmitted = false;
342
+ if (!this.#hasPreloadedData) {
343
+ this.#nodeResults = new Map();
344
+ this.#visitedNodes = new Set();
345
+ }
346
+ this.#erroredNodes = new Map();
347
+ this.#currentlyProcessing = new Set();
348
+ this.#remainingNodes = new Set(this.#graph.nodes.map((n) => n.id));
349
+ this.#pendingUserInputs = {};
350
+ this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
351
+ this.#graphOutputs = {};
352
+ this.#executionCache ??= new Map();
353
+ this.#queuedNodes = new Set();
354
+ this.#loopControllersSeen = new Set();
355
+ this.#subprocessors = new Set();
356
+ this.#attachedNodeData = new Map();
357
+ this.#globals ??= new Map();
358
+ this.#ignoreNodes = new Set();
359
+ this.#abortController = this.#newAbortController();
360
+ this.#abortController.signal.addEventListener('abort', () => {
361
+ this.#aborted = true;
362
+ });
363
+ this.#aborted = false;
364
+ this.#abortError = undefined;
365
+ this.#abortSuccessfully = false;
366
+ this.#nodeAbortControllers = new Map();
367
+ this.#loadedProjects = {};
368
+ this.#graphInputNodeValues = {};
369
+ }
370
+ /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
371
+ async processGraph(
372
+ /** Required and optional context available to the nodes and all subgraphs. */
373
+ context,
374
+ /** Inputs to the main graph. You should pass all inputs required by the GraphInputNodes of the graph. */
375
+ inputs = {},
376
+ /** Contextual data available to all graphs and subgraphs. Kind of like react context, avoids drilling down data into subgraphs. Be careful when using it. */
377
+ contextValues = {}) {
378
+ if (this.#running) {
379
+ throw new Error('Cannot process graph while already processing');
380
+ }
381
+ try {
382
+ this.#initializeGraphRun(context, inputs, contextValues);
383
+ await this.#loadProjectReferences();
384
+ this.#preprocessGraph();
385
+ await this.#emitGraphStart();
386
+ await this.#emitPreloadedNodeResults();
387
+ await this.#waitUntilUnpaused();
388
+ await this.#queueStartNodes(getStartNodes(this.#executionState, this.#graph.nodes, this.runToNodeIds));
389
+ await this.#processingQueue.onIdle();
390
+ this.#markUnqueuedNodesIgnored();
391
+ await this.#throwIfGraphErrored();
392
+ return await this.#finalizeGraphRun();
393
+ }
394
+ finally {
395
+ this.#running = false;
396
+ this.#cleanupTokenizerErrorListener();
397
+ await this.#emitFinishIfNeeded();
398
+ }
399
+ }
400
+ async #emitFinishIfNeeded() {
401
+ if (this.#isSubProcessor || this.#finishEmitted) {
402
+ return;
403
+ }
404
+ this.#finishEmitted = true;
405
+ await this.#emitter.emit('finish', undefined);
406
+ }
407
+ #initializeGraphRun(context, inputs, contextValues) {
408
+ this.#initProcessState();
409
+ this.#context = context;
410
+ this.#graphInputs = inputs;
411
+ this.#contextValues = contextValues;
412
+ this.#rootRunId = this.#parent ? this.#parent.#rootRunId : nanoid();
413
+ this.#graphRunId = nanoid();
414
+ this.#parentGraphRunId = this.#parent ? this.#parent.#graphRunId : undefined;
415
+ this.#cleanupTokenizerErrorListener();
416
+ const unsubscribeTokenizerError = this.#context.tokenizer.on('error', (error) => {
417
+ emitDetached(this.#emitter, 'error', { error });
418
+ });
419
+ this.#unsubscribeTokenizerError =
420
+ typeof unsubscribeTokenizerError === 'function' ? unsubscribeTokenizerError : undefined;
421
+ }
422
+ #cleanupTokenizerErrorListener() {
423
+ const unsubscribeTokenizerError = this.#unsubscribeTokenizerError;
424
+ this.#unsubscribeTokenizerError = undefined;
425
+ try {
426
+ unsubscribeTokenizerError?.();
427
+ }
428
+ catch (err) {
429
+ emitDetached(this.#emitter, 'error', { error: getError(err) });
430
+ }
431
+ }
432
+ async #emitGraphStart() {
433
+ if (!this.#isSubProcessor) {
434
+ await this.#emitter.emit('start', this.#withExecution({
435
+ contextValues: this.#contextValues,
436
+ inputs: this.#graphInputs,
437
+ project: this.#project,
438
+ startGraph: this.#graph,
439
+ }));
440
+ }
441
+ await this.#emitter.emit('graphStart', this.#withExecution({ graph: this.#graph, inputs: this.#graphInputs }));
442
+ }
443
+ async #emitPreloadedNodeResults() {
444
+ if (!this.#hasPreloadedData) {
445
+ return;
446
+ }
447
+ for (const node of this.#graph.nodes) {
448
+ if (!this.#nodeResults.has(node.id)) {
449
+ continue;
450
+ }
451
+ this.#emitTraceEvent(`Node ${node.title} has preloaded data`);
452
+ await this.#emitter.emit('nodeStart', this.#withExecution({
453
+ node,
454
+ inputs: {},
455
+ processId: 'preload',
456
+ }));
457
+ await this.#emitter.emit('nodeFinish', this.#withExecution({
458
+ node,
459
+ outputs: this.#nodeResults.get(node.id),
460
+ processId: 'preload',
461
+ }));
462
+ }
463
+ }
464
+ async #queueStartNodes(startNodes) {
465
+ for (const startNode of startNodes) {
466
+ void this.#processingQueue.add(async () => {
467
+ await this.#fetchNodeDataAndProcessNode(startNode);
468
+ });
469
+ }
470
+ }
471
+ #markUnqueuedNodesIgnored() {
472
+ if (!this.runToNodeIds) {
473
+ return;
474
+ }
475
+ for (const node of this.#graph.nodes) {
476
+ if (this.#queuedNodes.has(node.id) === false) {
477
+ this.#ignoreNodes.add(node.id);
478
+ }
479
+ }
480
+ }
481
+ #getUnhandledErroredNodes() {
482
+ return [...this.#erroredNodes.entries()].filter(([nodeId]) => {
483
+ const erroredNodeAttachedData = this.#getAttachedDataTo(nodeId);
484
+ return erroredNodeAttachedData.races == null || erroredNodeAttachedData.races.completed === false;
485
+ });
486
+ }
487
+ #createGraphError(erroredNodes) {
488
+ if (this.#abortError) {
489
+ return this.#getAbortError();
490
+ }
491
+ const message = `Graph ${this.#graph.metadata.name} (${this.#graph.metadata.id}) failed to process due to errors in nodes:\n${erroredNodes
492
+ .map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})`)
493
+ .join('\n')}`;
494
+ if (erroredNodes.length === 1) {
495
+ const [, nodeError] = erroredNodes[0];
496
+ return new Error(message, { cause: nodeError });
497
+ }
498
+ return new AggregateError(erroredNodes.map(([, nodeError]) => nodeError), message);
499
+ }
500
+ async #throwIfGraphErrored() {
501
+ const erroredNodes = this.#getUnhandledErroredNodes();
502
+ if (!erroredNodes.length || this.#abortSuccessfully) {
503
+ return;
504
+ }
505
+ const error = this.#createGraphError(erroredNodes);
506
+ await this.#emitter.emit('graphError', this.#withExecution({ graph: this.#graph, error }));
507
+ if (!this.#isSubProcessor) {
508
+ await this.#emitter.emit('error', { error });
509
+ }
510
+ throw error;
511
+ }
512
+ async #finalizeGraphRun() {
513
+ if (this.#graphOutputs['cost'] == null) {
514
+ this.#graphOutputs['cost'] = {
515
+ type: 'number',
516
+ value: this.#totalCost,
517
+ };
518
+ }
519
+ const outputValues = this.#graphOutputs;
520
+ this.#running = false;
521
+ await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
522
+ if (!this.#isSubProcessor) {
523
+ await this.#emitter.emit('done', { results: outputValues });
524
+ await this.#emitFinishIfNeeded();
525
+ }
526
+ return outputValues;
527
+ }
528
+ async #loadProjectReferences() {
529
+ if ((this.#project.references?.length ?? 0) > 0) {
530
+ if (!this.#context.projectReferenceLoader) {
531
+ throw new Error('Project references are set, but no projectReferenceLoader is set in the context. Since this project uses project references, you must provide a projectReferenceLoader in the context.');
532
+ }
533
+ const seenProjectIds = new Set();
534
+ const loadProject = async (ref) => {
535
+ if (seenProjectIds.has(ref.id)) {
536
+ return;
537
+ }
538
+ seenProjectIds.add(ref.id);
539
+ const project = await this.#context.projectReferenceLoader.loadProject(this.#context.projectPath, ref);
540
+ this.#loadedProjects[project.metadata.id] = project;
541
+ for (const reference of project.references ?? []) {
542
+ await loadProject(reference);
543
+ }
544
+ };
545
+ for (const reference of this.#project.references) {
546
+ await loadProject(reference);
547
+ }
548
+ }
549
+ }
550
+ /** Returns true if any input node has errored. Optionally emits a trace event. */
551
+ #hasErroredInputNode(node, inputNodes, trace = false) {
552
+ return hasErroredInputNode(this.#executionState, node, inputNodes, trace ? (message) => this.#emitTraceEvent(message) : undefined);
553
+ }
554
+ /** Returns true if all required inputs have connections. */
555
+ #areRequiredInputsConnected(node) {
556
+ return areRequiredInputsConnected(this.#executionState, node);
557
+ }
558
+ /** Accumulates cost from a node's output. */
559
+ #accumulateCost(output) {
560
+ if (output['cost']?.type === 'number') {
561
+ this.#totalCost += coerceTypeOptional(output['cost'], 'number') ?? 0;
562
+ }
563
+ }
564
+ /** Checks if a data value represents a control-flow-excluded signal. */
565
+ #isControlFlowExcluded(value) {
566
+ return value != null && getScalarTypeOf(value.type) === 'control-flow-excluded';
567
+ }
568
+ async #fetchNodeDataAndProcessNode(node) {
569
+ if (this.#currentlyProcessing.has(node.id) || this.#queuedNodes.has(node.id)) {
570
+ return;
571
+ }
572
+ if (this.#nodeResults.has(node.id) || this.#erroredNodes.has(node.id)) {
573
+ return;
574
+ }
575
+ const inputNodes = getInputNodesTo(this.#executionState, node);
576
+ if (this.#hasErroredInputNode(node, inputNodes)) {
577
+ return;
578
+ }
579
+ if (!this.#areRequiredInputsConnected(node)) {
580
+ return;
581
+ }
582
+ this.#emitTraceEvent(`Node ${node.title} has required inputs nodes: ${inputNodes.map((n) => n.title).join(', ')}`);
583
+ const attachedData = this.#getAttachedDataTo(node);
584
+ if (node.type === 'raceInputs' || attachedData.races) {
585
+ for (const inputNode of inputNodes) {
586
+ const inputNodeAttachedData = this.#getAttachedDataTo(inputNode);
587
+ const raceIds = new Set([...(attachedData.races?.raceIds ?? [])]);
588
+ if (node.type === 'raceInputs') {
589
+ raceIds.add(`race-${node.id}`);
590
+ }
591
+ inputNodeAttachedData.races = {
592
+ propagate: false,
593
+ raceIds: [...raceIds],
594
+ completed: false,
595
+ };
596
+ }
597
+ }
598
+ this.#queuedNodes.add(node.id);
599
+ void this.#processingQueue.addAll(inputNodes.map((inputNode) => {
600
+ return async () => {
601
+ this.#emitTraceEvent(`Fetching required data for node ${inputNode.title} (${inputNode.id})`);
602
+ await this.#fetchNodeDataAndProcessNode(inputNode);
603
+ };
604
+ }));
605
+ await this.#processNodeIfAllInputsAvailable(node);
606
+ }
607
+ /** If all inputs are present, all conditions met, processes the node. */
608
+ async #processNodeIfAllInputsAvailable(node) {
609
+ const builtInNode = node;
610
+ const inputNodes = getInputNodesTo(this.#executionState, node);
611
+ if (this.#shouldSkipNodeProcessing(node, inputNodes)) {
612
+ return;
613
+ }
614
+ const inputValues = this.#getInputValuesForNode(node);
615
+ if (this.#excludedDueToControlFlow(node, inputValues, nanoid(), LOOP_NOT_BROKEN_SENTINEL)) {
616
+ this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
617
+ return;
618
+ }
619
+ const waitingForInputNode = getWaitingForInputNode(this.#executionState, node, inputNodes, inputValues);
620
+ if (waitingForInputNode) {
621
+ this.#emitTraceEvent(`Node ${node.title} is waiting for input node ${waitingForInputNode}`);
622
+ return;
623
+ }
624
+ const attachedData = this.#getAttachedDataTo(node);
625
+ if (this.#beginNodeProcessing(node, attachedData) === false) {
626
+ return;
627
+ }
628
+ const processId = await this.#processNode(node);
629
+ if (this.slowMode) {
630
+ await new Promise((resolve) => setTimeout(resolve, 250));
631
+ }
632
+ this.#emitTraceEvent(`Finished processing node ${node.title} (${node.id})`);
633
+ this.#visitedNodes.add(node.id);
634
+ this.#currentlyProcessing.delete(node.id);
635
+ this.#remainingNodes.delete(node.id);
636
+ const outputNodes = getOutputNodesFrom(this.#executionState, node);
637
+ this.#handleLoopControllerPostProcess(node, attachedData);
638
+ this.#handleCompletedRace(node);
639
+ if (!this.#assignChildLoopInfo(node, builtInNode, attachedData, processId)) {
640
+ return;
641
+ }
642
+ this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
643
+ this.#queueOutputNodes(node, outputNodes.nodes);
644
+ }
645
+ #shouldSkipNodeProcessing(node, inputNodes) {
646
+ if (this.#ignoreNodes.has(node.id)) {
647
+ this.#emitTraceEvent(`Node ${node.title} is ignored`);
648
+ return true;
649
+ }
650
+ if (this.runToNodeIds) {
651
+ const dependencyNodes = this.getDependencyNodesDeep(node.id);
652
+ if (this.runToNodeIds.some((runTo) => runTo !== node.id && dependencyNodes.includes(runTo))) {
653
+ this.#emitTraceEvent(`Node ${node.title} is excluded due to runToNodeIds`);
654
+ return true;
655
+ }
656
+ }
657
+ if (this.#currentlyProcessing.has(node.id)) {
658
+ this.#emitTraceEvent(`Node ${node.title} is already being processed`);
659
+ return true;
660
+ }
661
+ if (this.#visitedNodes.has(node.id) && node.type !== 'loopController') {
662
+ this.#emitTraceEvent(`Node ${node.title} has already been processed`);
663
+ return true;
664
+ }
665
+ if (this.#erroredNodes.has(node.id)) {
666
+ this.#emitTraceEvent(`Node ${node.title} has already errored`);
667
+ return true;
668
+ }
669
+ if (this.#hasErroredInputNode(node, inputNodes, true)) {
670
+ return true;
671
+ }
672
+ if (!this.#areRequiredInputsConnected(node)) {
673
+ this.#emitTraceEvent(`Node ${node.title} has required inputs nodes: ${inputNodes.map((n) => n.title).join(', ')}`);
674
+ return true;
675
+ }
676
+ return false;
677
+ }
678
+ #beginNodeProcessing(node, attachedData) {
679
+ if (attachedData.races?.completed) {
680
+ this.#emitTraceEvent(`Node ${node.title} is part of a race that was completed`);
681
+ return false;
682
+ }
683
+ this.#currentlyProcessing.add(node.id);
684
+ if (node.type === 'loopController') {
685
+ this.#loopControllersSeen.add(node.id);
686
+ }
687
+ if (attachedData.loopInfo && attachedData.loopInfo.loopControllerId !== node.id) {
688
+ attachedData.loopInfo.nodes.add(node.id);
689
+ }
690
+ return true;
691
+ }
692
+ #handleLoopControllerPostProcess(node, attachedData) {
693
+ if (node.type !== 'loopController') {
694
+ return;
695
+ }
696
+ const loopControllerResults = this.#nodeResults.get(node.id);
697
+ const breakValue = loopControllerResults['break'];
698
+ const didBreak = didLoopControllerBreak(breakValue);
699
+ if (didBreak) {
700
+ return;
701
+ }
702
+ this.#emitTraceEvent(`Loop controller ${node.title} did not break, so we're looping again`);
703
+ for (const loopNodeId of attachedData.loopInfo?.nodes ?? []) {
704
+ const cycleNode = this.#nodesById[loopNodeId];
705
+ this.#emitTraceEvent(`Clearing cycle node ${cycleNode.title} (${cycleNode.id})`);
706
+ this.#visitedNodes.delete(cycleNode.id);
707
+ this.#currentlyProcessing.delete(cycleNode.id);
708
+ this.#remainingNodes.add(cycleNode.id);
709
+ this.#nodeResults.delete(cycleNode.id);
710
+ }
711
+ }
712
+ #handleCompletedRace(node) {
713
+ if (node.type !== 'raceInputs') {
714
+ return;
715
+ }
716
+ const allNodesForRace = [...this.#attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(`race-${node.id}`));
717
+ for (const [nodeId] of allNodesForRace) {
718
+ for (const [key, abortController] of this.#nodeAbortControllers.entries()) {
719
+ if (key.startsWith(nodeId)) {
720
+ this.#emitTraceEvent(`Aborting node ${nodeId} because other race branch won`);
721
+ abortController.abort();
722
+ }
723
+ }
724
+ for (const [, nodeAttachedData] of [...this.#attachedNodeData.entries()]) {
725
+ if (nodeAttachedData.races?.raceIds.includes(`race-${node.id}`)) {
726
+ nodeAttachedData.races.completed = true;
727
+ }
728
+ }
729
+ }
730
+ }
731
+ #assignChildLoopInfo(node, builtInNode, attachedData, processId) {
732
+ if (builtInNode.type !== 'loopController') {
733
+ return true;
734
+ }
735
+ let childLoopInfo = attachedData.loopInfo;
736
+ if (childLoopInfo != null && childLoopInfo.loopControllerId !== builtInNode.id) {
737
+ this.#nodeErrored(node, new Error('Nested loops are not supported'), processId);
738
+ return false;
739
+ }
740
+ childLoopInfo = {
741
+ propagate: (parent, connectionsFromParent) => {
742
+ if (parent.type === 'loopController' && connectionsFromParent.some((c) => c.outputId === 'break')) {
743
+ return false;
744
+ }
745
+ return true;
746
+ },
747
+ loopControllerId: node.id,
748
+ nodes: childLoopInfo?.nodes ?? new Set(),
749
+ iterationCount: (childLoopInfo?.iterationCount ?? 0) + 1,
750
+ };
751
+ attachedData.loopInfo = childLoopInfo;
752
+ return true;
753
+ }
754
+ #propagateAttachedDataToOutputNodes(node, attachedData, outputConnections) {
755
+ for (const { node: outputNode, connections: connectionsToOutputNode } of outputConnections) {
756
+ const outputNodeAttachedData = this.#getAttachedDataTo(outputNode);
757
+ const propagatedAttachedData = Object.entries(attachedData).filter(([, value]) => {
758
+ if (!value) {
759
+ return false;
760
+ }
761
+ if (typeof value.propagate === 'boolean') {
762
+ return value.propagate;
763
+ }
764
+ return value.propagate(node, connectionsToOutputNode);
765
+ });
766
+ for (const [key, value] of propagatedAttachedData) {
767
+ outputNodeAttachedData[key] = value;
768
+ }
769
+ }
770
+ }
771
+ #queueOutputNodes(node, outputNodes) {
772
+ void this.#processingQueue.addAll(outputNodes.map((outputNode) => async () => {
773
+ this.#emitTraceEvent(`Trying to run output node from ${node.title}: ${outputNode.title} (${outputNode.id})`);
774
+ await this.#processNodeIfAllInputsAvailable(outputNode);
775
+ }));
776
+ }
777
+ #getAttachedDataTo(node) {
778
+ const nodeId = typeof node === 'string' ? node : node.id;
779
+ let nodeData = this.#attachedNodeData.get(nodeId);
780
+ if (nodeData == null) {
781
+ nodeData = {};
782
+ this.#attachedNodeData.set(nodeId, nodeData);
783
+ }
784
+ return nodeData;
785
+ }
786
+ async #processNode(node) {
787
+ const processId = nanoid();
788
+ if (this.#abortController.signal.aborted) {
789
+ this.#nodeErrored(node, new Error('Processing aborted'), processId);
790
+ return processId;
791
+ }
792
+ const inputNodes = getInputNodesTo(this.#executionState, node);
793
+ const erroredInputNodes = inputNodes.filter((inputNode) => this.#erroredNodes.has(inputNode.id));
794
+ if (erroredInputNodes.length > 0) {
795
+ const error = new Error(`Cannot process node ${node.title} (${node.id}) because it depends on errored nodes: ${erroredInputNodes
796
+ .map((n) => `${n.title} (${n.id})`)
797
+ .join(', ')}`);
798
+ this.#nodeErrored(node, error, processId);
799
+ return processId;
800
+ }
801
+ if (node.isSplitRun) {
802
+ await this.#processSplitRunNode(node, processId);
803
+ }
804
+ else {
805
+ await this.#processNormalNode(node, processId);
806
+ }
807
+ return processId;
808
+ }
809
+ async #processSplitRunNode(node, processId) {
810
+ return processSplitRunNode(node, processId, {
811
+ getInputValues: (n) => this.#getInputValuesForNode(n),
812
+ isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid),
813
+ processNodeWithInputData: (n, inputs, idx, pid, partial) => this.#processNodeWithInputData(n, inputs, idx, pid, partial),
814
+ splitRunConcurrency: this.#concurrency.splitRunConcurrency,
815
+ accumulateCost: (output) => this.#accumulateCost(output),
816
+ setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
817
+ markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
818
+ nodeErrored: (n, err, pid) => this.#nodeErrored(n, err, pid),
819
+ isAborted: () => this.#aborted,
820
+ emit: (event, data) => {
821
+ emitDetached(this.#emitter, event, this.#withExecution(data));
822
+ },
823
+ });
824
+ }
825
+ async #processNormalNode(node, processId) {
826
+ const inputValues = this.#getInputValuesForNode(node);
827
+ if (this.#excludedDueToControlFlow(node, inputValues, processId)) {
828
+ return;
829
+ }
830
+ // Use awaited emit (not emitDetached) so that listeners can yield to the
831
+ // macrotask queue, giving the browser a chance to repaint during execution.
832
+ await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: inputValues, processId }));
833
+ try {
834
+ const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => {
835
+ emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs: partialOutputs, index, processId }));
836
+ });
837
+ this.#nodeResults.set(node.id, outputValues);
838
+ this.#visitedNodes.add(node.id);
839
+ this.#accumulateCost(outputValues);
840
+ await this.#emitter.emit('nodeFinish', this.#withExecution({ node, outputs: outputValues, processId }));
841
+ }
842
+ catch (error) {
843
+ this.#nodeErrored(node, error, processId);
844
+ }
845
+ }
846
+ #nodeErrored(node, e, processId) {
847
+ const error = getError(e);
848
+ emitDetached(this.#emitter, 'nodeError', this.#withExecution({ node, error, processId }));
849
+ this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);
850
+ this.#erroredNodes.set(node.id, error);
851
+ }
852
+ getRootProcessor() {
853
+ let processor = this;
854
+ while (processor.#parent) {
855
+ processor = processor.#parent;
856
+ }
857
+ return processor;
858
+ }
859
+ /** Raise a user event on the processor, all subprocessors, and their children. */
860
+ raiseEvent(event, data) {
861
+ emitDetached(this.#emitter, `userEvent:${event}`, data);
862
+ for (const subprocessor of this.#subprocessors) {
863
+ subprocessor.raiseEvent(event, data);
864
+ }
865
+ }
866
+ #newAbortController() {
867
+ const controller = new AbortController();
868
+ emitDetached(this.#emitter, 'newAbortController', controller);
869
+ return controller;
870
+ }
871
+ async #processNodeWithInputData(node, inputValues, index, processId, partialOutput) {
872
+ const instance = this.#nodeInstances[node.id];
873
+ const nodeAbortController = this.#newAbortController();
874
+ const abortListener = () => {
875
+ nodeAbortController.abort();
876
+ };
877
+ this.#nodeAbortControllers.set(`${node.id}-${processId}`, nodeAbortController);
878
+ this.#abortController.signal.addEventListener('abort', abortListener);
879
+ const context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput);
880
+ await this.#waitUntilUnpaused();
881
+ let results;
882
+ try {
883
+ results = await instance.process(inputValues, context);
884
+ }
885
+ finally {
886
+ this.#nodeAbortControllers.delete(`${node.id}-${processId}`);
887
+ this.#abortController.signal.removeEventListener('abort', abortListener);
888
+ }
889
+ if (nodeAbortController.signal.aborted) {
890
+ throw new Error('Aborted');
891
+ }
892
+ return results;
893
+ }
894
+ #getTokenizer() {
895
+ return this.#context.tokenizer;
896
+ }
897
+ #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput) {
898
+ const plugin = this.#registry.getPluginFor(node.type);
899
+ return buildNodeProcessContext({
900
+ abortGraph: (error) => {
901
+ void this.abort(error === undefined, error);
902
+ },
903
+ attachedData: this.#getAttachedDataTo(node),
904
+ codeRunner: this.#context.codeRunner ?? new IsomorphicCodeRunner(),
905
+ context: this.#context,
906
+ contextValues: this.#contextValues,
907
+ createSubProcessor: (subGraphId, options = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options),
908
+ execution: this.#buildExecutionMetadata(),
909
+ executionCache: this.#executionCache,
910
+ executor: this.executor ?? 'nodejs',
911
+ externalFunctions: this.#externalFunctions,
912
+ getGlobal: (id) => this.#globals.get(id),
913
+ getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
914
+ graphInputNodeValues: this.#graphInputNodeValues,
915
+ graphInputs: this.#graphInputs,
916
+ graphOutputs: this.#graphOutputs,
917
+ loadedProjects: this.#loadedProjects,
918
+ node,
919
+ nodeAbortController,
920
+ onPartialOutputs: (partialOutputs) => {
921
+ partialOutput?.(node, partialOutputs, index);
922
+ this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
923
+ },
924
+ processId,
925
+ project: this.#project,
926
+ raiseEvent: (event, data) => {
927
+ this.getRootProcessor().raiseEvent(event, data);
928
+ },
929
+ requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId),
930
+ setGlobal: (id, value) => {
931
+ this.#globals.set(id, value);
932
+ emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
933
+ },
934
+ tokenizer: this.#getTokenizer(),
935
+ trace: (message) => {
936
+ this.#emitTraceEvent(message);
937
+ },
938
+ waitEvent: async (event) => {
939
+ return new Promise((resolve, reject) => {
940
+ const abortListener = () => {
941
+ reject(new Error('Process aborted'));
942
+ };
943
+ this.#emitter
944
+ .once(`userEvent:${event}`)
945
+ .then(resolve)
946
+ .catch(reject)
947
+ .finally(() => {
948
+ nodeAbortController.signal.removeEventListener('abort', abortListener);
949
+ });
950
+ nodeAbortController.signal.addEventListener('abort', abortListener, { once: true });
951
+ });
952
+ },
953
+ waitForGlobal: async (id) => {
954
+ if (this.#globals.has(id)) {
955
+ return this.#globals.get(id);
956
+ }
957
+ await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
958
+ return this.#globals.get(id);
959
+ },
960
+ });
961
+ }
962
+ #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
963
+ const { useAsGraphPartialOutput } = node.data ?? {};
964
+ if (!(useAsGraphPartialOutput && this.#executor && this.#parent)) {
965
+ return;
966
+ }
967
+ const executorNode = this.#parent.#nodesById[this.#executor.nodeId];
968
+ if (!executorNode) {
969
+ return;
970
+ }
971
+ const parentExecution = this.#parent.#buildExecutionMetadata();
972
+ emitDetached(this.#emitter, 'partialOutput', {
973
+ index: this.#executor.index,
974
+ node: executorNode,
975
+ outputs: partialOutputs,
976
+ processId: this.#executor.processId,
977
+ execution: parentExecution,
978
+ });
979
+ }
980
+ #createSubProcessor(node, index, processId, subGraphId, { signal, project } = {}) {
981
+ const processor = new GraphProcessor(project ?? this.#project, subGraphId, this.#registry, this.#includeTrace, {
982
+ concurrency: this.#concurrency,
983
+ });
984
+ processor.executor = this.executor;
985
+ processor.#isSubProcessor = true;
986
+ processor.#executionCache = this.#executionCache;
987
+ processor.#externalFunctions = this.#externalFunctions;
988
+ processor.#contextValues = this.#contextValues;
989
+ processor.#parent = this;
990
+ processor.#globals = this.#globals;
991
+ processor.#executor = {
992
+ nodeId: node.id,
993
+ parentGraphId: this.#graph.metadata.id,
994
+ index,
995
+ processId,
996
+ };
997
+ wireSubprocessorEvents(processor, this.#emitter, {
998
+ isPaused: () => this.#isPaused,
999
+ pause: () => {
1000
+ void this.pause();
1001
+ },
1002
+ resume: () => {
1003
+ void this.resume();
1004
+ },
1005
+ });
1006
+ this.#subprocessors.add(processor);
1007
+ wireSubprocessorLifecycle(processor, {
1008
+ signal,
1009
+ parentAbortSignal: this.#abortController.signal,
1010
+ onParentPause: (listener) => {
1011
+ this.on('pause', listener);
1012
+ return () => {
1013
+ this.off('pause', listener);
1014
+ };
1015
+ },
1016
+ onParentResume: (listener) => {
1017
+ this.on('resume', listener);
1018
+ return () => {
1019
+ this.off('resume', listener);
1020
+ };
1021
+ },
1022
+ });
1023
+ return processor;
1024
+ }
1025
+ async #requestUserInput(node, inputStrings, inputValues, renderingType, processId) {
1026
+ return await new Promise((resolve, reject) => {
1027
+ const abortListener = () => {
1028
+ delete this.#pendingUserInputs[node.id];
1029
+ reject(new Error('Processing aborted'));
1030
+ };
1031
+ this.#pendingUserInputs[node.id] = {
1032
+ resolve,
1033
+ reject,
1034
+ };
1035
+ this.#abortController.signal.addEventListener('abort', abortListener, { once: true });
1036
+ emitDetached(this.#emitter, 'userInput', this.#withExecution({
1037
+ node,
1038
+ inputStrings,
1039
+ inputs: inputValues,
1040
+ renderingType,
1041
+ callback: (results) => {
1042
+ this.#abortController.signal.removeEventListener('abort', abortListener);
1043
+ resolve(results);
1044
+ delete this.#pendingUserInputs[node.id];
1045
+ },
1046
+ processId,
1047
+ }));
1048
+ });
1049
+ }
1050
+ #excludedDueToControlFlow(node, inputValues, processId, typeOfExclusion = undefined) {
1051
+ if (node.disabled) {
1052
+ this.#emitTraceEvent(`Excluding node ${node.title} because it's disabled`);
1053
+ this.#visitedNodes.add(node.id);
1054
+ this.#markAsExcluded(node, processId, inputValues, 'disabled');
1055
+ return true;
1056
+ }
1057
+ if (node.isConditional && typeOfExclusion === undefined) {
1058
+ const ifValue = coerceTypeOptional(inputValues[IF_PORT.id], 'boolean');
1059
+ if (ifValue === false) {
1060
+ this.#emitTraceEvent(`Excluding node ${node.title} because if port is false`);
1061
+ this.#visitedNodes.add(node.id);
1062
+ this.#markAsExcluded(node, processId, inputValues, 'if port is false');
1063
+ return true;
1064
+ }
1065
+ }
1066
+ const inputsWithValues = entries(inputValues);
1067
+ const controlFlowExcludedValues = inputsWithValues.filter(([, value]) => this.#isControlFlowExcluded(value) && (!typeOfExclusion || value.value === typeOfExclusion));
1068
+ const inputIsExcludedValue = inputsWithValues.length > 0 && controlFlowExcludedValues.length > 0;
1069
+ const isWaitingForLoop = controlFlowExcludedValues.some((value) => value?.[1]?.value === LOOP_NOT_BROKEN_SENTINEL);
1070
+ const nodesAllowedToConsumeExcludedValue = [
1071
+ 'if',
1072
+ 'ifElse',
1073
+ 'coalesce',
1074
+ 'graphOutput',
1075
+ 'raceInputs',
1076
+ 'loopController',
1077
+ ];
1078
+ const allowedToConsumedExcludedValue = nodesAllowedToConsumeExcludedValue.includes(node.type) && !isWaitingForLoop;
1079
+ if (inputIsExcludedValue && !allowedToConsumedExcludedValue) {
1080
+ if (!isWaitingForLoop) {
1081
+ if (inputIsExcludedValue) {
1082
+ this.#emitTraceEvent(`Excluding node ${node.title} because of control flow. Input is has excluded value: ${controlFlowExcludedValues[0]?.[0]}`);
1083
+ }
1084
+ this.#visitedNodes.add(node.id);
1085
+ this.#markAsExcluded(node, processId, inputValues, 'input is excluded value');
1086
+ }
1087
+ return true;
1088
+ }
1089
+ return false;
1090
+ }
1091
+ #markAsExcluded(node, processId, inputValues, reason) {
1092
+ const outputs = {};
1093
+ for (const output of this.#definitions[node.id].outputs) {
1094
+ outputs[output.id] = { type: 'control-flow-excluded', value: undefined };
1095
+ }
1096
+ // Prevent infinite loop, a control-flow-excluded to loop controller shouldn't set the break port, let the loop controller handle it
1097
+ if (node.type === 'loopController') {
1098
+ outputs['break'] = { type: 'control-flow-excluded', value: LOOP_NOT_BROKEN_SENTINEL };
1099
+ }
1100
+ this.#nodeResults.set(node.id, outputs);
1101
+ emitDetached(this.#emitter, 'nodeExcluded', this.#withExecution({
1102
+ node,
1103
+ processId,
1104
+ inputs: inputValues,
1105
+ outputs,
1106
+ reason,
1107
+ }));
1108
+ }
1109
+ #getInputValuesForNode(node) {
1110
+ const connections = this.#connections[node.id];
1111
+ return this.#definitions[node.id].inputs.reduce((values, input) => {
1112
+ if (!connections) {
1113
+ return values;
1114
+ }
1115
+ const connection = connections.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
1116
+ if (connection) {
1117
+ const outputNode = this.#nodeInstances[connection.outputNodeId].chartNode;
1118
+ const outputNodeOutputs = this.#nodeResults.get(outputNode.id);
1119
+ const outputResult = outputNodeOutputs?.[connection.outputId];
1120
+ values[input.id] = outputResult;
1121
+ }
1122
+ return values;
1123
+ }, {});
1124
+ }
1125
+ get #executionState() {
1126
+ return {
1127
+ connections: this.#connections,
1128
+ definitions: this.#definitions,
1129
+ erroredNodes: this.#erroredNodes,
1130
+ loopControllersSeen: this.#loopControllersSeen,
1131
+ nodesById: this.#nodesById,
1132
+ stronglyConnectedComponents: this.#scc,
1133
+ visitedNodes: this.#visitedNodes,
1134
+ };
1135
+ }
1136
+ }