@valerypopoff/rivet2-core 2.8.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 (32) hide show
  1. package/dist/cjs/bundle.cjs +449 -319
  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 +50 -3
  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/StreamingOutputWatch.js +18 -18
  10. package/dist/esm/model/chat-v2/chatV2Shared.js +2 -1
  11. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +2 -1
  12. package/dist/esm/model/nodes/ChatNodeBase.js +18 -13
  13. package/dist/esm/model/nodes/CoalesceNewNode.js +22 -0
  14. package/dist/esm/model/nodes/CoalesceNode.js +15 -133
  15. package/dist/esm/model/nodes/CoalesceNodeBase.js +131 -0
  16. package/dist/esm/model/nodes/StopWatchingStreamingOutputNode.js +2 -0
  17. package/dist/esm/plugins/anthropic/nodes/ChatAnthropicNode.js +17 -15
  18. package/dist/esm/plugins/google/google.js +8 -128
  19. package/dist/esm/plugins/google/googleGenerativeAi.js +101 -0
  20. package/dist/esm/plugins/google/nodes/ChatGoogleNode.js +36 -15
  21. package/dist/types/model/GraphPreprocessor.d.ts +2 -0
  22. package/dist/types/model/GraphProcessor.d.ts +3 -1
  23. package/dist/types/model/LegacyChatEditorCache.d.ts +39 -0
  24. package/dist/types/model/Nodes.d.ts +3 -2
  25. package/dist/types/model/StreamingOutputWatch.d.ts +13 -11
  26. package/dist/types/model/chat-v2/chatV2Shared.d.ts +1 -0
  27. package/dist/types/model/nodes/CoalesceNewNode.d.ts +10 -0
  28. package/dist/types/model/nodes/CoalesceNode.d.ts +9 -15
  29. package/dist/types/model/nodes/CoalesceNodeBase.d.ts +19 -0
  30. package/dist/types/plugins/google/google.d.ts +3 -110
  31. package/dist/types/plugins/google/googleGenerativeAi.d.ts +110 -0
  32. 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;
@@ -2649,12 +2669,13 @@ export class GraphProcessor {
2649
2669
  nextUpdateIndex: 0,
2650
2670
  history: new StreamingOutputWatchHistory(),
2651
2671
  historySummaryEmitted: false,
2672
+ unmatchedStopResolved: false,
2652
2673
  };
2653
2674
  const plans = this.#streamingWatchPlansBySourceNodeId.get(sourceNode.id) ?? [];
2654
2675
  plans.push(plan);
2655
2676
  this.#streamingWatchPlansBySourceNodeId.set(sourceNode.id, plans);
2656
2677
  this.#streamingWatchPlansByWatchNodeId.set(watchNode.id, plan);
2657
- 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));
2658
2679
  this.#streamingOutputWatches.set(watchNode.id, watch);
2659
2680
  for (const nodeId of [watchNode.id, ...branchNodeIds]) {
2660
2681
  this.#ignoreNodes.add(nodeId);
@@ -3104,7 +3125,10 @@ export class GraphProcessor {
3104
3125
  return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending);
3105
3126
  }
3106
3127
  #hasUnresolvedForegroundOutputStreamingWatch() {
3107
- 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
+ });
3108
3132
  }
3109
3133
  #hasDrainableStreamingOutputWatches() {
3110
3134
  return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
@@ -3127,6 +3151,11 @@ export class GraphProcessor {
3127
3151
  // work after the compatible scheduler has returned, so wait for that work
3128
3152
  // before deciding every Watch boundary is quiet.
3129
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();
3130
3159
  } while (this.#hasDrainableStreamingOutputWatches());
3131
3160
  for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3132
3161
  const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
@@ -3137,6 +3166,20 @@ export class GraphProcessor {
3137
3166
  await this.#emitter.emit('streamingOutputWatchSummary', this.#withExecution({ watchNode: plan.watchNode, summary }));
3138
3167
  }
3139
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
+ }
3140
3183
  #prepareAsyncBranchTopology() {
3141
3184
  const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
3142
3185
  const outgoingByNodeId = new Map();
@@ -3152,6 +3195,10 @@ export class GraphProcessor {
3152
3195
  incomingByNodeId.set(connection.inputNodeId, incoming);
3153
3196
  }
3154
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;
3155
3202
  if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRelevant(triggerNode.id)) {
3156
3203
  continue;
3157
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)
@@ -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) {
@@ -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',
@@ -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,
@@ -0,0 +1,22 @@
1
+ import { dedent } from 'ts-dedent';
2
+ import { nodeDefinition } from '../NodeDefinition.js';
3
+ import {} from '../NodeImpl.js';
4
+ import {} from '../NodeBase.js';
5
+ import { CoalesceNodeBase, createCoalesceNode } from './CoalesceNodeBase.js';
6
+ export class CoalesceNewNodeImpl extends CoalesceNodeBase {
7
+ includesLegacyConditionalInput = false;
8
+ static create = () => createCoalesceNode('coalesceNew', 'Coalesce');
9
+ static getUIData() {
10
+ return {
11
+ infoBoxBody: dedent `
12
+ Takes in any number of inputs and outputs the first value that is not "Not Ran". Useful for consolidating branches after a Match node.
13
+
14
+ Null and undefined input values are emitted by default, but the node can be configured to skip either value and continue checking later inputs.
15
+ `,
16
+ infoBoxTitle: 'Coalesce Node',
17
+ contextMenuTitle: 'Coalesce',
18
+ group: ['Logic'],
19
+ };
20
+ }
21
+ }
22
+ export const coalesceNewNode = nodeDefinition(CoalesceNewNodeImpl, 'Coalesce');
@@ -1,144 +1,26 @@
1
- import { NodeImpl } from '../NodeImpl.js';
2
- import {} from '../NodeBase.js';
3
- import { unwrapDataValue } from '../DataValue.js';
4
- import { nanoid } from 'nanoid/non-secure';
5
- import {} from '../GraphProcessor.js';
6
1
  import { dedent } from 'ts-dedent';
7
2
  import { nodeDefinition } from '../NodeDefinition.js';
8
- import {} from '../EditorDefinition.js';
9
- import { getNextVariadicPortIndex } from './variadicPortIndex.js';
10
- const INPUT_PORT_ID_PATTERN = /^input(\d+)$/;
11
- const IGNORE_NULL_LABEL = "Ignore 'null'";
12
- const IGNORE_UNDEFINED_LABEL = "Ignore 'undefined'";
13
- export class CoalesceNodeImpl extends NodeImpl {
14
- static create = () => {
15
- const chartNode = {
16
- type: 'coalesce',
17
- title: 'Coalesce',
18
- id: nanoid(),
19
- data: {
20
- ignoreNull: false,
21
- ignoreUndefined: false,
22
- },
23
- visualData: {
24
- x: 0,
25
- y: 0,
26
- width: 190,
27
- },
28
- };
29
- return chartNode;
30
- };
31
- getInputDefinitions(connections) {
32
- const inputs = [];
33
- const inputCount = getNextVariadicPortIndex(connections, this.chartNode.id, 'input', 'strict-positive');
34
- inputs.push({
35
- dataType: 'boolean',
36
- id: 'conditional',
37
- title: 'Conditional',
38
- });
39
- for (let i = 1; i <= inputCount; i++) {
40
- inputs.push({
41
- dataType: 'any',
42
- id: `input${i}`,
43
- title: `Input ${i}`,
44
- });
45
- }
46
- return inputs;
47
- }
48
- getOutputDefinitions() {
49
- return [
50
- {
51
- dataType: 'any',
52
- id: 'output',
53
- title: 'Output',
54
- },
55
- ];
56
- }
57
- getEditors() {
58
- return [
59
- {
60
- type: 'toggle',
61
- label: IGNORE_NULL_LABEL,
62
- dataKey: 'ignoreNull',
63
- },
64
- {
65
- type: 'toggle',
66
- label: IGNORE_UNDEFINED_LABEL,
67
- dataKey: 'ignoreUndefined',
68
- },
69
- ];
70
- }
71
- getBody() {
72
- const ignoredValues = [];
73
- if (this.data.ignoreNull) {
74
- ignoredValues.push(IGNORE_NULL_LABEL);
75
- }
76
- if (this.data.ignoreUndefined) {
77
- ignoredValues.push(IGNORE_UNDEFINED_LABEL);
78
- }
79
- return ignoredValues.length > 0 ? ignoredValues.join('\n') : undefined;
80
- }
3
+ import {} from '../NodeImpl.js';
4
+ import {} from '../NodeBase.js';
5
+ import { CoalesceNodeBase, createCoalesceNode } from './CoalesceNodeBase.js';
6
+ /** Display-only label; the persisted node type remains the stable `coalesce`. */
7
+ export const coalesceLegacyDisplayName = 'Coalesce (legacy)';
8
+ /** The persisted `coalesce` type remains available for existing graphs. */
9
+ export class CoalesceNodeImpl extends CoalesceNodeBase {
10
+ includesLegacyConditionalInput = true;
11
+ static create = () => createCoalesceNode('coalesce', coalesceLegacyDisplayName);
81
12
  static getUIData() {
82
13
  return {
83
14
  infoBoxBody: dedent `
84
- Takes in any number of inputs and outputs the first value that is not "Not Ran". Useful for consolidating branches after a Match node.
15
+ Legacy Coalesce node. Takes in any number of inputs and outputs the first value that is not "Not Ran". Useful for consolidating branches after a Match node.
85
16
 
86
- Null and undefined input values are emitted by default, but the node can be configured to skip either value and continue checking later inputs.
17
+ Its Conditional input can exclude the node itself. New graphs should use Coalesce instead, which has the same fallback behavior without that port.
87
18
  `,
88
- infoBoxTitle: 'Coalesce Node',
89
- contextMenuTitle: 'Coalesce',
19
+ infoBoxTitle: `${coalesceLegacyDisplayName} Node`,
20
+ contextMenuTitle: coalesceLegacyDisplayName,
90
21
  group: ['Logic'],
91
22
  };
92
23
  }
93
- async process(inputData) {
94
- const conditional = inputData['conditional'];
95
- // This lets the coalesce actually be control-flow-excluded itself, because otherwise
96
- // the input control-flow-excluded are consumed.
97
- if (conditional?.type === 'control-flow-excluded') {
98
- return {
99
- ['output']: {
100
- type: 'control-flow-excluded',
101
- value: undefined,
102
- },
103
- };
104
- }
105
- const inputCount = this.#getInputCountFromValues(inputData);
106
- for (let i = 1; i <= inputCount; i++) {
107
- const inputValue = inputData[`input${i}`];
108
- if (inputValue && inputValue.type !== 'control-flow-excluded' && !this.#shouldSkipInputValue(inputValue)) {
109
- return {
110
- ['output']: inputValue,
111
- };
112
- }
113
- }
114
- return {
115
- ['output']: {
116
- type: 'control-flow-excluded',
117
- value: undefined,
118
- },
119
- };
120
- }
121
- #getInputCountFromValues(inputData) {
122
- let maxInputNumber = 0;
123
- for (const inputId of Object.keys(inputData)) {
124
- const inputNumber = this.#getInputPortNumber(inputId);
125
- if (inputNumber && inputNumber > maxInputNumber) {
126
- maxInputNumber = inputNumber;
127
- }
128
- }
129
- return maxInputNumber;
130
- }
131
- #getInputPortNumber(inputId) {
132
- const match = INPUT_PORT_ID_PATTERN.exec(inputId);
133
- if (!match) {
134
- return undefined;
135
- }
136
- const inputNumber = Number(match[1]);
137
- return Number.isSafeInteger(inputNumber) && inputNumber > 0 ? inputNumber : undefined;
138
- }
139
- #shouldSkipInputValue(inputValue) {
140
- const value = unwrapDataValue(inputValue).value;
141
- return ((this.data.ignoreNull === true && value === null) || (this.data.ignoreUndefined === true && value === undefined));
142
- }
143
24
  }
144
- export const coalesceNode = nodeDefinition(CoalesceNodeImpl, 'Coalesce');
25
+ export {} from './CoalesceNodeBase.js';
26
+ export const coalesceNode = nodeDefinition(CoalesceNodeImpl, coalesceLegacyDisplayName);