@valerypopoff/rivet2-core 2.1.4 → 2.1.6

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