@valerypopoff/rivet2-core 2.0.11 → 2.1.1

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 (75) hide show
  1. package/dist/cjs/bundle.cjs +1657 -158
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/esm/exports.js +4 -0
  4. package/dist/esm/model/GraphBoundaryCache.js +36 -4
  5. package/dist/esm/model/GraphBoundaryEffects.js +32 -0
  6. package/dist/esm/model/GraphPreprocessor.js +6 -4
  7. package/dist/esm/model/GraphProcessor.js +129 -17
  8. package/dist/esm/model/NodeGraph.js +1 -1
  9. package/dist/esm/model/NodePrefabResolver.js +57 -0
  10. package/dist/esm/model/Nodes.js +4 -1
  11. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  12. package/dist/esm/model/UiGraph.js +113 -0
  13. package/dist/esm/model/UiGraphRendererStyles.js +241 -0
  14. package/dist/esm/model/chat/openAIChatRuntime.js +0 -1
  15. package/dist/esm/model/chat-v2/aiSdkBridge.js +100 -2
  16. package/dist/esm/model/chat-v2/chatV2FeatureCompatibility.js +1 -1
  17. package/dist/esm/model/chat-v2/chatV2Outputs.js +11 -2
  18. package/dist/esm/model/chat-v2/chatV2Pipeline.js +38 -31
  19. package/dist/esm/model/chat-v2/chatV2ResponseFormat.js +4 -1
  20. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -2
  21. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +5 -5
  22. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +8 -2
  23. package/dist/esm/model/chat-v2/providerOptions.js +65 -2
  24. package/dist/esm/model/nodes/CoalesceNode.js +1 -1
  25. package/dist/esm/model/nodes/CompareNode.js +15 -14
  26. package/dist/esm/model/nodes/GraphOutputNode.js +1 -0
  27. package/dist/esm/model/nodes/LLMChatV2Node.js +66 -17
  28. package/dist/esm/model/nodes/NodePrefabInstanceNode.js +39 -0
  29. package/dist/esm/model/nodes/PromptNode.js +2 -1
  30. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +49 -7
  31. package/dist/esm/model/nodes/SubGraphNode.js +42 -5
  32. package/dist/esm/utils/index.js +2 -0
  33. package/dist/esm/utils/jsonValueToDataValue.js +48 -0
  34. package/dist/esm/utils/projectComparison/connections.js +57 -0
  35. package/dist/esm/utils/projectComparison/graphs.js +60 -0
  36. package/dist/esm/utils/projectComparison/nodes.js +53 -0
  37. package/dist/esm/utils/projectComparison/summaries.js +60 -0
  38. package/dist/esm/utils/projectComparison/values.js +40 -0
  39. package/dist/esm/utils/projectComparison.js +73 -0
  40. package/dist/esm/utils/serialization/serializationHelpers.js +24 -3
  41. package/dist/esm/utils/serialization/serialization_v4.js +30 -0
  42. package/dist/types/exports.d.ts +5 -0
  43. package/dist/types/model/EditorDefinition.d.ts +1 -0
  44. package/dist/types/model/ExecutorProtocol.d.ts +13 -3
  45. package/dist/types/model/GraphBoundaryCache.d.ts +9 -3
  46. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -0
  47. package/dist/types/model/GraphProcessor.d.ts +15 -0
  48. package/dist/types/model/NodeBase.d.ts +5 -0
  49. package/dist/types/model/NodeBodySpec.d.ts +1 -0
  50. package/dist/types/model/NodePrefabResolver.d.ts +13 -0
  51. package/dist/types/model/Nodes.d.ts +5 -4
  52. package/dist/types/model/ProcessContext.d.ts +5 -1
  53. package/dist/types/model/ProcessContextBuilder.d.ts +4 -2
  54. package/dist/types/model/Project.d.ts +9 -0
  55. package/dist/types/model/UiGraph.d.ts +84 -0
  56. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -0
  57. package/dist/types/model/chat-v2/aiSdkBridge.d.ts +1 -0
  58. package/dist/types/model/chat-v2/chatV2FeatureCompatibility.d.ts +1 -1
  59. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +4 -2
  60. package/dist/types/model/chat-v2/chatV2ResponseFormat.d.ts +1 -1
  61. package/dist/types/model/chat-v2/chatV2Types.d.ts +24 -1
  62. package/dist/types/model/chat-v2/providerOptions.d.ts +1 -0
  63. package/dist/types/model/nodes/CompareNode.d.ts +4 -0
  64. package/dist/types/model/nodes/LLMChatV2Node.d.ts +2 -1
  65. package/dist/types/model/nodes/NodePrefabInstanceNode.d.ts +13 -0
  66. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  67. package/dist/types/utils/index.d.ts +2 -0
  68. package/dist/types/utils/jsonValueToDataValue.d.ts +2 -0
  69. package/dist/types/utils/projectComparison/connections.d.ts +5 -0
  70. package/dist/types/utils/projectComparison/graphs.d.ts +3 -0
  71. package/dist/types/utils/projectComparison/nodes.d.ts +5 -0
  72. package/dist/types/utils/projectComparison/summaries.d.ts +4 -0
  73. package/dist/types/utils/projectComparison/values.d.ts +5 -0
  74. package/dist/types/utils/projectComparison.d.ts +77 -0
  75. package/package.json +1 -1
@@ -4,6 +4,10 @@ export * from './model/GraphProcessor.js';
4
4
  export * from './model/DataValue.js';
5
5
  export * from './model/NodeBase.js';
6
6
  export * from './model/NodeGraph.js';
7
+ export * from './model/NodePrefabResolver.js';
8
+ export { getGraphBoundary } from './model/GraphBoundaryCache.js';
9
+ export * from './model/UiGraph.js';
10
+ export * from './model/UiGraphRendererStyles.js';
7
11
  export * from './model/NodeImpl.js';
8
12
  export * from './model/NodeDefinition.js';
9
13
  export * from './model/Nodes.js';
@@ -1,3 +1,4 @@
1
+ export const GRAPH_BOUNDARY_OUTPUT_DEMAND_OPTIMIZATION_ENABLED = false;
1
2
  export function getGraphBoundary(project, graphId, cache) {
2
3
  if (!graphId) {
3
4
  return undefined;
@@ -17,15 +18,40 @@ export function getGraphBoundary(project, graphId, cache) {
17
18
  cache.set(graph, boundary);
18
19
  return boundary;
19
20
  }
20
- export function getGraphBoundaryInputDefinitions(boundary) {
21
- return boundary.inputs.map((input) => ({
21
+ export function applyGraphBoundaryPortOrder(boundaryItems, portOrder) {
22
+ if (!portOrder?.length) {
23
+ return [...boundaryItems];
24
+ }
25
+ const itemsById = new Map(boundaryItems.map((item) => [item.id, item]));
26
+ const usedIds = new Set();
27
+ const orderedItems = [];
28
+ for (const id of portOrder) {
29
+ if (usedIds.has(id)) {
30
+ continue;
31
+ }
32
+ const item = itemsById.get(id);
33
+ if (!item) {
34
+ continue;
35
+ }
36
+ orderedItems.push(item);
37
+ usedIds.add(id);
38
+ }
39
+ for (const item of boundaryItems) {
40
+ if (!usedIds.has(item.id)) {
41
+ orderedItems.push(item);
42
+ }
43
+ }
44
+ return orderedItems;
45
+ }
46
+ export function getGraphBoundaryInputDefinitions(boundary, inputPortOrder) {
47
+ return applyGraphBoundaryPortOrder(boundary.inputs, inputPortOrder).map((input) => ({
22
48
  id: input.portId,
23
49
  title: input.id,
24
50
  dataType: input.dataType,
25
51
  }));
26
52
  }
27
- export function getGraphBoundaryOutputDefinitions(boundary) {
28
- return boundary.outputs.map((output) => ({
53
+ export function getGraphBoundaryOutputDefinitions(boundary, outputPortOrder) {
54
+ return applyGraphBoundaryPortOrder(boundary.outputs, outputPortOrder).map((output) => ({
29
55
  id: output.portId,
30
56
  title: output.id,
31
57
  dataType: output.dataType,
@@ -56,6 +82,11 @@ export function buildExcludedGraphBoundaryOutputs(boundary) {
56
82
  }
57
83
  return outputs;
58
84
  }
85
+ export function getRequestedGraphOutputNodeIds(boundary, requestedOutputPortIds) {
86
+ return boundary.outputs
87
+ .filter((output) => requestedOutputPortIds.has(output.portId))
88
+ .map((output) => output.nodeId);
89
+ }
59
90
  function deriveGraphBoundary(graph) {
60
91
  const inputsById = new Map();
61
92
  const outputsById = new Map();
@@ -74,6 +105,7 @@ function deriveGraphBoundary(graph) {
74
105
  outputsById.set(outputNode.data.id, {
75
106
  dataType: outputNode.data.dataType,
76
107
  id: outputNode.data.id,
108
+ nodeId: outputNode.id,
77
109
  portId: outputNode.data.id,
78
110
  });
79
111
  }
@@ -0,0 +1,32 @@
1
+ export function ensureGraphCostOutput(graphOutputs, totalCost) {
2
+ const costPort = 'cost';
3
+ if (graphOutputs[costPort] == null) {
4
+ graphOutputs[costPort] = {
5
+ type: 'number',
6
+ value: totalCost,
7
+ };
8
+ }
9
+ }
10
+ export function applyFrozenGraphBoundaryEffects(graphOutputs, node, outputValues) {
11
+ if (node.type === 'graphOutput') {
12
+ const outputId = node.data?.id;
13
+ const valueOutput = outputValues['valueOutput'];
14
+ if (outputId && valueOutput) {
15
+ graphOutputs[outputId] = valueOutput;
16
+ }
17
+ return undefined;
18
+ }
19
+ if (node.type !== 'setGlobal') {
20
+ return undefined;
21
+ }
22
+ const savedValue = outputValues['saved-value'];
23
+ const variableId = outputValues['variable_id_out'];
24
+ const variableIdValue = variableId?.type === 'string' ? variableId.value : undefined;
25
+ if (!variableIdValue || !savedValue) {
26
+ return undefined;
27
+ }
28
+ return {
29
+ variableId: variableIdValue,
30
+ value: savedValue,
31
+ };
32
+ }
@@ -1,12 +1,14 @@
1
1
  import { values } from '../utils/typeSafety.js';
2
2
  import { findStronglyConnectedComponents } from './CycleDetector.js';
3
+ import { resolveNodePrefabInstances } from './NodePrefabResolver.js';
3
4
  export function preprocessGraphState(options) {
4
5
  const { buildExecutionPlan, definitionContext, graph, loadedProjects, project, registry, warnOnInvalidGraph } = options;
5
- const effectiveDefinitionContext = definitionContext && graph.nodes.some(usesGraphBoundaryDefinitionContext) ? definitionContext : undefined;
6
+ const graphNodes = resolveNodePrefabInstances(project, graph.nodes);
7
+ const effectiveDefinitionContext = definitionContext && graphNodes.some(usesGraphBoundaryDefinitionContext) ? definitionContext : undefined;
6
8
  const nodeInstances = {};
7
9
  const nodesById = {};
8
10
  const connections = {};
9
- for (const node of graph.nodes) {
11
+ for (const node of graphNodes) {
10
12
  nodeInstances[node.id] = registry.createDynamicImpl(node);
11
13
  nodesById[node.id] = node;
12
14
  }
@@ -36,7 +38,7 @@ export function preprocessGraphState(options) {
36
38
  definitionContext: effectiveDefinitionContext,
37
39
  warnOnInvalidGraph,
38
40
  });
39
- const stronglyConnectedComponents = findStronglyConnectedComponents(graph.nodes, (node) => {
41
+ const stronglyConnectedComponents = findStronglyConnectedComponents(graphNodes, (node) => {
40
42
  const nodeConnections = connections[node.id] ?? [];
41
43
  return nodeConnections
42
44
  .filter((connection) => connection.outputNodeId === node.id)
@@ -60,7 +62,7 @@ export function preprocessGraphState(options) {
60
62
  ...buildGraphExecutionPlan({
61
63
  connections,
62
64
  definitions,
63
- graphNodes: graph.nodes,
65
+ graphNodes,
64
66
  nodesById,
65
67
  stronglyConnectedComponents,
66
68
  }),
@@ -9,6 +9,7 @@ import { coerceTypeOptional } from '../utils/coerceType.js';
9
9
  import { getPluginConfig } from '../utils/index.js';
10
10
  import { isGraphExecutionPlan, preprocessGraphState, toReusableGraphExecutionPlan, } from './GraphPreprocessor.js';
11
11
  import { getGraphBoundary, } from './GraphBoundaryCache.js';
12
+ import { applyFrozenGraphBoundaryEffects, ensureGraphCostOutput } from './GraphBoundaryEffects.js';
12
13
  import { replayExecutionRecording } from './RecordingPlayer.js';
13
14
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
14
15
  import { buildNodeProcessContext } from './ProcessContextBuilder.js';
@@ -20,6 +21,45 @@ import { emitDetached } from '../utils/emitDetached.js';
20
21
  import { createExcludedNodeOutputs, getControlFlowExclusionDecision, getMissingRequiredInputExclusion, } from './NodeExclusionPolicy.js';
21
22
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
22
23
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
24
+ export function cloneFrozenNodeOutputs(outputs) {
25
+ if (typeof structuredClone !== 'function') {
26
+ throw new Error('Frozen node output cloning requires structuredClone support');
27
+ }
28
+ return structuredClone(outputs);
29
+ }
30
+ export function cloneFrozenNodeOutputsByGraph(outputsByGraph) {
31
+ return Object.fromEntries(Object.entries(outputsByGraph).map(([graphId, outputsByNode]) => [
32
+ graphId,
33
+ outputsByNode
34
+ ? Object.fromEntries(Object.entries(outputsByNode).map(([nodeId, outputInstances]) => [
35
+ nodeId,
36
+ outputInstances?.map((outputs) => cloneFrozenNodeOutputs(outputs)),
37
+ ]))
38
+ : undefined,
39
+ ]));
40
+ }
41
+ export function hasFrozenNodeOutputs(outputsByGraph) {
42
+ if (!outputsByGraph) {
43
+ return false;
44
+ }
45
+ return Object.values(outputsByGraph).some((outputsByNode) => Object.values(outputsByNode ?? {}).some((outputInstances) => (outputInstances?.length ?? 0) > 0));
46
+ }
47
+ export function createFrozenNodeOutputResolver(outputsByGraph) {
48
+ if (!hasFrozenNodeOutputs(outputsByGraph)) {
49
+ return undefined;
50
+ }
51
+ const countersByGraphRunAndNode = new Map();
52
+ return ({ execution, graphId, node }) => {
53
+ const outputInstances = outputsByGraph?.[graphId]?.[node.id];
54
+ if (!outputInstances?.length) {
55
+ return undefined;
56
+ }
57
+ const counterKey = `${execution.graphRunId}:${graphId}:${node.id}`;
58
+ const currentIndex = countersByGraphRunAndNode.get(counterKey) ?? 0;
59
+ countersByGraphRunAndNode.set(counterKey, currentIndex + 1);
60
+ return cloneFrozenNodeOutputs(outputInstances[Math.min(currentIndex, outputInstances.length - 1)]);
61
+ };
62
+ }
23
63
  const DEFAULT_NODE_CONCURRENCY = 8;
24
64
  export const DEFAULT_SPLIT_RUN_CONCURRENCY = 4;
25
65
  const DEFAULT_ISOMORPHIC_CODE_RUNNER = new IsomorphicCodeRunner();
@@ -86,6 +126,7 @@ export class GraphProcessor {
86
126
  #scheduler;
87
127
  #runtimeProfiler;
88
128
  #captureNodeTimings;
129
+ #frozenNodeOutputResolver;
89
130
  #useSeededExecutionPlanOnNextRun = false;
90
131
  id = nanoid();
91
132
  #includeTrace = true;
@@ -132,6 +173,7 @@ export class GraphProcessor {
132
173
  #scc = undefined;
133
174
  #graphExecutionPlan;
134
175
  #nodeProcessContextBase = undefined;
176
+ #runToRelevantNodeIds;
135
177
  #nodesNotInCycle = undefined;
136
178
  #nodeAbortControllers = new Map();
137
179
  #graphInputNodeValues = {};
@@ -218,7 +260,7 @@ export class GraphProcessor {
218
260
  const runtimeCache = this.#canUseRuntimeExecutionPlanCache() ? this.#runtimeCache : undefined;
219
261
  const shouldUseRuntimeCache = runtimeCache != null;
220
262
  const cachedPlan = runtimeCache?.executionPlans?.get(this.#graph);
221
- if (cachedPlan) {
263
+ if (cachedPlan && runtimeCache?.executionPlanNodePrefabs?.get(this.#graph) === this.#project.nodePrefabs) {
222
264
  this.#applyPreprocessedGraph(cachedPlan, { recreateNodeInstances: true });
223
265
  return;
224
266
  }
@@ -237,7 +279,9 @@ export class GraphProcessor {
237
279
  });
238
280
  if (shouldUseRuntimeCache && isGraphExecutionPlan(preprocessedGraph)) {
239
281
  runtimeCache.executionPlans ??= new WeakMap();
282
+ runtimeCache.executionPlanNodePrefabs ??= new WeakMap();
240
283
  runtimeCache.executionPlans.set(this.#graph, toReusableGraphExecutionPlan(preprocessedGraph));
284
+ runtimeCache.executionPlanNodePrefabs.set(this.#graph, this.#project.nodePrefabs);
241
285
  }
242
286
  this.#applyPreprocessedGraph(preprocessedGraph);
243
287
  }
@@ -269,7 +313,9 @@ export class GraphProcessor {
269
313
  }
270
314
  #applyPreprocessedGraph(preprocessedGraph, options = {}) {
271
315
  const nodeInstances = options.recreateNodeInstances || !('nodeInstances' in preprocessedGraph)
272
- ? this.#createNodeInstances(isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph.graphNodes : this.#graph.nodes)
316
+ ? this.#createNodeInstances(isGraphExecutionPlan(preprocessedGraph)
317
+ ? preprocessedGraph.graphNodes
318
+ : Object.values(preprocessedGraph.nodesById))
273
319
  : preprocessedGraph.nodeInstances;
274
320
  replaceRecordContents(this.#nodeInstances, nodeInstances);
275
321
  replaceRecordContents(this.#nodesById, preprocessedGraph.nodesById);
@@ -435,6 +481,9 @@ export class GraphProcessor {
435
481
  this.#visitedNodes.add(nodeId);
436
482
  this.#hasPreloadedData = true;
437
483
  }
484
+ setFrozenNodeOutputResolver(resolver) {
485
+ this.#frozenNodeOutputResolver = resolver;
486
+ }
438
487
  /** Gets all node IDs that a given node ID depends on being complete before the given node ID can start. */
439
488
  getDependencyNodesDeep(nodeId) {
440
489
  this.#ensureGraphPreprocessed();
@@ -518,6 +567,7 @@ export class GraphProcessor {
518
567
  this.#globals ??= new Map();
519
568
  this.#ignoreNodes = new Set();
520
569
  this.#nodeProcessContextBase = undefined;
570
+ this.#runToRelevantNodeIds = undefined;
521
571
  this.#abortController = this.#newAbortController();
522
572
  this.#abortController.signal.addEventListener('abort', () => {
523
573
  this.#aborted = true;
@@ -828,12 +878,7 @@ export class GraphProcessor {
828
878
  throw error;
829
879
  }
830
880
  async #finalizeGraphRun() {
831
- if (this.#graphOutputs['cost'] == null) {
832
- this.#graphOutputs['cost'] = {
833
- type: 'number',
834
- value: this.#totalCost,
835
- };
836
- }
881
+ ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
837
882
  const outputValues = this.#graphOutputs;
838
883
  this.#running = false;
839
884
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
@@ -974,7 +1019,7 @@ export class GraphProcessor {
974
1019
  const processProfileStart = this.#startRuntimeProfile();
975
1020
  let processResult;
976
1021
  try {
977
- processResult = await this.#processNode(node);
1022
+ processResult = await this.#processNode(node, inputValues);
978
1023
  }
979
1024
  finally {
980
1025
  this.#finishRuntimeProfile('nodeDispatch', processProfileStart);
@@ -1152,18 +1197,22 @@ export class GraphProcessor {
1152
1197
  }
1153
1198
  return nodeData;
1154
1199
  }
1155
- async #processNode(node) {
1200
+ async #processNode(node, inputValues) {
1156
1201
  const processId = nanoid();
1157
1202
  if (this.#abortController.signal.aborted) {
1158
1203
  await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#abortController.signal), processId);
1159
1204
  this.#successfulAbortTerminalProcessIds.delete(processId);
1160
1205
  return { processId, shouldQueueOutputNodes: false };
1161
1206
  }
1162
- if (node.isSplitRun) {
1207
+ const frozenOutputs = this.#resolveFrozenNodeOutputs(node, inputValues, processId);
1208
+ if (frozenOutputs) {
1209
+ await this.#processFrozenNode(node, processId, inputValues, frozenOutputs);
1210
+ }
1211
+ else if (node.isSplitRun) {
1163
1212
  await this.#processSplitRunNode(node, processId);
1164
1213
  }
1165
1214
  else {
1166
- await this.#processNormalNode(node, processId);
1215
+ await this.#processNormalNode(node, processId, inputValues);
1167
1216
  }
1168
1217
  const successfulAbortTerminal = this.#successfulAbortTerminalProcessIds.delete(processId);
1169
1218
  return { processId, shouldQueueOutputNodes: !successfulAbortTerminal };
@@ -1191,13 +1240,37 @@ export class GraphProcessor {
1191
1240
  finishNodeTiming: this.#captureNodeTimings ? (start) => this.#finishNodeTiming(start) : undefined,
1192
1241
  });
1193
1242
  }
1194
- async #processNormalNode(node, processId) {
1195
- const inputValuesProfileStart = this.#startRuntimeProfile();
1196
- const inputValues = this.#getInputValuesForNode(node);
1197
- this.#finishRuntimeProfile('getInputValuesForNode', inputValuesProfileStart);
1198
- if (this.#excludedDueToControlFlow(node, inputValues, processId)) {
1243
+ #resolveFrozenNodeOutputs(node, inputValues, processId) {
1244
+ return this.#frozenNodeOutputResolver?.({
1245
+ execution: this.#buildExecutionMetadata(),
1246
+ graphId: this.#graph.metadata.id,
1247
+ inputs: inputValues,
1248
+ node,
1249
+ processId,
1250
+ });
1251
+ }
1252
+ async #processFrozenNode(node, processId, inputValues, outputValues) {
1253
+ await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: inputValues, processId }));
1254
+ const timingStart = this.#startNodeTiming();
1255
+ this.#nodeResults.set(node.id, outputValues);
1256
+ this.#visitedNodes.add(node.id);
1257
+ this.#accumulateCost(outputValues);
1258
+ this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
1259
+ await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
1260
+ node,
1261
+ outputs: outputValues,
1262
+ processId,
1263
+ }, this.#finishNodeTiming(timingStart))));
1264
+ }
1265
+ #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
1266
+ const setGlobalEffect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
1267
+ if (!setGlobalEffect) {
1199
1268
  return;
1200
1269
  }
1270
+ this.#globals.set(setGlobalEffect.variableId, setGlobalEffect.value);
1271
+ emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id: setGlobalEffect.variableId, value: setGlobalEffect.value, processId }));
1272
+ }
1273
+ async #processNormalNode(node, processId, inputValues) {
1201
1274
  // Use awaited emit (not emitDetached) so that listeners can yield to the
1202
1275
  // macrotask queue, giving the browser a chance to repaint during execution.
1203
1276
  await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: inputValues, processId }));
@@ -1373,12 +1446,14 @@ export class GraphProcessor {
1373
1446
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput) {
1374
1447
  const plugin = this.#registry.getPluginFor(node.type);
1375
1448
  return buildNodeProcessContext({
1449
+ activeOutputPortIds: this.#getActiveOutputPortIds(node),
1376
1450
  attachedData: this.#getAttachedDataTo(node),
1377
1451
  base: this.#nodeProcessContextBase,
1378
1452
  createSubProcessor: (subGraphId, options = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options),
1379
1453
  execution: this.#buildExecutionMetadata(),
1380
1454
  externalFunctions: this.#externalFunctions,
1381
1455
  getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
1456
+ isDirectRunTarget: this.runToNodeIds?.includes(node.id) ?? false,
1382
1457
  node,
1383
1458
  nodeAbortController,
1384
1459
  onPartialOutputs: (partialOutputs) => {
@@ -1408,6 +1483,42 @@ export class GraphProcessor {
1408
1483
  },
1409
1484
  });
1410
1485
  }
1486
+ #getActiveOutputPortIds(node) {
1487
+ const outputConnections = getOutputNodesFrom(this.#executionState, node).connectionsToNodes;
1488
+ if (outputConnections.length === 0) {
1489
+ return new Set();
1490
+ }
1491
+ const runToRelevantNodeIds = this.#getRunToRelevantNodeIds();
1492
+ const activeOutputPortIds = new Set();
1493
+ for (const { node: outputNode, connections } of outputConnections) {
1494
+ if (outputNode.disabled) {
1495
+ continue;
1496
+ }
1497
+ if (runToRelevantNodeIds && !runToRelevantNodeIds.has(outputNode.id)) {
1498
+ continue;
1499
+ }
1500
+ for (const connection of connections) {
1501
+ activeOutputPortIds.add(connection.outputId);
1502
+ }
1503
+ }
1504
+ return activeOutputPortIds;
1505
+ }
1506
+ #getRunToRelevantNodeIds() {
1507
+ if (!this.runToNodeIds) {
1508
+ return undefined;
1509
+ }
1510
+ if (this.#runToRelevantNodeIds) {
1511
+ return this.#runToRelevantNodeIds;
1512
+ }
1513
+ const relevantNodeIds = new Set();
1514
+ for (const runToNodeId of this.runToNodeIds) {
1515
+ for (const dependencyNodeId of this.getDependencyNodesDeep(runToNodeId)) {
1516
+ relevantNodeIds.add(dependencyNodeId);
1517
+ }
1518
+ }
1519
+ this.#runToRelevantNodeIds = relevantNodeIds;
1520
+ return relevantNodeIds;
1521
+ }
1411
1522
  #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
1412
1523
  const { useAsGraphPartialOutput } = node.data ?? {};
1413
1524
  if (!(useAsGraphPartialOutput && this.#executor && this.#parent)) {
@@ -1456,6 +1567,7 @@ export class GraphProcessor {
1456
1567
  processor.#contextValues = this.#contextValues;
1457
1568
  processor.#parent = this;
1458
1569
  processor.#globals = this.#globals;
1570
+ processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
1459
1571
  processor.#executor = {
1460
1572
  nodeId: node.id,
1461
1573
  parentGraphId: this.#graph.metadata.id,
@@ -7,7 +7,7 @@ export function emptyNodeGraph() {
7
7
  connections: [],
8
8
  metadata: {
9
9
  id: nanoid(),
10
- name: 'Untitled Graph',
10
+ name: 'Untitled graph',
11
11
  description: '',
12
12
  },
13
13
  };
@@ -0,0 +1,57 @@
1
+ export const NODE_PREFAB_INSTANCE_TYPE = 'nodePrefabInstance';
2
+ const BLOCKED_NODE_PREFAB_SOURCE_TYPES = new Set([
3
+ 'comment',
4
+ 'graphInput',
5
+ 'graphOutput',
6
+ 'referencedGraphAlias',
7
+ NODE_PREFAB_INSTANCE_TYPE,
8
+ ]);
9
+ export function isNodePrefabInstanceNode(node) {
10
+ return node?.type === NODE_PREFAB_INSTANCE_TYPE;
11
+ }
12
+ export function canUseNodeAsPrefabSource(node) {
13
+ return !BLOCKED_NODE_PREFAB_SOURCE_TYPES.has(node.type);
14
+ }
15
+ export function getNodePrefabInstancePrefabId(node) {
16
+ if (!isNodePrefabInstanceNode(node)) {
17
+ return undefined;
18
+ }
19
+ const prefabId = node.data?.prefabId;
20
+ return typeof prefabId === 'string' && prefabId.length > 0 ? prefabId : undefined;
21
+ }
22
+ export function resolveNodePrefabInstance(project, node) {
23
+ const prefabId = getNodePrefabInstancePrefabId(node);
24
+ if (!prefabId) {
25
+ return node;
26
+ }
27
+ const sourceNode = project.nodePrefabs?.[prefabId]?.sourceNode;
28
+ if (!sourceNode || !canUseNodeAsPrefabSource(sourceNode)) {
29
+ return {
30
+ ...node,
31
+ title: `Missing library node (${prefabId})`,
32
+ };
33
+ }
34
+ return {
35
+ ...structuredClone(sourceNode),
36
+ id: node.id,
37
+ visualData: {
38
+ ...structuredClone(sourceNode.visualData),
39
+ x: node.visualData.x,
40
+ y: node.visualData.y,
41
+ width: node.visualData.width ?? sourceNode.visualData.width,
42
+ zIndex: node.visualData.zIndex,
43
+ },
44
+ };
45
+ }
46
+ export function resolveNodePrefabInstances(project, nodes) {
47
+ return nodes.map((node) => resolveNodePrefabInstance(project, node));
48
+ }
49
+ export function getNodePrefabDisplayName(project, prefabId) {
50
+ if (!prefabId) {
51
+ return 'Missing library node';
52
+ }
53
+ const sourceNode = project.nodePrefabs?.[prefabId]?.sourceNode;
54
+ return sourceNode && canUseNodeAsPrefabSource(sourceNode)
55
+ ? sourceNode.title || 'Untitled library node'
56
+ : 'Missing library node';
57
+ }
@@ -178,6 +178,8 @@ import { mcpGetPromptNode } from './nodes/MCPGetPromptNode.js';
178
178
  export * from './nodes/MCPGetPromptNode.js';
179
179
  import { referencedGraphAliasNode } from './nodes/ReferencedGraphAliasNode.js';
180
180
  export * from './nodes/ReferencedGraphAliasNode.js';
181
+ import { nodePrefabInstanceNode } from './nodes/NodePrefabInstanceNode.js';
182
+ export * from './nodes/NodePrefabInstanceNode.js';
181
183
  export const registerBuiltInNodes = (registry) => {
182
184
  return registry
183
185
  .register(toYamlNode)
@@ -268,7 +270,8 @@ export const registerBuiltInNodes = (registry) => {
268
270
  .register(mcpDiscoveryNode)
269
271
  .register(mcpToolCallNode)
270
272
  .register(mcpGetPromptNode)
271
- .register(referencedGraphAliasNode);
273
+ .register(referencedGraphAliasNode)
274
+ .register(nodePrefabInstanceNode);
272
275
  };
273
276
  let globalRivetNodeRegistry = registerBuiltInNodes(new NodeRegistration());
274
277
  export { globalRivetNodeRegistry };
@@ -1,9 +1,11 @@
1
1
  export function buildNodeProcessContext(options) {
2
- const { attachedData, base, createSubProcessor, execution, externalFunctions, getPluginConfig, node, nodeAbortController, onPartialOutputs, processId, requestUserInput, setGlobal, waitEvent, } = options;
2
+ const { attachedData, activeOutputPortIds, base, createSubProcessor, execution, externalFunctions, getPluginConfig, isDirectRunTarget, node, nodeAbortController, onPartialOutputs, processId, requestUserInput, setGlobal, waitEvent, } = options;
3
3
  return {
4
4
  ...base,
5
5
  node,
6
6
  attachedData,
7
+ activeOutputPortIds,
8
+ isDirectRunTarget,
7
9
  waitEvent,
8
10
  externalFunctions: { ...externalFunctions },
9
11
  onPartialOutputs,
@@ -0,0 +1,113 @@
1
+ import { newId } from '../utils/newId.js';
2
+ export function createDefaultUiGraph(options = {}) {
3
+ const promptStateKey = 'input';
4
+ const resultStateKey = 'result';
5
+ return {
6
+ id: newId(),
7
+ name: options.name ?? 'Untitled web app',
8
+ components: [
9
+ {
10
+ id: newId(),
11
+ type: 'markdown',
12
+ markdown: '## New Rivet web app\n\nEnter a value and run a graph.',
13
+ },
14
+ {
15
+ id: newId(),
16
+ type: 'textarea',
17
+ label: 'Input',
18
+ stateKey: promptStateKey,
19
+ placeholder: 'Type something...',
20
+ },
21
+ {
22
+ id: newId(),
23
+ type: 'button',
24
+ label: 'Run graph',
25
+ action: {
26
+ type: 'runGraph',
27
+ graphId: options.graphId,
28
+ inputMappings: [{ inputKey: 'input', stateKey: promptStateKey }],
29
+ outputs: [{ stateKey: resultStateKey }],
30
+ },
31
+ },
32
+ {
33
+ id: newId(),
34
+ type: 'output',
35
+ label: 'Result',
36
+ stateKey: resultStateKey,
37
+ renderAs: 'json',
38
+ },
39
+ ],
40
+ };
41
+ }
42
+ export function getUiGraphInitialState(uiGraph) {
43
+ const state = {};
44
+ for (const component of uiGraph.components) {
45
+ if (component.type === 'input' || component.type === 'textarea') {
46
+ state[component.stateKey] = component.defaultValue ?? '';
47
+ }
48
+ }
49
+ return state;
50
+ }
51
+ export function getUiGraphActionComponent(uiGraph, componentId) {
52
+ return uiGraph.components.find((component) => component.id === componentId && component.type === 'button');
53
+ }
54
+ export function resolveUiGraphActionInputs(action, state) {
55
+ const inputs = {};
56
+ if (action.inputMappings) {
57
+ for (const binding of action.inputMappings) {
58
+ if (binding.inputKey) {
59
+ inputs[binding.inputKey] = state[binding.stateKey];
60
+ }
61
+ }
62
+ return inputs;
63
+ }
64
+ for (const [inputId, binding] of Object.entries(action.inputs ?? {})) {
65
+ inputs[inputId] = binding.type === 'state' ? state[binding.key] : binding.value;
66
+ }
67
+ return inputs;
68
+ }
69
+ export function resolveUiGraphActionOutputStateValue(action, outputs) {
70
+ if (!action.outputKey) {
71
+ return outputs;
72
+ }
73
+ if (!Object.prototype.hasOwnProperty.call(outputs, action.outputKey)) {
74
+ throw new Error(`Graph output "${action.outputKey}" was not returned by the target graph.`);
75
+ }
76
+ return outputs[action.outputKey]?.value;
77
+ }
78
+ export function resolveUiGraphActionOutputStatePatch(action, outputs) {
79
+ const bindings = getUiGraphActionOutputBindings(action);
80
+ const statePatch = {};
81
+ for (const binding of bindings) {
82
+ const stateKey = binding.stateKey.trim();
83
+ if (!stateKey) {
84
+ continue;
85
+ }
86
+ statePatch[stateKey] = resolveUiGraphOutputBindingValue(binding, outputs);
87
+ }
88
+ return statePatch;
89
+ }
90
+ export function getUiGraphActionOutputBindings(action) {
91
+ if (action.outputs) {
92
+ return action.outputs;
93
+ }
94
+ return action.outputStateKey ? [{ outputKey: action.outputKey, stateKey: action.outputStateKey }] : [];
95
+ }
96
+ export function getUiGraphActionInputBindings(action) {
97
+ if (action.inputMappings) {
98
+ return action.inputMappings;
99
+ }
100
+ return Object.entries(action.inputs ?? {}).map(([inputKey, binding]) => ({
101
+ inputKey,
102
+ stateKey: binding.type === 'state' ? binding.key : '',
103
+ }));
104
+ }
105
+ function resolveUiGraphOutputBindingValue(binding, outputs) {
106
+ if (!binding.outputKey) {
107
+ return outputs;
108
+ }
109
+ if (!Object.prototype.hasOwnProperty.call(outputs, binding.outputKey)) {
110
+ throw new Error(`Graph output "${binding.outputKey}" was not returned by the target graph.`);
111
+ }
112
+ return outputs[binding.outputKey]?.value;
113
+ }