@valerypopoff/rivet2-core 2.0.7 → 2.0.9

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 (63) hide show
  1. package/dist/cjs/bundle.cjs +1757 -789
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/api/createProcessor.js +9 -2
  4. package/dist/esm/api/streaming.js +1 -0
  5. package/dist/esm/exports.js +1 -0
  6. package/dist/esm/model/DebuggerTransportSentinel.js +78 -0
  7. package/dist/esm/model/GraphAbortReasons.js +69 -0
  8. package/dist/esm/model/GraphBoundaryCache.js +92 -0
  9. package/dist/esm/model/GraphPreprocessor.js +212 -32
  10. package/dist/esm/model/GraphProcessor.js +493 -172
  11. package/dist/esm/model/NodeExclusionPolicy.js +67 -0
  12. package/dist/esm/model/NodeExecutionPlanner.js +66 -22
  13. package/dist/esm/model/NodeImpl.js +6 -4
  14. package/dist/esm/model/ProcessContextBuilder.js +2 -17
  15. package/dist/esm/model/RecordingPlayer.js +27 -7
  16. package/dist/esm/model/SplitRunProcessor.js +48 -9
  17. package/dist/esm/model/SubprocessorBridge.js +30 -23
  18. package/dist/esm/model/chat-v2/chatV2Outputs.js +183 -0
  19. package/dist/esm/model/chat-v2/chatV2Pipeline.js +30 -212
  20. package/dist/esm/model/nodes/CodeNewNode.js +1 -1
  21. package/dist/esm/model/nodes/CodeNode.js +1 -1
  22. package/dist/esm/model/nodes/GetGlobalNode.js +14 -4
  23. package/dist/esm/model/nodes/GraphOutputNode.js +31 -2
  24. package/dist/esm/model/nodes/HttpCallNode.js +20 -18
  25. package/dist/esm/model/nodes/LoopUntilNode.js +18 -45
  26. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +24 -63
  27. package/dist/esm/model/nodes/SetGlobalNode.js +2 -1
  28. package/dist/esm/model/nodes/SubGraphNode.js +22 -63
  29. package/dist/esm/model/nodes/codeNodeErrorDiagnostics.js +2 -3
  30. package/dist/esm/recording/ExecutionRecorder.js +19 -6
  31. package/dist/esm/utils/emitDetached.js +2 -2
  32. package/dist/esm/utils/interpolation.js +41 -1
  33. package/dist/esm/utils/serialization/serialization.js +6 -5
  34. package/dist/esm/utils/serialization/serializationHelpers.js +2 -2
  35. package/dist/esm/utils/serialization/serializationInput.js +48 -0
  36. package/dist/esm/utils/serialization/serializationUtils.js +2 -33
  37. package/dist/esm/utils/serialization/serialization_v2.js +8 -8
  38. package/dist/types/api/createProcessor.d.ts +9 -2
  39. package/dist/types/api/streaming.d.ts +1 -0
  40. package/dist/types/exports.d.ts +1 -0
  41. package/dist/types/model/DebuggerTransportSentinel.d.ts +21 -0
  42. package/dist/types/model/EditorDefinition.d.ts +2 -0
  43. package/dist/types/model/ExecutorProtocol.d.ts +5 -0
  44. package/dist/types/model/GraphAbortReasons.d.ts +23 -0
  45. package/dist/types/model/GraphBoundaryCache.d.ts +27 -0
  46. package/dist/types/model/GraphPreprocessor.d.ts +39 -3
  47. package/dist/types/model/GraphProcessor.d.ts +20 -1
  48. package/dist/types/model/NodeExclusionPolicy.d.ts +21 -0
  49. package/dist/types/model/NodeExecutionPlanner.d.ts +3 -8
  50. package/dist/types/model/NodeImpl.d.ts +10 -5
  51. package/dist/types/model/Nodes.d.ts +2 -2
  52. package/dist/types/model/ProcessContext.d.ts +3 -0
  53. package/dist/types/model/ProcessContextBuilder.d.ts +4 -20
  54. package/dist/types/model/SplitRunProcessor.d.ts +8 -3
  55. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +29 -0
  56. package/dist/types/model/nodes/LoopUntilNode.d.ts +5 -4
  57. package/dist/types/model/nodes/ReferencedGraphAliasNode.d.ts +5 -4
  58. package/dist/types/model/nodes/SubGraphNode.d.ts +6 -5
  59. package/dist/types/model/nodes/codeNodeErrorDiagnostics.d.ts +1 -2
  60. package/dist/types/recording/RecordedEvents.d.ts +4 -0
  61. package/dist/types/utils/emitDetached.d.ts +2 -2
  62. package/dist/types/utils/serialization/serializationInput.d.ts +7 -0
  63. package/package.json +1 -1
@@ -6,7 +6,7 @@ import { deserializeProject } from '../utils/serialization/serialization.js';
6
6
  import { GptTokenizerTokenizer } from '../integrations/GptTokenizerTokenizer.js';
7
7
  import { looseDataValuesToDataValues } from './looseDataValue.js';
8
8
  import { resolveProcessSettings } from './processSettings.js';
9
- export function coreCreateProcessor(project, options) {
9
+ export function coreCreateProcessor(project, options, internalOptions = {}) {
10
10
  const { graph, inputs = {}, context = {} } = options;
11
11
  const graphId = graph
12
12
  ? graph in project.graphs
@@ -17,7 +17,14 @@ export function coreCreateProcessor(project, options) {
17
17
  throw new Error(`Graph not found, and no main graph specified.`);
18
18
  }
19
19
  // TODO: Consolidate options into one object
20
- const processor = new GraphProcessor(project, graphId, options.registry ?? globalRivetNodeRegistry, options.includeTrace, { concurrency: options.concurrency });
20
+ const processor = new GraphProcessor(project, graphId, options.registry ?? globalRivetNodeRegistry, options.includeTrace, {
21
+ cacheLoadedProjects: internalOptions.cacheLoadedProjects,
22
+ captureNodeTimings: options.captureNodeTimings,
23
+ concurrency: options.concurrency,
24
+ executionPlanCacheMode: internalOptions.executionPlanCacheMode,
25
+ runtimeCache: internalOptions.runtimeCache,
26
+ scheduler: internalOptions.scheduler,
27
+ });
21
28
  if (options.onStart) {
22
29
  processor.on('start', options.onStart);
23
30
  }
@@ -56,6 +56,7 @@ export async function* getProcessorEvents(processor, spec) {
56
56
  outputs: event.outputs,
57
57
  nodeId: event.node.id,
58
58
  nodeTitle: event.node.title,
59
+ ...(event.durationMs === undefined ? {} : { durationMs: event.durationMs }),
59
60
  };
60
61
  }
61
62
  }
@@ -12,6 +12,7 @@ export * from './native/BaseDir.js';
12
12
  export * from './native/NativeApi.js';
13
13
  export * from './native/BrowserNativeApi.js';
14
14
  export * from './model/ProcessContext.js';
15
+ export * from './model/DebuggerTransportSentinel.js';
15
16
  export * from './model/ProjectReferenceLoader.js';
16
17
  export * from './model/RivetUIContext.js';
17
18
  export * from './model/chat-v2/index.js';
@@ -0,0 +1,78 @@
1
+ const DEBUGGER_TRANSPORT_SENTINEL_KEY = '__rivetDebuggerTransportSentinel';
2
+ const DEBUGGER_TRANSPORT_SENTINEL_VERSION = 1;
3
+ export function createDebuggerTransportUndefinedSentinel() {
4
+ return {
5
+ [DEBUGGER_TRANSPORT_SENTINEL_KEY]: {
6
+ type: 'undefined',
7
+ version: DEBUGGER_TRANSPORT_SENTINEL_VERSION,
8
+ },
9
+ };
10
+ }
11
+ export function createDebuggerTransportEscapedSentinel(value) {
12
+ return {
13
+ [DEBUGGER_TRANSPORT_SENTINEL_KEY]: {
14
+ type: 'escaped-sentinel',
15
+ version: DEBUGGER_TRANSPORT_SENTINEL_VERSION,
16
+ value,
17
+ },
18
+ };
19
+ }
20
+ export function createDebuggerTransportEscapedSentinelEnvelope(value) {
21
+ return createDebuggerTransportEscapedSentinel(getDebuggerTransportSentinel(value) ?? value);
22
+ }
23
+ export function isDebuggerTransportSentinelEnvelope(value) {
24
+ return getDebuggerTransportSentinel(value) != null;
25
+ }
26
+ export function decodeDebuggerTransportSentinels(value) {
27
+ return decodeDebuggerTransportSentinelsInner(value);
28
+ }
29
+ function decodeDebuggerTransportSentinelsInner(value) {
30
+ const sentinel = getDebuggerTransportSentinel(value);
31
+ if (sentinel) {
32
+ if (sentinel.type === 'undefined') {
33
+ return undefined;
34
+ }
35
+ if (sentinel.type === 'escaped-sentinel') {
36
+ return {
37
+ [DEBUGGER_TRANSPORT_SENTINEL_KEY]: decodeDebuggerTransportSentinelsInner(sentinel.value),
38
+ };
39
+ }
40
+ }
41
+ if (Array.isArray(value)) {
42
+ return value.map((item) => decodeDebuggerTransportSentinelsInner(item));
43
+ }
44
+ if (typeof value !== 'object' || value == null) {
45
+ return value;
46
+ }
47
+ const decoded = {};
48
+ for (const [key, item] of Object.entries(value)) {
49
+ decoded[key] = decodeDebuggerTransportSentinelsInner(item);
50
+ }
51
+ return decoded;
52
+ }
53
+ function getDebuggerTransportSentinel(value) {
54
+ if (typeof value !== 'object' || value == null || Array.isArray(value)) {
55
+ return undefined;
56
+ }
57
+ const valueKeys = Object.keys(value);
58
+ if (valueKeys.length !== 1 || valueKeys[0] !== DEBUGGER_TRANSPORT_SENTINEL_KEY) {
59
+ return undefined;
60
+ }
61
+ const sentinel = value[DEBUGGER_TRANSPORT_SENTINEL_KEY];
62
+ if (typeof sentinel !== 'object' || sentinel == null || Array.isArray(sentinel)) {
63
+ return undefined;
64
+ }
65
+ const typedSentinel = sentinel;
66
+ const sentinelKeys = Object.keys(typedSentinel);
67
+ if (typedSentinel.type === 'undefined') {
68
+ return sentinelKeys.length === 2 && typedSentinel.version === DEBUGGER_TRANSPORT_SENTINEL_VERSION
69
+ ? typedSentinel
70
+ : undefined;
71
+ }
72
+ if (typedSentinel.type === 'escaped-sentinel') {
73
+ return sentinelKeys.length === 3 && typedSentinel.version === DEBUGGER_TRANSPORT_SENTINEL_VERSION
74
+ ? typedSentinel
75
+ : undefined;
76
+ }
77
+ return undefined;
78
+ }
@@ -0,0 +1,69 @@
1
+ export const RACE_LOSER_EXCLUSION_REASON = 'Race branch lost';
2
+ export const SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON = 'Graph aborted successfully';
3
+ const GRAPH_ABORT_ERROR_MARKER = 'rivet:graph-abort-error';
4
+ const GRAPH_ABORT_REASON_MARKER = 'rivet:graph-abort-reason';
5
+ export function createGraphAbortReason(successful, error) {
6
+ return {
7
+ error,
8
+ marker: GRAPH_ABORT_REASON_MARKER,
9
+ successful,
10
+ };
11
+ }
12
+ export function createGraphAbortError(reason, message = 'Processing aborted') {
13
+ const error = new Error(message);
14
+ Object.defineProperties(error, {
15
+ graphAbortReason: {
16
+ configurable: true,
17
+ value: reason,
18
+ },
19
+ marker: {
20
+ configurable: true,
21
+ value: GRAPH_ABORT_ERROR_MARKER,
22
+ },
23
+ });
24
+ return error;
25
+ }
26
+ export function createGraphAbortErrorFromSignal(signal, message = 'Processing aborted') {
27
+ return createGraphAbortError(getGraphAbortReasonFromSignal(signal), message);
28
+ }
29
+ export function getAbortSignalReason(signal) {
30
+ return signal ? signal.reason : undefined;
31
+ }
32
+ export function getGraphAbortReasonFromSignal(signal) {
33
+ return getGraphAbortReason(getAbortSignalReason(signal));
34
+ }
35
+ export function getGraphAbortReasonFromError(error) {
36
+ if (!isGraphAbortError(error)) {
37
+ return undefined;
38
+ }
39
+ return error.graphAbortReason;
40
+ }
41
+ export function isRaceLoserGraphAbortReason(reason) {
42
+ return reason?.successful === true && reason.error === RACE_LOSER_EXCLUSION_REASON;
43
+ }
44
+ export function isSuccessfulNonRaceGraphAbortReason(reason) {
45
+ return reason?.successful === true && !isRaceLoserGraphAbortReason(reason);
46
+ }
47
+ export function isAbortLikeError(error) {
48
+ const normalized = `${error.name}: ${error.message}`.trim();
49
+ return (/^(Error:\s*)?(Aborted|Processing aborted|Process aborted)\.?$/i.test(error.message.trim()) ||
50
+ /^AbortError\b/i.test(normalized) ||
51
+ /\boperation was aborted\.?$/i.test(error.message.trim()));
52
+ }
53
+ function getGraphAbortReason(reason) {
54
+ if (!isGraphAbortReason(reason)) {
55
+ return undefined;
56
+ }
57
+ return reason;
58
+ }
59
+ function isGraphAbortReason(reason) {
60
+ return (typeof reason === 'object' &&
61
+ reason != null &&
62
+ reason.marker === GRAPH_ABORT_REASON_MARKER &&
63
+ typeof reason.successful === 'boolean');
64
+ }
65
+ function isGraphAbortError(error) {
66
+ return (typeof error === 'object' &&
67
+ error != null &&
68
+ error.marker === GRAPH_ABORT_ERROR_MARKER);
69
+ }
@@ -0,0 +1,92 @@
1
+ export function getGraphBoundary(project, graphId, cache) {
2
+ if (!graphId) {
3
+ return undefined;
4
+ }
5
+ const graph = project.graphs[graphId];
6
+ if (!graph) {
7
+ return undefined;
8
+ }
9
+ if (!cache) {
10
+ return deriveGraphBoundary(graph);
11
+ }
12
+ const cached = cache.get(graph);
13
+ if (cached) {
14
+ return cached;
15
+ }
16
+ const boundary = deriveGraphBoundary(graph);
17
+ cache.set(graph, boundary);
18
+ return boundary;
19
+ }
20
+ export function getGraphBoundaryInputDefinitions(boundary) {
21
+ return boundary.inputs.map((input) => ({
22
+ id: input.portId,
23
+ title: input.id,
24
+ dataType: input.dataType,
25
+ }));
26
+ }
27
+ export function getGraphBoundaryOutputDefinitions(boundary) {
28
+ return boundary.outputs.map((output) => ({
29
+ id: output.portId,
30
+ title: output.id,
31
+ dataType: output.dataType,
32
+ }));
33
+ }
34
+ export function buildGraphBoundaryInputData(boundary, inputs, defaults) {
35
+ const inputData = {};
36
+ for (const input of boundary.inputs) {
37
+ const inputValue = inputs[input.portId];
38
+ if (inputValue != null) {
39
+ inputData[input.portId] = inputValue;
40
+ continue;
41
+ }
42
+ const defaultValue = defaults?.[input.id];
43
+ if (defaultValue != null) {
44
+ inputData[input.portId] = defaultValue;
45
+ }
46
+ }
47
+ return inputData;
48
+ }
49
+ export function buildExcludedGraphBoundaryOutputs(boundary) {
50
+ const outputs = {};
51
+ for (const output of boundary.outputs) {
52
+ outputs[output.portId] = {
53
+ type: 'control-flow-excluded',
54
+ value: undefined,
55
+ };
56
+ }
57
+ return outputs;
58
+ }
59
+ function deriveGraphBoundary(graph) {
60
+ const inputsById = new Map();
61
+ const outputsById = new Map();
62
+ for (const node of graph.nodes) {
63
+ if (node.type === 'graphInput' && !inputsById.has(getBoundaryNodeId(node))) {
64
+ const inputNode = node;
65
+ inputsById.set(inputNode.data.id, {
66
+ dataType: inputNode.data.dataType,
67
+ editor: inputNode.data.editor,
68
+ id: inputNode.data.id,
69
+ portId: inputNode.data.id,
70
+ });
71
+ }
72
+ else if (node.type === 'graphOutput' && !outputsById.has(getBoundaryNodeId(node))) {
73
+ const outputNode = node;
74
+ outputsById.set(outputNode.data.id, {
75
+ dataType: outputNode.data.dataType,
76
+ id: outputNode.data.id,
77
+ portId: outputNode.data.id,
78
+ });
79
+ }
80
+ }
81
+ return {
82
+ inputs: Array.from(inputsById.keys())
83
+ .sort()
84
+ .map((id) => inputsById.get(id)),
85
+ outputs: Array.from(outputsById.keys())
86
+ .sort()
87
+ .map((id) => outputsById.get(id)),
88
+ };
89
+ }
90
+ function getBoundaryNodeId(node) {
91
+ return node.data.id;
92
+ }
@@ -1,7 +1,8 @@
1
1
  import { values } from '../utils/typeSafety.js';
2
2
  import { findStronglyConnectedComponents } from './CycleDetector.js';
3
3
  export function preprocessGraphState(options) {
4
- const { graph, loadedProjects, project, registry, warnOnInvalidGraph } = options;
4
+ const { buildExecutionPlan, definitionContext, graph, loadedProjects, project, registry, warnOnInvalidGraph } = options;
5
+ const effectiveDefinitionContext = definitionContext && graph.nodes.some(usesGraphBoundaryDefinitionContext) ? definitionContext : undefined;
5
6
  const nodeInstances = {};
6
7
  const nodesById = {};
7
8
  const connections = {};
@@ -32,6 +33,7 @@ export function preprocessGraphState(options) {
32
33
  nodeInstances,
33
34
  nodesById,
34
35
  project,
36
+ definitionContext: effectiveDefinitionContext,
35
37
  warnOnInvalidGraph,
36
38
  });
37
39
  const stronglyConnectedComponents = findStronglyConnectedComponents(graph.nodes, (node) => {
@@ -41,57 +43,235 @@ export function preprocessGraphState(options) {
41
43
  .map((connection) => nodesById[connection.inputNodeId])
42
44
  .filter(Boolean);
43
45
  });
44
- return {
46
+ const nodesNotInCycle = stronglyConnectedComponents.filter((component) => component.length === 1).flat();
47
+ const result = {
45
48
  connections,
46
49
  definitions,
47
50
  nodeInstances,
48
51
  nodesById,
49
- nodesNotInCycle: stronglyConnectedComponents.filter((component) => component.length === 1).flat(),
52
+ nodesNotInCycle,
50
53
  stronglyConnectedComponents,
51
54
  };
55
+ if (!buildExecutionPlan) {
56
+ return result;
57
+ }
58
+ return {
59
+ ...result,
60
+ ...buildGraphExecutionPlan({
61
+ connections,
62
+ definitions,
63
+ graphNodes: graph.nodes,
64
+ nodesById,
65
+ stronglyConnectedComponents,
66
+ }),
67
+ };
68
+ }
69
+ export function isGraphExecutionPlan(preprocessedGraph) {
70
+ return 'inputConnectionByNodeAndPort' in preprocessedGraph;
71
+ }
72
+ export function toReusableGraphExecutionPlan(preprocessedGraph) {
73
+ return {
74
+ connections: preprocessedGraph.connections,
75
+ cycleIndexByNode: preprocessedGraph.cycleIndexByNode,
76
+ definitions: preprocessedGraph.definitions,
77
+ graphNodes: preprocessedGraph.graphNodes,
78
+ nodeIds: preprocessedGraph.nodeIds,
79
+ inputConnectionByNodeAndPort: preprocessedGraph.inputConnectionByNodeAndPort,
80
+ inputConnectionsByNode: preprocessedGraph.inputConnectionsByNode,
81
+ inputNodesByNode: preprocessedGraph.inputNodesByNode,
82
+ missingRequiredInputsByNode: preprocessedGraph.missingRequiredInputsByNode,
83
+ nodesById: preprocessedGraph.nodesById,
84
+ nodesNotInCycle: preprocessedGraph.nodesNotInCycle,
85
+ outputConnectionsByNodeAndPort: preprocessedGraph.outputConnectionsByNodeAndPort,
86
+ outputNodeResultsByNode: preprocessedGraph.outputNodeResultsByNode,
87
+ startNodes: preprocessedGraph.startNodes,
88
+ stronglyConnectedComponents: preprocessedGraph.stronglyConnectedComponents,
89
+ };
52
90
  }
53
91
  function loadInputOutputDefinitions(options) {
54
- const { connections, loadedProjects, nodeInstances, nodesById, project, warnOnInvalidGraph } = options;
92
+ const { connections, definitionContext, loadedProjects, nodeInstances, nodesById, project, warnOnInvalidGraph } = options;
55
93
  const definitions = {};
94
+ if (!definitionContext) {
95
+ for (const node of values(nodesById)) {
96
+ const connectionsForNode = connections[node.id] ?? [];
97
+ const inputDefinitions = nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(connectionsForNode, nodesById, project, loadedProjects);
98
+ const outputDefinitions = nodeInstances[node.id].getOutputDefinitions(connectionsForNode, nodesById, project, loadedProjects);
99
+ definitions[node.id] = {
100
+ inputs: inputDefinitions,
101
+ outputs: outputDefinitions,
102
+ };
103
+ const invalidConnections = connectionsForNode.filter((connection) => {
104
+ if (connection.inputNodeId === node.id) {
105
+ const inputDefinition = inputDefinitions.find((definition) => definition.id === connection.inputId);
106
+ if (!inputDefinition) {
107
+ if (warnOnInvalidGraph) {
108
+ const sourceNode = nodesById[connection.outputNodeId];
109
+ console.warn(`[Warn] Invalid connection going from "${sourceNode?.title}".${connection.outputId} to "${node.title}".${connection.inputId}`);
110
+ }
111
+ return true;
112
+ }
113
+ }
114
+ else {
115
+ const outputDefinition = outputDefinitions.find((definition) => definition.id === connection.outputId);
116
+ if (!outputDefinition) {
117
+ if (warnOnInvalidGraph) {
118
+ const targetNode = nodesById[connection.inputNodeId];
119
+ console.warn(`[Warn] Invalid connection going from "${node.title}".${connection.outputId} to "${targetNode?.title}".${connection.inputId}`);
120
+ }
121
+ return true;
122
+ }
123
+ }
124
+ return false;
125
+ });
126
+ if (invalidConnections.length > 0) {
127
+ for (const invalidConnection of invalidConnections) {
128
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.inputNodeId);
129
+ if (invalidConnection.outputNodeId !== invalidConnection.inputNodeId) {
130
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.outputNodeId);
131
+ }
132
+ }
133
+ }
134
+ }
135
+ return definitions;
136
+ }
56
137
  for (const node of values(nodesById)) {
57
138
  const connectionsForNode = connections[node.id] ?? [];
58
- const inputDefinitions = nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(connectionsForNode, nodesById, project, loadedProjects);
59
- const outputDefinitions = nodeInstances[node.id].getOutputDefinitions(connectionsForNode, nodesById, project, loadedProjects);
139
+ const nodeDefinitionContext = usesGraphBoundaryDefinitionContext(node) ? definitionContext : undefined;
140
+ const inputDefinitions = nodeDefinitionContext
141
+ ? nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(connectionsForNode, nodesById, project, loadedProjects, nodeDefinitionContext)
142
+ : nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(connectionsForNode, nodesById, project, loadedProjects);
143
+ const outputDefinitions = nodeDefinitionContext
144
+ ? nodeInstances[node.id].getOutputDefinitions(connectionsForNode, nodesById, project, loadedProjects, nodeDefinitionContext)
145
+ : nodeInstances[node.id].getOutputDefinitions(connectionsForNode, nodesById, project, loadedProjects);
60
146
  definitions[node.id] = {
61
147
  inputs: inputDefinitions,
62
148
  outputs: outputDefinitions,
63
149
  };
64
- const invalidConnections = connectionsForNode.filter((connection) => {
65
- if (connection.inputNodeId === node.id) {
66
- const inputDefinition = inputDefinitions.find((definition) => definition.id === connection.inputId);
67
- if (!inputDefinition) {
68
- if (warnOnInvalidGraph) {
69
- const sourceNode = nodesById[connection.outputNodeId];
70
- console.warn(`[Warn] Invalid connection going from "${sourceNode?.title}".${connection.outputId} to "${node.title}".${connection.inputId}`);
71
- }
72
- return true;
150
+ removeInvalidDefinitionConnections(connections, connectionsForNode, inputDefinitions, node, nodesById, outputDefinitions, warnOnInvalidGraph);
151
+ }
152
+ return definitions;
153
+ }
154
+ function removeInvalidDefinitionConnections(connections, connectionsForNode, inputDefinitions, node, nodesById, outputDefinitions, warnOnInvalidGraph) {
155
+ const invalidConnections = connectionsForNode.filter((connection) => {
156
+ if (connection.inputNodeId === node.id) {
157
+ const inputDefinition = inputDefinitions.find((definition) => definition.id === connection.inputId);
158
+ if (!inputDefinition) {
159
+ if (warnOnInvalidGraph) {
160
+ const sourceNode = nodesById[connection.outputNodeId];
161
+ console.warn(`[Warn] Invalid connection going from "${sourceNode?.title}".${connection.outputId} to "${node.title}".${connection.inputId}`);
73
162
  }
163
+ return true;
74
164
  }
75
- else {
76
- const outputDefinition = outputDefinitions.find((definition) => definition.id === connection.outputId);
77
- if (!outputDefinition) {
78
- if (warnOnInvalidGraph) {
79
- const targetNode = nodesById[connection.inputNodeId];
80
- console.warn(`[Warn] Invalid connection going from "${node.title}".${connection.outputId} to "${targetNode?.title}".${connection.inputId}`);
81
- }
82
- return true;
165
+ }
166
+ else {
167
+ const outputDefinition = outputDefinitions.find((definition) => definition.id === connection.outputId);
168
+ if (!outputDefinition) {
169
+ if (warnOnInvalidGraph) {
170
+ const targetNode = nodesById[connection.inputNodeId];
171
+ console.warn(`[Warn] Invalid connection going from "${node.title}".${connection.outputId} to "${targetNode?.title}".${connection.inputId}`);
83
172
  }
173
+ return true;
84
174
  }
85
- return false;
86
- });
87
- for (const nodeConnections of values(connections)) {
88
- for (const invalidConnection of invalidConnections) {
89
- const invalidConnectionIndex = nodeConnections.indexOf(invalidConnection);
90
- if (invalidConnectionIndex !== -1) {
91
- nodeConnections.splice(invalidConnectionIndex, 1);
92
- }
175
+ }
176
+ return false;
177
+ });
178
+ if (invalidConnections.length > 0) {
179
+ for (const invalidConnection of invalidConnections) {
180
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.inputNodeId);
181
+ if (invalidConnection.outputNodeId !== invalidConnection.inputNodeId) {
182
+ removeConnectionFromNode(connections, invalidConnection, invalidConnection.outputNodeId);
93
183
  }
94
184
  }
95
185
  }
96
- return definitions;
186
+ }
187
+ function usesGraphBoundaryDefinitionContext(node) {
188
+ return node.type === 'subGraph' || node.type === 'referencedGraphAlias' || node.type === 'loopUntil';
189
+ }
190
+ function removeConnectionFromNode(connections, connection, nodeId) {
191
+ const nodeConnections = connections[nodeId];
192
+ if (!nodeConnections) {
193
+ return;
194
+ }
195
+ const invalidConnectionIndex = nodeConnections.indexOf(connection);
196
+ if (invalidConnectionIndex !== -1) {
197
+ nodeConnections.splice(invalidConnectionIndex, 1);
198
+ }
199
+ }
200
+ function buildGraphExecutionPlan(options) {
201
+ const { connections, definitions, graphNodes, nodesById, stronglyConnectedComponents } = options;
202
+ const cycleIndexByNode = {};
203
+ const inputConnectionByNodeAndPort = {};
204
+ const inputConnectionsByNode = {};
205
+ const inputNodesByNode = {};
206
+ const missingRequiredInputsByNode = {};
207
+ const outputConnectionsByNodeAndPort = {};
208
+ const outputNodeResultsByNode = {};
209
+ stronglyConnectedComponents.forEach((component, index) => {
210
+ for (const node of component) {
211
+ cycleIndexByNode[node.id] = index;
212
+ }
213
+ });
214
+ for (const node of graphNodes) {
215
+ const nodeConnections = connections[node.id] ?? [];
216
+ const inputDefinitions = definitions[node.id]?.inputs ?? [];
217
+ const outputDefinitions = definitions[node.id]?.outputs ?? [];
218
+ const validInputIds = new Set(inputDefinitions.map((definition) => definition.id));
219
+ const validOutputIds = new Set(outputDefinitions.map((definition) => definition.id));
220
+ const inputConnections = nodeConnections.filter((connection) => connection.inputNodeId === node.id && validInputIds.has(connection.inputId));
221
+ const outputConnections = nodeConnections.filter((connection) => connection.outputNodeId === node.id && validOutputIds.has(connection.outputId));
222
+ inputConnectionsByNode[node.id] = inputConnections;
223
+ outputConnectionsByNodeAndPort[node.id] = {};
224
+ inputConnectionByNodeAndPort[node.id] = {};
225
+ for (const connection of inputConnections) {
226
+ inputConnectionByNodeAndPort[node.id][connection.inputId] ??= connection;
227
+ }
228
+ for (const connection of outputConnections) {
229
+ outputConnectionsByNodeAndPort[node.id][connection.outputId] ??= [];
230
+ outputConnectionsByNodeAndPort[node.id][connection.outputId].push(connection);
231
+ }
232
+ inputNodesByNode[node.id] = inputConnections
233
+ .map((connection) => nodesById[connection.outputNodeId])
234
+ .filter((inputNode) => inputNode != null);
235
+ missingRequiredInputsByNode[node.id] = inputDefinitions.filter((input) => input.required && inputConnectionByNodeAndPort[node.id]?.[input.id] == null);
236
+ const outputNodes = [];
237
+ const seenOutputNodeIds = new Set();
238
+ const outputConnectionsByNode = new Map();
239
+ for (const connection of outputConnections) {
240
+ const outputNode = nodesById[connection.inputNodeId];
241
+ if (!outputNode) {
242
+ continue;
243
+ }
244
+ if (!seenOutputNodeIds.has(outputNode.id)) {
245
+ outputNodes.push(outputNode);
246
+ seenOutputNodeIds.add(outputNode.id);
247
+ }
248
+ const nodeConnections = outputConnectionsByNode.get(outputNode.id);
249
+ if (nodeConnections) {
250
+ nodeConnections.push(connection);
251
+ }
252
+ else {
253
+ outputConnectionsByNode.set(outputNode.id, [connection]);
254
+ }
255
+ }
256
+ outputNodeResultsByNode[node.id] = {
257
+ connections: outputConnections,
258
+ connectionsToNodes: outputNodes.map((outputNode) => ({
259
+ connections: outputConnectionsByNode.get(outputNode.id) ?? [],
260
+ node: outputNode,
261
+ })),
262
+ nodes: outputNodes,
263
+ };
264
+ }
265
+ return {
266
+ cycleIndexByNode,
267
+ graphNodes,
268
+ nodeIds: graphNodes.map((node) => node.id),
269
+ inputConnectionByNodeAndPort,
270
+ inputConnectionsByNode,
271
+ inputNodesByNode,
272
+ missingRequiredInputsByNode,
273
+ outputConnectionsByNodeAndPort,
274
+ outputNodeResultsByNode,
275
+ startNodes: graphNodes.filter((node) => outputNodeResultsByNode[node.id]?.nodes.length === 0),
276
+ };
97
277
  }