@valerypopoff/rivet2-core 2.3.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 (105) hide show
  1. package/dist/cjs/bundle.cjs +1947 -765
  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 +1537 -121
  8. package/dist/cjs/webAppRuntime.cjs.map +4 -4
  9. package/dist/esm/api/createProcessor.js +2 -0
  10. package/dist/esm/exports.js +4 -1
  11. package/dist/esm/integrations/CodeRunner.js +5 -0
  12. package/dist/esm/integrations/mcp/MCPBase.js +16 -6
  13. package/dist/esm/interpolationRuntime.js +5 -0
  14. package/dist/esm/model/AgentResponseTrace.js +16 -0
  15. package/dist/esm/model/GraphBoundaryCache.js +0 -6
  16. package/dist/esm/model/GraphBoundaryEffects.js +5 -1
  17. package/dist/esm/model/GraphOutputSelection.js +34 -0
  18. package/dist/esm/model/GraphProcessor.js +150 -44
  19. package/dist/esm/model/NodeExclusionPolicy.js +9 -1
  20. package/dist/esm/model/ProcessContextBuilder.js +4 -1
  21. package/dist/esm/model/RecordingPlayer.js +19 -6
  22. package/dist/esm/model/StoredValueStore.js +4 -3
  23. package/dist/esm/model/SubprocessorBridge.js +1 -0
  24. package/dist/esm/model/UiGraphActionProtocol.js +46 -4
  25. package/dist/esm/model/UiGraphBrowserRuntime.js +15 -1
  26. package/dist/esm/model/UiGraphIndexedDbPersistence.js +523 -0
  27. package/dist/esm/model/UiGraphRendererStyles.js +14 -0
  28. package/dist/esm/model/WebAppBrowserStorage.js +653 -0
  29. package/dist/esm/model/WebAppBrowserStorageRpc.js +200 -0
  30. package/dist/esm/model/chat-v2/chatV2CallObserver.js +1 -0
  31. package/dist/esm/model/chat-v2/chatV2EditorCache.js +2 -33
  32. package/dist/esm/model/chat-v2/llmChatV2NodeRuntime.js +1 -0
  33. package/dist/esm/model/chat-v2/llmChatV2OutputClone.js +42 -0
  34. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +31 -2
  35. package/dist/esm/model/chat-v2/llmProfile.js +17 -1
  36. package/dist/esm/model/chat-v2/llmProfileFallback.js +17 -5
  37. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +2 -0
  38. package/dist/esm/model/chat-v2/llmProfileNodeRuntime.js +4 -0
  39. package/dist/esm/model/chat-v2/toolContinuation.js +27 -1
  40. package/dist/esm/model/nodes/CodeNewNode.js +16 -16
  41. package/dist/esm/model/nodes/DestructureNode.js +2 -2
  42. package/dist/esm/model/nodes/ExpressionNode.js +16 -16
  43. package/dist/esm/model/nodes/ExtractObjectPathNode.js +2 -2
  44. package/dist/esm/model/nodes/ExtractYamlNode.js +5 -5
  45. package/dist/esm/model/nodes/JSFilterNode.js +3 -1
  46. package/dist/esm/model/nodes/JSMapNode.js +3 -1
  47. package/dist/esm/model/nodes/LLMChatV2Node.js +21 -2
  48. package/dist/esm/model/nodes/MCPGetPromptNode.js +6 -2
  49. package/dist/esm/model/nodes/MCPToolCallNode.js +6 -2
  50. package/dist/esm/model/nodes/ObjectNode.js +19 -20
  51. package/dist/esm/model/nodes/PromptNode.js +10 -11
  52. package/dist/esm/model/nodes/ReferencedGraphAliasNode.js +2 -40
  53. package/dist/esm/model/nodes/SubGraphNode.js +40 -26
  54. package/dist/esm/model/nodes/TextNode.js +11 -32
  55. package/dist/esm/model/nodes/ToTreeNode.js +6 -13
  56. package/dist/esm/model/nodes/ToolNode.js +33 -16
  57. package/dist/esm/model/nodes/jsListCallbackHelpers.js +19 -15
  58. package/dist/esm/model/nodes/jsValueInterpolation.js +83 -30
  59. package/dist/esm/model/nodes/nodeBodyPreview.js +23 -0
  60. package/dist/esm/plugins/openai/nodes/ThreadMessageNode.js +14 -11
  61. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  62. package/dist/esm/utils/index.js +2 -0
  63. package/dist/esm/utils/interpolation.js +478 -221
  64. package/dist/esm/utils/interpolationSyntax.js +175 -0
  65. package/dist/esm/utils/jsonPath.js +129 -0
  66. package/dist/esm/webAppRuntime.js +5 -2
  67. package/dist/types/api/createProcessor.d.ts +2 -0
  68. package/dist/types/exports.d.ts +5 -1
  69. package/dist/types/integrations/CodeRunnerOptions.d.ts +9 -0
  70. package/dist/types/integrations/mcp/MCPBase.d.ts +3 -1
  71. package/dist/types/interpolationRuntime.d.ts +5 -0
  72. package/dist/types/model/AgentResponseTrace.d.ts +1 -0
  73. package/dist/types/model/ExecutorProtocol.d.ts +9 -1
  74. package/dist/types/model/GraphBoundaryCache.d.ts +0 -2
  75. package/dist/types/model/GraphOutputSelection.d.ts +8 -0
  76. package/dist/types/model/GraphProcessor.d.ts +7 -4
  77. package/dist/types/model/NodeExclusionPolicy.d.ts +6 -0
  78. package/dist/types/model/ProcessContext.d.ts +36 -2
  79. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  80. package/dist/types/model/UiGraphActionProtocol.d.ts +8 -3
  81. package/dist/types/model/UiGraphBrowserRuntime.d.ts +6 -0
  82. package/dist/types/model/UiGraphIndexedDbPersistence.d.ts +50 -0
  83. package/dist/types/model/UiGraphRendererStyles.d.ts +1 -1
  84. package/dist/types/model/WebAppBrowserStorage.d.ts +90 -0
  85. package/dist/types/model/WebAppBrowserStorageRpc.d.ts +85 -0
  86. package/dist/types/model/chat-v2/chatV2Types.d.ts +3 -1
  87. package/dist/types/model/chat-v2/llmChatV2OutputClone.d.ts +3 -0
  88. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +5 -1
  89. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +4 -0
  90. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +10 -0
  91. package/dist/types/model/chat-v2/llmProfileTypes.d.ts +6 -0
  92. package/dist/types/model/chat-v2/toolContinuation.d.ts +14 -0
  93. package/dist/types/model/nodes/ObjectNode.d.ts +1 -1
  94. package/dist/types/model/nodes/SubGraphNode.d.ts +2 -0
  95. package/dist/types/model/nodes/ToTreeNode.d.ts +5 -2
  96. package/dist/types/model/nodes/ToolNode.d.ts +13 -1
  97. package/dist/types/model/nodes/jsValueInterpolation.d.ts +16 -8
  98. package/dist/types/model/nodes/nodeBodyPreview.d.ts +7 -0
  99. package/dist/types/recording/RecordedEvents.d.ts +11 -0
  100. package/dist/types/utils/index.d.ts +2 -0
  101. package/dist/types/utils/interpolation.d.ts +93 -8
  102. package/dist/types/utils/interpolationSyntax.d.ts +21 -0
  103. package/dist/types/utils/jsonPath.d.ts +15 -0
  104. package/dist/types/webAppRuntime.d.ts +8 -2
  105. package/package.json +11 -1
@@ -138,7 +138,9 @@ export function coreCreateProcessor(project, options, internalOptions = {}) {
138
138
  settings: resolveProcessSettings(options),
139
139
  getChatNodeEndpoint: options.getChatNodeEndpoint,
140
140
  onChatV2CallFinished: options.onChatV2CallFinished,
141
+ onLLMChatOutputSnapshot: options.onLLMChatOutputSnapshot,
141
142
  llmProfileHealthStore: options.llmProfileHealthStore,
143
+ llmProfileHealthExecutionCorrelationId: options.llmProfileHealthExecutionCorrelationId,
142
144
  evaluation: options.evaluation,
143
145
  }, resolvedInputs, resolvedContextValues, { returnWhenGraphOutputsReady: options.returnWhenGraphOutputsReady });
144
146
  if (abortSignal?.aborted) {
@@ -1,6 +1,7 @@
1
1
  export * from './utils/index.js';
2
2
  // eslint-disable-next-line import/no-cycle -- GraphProcessor depends on CodeRunner, which exposes the top-level Rivet export surface.
3
3
  export * from './model/GraphProcessor.js';
4
+ export { canConsumeControlFlowExcludedInput } from './model/NodeExclusionPolicy.js';
4
5
  export * from './model/DataValue.js';
5
6
  export * from './model/NodeBase.js';
6
7
  export * from './model/NodeGraph.js';
@@ -15,6 +16,7 @@ export * from './model/UiGraphWebAppStorage.js';
15
16
  export * from './model/StoredValueStore.js';
16
17
  export * from './model/ToolCallContinuation.js';
17
18
  export * from './model/UiGraphActionProtocol.js';
19
+ export * from './model/WebAppBrowserStorageRpc.js';
18
20
  export * from './model/GraphProgress.js';
19
21
  export * from './model/UiGraphRendererStyles.js';
20
22
  export * from './model/MarkdownSanitizationPolicy.js';
@@ -64,7 +66,8 @@ export * from './integrations/Tokenizer.js';
64
66
  export * from './integrations/GptTokenizerTokenizer.js';
65
67
  export { JS_LIST_CALLBACK_LOCAL_NAMES, interpolateJSListCallbackBody } from './model/nodes/jsListCallbackHelpers.js';
66
68
  export { findAutoDelegateGraphCandidate } from './model/nodes/toolCallDelegation.js';
67
- 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';
68
71
  export { WarningsPort } from './utils/symbols.js';
69
72
  import * as openai from './utils/openai.js';
70
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';
@@ -103,6 +103,9 @@ export function mergeAgentTraceEvent(existing, incoming) {
103
103
  if (existing.type === 'llm-call-finished' && incoming.type === 'llm-call-finished') {
104
104
  return {
105
105
  ...incoming,
106
+ ...(incoming.profileName == null && existing.profileName != null
107
+ ? { profileName: existing.profileName }
108
+ : {}),
106
109
  ...(incoming.profileHealthKey == null && existing.profileHealthKey != null
107
110
  ? { profileHealthKey: existing.profileHealthKey }
108
111
  : {}),
@@ -111,6 +114,14 @@ export function mergeAgentTraceEvent(existing, incoming) {
111
114
  : {}),
112
115
  };
113
116
  }
117
+ if (existing.type === 'llm-profile-attempt' && incoming.type === 'llm-profile-attempt') {
118
+ return {
119
+ ...incoming,
120
+ ...(incoming.profileName == null && existing.profileName != null
121
+ ? { profileName: existing.profileName }
122
+ : {}),
123
+ };
124
+ }
114
125
  if (existing.type === 'tool-call-finished' &&
115
126
  incoming.type === 'tool-call-finished' &&
116
127
  existing.resultOwner != null &&
@@ -131,6 +142,7 @@ function toModelCallTrace(event) {
131
142
  outcome: event.outcome,
132
143
  attemptIndex: event.attemptIndex,
133
144
  ...(event.profileIndex == null ? {} : { profileIndex: event.profileIndex }),
145
+ ...(event.profileName == null ? {} : { profileName: event.profileName }),
134
146
  ...(event.profileHealthKey == null ? {} : { profileHealthKey: event.profileHealthKey }),
135
147
  ...(event.profileHealthState == null ? {} : { profileHealthState: event.profileHealthState }),
136
148
  ...(event.roundIndex == null ? {} : { roundIndex: event.roundIndex }),
@@ -360,6 +372,7 @@ function isAgentModelCallTrace(value) {
360
372
  'outcome',
361
373
  'attemptIndex',
362
374
  'profileIndex',
375
+ 'profileName',
363
376
  'profileHealthKey',
364
377
  'profileHealthState',
365
378
  'roundIndex',
@@ -380,6 +393,7 @@ function isAgentModelCallTrace(value) {
380
393
  (value.outcome === 'success' || value.outcome === 'provider-failure' || value.outcome === 'aborted') &&
381
394
  isNonNegativeInteger(value.attemptIndex) &&
382
395
  isOptionalNonNegativeInteger(value.profileIndex) &&
396
+ isOptionalString(value.profileName) &&
383
397
  isOptionalString(value.profileHealthKey) &&
384
398
  (value.profileHealthState === undefined ||
385
399
  value.profileHealthState === 'closed' ||
@@ -398,6 +412,7 @@ function isAgentLLMProfileAttemptTrace(value) {
398
412
  'eventId',
399
413
  'roundIndex',
400
414
  'profileIndex',
415
+ 'profileName',
401
416
  'nodeId',
402
417
  'processId',
403
418
  'provider',
@@ -418,6 +433,7 @@ function isAgentLLMProfileAttemptTrace(value) {
418
433
  typeof value.eventId === 'string' &&
419
434
  isNonNegativeInteger(value.roundIndex) &&
420
435
  isOptionalNonNegativeInteger(value.profileIndex) &&
436
+ isOptionalString(value.profileName) &&
421
437
  typeof value.nodeId === 'string' &&
422
438
  typeof value.processId === 'string' &&
423
439
  typeof value.provider === 'string' &&
@@ -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) {
@@ -825,6 +840,7 @@ export class GraphProcessor {
825
840
  // observer from the root run so nested LLM calls are not emitted once by
826
841
  // every ancestor before their own event is bridged to the root emitter.
827
842
  const hostChatV2Observer = this.getRootProcessor().#context.onChatV2CallFinished;
843
+ const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#context.onLLMChatOutputSnapshot;
828
844
  const hostLLMProfileAttemptObserver = this.getRootProcessor().#context.onLLMProfileAttempt;
829
845
  this.#nodeProcessContextBase = {
830
846
  ...this.#context,
@@ -860,6 +876,18 @@ export class GraphProcessor {
860
876
  const { rawUsage: _rawUsage, ...traceEvent } = event;
861
877
  emitDetached(this.#emitter, 'llmCallFinished', this.#withExecution(traceEvent));
862
878
  },
879
+ onLLMChatOutputSnapshot: (event) => {
880
+ try {
881
+ const observerResult = hostLLMChatOutputSnapshotObserver?.(event);
882
+ if (observerResult != null && typeof observerResult.then === 'function') {
883
+ void Promise.resolve(observerResult).catch(() => undefined);
884
+ }
885
+ }
886
+ catch {
887
+ // Snapshot observers are display-only and must never affect execution.
888
+ }
889
+ emitDetached(this.#emitter, 'llmChatOutputSnapshot', this.#withExecution(event));
890
+ },
863
891
  onLLMProfileAttempt: (event) => {
864
892
  try {
865
893
  const observerResult = hostLLMProfileAttemptObserver?.(event);
@@ -885,12 +913,31 @@ export class GraphProcessor {
885
913
  this.#emitTraceEvent(message);
886
914
  },
887
915
  setStoredValue: (key, value) => this.#storedValueController.set(key, value),
888
- waitForGlobal: async (id) => {
916
+ waitForGlobal: async (id, signal = this.#abortController.signal) => {
917
+ if (signal.aborted) {
918
+ throw createGraphAbortErrorFromSignal(signal);
919
+ }
889
920
  if (this.#globals.has(id)) {
890
921
  return this.#globals.get(id);
891
922
  }
892
- await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
893
- 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
+ });
894
941
  },
895
942
  waitForStoredValue: (key, signal) => this.#storedValueController.waitForSet(key, signal),
896
943
  };
@@ -924,7 +971,7 @@ export class GraphProcessor {
924
971
  return;
925
972
  }
926
973
  for (const node of this.#executionGraphNodes) {
927
- if (!this.#nodeResults.has(node.id)) {
974
+ if (!this.#isNodeSelected(node.id) || !this.#nodeResults.has(node.id)) {
928
975
  continue;
929
976
  }
930
977
  if (this.#suppressedPreloadedNodeIds.has(node.id)) {
@@ -953,7 +1000,8 @@ export class GraphProcessor {
953
1000
  }
954
1001
  }
955
1002
  async #processCompatibleGraph() {
956
- 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));
957
1005
  await this.#processingQueue.onIdle();
958
1006
  this.#markUnqueuedNodesIgnored();
959
1007
  }
@@ -961,7 +1009,11 @@ export class GraphProcessor {
961
1009
  if (this.#scheduler !== 'fast-acyclic') {
962
1010
  return false;
963
1011
  }
964
- 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) {
965
1017
  return false;
966
1018
  }
967
1019
  if (this.#nodesNotInCycle.length !== this.#executionGraphNodes.length) {
@@ -1164,6 +1216,8 @@ export class GraphProcessor {
1164
1216
  }
1165
1217
  }
1166
1218
  async #fetchNodeDataAndProcessNode(node) {
1219
+ if (!this.#isNodeSelected(node.id))
1220
+ return;
1167
1221
  const profileStart = this.#startRuntimeProfile();
1168
1222
  try {
1169
1223
  if (this.#currentlyProcessing.has(node.id)) {
@@ -1215,6 +1269,8 @@ export class GraphProcessor {
1215
1269
  }
1216
1270
  /** If all inputs are present, all conditions met, processes the node. */
1217
1271
  async #processNodeIfAllInputsAvailable(node, options = {}) {
1272
+ if (!this.#isNodeSelected(node.id))
1273
+ return [];
1218
1274
  const { queueOutputNodes = true } = options;
1219
1275
  const builtInNode = node;
1220
1276
  const inputNodesProfileStart = this.#startRuntimeProfile();
@@ -1445,7 +1501,10 @@ export class GraphProcessor {
1445
1501
  }
1446
1502
  }
1447
1503
  #queueOutputNodes(node, outputNodes) {
1448
- 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 () => {
1449
1508
  this.#emitTraceEvent(`Trying to run output node from ${node.title}: ${outputNode.title} (${outputNode.id})`);
1450
1509
  await this.#processNodeIfAllInputsAvailable(outputNode);
1451
1510
  }));
@@ -1843,6 +1902,11 @@ export class GraphProcessor {
1843
1902
  }
1844
1903
  }
1845
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
+ }
1846
1910
  const instance = this.#nodeInstances[node.id];
1847
1911
  const nodeAbortController = this.#newAbortController();
1848
1912
  this.#registerNodeAbortController(node.id, nodeAbortController);
@@ -1860,6 +1924,9 @@ export class GraphProcessor {
1860
1924
  this.#finishRuntimeProfile('createNodeProcessContext', createContextProfileStart);
1861
1925
  }
1862
1926
  await this.#waitUntilUnpaused();
1927
+ if (nodeAbortController.signal.aborted) {
1928
+ throw createGraphAbortErrorFromSignal(nodeAbortController.signal);
1929
+ }
1863
1930
  const implementationProfileStart = this.#startRuntimeProfile();
1864
1931
  let results;
1865
1932
  try {
@@ -1912,13 +1979,14 @@ export class GraphProcessor {
1912
1979
  this.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
1913
1980
  },
1914
1981
  processId,
1915
- 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),
1916
1983
  reportProgress: (progress) => {
1917
1984
  const normalized = normalizeGraphProgress(progress);
1918
1985
  if (normalized) {
1919
1986
  emitDetached(this.#emitter, 'progress', this.#withExecution({ node, processId, progress: normalized }));
1920
1987
  }
1921
1988
  },
1989
+ splitIndex: node.isSplitRun ? index : 0,
1922
1990
  setGlobal: (id, value) => {
1923
1991
  this.#globals.set(id, value);
1924
1992
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
@@ -1926,18 +1994,27 @@ export class GraphProcessor {
1926
1994
  toolCallContinuation,
1927
1995
  toolCallTraceSource,
1928
1996
  waitEvent: async (event) => {
1997
+ const signal = nodeAbortController.signal;
1998
+ if (signal.aborted) {
1999
+ throw createGraphAbortErrorFromSignal(signal, 'Process aborted');
2000
+ }
1929
2001
  return new Promise((resolve, reject) => {
1930
2002
  const abortListener = () => {
1931
- reject(createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Process aborted'));
2003
+ cleanup();
2004
+ reject(createGraphAbortErrorFromSignal(signal, 'Process aborted'));
1932
2005
  };
1933
- this.#emitter
1934
- .once(`userEvent:${event}`)
1935
- .then(resolve)
1936
- .catch(reject)
1937
- .finally(() => {
1938
- nodeAbortController.signal.removeEventListener('abort', abortListener);
2006
+ const unsubscribe = this.#emitter.on(`userEvent:${event}`, (data) => {
2007
+ cleanup();
2008
+ resolve(data);
1939
2009
  });
1940
- 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
+ }
1941
2018
  });
1942
2019
  },
1943
2020
  });
@@ -2193,7 +2270,7 @@ export class GraphProcessor {
2193
2270
  state: {
2194
2271
  erroredNodeIds: new Set(this.#erroredNodes.keys()),
2195
2272
  nodeOutputs: this.#nodeResults,
2196
- runToRelevantNodeIds: this.#getRunToRelevantNodeIds(),
2273
+ runToRelevantNodeIds: this.#getExecutionRelevantNodeIds(),
2197
2274
  visitedNodeIds: this.#visitedNodes,
2198
2275
  },
2199
2276
  });
@@ -2250,8 +2327,8 @@ export class GraphProcessor {
2250
2327
  const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2251
2328
  const outgoingByNodeId = new Map();
2252
2329
  const incomingByNodeId = new Map();
2253
- const runToRelevantNodeIds = this.#getRunToRelevantNodeIds();
2254
- const isRunToRelevant = (nodeId) => !runToRelevantNodeIds || runToRelevantNodeIds.has(nodeId);
2330
+ const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2331
+ const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
2255
2332
  for (const connection of connections) {
2256
2333
  const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
2257
2334
  outgoing.push(connection);
@@ -2261,7 +2338,7 @@ export class GraphProcessor {
2261
2338
  incomingByNodeId.set(connection.inputNodeId, incoming);
2262
2339
  }
2263
2340
  for (const triggerNode of Object.values(this.#nodesById)) {
2264
- if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRunToRelevant(triggerNode.id)) {
2341
+ if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRelevant(triggerNode.id)) {
2265
2342
  continue;
2266
2343
  }
2267
2344
  if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId && this.#nodeResults.has(triggerNode.id)) {
@@ -2270,7 +2347,7 @@ export class GraphProcessor {
2270
2347
  const nodeIds = new Set();
2271
2348
  const pendingNodeIds = (outgoingByNodeId.get(triggerNode.id) ?? [])
2272
2349
  .map((connection) => connection.inputNodeId)
2273
- .filter(isRunToRelevant);
2350
+ .filter(isRelevant);
2274
2351
  while (pendingNodeIds.length > 0) {
2275
2352
  const nodeId = pendingNodeIds.pop();
2276
2353
  if (nodeId === triggerNode.id) {
@@ -2291,7 +2368,7 @@ export class GraphProcessor {
2291
2368
  }
2292
2369
  nodeIds.add(nodeId);
2293
2370
  for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
2294
- if (isRunToRelevant(connection.inputNodeId)) {
2371
+ if (isRelevant(connection.inputNodeId)) {
2295
2372
  pendingNodeIds.push(connection.inputNodeId);
2296
2373
  }
2297
2374
  }
@@ -2390,17 +2467,19 @@ export class GraphProcessor {
2390
2467
  if (outputConnections.length === 0) {
2391
2468
  return new Set();
2392
2469
  }
2393
- const runToRelevantNodeIds = this.#getRunToRelevantNodeIds();
2470
+ const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2394
2471
  const activeOutputPortIds = new Set();
2395
2472
  for (const { node: outputNode, connections } of outputConnections) {
2396
2473
  if (outputNode.disabled) {
2397
2474
  continue;
2398
2475
  }
2399
- if (runToRelevantNodeIds && !runToRelevantNodeIds.has(outputNode.id)) {
2476
+ if (relevantNodeIds && !relevantNodeIds.has(outputNode.id)) {
2400
2477
  continue;
2401
2478
  }
2402
2479
  for (const connection of connections) {
2403
- activeOutputPortIds.add(connection.outputId);
2480
+ if (this.#isDefinitionValidConnection(connection)) {
2481
+ activeOutputPortIds.add(connection.outputId);
2482
+ }
2404
2483
  }
2405
2484
  }
2406
2485
  return activeOutputPortIds;
@@ -2416,6 +2495,15 @@ export class GraphProcessor {
2416
2495
  }
2417
2496
  }
2418
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
+ }
2419
2507
  #getRunToRelevantNodeIds() {
2420
2508
  if (!this.runToNodeIds) {
2421
2509
  return undefined;
@@ -2537,27 +2625,45 @@ export class GraphProcessor {
2537
2625
  }
2538
2626
  return processor;
2539
2627
  }
2540
- 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
+ }
2541
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
+ };
2542
2640
  const abortListener = () => {
2543
- delete this.#pendingUserInputs[node.id];
2544
- reject(createGraphAbortErrorFromSignal(this.#abortController.signal));
2641
+ if (settled)
2642
+ return;
2643
+ settled = true;
2644
+ cleanup();
2645
+ reject(createGraphAbortErrorFromSignal(signal));
2545
2646
  };
2546
- this.#pendingUserInputs[node.id] = {
2547
- resolve,
2548
- reject,
2647
+ const respond = (results) => {
2648
+ if (settled)
2649
+ return;
2650
+ settled = true;
2651
+ cleanup();
2652
+ resolve(results);
2549
2653
  };
2550
- 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
+ }
2551
2661
  emitDetached(this.#emitter, 'userInput', this.#withExecution({
2552
2662
  node,
2553
2663
  inputStrings,
2554
2664
  inputs: inputValues,
2555
2665
  renderingType,
2556
- callback: (results) => {
2557
- this.#abortController.signal.removeEventListener('abort', abortListener);
2558
- resolve(results);
2559
- delete this.#pendingUserInputs[node.id];
2560
- },
2666
+ callback: respond,
2561
2667
  processId,
2562
2668
  }));
2563
2669
  });