@valerypopoff/rivet2-core 2.1.4 → 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 (70) hide show
  1. package/dist/cjs/bundle.cjs +3733 -969
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/webAppRuntime.cjs +605 -16
  4. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  5. package/dist/esm/api/createProcessor.js +5 -1
  6. package/dist/esm/exports.js +3 -0
  7. package/dist/esm/model/GraphBoundaryEffects.js +13 -0
  8. package/dist/esm/model/GraphProcessor.js +1127 -82
  9. package/dist/esm/model/ManagedAsyncBranches.js +28 -0
  10. package/dist/esm/model/Nodes.js +9 -0
  11. package/dist/esm/model/ProcessContextBuilder.js +2 -1
  12. package/dist/esm/model/RecordingPlayer.js +9 -0
  13. package/dist/esm/model/StoredValueStore.js +226 -0
  14. package/dist/esm/model/SubprocessorBridge.js +50 -19
  15. package/dist/esm/model/ToolCallContinuation.js +1 -0
  16. package/dist/esm/model/UiGraph.js +50 -0
  17. package/dist/esm/model/UiGraphActionProtocol.js +10 -1
  18. package/dist/esm/model/UiGraphBrowserRuntime.js +333 -0
  19. package/dist/esm/model/UiGraphNormalization.js +35 -185
  20. package/dist/esm/model/UiGraphRendererStyles.js +772 -74
  21. package/dist/esm/model/UiGraphRuntimeModel.js +230 -14
  22. package/dist/esm/model/UiGraphSchema.js +91 -0
  23. package/dist/esm/model/UiGraphWebAppStorage.js +1 -0
  24. package/dist/esm/model/chat/chatMessages.js +5 -9
  25. package/dist/esm/model/chat-v2/chatV2Errors.js +36 -3
  26. package/dist/esm/model/chat-v2/index.js +1 -0
  27. package/dist/esm/model/chat-v2/toolContinuation.js +6 -8
  28. package/dist/esm/model/chat-v2/toolContinuationConnection.js +68 -0
  29. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +12 -40
  30. package/dist/esm/model/nodes/GetStoredValueNode.js +109 -0
  31. package/dist/esm/model/nodes/LLMChatV2Node.js +17 -1
  32. package/dist/esm/model/nodes/MatchNode.js +7 -7
  33. package/dist/esm/model/nodes/SetStoredValueNode.js +84 -0
  34. package/dist/esm/model/nodes/StartBackgroundBranchNode.js +59 -0
  35. package/dist/esm/model/nodes/StoredValueNodeUtils.js +47 -0
  36. package/dist/esm/model/nodes/toolCallDelegation.js +44 -1
  37. package/dist/esm/recording/ExecutionRecorder.js +1 -0
  38. package/dist/esm/utils/coerceType.js +3 -0
  39. package/dist/esm/webAppRuntime.js +3 -3
  40. package/dist/types/api/createProcessor.d.ts +4 -0
  41. package/dist/types/exports.d.ts +3 -0
  42. package/dist/types/model/EditorDefinition.d.ts +2 -1
  43. package/dist/types/model/ExecutorProtocol.d.ts +12 -0
  44. package/dist/types/model/GraphBoundaryEffects.d.ts +9 -1
  45. package/dist/types/model/GraphProcessor.d.ts +19 -2
  46. package/dist/types/model/ManagedAsyncBranches.d.ts +6 -0
  47. package/dist/types/model/Nodes.d.ts +5 -2
  48. package/dist/types/model/ProcessContext.d.ts +15 -0
  49. package/dist/types/model/ProcessContextBuilder.d.ts +2 -1
  50. package/dist/types/model/StoredValueStore.d.ts +55 -0
  51. package/dist/types/model/SubprocessorBridge.d.ts +4 -2
  52. package/dist/types/model/ToolCallContinuation.d.ts +13 -0
  53. package/dist/types/model/UiGraph.d.ts +21 -0
  54. package/dist/types/model/UiGraphActionProtocol.d.ts +2 -0
  55. package/dist/types/model/UiGraphBrowserRuntime.d.ts +51 -0
  56. package/dist/types/model/UiGraphRendererStyles.d.ts +2 -2
  57. package/dist/types/model/UiGraphRuntimeModel.d.ts +22 -3
  58. package/dist/types/model/UiGraphSchema.d.ts +113 -0
  59. package/dist/types/model/UiGraphWebAppStorage.d.ts +3 -0
  60. package/dist/types/model/chat-v2/index.d.ts +1 -0
  61. package/dist/types/model/chat-v2/toolContinuation.d.ts +1 -0
  62. package/dist/types/model/chat-v2/toolContinuationConnection.d.ts +28 -0
  63. package/dist/types/model/nodes/GetStoredValueNode.d.ts +25 -0
  64. package/dist/types/model/nodes/SetStoredValueNode.d.ts +23 -0
  65. package/dist/types/model/nodes/StartBackgroundBranchNode.d.ts +14 -0
  66. package/dist/types/model/nodes/StoredValueNodeUtils.d.ts +5 -0
  67. package/dist/types/model/nodes/toolCallDelegation.d.ts +4 -0
  68. package/dist/types/recording/RecordedEvents.d.ts +5 -0
  69. package/dist/types/webAppRuntime.d.ts +4 -4
  70. package/package.json +1 -1
@@ -21,9 +21,25 @@ import { emitDetached } from '../utils/emitDetached.js';
21
21
  import { GraphRunLifecycle } from './GraphRunLifecycle.js';
22
22
  import { normalizeGraphProgress } from './GraphProgress.js';
23
23
  import { RIVET_WEB_APP_STATUS_FUNCTION_NAME, rivetWebAppStatusExternalFunction } from './UiGraphWebAppStatus.js';
24
+ import { RivetStoredValueController } from './StoredValueStore.js';
24
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';
25
29
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
26
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
+ }
27
43
  export function cloneFrozenNodeOutputs(outputs) {
28
44
  if (typeof structuredClone !== 'function') {
29
45
  throw new Error('Frozen node output cloning requires structuredClone support');
@@ -70,6 +86,7 @@ const FAST_ACYCLIC_UNSUPPORTED_NODE_TYPES = new Set([
70
86
  'loopController',
71
87
  'loopUntil',
72
88
  'raceInputs',
89
+ 'startBackgroundBranch',
73
90
  'userInput',
74
91
  'waitForEvent',
75
92
  ]);
@@ -120,6 +137,19 @@ export class GraphProcessor {
120
137
  #externalFunctions = {};
121
138
  slowMode = false;
122
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;
123
153
  #registry;
124
154
  #concurrency;
125
155
  #executionPlanCacheMode;
@@ -129,6 +159,7 @@ export class GraphProcessor {
129
159
  #runtimeProfiler;
130
160
  #captureNodeTimings;
131
161
  #frozenNodeOutputResolver;
162
+ #storedValueStore;
132
163
  #useSeededExecutionPlanOnNextRun = false;
133
164
  id = nanoid();
134
165
  #includeTrace = true;
@@ -162,6 +193,7 @@ export class GraphProcessor {
162
193
  #subprocessors = undefined;
163
194
  #contextValues = undefined;
164
195
  #globals = undefined;
196
+ #storedValueController = undefined;
165
197
  #attachedNodeData = undefined;
166
198
  #successfulAbortTerminalProcessIds = undefined;
167
199
  #totalCost = 0;
@@ -173,6 +205,9 @@ export class GraphProcessor {
173
205
  #graphExecutionPlan;
174
206
  #nodeProcessContextBase = undefined;
175
207
  #runToRelevantNodeIds;
208
+ #managedAsyncBranches;
209
+ #managedAsyncBranchFailures = [];
210
+ #runCompletionPromise;
176
211
  #nodesNotInCycle = undefined;
177
212
  #nodeAbortControllers = new Map();
178
213
  #graphInputNodeValues = {};
@@ -182,6 +217,13 @@ export class GraphProcessor {
182
217
  get isRunning() {
183
218
  return this.#lifecycle.isRunning;
184
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
+ }
185
227
  #startNodeTiming() {
186
228
  return this.#captureNodeTimings ? getMonotonicTimeMs() : undefined;
187
229
  }
@@ -225,7 +267,7 @@ export class GraphProcessor {
225
267
  }
226
268
  constructor(project, graphId, registry, includeTrace, options) {
227
269
  this.#project = project;
228
- const graph = resolveProcessorGraph(project, graphId);
270
+ const graph = options?.[graphProcessorGraphOverride] ?? resolveProcessorGraph(project, graphId);
229
271
  if (!graph) {
230
272
  throw new Error(`Graph ${graphId} not found in project`);
231
273
  }
@@ -242,6 +284,7 @@ export class GraphProcessor {
242
284
  this.#scheduler = options?.scheduler ?? 'compatible';
243
285
  this.#runtimeProfiler = options?.runtimeProfiler;
244
286
  this.#captureNodeTimings = options?.captureNodeTimings ?? false;
287
+ this.#consumedAsyncBranchTriggerNodeId = options?.[consumedAsyncBranchTriggerOverride];
245
288
  this.#emitter.bindMethods(this, ['on', 'off', 'once', 'onAny', 'offAny']);
246
289
  this.setExternalFunction('echo', async (value) => ({ type: 'any', value }));
247
290
  this.setExternalFunction(RIVET_WEB_APP_STATUS_FUNCTION_NAME, rivetWebAppStatusExternalFunction);
@@ -398,6 +441,12 @@ export class GraphProcessor {
398
441
  setExternalFunction(name, fn) {
399
442
  this.#externalFunctions[name] = fn;
400
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
+ }
401
450
  async abort(successful = false, error) {
402
451
  if (!this.#lifecycle.requestAbort(successful, error)) {
403
452
  return Promise.resolve();
@@ -405,11 +454,16 @@ export class GraphProcessor {
405
454
  const abortReason = createGraphAbortReason(successful, error);
406
455
  this.#abortController.abort(abortReason);
407
456
  this.#abortActiveNodeControllers(abortReason);
408
- emitDetached(this.#emitter, 'graphAbort', this.#withExecution({ successful, error, graph: this.#graph }));
409
- if (!this.#isSubProcessor) {
410
- 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
+ }
411
462
  }
412
463
  await this.#processingQueue.onIdle();
464
+ if (!this.#isSubProcessor) {
465
+ await this.#managedAsyncBranches?.drain();
466
+ }
413
467
  }
414
468
  pause() {
415
469
  if (this.#lifecycle.pause()) {
@@ -459,16 +513,19 @@ export class GraphProcessor {
459
513
  }
460
514
  }
461
515
  preloadNodeData(nodeId, data) {
462
- this.#nodeResults ??= new Map();
463
- this.#visitedNodes ??= new Set();
464
516
  for (const value of Object.values(data)) {
465
517
  if (!value || !('type' in value) || !value.type) {
466
518
  throw new Error(`Invalid data value for node ${nodeId}, must be a DataValue`);
467
519
  }
468
520
  }
469
- this.#nodeResults.set(nodeId, data);
470
- this.#visitedNodes.add(nodeId);
521
+ this.#preloadedNodeResults.set(nodeId, data);
471
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
+ }
472
529
  }
473
530
  setFrozenNodeOutputResolver(resolver) {
474
531
  this.#frozenNodeOutputResolver = resolver;
@@ -535,28 +592,39 @@ export class GraphProcessor {
535
592
  }
536
593
  #initProcessState() {
537
594
  this.#lifecycle.begin();
538
- if (!this.#hasPreloadedData) {
539
- this.#nodeResults = new Map();
540
- this.#visitedNodes = new Set();
541
- }
595
+ this.#nodeResults = new Map(this.#preloadedNodeResults);
596
+ this.#visitedNodes = new Set(this.#preloadedNodeResults.keys());
597
+ this.#hasPreloadedData = this.#preloadedNodeResults.size > 0;
542
598
  this.#erroredNodes = new Map();
543
599
  this.#currentlyProcessing = new Set();
544
600
  const seededExecutionPlan = this.#seededExecutionPlanForNextRun();
545
601
  this.#remainingNodes = new Set(seededExecutionPlan ? seededExecutionPlan.nodeIds : this.#graph.nodes.map((node) => node.id));
546
602
  this.#pendingUserInputs = {};
547
603
  this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
548
- this.#graphOutputs = {};
604
+ this.#graphOutputs = this.#sharedRunStateOverride?.graphOutputs ?? {};
549
605
  this.#executionCache ??= new Map();
550
606
  this.#queuedNodes = new Set();
607
+ this.#toolCallContinuationInvocations = new Map();
608
+ this.#continuationCompletionOwnerByNodeId = new Map();
609
+ this.#effectiveConnectionsForRun = undefined;
610
+ this.#asyncBranchPlansByTriggerNodeId = new Map();
551
611
  this.#loopControllersSeen = new Set();
552
612
  this.#subprocessors = new Set();
553
- this.#attachedNodeData = new Map();
613
+ this.#attachedNodeData = this.#sharedRunStateOverride?.attachedNodeData ?? new Map();
554
614
  this.#globals ??= new Map();
615
+ if (!this.#isSubProcessor) {
616
+ this.#storedValueController = new RivetStoredValueController(this.#storedValueStore);
617
+ }
555
618
  this.#ignoreNodes = new Set();
556
619
  this.#nodeProcessContextBase = undefined;
557
620
  this.#runToRelevantNodeIds = undefined;
621
+ if (!this.#isSubProcessor) {
622
+ this.#managedAsyncBranches = new ManagedAsyncBranches();
623
+ this.#managedAsyncBranchFailures = [];
624
+ }
558
625
  this.#abortController = this.#newAbortController();
559
626
  this.#successfulAbortTerminalProcessIds = new Set();
627
+ this.#totalCost = 0;
560
628
  this.#nodeAbortControllers = new Map();
561
629
  this.#loadedProjects =
562
630
  this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {};
@@ -566,7 +634,7 @@ export class GraphProcessor {
566
634
  this.#runtimeCache.graphBoundaries = undefined;
567
635
  }
568
636
  }
569
- this.#graphInputNodeValues = {};
637
+ this.#graphInputNodeValues = this.#sharedRunStateOverride?.graphInputNodeValues ?? {};
570
638
  }
571
639
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
572
640
  async processGraph(
@@ -575,36 +643,84 @@ export class GraphProcessor {
575
643
  /** Inputs to the main graph. You should pass all inputs required by the GraphInputNodes of the graph. */
576
644
  inputs = {},
577
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. */
578
- contextValues = {}) {
646
+ contextValues = {},
647
+ /** Allows callers such as web apps to receive root outputs while managed async branches continue settling. */
648
+ options = {}) {
579
649
  if (this.#lifecycle.isRunning) {
580
650
  throw new Error('Cannot process graph while already processing');
581
651
  }
582
- try {
583
- this.#profileRuntimeSync('initializeGraphRun', () => this.#initializeGraphRun(context, inputs, contextValues));
584
- await this.#profileRuntimeAsync('loadProjectReferences', () => this.#loadProjectReferences());
585
- this.#profileRuntimeSync('prepareNodeProcessContextBase', () => this.#prepareNodeProcessContextBase());
586
- const shouldUseSeededExecutionPlan = this.#seededExecutionPlanForNextRun() != null;
587
- this.#useSeededExecutionPlanOnNextRun = false;
588
- if (!shouldUseSeededExecutionPlan) {
589
- this.#preprocessGraph();
590
- }
591
- await this.#profileRuntimeAsync('emitGraphStart', () => this.#emitGraphStart());
592
- await this.#profileRuntimeAsync('emitPreloadedNodeResults', () => this.#emitPreloadedNodeResults());
593
- await this.#profileRuntimeAsync('waitUntilUnpaused', () => this.#waitUntilUnpaused());
594
- if (this.#canUseFastAcyclicScheduler()) {
595
- 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());
596
699
  }
597
- else {
598
- 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());
599
707
  }
600
- await this.#profileRuntimeAsync('throwIfGraphErrored', () => this.#throwIfGraphErrored());
601
- return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
602
- }
603
- finally {
604
- this.#lifecycle.complete();
605
- this.#cleanupTokenizerErrorListener();
606
- 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;
607
722
  }
723
+ return await completionPromise;
608
724
  }
609
725
  async #emitFinishIfNeeded() {
610
726
  if (!this.#lifecycle.claimRootFinish(this.#isSubProcessor)) {
@@ -617,9 +733,16 @@ export class GraphProcessor {
617
733
  this.#context = context;
618
734
  this.#graphInputs = inputs;
619
735
  this.#contextValues = contextValues;
620
- this.#rootRunId = this.#parent ? this.#parent.#rootRunId : nanoid();
621
- this.#graphRunId = nanoid();
622
- 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
+ }
623
746
  this.#cleanupTokenizerErrorListener();
624
747
  const unsubscribeTokenizerError = this.#context.tokenizer.on('error', (error) => {
625
748
  emitDetached(this.#emitter, 'error', { error });
@@ -631,13 +754,15 @@ export class GraphProcessor {
631
754
  this.#nodeProcessContextBase = {
632
755
  ...this.#context,
633
756
  abortGraph: (error) => {
634
- void this.abort(error === undefined, error);
757
+ void (this.#abortOwnerOverride ?? this).abort(error === undefined, error);
635
758
  },
636
759
  codeRunner: this.#context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
637
760
  contextValues: this.#contextValues,
638
761
  executionCache: this.#executionCache,
639
762
  executor: this.executor ?? 'nodejs',
640
763
  getGlobal: (id) => this.#globals.get(id),
764
+ getCachedStoredValue: (key) => this.#storedValueController.getCached(key),
765
+ getStoredValue: (key) => this.#storedValueController.get(key),
641
766
  getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
642
767
  graphInputNodeValues: this.#graphInputNodeValues,
643
768
  graphInputs: this.#graphInputs,
@@ -651,6 +776,7 @@ export class GraphProcessor {
651
776
  trace: (message) => {
652
777
  this.#emitTraceEvent(message);
653
778
  },
779
+ setStoredValue: (key, value) => this.#storedValueController.set(key, value),
654
780
  waitForGlobal: async (id) => {
655
781
  if (this.#globals.has(id)) {
656
782
  return this.#globals.get(id);
@@ -658,6 +784,7 @@ export class GraphProcessor {
658
784
  await this.getRootProcessor().#emitter.once(`globalSet:${id}`);
659
785
  return this.#globals.get(id);
660
786
  },
787
+ waitForStoredValue: (key, signal) => this.#storedValueController.waitForSet(key, signal),
661
788
  };
662
789
  }
663
790
  #cleanupTokenizerErrorListener() {
@@ -671,6 +798,9 @@ export class GraphProcessor {
671
798
  }
672
799
  }
673
800
  async #emitGraphStart() {
801
+ if (this.#suppressGraphLifecycleEvents) {
802
+ return;
803
+ }
674
804
  if (!this.#isSubProcessor) {
675
805
  await this.#emitter.emit('start', this.#withExecution({
676
806
  contextValues: this.#contextValues,
@@ -689,6 +819,9 @@ export class GraphProcessor {
689
819
  if (!this.#nodeResults.has(node.id)) {
690
820
  continue;
691
821
  }
822
+ if (this.#suppressedPreloadedNodeIds.has(node.id)) {
823
+ continue;
824
+ }
692
825
  this.#emitTraceEvent(`Node ${node.title} has preloaded data`);
693
826
  await this.#emitter.emit('nodeStart', this.#withExecution({
694
827
  node,
@@ -832,35 +965,44 @@ export class GraphProcessor {
832
965
  return erroredNodeAttachedData.races == null || erroredNodeAttachedData.races.completed === false;
833
966
  });
834
967
  }
835
- #createGraphError(erroredNodes) {
968
+ #createGraphError(erroredNodes, managedAsyncFailures = []) {
836
969
  if (this.#lifecycle.abortError) {
837
970
  return this.#lifecycle.getAbortError();
838
971
  }
839
- const message = `Graph ${this.#graph.metadata.name} (${this.#graph.metadata.id}) failed to process due to errors in nodes:\n${erroredNodes
840
- .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})`)
841
978
  .join('\n')}`;
842
- if (erroredNodes.length === 1) {
843
- const [, nodeError] = erroredNodes[0];
844
- return new Error(message, { cause: nodeError });
979
+ if (errors.length === 1) {
980
+ return new Error(message, { cause: errors[0].error });
845
981
  }
846
- return new AggregateError(erroredNodes.map(([, nodeError]) => nodeError), message);
982
+ return new AggregateError(errors.map(({ error }) => error), message);
847
983
  }
848
- async #throwIfGraphErrored() {
984
+ async #throwIfGraphErrored(includeManagedAsyncFailures = true) {
849
985
  const erroredNodes = this.#getUnhandledErroredNodes();
850
- if (!erroredNodes.length || this.#lifecycle.abortSuccessful) {
986
+ const managedAsyncFailures = includeManagedAsyncFailures ? this.#managedAsyncBranchFailures : [];
987
+ if ((!erroredNodes.length && !managedAsyncFailures.length) || this.#lifecycle.abortSuccessful) {
851
988
  return;
852
989
  }
853
- const error = this.#createGraphError(erroredNodes);
854
- await this.#emitter.emit('graphError', this.#withExecution({ graph: this.#graph, error }));
855
- 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) {
856
995
  await this.#emitter.emit('error', { error });
857
996
  }
858
997
  throw error;
859
998
  }
860
999
  async #finalizeGraphRun() {
861
- ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
862
1000
  const outputValues = this.#graphOutputs;
863
1001
  this.#lifecycle.complete();
1002
+ if (this.#suppressGraphLifecycleEvents) {
1003
+ return outputValues;
1004
+ }
1005
+ ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
864
1006
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
865
1007
  if (!this.#isSubProcessor) {
866
1008
  await this.#emitter.emit('done', { results: outputValues });
@@ -914,7 +1056,13 @@ export class GraphProcessor {
914
1056
  async #fetchNodeDataAndProcessNode(node) {
915
1057
  const profileStart = this.#startRuntimeProfile();
916
1058
  try {
917
- 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)) {
918
1066
  return;
919
1067
  }
920
1068
  if (this.#nodeResults.has(node.id) || this.#erroredNodes.has(node.id)) {
@@ -962,6 +1110,10 @@ export class GraphProcessor {
962
1110
  const inputNodesProfileStart = this.#startRuntimeProfile();
963
1111
  const inputNodes = getInputNodesTo(this.#executionState, node);
964
1112
  this.#finishRuntimeProfile('getInputNodesTo', inputNodesProfileStart);
1113
+ const continuedOutputNodes = this.#propagateCompletedContinuationNode(node, queueOutputNodes);
1114
+ if (continuedOutputNodes) {
1115
+ return continuedOutputNodes;
1116
+ }
965
1117
  if (this.#shouldSkipNodeProcessing(node, inputNodes)) {
966
1118
  return [];
967
1119
  }
@@ -1025,11 +1177,31 @@ export class GraphProcessor {
1025
1177
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
1026
1178
  if (queueOutputNodes && processResult.shouldQueueOutputNodes) {
1027
1179
  const queueOutputsProfileStart = this.#startRuntimeProfile();
1028
- this.#queueOutputNodes(node, outputNodes.nodes);
1180
+ if (node.type === 'startBackgroundBranch') {
1181
+ this.#startManagedAsyncBranch(node);
1182
+ }
1183
+ else {
1184
+ this.#queueOutputNodes(node, outputNodes.nodes);
1185
+ }
1029
1186
  this.#finishRuntimeProfile('queueOutputNodes', queueOutputsProfileStart);
1030
1187
  }
1031
1188
  return processResult.shouldQueueOutputNodes ? outputNodes.nodes : [];
1032
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
+ }
1033
1205
  #shouldSkipNodeProcessing(node, inputNodes) {
1034
1206
  if (this.#ignoreNodes.has(node.id)) {
1035
1207
  this.#emitTraceEvent(`Node ${node.title} is ignored`);
@@ -1168,6 +1340,153 @@ export class GraphProcessor {
1168
1340
  await this.#processNodeIfAllInputsAvailable(outputNode);
1169
1341
  }));
1170
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
+ }
1171
1490
  #getAttachedDataTo(node) {
1172
1491
  const nodeId = typeof node === 'string' ? node : node.id;
1173
1492
  let nodeData = this.#attachedNodeData.get(nodeId);
@@ -1185,7 +1504,10 @@ export class GraphProcessor {
1185
1504
  return { processId, shouldQueueOutputNodes: false };
1186
1505
  }
1187
1506
  const frozenOutputs = this.#resolveFrozenNodeOutputs(node, inputValues, processId);
1188
- 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) {
1189
1511
  await this.#processFrozenNode(node, processId, inputValues, frozenOutputs);
1190
1512
  }
1191
1513
  else if (node.isSplitRun) {
@@ -1235,20 +1557,24 @@ export class GraphProcessor {
1235
1557
  this.#nodeResults.set(node.id, outputValues);
1236
1558
  this.#visitedNodes.add(node.id);
1237
1559
  this.#accumulateCost(outputValues);
1238
- this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
1560
+ await this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
1239
1561
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
1240
1562
  node,
1241
1563
  outputs: outputValues,
1242
1564
  processId,
1243
1565
  }, this.#finishNodeTiming(timingStart))));
1244
1566
  }
1245
- #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
1246
- const setGlobalEffect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
1247
- if (!setGlobalEffect) {
1567
+ async #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
1568
+ const effect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
1569
+ if (!effect) {
1248
1570
  return;
1249
1571
  }
1250
- this.#globals.set(setGlobalEffect.variableId, setGlobalEffect.value);
1251
- emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id: setGlobalEffect.variableId, value: setGlobalEffect.value, processId }));
1572
+ if (effect.type === 'setStoredValue') {
1573
+ await this.#storedValueController.seed(effect.key, effect.value);
1574
+ return;
1575
+ }
1576
+ this.#globals.set(effect.variableId, effect.value);
1577
+ emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id: effect.variableId, value: effect.value, processId }));
1252
1578
  }
1253
1579
  async #processNormalNode(node, processId, inputValues) {
1254
1580
  // Use awaited emit (not emitDetached) so that listeners can yield to the
@@ -1256,9 +1582,7 @@ export class GraphProcessor {
1256
1582
  await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: inputValues, processId }));
1257
1583
  const timingStart = this.#startNodeTiming();
1258
1584
  try {
1259
- const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => {
1260
- emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs: partialOutputs, index, processId }));
1261
- });
1585
+ const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => this.#emitNodePartialOutput(node, partialOutputs, index, processId));
1262
1586
  this.#nodeResults.set(node.id, outputValues);
1263
1587
  this.#visitedNodes.add(node.id);
1264
1588
  this.#accumulateCost(outputValues);
@@ -1284,6 +1608,9 @@ export class GraphProcessor {
1284
1608
  await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({ node, error, processId }, durationMs, splitRunDurationMs)));
1285
1609
  this.#emitTraceEvent(`Node ${node.title} (${node.id}-${processId}) errored: ${error.stack}`);
1286
1610
  }
1611
+ #emitNodePartialOutput(node, outputs, index, processId) {
1612
+ emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs, index, processId }));
1613
+ }
1287
1614
  #getErrorExclusionReason(node, error, processId) {
1288
1615
  if (this.#getAttachedDataTo(node).races?.completed) {
1289
1616
  return RACE_LOSER_EXCLUSION_REASON;
@@ -1392,39 +1719,52 @@ export class GraphProcessor {
1392
1719
  if (this.#abortController.signal.aborted) {
1393
1720
  nodeAbortController.abort(getAbortSignalReason(this.#abortController.signal));
1394
1721
  }
1395
- const createContextProfileStart = this.#startRuntimeProfile();
1396
- const context = this.#createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput);
1397
- this.#finishRuntimeProfile('createNodeProcessContext', createContextProfileStart);
1398
- let results;
1722
+ let continuationFinalized = false;
1399
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
+ }
1400
1732
  await this.#waitUntilUnpaused();
1401
1733
  const implementationProfileStart = this.#startRuntimeProfile();
1734
+ let results;
1402
1735
  try {
1403
1736
  results = await instance.process(inputValues, context);
1404
1737
  }
1405
1738
  finally {
1406
1739
  this.#finishRuntimeProfile('nodeImplementation', implementationProfileStart);
1407
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;
1408
1754
  }
1409
1755
  finally {
1410
- this.#unregisterNodeAbortController(node.id, nodeAbortController);
1411
- }
1412
- const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
1413
- if (nodeAbortController.signal.aborted) {
1414
- if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
1415
- this.#successfulAbortTerminalProcessIds.add(processId);
1416
- }
1417
- else {
1418
- throw createGraphAbortError(abortReason, 'Aborted');
1756
+ if (!continuationFinalized) {
1757
+ this.#discardToolCallContinuation(processId, index);
1419
1758
  }
1759
+ this.#unregisterNodeAbortController(node.id, nodeAbortController);
1420
1760
  }
1421
- return results;
1422
1761
  }
1423
1762
  #getTokenizer() {
1424
1763
  return this.#context.tokenizer;
1425
1764
  }
1426
1765
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput) {
1427
1766
  const plugin = this.#registry.getPluginFor(node.type);
1767
+ const toolCallContinuation = this.#getToolCallContinuationContext(node, nodeAbortController.signal, processId, index);
1428
1768
  return buildNodeProcessContext({
1429
1769
  activeOutputPortIds: this.#getActiveOutputPortIds(node),
1430
1770
  attachedData: this.#getAttachedDataTo(node),
@@ -1452,6 +1792,7 @@ export class GraphProcessor {
1452
1792
  this.#globals.set(id, value);
1453
1793
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
1454
1794
  },
1795
+ toolCallContinuation,
1455
1796
  waitEvent: async (event) => {
1456
1797
  return new Promise((resolve, reject) => {
1457
1798
  const abortListener = () => {
@@ -1469,7 +1810,703 @@ export class GraphProcessor {
1469
1810
  },
1470
1811
  });
1471
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
+ }
1472
2506
  #getActiveOutputPortIds(node) {
2507
+ if (this.#sameGraphRunOwnerOverride) {
2508
+ return this.#sameGraphRunOwnerOverride.#getActiveOutputPortIds(node);
2509
+ }
1473
2510
  const outputConnections = getOutputNodesFrom(this.#executionState, node).connectionsToNodes;
1474
2511
  if (outputConnections.length === 0) {
1475
2512
  return new Set();
@@ -1506,6 +2543,13 @@ export class GraphProcessor {
1506
2543
  return relevantNodeIds;
1507
2544
  }
1508
2545
  #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
2546
+ if (this.#suppressGraphPartialOutputs) {
2547
+ return;
2548
+ }
2549
+ if (this.#sameGraphRunOwnerOverride) {
2550
+ this.#sameGraphRunOwnerOverride.#emitGraphPartialOutputIfNeeded(node, partialOutputs);
2551
+ return;
2552
+ }
1509
2553
  const { useAsGraphPartialOutput } = node.data ?? {};
1510
2554
  if (!(useAsGraphPartialOutput && this.#executor && this.#parent)) {
1511
2555
  return;
@@ -1553,6 +2597,7 @@ export class GraphProcessor {
1553
2597
  processor.#contextValues = this.#contextValues;
1554
2598
  processor.#parent = this;
1555
2599
  processor.#globals = this.#globals;
2600
+ processor.#storedValueController = this.#storedValueController;
1556
2601
  processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
1557
2602
  processor.#executor = {
1558
2603
  nodeId: node.id,