@valerypopoff/rivet2-core 2.4.0 → 2.5.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 (61) hide show
  1. package/dist/cjs/bundle.cjs +1430 -669
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +1578 -0
  4. package/dist/cjs/interpolationRuntime.cjs.map +7 -0
  5. package/dist/cjs/interpolationSyntax.cjs +186 -0
  6. package/dist/cjs/interpolationSyntax.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs.map +2 -2
  8. package/dist/esm/exports.js +2 -1
  9. package/dist/esm/integrations/CodeRunner.js +5 -0
  10. package/dist/esm/integrations/mcp/MCPBase.js +16 -6
  11. package/dist/esm/interpolationRuntime.js +5 -0
  12. package/dist/esm/model/GraphBoundaryCache.js +0 -6
  13. package/dist/esm/model/GraphBoundaryEffects.js +5 -1
  14. package/dist/esm/model/GraphOutputSelection.js +34 -0
  15. package/dist/esm/model/GraphProcessor.js +136 -44
  16. package/dist/esm/model/ProcessContextBuilder.js +2 -0
  17. package/dist/esm/model/RecordingPlayer.js +11 -6
  18. package/dist/esm/model/StoredValueStore.js +4 -3
  19. package/dist/esm/model/nodes/CodeNewNode.js +16 -16
  20. package/dist/esm/model/nodes/DestructureNode.js +2 -2
  21. package/dist/esm/model/nodes/ExpressionNode.js +16 -16
  22. package/dist/esm/model/nodes/ExtractObjectPathNode.js +2 -2
  23. package/dist/esm/model/nodes/ExtractYamlNode.js +5 -5
  24. package/dist/esm/model/nodes/JSFilterNode.js +3 -1
  25. package/dist/esm/model/nodes/JSMapNode.js +3 -1
  26. package/dist/esm/model/nodes/MCPGetPromptNode.js +6 -2
  27. package/dist/esm/model/nodes/MCPToolCallNode.js +6 -2
  28. package/dist/esm/model/nodes/ObjectNode.js +19 -20
  29. package/dist/esm/model/nodes/PromptNode.js +10 -11
  30. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +2 -40
  31. package/dist/esm/model/nodes/SubGraphNode.js +40 -26
  32. package/dist/esm/model/nodes/TextNode.js +11 -32
  33. package/dist/esm/model/nodes/ToTreeNode.js +6 -13
  34. package/dist/esm/model/nodes/ToolNode.js +33 -16
  35. package/dist/esm/model/nodes/jsListCallbackHelpers.js +19 -15
  36. package/dist/esm/model/nodes/jsValueInterpolation.js +83 -30
  37. package/dist/esm/model/nodes/nodeBodyPreview.js +23 -0
  38. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +14 -11
  39. package/dist/esm/utils/index.js +2 -0
  40. package/dist/esm/utils/interpolation.js +478 -221
  41. package/dist/esm/utils/interpolationSyntax.js +175 -0
  42. package/dist/esm/utils/jsonPath.js +129 -0
  43. package/dist/types/exports.d.ts +3 -1
  44. package/dist/types/integrations/CodeRunnerOptions.d.ts +9 -0
  45. package/dist/types/integrations/mcp/MCPBase.d.ts +3 -1
  46. package/dist/types/interpolationRuntime.d.ts +5 -0
  47. package/dist/types/model/GraphBoundaryCache.d.ts +0 -2
  48. package/dist/types/model/GraphOutputSelection.d.ts +8 -0
  49. package/dist/types/model/GraphProcessor.d.ts +4 -3
  50. package/dist/types/model/ProcessContext.d.ts +3 -2
  51. package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
  52. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  53. package/dist/types/model/nodes/ToTreeNode.d.ts +5 -2
  54. package/dist/types/model/nodes/ToolNode.d.ts +13 -1
  55. package/dist/types/model/nodes/jsValueInterpolation.d.ts +16 -8
  56. package/dist/types/model/nodes/nodeBodyPreview.d.ts +7 -0
  57. package/dist/types/utils/index.d.ts +2 -0
  58. package/dist/types/utils/interpolation.d.ts +93 -8
  59. package/dist/types/utils/interpolationSyntax.d.ts +21 -0
  60. package/dist/types/utils/jsonPath.d.ts +15 -0
  61. package/package.json +11 -1
@@ -66,7 +66,8 @@ export * from './integrations/Tokenizer.js';
66
66
  export * from './integrations/GptTokenizerTokenizer.js';
67
67
  export { JS_LIST_CALLBACK_LOCAL_NAMES, interpolateJSListCallbackBody } from './model/nodes/jsListCallbackHelpers.js';
68
68
  export { findAutoDelegateGraphCandidate } from './model/nodes/toolCallDelegation.js';
69
- export { extractInterpolationVariables, findInterpolationTokenSpans, getInterpolationTokenName, interpolate, protectEscapedInterpolationTokens, restoreEscapedInterpolationTokens, } from './utils/interpolation.js';
69
+ export { extractInterpolationVariables, extractInterpolationVariableReferences, findInterpolationTokenSpans, getInterpolationTokenReference, getInterpolationTokenName, interpolate, parseInterpolationExpression, parseInterpolationTemplate, protectEscapedInterpolationTokens, resolveCodeInterpolationExpression, resolveInterpolationExpressionRawValue, resolveInterpolationTokenRawValue, restoreEscapedInterpolationTokens, stringifyInterpolationSourceValue, } from './utils/interpolation.js';
70
+ export { scanInterpolationTokenSpans } from './utils/interpolationSyntax.js';
70
71
  export { WarningsPort } from './utils/symbols.js';
71
72
  import * as openai from './utils/openai.js';
72
73
  export { openai };
@@ -1,3 +1,4 @@
1
+ import { resolveCodeInterpolationExpression } from '../utils/interpolation.js';
1
2
  // eslint-disable-next-line import/no-cycle -- Authored code receives the complete public Rivet namespace at execution time.
2
3
  import * as Rivet from '../exports.js';
3
4
  export { ALL_CODE_RUNNER_OPTIONS } from './CodeRunnerOptions.js';
@@ -25,6 +26,10 @@ export class IsomorphicCodeRunner {
25
26
  argNames.push('context');
26
27
  args.push(contextValues);
27
28
  }
29
+ if (options.interpolationHelperIdentifier) {
30
+ argNames.push(options.interpolationHelperIdentifier);
31
+ args.push(resolveCodeInterpolationExpression);
32
+ }
28
33
  argNames.push(code);
29
34
  const AsyncFunction = async function () { }.constructor;
30
35
  const codeFunction = new AsyncFunction(...argNames);
@@ -1,6 +1,6 @@
1
- import { coerceTypeOptional } from '../../utils/coerceType.js';
1
+ import { createInterpolationInputDefinition } from '../../model/interpolationInputDefinition.js';
2
2
  import { getInputOrData } from '../../utils/inputs.js';
3
- import { interpolate } from '../../utils/interpolation.js';
3
+ import { extractInterpolationVariables, interpolate } from '../../utils/interpolation.js';
4
4
  import { keys } from '../../utils/typeSafety.js';
5
5
  import { MCPError, MCPErrorType } from './MCPProvider.js';
6
6
  import { getServerHelperMessage, getServerOptions, loadMCPConfiguration } from './MCPUtils.js';
@@ -134,12 +134,22 @@ export async function resolveMCPServer(data, inputs, context) {
134
134
  }
135
135
  return undefined;
136
136
  }
137
- export function interpolateMCPArgumentTemplate(template, inputs) {
137
+ export function interpolateMCPArgumentTemplate(template, inputs, graphInputValues, contextValues) {
138
138
  const values = {};
139
139
  for (const key of keys(inputs)) {
140
- if (key.startsWith('input')) {
141
- values[key.slice('input-'.length)] = coerceTypeOptional(inputs[key], 'string') ?? '';
140
+ if (key.startsWith('input-')) {
141
+ values[key.slice('input-'.length)] = inputs[key];
142
142
  }
143
143
  }
144
- return interpolate(template, values);
144
+ return interpolate(template, values, graphInputValues, contextValues, {
145
+ coerceBareVariableDataValues: true,
146
+ });
147
+ }
148
+ export function getMCPArgumentTemplateInputs(template) {
149
+ return extractInterpolationVariables(template ?? '').map((interpolationName) => createInterpolationInputDefinition({
150
+ id: `input-${interpolationName}`,
151
+ interpolationName,
152
+ dataType: 'any',
153
+ required: false,
154
+ }));
145
155
  }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Narrow runtime entrypoint for JavaScript executors. Build tooling can bundle
3
+ * this module into isolated workers without exposing the complete Core API.
4
+ */
5
+ export { resolveCodeInterpolationExpression } from './utils/interpolation.js';
@@ -1,4 +1,3 @@
1
- export const GRAPH_BOUNDARY_OUTPUT_DEMAND_OPTIMIZATION_ENABLED = false;
2
1
  export function getGraphBoundary(project, graphId, cache) {
3
2
  if (!graphId) {
4
3
  return undefined;
@@ -82,11 +81,6 @@ export function buildExcludedGraphBoundaryOutputs(boundary) {
82
81
  }
83
82
  return outputs;
84
83
  }
85
- export function getRequestedGraphOutputNodeIds(boundary, requestedOutputPortIds) {
86
- return boundary.outputs
87
- .filter((output) => requestedOutputPortIds.has(output.portId))
88
- .map((output) => output.nodeId);
89
- }
90
84
  function deriveGraphBoundary(graph) {
91
85
  const inputsById = new Map();
92
86
  const outputsById = new Map();
@@ -11,7 +11,11 @@ export function applyFrozenGraphBoundaryEffects(graphOutputs, node, outputValues
11
11
  if (node.type === 'graphOutput') {
12
12
  const outputId = node.data?.id;
13
13
  const valueOutput = outputValues['valueOutput'];
14
- if (outputId && valueOutput) {
14
+ // Duplicate Graph Outputs share the ordinary first-non-excluded winner,
15
+ // whether a producer is computed or replayed from frozen outputs.
16
+ if (outputId &&
17
+ valueOutput &&
18
+ (graphOutputs[outputId] == null || graphOutputs[outputId]?.type === 'control-flow-excluded')) {
15
19
  graphOutputs[outputId] = valueOutput;
16
20
  }
17
21
  return undefined;
@@ -0,0 +1,34 @@
1
+ import { resolveToolContinuationConnections } from './chat-v2/toolContinuationConnection.js';
2
+ /** Invocation-local selection over compiled topology, never a mutation of the reusable graph plan. */
3
+ export function createGraphOutputSelection(graph, requestedOutputIds, getInputNodes) {
4
+ const requestedIds = new Set(requestedOutputIds);
5
+ const missingIds = new Set(requestedIds);
6
+ const startNodes = graph.nodes.filter((node) => {
7
+ if (node.type !== 'graphOutput')
8
+ return false;
9
+ const outputId = node.data.id;
10
+ missingIds.delete(outputId);
11
+ return requestedIds.has(outputId);
12
+ });
13
+ if (missingIds.size > 0) {
14
+ throw new Error(`Unknown requested graph output IDs: ${[...missingIds].map((id) => JSON.stringify(id)).join(', ')}`);
15
+ }
16
+ const continuations = resolveToolContinuationConnections(graph);
17
+ const nodeIds = new Set();
18
+ const pendingNodes = [...startNodes];
19
+ for (let index = 0; index < pendingNodes.length; index++) {
20
+ const node = pendingNodes[index];
21
+ if (nodeIds.has(node.id))
22
+ continue;
23
+ nodeIds.add(node.id);
24
+ // Include every scheduler prerequisite, even if only the first provider supplies an input value.
25
+ pendingNodes.push(...getInputNodes(node));
26
+ const continuation = continuations.get(node.id);
27
+ if (continuation?.kind === 'connected') {
28
+ // A connected Delegate is part of the LLM computation despite the forward-facing wire.
29
+ pendingNodes.push(continuation.delegateNode);
30
+ }
31
+ // Ambiguous continuations retain their existing node-execution error; never choose a winner here.
32
+ }
33
+ return { startNodes, nodeIds };
34
+ }
@@ -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 { createGraphOutputSelection } from './GraphOutputSelection.js';
12
13
  import { applyFrozenGraphBoundaryEffects, ensureGraphCostOutput } from './GraphBoundaryEffects.js';
13
14
  import { replayExecutionRecording } from './RecordingPlayer.js';
14
15
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
@@ -213,6 +214,7 @@ export class GraphProcessor {
213
214
  #graphExecutionPlan;
214
215
  #nodeProcessContextBase = undefined;
215
216
  #runToRelevantNodeIds;
217
+ #graphOutputSelection;
216
218
  #managedAsyncBranches;
217
219
  #managedAsyncBranchFailures = [];
218
220
  #runCompletionPromise;
@@ -444,7 +446,6 @@ export class GraphProcessor {
444
446
  const pending = this.#pendingUserInputs[nodeId];
445
447
  if (pending) {
446
448
  pending.resolve(values);
447
- delete this.#pendingUserInputs[nodeId];
448
449
  }
449
450
  for (const processor of this.#subprocessors) {
450
451
  processor.userInput(nodeId, values);
@@ -547,7 +548,7 @@ export class GraphProcessor {
547
548
  this.#hasPreloadedData = true;
548
549
  // Preserve the historical ability to preload an idle processor as well as
549
550
  // inject a boundary into a run that has already initialized.
550
- if (this.#lifecycle.isRunning) {
551
+ if (this.#lifecycle.isRunning && this.#isNodeSelected(nodeId)) {
551
552
  this.#nodeResults.set(nodeId, data);
552
553
  this.#visitedNodes.add(nodeId);
553
554
  }
@@ -597,13 +598,16 @@ export class GraphProcessor {
597
598
  }
598
599
  }
599
600
  async replayRecording(recorder) {
601
+ if (this.#lifecycle.isRunning) {
602
+ throw new Error('Cannot process graph while already processing');
603
+ }
600
604
  // Playback is a new root run, even though its node/graph events originate
601
605
  // from a historic recording. Giving the processor a real identity here is
602
606
  // essential if the user aborts while playback is in progress: abort()
603
607
  // emits its own graph terminal outside RecordingPlayer's event adapter.
604
608
  this.#initializeExecutionIdentity();
605
609
  this.#initProcessState();
606
- this.#graphOutputs = await replayExecutionRecording({
610
+ return await replayExecutionRecording({
607
611
  emitter: this.#emitter,
608
612
  erroredNodes: this.#erroredNodes,
609
613
  graphInputs: this.#graphInputs,
@@ -631,7 +635,6 @@ export class GraphProcessor {
631
635
  visitedNodes: this.#visitedNodes,
632
636
  waitUntilUnpaused: () => this.#waitUntilUnpaused(),
633
637
  });
634
- return this.#graphOutputs;
635
638
  }
636
639
  #initProcessState() {
637
640
  this.#lifecycle.begin();
@@ -665,6 +668,7 @@ export class GraphProcessor {
665
668
  this.#ignoreNodes = new Set();
666
669
  this.#nodeProcessContextBase = undefined;
667
670
  this.#runToRelevantNodeIds = undefined;
671
+ this.#graphOutputSelection = undefined;
668
672
  if (!this.#isSubProcessor) {
669
673
  this.#managedAsyncBranches = new ManagedAsyncBranches();
670
674
  this.#managedAsyncBranchFailures = [];
@@ -690,12 +694,11 @@ export class GraphProcessor {
690
694
  /** Inputs to the main graph. You should pass all inputs required by the GraphInputNodes of the graph. */
691
695
  inputs = {},
692
696
  /** Contextual data available to all graphs and subgraphs. Kind of like react context, avoids drilling down data into subgraphs. Be careful when using it. */
693
- contextValues = {},
694
- /** Allows callers such as web apps to receive root outputs while managed async branches continue settling. */
695
- options = {}) {
697
+ contextValues = {}, options = {}) {
696
698
  if (this.#lifecycle.isRunning) {
697
699
  throw new Error('Cannot process graph while already processing');
698
700
  }
701
+ const requestedGraphOutputIds = options.requestedGraphOutputIds?.slice();
699
702
  let resolveOutputsReady;
700
703
  let rejectOutputsReady;
701
704
  const outputsReadyPromise = options.returnWhenGraphOutputsReady === true
@@ -717,6 +720,18 @@ export class GraphProcessor {
717
720
  this.#preprocessGraph();
718
721
  }
719
722
  this.#assertNoDataBusRunTargets();
723
+ if (requestedGraphOutputIds !== undefined) {
724
+ if (this.runToNodeIds !== undefined) {
725
+ throw new Error('requestedGraphOutputIds cannot be combined with runToNodeIds');
726
+ }
727
+ this.#graphOutputSelection = createGraphOutputSelection({ nodes: this.#executionGraphNodes, connections: this.#getEffectiveConnections() }, requestedGraphOutputIds, (node) => getInputNodesTo(this.#executionState, node));
728
+ for (const nodeId of this.#nodeResults.keys()) {
729
+ if (!this.#isNodeSelected(nodeId)) {
730
+ this.#nodeResults.delete(nodeId);
731
+ this.#visitedNodes.delete(nodeId);
732
+ }
733
+ }
734
+ }
720
735
  this.#prepareAsyncBranchTopology();
721
736
  }
722
737
  catch (error) {
@@ -898,12 +913,31 @@ export class GraphProcessor {
898
913
  this.#emitTraceEvent(message);
899
914
  },
900
915
  setStoredValue: (key, value) => this.#storedValueController.set(key, value),
901
- waitForGlobal: async (id) => {
916
+ waitForGlobal: async (id, signal = this.#abortController.signal) => {
917
+ if (signal.aborted) {
918
+ throw createGraphAbortErrorFromSignal(signal);
919
+ }
902
920
  if (this.#globals.has(id)) {
903
921
  return this.#globals.get(id);
904
922
  }
905
- await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
906
- return this.#globals.get(id);
923
+ return await new Promise((resolve, reject) => {
924
+ const abortListener = () => {
925
+ cleanup();
926
+ reject(createGraphAbortErrorFromSignal(signal));
927
+ };
928
+ const unsubscribe = this.getRootProcessor().#emitter.on(`globalSet:${id}`, () => {
929
+ cleanup();
930
+ resolve(this.#globals.get(id));
931
+ });
932
+ const cleanup = () => {
933
+ unsubscribe();
934
+ signal.removeEventListener('abort', abortListener);
935
+ };
936
+ signal.addEventListener('abort', abortListener, { once: true });
937
+ if (signal.aborted) {
938
+ abortListener();
939
+ }
940
+ });
907
941
  },
908
942
  waitForStoredValue: (key, signal) => this.#storedValueController.waitForSet(key, signal),
909
943
  };
@@ -937,7 +971,7 @@ export class GraphProcessor {
937
971
  return;
938
972
  }
939
973
  for (const node of this.#executionGraphNodes) {
940
- if (!this.#nodeResults.has(node.id)) {
974
+ if (!this.#isNodeSelected(node.id) || !this.#nodeResults.has(node.id)) {
941
975
  continue;
942
976
  }
943
977
  if (this.#suppressedPreloadedNodeIds.has(node.id)) {
@@ -966,7 +1000,8 @@ export class GraphProcessor {
966
1000
  }
967
1001
  }
968
1002
  async #processCompatibleGraph() {
969
- await this.#queueStartNodes(getStartNodes(this.#executionState, this.#executionGraphNodes, this.runToNodeIds));
1003
+ await this.#queueStartNodes(this.#graphOutputSelection?.startNodes ??
1004
+ getStartNodes(this.#executionState, this.#executionGraphNodes, this.runToNodeIds));
970
1005
  await this.#processingQueue.onIdle();
971
1006
  this.#markUnqueuedNodesIgnored();
972
1007
  }
@@ -974,7 +1009,11 @@ export class GraphProcessor {
974
1009
  if (this.#scheduler !== 'fast-acyclic') {
975
1010
  return false;
976
1011
  }
977
- if (this.#hasPreloadedData || this.runToNodeIds || this.slowMode || this.#includeTrace) {
1012
+ if (this.#graphOutputSelection ||
1013
+ this.#hasPreloadedData ||
1014
+ this.runToNodeIds ||
1015
+ this.slowMode ||
1016
+ this.#includeTrace) {
978
1017
  return false;
979
1018
  }
980
1019
  if (this.#nodesNotInCycle.length !== this.#executionGraphNodes.length) {
@@ -1177,6 +1216,8 @@ export class GraphProcessor {
1177
1216
  }
1178
1217
  }
1179
1218
  async #fetchNodeDataAndProcessNode(node) {
1219
+ if (!this.#isNodeSelected(node.id))
1220
+ return;
1180
1221
  const profileStart = this.#startRuntimeProfile();
1181
1222
  try {
1182
1223
  if (this.#currentlyProcessing.has(node.id)) {
@@ -1228,6 +1269,8 @@ export class GraphProcessor {
1228
1269
  }
1229
1270
  /** If all inputs are present, all conditions met, processes the node. */
1230
1271
  async #processNodeIfAllInputsAvailable(node, options = {}) {
1272
+ if (!this.#isNodeSelected(node.id))
1273
+ return [];
1231
1274
  const { queueOutputNodes = true } = options;
1232
1275
  const builtInNode = node;
1233
1276
  const inputNodesProfileStart = this.#startRuntimeProfile();
@@ -1458,7 +1501,10 @@ export class GraphProcessor {
1458
1501
  }
1459
1502
  }
1460
1503
  #queueOutputNodes(node, outputNodes) {
1461
- void this.#processingQueue.addAll(outputNodes.map((outputNode) => async () => {
1504
+ const selectedOutputs = this.#graphOutputSelection
1505
+ ? outputNodes.filter((outputNode) => this.#isNodeSelected(outputNode.id))
1506
+ : outputNodes;
1507
+ void this.#processingQueue.addAll(selectedOutputs.map((outputNode) => async () => {
1462
1508
  this.#emitTraceEvent(`Trying to run output node from ${node.title}: ${outputNode.title} (${outputNode.id})`);
1463
1509
  await this.#processNodeIfAllInputsAvailable(outputNode);
1464
1510
  }));
@@ -1856,6 +1902,11 @@ export class GraphProcessor {
1856
1902
  }
1857
1903
  }
1858
1904
  async #processNodeWithInputData(node, inputValues, index, processId, partialOutput, markResultAsEditorCacheHit) {
1905
+ // Split items enter here independently. A race can finish after the caller
1906
+ // started but before a queued item receives its own abort controller.
1907
+ if (this.#shouldSkipCompletedRaceNode(node, this.#getAttachedDataTo(node))) {
1908
+ throw createGraphAbortError(createGraphAbortReason(true, RACE_LOSER_EXCLUSION_REASON));
1909
+ }
1859
1910
  const instance = this.#nodeInstances[node.id];
1860
1911
  const nodeAbortController = this.#newAbortController();
1861
1912
  this.#registerNodeAbortController(node.id, nodeAbortController);
@@ -1873,6 +1924,9 @@ export class GraphProcessor {
1873
1924
  this.#finishRuntimeProfile('createNodeProcessContext', createContextProfileStart);
1874
1925
  }
1875
1926
  await this.#waitUntilUnpaused();
1927
+ if (nodeAbortController.signal.aborted) {
1928
+ throw createGraphAbortErrorFromSignal(nodeAbortController.signal);
1929
+ }
1876
1930
  const implementationProfileStart = this.#startRuntimeProfile();
1877
1931
  let results;
1878
1932
  try {
@@ -1925,7 +1979,7 @@ export class GraphProcessor {
1925
1979
  this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
1926
1980
  },
1927
1981
  processId,
1928
- requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId),
1982
+ requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId, nodeAbortController.signal),
1929
1983
  reportProgress: (progress) => {
1930
1984
  const normalized = normalizeGraphProgress(progress);
1931
1985
  if (normalized) {
@@ -1940,18 +1994,27 @@ export class GraphProcessor {
1940
1994
  toolCallContinuation,
1941
1995
  toolCallTraceSource,
1942
1996
  waitEvent: async (event) => {
1997
+ const signal = nodeAbortController.signal;
1998
+ if (signal.aborted) {
1999
+ throw createGraphAbortErrorFromSignal(signal, 'Process aborted');
2000
+ }
1943
2001
  return new Promise((resolve, reject) => {
1944
2002
  const abortListener = () => {
1945
- reject(createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Process aborted'));
2003
+ cleanup();
2004
+ reject(createGraphAbortErrorFromSignal(signal, 'Process aborted'));
1946
2005
  };
1947
- this.#emitter
1948
- .once(`userEvent:${event}`)
1949
- .then(resolve)
1950
- .catch(reject)
1951
- .finally(() => {
1952
- nodeAbortController.signal.removeEventListener('abort', abortListener);
2006
+ const unsubscribe = this.#emitter.on(`userEvent:${event}`, (data) => {
2007
+ cleanup();
2008
+ resolve(data);
1953
2009
  });
1954
- nodeAbortController.signal.addEventListener('abort', abortListener, { once: true });
2010
+ const cleanup = () => {
2011
+ unsubscribe();
2012
+ signal.removeEventListener('abort', abortListener);
2013
+ };
2014
+ signal.addEventListener('abort', abortListener, { once: true });
2015
+ if (signal.aborted) {
2016
+ abortListener();
2017
+ }
1955
2018
  });
1956
2019
  },
1957
2020
  });
@@ -2207,7 +2270,7 @@ export class GraphProcessor {
2207
2270
  state: {
2208
2271
  erroredNodeIds: new Set(this.#erroredNodes.keys()),
2209
2272
  nodeOutputs: this.#nodeResults,
2210
- runToRelevantNodeIds: this.#getRunToRelevantNodeIds(),
2273
+ runToRelevantNodeIds: this.#getExecutionRelevantNodeIds(),
2211
2274
  visitedNodeIds: this.#visitedNodes,
2212
2275
  },
2213
2276
  });
@@ -2264,8 +2327,8 @@ export class GraphProcessor {
2264
2327
  const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2265
2328
  const outgoingByNodeId = new Map();
2266
2329
  const incomingByNodeId = new Map();
2267
- const runToRelevantNodeIds = this.#getRunToRelevantNodeIds();
2268
- const isRunToRelevant = (nodeId) => !runToRelevantNodeIds || runToRelevantNodeIds.has(nodeId);
2330
+ const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2331
+ const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
2269
2332
  for (const connection of connections) {
2270
2333
  const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
2271
2334
  outgoing.push(connection);
@@ -2275,7 +2338,7 @@ export class GraphProcessor {
2275
2338
  incomingByNodeId.set(connection.inputNodeId, incoming);
2276
2339
  }
2277
2340
  for (const triggerNode of Object.values(this.#nodesById)) {
2278
- if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRunToRelevant(triggerNode.id)) {
2341
+ if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRelevant(triggerNode.id)) {
2279
2342
  continue;
2280
2343
  }
2281
2344
  if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId && this.#nodeResults.has(triggerNode.id)) {
@@ -2284,7 +2347,7 @@ export class GraphProcessor {
2284
2347
  const nodeIds = new Set();
2285
2348
  const pendingNodeIds = (outgoingByNodeId.get(triggerNode.id) ?? [])
2286
2349
  .map((connection) => connection.inputNodeId)
2287
- .filter(isRunToRelevant);
2350
+ .filter(isRelevant);
2288
2351
  while (pendingNodeIds.length > 0) {
2289
2352
  const nodeId = pendingNodeIds.pop();
2290
2353
  if (nodeId === triggerNode.id) {
@@ -2305,7 +2368,7 @@ export class GraphProcessor {
2305
2368
  }
2306
2369
  nodeIds.add(nodeId);
2307
2370
  for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
2308
- if (isRunToRelevant(connection.inputNodeId)) {
2371
+ if (isRelevant(connection.inputNodeId)) {
2309
2372
  pendingNodeIds.push(connection.inputNodeId);
2310
2373
  }
2311
2374
  }
@@ -2404,17 +2467,19 @@ export class GraphProcessor {
2404
2467
  if (outputConnections.length === 0) {
2405
2468
  return new Set();
2406
2469
  }
2407
- const runToRelevantNodeIds = this.#getRunToRelevantNodeIds();
2470
+ const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2408
2471
  const activeOutputPortIds = new Set();
2409
2472
  for (const { node: outputNode, connections } of outputConnections) {
2410
2473
  if (outputNode.disabled) {
2411
2474
  continue;
2412
2475
  }
2413
- if (runToRelevantNodeIds && !runToRelevantNodeIds.has(outputNode.id)) {
2476
+ if (relevantNodeIds && !relevantNodeIds.has(outputNode.id)) {
2414
2477
  continue;
2415
2478
  }
2416
2479
  for (const connection of connections) {
2417
- activeOutputPortIds.add(connection.outputId);
2480
+ if (this.#isDefinitionValidConnection(connection)) {
2481
+ activeOutputPortIds.add(connection.outputId);
2482
+ }
2418
2483
  }
2419
2484
  }
2420
2485
  return activeOutputPortIds;
@@ -2430,6 +2495,15 @@ export class GraphProcessor {
2430
2495
  }
2431
2496
  }
2432
2497
  }
2498
+ #isNodeSelected(nodeId) {
2499
+ return !this.#graphOutputSelection || this.#graphOutputSelection.nodeIds.has(nodeId);
2500
+ }
2501
+ #getExecutionRelevantNodeIds() {
2502
+ if (this.#sameGraphRunOwnerOverride) {
2503
+ return this.#sameGraphRunOwnerOverride.#getExecutionRelevantNodeIds();
2504
+ }
2505
+ return this.#graphOutputSelection?.nodeIds ?? this.#getRunToRelevantNodeIds();
2506
+ }
2433
2507
  #getRunToRelevantNodeIds() {
2434
2508
  if (!this.runToNodeIds) {
2435
2509
  return undefined;
@@ -2551,27 +2625,45 @@ export class GraphProcessor {
2551
2625
  }
2552
2626
  return processor;
2553
2627
  }
2554
- async #requestUserInput(node, inputStrings, inputValues, renderingType, processId) {
2628
+ async #requestUserInput(node, inputStrings, inputValues, renderingType, processId, signal) {
2629
+ if (signal.aborted) {
2630
+ throw createGraphAbortErrorFromSignal(signal);
2631
+ }
2555
2632
  return await new Promise((resolve, reject) => {
2633
+ let settled = false;
2634
+ const cleanup = () => {
2635
+ signal.removeEventListener('abort', abortListener);
2636
+ if (this.#pendingUserInputs[node.id] === pending) {
2637
+ delete this.#pendingUserInputs[node.id];
2638
+ }
2639
+ };
2556
2640
  const abortListener = () => {
2557
- delete this.#pendingUserInputs[node.id];
2558
- reject(createGraphAbortErrorFromSignal(this.#abortController.signal));
2641
+ if (settled)
2642
+ return;
2643
+ settled = true;
2644
+ cleanup();
2645
+ reject(createGraphAbortErrorFromSignal(signal));
2559
2646
  };
2560
- this.#pendingUserInputs[node.id] = {
2561
- resolve,
2562
- reject,
2647
+ const respond = (results) => {
2648
+ if (settled)
2649
+ return;
2650
+ settled = true;
2651
+ cleanup();
2652
+ resolve(results);
2563
2653
  };
2564
- this.#abortController.signal.addEventListener('abort', abortListener, { once: true });
2654
+ const pending = { resolve: respond };
2655
+ this.#pendingUserInputs[node.id] = pending;
2656
+ signal.addEventListener('abort', abortListener, { once: true });
2657
+ if (signal.aborted) {
2658
+ abortListener();
2659
+ return;
2660
+ }
2565
2661
  emitDetached(this.#emitter, 'userInput', this.#withExecution({
2566
2662
  node,
2567
2663
  inputStrings,
2568
2664
  inputs: inputValues,
2569
2665
  renderingType,
2570
- callback: (results) => {
2571
- this.#abortController.signal.removeEventListener('abort', abortListener);
2572
- resolve(results);
2573
- delete this.#pendingUserInputs[node.id];
2574
- },
2666
+ callback: respond,
2575
2667
  processId,
2576
2668
  }));
2577
2669
  });
@@ -8,6 +8,8 @@ export function buildNodeProcessContext(options) {
8
8
  isDirectRunTarget,
9
9
  markResultAsEditorCacheHit,
10
10
  waitEvent,
11
+ waitForGlobal: (id, signal = nodeAbortController.signal) => base.waitForGlobal(id, signal),
12
+ waitForStoredValue: (key, signal = nodeAbortController.signal) => base.waitForStoredValue(key, signal),
11
13
  externalFunctions: { ...externalFunctions },
12
14
  onPartialOutputs,
13
15
  signal: nodeAbortController.signal,
@@ -34,7 +34,8 @@ const REPLAY_TIMED_LIFECYCLE_EVENTS = new Set([
34
34
  'nodeOutputsCleared',
35
35
  ]);
36
36
  export async function replayExecutionRecording(options) {
37
- const { emitter, erroredNodes, graphOutputs, fallbackGraphId, initialReplayExecution, project, recorder, recordingPlaybackChatLatency, setContextValues, setGraphInputs, setGraphOutputs, setRunning, visitedNodes, waitUntilUnpaused, nodeResults, isAborted, } = options;
37
+ const { emitter, erroredNodes, fallbackGraphId, initialReplayExecution, project, recorder, recordingPlaybackChatLatency, setContextValues, setGraphInputs, setGraphOutputs, setRunning, visitedNodes, waitUntilUnpaused, nodeResults, isAborted, } = options;
38
+ let graphOutputs = options.graphOutputs;
38
39
  const nodesByIdAllGraphs = {};
39
40
  const graphIdByNodeId = {};
40
41
  for (const graph of Object.values(project.graphs)) {
@@ -165,13 +166,13 @@ export async function replayExecutionRecording(options) {
165
166
  : nanoid();
166
167
  replayRootRunIds.set(recordedExecution.rootRunId, replayRootRunId);
167
168
  }
168
- const getReplayGraphRunId = (recordedGraphRunId) => {
169
+ const getReplayGraphRunId = (recordedGraphRunId, initialGraphRunId) => {
169
170
  let graphRunIds = replayGraphRunIdsByRoot.get(recordedExecution.rootRunId);
170
171
  if (graphRunIds == null) {
171
172
  graphRunIds = new Map();
172
173
  replayGraphRunIdsByRoot.set(recordedExecution.rootRunId, graphRunIds);
173
174
  }
174
- const replayGraphRunId = graphRunIds.get(recordedGraphRunId) ?? nanoid();
175
+ const replayGraphRunId = initialGraphRunId ?? graphRunIds.get(recordedGraphRunId) ?? nanoid();
175
176
  graphRunIds.set(recordedGraphRunId, replayGraphRunId);
176
177
  return replayGraphRunId;
177
178
  };
@@ -183,7 +184,9 @@ export async function replayExecutionRecording(options) {
183
184
  return {
184
185
  ...rest,
185
186
  rootRunId: replayRootRunId,
186
- graphRunId: isInitialRootGraph ? initialReplayExecution.graphRunId : getReplayGraphRunId(graphRunId),
187
+ // Seed the root mapping too, so child parentGraphRunId references resolve
188
+ // to the same identity already allocated by the playback processor.
189
+ graphRunId: getReplayGraphRunId(graphRunId, isInitialRootGraph ? initialReplayExecution.graphRunId : undefined),
187
190
  ...(parentGraphRunId == null ? {} : { parentGraphRunId: getReplayGraphRunId(parentGraphRunId) }),
188
191
  };
189
192
  };
@@ -234,8 +237,10 @@ export async function replayExecutionRecording(options) {
234
237
  case 'done': {
235
238
  emitFallbackRootTerminal('completed', { outputs: event.data.results });
236
239
  emitReplayTerminalEvent('done', event.data);
237
- setGraphOutputs(event.data.results);
238
- setRunning(false);
240
+ graphOutputs = event.data.results;
241
+ setGraphOutputs(graphOutputs);
242
+ // Keep ownership until playback drains, just like a live graph run.
243
+ // A done listener must not start work that final cleanup could clobber.
239
244
  break;
240
245
  }
241
246
  case 'error': {
@@ -87,10 +87,11 @@ export class RivetStoredValueController {
87
87
  }
88
88
  });
89
89
  });
90
+ // Observe the registered wait before checking cancellation again, or an
91
+ // abort while the key lock releases can orphan its rejected promise.
92
+ const value = waiterPromise === undefined ? immediateValue : await waiterPromise;
90
93
  signal?.throwIfAborted();
91
- if (immediateValue !== undefined)
92
- return immediateValue;
93
- return await waiterPromise;
94
+ return value;
94
95
  }
95
96
  async #getUnlocked(key) {
96
97
  const cached = this.#cache.get(key);