@valerypopoff/rivet2-core 2.1.3 → 2.1.5

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 (114) hide show
  1. package/dist/cjs/bundle.cjs +10138 -5679
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +1214 -0
  4. package/dist/cjs/webAppRuntime.cjs.map +7 -0
  5. package/dist/esm/api/createProcessor.js +8 -1
  6. package/dist/esm/api/streaming.js +6 -0
  7. package/dist/esm/exports.js +8 -0
  8. package/dist/esm/integrations/mcp/MCPBase.js +92 -34
  9. package/dist/esm/model/GraphBoundaryEffects.js +13 -0
  10. package/dist/esm/model/GraphProcessor.js +1138 -86
  11. package/dist/esm/model/GraphProgress.js +15 -0
  12. package/dist/esm/model/ManagedAsyncBranches.js +28 -0
  13. package/dist/esm/model/Nodes.js +12 -0
  14. package/dist/esm/model/ProcessContextBuilder.js +3 -1
  15. package/dist/esm/model/RecordingPlayer.js +19 -0
  16. package/dist/esm/model/StoredValueStore.js +226 -0
  17. package/dist/esm/model/SubprocessorBridge.js +50 -18
  18. package/dist/esm/model/ToolCallContinuation.js +1 -0
  19. package/dist/esm/model/UiGraph.js +177 -4
  20. package/dist/esm/model/UiGraphActionProtocol.js +131 -0
  21. package/dist/esm/model/UiGraphBindings.js +530 -0
  22. package/dist/esm/model/UiGraphBrowserRuntime.js +373 -0
  23. package/dist/esm/model/UiGraphNormalization.js +148 -0
  24. package/dist/esm/model/UiGraphRendererStyles.js +1108 -42
  25. package/dist/esm/model/UiGraphRuntimeModel.js +518 -2
  26. package/dist/esm/model/UiGraphSchema.js +91 -0
  27. package/dist/esm/model/UiGraphWebAppStatus.js +19 -0
  28. package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
  29. package/dist/esm/model/chat/chatMessages.js +5 -9
  30. package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
  31. package/dist/esm/model/chat-v2/index.js +1 -0
  32. package/dist/esm/model/chat-v2/toolContinuation.js +6 -8
  33. package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
  34. package/dist/esm/model/nodes/ArrayNode.js +2 -13
  35. package/dist/esm/model/nodes/AssembleMessageNode.js +2 -13
  36. package/dist/esm/model/nodes/AssemblePromptNode.js +2 -13
  37. package/dist/esm/model/nodes/CoalesceNode.js +2 -15
  38. package/dist/esm/model/nodes/DelayNode.js +3 -14
  39. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
  40. package/dist/esm/model/nodes/DidRunNode.js +2 -13
  41. package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
  42. package/dist/esm/model/nodes/JoinNode.js +2 -13
  43. package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
  44. package/dist/esm/model/nodes/LoopControllerNode.js +3 -14
  45. package/dist/esm/model/nodes/MCPDiscoveryNode.js +19 -90
  46. package/dist/esm/model/nodes/MCPGetPromptNode.js +11 -97
  47. package/dist/esm/model/nodes/MCPToolCallNode.js +11 -97
  48. package/dist/esm/model/nodes/MatchNode.js +7 -7
  49. package/dist/esm/model/nodes/PassthroughNode.js +3 -14
  50. package/dist/esm/model/nodes/RaceInputsNode.js +2 -13
  51. package/dist/esm/model/nodes/ReportProgressNode.js +57 -0
  52. package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
  53. package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
  54. package/dist/esm/model/nodes/StoredValueNodeUtils.js +47 -0
  55. package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
  56. package/dist/esm/model/nodes/variadicPortIndex.js +32 -0
  57. package/dist/esm/plugins/anthropic/anthropic.js +1 -1
  58. package/dist/esm/recording/ExecutionRecorder.js +6 -0
  59. package/dist/esm/utils/coerceType.js +3 -0
  60. package/dist/esm/utils/fetchEventSource.js +16 -17
  61. package/dist/esm/utils/serialization/serialization.js +4 -0
  62. package/dist/esm/utils/serialization/serializationUtils.js +8 -27
  63. package/dist/esm/utils/serialization/serialization_v4.js +3 -3
  64. package/dist/esm/webAppRuntime.js +4 -2
  65. package/dist/types/api/createProcessor.d.ts +4 -0
  66. package/dist/types/api/streaming.d.ts +6 -0
  67. package/dist/types/exports.d.ts +8 -0
  68. package/dist/types/integrations/mcp/MCPBase.d.ts +26 -3
  69. package/dist/types/model/EditorDefinition.d.ts +2 -1
  70. package/dist/types/model/ExecutorProtocol.d.ts +19 -0
  71. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
  72. package/dist/types/model/GraphProcessor.d.ts +26 -2
  73. package/dist/types/model/GraphProgress.d.ts +6 -0
  74. package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
  75. package/dist/types/model/Nodes.d.ts +6 -2
  76. package/dist/types/model/ProcessContext.d.ts +18 -0
  77. package/dist/types/model/ProcessContextBuilder.d.ts +3 -1
  78. package/dist/types/model/StoredValueStore.d.ts +55 -0
  79. package/dist/types/model/SubprocessorBridge.d.ts +4 -2
  80. package/dist/types/model/ToolCallContinuation.d.ts +13 -0
  81. package/dist/types/model/UiGraph.d.ts +63 -9
  82. package/dist/types/model/UiGraphActionProtocol.d.ts +71 -0
  83. package/dist/types/model/UiGraphBindings.d.ts +45 -0
  84. package/dist/types/model/UiGraphBrowserRuntime.d.ts +55 -0
  85. package/dist/types/model/UiGraphNormalization.d.ts +24 -0
  86. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
  87. package/dist/types/model/UiGraphRuntimeModel.d.ts +97 -6
  88. package/dist/types/model/UiGraphSchema.d.ts +113 -0
  89. package/dist/types/model/UiGraphWebAppStatus.d.ts +5 -0
  90. package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
  91. package/dist/types/model/chat-v2/index.d.ts +1 -0
  92. package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
  93. package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
  94. package/dist/types/model/nodes/ArrayNode.d.ts +0 -1
  95. package/dist/types/model/nodes/AssembleMessageNode.d.ts +0 -1
  96. package/dist/types/model/nodes/AssemblePromptNode.d.ts +0 -1
  97. package/dist/types/model/nodes/DelayNode.d.ts +0 -1
  98. package/dist/types/model/nodes/DidRunNode.d.ts +0 -1
  99. package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
  100. package/dist/types/model/nodes/JoinNode.d.ts +0 -1
  101. package/dist/types/model/nodes/LoopControllerNode.d.ts +0 -1
  102. package/dist/types/model/nodes/PassthroughNode.d.ts +0 -1
  103. package/dist/types/model/nodes/RaceInputsNode.d.ts +0 -1
  104. package/dist/types/model/nodes/ReportProgressNode.d.ts +23 -0
  105. package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
  106. package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
  107. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
  108. package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
  109. package/dist/types/model/nodes/variadicPortIndex.d.ts +4 -0
  110. package/dist/types/recording/RecordedEvents.d.ts +10 -0
  111. package/dist/types/webAppRuntime.d.ts +8 -3
  112. package/package.json +2 -2
  113. package/dist/esm/plugins/anthropic/fetchEventSource.js +0 -107
  114. package/dist/types/plugins/anthropic/fetchEventSource.d.ts +0 -11
@@ -8,7 +8,7 @@ import { nanoid } from 'nanoid/non-secure';
8
8
  import { coerceTypeOptional } from '../utils/coerceType.js';
9
9
  import { getPluginConfig } from '../utils/index.js';
10
10
  import { isGraphExecutionPlan, preprocessGraphState, toReusableGraphExecutionPlan, } from './GraphPreprocessor.js';
11
- import { getGraphBoundary, } from './GraphBoundaryCache.js';
11
+ import { getGraphBoundary } from './GraphBoundaryCache.js';
12
12
  import { applyFrozenGraphBoundaryEffects, ensureGraphCostOutput } from './GraphBoundaryEffects.js';
13
13
  import { replayExecutionRecording } from './RecordingPlayer.js';
14
14
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
@@ -19,9 +19,27 @@ import { wireSubprocessorEvents, wireSubprocessorLifecycle } from './Subprocesso
19
19
  import { createGraphAbortError, createGraphAbortErrorFromSignal, createGraphAbortReason, getAbortSignalReason, getGraphAbortReasonFromError, getGraphAbortReasonFromSignal, isAbortLikeError, isRaceLoserGraphAbortReason, isSuccessfulNonRaceGraphAbortReason, RACE_LOSER_EXCLUSION_REASON, SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON, } from './GraphAbortReasons.js';
20
20
  import { emitDetached } from '../utils/emitDetached.js';
21
21
  import { GraphRunLifecycle } from './GraphRunLifecycle.js';
22
+ import { normalizeGraphProgress } from './GraphProgress.js';
23
+ import { RIVET_WEB_APP_STATUS_FUNCTION_NAME, rivetWebAppStatusExternalFunction } from './UiGraphWebAppStatus.js';
24
+ import { RivetStoredValueController } from './StoredValueStore.js';
22
25
  import { createExcludedNodeOutputs, getControlFlowExclusionDecision, getMissingRequiredInputExclusion, } from './NodeExclusionPolicy.js';
26
+ import { DELEGATE_TOOL_CALL_INPUT_ID, resolveToolContinuationConnection, } from './chat-v2/toolContinuationConnection.js';
27
+ import { buildDelegatedToolCallOutputs, delegateToolCall, isDelegatedToolCallRecord, } from './nodes/toolCallDelegation.js';
28
+ import { ManagedAsyncBranches } from './ManagedAsyncBranches.js';
23
29
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
24
30
  import { IsomorphicCodeRunner } from '../integrations/CodeRunner.js';
31
+ const graphProcessorGraphOverride = Symbol('graphProcessorGraphOverride');
32
+ const consumedAsyncBranchTriggerOverride = Symbol('consumedAsyncBranchTriggerOverride');
33
+ function createGraphOutputsOverlay(parent) {
34
+ const writes = {};
35
+ const view = new Proxy(writes, {
36
+ get: (target, property, receiver) => Reflect.has(target, property) ? Reflect.get(target, property, receiver) : Reflect.get(parent, property),
37
+ getOwnPropertyDescriptor: (target, property) => Reflect.getOwnPropertyDescriptor(target, property) ?? Reflect.getOwnPropertyDescriptor(parent, property),
38
+ has: (target, property) => Reflect.has(target, property) || Reflect.has(parent, property),
39
+ ownKeys: (target) => [...new Set([...Reflect.ownKeys(parent), ...Reflect.ownKeys(target)])],
40
+ });
41
+ return { view, writes };
42
+ }
25
43
  export function cloneFrozenNodeOutputs(outputs) {
26
44
  if (typeof structuredClone !== 'function') {
27
45
  throw new Error('Frozen node output cloning requires structuredClone support');
@@ -68,6 +86,7 @@ const FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = new Set([
68
86
  'loopController',
69
87
  'loopUntil',
70
88
  'raceInputs',
89
+ 'startBackgroundBranch',
71
90
  'userInput',
72
91
  'waitForEvent',
73
92
  ]);
@@ -118,6 +137,19 @@ export class GraphProcessor {
118
137
  #externalFunctions = {};
119
138
  slowMode = false;
120
139
  #parent;
140
+ #abortOwnerOverride;
141
+ #sameGraphRunOwnerOverride;
142
+ #suppressGraphPartialOutputs = false;
143
+ #suppressGraphLifecycleEvents = false;
144
+ #executionIdentityOverride;
145
+ #sharedRunStateOverride;
146
+ #suppressedPreloadedNodeIds = new Set();
147
+ #preloadedNodeResults = new Map();
148
+ #toolCallContinuationInvocations = new Map();
149
+ #continuationCompletionOwnerByNodeId = new Map();
150
+ #effectiveConnectionsForRun;
151
+ #asyncBranchPlansByTriggerNodeId = new Map();
152
+ #consumedAsyncBranchTriggerNodeId;
121
153
  #registry;
122
154
  #concurrency;
123
155
  #executionPlanCacheMode;
@@ -127,6 +159,7 @@ export class GraphProcessor {
127
159
  #runtimeProfiler;
128
160
  #captureNodeTimings;
129
161
  #frozenNodeOutputResolver;
162
+ #storedValueStore;
130
163
  #useSeededExecutionPlanOnNextRun = false;
131
164
  id = nanoid();
132
165
  #includeTrace = true;
@@ -160,6 +193,7 @@ export class GraphProcessor {
160
193
  #subprocessors = undefined;
161
194
  #contextValues = undefined;
162
195
  #globals = undefined;
196
+ #storedValueController = undefined;
163
197
  #attachedNodeData = undefined;
164
198
  #successfulAbortTerminalProcessIds = undefined;
165
199
  #totalCost = 0;
@@ -171,6 +205,9 @@ export class GraphProcessor {
171
205
  #graphExecutionPlan;
172
206
  #nodeProcessContextBase = undefined;
173
207
  #runToRelevantNodeIds;
208
+ #managedAsyncBranches;
209
+ #managedAsyncBranchFailures = [];
210
+ #runCompletionPromise;
174
211
  #nodesNotInCycle = undefined;
175
212
  #nodeAbortControllers = new Map();
176
213
  #graphInputNodeValues = {};
@@ -180,6 +217,13 @@ export class GraphProcessor {
180
217
  get isRunning() {
181
218
  return this.#lifecycle.isRunning;
182
219
  }
220
+ /** Waits for the current run's full lifecycle, including managed async branches. */
221
+ async waitForRunCompletion() {
222
+ if (!this.#runCompletionPromise) {
223
+ throw new Error('No graph run has been started.');
224
+ }
225
+ return await this.#runCompletionPromise;
226
+ }
183
227
  #startNodeTiming() {
184
228
  return this.#captureNodeTimings ? getMonotonicTimeMs() : undefined;
185
229
  }
@@ -223,7 +267,7 @@ export class GraphProcessor {
223
267
  }
224
268
  constructor(project, graphId, registry, includeTrace, options) {
225
269
  this.#project = project;
226
- const graph = resolveProcessorGraph(project, graphId);
270
+ const graph = options?.[graphProcessorGraphOverride] ?? resolveProcessorGraph(project, graphId);
227
271
  if (!graph) {
228
272
  throw new Error(`Graph ${graphId} not found in project`);
229
273
  }
@@ -240,8 +284,10 @@ export class GraphProcessor {
240
284
  this.#scheduler = options?.scheduler ?? 'compatible';
241
285
  this.#runtimeProfiler = options?.runtimeProfiler;
242
286
  this.#captureNodeTimings = options?.captureNodeTimings ?? false;
287
+ this.#consumedAsyncBranchTriggerNodeId = options?.[consumedAsyncBranchTriggerOverride];
243
288
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
244
289
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
290
+ this.setExternalFunction(RIVET_WEB_APP_STATUS_FUNCTION_NAME, rivetWebAppStatusExternalFunction);
245
291
  this.#emitter.on('globalSet', ({ id, value }) => {
246
292
  emitDetached(this.#emitter, `globalSet:${id}`, value);
247
293
  });
@@ -395,6 +441,12 @@ export class GraphProcessor {
395
441
  setExternalFunction(name, fn) {
396
442
  this.#externalFunctions[name] = fn;
397
443
  }
444
+ setStoredValueStore(store) {
445
+ if (this.#lifecycle.isRunning) {
446
+ throw new Error('Cannot change the stored value store while the graph is running.');
447
+ }
448
+ this.#storedValueStore = store;
449
+ }
398
450
  async abort(successful = false, error) {
399
451
  if (!this.#lifecycle.requestAbort(successful, error)) {
400
452
  return Promise.resolve();
@@ -402,11 +454,16 @@ export class GraphProcessor {
402
454
  const abortReason = createGraphAbortReason(successful, error);
403
455
  this.#abortController.abort(abortReason);
404
456
  this.#abortActiveNodeControllers(abortReason);
405
- emitDetached(this.#emitter, 'graphAbort', this.#withExecution({ successful, error, graph: this.#graph }));
406
- if (!this.#isSubProcessor) {
407
- emitDetached(this.#emitter, 'abort', { successful, error });
457
+ if (!this.#suppressGraphLifecycleEvents) {
458
+ emitDetached(this.#emitter, 'graphAbort', this.#withExecution({ successful, error, graph: this.#graph }));
459
+ if (!this.#isSubProcessor) {
460
+ emitDetached(this.#emitter, 'abort', { successful, error });
461
+ }
408
462
  }
409
463
  await this.#processingQueue.onIdle();
464
+ if (!this.#isSubProcessor) {
465
+ await this.#managedAsyncBranches?.drain();
466
+ }
410
467
  }
411
468
  pause() {
412
469
  if (this.#lifecycle.pause()) {
@@ -456,16 +513,19 @@ export class GraphProcessor {
456
513
  }
457
514
  }
458
515
  preloadNodeData(nodeId, data) {
459
- this.#nodeResults ??= new Map();
460
- this.#visitedNodes ??= new Set();
461
516
  for (const value of Object.values(data)) {
462
517
  if (!value || !('type' in value) || !value.type) {
463
518
  throw new Error(`Invalid data value for node ${nodeId}, must be a DataValue`);
464
519
  }
465
520
  }
466
- this.#nodeResults.set(nodeId, data);
467
- this.#visitedNodes.add(nodeId);
521
+ this.#preloadedNodeResults.set(nodeId, data);
468
522
  this.#hasPreloadedData = true;
523
+ // Preserve the historical ability to preload an idle processor as well as
524
+ // inject a boundary into a run that has already initialized.
525
+ if (this.#lifecycle.isRunning) {
526
+ this.#nodeResults.set(nodeId, data);
527
+ this.#visitedNodes.add(nodeId);
528
+ }
469
529
  }
470
530
  setFrozenNodeOutputResolver(resolver) {
471
531
  this.#frozenNodeOutputResolver = resolver;
@@ -532,30 +592,39 @@ export class GraphProcessor {
532
592
  }
533
593
  #initProcessState() {
534
594
  this.#lifecycle.begin();
535
- if (!this.#hasPreloadedData) {
536
- this.#nodeResults = new Map();
537
- this.#visitedNodes = new Set();
538
- }
595
+ this.#nodeResults = new Map(this.#preloadedNodeResults);
596
+ this.#visitedNodes = new Set(this.#preloadedNodeResults.keys());
597
+ this.#hasPreloadedData = this.#preloadedNodeResults.size > 0;
539
598
  this.#erroredNodes = new Map();
540
599
  this.#currentlyProcessing = new Set();
541
600
  const seededExecutionPlan = this.#seededExecutionPlanForNextRun();
542
- this.#remainingNodes = new Set(seededExecutionPlan
543
- ? seededExecutionPlan.nodeIds
544
- : this.#graph.nodes.map((node) => node.id));
601
+ this.#remainingNodes = new Set(seededExecutionPlan ? seededExecutionPlan.nodeIds : this.#graph.nodes.map((node) => node.id));
545
602
  this.#pendingUserInputs = {};
546
603
  this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
547
- this.#graphOutputs = {};
604
+ this.#graphOutputs = this.#sharedRunStateOverride?.graphOutputs ?? {};
548
605
  this.#executionCache ??= new Map();
549
606
  this.#queuedNodes = new Set();
607
+ this.#toolCallContinuationInvocations = new Map();
608
+ this.#continuationCompletionOwnerByNodeId = new Map();
609
+ this.#effectiveConnectionsForRun = undefined;
610
+ this.#asyncBranchPlansByTriggerNodeId = new Map();
550
611
  this.#loopControllersSeen = new Set();
551
612
  this.#subprocessors = new Set();
552
- this.#attachedNodeData = new Map();
613
+ this.#attachedNodeData = this.#sharedRunStateOverride?.attachedNodeData ?? new Map();
553
614
  this.#globals ??= new Map();
615
+ if (!this.#isSubProcessor) {
616
+ this.#storedValueController = new RivetStoredValueController(this.#storedValueStore);
617
+ }
554
618
  this.#ignoreNodes = new Set();
555
619
  this.#nodeProcessContextBase = undefined;
556
620
  this.#runToRelevantNodeIds = undefined;
621
+ if (!this.#isSubProcessor) {
622
+ this.#managedAsyncBranches = new ManagedAsyncBranches();
623
+ this.#managedAsyncBranchFailures = [];
624
+ }
557
625
  this.#abortController = this.#newAbortController();
558
626
  this.#successfulAbortTerminalProcessIds = new Set();
627
+ this.#totalCost = 0;
559
628
  this.#nodeAbortControllers = new Map();
560
629
  this.#loadedProjects =
561
630
  this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {};
@@ -565,7 +634,7 @@ export class GraphProcessor {
565
634
  this.#runtimeCache.graphBoundaries = undefined;
566
635
  }
567
636
  }
568
- this.#graphInputNodeValues = {};
637
+ this.#graphInputNodeValues = this.#sharedRunStateOverride?.graphInputNodeValues ?? {};
569
638
  }
570
639
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
571
640
  async processGraph(
@@ -574,36 +643,84 @@ export class GraphProcessor {
574
643
  /** Inputs to the main graph. You should pass all inputs required by the GraphInputNodes of the graph. */
575
644
  inputs = {},
576
645
  /** Contextual data available to all graphs and subgraphs. Kind of like react context, avoids drilling down data into subgraphs. Be careful when using it. */
577
- contextValues = {}) {
646
+ contextValues = {},
647
+ /** Allows callers such as web apps to receive root outputs while managed async branches continue settling. */
648
+ options = {}) {
578
649
  if (this.#lifecycle.isRunning) {
579
650
  throw new Error('Cannot process graph while already processing');
580
651
  }
581
- try {
582
- this.#profileRuntimeSync('initializeGraphRun', () => this.#initializeGraphRun(context, inputs, contextValues));
583
- await this.#profileRuntimeAsync('loadProjectReferences', () => this.#loadProjectReferences());
584
- this.#profileRuntimeSync('prepareNodeProcessContextBase', () => this.#prepareNodeProcessContextBase());
585
- const shouldUseSeededExecutionPlan = this.#seededExecutionPlanForNextRun() != null;
586
- this.#useSeededExecutionPlanOnNextRun = false;
587
- if (!shouldUseSeededExecutionPlan) {
588
- this.#preprocessGraph();
589
- }
590
- await this.#profileRuntimeAsync('emitGraphStart', () => this.#emitGraphStart());
591
- await this.#profileRuntimeAsync('emitPreloadedNodeResults', () => this.#emitPreloadedNodeResults());
592
- await this.#profileRuntimeAsync('waitUntilUnpaused', () => this.#waitUntilUnpaused());
593
- if (this.#canUseFastAcyclicScheduler()) {
594
- await this.#profileRuntimeAsync('processFastAcyclicGraph', () => this.#processFastAcyclicGraph());
652
+ let resolveOutputsReady;
653
+ let rejectOutputsReady;
654
+ const outputsReadyPromise = options.returnWhenGraphOutputsReady === true
655
+ ? new Promise((resolve, reject) => {
656
+ resolveOutputsReady = resolve;
657
+ rejectOutputsReady = reject;
658
+ })
659
+ : undefined;
660
+ let outputsWerePublishedEarly = false;
661
+ const completionPromise = (async () => {
662
+ try {
663
+ this.#profileRuntimeSync('initializeGraphRun', () => this.#initializeGraphRun(context, inputs, contextValues));
664
+ await this.#profileRuntimeAsync('loadProjectReferences', () => this.#loadProjectReferences());
665
+ this.#profileRuntimeSync('prepareNodeProcessContextBase', () => this.#prepareNodeProcessContextBase());
666
+ const shouldUseSeededExecutionPlan = this.#seededExecutionPlanForNextRun() != null;
667
+ this.#useSeededExecutionPlanOnNextRun = false;
668
+ if (!shouldUseSeededExecutionPlan) {
669
+ this.#preprocessGraph();
670
+ }
671
+ this.#prepareAsyncBranchTopology();
672
+ await this.#profileRuntimeAsync('emitGraphStart', () => this.#emitGraphStart());
673
+ await this.#profileRuntimeAsync('emitPreloadedNodeResults', () => this.#emitPreloadedNodeResults());
674
+ await this.#profileRuntimeAsync('waitUntilUnpaused', () => this.#waitUntilUnpaused());
675
+ if (this.#canUseFastAcyclicScheduler()) {
676
+ await this.#profileRuntimeAsync('processFastAcyclicGraph', () => this.#processFastAcyclicGraph());
677
+ }
678
+ else {
679
+ await this.#profileRuntimeAsync('processCompatibleGraph', () => this.#processCompatibleGraph());
680
+ }
681
+ if (options.returnWhenGraphOutputsReady === true &&
682
+ !this.#isSubProcessor &&
683
+ this.#managedAsyncBranches.hasPending) {
684
+ await this.#profileRuntimeAsync('throwIfGraphErrored', () => this.#throwIfGraphErrored(false));
685
+ // Publish a snapshot instead of the live root output object. In particular,
686
+ // the provisional cost must not occupy the root cost port before managed
687
+ // async branches contribute their cost during finalization.
688
+ const outputsReady = { ...this.#graphOutputs };
689
+ ensureGraphCostOutput(outputsReady, this.#totalCost);
690
+ await this.#emitter.emit('graphOutputsReady', this.#withExecution({ graph: this.#graph, outputs: outputsReady }));
691
+ outputsWerePublishedEarly = true;
692
+ resolveOutputsReady?.(outputsReady);
693
+ }
694
+ if (!this.#isSubProcessor) {
695
+ await this.#profileRuntimeAsync('drainManagedAsyncBranches', () => this.#managedAsyncBranches.drain());
696
+ }
697
+ await this.#profileRuntimeAsync('throwIfGraphErrored', () => this.#throwIfGraphErrored());
698
+ return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
595
699
  }
596
- else {
597
- await this.#profileRuntimeAsync('processCompatibleGraph', () => this.#processCompatibleGraph());
700
+ finally {
701
+ if (!this.#isSubProcessor) {
702
+ await this.#managedAsyncBranches?.drain();
703
+ }
704
+ this.#lifecycle.complete();
705
+ this.#cleanupTokenizerErrorListener();
706
+ await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
598
707
  }
599
- await this.#profileRuntimeAsync('throwIfGraphErrored', () => this.#throwIfGraphErrored());
600
- return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
601
- }
602
- finally {
603
- this.#lifecycle.complete();
604
- this.#cleanupTokenizerErrorListener();
605
- await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
708
+ })();
709
+ this.#runCompletionPromise = completionPromise;
710
+ if (outputsReadyPromise) {
711
+ // Without a real early publication, preserve ordinary processGraph semantics:
712
+ // resolve or reject only after terminal cleanup and finish listeners settle.
713
+ // The rejection callback also observes late failures after early publication.
714
+ void completionPromise.then((outputs) => {
715
+ if (!outputsWerePublishedEarly)
716
+ resolveOutputsReady?.(outputs);
717
+ }, (error) => {
718
+ if (!outputsWerePublishedEarly)
719
+ rejectOutputsReady?.(error);
720
+ });
721
+ return await outputsReadyPromise;
606
722
  }
723
+ return await completionPromise;
607
724
  }
608
725
  async #emitFinishIfNeeded() {
609
726
  if (!this.#lifecycle.claimRootFinish(this.#isSubProcessor)) {
@@ -616,9 +733,16 @@ export class GraphProcessor {
616
733
  this.#context = context;
617
734
  this.#graphInputs = inputs;
618
735
  this.#contextValues = contextValues;
619
- this.#rootRunId = this.#parent ? this.#parent.#rootRunId : nanoid();
620
- this.#graphRunId = nanoid();
621
- this.#parentGraphRunId = this.#parent ? this.#parent.#graphRunId : undefined;
736
+ if (this.#executionIdentityOverride) {
737
+ this.#rootRunId = this.#executionIdentityOverride.rootRunId;
738
+ this.#graphRunId = this.#executionIdentityOverride.graphRunId;
739
+ this.#parentGraphRunId = this.#executionIdentityOverride.parentGraphRunId;
740
+ }
741
+ else {
742
+ this.#rootRunId = this.#parent ? this.#parent.#rootRunId : nanoid();
743
+ this.#graphRunId = nanoid();
744
+ this.#parentGraphRunId = this.#parent ? this.#parent.#graphRunId : undefined;
745
+ }
622
746
  this.#cleanupTokenizerErrorListener();
623
747
  const unsubscribeTokenizerError = this.#context.tokenizer.on('error', (error) => {
624
748
  emitDetached(this.#emitter, 'error', { error });
@@ -630,13 +754,15 @@ export class GraphProcessor {
630
754
  this.#nodeProcessContextBase = {
631
755
  ...this.#context,
632
756
  abortGraph: (error) => {
633
- void this.abort(error === undefined, error);
757
+ void (this.#abortOwnerOverride ?? this).abort(error === undefined, error);
634
758
  },
635
759
  codeRunner: this.#context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
636
760
  contextValues: this.#contextValues,
637
761
  executionCache: this.#executionCache,
638
762
  executor: this.executor ?? 'nodejs',
639
763
  getGlobal: (id) => this.#globals.get(id),
764
+ getCachedStoredValue: (key) => this.#storedValueController.getCached(key),
765
+ getStoredValue: (key) => this.#storedValueController.get(key),
640
766
  getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
641
767
  graphInputNodeValues: this.#graphInputNodeValues,
642
768
  graphInputs: this.#graphInputs,
@@ -650,6 +776,7 @@ export class GraphProcessor {
650
776
  trace: (message) => {
651
777
  this.#emitTraceEvent(message);
652
778
  },
779
+ setStoredValue: (key, value) => this.#storedValueController.set(key, value),
653
780
  waitForGlobal: async (id) => {
654
781
  if (this.#globals.has(id)) {
655
782
  return this.#globals.get(id);
@@ -657,6 +784,7 @@ export class GraphProcessor {
657
784
  await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
658
785
  return this.#globals.get(id);
659
786
  },
787
+ waitForStoredValue: (key, signal) => this.#storedValueController.waitForSet(key, signal),
660
788
  };
661
789
  }
662
790
  #cleanupTokenizerErrorListener() {
@@ -670,6 +798,9 @@ export class GraphProcessor {
670
798
  }
671
799
  }
672
800
  async #emitGraphStart() {
801
+ if (this.#suppressGraphLifecycleEvents) {
802
+ return;
803
+ }
673
804
  if (!this.#isSubProcessor) {
674
805
  await this.#emitter.emit('start', this.#withExecution({
675
806
  contextValues: this.#contextValues,
@@ -688,6 +819,9 @@ export class GraphProcessor {
688
819
  if (!this.#nodeResults.has(node.id)) {
689
820
  continue;
690
821
  }
822
+ if (this.#suppressedPreloadedNodeIds.has(node.id)) {
823
+ continue;
824
+ }
691
825
  this.#emitTraceEvent(`Node ${node.title} has preloaded data`);
692
826
  await this.#emitter.emit('nodeStart', this.#withExecution({
693
827
  node,
@@ -831,35 +965,44 @@ export class GraphProcessor {
831
965
  return erroredNodeAttachedData.races == null || erroredNodeAttachedData.races.completed === false;
832
966
  });
833
967
  }
834
- #createGraphError(erroredNodes) {
968
+ #createGraphError(erroredNodes, managedAsyncFailures = []) {
835
969
  if (this.#lifecycle.abortError) {
836
970
  return this.#lifecycle.getAbortError();
837
971
  }
838
- const message = `Graph ${this.#graph.metadata.name} (${this.#graph.metadata.id}) failed to process due to errors in nodes:\n${erroredNodes
839
- .map(([nodeId]) => `- ${this.#nodesById[nodeId].title} (${nodeId})`)
972
+ const errors = [
973
+ ...erroredNodes.map(([nodeId, error]) => ({ error, node: this.#nodesById[nodeId] })),
974
+ ...managedAsyncFailures.flatMap((failure) => failure.nodeErrors.length > 0 ? failure.nodeErrors : [{ error: failure.error, node: failure.triggerNode }]),
975
+ ];
976
+ const message = `Graph ${this.#graph.metadata.name} (${this.#graph.metadata.id}) failed to process due to errors in nodes:\n${errors
977
+ .map(({ node }) => `- ${node.title} (${node.id})`)
840
978
  .join('\n')}`;
841
- if (erroredNodes.length === 1) {
842
- const [, nodeError] = erroredNodes[0];
843
- return new Error(message, { cause: nodeError });
979
+ if (errors.length === 1) {
980
+ return new Error(message, { cause: errors[0].error });
844
981
  }
845
- return new AggregateError(erroredNodes.map(([, nodeError]) => nodeError), message);
982
+ return new AggregateError(errors.map(({ error }) => error), message);
846
983
  }
847
- async #throwIfGraphErrored() {
984
+ async #throwIfGraphErrored(includeManagedAsyncFailures = true) {
848
985
  const erroredNodes = this.#getUnhandledErroredNodes();
849
- if (!erroredNodes.length || this.#lifecycle.abortSuccessful) {
986
+ const managedAsyncFailures = includeManagedAsyncFailures ? this.#managedAsyncBranchFailures : [];
987
+ if ((!erroredNodes.length && !managedAsyncFailures.length) || this.#lifecycle.abortSuccessful) {
850
988
  return;
851
989
  }
852
- const error = this.#createGraphError(erroredNodes);
853
- await this.#emitter.emit('graphError', this.#withExecution({ graph: this.#graph, error }));
854
- if (!this.#isSubProcessor) {
990
+ const error = this.#createGraphError(erroredNodes, managedAsyncFailures);
991
+ if (!this.#suppressGraphLifecycleEvents) {
992
+ await this.#emitter.emit('graphError', this.#withExecution({ graph: this.#graph, error }));
993
+ }
994
+ if (!this.#isSubProcessor && !this.#suppressGraphLifecycleEvents) {
855
995
  await this.#emitter.emit('error', { error });
856
996
  }
857
997
  throw error;
858
998
  }
859
999
  async #finalizeGraphRun() {
860
- ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
861
1000
  const outputValues = this.#graphOutputs;
862
1001
  this.#lifecycle.complete();
1002
+ if (this.#suppressGraphLifecycleEvents) {
1003
+ return outputValues;
1004
+ }
1005
+ ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
863
1006
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
864
1007
  if (!this.#isSubProcessor) {
865
1008
  await this.#emitter.emit('done', { results: outputValues });
@@ -913,7 +1056,13 @@ export class GraphProcessor {
913
1056
  async #fetchNodeDataAndProcessNode(node) {
914
1057
  const profileStart = this.#startRuntimeProfile();
915
1058
  try {
916
- if (this.#currentlyProcessing.has(node.id) || this.#queuedNodes.has(node.id)) {
1059
+ if (this.#currentlyProcessing.has(node.id)) {
1060
+ return;
1061
+ }
1062
+ if (this.#propagateCompletedContinuationNode(node, true)) {
1063
+ return;
1064
+ }
1065
+ if (this.#queuedNodes.has(node.id)) {
917
1066
  return;
918
1067
  }
919
1068
  if (this.#nodeResults.has(node.id) || this.#erroredNodes.has(node.id)) {
@@ -961,6 +1110,10 @@ export class GraphProcessor {
961
1110
  const inputNodesProfileStart = this.#startRuntimeProfile();
962
1111
  const inputNodes = getInputNodesTo(this.#executionState, node);
963
1112
  this.#finishRuntimeProfile('getInputNodesTo', inputNodesProfileStart);
1113
+ const continuedOutputNodes = this.#propagateCompletedContinuationNode(node, queueOutputNodes);
1114
+ if (continuedOutputNodes) {
1115
+ return continuedOutputNodes;
1116
+ }
964
1117
  if (this.#shouldSkipNodeProcessing(node, inputNodes)) {
965
1118
  return [];
966
1119
  }
@@ -1024,11 +1177,31 @@ export class GraphProcessor {
1024
1177
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
1025
1178
  if (queueOutputNodes && processResult.shouldQueueOutputNodes) {
1026
1179
  const queueOutputsProfileStart = this.#startRuntimeProfile();
1027
- this.#queueOutputNodes(node, outputNodes.nodes);
1180
+ if (node.type === 'startBackgroundBranch') {
1181
+ this.#startManagedAsyncBranch(node);
1182
+ }
1183
+ else {
1184
+ this.#queueOutputNodes(node, outputNodes.nodes);
1185
+ }
1028
1186
  this.#finishRuntimeProfile('queueOutputNodes', queueOutputsProfileStart);
1029
1187
  }
1030
1188
  return processResult.shouldQueueOutputNodes ? outputNodes.nodes : [];
1031
1189
  }
1190
+ #propagateCompletedContinuationNode(node, queueOutputNodes) {
1191
+ const ownerLLMNodeId = this.#continuationCompletionOwnerByNodeId.get(node.id);
1192
+ if (ownerLLMNodeId == null || !this.#nodeResults.has(ownerLLMNodeId)) {
1193
+ return undefined;
1194
+ }
1195
+ this.#continuationCompletionOwnerByNodeId.delete(node.id);
1196
+ const outputNodes = getOutputNodesFrom(this.#executionState, node);
1197
+ const attachedData = this.#getAttachedDataTo(node);
1198
+ this.#registerNodeInActiveLoop(node, attachedData);
1199
+ this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
1200
+ if (queueOutputNodes && node.type !== 'startBackgroundBranch') {
1201
+ this.#queueOutputNodes(node, outputNodes.nodes);
1202
+ }
1203
+ return outputNodes.nodes;
1204
+ }
1032
1205
  #shouldSkipNodeProcessing(node, inputNodes) {
1033
1206
  if (this.#ignoreNodes.has(node.id)) {
1034
1207
  this.#emitTraceEvent(`Node ${node.title} is ignored`);
@@ -1167,6 +1340,153 @@ export class GraphProcessor {
1167
1340
  await this.#processNodeIfAllInputsAvailable(outputNode);
1168
1341
  }));
1169
1342
  }
1343
+ #startManagedAsyncBranch(triggerNode) {
1344
+ const outputs = this.#nodeResults.get(triggerNode.id);
1345
+ if (!outputs) {
1346
+ return;
1347
+ }
1348
+ const activeOutputPortIds = this.#getActiveOutputPortIds(triggerNode);
1349
+ const hasRunnableOutput = [...activeOutputPortIds].some((portId) => {
1350
+ const output = outputs[portId];
1351
+ return output != null && output.type !== 'control-flow-excluded';
1352
+ });
1353
+ if (!hasRunnableOutput) {
1354
+ return;
1355
+ }
1356
+ const plan = this.#getActiveAsyncBranchPlan(triggerNode, activeOutputPortIds);
1357
+ if (!plan) {
1358
+ return;
1359
+ }
1360
+ const root = this.getRootProcessor();
1361
+ root.#managedAsyncBranches ??= new ManagedAsyncBranches();
1362
+ const queueKey = `${this.#project.metadata?.id ?? 'project'}:${this.#graph.metadata?.id ?? 'graph'}:${triggerNode.id}`;
1363
+ let branchProcessor;
1364
+ root.#managedAsyncBranches.enqueue(queueKey, async () => {
1365
+ await this.#runManagedAsyncBranch(triggerNode, outputs, plan, (processor) => {
1366
+ branchProcessor = processor;
1367
+ });
1368
+ }, (error) => {
1369
+ root.#recordManagedAsyncBranchFailure(triggerNode, branchProcessor, error);
1370
+ });
1371
+ }
1372
+ async #runManagedAsyncBranch(triggerNode, triggerOutputs, plan, onProcessorCreated) {
1373
+ const root = this.getRootProcessor();
1374
+ const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
1375
+ const isRootGraphOrigin = !sameGraphOwner.#isSubProcessor;
1376
+ if (root.#abortController.signal.aborted) {
1377
+ throw createGraphAbortErrorFromSignal(root.#abortController.signal, 'Async branch aborted before it started');
1378
+ }
1379
+ const graphId = plan.graph.metadata?.id;
1380
+ if (!graphId) {
1381
+ throw new Error('Cannot start an async branch because the current graph has no ID.');
1382
+ }
1383
+ const branchRuntimeCache = {
1384
+ ...this.#runtimeCache,
1385
+ graphBoundaries: undefined,
1386
+ loadedProjects: { ...this.#loadedProjects },
1387
+ };
1388
+ const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
1389
+ cacheLoadedProjects: true,
1390
+ captureNodeTimings: this.#captureNodeTimings,
1391
+ concurrency: this.#concurrency,
1392
+ executionPlanCacheMode: this.#executionPlanCacheMode,
1393
+ runtimeCache: branchRuntimeCache,
1394
+ runtimeProfiler: this.#runtimeProfiler,
1395
+ scheduler: this.#scheduler,
1396
+ [graphProcessorGraphOverride]: plan.graph,
1397
+ [consumedAsyncBranchTriggerOverride]: triggerNode.id,
1398
+ });
1399
+ onProcessorCreated(processor);
1400
+ processor.executor = this.executor;
1401
+ processor.#isSubProcessor = true;
1402
+ processor.#executionCache = this.#executionCache;
1403
+ processor.#externalFunctions = this.#externalFunctions;
1404
+ processor.#contextValues = this.#contextValues;
1405
+ processor.#parent = sameGraphOwner;
1406
+ processor.#abortOwnerOverride = root;
1407
+ processor.#suppressGraphPartialOutputs = true;
1408
+ processor.#globals = this.#globals;
1409
+ processor.#storedValueController = this.#storedValueController;
1410
+ processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
1411
+ processor.#executor = this.#executor;
1412
+ processor.#suppressGraphLifecycleEvents = isRootGraphOrigin;
1413
+ processor.#sharedRunStateOverride = {
1414
+ attachedNodeData: this.#attachedNodeData,
1415
+ graphInputNodeValues: this.#graphInputNodeValues,
1416
+ // Async branches cannot contain Graph Output nodes. Keep their synthetic
1417
+ // boundary outputs private so branch finalization cannot seed the root's
1418
+ // derived cost output before the root has accumulated every path.
1419
+ graphOutputs: {},
1420
+ };
1421
+ const branchRunToNodeIds = this.runToNodeIds?.filter((nodeId) => plan.nodeIds.has(nodeId));
1422
+ processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
1423
+ processor.#executionIdentityOverride = isRootGraphOrigin
1424
+ ? {
1425
+ rootRunId: this.#rootRunId,
1426
+ graphRunId: this.#graphRunId,
1427
+ parentGraphRunId: this.#parentGraphRunId,
1428
+ }
1429
+ : {
1430
+ rootRunId: root.#rootRunId,
1431
+ graphRunId: nanoid(),
1432
+ parentGraphRunId: sameGraphOwner.#graphRunId,
1433
+ };
1434
+ processor.preloadNodeData(triggerNode.id, triggerOutputs);
1435
+ processor.#suppressedPreloadedNodeIds.add(triggerNode.id);
1436
+ const unwireEvents = wireSubprocessorEvents(processor, root.#emitter, {
1437
+ autoCleanup: false,
1438
+ isPaused: () => root.#lifecycle.isPaused,
1439
+ pause: () => {
1440
+ void root.pause();
1441
+ },
1442
+ resume: () => {
1443
+ void root.resume();
1444
+ },
1445
+ });
1446
+ const unwireLifecycle = wireSubprocessorLifecycle(processor, {
1447
+ autoCleanup: false,
1448
+ signal: sameGraphOwner === root ? undefined : sameGraphOwner.#abortController.signal,
1449
+ parentAbortSignal: root.#abortController.signal,
1450
+ onParentPause: (listener) => {
1451
+ root.on('pause', listener);
1452
+ return () => {
1453
+ root.off('pause', listener);
1454
+ };
1455
+ },
1456
+ onParentResume: (listener) => {
1457
+ root.on('resume', listener);
1458
+ return () => {
1459
+ root.off('resume', listener);
1460
+ };
1461
+ },
1462
+ });
1463
+ root.#subprocessors.add(processor);
1464
+ try {
1465
+ if (root.#lifecycle.isPaused) {
1466
+ processor.pause();
1467
+ }
1468
+ await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
1469
+ }
1470
+ finally {
1471
+ root.#totalCost += processor.#totalCost;
1472
+ unwireLifecycle();
1473
+ unwireEvents();
1474
+ root.#subprocessors.delete(processor);
1475
+ }
1476
+ }
1477
+ #recordManagedAsyncBranchFailure(triggerNode, processor, error) {
1478
+ const nodeErrors = processor && processor.#erroredNodes
1479
+ ? [...processor.#erroredNodes.entries()].flatMap(([nodeId, nodeError]) => {
1480
+ const node = processor.#nodesById[nodeId];
1481
+ return node ? [{ error: nodeError, node }] : [];
1482
+ })
1483
+ : [];
1484
+ this.#managedAsyncBranchFailures.push({
1485
+ error: getError(error),
1486
+ nodeErrors,
1487
+ triggerNode,
1488
+ });
1489
+ }
1170
1490
  #getAttachedDataTo(node) {
1171
1491
  const nodeId = typeof node === 'string' ? node : node.id;
1172
1492
  let nodeData = this.#attachedNodeData.get(nodeId);
@@ -1184,7 +1504,10 @@ export class GraphProcessor {
1184
1504
  return { processId, shouldQueueOutputNodes: false };
1185
1505
  }
1186
1506
  const frozenOutputs = this.#resolveFrozenNodeOutputs(node, inputValues, processId);
1187
- if (frozenOutputs) {
1507
+ if (frozenOutputs && node.type === 'startBackgroundBranch') {
1508
+ await this.#nodeErrored(node, new Error('Start Async Branch cannot use frozen outputs because replaying it could repeat async side effects.'), processId);
1509
+ }
1510
+ else if (frozenOutputs) {
1188
1511
  await this.#processFrozenNode(node, processId, inputValues, frozenOutputs);
1189
1512
  }
1190
1513
  else if (node.isSplitRun) {
@@ -1234,20 +1557,24 @@ export class GraphProcessor {
1234
1557
  this.#nodeResults.set(node.id, outputValues);
1235
1558
  this.#visitedNodes.add(node.id);
1236
1559
  this.#accumulateCost(outputValues);
1237
- this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
1560
+ await this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
1238
1561
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
1239
1562
  node,
1240
1563
  outputs: outputValues,
1241
1564
  processId,
1242
1565
  }, this.#finishNodeTiming(timingStart))));
1243
1566
  }
1244
- #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
1245
- const setGlobalEffect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
1246
- if (!setGlobalEffect) {
1567
+ async #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
1568
+ const effect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
1569
+ if (!effect) {
1570
+ return;
1571
+ }
1572
+ if (effect.type === 'setStoredValue') {
1573
+ await this.#storedValueController.seed(effect.key, effect.value);
1247
1574
  return;
1248
1575
  }
1249
- this.#globals.set(setGlobalEffect.variableId, setGlobalEffect.value);
1250
- emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id: setGlobalEffect.variableId, value: setGlobalEffect.value, processId }));
1576
+ this.#globals.set(effect.variableId, effect.value);
1577
+ emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id: effect.variableId, value: effect.value, processId }));
1251
1578
  }
1252
1579
  async #processNormalNode(node, processId, inputValues) {
1253
1580
  // Use awaited emit (not emitDetached) so that listeners can yield to the
@@ -1255,9 +1582,7 @@ export class GraphProcessor {
1255
1582
  await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: inputValues, processId }));
1256
1583
  const timingStart = this.#startNodeTiming();
1257
1584
  try {
1258
- const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => {
1259
- emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs: partialOutputs, index, processId }));
1260
- });
1585
+ const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => this.#emitNodePartialOutput(node, partialOutputs, index, processId));
1261
1586
  this.#nodeResults.set(node.id, outputValues);
1262
1587
  this.#visitedNodes.add(node.id);
1263
1588
  this.#accumulateCost(outputValues);
@@ -1283,6 +1608,9 @@ export class GraphProcessor {
1283
1608
  await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({ node, error, processId }, durationMs, splitRunDurationMs)));
1284
1609
  this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);
1285
1610
  }
1611
+ #emitNodePartialOutput(node, outputs, index, processId) {
1612
+ emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs, index, processId }));
1613
+ }
1286
1614
  #getErrorExclusionReason(node, error, processId) {
1287
1615
  if (this.#getAttachedDataTo(node).races?.completed) {
1288
1616
  return RACE_LOSER_EXCLUSION_REASON;
@@ -1391,39 +1719,52 @@ export class GraphProcessor {
1391
1719
  if (this.#abortController.signal.aborted) {
1392
1720
  nodeAbortController.abort(getAbortSignalReason(this.#abortController.signal));
1393
1721
  }
1394
- const createContextProfileStart = this.#startRuntimeProfile();
1395
- const context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput);
1396
- this.#finishRuntimeProfile('createNodeProcessContext', createContextProfileStart);
1397
- let results;
1722
+ let continuationFinalized = false;
1398
1723
  try {
1724
+ const createContextProfileStart = this.#startRuntimeProfile();
1725
+ let context;
1726
+ try {
1727
+ context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput);
1728
+ }
1729
+ finally {
1730
+ this.#finishRuntimeProfile('createNodeProcessContext', createContextProfileStart);
1731
+ }
1399
1732
  await this.#waitUntilUnpaused();
1400
1733
  const implementationProfileStart = this.#startRuntimeProfile();
1734
+ let results;
1401
1735
  try {
1402
1736
  results = await instance.process(inputValues, context);
1403
1737
  }
1404
1738
  finally {
1405
1739
  this.#finishRuntimeProfile('nodeImplementation', implementationProfileStart);
1406
1740
  }
1741
+ const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
1742
+ if (nodeAbortController.signal.aborted) {
1743
+ if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
1744
+ this.#successfulAbortTerminalProcessIds.add(processId);
1745
+ return results;
1746
+ }
1747
+ else {
1748
+ throw createGraphAbortError(abortReason, 'Aborted');
1749
+ }
1750
+ }
1751
+ this.#finalizeToolCallContinuation(processId, index, results);
1752
+ continuationFinalized = true;
1753
+ return results;
1407
1754
  }
1408
1755
  finally {
1409
- this.#unregisterNodeAbortController(node.id, nodeAbortController);
1410
- }
1411
- const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
1412
- if (nodeAbortController.signal.aborted) {
1413
- if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
1414
- this.#successfulAbortTerminalProcessIds.add(processId);
1415
- }
1416
- else {
1417
- throw createGraphAbortError(abortReason, 'Aborted');
1756
+ if (!continuationFinalized) {
1757
+ this.#discardToolCallContinuation(processId, index);
1418
1758
  }
1759
+ this.#unregisterNodeAbortController(node.id, nodeAbortController);
1419
1760
  }
1420
- return results;
1421
1761
  }
1422
1762
  #getTokenizer() {
1423
1763
  return this.#context.tokenizer;
1424
1764
  }
1425
1765
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput) {
1426
1766
  const plugin = this.#registry.getPluginFor(node.type);
1767
+ const toolCallContinuation = this.#getToolCallContinuationContext(node, nodeAbortController.signal, processId, index);
1427
1768
  return buildNodeProcessContext({
1428
1769
  activeOutputPortIds: this.#getActiveOutputPortIds(node),
1429
1770
  attachedData: this.#getAttachedDataTo(node),
@@ -1441,10 +1782,17 @@ export class GraphProcessor {
1441
1782
  },
1442
1783
  processId,
1443
1784
  requestUserInput: async (inputStrings, renderingType) => this.#requestUserInput(node, inputStrings, inputValues, renderingType, processId),
1785
+ reportProgress: (progress) => {
1786
+ const normalized = normalizeGraphProgress(progress);
1787
+ if (normalized) {
1788
+ emitDetached(this.#emitter, 'progress', this.#withExecution({ node, processId, progress: normalized }));
1789
+ }
1790
+ },
1444
1791
  setGlobal: (id, value) => {
1445
1792
  this.#globals.set(id, value);
1446
1793
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
1447
1794
  },
1795
+ toolCallContinuation,
1448
1796
  waitEvent: async (event) => {
1449
1797
  return new Promise((resolve, reject) => {
1450
1798
  const abortListener = () => {
@@ -1462,7 +1810,703 @@ export class GraphProcessor {
1462
1810
  },
1463
1811
  });
1464
1812
  }
1813
+ #getToolCallContinuationContext(node, llmSignal, processId, index) {
1814
+ if (node.type !== 'llmChatV2') {
1815
+ return undefined;
1816
+ }
1817
+ const connections = this.#getEffectiveConnections();
1818
+ const resolution = resolveToolContinuationConnection({
1819
+ connections,
1820
+ nodes: Object.values(this.#nodesById),
1821
+ }, node.id);
1822
+ if (resolution.kind === 'none') {
1823
+ return undefined;
1824
+ }
1825
+ if (resolution.kind === 'ambiguous') {
1826
+ throw new Error(`LLM Chat "${node.title}" has ${resolution.candidates.length} connected Delegate Tool Call nodes. Auto-continue requires exactly one Delegate Tool Call connection.`);
1827
+ }
1828
+ const delegateNode = resolution.delegateNode;
1829
+ const invocationKey = this.#getToolCallContinuationInvocationKey(processId, index);
1830
+ const invocation = {
1831
+ delegateNode,
1832
+ latestOutputs: new Map(),
1833
+ llmNodeId: node.id,
1834
+ released: false,
1835
+ };
1836
+ this.#toolCallContinuationInvocations.set(invocationKey, invocation);
1837
+ return {
1838
+ run: (toolCalls, assistantMessage) => this.#runToolCallContinuationRound(node, invocation, toolCalls, assistantMessage, llmSignal),
1839
+ release: () => {
1840
+ invocation.released = true;
1841
+ },
1842
+ };
1843
+ }
1844
+ #getToolCallContinuationInvocationKey(processId, index) {
1845
+ return `${processId}:${index}`;
1846
+ }
1847
+ #finalizeToolCallContinuation(processId, index, nodeOutputs) {
1848
+ const invocationKey = this.#getToolCallContinuationInvocationKey(processId, index);
1849
+ const invocation = this.#toolCallContinuationInvocations.get(invocationKey);
1850
+ this.#toolCallContinuationInvocations.delete(invocationKey);
1851
+ if (!invocation || invocation.released) {
1852
+ return;
1853
+ }
1854
+ if (invocation.latestOutputs.size === 0) {
1855
+ const replayedCalls = nodeOutputs['function-calls'];
1856
+ if (replayedCalls?.type === 'object[]' &&
1857
+ replayedCalls.value.length > 0 &&
1858
+ replayedCalls.value.every(isDelegatedToolCallRecord)) {
1859
+ invocation.latestOutputs.set(invocation.delegateNode.id, buildDelegatedToolCallOutputs(replayedCalls.value));
1860
+ }
1861
+ }
1862
+ for (const [nodeId, outputs] of invocation.latestOutputs) {
1863
+ this.#nodeResults.set(nodeId, outputs);
1864
+ this.#visitedNodes.add(nodeId);
1865
+ this.#remainingNodes.delete(nodeId);
1866
+ this.#continuationCompletionOwnerByNodeId.set(nodeId, invocation.llmNodeId);
1867
+ }
1868
+ }
1869
+ #discardToolCallContinuation(processId, index) {
1870
+ this.#toolCallContinuationInvocations.delete(this.#getToolCallContinuationInvocationKey(processId, index));
1871
+ }
1872
+ async #runToolCallContinuationRound(llmNode, invocation, toolCalls, assistantMessage, llmSignal) {
1873
+ if (toolCalls.length === 0) {
1874
+ return [];
1875
+ }
1876
+ if (this.#abortController.signal.aborted) {
1877
+ throw createGraphAbortErrorFromSignal(this.#abortController.signal);
1878
+ }
1879
+ const { delegateNode } = invocation;
1880
+ const processIds = toolCalls.map(() => nanoid());
1881
+ const inputValuesByCall = toolCalls.map((toolCall) => ({
1882
+ [DELEGATE_TOOL_CALL_INPUT_ID]: {
1883
+ type: 'object',
1884
+ value: toolCall,
1885
+ },
1886
+ }));
1887
+ const nodeAbortControllers = toolCalls.map(() => this.#newAbortController());
1888
+ nodeAbortControllers.forEach((controller) => this.#registerNodeAbortController(delegateNode.id, controller));
1889
+ const abortAllCalls = (reason) => {
1890
+ for (const controller of nodeAbortControllers) {
1891
+ if (!controller.signal.aborted) {
1892
+ controller.abort(reason);
1893
+ }
1894
+ }
1895
+ };
1896
+ const abortFromLLM = () => {
1897
+ abortAllCalls(getAbortSignalReason(llmSignal));
1898
+ };
1899
+ llmSignal.addEventListener('abort', abortFromLLM, { once: true });
1900
+ if (this.#abortController.signal.aborted) {
1901
+ abortAllCalls(getAbortSignalReason(this.#abortController.signal));
1902
+ }
1903
+ else if (llmSignal.aborted) {
1904
+ abortFromLLM();
1905
+ }
1906
+ try {
1907
+ await this.#waitUntilUnpaused();
1908
+ const abortedController = nodeAbortControllers.find((controller) => controller.signal.aborted);
1909
+ if (abortedController) {
1910
+ throw createGraphAbortErrorFromSignal(abortedController.signal, 'Delegate Tool Call aborted');
1911
+ }
1912
+ const hasAssistantMessage = assistantMessage.trim().length > 0;
1913
+ const branchContext = this.#createContinuationBranchContext();
1914
+ const canRunContinuationBranches = !branchContext.unsafeNodeIds.has(llmNode.id) && !branchContext.unsafeNodeIds.has(delegateNode.id);
1915
+ const assistantOutputs = {
1916
+ ['assistant-message']: {
1917
+ type: 'string',
1918
+ value: assistantMessage,
1919
+ },
1920
+ };
1921
+ const preToolOutputPorts = new Set(['assistant-message']);
1922
+ const hasActivePreToolBranch = hasAssistantMessage && this.#getActiveOutputPortIds(delegateNode).has('assistant-message');
1923
+ const continuationBranchBoundaries = new Set([llmNode.id, ...this.#currentlyProcessing]);
1924
+ // Validate round-level configuration before any of the parallel calls can
1925
+ // start side effects. Preserve one real Delegate error run for diagnostics.
1926
+ try {
1927
+ if (this.#nodeResults.has(delegateNode.id) ||
1928
+ this.#resolveFrozenNodeOutputs(delegateNode, inputValuesByCall[0], processIds[0])) {
1929
+ throw new Error(`Delegate Tool Call "${delegateNode.title}" is the active auto-continuation handler and cannot use preloaded or frozen outputs. Clear its preload or unfreeze it before running this graph.`);
1930
+ }
1931
+ if (hasActivePreToolBranch) {
1932
+ if (!canRunContinuationBranches) {
1933
+ throw new Error(`Delegate Tool Call "${delegateNode.title}" cannot fire its pre-tool Message branch because the LLM/Delegate continuation is inside an unsupported cycle, race, or loop.`);
1934
+ }
1935
+ this.#buildContinuationBranchPlan(delegateNode, assistantOutputs, preToolOutputPorts, new Map(), continuationBranchBoundaries, branchContext, true);
1936
+ }
1937
+ }
1938
+ catch (error) {
1939
+ const processId = processIds[0];
1940
+ const inputValues = inputValuesByCall[0];
1941
+ await this.#emitter.emit('nodeStart', this.#withExecution({ node: delegateNode, inputs: inputValues, processId }));
1942
+ const timingStart = this.#startNodeTiming();
1943
+ await this.#nodeErrored(delegateNode, error, processId, this.#finishNodeTiming(timingStart));
1944
+ throw error;
1945
+ }
1946
+ let firstFailure;
1947
+ let hasFailure = false;
1948
+ const abortSiblingOnFailure = async (work) => {
1949
+ try {
1950
+ return await work;
1951
+ }
1952
+ catch (error) {
1953
+ if (!hasFailure) {
1954
+ hasFailure = true;
1955
+ firstFailure = error;
1956
+ }
1957
+ abortAllCalls(error);
1958
+ throw error;
1959
+ }
1960
+ };
1961
+ const runInvocation = async (toolCall, toolCallIndex) => {
1962
+ const processId = processIds[toolCallIndex];
1963
+ const inputValues = inputValuesByCall[toolCallIndex];
1964
+ const nodeAbortController = nodeAbortControllers[toolCallIndex];
1965
+ let timingStart;
1966
+ let delegateStarted = false;
1967
+ let delegateFinished = false;
1968
+ try {
1969
+ await this.#waitUntilUnpaused();
1970
+ if (nodeAbortController.signal.aborted) {
1971
+ throw createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Delegate Tool Call aborted');
1972
+ }
1973
+ await this.#emitter.emit('nodeStart', this.#withExecution({ node: delegateNode, inputs: inputValues, processId }));
1974
+ delegateStarted = true;
1975
+ timingStart = this.#startNodeTiming();
1976
+ const delegateContext = this.#createNodeProcessContext(delegateNode, inputValues, 0, processId, nodeAbortController, (node, partialOutputs, index) => this.#emitNodePartialOutput(node, partialOutputs, index, processId));
1977
+ if (hasAssistantMessage) {
1978
+ emitDetached(this.#emitter, 'partialOutput', this.#withExecution({
1979
+ node: delegateNode,
1980
+ outputs: assistantOutputs,
1981
+ index: 0,
1982
+ processId,
1983
+ }));
1984
+ }
1985
+ let preToolBranchPromise;
1986
+ if (hasActivePreToolBranch) {
1987
+ preToolBranchPromise = this.#runContinuationOutputBranch(delegateNode, assistantOutputs, preToolOutputPorts, nodeAbortController.signal, new Map(), continuationBranchBoundaries, branchContext, true, true);
1988
+ }
1989
+ // Start tool work without waiting for the early Message branch. The
1990
+ // branch and every sibling Delegate invocation remain independent.
1991
+ const invocationWork = await Promise.allSettled([
1992
+ abortSiblingOnFailure(delegateToolCall(toolCall, delegateContext, delegateNode.data)),
1993
+ abortSiblingOnFailure(preToolBranchPromise ?? Promise.resolve({ graphOutputWrites: {}, nodeOutputs: new Map() })),
1994
+ ]);
1995
+ const toolOutcome = invocationWork[0];
1996
+ const preToolBranchOutcome = invocationWork[1];
1997
+ if (toolOutcome.status === 'rejected')
1998
+ throw toolOutcome.reason;
1999
+ if (preToolBranchOutcome.status === 'rejected')
2000
+ throw preToolBranchOutcome.reason;
2001
+ const toolResult = toolOutcome.value;
2002
+ const preToolBranch = preToolBranchOutcome.value;
2003
+ if (nodeAbortController.signal.aborted) {
2004
+ throw createGraphAbortErrorFromSignal(nodeAbortController.signal, 'Delegate Tool Call aborted');
2005
+ }
2006
+ const outputs = buildDelegatedToolCallOutputs([toolResult.record], hasAssistantMessage ? assistantMessage : undefined, toolResult.cost);
2007
+ this.#accumulateCost(outputs);
2008
+ await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
2009
+ node: delegateNode,
2010
+ outputs,
2011
+ processId,
2012
+ }, this.#finishNodeTiming(timingStart))));
2013
+ delegateFinished = true;
2014
+ const finalOutputPorts = new Set(['output', 'message']);
2015
+ const finalBranch = canRunContinuationBranches
2016
+ ? await this.#runContinuationOutputBranch(delegateNode, outputs, finalOutputPorts, nodeAbortController.signal, preToolBranch.nodeOutputs, continuationBranchBoundaries, branchContext, false, true)
2017
+ : { graphOutputWrites: {}, nodeOutputs: new Map() };
2018
+ return { finalBranch, outputs, preToolBranch, toolResult };
2019
+ }
2020
+ catch (error) {
2021
+ if (delegateStarted && !delegateFinished) {
2022
+ await this.#nodeErrored(delegateNode, error, processId, this.#finishNodeTiming(timingStart));
2023
+ }
2024
+ throw error;
2025
+ }
2026
+ };
2027
+ const toolWorkOutcomes = await Promise.allSettled(toolCalls.map((toolCall, toolCallIndex) => abortSiblingOnFailure(runInvocation(toolCall, toolCallIndex))));
2028
+ if (hasFailure) {
2029
+ throw firstFailure;
2030
+ }
2031
+ const invocationResults = toolWorkOutcomes.map((outcome) => {
2032
+ if (outcome.status === 'rejected') {
2033
+ throw outcome.reason;
2034
+ }
2035
+ return outcome.value;
2036
+ });
2037
+ for (const result of invocationResults) {
2038
+ invocation.latestOutputs.set(delegateNode.id, result.outputs);
2039
+ for (const branch of [result.preToolBranch, result.finalBranch]) {
2040
+ this.#commitContinuationGraphOutputs(branch.graphOutputWrites);
2041
+ for (const [nodeId, outputs] of branch.nodeOutputs) {
2042
+ invocation.latestOutputs.set(nodeId, outputs);
2043
+ }
2044
+ }
2045
+ }
2046
+ return invocationResults.map(({ toolResult }) => ({
2047
+ message: toolResult.message,
2048
+ record: toolResult.record,
2049
+ }));
2050
+ }
2051
+ finally {
2052
+ llmSignal.removeEventListener('abort', abortFromLLM);
2053
+ nodeAbortControllers.forEach((controller) => this.#unregisterNodeAbortController(delegateNode.id, controller));
2054
+ }
2055
+ }
2056
+ async #runContinuationOutputBranch(sourceNode, sourceOutputs, activeOutputPortIds, signal, availableNodeOutputs, excludedNodeIds, branchContext, failOnUnsafeReadyNode = false, deferGraphOutputCommit = false) {
2057
+ if (signal.aborted) {
2058
+ throw createGraphAbortErrorFromSignal(signal, 'Tool continuation branch aborted');
2059
+ }
2060
+ const branchPlan = this.#buildContinuationBranchPlan(sourceNode, sourceOutputs, activeOutputPortIds, availableNodeOutputs, excludedNodeIds, branchContext, failOnUnsafeReadyNode);
2061
+ if (!branchPlan) {
2062
+ return { graphOutputWrites: {}, nodeOutputs: new Map() };
2063
+ }
2064
+ const graphId = branchPlan.graph.metadata?.id;
2065
+ if (!graphId) {
2066
+ throw new Error('Cannot execute a tool continuation branch because the current graph has no ID.');
2067
+ }
2068
+ const branchRuntimeCache = {
2069
+ ...this.#runtimeCache,
2070
+ graphBoundaries: undefined,
2071
+ loadedProjects: { ...this.#loadedProjects },
2072
+ };
2073
+ const branchGraphOutputs = createGraphOutputsOverlay(this.#graphOutputs);
2074
+ const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
2075
+ cacheLoadedProjects: true,
2076
+ captureNodeTimings: this.#captureNodeTimings,
2077
+ concurrency: this.#concurrency,
2078
+ executionPlanCacheMode: this.#executionPlanCacheMode,
2079
+ runtimeCache: branchRuntimeCache,
2080
+ runtimeProfiler: this.#runtimeProfiler,
2081
+ scheduler: this.#scheduler,
2082
+ [graphProcessorGraphOverride]: branchPlan.graph,
2083
+ });
2084
+ processor.executor = this.executor;
2085
+ processor.#isSubProcessor = true;
2086
+ processor.#executionCache = this.#executionCache;
2087
+ processor.#externalFunctions = this.#externalFunctions;
2088
+ processor.#contextValues = this.#contextValues;
2089
+ processor.#parent = this;
2090
+ processor.#abortOwnerOverride = this.#abortOwnerOverride ?? this;
2091
+ processor.#sameGraphRunOwnerOverride = this.#sameGraphRunOwnerOverride ?? this;
2092
+ processor.#globals = this.#globals;
2093
+ processor.#storedValueController = this.#storedValueController;
2094
+ processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
2095
+ processor.#executor = this.#executor;
2096
+ processor.#suppressGraphLifecycleEvents = true;
2097
+ processor.#sharedRunStateOverride = {
2098
+ attachedNodeData: this.#attachedNodeData,
2099
+ graphInputNodeValues: this.#graphInputNodeValues,
2100
+ graphOutputs: branchGraphOutputs.view,
2101
+ };
2102
+ const branchNodeIds = new Set(branchPlan.graph.nodes.map((node) => node.id));
2103
+ const branchRunToNodeIds = this.runToNodeIds?.filter((nodeId) => branchNodeIds.has(nodeId));
2104
+ processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
2105
+ processor.#executionIdentityOverride = {
2106
+ rootRunId: this.#rootRunId,
2107
+ graphRunId: this.#graphRunId,
2108
+ parentGraphRunId: this.#parentGraphRunId,
2109
+ };
2110
+ for (const [nodeId, outputs] of branchPlan.preloadedOutputs) {
2111
+ processor.preloadNodeData(nodeId, outputs);
2112
+ processor.#suppressedPreloadedNodeIds.add(nodeId);
2113
+ }
2114
+ const unwireEvents = wireSubprocessorEvents(processor, this.#emitter, {
2115
+ autoCleanup: false,
2116
+ isPaused: () => this.#lifecycle.isPaused,
2117
+ pause: () => {
2118
+ void this.pause();
2119
+ },
2120
+ resume: () => {
2121
+ void this.resume();
2122
+ },
2123
+ });
2124
+ const unwireLifecycle = wireSubprocessorLifecycle(processor, {
2125
+ autoCleanup: false,
2126
+ signal,
2127
+ parentAbortSignal: this.#abortController.signal,
2128
+ onParentPause: (listener) => {
2129
+ this.on('pause', listener);
2130
+ return () => {
2131
+ this.off('pause', listener);
2132
+ };
2133
+ },
2134
+ onParentResume: (listener) => {
2135
+ this.on('resume', listener);
2136
+ return () => {
2137
+ this.off('resume', listener);
2138
+ };
2139
+ },
2140
+ });
2141
+ this.#subprocessors.add(processor);
2142
+ try {
2143
+ if (signal.aborted) {
2144
+ throw createGraphAbortErrorFromSignal(signal, 'Tool continuation branch aborted');
2145
+ }
2146
+ await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
2147
+ if (!deferGraphOutputCommit) {
2148
+ this.#commitContinuationGraphOutputs(branchGraphOutputs.writes);
2149
+ }
2150
+ return {
2151
+ graphOutputWrites: branchGraphOutputs.writes,
2152
+ nodeOutputs: this.#getContinuationBranchResults(processor, branchPlan),
2153
+ };
2154
+ }
2155
+ finally {
2156
+ this.#totalCost += processor.#totalCost;
2157
+ unwireLifecycle();
2158
+ unwireEvents();
2159
+ this.#subprocessors.delete(processor);
2160
+ }
2161
+ }
2162
+ #commitContinuationGraphOutputs(writes) {
2163
+ for (const [outputId, value] of Object.entries(writes)) {
2164
+ const existingValue = this.#graphOutputs[outputId];
2165
+ if (existingValue == null || existingValue.type === 'control-flow-excluded') {
2166
+ this.#graphOutputs[outputId] = value;
2167
+ }
2168
+ }
2169
+ }
2170
+ #getContinuationBranchResults(processor, branchPlan) {
2171
+ const results = new Map();
2172
+ for (const [nodeId, outputs] of processor.#nodeResults) {
2173
+ if (branchPlan.preloadedOutputs.has(nodeId) || !processor.#visitedNodes.has(nodeId)) {
2174
+ continue;
2175
+ }
2176
+ results.set(nodeId, outputs);
2177
+ }
2178
+ return results;
2179
+ }
2180
+ #buildContinuationBranchPlan(sourceNode, sourceOutputs, activeOutputPortIds, availableNodeOutputs, excludedNodeIds, branchContext, failOnUnsafeReadyNode = false) {
2181
+ const { connections, unsafeNodeIds } = branchContext;
2182
+ const hasAvailableSourceOutput = (outputId) => {
2183
+ const output = sourceOutputs[outputId];
2184
+ return output != null && output.type !== 'control-flow-excluded';
2185
+ };
2186
+ const getAvailableNodeOutputs = (nodeId) => {
2187
+ if (excludedNodeIds.has(nodeId) || unsafeNodeIds.has(nodeId) || this.#erroredNodes.has(nodeId)) {
2188
+ return undefined;
2189
+ }
2190
+ return availableNodeOutputs.get(nodeId) ?? this.#nodeResults.get(nodeId);
2191
+ };
2192
+ const runToRelevantNodeIds = this.#getRunToRelevantNodeIds();
2193
+ const canConsiderNode = (nodeId) => {
2194
+ const node = this.#nodesById[nodeId];
2195
+ return (node != null &&
2196
+ !node.disabled &&
2197
+ !this.#visitedNodes.has(nodeId) &&
2198
+ (!runToRelevantNodeIds || runToRelevantNodeIds.has(nodeId)));
2199
+ };
2200
+ const isUnsafeNode = (nodeId) => excludedNodeIds.has(nodeId) || unsafeNodeIds.has(nodeId);
2201
+ const outgoingConnectionsByNode = new Map();
2202
+ const incomingConnectionsByNode = new Map();
2203
+ for (const connection of connections) {
2204
+ const outgoing = outgoingConnectionsByNode.get(connection.outputNodeId);
2205
+ if (outgoing) {
2206
+ outgoing.push(connection);
2207
+ }
2208
+ else {
2209
+ outgoingConnectionsByNode.set(connection.outputNodeId, [connection]);
2210
+ }
2211
+ const incoming = incomingConnectionsByNode.get(connection.inputNodeId);
2212
+ if (incoming) {
2213
+ incoming.push(connection);
2214
+ }
2215
+ else {
2216
+ incomingConnectionsByNode.set(connection.inputNodeId, [connection]);
2217
+ }
2218
+ }
2219
+ const reachableNodeIds = new Set();
2220
+ const candidateNodeIds = new Set();
2221
+ for (const connection of outgoingConnectionsByNode.get(sourceNode.id) ?? []) {
2222
+ if (activeOutputPortIds.has(connection.outputId) && canConsiderNode(connection.inputNodeId)) {
2223
+ candidateNodeIds.add(connection.inputNodeId);
2224
+ }
2225
+ }
2226
+ const boundaryNodeIds = new Set();
2227
+ let addedNode = true;
2228
+ while (addedNode) {
2229
+ addedNode = false;
2230
+ for (const candidateNodeId of [...candidateNodeIds]) {
2231
+ const incomingConnections = incomingConnectionsByNode.get(candidateNodeId) ?? [];
2232
+ const isReady = incomingConnections.every((connection) => {
2233
+ if (connection.outputNodeId === sourceNode.id) {
2234
+ return activeOutputPortIds.has(connection.outputId) || hasAvailableSourceOutput(connection.outputId);
2235
+ }
2236
+ return (reachableNodeIds.has(connection.outputNodeId) || getAvailableNodeOutputs(connection.outputNodeId) != null);
2237
+ });
2238
+ if (!isReady) {
2239
+ continue;
2240
+ }
2241
+ candidateNodeIds.delete(candidateNodeId);
2242
+ if (isUnsafeNode(candidateNodeId)) {
2243
+ if (failOnUnsafeReadyNode) {
2244
+ const unsafeNode = this.#nodesById[candidateNodeId];
2245
+ throw new Error(`Delegate Tool Call "${sourceNode.title}" cannot fire its pre-tool Message branch through unsupported node "${unsafeNode.title}". Move cycles, races, loops, and foreground rejoin points outside that branch.`);
2246
+ }
2247
+ continue;
2248
+ }
2249
+ reachableNodeIds.add(candidateNodeId);
2250
+ addedNode = true;
2251
+ for (const connection of incomingConnections) {
2252
+ if (connection.outputNodeId !== sourceNode.id &&
2253
+ !reachableNodeIds.has(connection.outputNodeId) &&
2254
+ getAvailableNodeOutputs(connection.outputNodeId) != null) {
2255
+ boundaryNodeIds.add(connection.outputNodeId);
2256
+ }
2257
+ }
2258
+ if (this.#nodesById[candidateNodeId]?.type === 'startBackgroundBranch') {
2259
+ continue;
2260
+ }
2261
+ for (const connection of outgoingConnectionsByNode.get(candidateNodeId) ?? []) {
2262
+ if (connection.inputNodeId !== sourceNode.id &&
2263
+ !reachableNodeIds.has(connection.inputNodeId) &&
2264
+ canConsiderNode(connection.inputNodeId)) {
2265
+ candidateNodeIds.add(connection.inputNodeId);
2266
+ }
2267
+ }
2268
+ }
2269
+ }
2270
+ if (reachableNodeIds.size === 0) {
2271
+ return undefined;
2272
+ }
2273
+ const includedNodeIds = new Set([sourceNode.id, ...reachableNodeIds, ...boundaryNodeIds]);
2274
+ const asyncBranchConnections = [];
2275
+ for (const nodeId of reachableNodeIds) {
2276
+ if (this.#nodesById[nodeId]?.type !== 'startBackgroundBranch') {
2277
+ continue;
2278
+ }
2279
+ const asyncPlan = this.#asyncBranchPlansByTriggerNodeId.get(nodeId);
2280
+ if (!asyncPlan) {
2281
+ continue;
2282
+ }
2283
+ for (const node of asyncPlan.graph.nodes) {
2284
+ includedNodeIds.add(node.id);
2285
+ }
2286
+ asyncBranchConnections.push(...asyncPlan.graph.connections);
2287
+ }
2288
+ const foregroundBranchConnections = connections.filter((connection) => {
2289
+ if (!reachableNodeIds.has(connection.inputNodeId)) {
2290
+ return false;
2291
+ }
2292
+ if (connection.outputNodeId === sourceNode.id) {
2293
+ return activeOutputPortIds.has(connection.outputId) || hasAvailableSourceOutput(connection.outputId);
2294
+ }
2295
+ return includedNodeIds.has(connection.outputNodeId);
2296
+ });
2297
+ const seenConnections = new Set();
2298
+ const branchConnections = [...foregroundBranchConnections, ...asyncBranchConnections].filter((connection) => {
2299
+ const key = `${connection.outputNodeId}:${connection.outputId}:${connection.inputNodeId}:${connection.inputId}`;
2300
+ if (seenConnections.has(key)) {
2301
+ return false;
2302
+ }
2303
+ seenConnections.add(key);
2304
+ return true;
2305
+ });
2306
+ const graph = {
2307
+ metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
2308
+ nodes: Object.values(this.#nodesById).filter((node) => includedNodeIds.has(node.id)),
2309
+ connections: branchConnections,
2310
+ };
2311
+ const preloadedOutputs = new Map([[sourceNode.id, sourceOutputs]]);
2312
+ for (const nodeId of boundaryNodeIds) {
2313
+ preloadedOutputs.set(nodeId, getAvailableNodeOutputs(nodeId));
2314
+ }
2315
+ return { graph, preloadedOutputs };
2316
+ }
2317
+ #createContinuationBranchContext() {
2318
+ const connections = this.#getEffectiveConnections();
2319
+ return {
2320
+ connections,
2321
+ unsafeNodeIds: this.#getUnsafeContinuationBranchNodeIds(),
2322
+ };
2323
+ }
2324
+ #getUnsafeContinuationBranchNodeIds() {
2325
+ const unsafeNodeIds = new Set();
2326
+ for (const component of this.#scc) {
2327
+ if (component.length > 1) {
2328
+ component.forEach((node) => unsafeNodeIds.add(node.id));
2329
+ }
2330
+ }
2331
+ for (const node of Object.values(this.#nodesById)) {
2332
+ const attachedData = this.#attachedNodeData.get(node.id);
2333
+ if (node.type === 'loopController' ||
2334
+ node.type === 'raceInputs' ||
2335
+ (attachedData != null && Object.values(attachedData).some(Boolean))) {
2336
+ unsafeNodeIds.add(node.id);
2337
+ }
2338
+ }
2339
+ // SCC preprocessing sees every persisted edge, including secondary edges
2340
+ // that still participate in scheduler readiness. Preserve the same view
2341
+ // when detecting a one-node cycle.
2342
+ for (const connection of this.#graph.connections) {
2343
+ if (connection.inputNodeId === connection.outputNodeId && this.#isDefinitionValidConnection(connection)) {
2344
+ unsafeNodeIds.add(connection.inputNodeId);
2345
+ }
2346
+ }
2347
+ return unsafeNodeIds;
2348
+ }
2349
+ #getEffectiveConnections() {
2350
+ if (this.#effectiveConnectionsForRun) {
2351
+ return this.#effectiveConnectionsForRun;
2352
+ }
2353
+ const plannedConnections = this.#graphExecutionPlan?.inputConnectionByNodeAndPort;
2354
+ if (plannedConnections) {
2355
+ this.#effectiveConnectionsForRun = Object.values(plannedConnections).flatMap((connectionsByPort) => Object.values(connectionsByPort).filter((connection) => connection != null));
2356
+ return this.#effectiveConnectionsForRun;
2357
+ }
2358
+ this.#effectiveConnectionsForRun = Object.values(this.#nodesById).flatMap((node) => {
2359
+ const seenInputIds = new Set();
2360
+ return (this.#connections[node.id] ?? []).filter((connection) => {
2361
+ if (connection.inputNodeId !== node.id || seenInputIds.has(connection.inputId)) {
2362
+ return false;
2363
+ }
2364
+ seenInputIds.add(connection.inputId);
2365
+ return true;
2366
+ });
2367
+ });
2368
+ return this.#effectiveConnectionsForRun;
2369
+ }
2370
+ #prepareAsyncBranchTopology() {
2371
+ const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2372
+ const outgoingByNodeId = new Map();
2373
+ const incomingByNodeId = new Map();
2374
+ const runToRelevantNodeIds = this.#getRunToRelevantNodeIds();
2375
+ const isRunToRelevant = (nodeId) => !runToRelevantNodeIds || runToRelevantNodeIds.has(nodeId);
2376
+ for (const connection of connections) {
2377
+ const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
2378
+ outgoing.push(connection);
2379
+ outgoingByNodeId.set(connection.outputNodeId, outgoing);
2380
+ const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
2381
+ incoming.push(connection);
2382
+ incomingByNodeId.set(connection.inputNodeId, incoming);
2383
+ }
2384
+ for (const triggerNode of Object.values(this.#nodesById)) {
2385
+ if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRunToRelevant(triggerNode.id)) {
2386
+ continue;
2387
+ }
2388
+ if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId && this.#nodeResults.has(triggerNode.id)) {
2389
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot use preloaded outputs because replaying it could repeat async side effects.`);
2390
+ }
2391
+ const nodeIds = new Set();
2392
+ const pendingNodeIds = (outgoingByNodeId.get(triggerNode.id) ?? [])
2393
+ .map((connection) => connection.inputNodeId)
2394
+ .filter(isRunToRelevant);
2395
+ while (pendingNodeIds.length > 0) {
2396
+ const nodeId = pendingNodeIds.pop();
2397
+ if (nodeId === triggerNode.id) {
2398
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot be part of a cycle or reconnect to its own inputs.`);
2399
+ }
2400
+ if (nodeIds.has(nodeId)) {
2401
+ continue;
2402
+ }
2403
+ const node = this.#nodesById[nodeId];
2404
+ if (!node) {
2405
+ continue;
2406
+ }
2407
+ if (node.disabled) {
2408
+ continue;
2409
+ }
2410
+ if (node.type === 'graphOutput') {
2411
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain Graph Output node "${node.title}". Async branches are side-effect-only.`);
2412
+ }
2413
+ nodeIds.add(nodeId);
2414
+ for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
2415
+ if (isRunToRelevant(connection.inputNodeId)) {
2416
+ pendingNodeIds.push(connection.inputNodeId);
2417
+ }
2418
+ }
2419
+ }
2420
+ for (const nodeId of nodeIds) {
2421
+ const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== triggerNode.id && !nodeIds.has(connection.outputNodeId));
2422
+ if (externalInput) {
2423
+ const node = this.#nodesById[nodeId];
2424
+ const externalNode = this.#nodesById[externalInput.outputNodeId];
2425
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot run "${node.title}" because it also depends on ` +
2426
+ `"${externalNode?.title ?? externalInput.outputNodeId}" outside the async branch. Assemble all required values before the async trigger.`);
2427
+ }
2428
+ }
2429
+ if (nodeIds.size === 0) {
2430
+ continue;
2431
+ }
2432
+ const preloadedNodeId = [...nodeIds].find((nodeId) => this.#nodeResults.has(nodeId));
2433
+ if (preloadedNodeId) {
2434
+ const preloadedNode = this.#nodesById[preloadedNodeId];
2435
+ throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain preloaded node "${preloadedNode.title}". Preloading an async descendant would bypass the trigger boundary.`);
2436
+ }
2437
+ // The node derives its variadic output definitions from connected inputs.
2438
+ // Retain shallow input anchors in the slice even though the trigger itself is preloaded.
2439
+ const triggerInputConnections = connections.filter((connection) => connection.inputNodeId === triggerNode.id);
2440
+ const inputAnchorNodeIds = new Set(triggerInputConnections.map((connection) => connection.outputNodeId));
2441
+ const includedNodeIds = new Set([triggerNode.id, ...nodeIds, ...inputAnchorNodeIds]);
2442
+ const graph = {
2443
+ metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
2444
+ nodes: this.#graph.nodes.filter((node) => includedNodeIds.has(node.id)),
2445
+ connections: connections.filter((connection) => connection.inputNodeId === triggerNode.id ||
2446
+ (nodeIds.has(connection.inputNodeId) &&
2447
+ (connection.outputNodeId === triggerNode.id || nodeIds.has(connection.outputNodeId)))),
2448
+ };
2449
+ this.#asyncBranchPlansByTriggerNodeId.set(triggerNode.id, { graph, nodeIds });
2450
+ if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId) {
2451
+ for (const nodeId of nodeIds) {
2452
+ this.#ignoreNodes.add(nodeId);
2453
+ }
2454
+ }
2455
+ }
2456
+ }
2457
+ #isDefinitionValidConnection(connection) {
2458
+ const outputDefinitions = this.#definitions[connection.outputNodeId]?.outputs ?? [];
2459
+ const inputDefinitions = this.#definitions[connection.inputNodeId]?.inputs ?? [];
2460
+ return (outputDefinitions.some((definition) => definition.id === connection.outputId) &&
2461
+ inputDefinitions.some((definition) => definition.id === connection.inputId));
2462
+ }
2463
+ #getActiveAsyncBranchPlan(triggerNode, activeOutputPortIds) {
2464
+ const plan = this.#asyncBranchPlansByTriggerNodeId.get(triggerNode.id);
2465
+ if (!plan || activeOutputPortIds.size === 0) {
2466
+ return undefined;
2467
+ }
2468
+ const outgoingByNodeId = new Map();
2469
+ for (const connection of plan.graph.connections) {
2470
+ const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
2471
+ outgoing.push(connection);
2472
+ outgoingByNodeId.set(connection.outputNodeId, outgoing);
2473
+ }
2474
+ const activeNodeIds = new Set();
2475
+ const pendingNodeIds = (outgoingByNodeId.get(triggerNode.id) ?? [])
2476
+ .filter((connection) => activeOutputPortIds.has(connection.outputId))
2477
+ .map((connection) => connection.inputNodeId);
2478
+ while (pendingNodeIds.length > 0) {
2479
+ const nodeId = pendingNodeIds.pop();
2480
+ if (activeNodeIds.has(nodeId)) {
2481
+ continue;
2482
+ }
2483
+ activeNodeIds.add(nodeId);
2484
+ for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
2485
+ pendingNodeIds.push(connection.inputNodeId);
2486
+ }
2487
+ }
2488
+ if (activeNodeIds.size === 0) {
2489
+ return undefined;
2490
+ }
2491
+ const triggerInputConnections = plan.graph.connections.filter((connection) => connection.inputNodeId === triggerNode.id);
2492
+ const inputAnchorNodeIds = new Set(triggerInputConnections.map((connection) => connection.outputNodeId));
2493
+ const includedNodeIds = new Set([triggerNode.id, ...activeNodeIds, ...inputAnchorNodeIds]);
2494
+ return {
2495
+ nodeIds: activeNodeIds,
2496
+ graph: {
2497
+ metadata: plan.graph.metadata ? { ...plan.graph.metadata } : undefined,
2498
+ nodes: plan.graph.nodes.filter((node) => includedNodeIds.has(node.id)),
2499
+ connections: plan.graph.connections.filter((connection) => connection.inputNodeId === triggerNode.id ||
2500
+ (activeNodeIds.has(connection.inputNodeId) &&
2501
+ (connection.outputNodeId === triggerNode.id || activeNodeIds.has(connection.outputNodeId)) &&
2502
+ (connection.outputNodeId !== triggerNode.id || activeOutputPortIds.has(connection.outputId)))),
2503
+ },
2504
+ };
2505
+ }
1465
2506
  #getActiveOutputPortIds(node) {
2507
+ if (this.#sameGraphRunOwnerOverride) {
2508
+ return this.#sameGraphRunOwnerOverride.#getActiveOutputPortIds(node);
2509
+ }
1466
2510
  const outputConnections = getOutputNodesFrom(this.#executionState, node).connectionsToNodes;
1467
2511
  if (outputConnections.length === 0) {
1468
2512
  return new Set();
@@ -1499,6 +2543,13 @@ export class GraphProcessor {
1499
2543
  return relevantNodeIds;
1500
2544
  }
1501
2545
  #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
2546
+ if (this.#suppressGraphPartialOutputs) {
2547
+ return;
2548
+ }
2549
+ if (this.#sameGraphRunOwnerOverride) {
2550
+ this.#sameGraphRunOwnerOverride.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
2551
+ return;
2552
+ }
1502
2553
  const { useAsGraphPartialOutput } = node.data ?? {};
1503
2554
  if (!(useAsGraphPartialOutput && this.#executor && this.#parent)) {
1504
2555
  return;
@@ -1546,6 +2597,7 @@ export class GraphProcessor {
1546
2597
  processor.#contextValues = this.#contextValues;
1547
2598
  processor.#parent = this;
1548
2599
  processor.#globals = this.#globals;
2600
+ processor.#storedValueController = this.#storedValueController;
1549
2601
  processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
1550
2602
  processor.#executor = {
1551
2603
  nodeId: node.id,