@valerypopoff/rivet2-core 2.7.0 → 2.9.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 (44) hide show
  1. package/dist/cjs/bundle.cjs +514 -353
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  4. package/dist/esm/model/GraphPreprocessor.js +11 -0
  5. package/dist/esm/model/GraphProcessor.js +84 -24
  6. package/dist/esm/model/LegacyChatEditorCache.js +50 -0
  7. package/dist/esm/model/NodeExclusionPolicy.js +1 -0
  8. package/dist/esm/model/Nodes.js +3 -0
  9. package/dist/esm/model/RecordingPlayer.js +20 -2
  10. package/dist/esm/model/StreamingOutputWatch.js +18 -18
  11. package/dist/esm/model/StreamingOutputWatchHistory.js +1 -0
  12. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  13. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +2 -1
  14. package/dist/esm/model/nodes/ChatLoopNode.js +8 -4
  15. package/dist/esm/model/nodes/ChatNodeBase.js +18 -13
  16. package/dist/esm/model/nodes/CoalesceNewNode.js +22 -0
  17. package/dist/esm/model/nodes/CoalesceNode.js +15 -133
  18. package/dist/esm/model/nodes/CoalesceNodeBase.js +131 -0
  19. package/dist/esm/model/nodes/CodeNewNode.js +1 -1
  20. package/dist/esm/model/nodes/ExpressionNode.js +1 -1
  21. package/dist/esm/model/nodes/LoopControllerNode.js +6 -4
  22. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +2 -0
  23. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +17 -15
  24. package/dist/esm/plugins/google/google.js +8 -128
  25. package/dist/esm/plugins/google/googleGenerativeAi.js +101 -0
  26. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +36 -15
  27. package/dist/esm/recording/ExecutionRecorder.js +2 -1
  28. package/dist/types/model/ExecutorProtocol.d.ts +1 -0
  29. package/dist/types/model/GraphPreprocessor.d.ts +2 -0
  30. package/dist/types/model/GraphProcessor.d.ts +5 -1
  31. package/dist/types/model/LegacyChatEditorCache.d.ts +39 -0
  32. package/dist/types/model/Nodes.d.ts +3 -2
  33. package/dist/types/model/StreamingOutputWatch.d.ts +13 -11
  34. package/dist/types/model/StreamingOutputWatchHistory.d.ts +2 -0
  35. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -0
  36. package/dist/types/model/nodes/ChatLoopNode.d.ts +2 -0
  37. package/dist/types/model/nodes/CoalesceNewNode.d.ts +10 -0
  38. package/dist/types/model/nodes/CoalesceNode.d.ts +9 -15
  39. package/dist/types/model/nodes/CoalesceNodeBase.d.ts +19 -0
  40. package/dist/types/model/nodes/LoopControllerNode.d.ts +2 -0
  41. package/dist/types/plugins/google/google.d.ts +3 -110
  42. package/dist/types/plugins/google/googleGenerativeAi.d.ts +110 -0
  43. package/dist/types/recording/RecordedEvents.d.ts +1 -0
  44. package/package.json +1 -1
@@ -36,6 +36,7 @@ export function preprocessGraphState(options) {
36
36
  connections[connection.outputNodeId].push(connection);
37
37
  }
38
38
  const definitions = loadInputOutputDefinitions({
39
+ inputAnchorDefinitions: options.inputAnchorDefinitions,
39
40
  connections,
40
41
  loadedProjects,
41
42
  nodeInstances,
@@ -102,6 +103,11 @@ function loadInputOutputDefinitions(options) {
102
103
  const definitions = {};
103
104
  if (!definitionContext) {
104
105
  for (const node of values(nodesById)) {
106
+ const anchorDefinitions = options.inputAnchorDefinitions?.[node.id];
107
+ if (anchorDefinitions) {
108
+ definitions[node.id] = anchorDefinitions;
109
+ continue;
110
+ }
105
111
  const connectionsForNode = connections[node.id] ?? [];
106
112
  const inputDefinitions = nodeInstances[node.id].getInputDefinitionsIncludingBuiltIn(connectionsForNode, nodesById, project, loadedProjects);
107
113
  const outputDefinitions = nodeInstances[node.id].getOutputDefinitions(connectionsForNode, nodesById, project, loadedProjects);
@@ -144,6 +150,11 @@ function loadInputOutputDefinitions(options) {
144
150
  return definitions;
145
151
  }
146
152
  for (const node of values(nodesById)) {
153
+ const anchorDefinitions = options.inputAnchorDefinitions?.[node.id];
154
+ if (anchorDefinitions) {
155
+ definitions[node.id] = anchorDefinitions;
156
+ continue;
157
+ }
147
158
  const connectionsForNode = connections[node.id] ?? [];
148
159
  const nodeDefinitionContext = usesGraphBoundaryDefinitionContext(node) ? definitionContext : undefined;
149
160
  const inputDefinitions = nodeDefinitionContext
@@ -43,6 +43,7 @@ import { loadProjectReferenceTree } from './ProjectReferenceLoader.js';
43
43
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
44
44
  const graphProcessorGraphOverride = Symbol('graphProcessorGraphOverride');
45
45
  const consumedAsyncBranchTriggerOverride = Symbol('consumedAsyncBranchTriggerOverride');
46
+ const asyncBranchInputAnchorsOverride = Symbol('asyncBranchInputAnchorsOverride');
46
47
  const consumedStreamingWatchNodeOverride = Symbol('consumedStreamingWatchNodeOverride');
47
48
  /**
48
49
  * These nodes expose a child graph's named Graph Output ports verbatim. Other
@@ -177,6 +178,7 @@ export class GraphProcessor {
177
178
  #effectiveConnectionsForRun;
178
179
  #asyncBranchPlansByTriggerNodeId = new Map();
179
180
  #consumedAsyncBranchTriggerNodeId;
181
+ #asyncBranchInputAnchors;
180
182
  #streamingWatchPlansBySourceNodeId = new Map();
181
183
  #streamingWatchPlansByWatchNodeId = new Map();
182
184
  #streamingOutputWatches = new Map();
@@ -225,6 +227,11 @@ export class GraphProcessor {
225
227
  #graphOutputs = undefined;
226
228
  #executionCache = undefined;
227
229
  #queuedNodes = undefined;
230
+ /**
231
+ * Nodes deferred only because Run To reached its initial scheduler quiescence.
232
+ * A streaming Stop can legitimately resume one of those selected paths later.
233
+ */
234
+ #deferredRunToIgnoredNodes = undefined;
228
235
  #loopControllersSeen = undefined;
229
236
  #subprocessors = undefined;
230
237
  #contextValues = undefined;
@@ -329,6 +336,7 @@ export class GraphProcessor {
329
336
  this.#runtimeProfiler = options?.runtimeProfiler;
330
337
  this.#captureNodeTimings = options?.captureNodeTimings ?? false;
331
338
  this.#consumedAsyncBranchTriggerNodeId = options?.[consumedAsyncBranchTriggerOverride];
339
+ this.#asyncBranchInputAnchors = options?.[asyncBranchInputAnchorsOverride];
332
340
  this.#consumedStreamingWatchNodeId = options?.[consumedStreamingWatchNodeOverride];
333
341
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
334
342
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
@@ -354,6 +362,7 @@ export class GraphProcessor {
354
362
  return;
355
363
  }
356
364
  const preprocessedGraph = preprocessGraphState({
365
+ inputAnchorDefinitions: this.#asyncBranchInputAnchors,
357
366
  graph: this.#graph,
358
367
  loadedProjects: this.#loadedProjects,
359
368
  project: this.#project,
@@ -691,6 +700,7 @@ export class GraphProcessor {
691
700
  this.#graphOutputs = this.#sharedRunStateOverride?.graphOutputs ?? {};
692
701
  this.#executionCache ??= new Map();
693
702
  this.#queuedNodes = new Set();
703
+ this.#deferredRunToIgnoredNodes = new Set();
694
704
  this.#connectedToolContinuationHost.reset();
695
705
  this.#continuationCompletionOwnerByNodeId = new Map();
696
706
  this.#effectiveConnectionsForRun = undefined;
@@ -1190,8 +1200,9 @@ export class GraphProcessor {
1190
1200
  return;
1191
1201
  }
1192
1202
  for (const node of this.#executionGraphNodes) {
1193
- if (this.#queuedNodes.has(node.id) === false) {
1203
+ if (this.#queuedNodes.has(node.id) === false && !this.#ignoreNodes.has(node.id)) {
1194
1204
  this.#ignoreNodes.add(node.id);
1205
+ this.#deferredRunToIgnoredNodes.add(node.id);
1195
1206
  }
1196
1207
  }
1197
1208
  }
@@ -1578,6 +1589,12 @@ export class GraphProcessor {
1578
1589
  const selectedOutputs = this.#graphOutputSelection
1579
1590
  ? outputNodes.filter((outputNode) => this.#isNodeSelected(outputNode.id))
1580
1591
  : outputNodes;
1592
+ const relevantNodeIds = this.#getExecutionRelevantNodeIds();
1593
+ for (const outputNode of selectedOutputs) {
1594
+ if (relevantNodeIds?.has(outputNode.id) && this.#deferredRunToIgnoredNodes.delete(outputNode.id)) {
1595
+ this.#ignoreNodes.delete(outputNode.id);
1596
+ }
1597
+ }
1581
1598
  void this.#processingQueue.addAll(selectedOutputs.map((outputNode) => async () => {
1582
1599
  this.#emitTraceEvent(`Trying to run output node from ${node.title}: ${outputNode.title} (${outputNode.id})`);
1583
1600
  await this.#processNodeIfAllInputsAvailable(outputNode);
@@ -1647,6 +1664,9 @@ export class GraphProcessor {
1647
1664
  scheduler: this.#scheduler,
1648
1665
  [graphProcessorGraphOverride]: plan.graph,
1649
1666
  [consumedAsyncBranchTriggerOverride]: triggerNode.id,
1667
+ [asyncBranchInputAnchorsOverride]: Object.fromEntries(plan.graph.connections
1668
+ .filter((connection) => connection.inputNodeId === triggerNode.id)
1669
+ .map((connection) => [connection.outputNodeId, this.#definitions[connection.outputNodeId]])),
1650
1670
  });
1651
1671
  onProcessorCreated(processor);
1652
1672
  processor.executor = this.executor;
@@ -1811,13 +1831,15 @@ export class GraphProcessor {
1811
1831
  emitDetached(this.#emitter, event, this.#withExecution(data));
1812
1832
  return;
1813
1833
  }
1814
- return this.#emitter.emit(event, this.#withExecution(data)).then(() => {
1815
- if (event === 'nodeFinish') {
1816
- // SplitRunDeps exposes overloaded event payloads; the runtime event
1817
- // discriminator guarantees this is the terminal-output shape.
1818
- this.#commitStreamingWatchStop(node, data.outputs);
1819
- }
1820
- });
1834
+ // SplitRunDeps exposes overloaded event payloads; the runtime event
1835
+ // discriminator guarantees this is the terminal-output shape.
1836
+ const stopClaim = event === 'nodeFinish'
1837
+ ? this.#claimStreamingWatchStopFromInvocation(node, data.outputs)
1838
+ : undefined;
1839
+ const eventData = event === 'nodeFinish' && stopClaim
1840
+ ? { ...data, streamingWatchTerminal: true }
1841
+ : data;
1842
+ return this.#emitter.emit(event, this.#withExecution(eventData)).then(() => stopClaim?.commit());
1821
1843
  },
1822
1844
  startNodeTiming: this.#captureNodeTimings ? () => this.#startNodeTiming() : undefined,
1823
1845
  finishNodeTiming: this.#captureNodeTimings ? (start) => this.#finishNodeTiming(start) : undefined,
@@ -1886,14 +1908,16 @@ export class GraphProcessor {
1886
1908
  this.#visitedNodes.add(node.id);
1887
1909
  this.#accumulateCost(outputValues);
1888
1910
  this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
1911
+ const stopClaim = this.#claimStreamingWatchStopFromInvocation(node, outputValues);
1889
1912
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
1890
1913
  node,
1891
1914
  outputs: outputValues,
1892
1915
  processId,
1893
1916
  resultOrigin,
1917
+ ...(stopClaim ? { streamingWatchTerminal: true } : {}),
1894
1918
  }, this.#finishNodeTiming(timingStart))));
1895
1919
  this.#finishStreamingOutputWatches(node, outputValues);
1896
- this.#commitStreamingWatchStop(node, outputValues);
1920
+ stopClaim?.commit();
1897
1921
  }
1898
1922
  catch (error) {
1899
1923
  await this.#nodeErrored(node, error, processId, this.#finishNodeTiming(timingStart), undefined, resultOrigin, this.#takeFailureOutputs(processId, 0));
@@ -2645,12 +2669,13 @@ export class GraphProcessor {
2645
2669
  nextUpdateIndex: 0,
2646
2670
  history: new StreamingOutputWatchHistory(),
2647
2671
  historySummaryEmitted: false,
2672
+ unmatchedStopResolved: false,
2648
2673
  };
2649
2674
  const plans = this.#streamingWatchPlansBySourceNodeId.get(sourceNode.id) ?? [];
2650
2675
  plans.push(plan);
2651
2676
  this.#streamingWatchPlansBySourceNodeId.set(sourceNode.id, plans);
2652
2677
  this.#streamingWatchPlansByWatchNodeId.set(watchNode.id, plan);
2653
- const watch = new StreamingOutputWatch(watchNode.data, (snapshot, registerCancel) => this.#runStreamingOutputWatchInvocation(plan, snapshot, registerCancel), (error) => this.#recordStreamingWatchFailure(watchNode, error), { requiresAcceptedStop: stopNodeId != null });
2678
+ const watch = new StreamingOutputWatch(watchNode.data, (snapshot, registerCancel) => this.#runStreamingOutputWatchInvocation(plan, snapshot, registerCancel), (error) => this.#recordStreamingWatchFailure(watchNode, error));
2654
2679
  this.#streamingOutputWatches.set(watchNode.id, watch);
2655
2680
  for (const nodeId of [watchNode.id, ...branchNodeIds]) {
2656
2681
  this.#ignoreNodes.add(nodeId);
@@ -2962,7 +2987,7 @@ export class GraphProcessor {
2962
2987
  processor.#streamingWatchInvocation = {
2963
2988
  plan,
2964
2989
  historyIteration,
2965
- acceptStop: (value) => this.#acceptStreamingWatchStop(plan, historyIteration, value, snapshot.updateIndex),
2990
+ claimStop: (value) => this.#claimAcceptedStreamingWatchStop(plan, historyIteration, value, snapshot.updateIndex),
2966
2991
  stopReached: false,
2967
2992
  };
2968
2993
  processor.preloadNodeData(plan.watchNode.id, this.#materializeStreamingOutputWatchSnapshot(snapshot));
@@ -3043,24 +3068,25 @@ export class GraphProcessor {
3043
3068
  root.#subprocessors.delete(processor);
3044
3069
  }
3045
3070
  }
3046
- #commitStreamingWatchStop(node, outputs) {
3071
+ #claimStreamingWatchStopFromInvocation(node, outputs) {
3047
3072
  const invocation = this.#streamingWatchInvocation;
3048
3073
  const completedValue = outputs['value'];
3049
3074
  if (invocation?.plan.stopNodeId === node.id &&
3050
3075
  invocation.stopReached &&
3051
3076
  completedValue !== undefined &&
3052
3077
  !this.#getUnhandledErroredNodes().length) {
3053
- invocation.acceptStop(completedValue);
3078
+ return invocation.claimStop(completedValue);
3054
3079
  }
3080
+ return undefined;
3055
3081
  }
3056
- #acceptStreamingWatchStop(plan, historyIteration, value, updateIndex) {
3082
+ #claimAcceptedStreamingWatchStop(plan, historyIteration, value, updateIndex) {
3057
3083
  const stopNodeId = plan.stopNodeId;
3058
3084
  if (!stopNodeId) {
3059
- return;
3085
+ return undefined;
3060
3086
  }
3061
3087
  const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3062
3088
  if (!watch || watch.stopped) {
3063
- return;
3089
+ return undefined;
3064
3090
  }
3065
3091
  plan.history.acceptStop(historyIteration);
3066
3092
  watch.stop(updateIndex);
@@ -3069,13 +3095,21 @@ export class GraphProcessor {
3069
3095
  throw new Error(`Watch Streaming Output "${plan.watchNode.title}" lost its Stop Watching Streaming Output node.`);
3070
3096
  }
3071
3097
  const acceptedValue = cloneExecutionOutputs({ ['value']: value })['value'];
3072
- this.#nodeResults.set(stopNode.id, { ['value']: acceptedValue });
3073
- this.#visitedNodes.add(stopNode.id);
3074
- this.#remainingNodes.delete(stopNode.id);
3075
- const attachedData = this.#getAttachedDataTo(stopNode);
3076
- const outputNodes = getOutputNodesFrom(this.#executionState, stopNode);
3077
- this.#propagateAttachedDataToOutputNodes(stopNode, attachedData, outputNodes.connectionsToNodes);
3078
- this.#queueOutputNodes(stopNode, outputNodes.nodes);
3098
+ let committed = false;
3099
+ return {
3100
+ commit: () => {
3101
+ if (committed)
3102
+ return;
3103
+ committed = true;
3104
+ this.#nodeResults.set(stopNode.id, { ['value']: acceptedValue });
3105
+ this.#visitedNodes.add(stopNode.id);
3106
+ this.#remainingNodes.delete(stopNode.id);
3107
+ const attachedData = this.#getAttachedDataTo(stopNode);
3108
+ const outputNodes = getOutputNodesFrom(this.#executionState, stopNode);
3109
+ this.#propagateAttachedDataToOutputNodes(stopNode, attachedData, outputNodes.connectionsToNodes);
3110
+ this.#queueOutputNodes(stopNode, outputNodes.nodes);
3111
+ },
3112
+ };
3079
3113
  }
3080
3114
  #cancelStreamingOutputWatchesForSource(nodeId) {
3081
3115
  for (const plan of this.#streamingWatchPlansBySourceNodeId.get(nodeId) ?? []) {
@@ -3091,7 +3125,10 @@ export class GraphProcessor {
3091
3125
  return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending);
3092
3126
  }
3093
3127
  #hasUnresolvedForegroundOutputStreamingWatch() {
3094
- return [...this.#streamingOutputWatches.values()].some((watch) => !watch.stopped && watch.canAffectForegroundOutputs);
3128
+ return [...this.#streamingOutputWatches].some(([watchNodeId, watch]) => {
3129
+ const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3130
+ return plan?.stopNodeId != null && !plan.unmatchedStopResolved && !watch.stopped;
3131
+ });
3095
3132
  }
3096
3133
  #hasDrainableStreamingOutputWatches() {
3097
3134
  return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
@@ -3114,6 +3151,11 @@ export class GraphProcessor {
3114
3151
  // work after the compatible scheduler has returned, so wait for that work
3115
3152
  // before deciding every Watch boundary is quiet.
3116
3153
  await this.#processingQueue.onIdle();
3154
+ this.#resolveUnmatchedStreamingWatchStops();
3155
+ // Excluding the parent Stop queues its ordinary downstream nodes. Let
3156
+ // their normal control-flow rules run before emitting the settled Watch
3157
+ // summary or finalizing the root graph.
3158
+ await this.#processingQueue.onIdle();
3117
3159
  } while (this.#hasDrainableStreamingOutputWatches());
3118
3160
  for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3119
3161
  const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
@@ -3124,6 +3166,20 @@ export class GraphProcessor {
3124
3166
  await this.#emitter.emit('streamingOutputWatchSummary', this.#withExecution({ watchNode: plan.watchNode, summary }));
3125
3167
  }
3126
3168
  }
3169
+ #resolveUnmatchedStreamingWatchStops() {
3170
+ for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3171
+ const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3172
+ if (!plan?.stopNodeId || plan.unmatchedStopResolved || !watch.finishedNormally) {
3173
+ continue;
3174
+ }
3175
+ const stopNode = this.#nodesById[plan.stopNodeId];
3176
+ if (!stopNode) {
3177
+ throw new Error(`Watch Streaming Output "${plan.watchNode.title}" lost its Stop Watching Streaming Output node.`);
3178
+ }
3179
+ plan.unmatchedStopResolved = true;
3180
+ this.#excludeNode(stopNode, nanoid(), {}, 'stream completed without Stop Watching Streaming Output accepting a value');
3181
+ }
3182
+ }
3127
3183
  #prepareAsyncBranchTopology() {
3128
3184
  const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
3129
3185
  const outgoingByNodeId = new Map();
@@ -3139,6 +3195,10 @@ export class GraphProcessor {
3139
3195
  incomingByNodeId.set(connection.inputNodeId, incoming);
3140
3196
  }
3141
3197
  for (const triggerNode of Object.values(this.#nodesById)) {
3198
+ // Input anchors describe the consumed trigger's ports, not executable work.
3199
+ // A variadic anchor may itself be an outer async trigger.
3200
+ if (this.#asyncBranchInputAnchors?.[triggerNode.id])
3201
+ continue;
3142
3202
  if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRelevant(triggerNode.id)) {
3143
3203
  continue;
3144
3204
  }
@@ -0,0 +1,50 @@
1
+ import CryptoJS from 'crypto-js';
2
+ import stableStringify from 'safe-stable-stringify';
3
+ import { cloneExecutionOutputs } from './ExecutionOutputClone.js';
4
+ /**
5
+ * Builds an opaque cache key for a legacy chat request.
6
+ *
7
+ * Legacy chat nodes may receive credentials and request headers from settings,
8
+ * neither of which belongs in a process-global key (or in clear text in any
9
+ * cache key). The digest scopes entries to the graph/node and all effective
10
+ * request/provider inputs without retaining those values in the Map key.
11
+ */
12
+ export function buildLegacyChatEditorCacheKey(parts) {
13
+ const serialized = stableStringify({ cacheVersion: 1, ...parts }) ?? '';
14
+ return `legacy-chat:v1:sha256:${CryptoJS.SHA256(serialized).toString(CryptoJS.enc.Hex)}`;
15
+ }
16
+ /**
17
+ * Resolves the existing host-owned editor cache for a legacy chat request.
18
+ * Programmatic callers that do not supply an editor cache remain isolated to
19
+ * their GraphProcessor's execution cache instead of sharing process state.
20
+ */
21
+ export function resolveLegacyChatEditorCache(params) {
22
+ if (!params.enabled) {
23
+ return { cache: undefined, cachedOutputs: undefined };
24
+ }
25
+ const cache = params.context.editorExecutionCache ?? params.context.executionCache;
26
+ if (cache == null) {
27
+ // Lightweight direct plugin callers historically provide only the process
28
+ // fields they need. Caching is optional, so an absent host cache must not
29
+ // make that invocation fail.
30
+ return { cache: undefined, cachedOutputs: undefined };
31
+ }
32
+ const cacheKey = buildLegacyChatEditorCacheKey({
33
+ graphId: params.context.execution?.graphId,
34
+ nodeId: params.context.node.id,
35
+ nodeType: params.context.node.type,
36
+ providerIdentity: params.providerIdentity,
37
+ request: params.request,
38
+ });
39
+ const cached = cache.get(cacheKey);
40
+ return {
41
+ cache: { cache, cacheKey },
42
+ cachedOutputs: cached == null ? undefined : cloneExecutionOutputs(cached),
43
+ };
44
+ }
45
+ /** Stores a private snapshot so downstream execution cannot mutate a cache entry. */
46
+ export function writeLegacyChatEditorCache(cache, outputs) {
47
+ if (cache != null) {
48
+ cache.cache.set(cache.cacheKey, cloneExecutionOutputs(outputs));
49
+ }
50
+ }
@@ -7,6 +7,7 @@ const nodesAllowedToConsumeExcludedValue = new Set([
7
7
  'if',
8
8
  'ifElse',
9
9
  'coalesce',
10
+ 'coalesceNew',
10
11
  'graphOutput',
11
12
  'raceInputs',
12
13
  'loopController',
@@ -62,6 +62,8 @@ import { contextNode } from './nodes/ContextNode.js';
62
62
  export * from './nodes/ContextNode.js';
63
63
  import { coalesceNode } from './nodes/CoalesceNode.js';
64
64
  export * from './nodes/CoalesceNode.js';
65
+ import { coalesceNewNode } from './nodes/CoalesceNewNode.js';
66
+ export * from './nodes/CoalesceNewNode.js';
65
67
  import { didRunNode } from './nodes/DidRunNode.js';
66
68
  export * from './nodes/DidRunNode.js';
67
69
  import { passthroughNode } from './nodes/PassthroughNode.js';
@@ -243,6 +245,7 @@ export const registerBuiltInNodes = (registry) => {
243
245
  .register(reportProgressNode)
244
246
  .register(contextNode)
245
247
  .register(coalesceNode)
248
+ .register(coalesceNewNode)
246
249
  .register(didRunNode)
247
250
  .register(passthroughNode)
248
251
  .register(dataBusNode)
@@ -356,6 +356,7 @@ export async function replayExecutionRecording(options) {
356
356
  outputs: data.outputs,
357
357
  processId: data.processId,
358
358
  ...(data.resultOrigin === undefined ? {} : { resultOrigin: data.resultOrigin }),
359
+ ...(data.streamingWatchTerminal ? { streamingWatchTerminal: true } : {}),
359
360
  execution,
360
361
  }, getRecordedDuration(data.durationMs, execution, data.nodeId, data.processId, getRecordedEventOccurrenceAt(event)), data.splitRunDurationMs));
361
362
  nodeResults.set(data.nodeId, data.outputs);
@@ -409,10 +410,27 @@ export async function replayExecutionRecording(options) {
409
410
  }
410
411
  case 'streamingOutputWatchSummary': {
411
412
  const { data } = event;
413
+ const execution = getExecution(data.execution?.graphId ?? getGraphIdForNode(data.watchNodeId), data.execution);
414
+ // Watch summaries identify one retained child branch as terminal.
415
+ // A replay creates fresh graph-run IDs, so remap that child identity
416
+ // with the same root-scoped map used for its retained node events.
417
+ const selectedIteration = data.summary.selectedIteration;
418
+ const summary = selectedIteration?.graphRunId != null && data.execution != null
419
+ ? {
420
+ ...data.summary,
421
+ selectedIteration: {
422
+ ...selectedIteration,
423
+ graphRunId: getReplayExecution({
424
+ ...data.execution,
425
+ graphRunId: selectedIteration.graphRunId,
426
+ }).graphRunId,
427
+ },
428
+ }
429
+ : data.summary;
412
430
  emitReplayExecutionEvent('streamingOutputWatchSummary', {
413
431
  watchNode: getNode(data.watchNodeId),
414
- summary: data.summary,
415
- execution: getExecution(data.execution?.graphId ?? getGraphIdForNode(data.watchNodeId), data.execution),
432
+ summary,
433
+ execution,
416
434
  });
417
435
  break;
418
436
  }
@@ -25,14 +25,13 @@ function normalizePositiveInteger(value, fallback, maximum) {
25
25
  /**
26
26
  * Owns bounded, cancellable delivery of a streaming node's immutable output
27
27
  * snapshots. It deliberately knows nothing about graph topology: the owning
28
- * GraphProcessor decides how a snapshot runs and whether accepting Stop is
29
- * required to complete the watch.
28
+ * GraphProcessor decides how a snapshot runs and whether a Stop boundary
29
+ * must be resolved after the stream completes.
30
30
  */
31
31
  export class StreamingOutputWatch {
32
32
  #options;
33
33
  #run;
34
34
  #onFailure;
35
- #requiresAcceptedStop;
36
35
  #queue = [];
37
36
  #activeRuns = new Set();
38
37
  #timer;
@@ -46,7 +45,7 @@ export class StreamingOutputWatch {
46
45
  #coalescedUpdates = 0;
47
46
  #droppedUpdates = 0;
48
47
  #maximumQueuedUpdates = 0;
49
- constructor(options, run, onFailure, { requiresAcceptedStop = true } = {}) {
48
+ constructor(options, run, onFailure) {
50
49
  this.#options = {
51
50
  triggerMode: options.triggerMode === 'interval' ? 'interval' : 'every-update',
52
51
  executionMode: options.executionMode === 'parallel' ? 'parallel' : 'sequential',
@@ -57,13 +56,12 @@ export class StreamingOutputWatch {
57
56
  };
58
57
  this.#run = run;
59
58
  this.#onFailure = onFailure;
60
- this.#requiresAcceptedStop = requiresAcceptedStop;
61
59
  }
62
60
  get hasPending() {
63
61
  // Stop prevents new delivery, but accepted and failing invocations still
64
62
  // belong to the root lifecycle until they settle. Hiding those active runs
65
- // here lets finalization report a later missing-Stop error instead of the
66
- // actual child failure.
63
+ // here would let a later completion resolve the Stop boundary before the
64
+ // actual child failure is observed.
67
65
  return this.#activeRuns.size > 0 || (!this.#stopped && (this.#queue.length > 0 || this.#timer != null));
68
66
  }
69
67
  get isAwaitingProducer() {
@@ -80,6 +78,19 @@ export class StreamingOutputWatch {
80
78
  get isSettled() {
81
79
  return !this.hasPending && (this.#stopped || this.#failure != null || this.#producerFinished);
82
80
  }
81
+ /**
82
+ * The producer delivered its final snapshot and every scheduled invocation
83
+ * settled without cancellation or failure. The scheduler deliberately does
84
+ * not infer graph topology; GraphProcessor decides whether this means a
85
+ * parent Stop must be excluded.
86
+ */
87
+ get finishedNormally() {
88
+ return (!this.#stopped &&
89
+ this.#failure == null &&
90
+ this.#producerFinished &&
91
+ this.#finalSnapshotSettled &&
92
+ !this.hasPending);
93
+ }
83
94
  get runtimeSummary() {
84
95
  return {
85
96
  receivedUpdates: this.#receivedUpdates,
@@ -89,14 +100,6 @@ export class StreamingOutputWatch {
89
100
  ...(this.#failureKind === undefined ? {} : { failureKind: this.#failureKind }),
90
101
  };
91
102
  }
92
- /**
93
- * A Stop boundary can enqueue ordinary parent-graph work when its node
94
- * completes. Until it settles, its result is not safe to expose
95
- * through the foreground-output boundary.
96
- */
97
- get canAffectForegroundOutputs() {
98
- return this.#requiresAcceptedStop;
99
- }
100
103
  publish(snapshot) {
101
104
  // A producer's terminal snapshot closes its partial stream. Ignore a
102
105
  // misbehaving late callback rather than scheduling work after a final
@@ -157,9 +160,6 @@ export class StreamingOutputWatch {
157
160
  }
158
161
  await Promise.all([...this.#activeRuns].map((run) => run.promise));
159
162
  }
160
- if (this.#producerFinished && this.#finalSnapshotSettled && !this.#stopped && this.#requiresAcceptedStop) {
161
- this.#fail(new Error('The watched streaming output completed before Stop Watching Streaming Output accepted a value.'), 'missing-stop');
162
- }
163
163
  }
164
164
  #scheduleInterval() {
165
165
  if (this.#timer != null) {
@@ -147,6 +147,7 @@ export class StreamingOutputWatchHistory {
147
147
  selectedIteration: selected == null
148
148
  ? undefined
149
149
  : {
150
+ graphRunId: selected.graphRunId,
150
151
  updateIndex: selected.updateIndex,
151
152
  reason: selected === this.#firstFailure ? 'failure' : selected === this.#stopWinner ? 'stop' : 'latest',
152
153
  },
@@ -1,3 +1,4 @@
1
+ export const STREAM_RESPONSE_HELPER_MESSAGE = 'Shows streamed response updates in the editor, including direct consumer previews. Ordinary consumers run after the final response; Watch Streaming Output branches can run during streaming.';
1
2
  export function createChatV2CommonNodeData(overrides = {}) {
2
3
  return {
3
4
  model: 'gpt-4o',
@@ -271,7 +272,7 @@ export function getCommonChatV2Editors(modelOptions) {
271
272
  type: 'toggle',
272
273
  label: 'Stream response',
273
274
  dataKey: 'useAsGraphPartialOutput',
274
- helperMessage: 'Shows streamed response updates in the node output while running in the editor. Other nodes only receive the final response after it is complete.',
275
+ helperMessage: STREAM_RESPONSE_HELPER_MESSAGE,
275
276
  },
276
277
  ],
277
278
  },
@@ -1,3 +1,4 @@
1
+ import { STREAM_RESPONSE_HELPER_MESSAGE } from './chatV2Shared.js';
1
2
  import { DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_COOLDOWN_MS, DEFAULT_LLM_CHAT_V2_RETRY_ON_NON_200_REPEAT_TIMES, } from './chatV2Retry.js';
2
3
  import { anthropicCacheControlTtlOptions, anthropicEffortOptions, anthropicThinkingModeOptions, chatV2ProviderOptions, customProviderApiOptions, getChatV2ModelOptions, googleThinkingLevelOptions, openAIReasoningEffortOptions, openAIWebSearchContextSizeOptions, } from './providerOptions.js';
3
4
  import { LLM_CHAT_V2_PARALLEL_TOOL_CALLS_HELPER_MESSAGE, supportsLLMChatV2ParallelToolCalls, } from './parallelToolCalls.js';
@@ -417,7 +418,7 @@ function getResponseSettingsEditors() {
417
418
  type: 'toggle',
418
419
  label: 'Stream response',
419
420
  dataKey: 'useAsGraphPartialOutput',
420
- helperMessage: 'Shows streamed response updates in the node output while running in the editor. Other nodes only receive the final response after it is complete.',
421
+ helperMessage: STREAM_RESPONSE_HELPER_MESSAGE,
421
422
  },
422
423
  {
423
424
  type: 'string',
@@ -7,11 +7,13 @@ import { dedent } from 'ts-dedent';
7
7
  import { nodeDefinition } from '../NodeDefinition.js';
8
8
  import { ChatNodeBase } from './ChatNodeBase.js';
9
9
  import { coerceType } from '../../utils/coerceType.js';
10
+ /** Display-only label; the persisted node type remains the stable `chatLoop`. */
11
+ export const chatLoopLegacyDisplayName = 'Chat Loop (legacy)';
10
12
  export class ChatLoopNodeImpl extends NodeImpl {
11
13
  static create() {
12
14
  const chartNode = {
13
15
  type: 'chatLoop',
14
- title: 'Chat Loop',
16
+ title: chatLoopLegacyDisplayName,
15
17
  id: nanoid(),
16
18
  visualData: {
17
19
  x: 0,
@@ -54,8 +56,8 @@ export class ChatLoopNodeImpl extends NodeImpl {
54
56
 
55
57
  The conversation history is maintained and sent with each new message.
56
58
  `,
57
- contextMenuTitle: 'Chat Loop',
58
- infoBoxTitle: 'Chat Loop Node',
59
+ contextMenuTitle: chatLoopLegacyDisplayName,
60
+ infoBoxTitle: `${chatLoopLegacyDisplayName} Node`,
59
61
  group: ['Convenience'],
60
62
  };
61
63
  }
@@ -147,4 +149,6 @@ export class ChatLoopNodeImpl extends NodeImpl {
147
149
  };
148
150
  }
149
151
  }
150
- export const chatLoopNode = nodeDefinition(ChatLoopNodeImpl, 'Chat Loop');
152
+ // The persisted `chatLoop` type is intentionally unchanged: the legacy
153
+ // marker is display-only, so projects saved before this rename still load.
154
+ export const chatLoopNode = nodeDefinition(ChatLoopNodeImpl, chatLoopLegacyDisplayName);
@@ -10,8 +10,7 @@ import { resolveAdditionalHeaders, resolveAdditionalParameters, resolveAudioAndM
10
10
  import { coercePromptToChatMessages, prependSystemPrompt } from '../chat/chatMessages.js';
11
11
  import { clampMaxTokensToModelLimit } from '../chat/tokenBudget.js';
12
12
  import { applyOpenAINonStreamingResponse, applyOpenAIStreamingResponse, handleOpenAIRetryableFailure, } from '../chat/openAIChatRuntime.js';
13
- // Temporary
14
- const cache = new Map();
13
+ import { resolveLegacyChatEditorCache, writeLegacyChatEditorCache } from '../LegacyChatEditorCache.js';
15
14
  export const ChatNodeBase = {
16
15
  defaultData: () => ({
17
16
  model: 'gpt-5',
@@ -652,9 +651,9 @@ export const ChatNodeBase = {
652
651
  },
653
652
  {
654
653
  type: 'toggle',
655
- label: 'Cache In Rivet',
654
+ label: 'Cache outputs (editor only)',
656
655
  dataKey: 'cache',
657
- helperMessage: 'If on, requests with the same parameters and messages will be cached in Rivet, for immediate responses without an API call.',
656
+ helperMessage: 'Reuses a matching ordinary chat response while this project remains open. Tool-capable requests always run normally.',
658
657
  },
659
658
  {
660
659
  type: 'toggle',
@@ -816,13 +815,19 @@ export const ChatNodeBase = {
816
815
  options.temperature = useTopP ? undefined : temperature; // Not supported in o1-preview
817
816
  options.max_tokens = maxTokens;
818
817
  }
819
- const cacheKey = JSON.stringify(options);
820
- if (data.cache) {
821
- const cached = cache.get(cacheKey);
822
- if (cached) {
823
- context.markResultAsEditorCacheHit?.();
824
- return cached;
825
- }
818
+ const { cache, cachedOutputs } = resolveLegacyChatEditorCache({
819
+ context,
820
+ enabled: data.cache && !data.enableFunctionUse,
821
+ providerIdentity: {
822
+ apiKey: context.settings.openAiKey ?? '',
823
+ organization: context.settings.openAiOrganization,
824
+ headers: allAdditionalHeaders,
825
+ },
826
+ request: options,
827
+ });
828
+ if (cachedOutputs != null) {
829
+ context.markResultAsEditorCacheHit?.();
830
+ return cachedOutputs;
826
831
  }
827
832
  const startTime = Date.now();
828
833
  // Non-streaming APIs
@@ -851,7 +856,7 @@ export const ChatNodeBase = {
851
856
  durationMs: Date.now() - startTime,
852
857
  });
853
858
  Object.freeze(output);
854
- cache.set(cacheKey, output);
859
+ writeLegacyChatEditorCache(cache, output);
855
860
  return output;
856
861
  }
857
862
  const chunks = streamChatCompletions({
@@ -883,7 +888,7 @@ export const ChatNodeBase = {
883
888
  });
884
889
  output['duration'] = { type: 'number', value: Date.now() - startTime };
885
890
  Object.freeze(output);
886
- cache.set(cacheKey, output);
891
+ writeLegacyChatEditorCache(cache, output);
887
892
  return output;
888
893
  }, {
889
894
  forever: true,