@valerypopoff/rivet2-core 2.17.0 → 2.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (120) hide show
  1. package/dist/cjs/bundle.cjs +3197 -1461
  2. package/dist/cjs/bundle.cjs.map +4 -4
  3. package/dist/cjs/interpolationRuntime.cjs +40 -4
  4. package/dist/cjs/interpolationRuntime.cjs.map +2 -2
  5. package/dist/cjs/serialization.cjs +1880 -0
  6. package/dist/cjs/serialization.cjs.map +7 -0
  7. package/dist/cjs/webAppRuntime.cjs +168 -6
  8. package/dist/cjs/webAppRuntime.cjs.map +3 -3
  9. package/dist/esm/api/processSettings.js +1 -0
  10. package/dist/esm/exports.js +3 -0
  11. package/dist/esm/model/AgentResponseTrace.js +99 -34
  12. package/dist/esm/model/AgentResponseTracePresentation.js +130 -0
  13. package/dist/esm/model/DataValue.js +11 -2
  14. package/dist/esm/model/GlobalVariables.js +2 -1
  15. package/dist/esm/model/GraphBoundaryEffects.js +38 -1
  16. package/dist/esm/model/GraphExecutionState.js +81 -0
  17. package/dist/esm/model/GraphProcessor.js +625 -943
  18. package/dist/esm/model/GraphSchedulerBoundaryState.js +64 -0
  19. package/dist/esm/model/Nodes.js +5 -0
  20. package/dist/esm/model/ProjectBundle.js +69 -11
  21. package/dist/esm/model/ProjectBundleRuntime.js +54 -0
  22. package/dist/esm/model/ProjectGraphCallSites.js +46 -0
  23. package/dist/esm/model/SchedulerBoundaryPlanner.js +233 -0
  24. package/dist/esm/model/SubprocessorBridge.js +125 -87
  25. package/dist/esm/model/ToolCallContinuationCoordinator.js +1 -1
  26. package/dist/esm/model/chat-v2/aiSdkBridge.js +15 -12
  27. package/dist/esm/model/chat-v2/chatV2CallObserver.js +2 -4
  28. package/dist/esm/model/chat-v2/chatV2CredentialNames.js +5 -1
  29. package/dist/esm/model/chat-v2/chatV2Outputs.js +2 -2
  30. package/dist/esm/model/chat-v2/chatV2Pipeline.js +11 -1
  31. package/dist/esm/model/chat-v2/chatV2ProviderProfile.js +3 -2
  32. package/dist/esm/model/chat-v2/chatV2ProviderRegistry.js +46 -6
  33. package/dist/esm/model/chat-v2/chatV2RuntimeOptions.js +7 -0
  34. package/dist/esm/model/chat-v2/chatV2UsageAccounting.js +10 -0
  35. package/dist/esm/model/chat-v2/llmChatV2Body.js +3 -3
  36. package/dist/esm/model/chat-v2/llmChatV2CacheBoundary.js +5 -2
  37. package/dist/esm/model/chat-v2/llmChatV2NodeData.js +1 -0
  38. package/dist/esm/model/chat-v2/llmChatV2NodeEditors.js +25 -15
  39. package/dist/esm/model/chat-v2/llmInvocationCoordinator.js +10 -2
  40. package/dist/esm/model/chat-v2/llmInvocationResultProjector.js +17 -0
  41. package/dist/esm/model/chat-v2/llmModelCandidate.js +2 -1
  42. package/dist/esm/model/chat-v2/llmProfile.js +2 -1
  43. package/dist/esm/model/chat-v2/llmProfileBody.js +9 -0
  44. package/dist/esm/model/chat-v2/llmProfileFallback.js +7 -4
  45. package/dist/esm/model/chat-v2/llmProfileFieldRegistry.js +1 -0
  46. package/dist/esm/model/chat-v2/llmProfileHealthStore.js +16 -3
  47. package/dist/esm/model/chat-v2/messageConverter.js +18 -16
  48. package/dist/esm/model/chat-v2/modelRegistry.js +14 -4
  49. package/dist/esm/model/chat-v2/openRouterModel.js +73 -0
  50. package/dist/esm/model/chat-v2/parallelToolCalls.js +2 -0
  51. package/dist/esm/model/chat-v2/providerOptions.js +30 -25
  52. package/dist/esm/model/classifier/credentials.js +13 -3
  53. package/dist/esm/model/classifier/limits.js +33 -3
  54. package/dist/esm/model/classifier/perplexity.js +63 -0
  55. package/dist/esm/model/classifier/profile.js +151 -0
  56. package/dist/esm/model/classifier/profileExecution.js +294 -0
  57. package/dist/esm/model/classifier/providers.js +217 -30
  58. package/dist/esm/model/classifier/state.js +4 -1
  59. package/dist/esm/model/classifier/types.js +11 -1
  60. package/dist/esm/model/nodeRunFailure.js +8 -1
  61. package/dist/esm/model/nodes/CallGraphNode.js +6 -0
  62. package/dist/esm/model/nodes/ClassifierEvaluateNode.js +257 -66
  63. package/dist/esm/model/nodes/ClassifierProfileNode.js +133 -0
  64. package/dist/esm/model/nodes/DelegateFunctionCallNode.js +1 -1
  65. package/dist/esm/model/nodes/LLMChatV2Node.js +2 -1
  66. package/dist/esm/model/nodes/SubGraphNode.js +4 -0
  67. package/dist/esm/model/nodes/toolCallDelegation.js +5 -1
  68. package/dist/esm/model/profileSuspensionHints.js +8 -0
  69. package/dist/esm/serialization.js +2 -0
  70. package/dist/esm/utils/coerceType.js +11 -1
  71. package/dist/esm/webAppRuntime.js +1 -0
  72. package/dist/types/exports.d.ts +3 -0
  73. package/dist/types/model/AgentResponseTrace.d.ts +15 -4
  74. package/dist/types/model/AgentResponseTracePresentation.d.ts +15 -0
  75. package/dist/types/model/DataValue.d.ts +12 -8
  76. package/dist/types/model/ExecutorProtocol.d.ts +14 -2
  77. package/dist/types/model/GraphBoundaryEffects.d.ts +10 -1
  78. package/dist/types/model/GraphExecutionState.d.ts +68 -0
  79. package/dist/types/model/GraphProcessor.d.ts +1 -0
  80. package/dist/types/model/GraphSchedulerBoundaryState.d.ts +96 -0
  81. package/dist/types/model/Nodes.d.ts +7 -4
  82. package/dist/types/model/ProcessContext.d.ts +12 -3
  83. package/dist/types/model/ProjectBundle.d.ts +18 -4
  84. package/dist/types/model/ProjectBundleRuntime.d.ts +24 -0
  85. package/dist/types/model/ProjectGraphCallSites.d.ts +12 -0
  86. package/dist/types/model/RivetUIContext.d.ts +1 -1
  87. package/dist/types/model/SchedulerBoundaryPlanner.d.ts +42 -0
  88. package/dist/types/model/Settings.d.ts +1 -0
  89. package/dist/types/model/SubgraphProjectTarget.d.ts +6 -0
  90. package/dist/types/model/SubprocessorBridge.d.ts +2 -0
  91. package/dist/types/model/chat-v2/chatV2CredentialNames.d.ts +4 -0
  92. package/dist/types/model/chat-v2/chatV2Outputs.d.ts +1 -1
  93. package/dist/types/model/chat-v2/chatV2ProviderRegistry.d.ts +79 -1
  94. package/dist/types/model/chat-v2/chatV2ProviderTypes.d.ts +1 -1
  95. package/dist/types/model/chat-v2/chatV2UsageAccounting.d.ts +2 -0
  96. package/dist/types/model/chat-v2/llmChatV2NodeData.d.ts +2 -1
  97. package/dist/types/model/chat-v2/llmInvocationCoordinator.d.ts +2 -0
  98. package/dist/types/model/chat-v2/llmInvocationResultProjector.d.ts +2 -0
  99. package/dist/types/model/chat-v2/llmProfileFallback.d.ts +51 -3
  100. package/dist/types/model/chat-v2/llmProfileFieldRegistry.d.ts +9 -6
  101. package/dist/types/model/chat-v2/llmProfileHealthStore.d.ts +6 -2
  102. package/dist/types/model/chat-v2/modelRegistry.d.ts +5 -4
  103. package/dist/types/model/chat-v2/openRouterModel.d.ts +2 -0
  104. package/dist/types/model/chat-v2/providerOptions.d.ts +2 -13
  105. package/dist/types/model/classifier/credentials.d.ts +4 -0
  106. package/dist/types/model/classifier/limits.d.ts +4 -1
  107. package/dist/types/model/classifier/perplexity.d.ts +7 -0
  108. package/dist/types/model/classifier/profile.d.ts +46 -0
  109. package/dist/types/model/classifier/profileExecution.d.ts +32 -0
  110. package/dist/types/model/classifier/providers.d.ts +32 -1
  111. package/dist/types/model/classifier/types.d.ts +9 -0
  112. package/dist/types/model/nodes/ClassifierEvaluateNode.d.ts +14 -12
  113. package/dist/types/model/nodes/ClassifierProfileNode.d.ts +20 -0
  114. package/dist/types/model/nodes/SubGraphNode.d.ts +1 -1
  115. package/dist/types/model/nodes/toolCallDelegation.d.ts +3 -1
  116. package/dist/types/model/profileSuspensionHints.d.ts +8 -0
  117. package/dist/types/recording/ExecutionRecorder.d.ts +5 -1
  118. package/dist/types/serialization.d.ts +2 -0
  119. package/dist/types/webAppRuntime.d.ts +1 -0
  120. package/package.json +7 -1
@@ -1,3 +1,6 @@
1
+ import { GraphInvocationState, GraphSharedExecutionState } from './GraphExecutionState.js';
2
+ import { planStreamingWatchTopology, planAsyncBranchTopology, getAsyncBranchWatchViolation, } from './SchedulerBoundaryPlanner.js';
3
+ import { GraphSchedulerBoundaryState, } from './GraphSchedulerBoundaryState.js';
1
4
  import {} from './DataValue.js';
2
5
  import { IF_PORT, } from './NodeBase.js';
3
6
  import PQueue from '../utils/pQueueCompat.js';
@@ -10,14 +13,14 @@ import { getPluginConfig } from '../utils/index.js';
10
13
  import { isGraphExecutionPlan, preprocessGraphState, toReusableGraphExecutionPlan, } from './GraphPreprocessor.js';
11
14
  import { getGraphBoundary } from './GraphBoundaryCache.js';
12
15
  import { createGraphOutputSelection } from './GraphOutputSelection.js';
13
- import { applyFrozenGraphBoundaryEffects, commitGraphOutputValue, ensureGraphCostOutput, } from './GraphBoundaryEffects.js';
16
+ import { applyFrozenGraphBoundaryEffects, commitGraphOutputValue, ensureGraphCostOutput, addGraphCostBreakdown, readGraphCostBreakdown, graphCostBreakdownMatchesCost, } from './GraphBoundaryEffects.js';
14
17
  import { coerceGraphOutputValue } from './nodes/GraphOutputNode.js';
15
18
  import { replayExecutionRecording } from './RecordingPlayer.js';
16
19
  import { didLoopControllerBreak, LOOP_NOT_BROKEN_SENTINEL } from './loopControllerBreak.js';
17
20
  import { buildNodeProcessContext } from './ProcessContextBuilder.js';
18
21
  import { processSplitRunNode } from './SplitRunProcessor.js';
19
22
  import { getInputNodesTo, getMissingRequiredInputs, getOutputNodesFrom, getStartNodes, getWaitingForInputNode, hasErroredInputNode, } from './NodeExecutionPlanner.js';
20
- import { wireSubprocessorEvents, wireSubprocessorLifecycle } from './SubprocessorBridge.js';
23
+ import { cleanupSubprocessorBindings, wireSubprocessorEvents, wireSubprocessorLifecycle, } from './SubprocessorBridge.js';
21
24
  import { createGraphAbortError, createGraphAbortErrorFromSignal, createGraphAbortReason, getAbortSignalReason, getGraphAbortReasonFromError, getGraphAbortReasonFromSignal, isAbortLikeError, isRaceLoserGraphAbortReason, isSuccessfulNonRaceGraphAbortReason, RACE_LOSER_EXCLUSION_REASON, SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON, } from './GraphAbortReasons.js';
22
25
  import { emitDetached } from '../utils/emitDetached.js';
23
26
  import { GraphRunLifecycle } from './GraphRunLifecycle.js';
@@ -42,7 +45,7 @@ import { resolveNodePrefabInstance } from './NodePrefabResolver.js';
42
45
  import { ConnectedToolContinuationHost, } from './ConnectedToolContinuationHost.js';
43
46
  import { resolveProjectGlobalVariables } from './GlobalVariables.js';
44
47
  import { loadProjectReferenceTree } from './ProjectReferenceLoader.js';
45
- import { getSubgraphProjectKey, isSubgraphProjectKey, } from './SubgraphProjectTarget.js';
48
+ import { getSubgraphProjectKey, isSubgraphProjectKey } from './SubgraphProjectTarget.js';
46
49
  import { MAX_CAUGHT_STREAMING_CHUNKS } from './nodes/CatchStreamingChunksNode.js';
47
50
  import { isEqual } from 'lodash-es';
48
51
  // eslint-disable-next-line import/no-cycle -- There has to be a cycle because CodeRunner needs to import the entirety of Rivet
@@ -151,6 +154,9 @@ function replaceRecordContents(target, source) {
151
154
  Object.assign(target, source);
152
155
  }
153
156
  export class GraphProcessor {
157
+ #run = new GraphInvocationState();
158
+ #shared = new GraphSharedExecutionState();
159
+ #boundaries = new GraphSchedulerBoundaryState();
154
160
  // Per-instance state
155
161
  #graph;
156
162
  #graphCallPath;
@@ -179,21 +185,9 @@ export class GraphProcessor {
179
185
  #asyncBranchPlansByTriggerNodeId = new Map();
180
186
  #consumedAsyncBranchTriggerNodeId;
181
187
  #asyncBranchInputAnchors;
182
- #streamingWatchPlansBySourceNodeId = new Map();
183
- #streamingWatchPlansByWatchNodeId = new Map();
184
- #streamingOutputWatches = new Map();
185
- #streamingCatchPlansBySourceNodeId = new Map();
186
- #streamingCatchTasks = new Set();
187
- #graphOutputPartialBindingsBySourceNodeId = new Map();
188
188
  #graphOutputPartialListener;
189
189
  #consumedStreamingWatchNodeId;
190
190
  #streamingWatchInvocation;
191
- #graphInputStreams = {};
192
- #callerInputStreams = new Map();
193
- #inputStreamRoutes = new Map();
194
- #streamCallerTasks = new Set();
195
- #inputStreamDisposers = [];
196
- #pendingGraphInputFinals = new Map();
197
191
  #registry;
198
192
  #concurrency;
199
193
  #executionPlanCacheMode;
@@ -215,64 +209,23 @@ export class GraphProcessor {
215
209
  runFromNodeId;
216
210
  /** The node that is executing this graph, almost always a subgraph node. Undefined for root. */
217
211
  #executor;
218
- #rootRunId = undefined;
219
- #graphRunId = undefined;
220
- #parentGraphRunId = undefined;
221
212
  /** The interval between nodeFinish events when playing back a recording. I.e. how fast the playback is. */
222
213
  recordingPlaybackChatLatency = 1000;
223
214
  warnOnInvalidGraph = false;
224
- // Per-process state
225
- #erroredNodes = undefined; // Values are strings in recordings
226
- #failureOutputsByProcessId = undefined;
227
- #remainingNodes = undefined;
228
- #visitedNodes = undefined;
229
- #currentlyProcessing = undefined;
230
- #context = undefined;
231
- #nodeResults = undefined;
232
- #abortController = undefined;
233
- #processingQueue = undefined;
234
- #graphInputs = undefined;
235
- #graphOutputs = undefined;
236
- #executionCache = undefined;
237
- #queuedNodes = undefined;
238
- /**
239
- * Nodes deferred only because Run To reached its initial scheduler quiescence.
240
- * A streaming Stop can legitimately resume one of those selected paths later.
241
- */
242
- #deferredRunToIgnoredNodes = undefined;
243
- #loopControllersSeen = undefined;
244
- #subprocessors = undefined;
215
+ // Instance configuration and compiled definitions remain outside run state.
245
216
  #contextValues = undefined;
246
- #globals = undefined;
247
217
  /** IDs assigned by the previous root invocation, retained only to reset project globals on reuse. */
248
218
  #projectGlobalVariableIdsAssignedByPreviousRootRun = new Set();
249
219
  /** Snapshot for lifecycle recording, populated only while a root run starts. */
250
220
  #initialProjectGlobalVariablesForRun = new Map();
251
- #storedValueController = undefined;
252
- #knowledgeStoreController = undefined;
253
- #attachedNodeData = undefined;
254
- #successfulAbortTerminalProcessIds = undefined;
255
- #totalCost = 0;
256
- #ignoreNodes = undefined;
257
- #hasPreloadedData = false;
258
- #loadedProjects = undefined;
259
- #subgraphTargetCache = new Map();
260
221
  #definitions = undefined;
261
222
  #scc = undefined;
262
223
  #graphExecutionPlan;
263
- #nodeProcessContextBase = undefined;
264
- #runToRelevantNodeIds;
265
- #graphOutputSelection;
266
224
  #managedAsyncBranches;
267
225
  #managedAsyncBranchFailures = [];
268
- #streamingWatchFailures = [];
269
226
  #runCompletionPromise;
270
227
  #nodesNotInCycle = undefined;
271
228
  #executionGraphNodes = undefined;
272
- #nodeAbortControllers = new Map();
273
- #graphInputNodeValues = {};
274
- /** User input nodes that are pending user input. */
275
- #pendingUserInputs = undefined;
276
229
  #unsubscribeTokenizerError;
277
230
  get isRunning() {
278
231
  return this.#lifecycle.isRunning;
@@ -374,7 +327,7 @@ export class GraphProcessor {
374
327
  const preprocessedGraph = preprocessGraphState({
375
328
  inputAnchorDefinitions: this.#asyncBranchInputAnchors,
376
329
  graph: this.#graph,
377
- loadedProjects: this.#loadedProjects,
330
+ loadedProjects: this.#run.loadedProjects,
378
331
  project: this.#project,
379
332
  registry: this.#registry,
380
333
  warnOnInvalidGraph: this.warnOnInvalidGraph,
@@ -438,7 +391,7 @@ export class GraphProcessor {
438
391
  this.#scc = preprocessedGraph.stronglyConnectedComponents;
439
392
  this.#nodesNotInCycle = preprocessedGraph.nodesNotInCycle;
440
393
  this.#executionGraphNodes = preprocessedGraph.graphNodes;
441
- this.#remainingNodes = new Set(this.#executionGraphNodes.map((node) => node.id));
394
+ this.#run.remainingNodes = new Set(this.#executionGraphNodes.map((node) => node.id));
442
395
  this.#graphExecutionPlan = isGraphExecutionPlan(preprocessedGraph) ? preprocessedGraph : undefined;
443
396
  }
444
397
  #seededExecutionPlanForNextRun() {
@@ -463,11 +416,12 @@ export class GraphProcessor {
463
416
  }
464
417
  #buildExecutionMetadata() {
465
418
  return {
466
- rootRunId: this.#rootRunId,
467
- graphRunId: this.#graphRunId,
419
+ rootRunId: this.#run.rootRunId,
420
+ graphRunId: this.#run.graphRunId,
468
421
  graphId: this.#graph.metadata.id,
422
+ projectId: this.#project.metadata.id,
469
423
  ...(this.#recordingProjectScope ? { projectScope: this.#recordingProjectScope } : {}),
470
- parentGraphRunId: this.#parentGraphRunId,
424
+ parentGraphRunId: this.#run.parentGraphRunId,
471
425
  executor: this.#executor
472
426
  ? {
473
427
  nodeId: this.#executor.nodeId,
@@ -476,7 +430,7 @@ export class GraphProcessor {
476
430
  splitIndex: this.#executor.index,
477
431
  }
478
432
  : undefined,
479
- ...(this.#context?.evaluation === undefined ? {} : { evaluation: this.#context.evaluation }),
433
+ ...(this.#run.context?.evaluation === undefined ? {} : { evaluation: this.#run.context.evaluation }),
480
434
  };
481
435
  }
482
436
  get recordingProjectScope() {
@@ -510,11 +464,11 @@ export class GraphProcessor {
510
464
  }
511
465
  }
512
466
  userInput(nodeId, values) {
513
- const pending = this.#pendingUserInputs[nodeId];
467
+ const pending = this.#run.pendingUserInputs[nodeId];
514
468
  if (pending) {
515
469
  pending.resolve(values);
516
470
  }
517
- for (const processor of this.#subprocessors) {
471
+ for (const processor of this.#run.subprocessors) {
518
472
  processor.userInput(nodeId, values);
519
473
  }
520
474
  }
@@ -538,7 +492,7 @@ export class GraphProcessor {
538
492
  return Promise.resolve();
539
493
  }
540
494
  const abortReason = createGraphAbortReason(successful, error);
541
- this.#abortController.abort(abortReason);
495
+ this.#run.abortController.abort(abortReason);
542
496
  this.#abortActiveNodeControllers(abortReason);
543
497
  this.#cancelStreamingOutputWatches();
544
498
  if (!this.#suppressGraphLifecycleEvents) {
@@ -547,7 +501,7 @@ export class GraphProcessor {
547
501
  emitDetached(this.#emitter, 'abort', { successful, error });
548
502
  }
549
503
  }
550
- await this.#processingQueue.onIdle();
504
+ await this.#run.processingQueue.onIdle();
551
505
  if (!this.#isSubProcessor) {
552
506
  await this.#managedAsyncBranches?.drain();
553
507
  }
@@ -570,7 +524,7 @@ export class GraphProcessor {
570
524
  if (!this.#lifecycle.isPaused) {
571
525
  return;
572
526
  }
573
- if (this.#abortController.signal.aborted) {
527
+ if (this.#run.abortController.signal.aborted) {
574
528
  throw this.#lifecycle.getAbortError();
575
529
  }
576
530
  await new Promise((resolve, reject) => {
@@ -583,10 +537,10 @@ export class GraphProcessor {
583
537
  resolve();
584
538
  });
585
539
  const cleanup = () => {
586
- this.#abortController.signal.removeEventListener('abort', abortListener);
540
+ this.#run.abortController.signal.removeEventListener('abort', abortListener);
587
541
  unsubscribeResume();
588
542
  };
589
- this.#abortController.signal.addEventListener('abort', abortListener, { once: true });
543
+ this.#run.abortController.signal.addEventListener('abort', abortListener, { once: true });
590
544
  });
591
545
  }
592
546
  async *events() {
@@ -615,12 +569,12 @@ export class GraphProcessor {
615
569
  }
616
570
  this.#assertStreamingOutputWatchPreloadCanBeAdded(nodeId);
617
571
  this.#preloadedNodeResults.set(nodeId, data);
618
- this.#hasPreloadedData = true;
572
+ this.#run.hasPreloadedData = true;
619
573
  // Preserve the historical ability to preload an idle processor as well as
620
574
  // inject a boundary into a run that has already initialized.
621
575
  if (this.#lifecycle.isRunning && this.#isNodeSelected(nodeId)) {
622
- this.#nodeResults.set(nodeId, data);
623
- this.#visitedNodes.add(nodeId);
576
+ this.#run.nodeResults.set(nodeId, data);
577
+ this.#run.visitedNodes.add(nodeId);
624
578
  }
625
579
  }
626
580
  setFrozenNodeOutputResolver(resolver) {
@@ -641,7 +595,7 @@ export class GraphProcessor {
641
595
  if (this.#definitions != null) {
642
596
  return;
643
597
  }
644
- this.#loadedProjects ??= {};
598
+ this.#run.loadedProjects ??= {};
645
599
  // This synchronous inspection API can be called before processGraph has
646
600
  // loaded references. Its provisional definitions must never be reused as
647
601
  // a runtime plan for a later fully loaded invocation.
@@ -679,13 +633,13 @@ export class GraphProcessor {
679
633
  this.#initProcessState();
680
634
  return await replayExecutionRecording({
681
635
  emitter: this.#emitter,
682
- erroredNodes: this.#erroredNodes,
683
- graphInputs: this.#graphInputs,
684
- graphOutputs: this.#graphOutputs,
636
+ erroredNodes: this.#run.erroredNodes,
637
+ graphInputs: this.#run.graphInputs,
638
+ graphOutputs: this.#run.graphOutputs,
685
639
  fallbackGraphId: this.#graph.metadata.id,
686
640
  initialReplayExecution: this.#buildExecutionMetadata(),
687
641
  isAborted: () => this.#lifecycle.isAborted,
688
- nodeResults: this.#nodeResults,
642
+ nodeResults: this.#run.nodeResults,
689
643
  project: this.#project,
690
644
  recorder,
691
645
  recordingPlaybackChatLatency: this.recordingPlaybackChatLatency,
@@ -693,82 +647,57 @@ export class GraphProcessor {
693
647
  this.#contextValues = contextValues;
694
648
  },
695
649
  setGraphInputs: (graphInputs) => {
696
- this.#graphInputs = graphInputs;
650
+ this.#run.graphInputs = graphInputs;
697
651
  },
698
652
  setGraphOutputs: (graphOutputs) => {
699
- this.#graphOutputs = graphOutputs;
653
+ this.#run.graphOutputs = graphOutputs;
700
654
  },
701
655
  setRunning: (running) => {
702
656
  if (!running)
703
657
  this.#lifecycle.complete();
704
658
  },
705
- visitedNodes: this.#visitedNodes,
659
+ visitedNodes: this.#run.visitedNodes,
706
660
  waitUntilUnpaused: () => this.#waitUntilUnpaused(),
707
661
  });
708
662
  }
709
663
  #initProcessState() {
710
664
  this.#lifecycle.begin();
711
- this.#nodeResults = new Map(this.#preloadedNodeResults);
712
- this.#visitedNodes = new Set(this.#preloadedNodeResults.keys());
713
- this.#hasPreloadedData = this.#preloadedNodeResults.size > 0;
714
- this.#erroredNodes = new Map();
715
- this.#failureOutputsByProcessId = new Map();
716
- this.#currentlyProcessing = new Set();
665
+ // Retain the invocation owner; child events and async cost accounting use it.
666
+ if (!this.#isSubProcessor)
667
+ this.#shared = this.#shared.nextRootRun();
717
668
  // A processor may be constructed with a reusable execution plan. In that
718
669
  // case preprocessing happened before this run, so retain the compiled
719
670
  // execution-node set rather than restoring the authored graph nodes (which
720
671
  // may include topology-only Data Bus nodes).
721
- this.#remainingNodes = new Set(this.#seededExecutionPlanForNextRun()?.nodeIds ?? []);
722
- this.#pendingUserInputs = {};
723
- this.#processingQueue = new PQueue({ concurrency: this.#concurrency.nodeConcurrency });
724
- this.#graphOutputs = this.#sharedRunStateOverride?.graphOutputs ?? {};
725
- this.#executionCache ??= new Map();
726
- this.#queuedNodes = new Set();
727
- this.#deferredRunToIgnoredNodes = new Set();
672
+ this.#run.initialize({
673
+ preloadedNodeResults: this.#preloadedNodeResults,
674
+ remainingNodeIds: this.#seededExecutionPlanForNextRun()?.nodeIds ?? [],
675
+ processingQueue: new PQueue({ concurrency: this.#concurrency.nodeConcurrency }),
676
+ createAbortController: () => this.#newAbortController(),
677
+ loadedProjects: this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {},
678
+ sharedOverride: this.#sharedRunStateOverride,
679
+ });
680
+ this.#shared.executionCache ??= new Map();
728
681
  this.#connectedToolContinuationHost.reset();
729
682
  this.#continuationCompletionOwnerByNodeId = new Map();
730
683
  this.#effectiveConnectionsForRun = undefined;
731
684
  this.#asyncBranchPlansByTriggerNodeId = new Map();
732
- this.#streamingWatchPlansBySourceNodeId = new Map();
733
- this.#streamingWatchPlansByWatchNodeId = new Map();
734
- this.#streamingOutputWatches = new Map();
735
- this.#streamingCatchPlansBySourceNodeId = new Map();
736
- this.#streamingCatchTasks = new Set();
737
- this.#graphOutputPartialBindingsBySourceNodeId = new Map();
738
- this.#loopControllersSeen = new Set();
739
- this.#subprocessors = new Set();
740
- this.#attachedNodeData = this.#sharedRunStateOverride?.attachedNodeData ?? new Map();
741
- this.#globals ??= new Map();
685
+ this.#boundaries.resetTopology();
686
+ this.#shared.globals ??= new Map();
742
687
  if (!this.#isSubProcessor) {
743
- this.#storedValueController = new RivetStoredValueController(this.#storedValueStore);
744
- this.#knowledgeStoreController = new KnowledgeStoreController(this.#knowledgeStores);
688
+ this.#shared.storedValueController = new RivetStoredValueController(this.#storedValueStore);
689
+ this.#shared.knowledgeStoreController = new KnowledgeStoreController(this.#knowledgeStores);
745
690
  }
746
- this.#ignoreNodes = new Set();
747
- this.#nodeProcessContextBase = undefined;
748
- this.#runToRelevantNodeIds = undefined;
749
- this.#graphOutputSelection = undefined;
750
691
  if (!this.#isSubProcessor) {
751
692
  this.#managedAsyncBranches = new ManagedAsyncBranches();
752
693
  this.#managedAsyncBranchFailures = [];
753
694
  }
754
- this.#streamingWatchFailures = [];
755
- this.#abortController = this.#newAbortController();
756
- this.#successfulAbortTerminalProcessIds = new Set();
757
- this.#totalCost = 0;
758
- this.#nodeAbortControllers = new Map();
759
- this.#loadedProjects =
760
- this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects ? { ...this.#runtimeCache.loadedProjects } : {};
761
- if (!this.#isSubProcessor) {
762
- // Latest and Published are selected afresh for each root invocation.
763
- this.#subgraphTargetCache = new Map();
764
- }
765
695
  // Referenced projects can be reloaded per run when loaded-project caching is disabled.
766
696
  if (!this.#cacheLoadedProjects && (this.#project.references?.length ?? 0) > 0) {
767
697
  if (this.#runtimeCache) {
768
698
  this.#runtimeCache.graphBoundaries = undefined;
769
699
  }
770
700
  }
771
- this.#graphInputNodeValues = this.#sharedRunStateOverride?.graphInputNodeValues ?? {};
772
701
  }
773
702
  /** Main function for running a graph. Runs a graph and returns the outputs from the output nodes of the graph. */
774
703
  async processGraph(
@@ -796,12 +725,7 @@ export class GraphProcessor {
796
725
  try {
797
726
  try {
798
727
  this.#profileRuntimeSync('initializeGraphRun', () => this.#initializeGraphRun(context, inputs, contextValues));
799
- this.#graphInputStreams = options.graphInputStreams ?? {};
800
- this.#callerInputStreams = new Map();
801
- this.#inputStreamRoutes = new Map();
802
- this.#streamCallerTasks = new Set();
803
- this.#inputStreamDisposers = [];
804
- this.#pendingGraphInputFinals = new Map();
728
+ this.#boundaries.initializeInputStreams(options.graphInputStreams);
805
729
  await this.#profileRuntimeAsync('loadProjectReferences', () => this.#loadProjectReferences());
806
730
  this.#profileRuntimeSync('initializeProjectGlobalVariables', () => this.#initializeProjectGlobalVariablesForRootRun());
807
731
  this.#profileRuntimeSync('prepareNodeProcessContextBase', () => this.#prepareNodeProcessContextBase());
@@ -815,11 +739,11 @@ export class GraphProcessor {
815
739
  if (this.runToNodeIds !== undefined) {
816
740
  throw new Error('requestedGraphOutputIds cannot be combined with runToNodeIds');
817
741
  }
818
- this.#graphOutputSelection = createGraphOutputSelection({ nodes: this.#executionGraphNodes, connections: this.#getEffectiveConnections() }, requestedGraphOutputIds, (node) => getInputNodesTo(this.#executionState, node));
819
- for (const nodeId of this.#nodeResults.keys()) {
742
+ this.#run.graphOutputSelection = createGraphOutputSelection({ nodes: this.#executionGraphNodes, connections: this.#getEffectiveConnections() }, requestedGraphOutputIds, (node) => getInputNodesTo(this.#executionState, node));
743
+ for (const nodeId of this.#run.nodeResults.keys()) {
820
744
  if (!this.#isNodeSelected(nodeId)) {
821
- this.#nodeResults.delete(nodeId);
822
- this.#visitedNodes.delete(nodeId);
745
+ this.#run.nodeResults.delete(nodeId);
746
+ this.#run.visitedNodes.delete(nodeId);
823
747
  }
824
748
  }
825
749
  }
@@ -853,8 +777,8 @@ export class GraphProcessor {
853
777
  // Publish a snapshot instead of the live root output object. In particular,
854
778
  // the provisional cost must not occupy the root cost port before managed
855
779
  // async branches contribute their cost during finalization.
856
- const outputsReady = { ...this.#graphOutputs };
857
- ensureGraphCostOutput(outputsReady, this.#totalCost);
780
+ const outputsReady = { ...this.#run.graphOutputs };
781
+ ensureGraphCostOutput(outputsReady, this.#run.totalCost, this.#run.costBreakdown);
858
782
  await this.#emitter.emit('graphOutputsReady', this.#withExecution({ graph: this.#graph, outputs: outputsReady }));
859
783
  outputsWerePublishedEarly = true;
860
784
  resolveOutputsReady?.(outputsReady);
@@ -864,18 +788,20 @@ export class GraphProcessor {
864
788
  return await this.#profileRuntimeAsync('finalizeGraphRun', () => this.#finalizeGraphRun());
865
789
  }
866
790
  finally {
867
- for (const dispose of this.#inputStreamDisposers)
868
- dispose();
869
- this.#pendingGraphInputFinals.clear();
870
- for (const streams of this.#callerInputStreams.values()) {
871
- for (const relay of Object.values(streams))
872
- relay.finish({ error: new Error('Graph input stream owner finished') });
791
+ try {
792
+ try {
793
+ this.#boundaries.releaseInputStreams();
794
+ }
795
+ finally {
796
+ await this.#drainSchedulerBoundaries();
797
+ }
798
+ }
799
+ finally {
800
+ this.#graphOutputPartialListener = undefined;
801
+ this.#lifecycle.complete();
802
+ this.#cleanupTokenizerErrorListener();
803
+ await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
873
804
  }
874
- await this.#drainSchedulerBoundaries();
875
- this.#graphOutputPartialListener = undefined;
876
- this.#lifecycle.complete();
877
- this.#cleanupTokenizerErrorListener();
878
- await this.#profileRuntimeAsync('emitFinish', () => this.#emitFinishIfNeeded());
879
805
  }
880
806
  })();
881
807
  this.#runCompletionPromise = completionPromise;
@@ -903,11 +829,11 @@ export class GraphProcessor {
903
829
  #initializeGraphRun(context, inputs, contextValues) {
904
830
  this.#initializeExecutionIdentity();
905
831
  this.#initProcessState();
906
- this.#context = context;
907
- this.#graphInputs = inputs;
832
+ this.#run.context = context;
833
+ this.#run.graphInputs = inputs;
908
834
  this.#contextValues = contextValues;
909
835
  this.#cleanupTokenizerErrorListener();
910
- const unsubscribeTokenizerError = this.#context.tokenizer.on('error', (error) => {
836
+ const unsubscribeTokenizerError = this.#run.context.tokenizer.on('error', (error) => {
911
837
  emitDetached(this.#emitter, 'error', { error });
912
838
  });
913
839
  this.#unsubscribeTokenizerError =
@@ -919,27 +845,27 @@ export class GraphProcessor {
919
845
  return;
920
846
  // Resolve before touching the shared map. An invalid reference or definition
921
847
  // must fail startup without leaving a partial new set of authored globals.
922
- const legacyProjects = Object.fromEntries(Object.entries(this.#loadedProjects).filter(([key]) => !isSubgraphProjectKey(key)));
848
+ const legacyProjects = Object.fromEntries(Object.entries(this.#run.loadedProjects).filter(([key]) => !isSubgraphProjectKey(key)));
923
849
  const resolved = resolveProjectGlobalVariables(this.#project, legacyProjects);
924
850
  for (const id of this.#projectGlobalVariableIdsAssignedByPreviousRootRun) {
925
- this.#globals.delete(id);
851
+ this.#shared.globals.delete(id);
926
852
  }
927
853
  for (const [id, value] of resolved) {
928
- this.#globals.set(id, value);
854
+ this.#shared.globals.set(id, value);
929
855
  }
930
856
  this.#projectGlobalVariableIdsAssignedByPreviousRootRun = new Set(resolved.keys());
931
857
  this.#initialProjectGlobalVariablesForRun = resolved;
932
858
  }
933
859
  #initializeExecutionIdentity() {
934
860
  if (this.#executionIdentityOverride) {
935
- this.#rootRunId = this.#executionIdentityOverride.rootRunId;
936
- this.#graphRunId = this.#executionIdentityOverride.graphRunId;
937
- this.#parentGraphRunId = this.#executionIdentityOverride.parentGraphRunId;
861
+ this.#run.rootRunId = this.#executionIdentityOverride.rootRunId;
862
+ this.#run.graphRunId = this.#executionIdentityOverride.graphRunId;
863
+ this.#run.parentGraphRunId = this.#executionIdentityOverride.parentGraphRunId;
938
864
  }
939
865
  else {
940
- this.#rootRunId = this.#parent ? this.#parent.#rootRunId : nanoid();
941
- this.#graphRunId = nanoid();
942
- this.#parentGraphRunId = this.#parent ? this.#parent.#graphRunId : undefined;
866
+ this.#run.rootRunId = this.#parent ? this.#parent.#run.rootRunId : nanoid();
867
+ this.#run.graphRunId = nanoid();
868
+ this.#run.parentGraphRunId = this.#parent ? this.#parent.#run.graphRunId : undefined;
943
869
  }
944
870
  }
945
871
  async #emitRootStartupError(error) {
@@ -958,26 +884,26 @@ export class GraphProcessor {
958
884
  // is already a GraphProcessor wrapper. Always resolve the original host
959
885
  // observer from the root run so nested LLM calls are not emitted once by
960
886
  // every ancestor before their own event is bridged to the root emitter.
961
- const hostChatV2Observer = this.getRootProcessor().#context.onChatV2CallFinished;
962
- const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#context.onLLMChatOutputSnapshot;
963
- const hostLLMProfileAttemptObserver = this.getRootProcessor().#context.onLLMProfileAttempt;
964
- this.#nodeProcessContextBase = {
965
- ...this.#context,
887
+ const hostChatV2Observer = this.getRootProcessor().#run.context.onChatV2CallFinished;
888
+ const hostLLMChatOutputSnapshotObserver = this.getRootProcessor().#run.context.onLLMChatOutputSnapshot;
889
+ const hostLLMProfileAttemptObserver = this.getRootProcessor().#run.context.onLLMProfileAttempt;
890
+ this.#run.nodeProcessContextBase = {
891
+ ...this.#run.context,
966
892
  abortGraph: (error) => {
967
893
  void (this.#abortOwnerOverride ?? this).abort(error === undefined, error);
968
894
  },
969
- codeRunner: this.#context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
895
+ codeRunner: this.#run.context.codeRunner ?? DEFAULT_ISOMORPHIC_CODE_RUNNER,
970
896
  contextValues: this.#contextValues,
971
- executionCache: this.#executionCache,
897
+ executionCache: this.#shared.executionCache,
972
898
  executor: this.executor ?? 'nodejs',
973
- getGlobal: (id) => this.#globals.get(id),
974
- getCachedStoredValue: (key) => this.#storedValueController.getCached(key),
975
- getStoredValue: (key) => this.#storedValueController.get(key),
976
- getKnowledgeStore: (connectionId) => this.#knowledgeStoreController.resolve(connectionId, this.#nodeProcessContextBase),
899
+ getGlobal: (id) => this.#shared.globals.get(id),
900
+ getCachedStoredValue: (key) => this.#shared.storedValueController.getCached(key),
901
+ getStoredValue: (key) => this.#shared.storedValueController.get(key),
902
+ getKnowledgeStore: (connectionId) => this.#shared.knowledgeStoreController.resolve(connectionId, this.#run.nodeProcessContextBase),
977
903
  getGraphBoundary: (project, graphId) => this.#getGraphBoundary(project, graphId),
978
- graphInputNodeValues: this.#graphInputNodeValues,
979
- graphInputs: this.#graphInputs,
980
- graphOutputs: this.#graphOutputs,
904
+ graphInputNodeValues: this.#run.graphInputNodeValues,
905
+ graphInputs: this.#run.graphInputs,
906
+ graphOutputs: this.#run.graphOutputs,
981
907
  graphCallPath: this.#graphCallPath,
982
908
  onChatV2CallFinished: (event) => {
983
909
  try {
@@ -1027,18 +953,18 @@ export class GraphProcessor {
1027
953
  raiseEvent: (event, data) => {
1028
954
  this.getRootProcessor().raiseEvent(event, data);
1029
955
  },
1030
- referencedProjects: this.#loadedProjects,
956
+ referencedProjects: this.#run.loadedProjects,
1031
957
  tokenizer: this.#getTokenizer(),
1032
958
  trace: (message) => {
1033
959
  this.#emitTraceEvent(message);
1034
960
  },
1035
- setStoredValue: (key, value) => this.#storedValueController.set(key, value),
1036
- waitForGlobal: async (id, signal = this.#abortController.signal) => {
961
+ setStoredValue: (key, value) => this.#shared.storedValueController.set(key, value),
962
+ waitForGlobal: async (id, signal = this.#run.abortController.signal) => {
1037
963
  if (signal.aborted) {
1038
964
  throw createGraphAbortErrorFromSignal(signal);
1039
965
  }
1040
- if (this.#globals.has(id)) {
1041
- return this.#globals.get(id);
966
+ if (this.#shared.globals.has(id)) {
967
+ return this.#shared.globals.get(id);
1042
968
  }
1043
969
  return await new Promise((resolve, reject) => {
1044
970
  const abortListener = () => {
@@ -1047,7 +973,7 @@ export class GraphProcessor {
1047
973
  };
1048
974
  const unsubscribe = this.getRootProcessor().#emitter.on(`globalSet:${id}`, () => {
1049
975
  cleanup();
1050
- resolve(this.#globals.get(id));
976
+ resolve(this.#shared.globals.get(id));
1051
977
  });
1052
978
  const cleanup = () => {
1053
979
  unsubscribe();
@@ -1059,7 +985,7 @@ export class GraphProcessor {
1059
985
  }
1060
986
  });
1061
987
  },
1062
- waitForStoredValue: (key, signal) => this.#storedValueController.waitForSet(key, signal),
988
+ waitForStoredValue: (key, signal) => this.#shared.storedValueController.waitForSet(key, signal),
1063
989
  };
1064
990
  }
1065
991
  #cleanupTokenizerErrorListener() {
@@ -1079,12 +1005,12 @@ export class GraphProcessor {
1079
1005
  if (!this.#isSubProcessor) {
1080
1006
  await this.#emitter.emit('start', this.#withExecution({
1081
1007
  contextValues: this.#contextValues,
1082
- inputs: this.#graphInputs,
1008
+ inputs: this.#run.graphInputs,
1083
1009
  project: this.#project,
1084
1010
  startGraph: this.#graph,
1085
1011
  }));
1086
1012
  }
1087
- await this.#emitter.emit('graphStart', this.#withExecution({ graph: this.#graph, inputs: this.#graphInputs }));
1013
+ await this.#emitter.emit('graphStart', this.#withExecution({ graph: this.#graph, inputs: this.#run.graphInputs }));
1088
1014
  }
1089
1015
  async #emitInitialProjectGlobalVariables() {
1090
1016
  if (this.#isSubProcessor || this.#suppressGraphLifecycleEvents)
@@ -1094,17 +1020,17 @@ export class GraphProcessor {
1094
1020
  }
1095
1021
  }
1096
1022
  async #emitPreloadedNodeResults() {
1097
- if (!this.#hasPreloadedData) {
1023
+ if (!this.#run.hasPreloadedData) {
1098
1024
  return;
1099
1025
  }
1100
1026
  for (const node of this.#executionGraphNodes) {
1101
- if (!this.#isNodeSelected(node.id) || !this.#nodeResults.has(node.id)) {
1027
+ if (!this.#isNodeSelected(node.id) || !this.#run.nodeResults.has(node.id)) {
1102
1028
  continue;
1103
1029
  }
1104
1030
  if (this.#suppressedPreloadedNodeIds.has(node.id)) {
1105
1031
  continue;
1106
1032
  }
1107
- const outputs = this.#nodeResults.get(node.id);
1033
+ const outputs = this.#run.nodeResults.get(node.id);
1108
1034
  // A preloaded producer is complete evidence, not a reconstructed token
1109
1035
  // stream. Watch receives it once as the producer's final snapshot.
1110
1036
  this.#assertStreamingOutputWatchFinalOutputs(node, outputs);
@@ -1126,45 +1052,45 @@ export class GraphProcessor {
1126
1052
  }
1127
1053
  async #queueStartNodes(startNodes) {
1128
1054
  for (const startNode of startNodes) {
1129
- void this.#processingQueue.add(async () => {
1055
+ void this.#run.processingQueue.add(async () => {
1130
1056
  await this.#fetchNodeDataAndProcessNode(startNode);
1131
1057
  });
1132
1058
  }
1133
1059
  }
1134
1060
  async #processCompatibleGraph() {
1135
- await this.#queueStartNodes(this.#graphOutputSelection?.startNodes ??
1061
+ await this.#queueStartNodes(this.#run.graphOutputSelection?.startNodes ??
1136
1062
  getStartNodes(this.#executionState, this.#executionGraphNodes, this.runToNodeIds));
1137
- await this.#processingQueue.onIdle();
1138
- if (Object.keys(this.#graphInputStreams).length) {
1063
+ await this.#run.processingQueue.onIdle();
1064
+ if (Object.keys(this.#boundaries.graphInputStreams).length) {
1139
1065
  await this.#waitForGraphInputStreams();
1140
- for (const [nodeId, outputs] of this.#pendingGraphInputFinals) {
1066
+ for (const [nodeId, outputs] of this.#boundaries.pendingGraphInputFinals) {
1141
1067
  this.#finishStreamingOutputWatches(this.#nodesById[nodeId], outputs);
1142
1068
  }
1143
- this.#pendingGraphInputFinals.clear();
1069
+ this.#boundaries.pendingGraphInputFinals.clear();
1144
1070
  for (const node of this.#executionGraphNodes) {
1145
1071
  if (!this.#isNodeSelected(node.id))
1146
1072
  continue;
1147
- void this.#processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
1073
+ void this.#run.processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
1148
1074
  }
1149
- await this.#processingQueue.onIdle();
1075
+ await this.#run.processingQueue.onIdle();
1150
1076
  }
1151
- while (this.#streamCallerTasks.size) {
1077
+ while (this.#boundaries.streamCallerTasks.size) {
1152
1078
  // A producer skipped transitively after an upstream failure never emits
1153
1079
  // nodeError itself. Settle its consumers once ordinary work is quiescent.
1154
- for (const [sourceId, routes] of this.#inputStreamRoutes) {
1155
- if (this.#currentlyProcessing.has(sourceId) || routes.every(({ relay }) => relay.result))
1080
+ for (const [sourceId, routes] of this.#boundaries.inputStreamRoutes) {
1081
+ if (this.#run.currentlyProcessing.has(sourceId) || routes.every(({ relay }) => relay.result))
1156
1082
  continue;
1157
- const failedDependency = this.getDependencyNodesDeep(sourceId).find((id) => this.#erroredNodes.has(id));
1083
+ const failedDependency = this.getDependencyNodesDeep(sourceId).find((id) => this.#run.erroredNodes.has(id));
1158
1084
  if (failedDependency) {
1159
- const error = getError(this.#erroredNodes.get(failedDependency));
1085
+ const error = getError(this.#run.erroredNodes.get(failedDependency));
1160
1086
  for (const { relay } of routes)
1161
1087
  relay.finish({ error });
1162
1088
  }
1163
1089
  }
1164
1090
  // Recheck skipped producers after each caller settles; another caller may
1165
1091
  // depend on ordinary nodes skipped because this caller failed.
1166
- await Promise.race(this.#streamCallerTasks);
1167
- await this.#processingQueue.onIdle();
1092
+ await Promise.race(this.#boundaries.streamCallerTasks);
1093
+ await this.#run.processingQueue.onIdle();
1168
1094
  }
1169
1095
  await this.#drainStreamingCatchTasks();
1170
1096
  this.#markUnqueuedNodesIgnored();
@@ -1173,10 +1099,10 @@ export class GraphProcessor {
1173
1099
  if (this.#scheduler !== 'fast-acyclic') {
1174
1100
  return false;
1175
1101
  }
1176
- if (this.#graphOutputSelection ||
1177
- this.#callerInputStreams.size > 0 ||
1178
- Object.keys(this.#graphInputStreams).length > 0 ||
1179
- this.#hasPreloadedData ||
1102
+ if (this.#run.graphOutputSelection ||
1103
+ this.#boundaries.callerInputStreams.size > 0 ||
1104
+ Object.keys(this.#boundaries.graphInputStreams).length > 0 ||
1105
+ this.#run.hasPreloadedData ||
1180
1106
  this.runToNodeIds ||
1181
1107
  this.slowMode ||
1182
1108
  this.#includeTrace) {
@@ -1282,14 +1208,14 @@ export class GraphProcessor {
1282
1208
  return;
1283
1209
  }
1284
1210
  for (const node of this.#executionGraphNodes) {
1285
- if (this.#queuedNodes.has(node.id) === false && !this.#ignoreNodes.has(node.id)) {
1286
- this.#ignoreNodes.add(node.id);
1287
- this.#deferredRunToIgnoredNodes.add(node.id);
1211
+ if (this.#run.queuedNodes.has(node.id) === false && !this.#run.ignoreNodes.has(node.id)) {
1212
+ this.#run.ignoreNodes.add(node.id);
1213
+ this.#run.deferredRunToIgnoredNodes.add(node.id);
1288
1214
  }
1289
1215
  }
1290
1216
  }
1291
1217
  #getUnhandledErroredNodes() {
1292
- return [...this.#erroredNodes.entries()].filter(([nodeId]) => {
1218
+ return [...this.#run.erroredNodes.entries()].filter(([nodeId]) => {
1293
1219
  const erroredNodeAttachedData = this.#getAttachedDataTo(nodeId);
1294
1220
  return erroredNodeAttachedData.races == null || erroredNodeAttachedData.races.completed === false;
1295
1221
  });
@@ -1314,7 +1240,7 @@ export class GraphProcessor {
1314
1240
  const erroredNodes = this.#getUnhandledErroredNodes();
1315
1241
  const branchFailures = [
1316
1242
  ...(includeManagedAsyncFailures ? this.#managedAsyncBranchFailures : []),
1317
- ...this.#streamingWatchFailures,
1243
+ ...this.#boundaries.streamingWatchFailures,
1318
1244
  ];
1319
1245
  if (this.#lifecycle.abortSuccessful ||
1320
1246
  (!this.#lifecycle.isAborted && !erroredNodes.length && !branchFailures.length)) {
@@ -1330,11 +1256,11 @@ export class GraphProcessor {
1330
1256
  throw error;
1331
1257
  }
1332
1258
  async #finalizeGraphRun() {
1333
- const outputValues = this.#graphOutputs;
1259
+ const outputValues = this.#run.graphOutputs;
1334
1260
  if (this.#suppressGraphLifecycleEvents) {
1335
1261
  return outputValues;
1336
1262
  }
1337
- ensureGraphCostOutput(this.#graphOutputs, this.#totalCost);
1263
+ ensureGraphCostOutput(this.#run.graphOutputs, this.#run.totalCost, this.#run.costBreakdown);
1338
1264
  await this.#emitter.emit('graphFinish', this.#withExecution({ graph: this.#graph, outputs: outputValues }));
1339
1265
  if (!this.#isSubProcessor) {
1340
1266
  await this.#emitter.emit('done', { results: outputValues });
@@ -1344,16 +1270,16 @@ export class GraphProcessor {
1344
1270
  async #loadProjectReferences() {
1345
1271
  if ((this.#project.references?.length ?? 0) > 0) {
1346
1272
  if (this.#cacheLoadedProjects && this.#runtimeCache?.loadedProjects) {
1347
- this.#loadedProjects = { ...this.#runtimeCache.loadedProjects };
1273
+ this.#run.loadedProjects = { ...this.#runtimeCache.loadedProjects };
1348
1274
  await this.#loadSubgraphProjectTargets();
1349
1275
  return;
1350
1276
  }
1351
- if (!this.#context.projectReferenceLoader) {
1277
+ if (!this.#run.context.projectReferenceLoader) {
1352
1278
  throw new Error('Project references are set, but no projectReferenceLoader is set in the context. Since this project uses project references, you must provide a projectReferenceLoader in the context.');
1353
1279
  }
1354
- this.#loadedProjects = await loadProjectReferenceTree(this.#project, this.#context.projectPath, this.#context.projectReferenceLoader);
1280
+ this.#run.loadedProjects = await loadProjectReferenceTree(this.#project, this.#run.context.projectPath, this.#run.context.projectReferenceLoader);
1355
1281
  if (this.#cacheLoadedProjects && this.#runtimeCache) {
1356
- this.#runtimeCache.loadedProjects = { ...this.#loadedProjects };
1282
+ this.#runtimeCache.loadedProjects = { ...this.#run.loadedProjects };
1357
1283
  }
1358
1284
  }
1359
1285
  await this.#loadSubgraphProjectTargets();
@@ -1386,7 +1312,7 @@ export class GraphProcessor {
1386
1312
  if (candidate.type !== 'subGraph' || candidate.disabled)
1387
1313
  continue;
1388
1314
  const node = candidate;
1389
- if (node.data.targetScope === 'other-projects' && !node.data.targetProjectId) {
1315
+ if (node.data.targetScope && !node.data.targetProjectId) {
1390
1316
  throw new Error('Select a project and graph for this Subgraph before running it.');
1391
1317
  }
1392
1318
  let childOwner = owner;
@@ -1394,24 +1320,27 @@ export class GraphProcessor {
1394
1320
  const target = {
1395
1321
  projectId: node.data.targetProjectId,
1396
1322
  version: node.data.targetVersion ?? 'latest',
1323
+ callerProjectId: owner.metadata.id,
1397
1324
  };
1398
1325
  const key = getSubgraphProjectKey(target);
1399
- let resolved = this.#subgraphTargetCache.get(key);
1326
+ let resolved = this.#shared.subgraphTargetCache.get(key);
1327
+ if (resolved)
1328
+ await this.#run.context.subgraphProjectLoader?.validateTarget?.(target);
1400
1329
  if (!resolved) {
1401
- if (!this.#context.subgraphProjectLoader) {
1330
+ if (!this.#run.context.subgraphProjectLoader) {
1402
1331
  throw new Error('Subgraph calls to another project require a subgraphProjectLoader. Use a project bundle locally or run through Rivet Studio Server.');
1403
1332
  }
1404
- resolved = await this.#context.subgraphProjectLoader.loadTarget(target);
1333
+ resolved = await this.#run.context.subgraphProjectLoader.loadTarget(target);
1405
1334
  if (resolved.project.metadata.id !== target.projectId) {
1406
1335
  throw new Error(`Subgraph target ${target.projectId} resolved to a different project.`);
1407
1336
  }
1408
- this.#subgraphTargetCache.set(key, resolved);
1337
+ this.#shared.subgraphTargetCache.set(key, resolved);
1409
1338
  }
1410
1339
  childOwner = resolved.project;
1411
- if (Object.hasOwn(this.#loadedProjects, key) && this.#loadedProjects[key] !== childOwner) {
1340
+ if (Object.hasOwn(this.#run.loadedProjects, key) && this.#run.loadedProjects[key] !== childOwner) {
1412
1341
  throw new Error('Subgraph target collides with an existing project reference.');
1413
1342
  }
1414
- Object.defineProperty(this.#loadedProjects, key, {
1343
+ Object.defineProperty(this.#run.loadedProjects, key, {
1415
1344
  configurable: true,
1416
1345
  enumerable: true,
1417
1346
  value: childOwner,
@@ -1428,9 +1357,9 @@ export class GraphProcessor {
1428
1357
  await visit(this.#project, this.#graph.metadata.id, 0);
1429
1358
  // Streaming topology may visit any resolved target, including a version of
1430
1359
  // a project with the same metadata ID as another selected target.
1431
- for (const [key, resolved] of this.#subgraphTargetCache) {
1432
- if (!Object.hasOwn(this.#loadedProjects, key)) {
1433
- Object.defineProperty(this.#loadedProjects, key, {
1360
+ for (const [key, resolved] of this.#shared.subgraphTargetCache) {
1361
+ if (!Object.hasOwn(this.#run.loadedProjects, key)) {
1362
+ Object.defineProperty(this.#run.loadedProjects, key, {
1434
1363
  configurable: true,
1435
1364
  enumerable: true,
1436
1365
  value: resolved.project,
@@ -1448,9 +1377,40 @@ export class GraphProcessor {
1448
1377
  return getMissingRequiredInputs(this.#executionState, node);
1449
1378
  }
1450
1379
  /** Accumulates cost from a node's output. */
1451
- #accumulateCost(output) {
1452
- if (output['cost']?.type === 'number') {
1453
- this.#totalCost += coerceTypeOptional(output['cost'], 'number') ?? 0;
1380
+ #accumulateCost(output, nodeType) {
1381
+ const carried = readGraphCostBreakdown(output);
1382
+ // Alias metric visibility must not discard the called graph's accounting.
1383
+ const aliasCost = nodeType === 'referencedGraphAlias' && carried ? carried.llm + carried.classifier + carried.other : undefined;
1384
+ const costOutput = output['cost'];
1385
+ if (costOutput?.type === 'number' || aliasCost != null) {
1386
+ const cost = costOutput?.type === 'number' ? costOutput.value : aliasCost;
1387
+ if (typeof cost !== 'number' ||
1388
+ !Number.isFinite(cost) ||
1389
+ cost < 0 ||
1390
+ !Number.isFinite(this.#run.totalCost + cost))
1391
+ return;
1392
+ this.#run.totalCost += cost;
1393
+ const family = nodeType === 'classifierEvaluate'
1394
+ ? 'classifier'
1395
+ : nodeType === 'llmChatV2' || nodeType === 'chat'
1396
+ ? 'llm'
1397
+ : 'other';
1398
+ // Authored metric-named graph outputs retain ownership. Do not attribute
1399
+ // an unrelated cost value using a child's runtime breakdown.
1400
+ const breakdown = carried && graphCostBreakdownMatchesCost(carried, cost)
1401
+ ? carried
1402
+ : { llm: 0, classifier: 0, other: 0, [family]: cost };
1403
+ if (cost !== 0 || family !== 'other' || carried) {
1404
+ this.#run.costBreakdown = addGraphCostBreakdown(this.#run.costBreakdown, breakdown);
1405
+ }
1406
+ }
1407
+ }
1408
+ #accumulateChildCost(processor) {
1409
+ if (!Number.isFinite(this.#run.totalCost + processor.#run.totalCost))
1410
+ return;
1411
+ this.#run.totalCost += processor.#run.totalCost;
1412
+ if (processor.#run.costBreakdown) {
1413
+ this.#run.costBreakdown = addGraphCostBreakdown(this.#run.costBreakdown, processor.#run.costBreakdown);
1454
1414
  }
1455
1415
  }
1456
1416
  async #fetchNodeDataAndProcessNode(node) {
@@ -1458,16 +1418,16 @@ export class GraphProcessor {
1458
1418
  return;
1459
1419
  const profileStart = this.#startRuntimeProfile();
1460
1420
  try {
1461
- if (this.#currentlyProcessing.has(node.id)) {
1421
+ if (this.#run.currentlyProcessing.has(node.id)) {
1462
1422
  return;
1463
1423
  }
1464
1424
  if (this.#propagateCompletedContinuationNode(node, true)) {
1465
1425
  return;
1466
1426
  }
1467
- if (this.#queuedNodes.has(node.id)) {
1427
+ if (this.#run.queuedNodes.has(node.id)) {
1468
1428
  return;
1469
1429
  }
1470
- if (this.#nodeResults.has(node.id) || this.#erroredNodes.has(node.id)) {
1430
+ if (this.#run.nodeResults.has(node.id) || this.#run.erroredNodes.has(node.id)) {
1471
1431
  return;
1472
1432
  }
1473
1433
  const inputNodesProfileStart = this.#startRuntimeProfile();
@@ -1492,8 +1452,8 @@ export class GraphProcessor {
1492
1452
  };
1493
1453
  }
1494
1454
  }
1495
- this.#queuedNodes.add(node.id);
1496
- void this.#processingQueue.addAll(inputNodes.map((inputNode) => {
1455
+ this.#run.queuedNodes.add(node.id);
1456
+ void this.#run.processingQueue.addAll(inputNodes.map((inputNode) => {
1497
1457
  return async () => {
1498
1458
  this.#emitTraceEvent(`Fetching required data for node ${inputNode.title} (${inputNode.id})`);
1499
1459
  await this.#fetchNodeDataAndProcessNode(inputNode);
@@ -1510,10 +1470,10 @@ export class GraphProcessor {
1510
1470
  if (!this.#isNodeSelected(node.id))
1511
1471
  return [];
1512
1472
  // Waiting graph callers must not occupy a queue slot needed by their producer.
1513
- if (this.#callerInputStreams.has(node.id) && !options.streamingDispatch) {
1473
+ if (this.#boundaries.callerInputStreams.has(node.id) && !options.streamingDispatch) {
1514
1474
  const task = this.#processNodeIfAllInputsAvailable(node, { ...options, streamingDispatch: true }).catch((error) => this.#nodeErrored(node, error, nanoid()));
1515
- this.#streamCallerTasks.add(task);
1516
- void task.then(() => this.#streamCallerTasks.delete(task), () => this.#streamCallerTasks.delete(task));
1475
+ this.#boundaries.streamCallerTasks.add(task);
1476
+ void task.then(() => this.#boundaries.streamCallerTasks.delete(task), () => this.#boundaries.streamCallerTasks.delete(task));
1517
1477
  return [];
1518
1478
  }
1519
1479
  const { queueOutputNodes = true } = options;
@@ -1529,11 +1489,11 @@ export class GraphProcessor {
1529
1489
  return [];
1530
1490
  }
1531
1491
  const namedInput = node.type === 'graphInput' ? node.data.id : undefined;
1532
- const inputStream = namedInput != null && Object.hasOwn(this.#graphInputStreams, namedInput)
1533
- ? this.#graphInputStreams[namedInput]
1492
+ const inputStream = namedInput != null && Object.hasOwn(this.#boundaries.graphInputStreams, namedInput)
1493
+ ? this.#boundaries.graphInputStreams[namedInput]
1534
1494
  : undefined;
1535
1495
  if (inputStream) {
1536
- const terminals = Object.values(this.#graphInputStreams).map((stream) => stream.result);
1496
+ const terminals = Object.values(this.#boundaries.graphInputStreams).map((stream) => stream.result);
1537
1497
  // A containing invocation cannot release a successful final into a deeper
1538
1498
  // caller when another required input failed or was excluded.
1539
1499
  const terminal = terminals.find((result) => result?.error) ??
@@ -1555,8 +1515,8 @@ export class GraphProcessor {
1555
1515
  return [];
1556
1516
  }
1557
1517
  else if (node.type !== 'graphInput' &&
1558
- !this.#callerInputStreams.has(node.id) &&
1559
- Object.values(this.#graphInputStreams).some((stream) => !stream.result || stream.result.error || stream.result.value?.type === 'control-flow-excluded')) {
1518
+ !this.#boundaries.callerInputStreams.has(node.id) &&
1519
+ Object.values(this.#boundaries.graphInputStreams).some((stream) => !stream.result || stream.result.error || stream.result.value?.type === 'control-flow-excluded')) {
1560
1520
  // Only streaming boundary plumbing runs early; ordinary side effects wait.
1561
1521
  return [];
1562
1522
  }
@@ -1572,7 +1532,7 @@ export class GraphProcessor {
1572
1532
  this.#emitTraceEvent(`Node ${node.title} is excluded due to control flow`);
1573
1533
  return loopExclusion === true ? [] : loopExclusion;
1574
1534
  }
1575
- const streamedInputs = this.#callerInputStreams.get(node.id);
1535
+ const streamedInputs = this.#boundaries.callerInputStreams.get(node.id);
1576
1536
  const blockingInputNodes = streamedInputs
1577
1537
  ? inputNodes.filter((inputNode) => this.#getInputConnectionsForNode(node).some((edge) => edge.outputNodeId === inputNode.id && !streamedInputs[edge.inputId]))
1578
1538
  : inputNodes;
@@ -1620,9 +1580,9 @@ export class GraphProcessor {
1620
1580
  await new Promise((resolve) => setTimeout(resolve, 250));
1621
1581
  }
1622
1582
  this.#emitTraceEvent(`Finished processing node ${node.title} (${node.id})`);
1623
- this.#visitedNodes.add(node.id);
1624
- this.#currentlyProcessing.delete(node.id);
1625
- this.#remainingNodes.delete(node.id);
1583
+ this.#run.visitedNodes.add(node.id);
1584
+ this.#run.currentlyProcessing.delete(node.id);
1585
+ this.#run.remainingNodes.delete(node.id);
1626
1586
  const outputNodesProfileStart = this.#startRuntimeProfile();
1627
1587
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
1628
1588
  this.#finishRuntimeProfile('getOutputNodesFrom', outputNodesProfileStart);
@@ -1648,7 +1608,7 @@ export class GraphProcessor {
1648
1608
  }
1649
1609
  #propagateCompletedContinuationNode(node, queueOutputNodes) {
1650
1610
  const ownerLLMNodeId = this.#continuationCompletionOwnerByNodeId.get(node.id);
1651
- if (ownerLLMNodeId == null || !this.#nodeResults.has(ownerLLMNodeId)) {
1611
+ if (ownerLLMNodeId == null || !this.#run.nodeResults.has(ownerLLMNodeId)) {
1652
1612
  return undefined;
1653
1613
  }
1654
1614
  this.#continuationCompletionOwnerByNodeId.delete(node.id);
@@ -1662,7 +1622,7 @@ export class GraphProcessor {
1662
1622
  return outputNodes.nodes;
1663
1623
  }
1664
1624
  #shouldSkipNodeProcessing(node, inputNodes) {
1665
- if (this.#ignoreNodes.has(node.id)) {
1625
+ if (this.#run.ignoreNodes.has(node.id)) {
1666
1626
  this.#emitTraceEvent(`Node ${node.title} is ignored`);
1667
1627
  return true;
1668
1628
  }
@@ -1673,15 +1633,15 @@ export class GraphProcessor {
1673
1633
  return true;
1674
1634
  }
1675
1635
  }
1676
- if (this.#currentlyProcessing.has(node.id)) {
1636
+ if (this.#run.currentlyProcessing.has(node.id)) {
1677
1637
  this.#emitTraceEvent(`Node ${node.title} is already being processed`);
1678
1638
  return true;
1679
1639
  }
1680
- if (this.#visitedNodes.has(node.id) && node.type !== 'loopController') {
1640
+ if (this.#run.visitedNodes.has(node.id) && node.type !== 'loopController') {
1681
1641
  this.#emitTraceEvent(`Node ${node.title} has already been processed`);
1682
1642
  return true;
1683
1643
  }
1684
- if (this.#erroredNodes.has(node.id)) {
1644
+ if (this.#run.erroredNodes.has(node.id)) {
1685
1645
  this.#emitTraceEvent(`Node ${node.title} has already errored`);
1686
1646
  return true;
1687
1647
  }
@@ -1700,9 +1660,9 @@ export class GraphProcessor {
1700
1660
  if (this.#shouldSkipCompletedRaceNode(node, attachedData)) {
1701
1661
  return false;
1702
1662
  }
1703
- this.#currentlyProcessing.add(node.id);
1663
+ this.#run.currentlyProcessing.add(node.id);
1704
1664
  if (node.type === 'loopController') {
1705
- this.#loopControllersSeen.add(node.id);
1665
+ this.#run.loopControllersSeen.add(node.id);
1706
1666
  }
1707
1667
  this.#registerNodeInActiveLoop(node, attachedData);
1708
1668
  return true;
@@ -1723,7 +1683,7 @@ export class GraphProcessor {
1723
1683
  if (node.type !== 'loopController') {
1724
1684
  return;
1725
1685
  }
1726
- const loopControllerResults = this.#nodeResults.get(node.id);
1686
+ const loopControllerResults = this.#run.nodeResults.get(node.id);
1727
1687
  const breakValue = loopControllerResults['break'];
1728
1688
  const didBreak = didLoopControllerBreak(breakValue);
1729
1689
  if (didBreak) {
@@ -1733,10 +1693,10 @@ export class GraphProcessor {
1733
1693
  for (const loopNodeId of attachedData.loopInfo?.nodes ?? []) {
1734
1694
  const cycleNode = this.#nodesById[loopNodeId];
1735
1695
  this.#emitTraceEvent(`Clearing cycle node ${cycleNode.title} (${cycleNode.id})`);
1736
- this.#visitedNodes.delete(cycleNode.id);
1737
- this.#currentlyProcessing.delete(cycleNode.id);
1738
- this.#remainingNodes.add(cycleNode.id);
1739
- this.#nodeResults.delete(cycleNode.id);
1696
+ this.#run.visitedNodes.delete(cycleNode.id);
1697
+ this.#run.currentlyProcessing.delete(cycleNode.id);
1698
+ this.#run.remainingNodes.add(cycleNode.id);
1699
+ this.#run.nodeResults.delete(cycleNode.id);
1740
1700
  }
1741
1701
  }
1742
1702
  #handleCompletedRace(node) {
@@ -1744,7 +1704,7 @@ export class GraphProcessor {
1744
1704
  return;
1745
1705
  }
1746
1706
  const raceId = `race-${node.id}`;
1747
- const allNodesForRace = [...this.#attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(raceId));
1707
+ const allNodesForRace = [...this.#run.attachedNodeData.entries()].filter(([, { races }]) => races?.raceIds.includes(raceId));
1748
1708
  for (const [, nodeAttachedData] of allNodesForRace) {
1749
1709
  if (nodeAttachedData.races?.raceIds.includes(raceId)) {
1750
1710
  nodeAttachedData.races.completed = true;
@@ -1794,22 +1754,22 @@ export class GraphProcessor {
1794
1754
  }
1795
1755
  }
1796
1756
  #queueOutputNodes(node, outputNodes) {
1797
- const selectedOutputs = this.#graphOutputSelection
1757
+ const selectedOutputs = this.#run.graphOutputSelection
1798
1758
  ? outputNodes.filter((outputNode) => this.#isNodeSelected(outputNode.id))
1799
1759
  : outputNodes;
1800
1760
  const relevantNodeIds = this.#getExecutionRelevantNodeIds();
1801
1761
  for (const outputNode of selectedOutputs) {
1802
- if (relevantNodeIds?.has(outputNode.id) && this.#deferredRunToIgnoredNodes.delete(outputNode.id)) {
1803
- this.#ignoreNodes.delete(outputNode.id);
1762
+ if (relevantNodeIds?.has(outputNode.id) && this.#run.deferredRunToIgnoredNodes.delete(outputNode.id)) {
1763
+ this.#run.ignoreNodes.delete(outputNode.id);
1804
1764
  }
1805
1765
  }
1806
- void this.#processingQueue.addAll(selectedOutputs.map((outputNode) => async () => {
1766
+ void this.#run.processingQueue.addAll(selectedOutputs.map((outputNode) => async () => {
1807
1767
  this.#emitTraceEvent(`Trying to run output node from ${node.title}: ${outputNode.title} (${outputNode.id})`);
1808
1768
  await this.#processNodeIfAllInputsAvailable(outputNode);
1809
1769
  }));
1810
1770
  }
1811
1771
  #startManagedAsyncBranch(triggerNode) {
1812
- const outputs = this.#nodeResults.get(triggerNode.id);
1772
+ const outputs = this.#run.nodeResults.get(triggerNode.id);
1813
1773
  if (!outputs) {
1814
1774
  return;
1815
1775
  }
@@ -1850,53 +1810,29 @@ export class GraphProcessor {
1850
1810
  const root = this.getRootProcessor();
1851
1811
  const sameGraphOwner = this.#sameGraphRunOwnerOverride ?? this;
1852
1812
  const isRootGraphOrigin = !sameGraphOwner.#isSubProcessor;
1853
- if (root.#abortController.signal.aborted) {
1854
- throw createGraphAbortErrorFromSignal(root.#abortController.signal, 'Async branch aborted before it started');
1813
+ if (root.#run.abortController.signal.aborted) {
1814
+ throw createGraphAbortErrorFromSignal(root.#run.abortController.signal, 'Async branch aborted before it started');
1855
1815
  }
1856
1816
  const graphId = plan.graph.metadata?.id;
1857
1817
  if (!graphId) {
1858
1818
  throw new Error('Cannot start an async branch because the current graph has no ID.');
1859
1819
  }
1860
- const branchRuntimeCache = {
1861
- ...this.#runtimeCache,
1862
- graphBoundaries: undefined,
1863
- loadedProjects: { ...this.#loadedProjects },
1864
- };
1865
- const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
1866
- cacheLoadedProjects: true,
1867
- captureNodeTimings: this.#captureNodeTimings,
1868
- concurrency: this.#concurrency,
1869
- executionPlanCacheMode: this.#executionPlanCacheMode,
1870
- runtimeCache: branchRuntimeCache,
1871
- runtimeProfiler: this.#runtimeProfiler,
1872
- scheduler: this.#scheduler,
1873
- [graphProcessorGraphOverride]: plan.graph,
1874
- [consumedAsyncBranchTriggerOverride]: triggerNode.id,
1875
- [asyncBranchInputAnchorsOverride]: Object.fromEntries(plan.graph.connections
1820
+ const processor = this.#constructChildInvocation({
1821
+ kind: 'async',
1822
+ graph: plan.graph,
1823
+ triggerNodeId: triggerNode.id,
1824
+ inputAnchors: Object.fromEntries(plan.graph.connections
1876
1825
  .filter((connection) => connection.inputNodeId === triggerNode.id)
1877
1826
  .map((connection) => [connection.outputNodeId, this.#definitions[connection.outputNodeId]])),
1827
+ onCreated: onProcessorCreated,
1878
1828
  });
1879
- onProcessorCreated(processor);
1880
- processor.executor = this.executor;
1881
- processor.#isSubProcessor = true;
1882
- processor.#subgraphTargetCache = this.#subgraphTargetCache;
1883
- processor.#recordingProjectScope = this.#recordingProjectScope;
1884
- processor.#executionCache = this.#executionCache;
1885
- processor.#externalFunctions = this.#externalFunctions;
1886
- processor.#contextValues = this.#contextValues;
1887
1829
  processor.#parent = sameGraphOwner;
1888
- processor.#graphCallPath = this.#graphCallPath;
1889
1830
  processor.#abortOwnerOverride = root;
1890
1831
  processor.#suppressGraphPartialOutputs = true;
1891
- processor.#globals = this.#globals;
1892
- processor.#storedValueController = this.#storedValueController;
1893
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
1894
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
1895
- processor.#executor = this.#executor;
1896
1832
  processor.#suppressGraphLifecycleEvents = isRootGraphOrigin;
1897
1833
  processor.#sharedRunStateOverride = {
1898
- attachedNodeData: this.#attachedNodeData,
1899
- graphInputNodeValues: this.#graphInputNodeValues,
1834
+ attachedNodeData: this.#run.attachedNodeData,
1835
+ graphInputNodeValues: this.#run.graphInputNodeValues,
1900
1836
  // Async branches cannot contain Graph Output nodes. Keep their synthetic
1901
1837
  // boundary outputs private so branch finalization cannot seed the root's
1902
1838
  // derived cost output before the root has accumulated every path.
@@ -1906,56 +1842,36 @@ export class GraphProcessor {
1906
1842
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
1907
1843
  processor.#executionIdentityOverride = isRootGraphOrigin
1908
1844
  ? {
1909
- rootRunId: this.#rootRunId,
1910
- graphRunId: this.#graphRunId,
1911
- parentGraphRunId: this.#parentGraphRunId,
1845
+ rootRunId: this.#run.rootRunId,
1846
+ graphRunId: this.#run.graphRunId,
1847
+ parentGraphRunId: this.#run.parentGraphRunId,
1912
1848
  }
1913
1849
  : {
1914
- rootRunId: root.#rootRunId,
1850
+ rootRunId: root.#run.rootRunId,
1915
1851
  graphRunId: nanoid(),
1916
- parentGraphRunId: sameGraphOwner.#graphRunId,
1852
+ parentGraphRunId: sameGraphOwner.#run.graphRunId,
1917
1853
  };
1918
1854
  processor.preloadNodeData(triggerNode.id, triggerOutputs);
1919
1855
  processor.#suppressedPreloadedNodeIds.add(triggerNode.id);
1920
- const unwireEvents = wireSubprocessorEvents(processor, root.#emitter, {
1856
+ const unwireEvents = this.#wireChildEvents(processor, root, {
1921
1857
  autoCleanup: false,
1922
- isPaused: () => root.#lifecycle.isPaused,
1923
- pause: () => {
1924
- void root.pause();
1925
- },
1926
- resume: () => {
1927
- void root.resume();
1928
- },
1929
1858
  });
1930
- const unwireLifecycle = wireSubprocessorLifecycle(processor, {
1859
+ const unwireLifecycle = this.#wireChildLifecycle(processor, root, unwireEvents, {
1931
1860
  autoCleanup: false,
1932
- signal: sameGraphOwner === root ? undefined : sameGraphOwner.#abortController.signal,
1933
- parentAbortSignal: root.#abortController.signal,
1934
- onParentPause: (listener) => {
1935
- root.on('pause', listener);
1936
- return () => {
1937
- root.off('pause', listener);
1938
- };
1939
- },
1940
- onParentResume: (listener) => {
1941
- root.on('resume', listener);
1942
- return () => {
1943
- root.off('resume', listener);
1944
- };
1945
- },
1861
+ signal: sameGraphOwner === root ? undefined : sameGraphOwner.#run.abortController.signal,
1946
1862
  });
1947
- root.#subprocessors.add(processor);
1863
+ root.#run.subprocessors.add(processor);
1864
+ let executionFailed = true;
1948
1865
  try {
1949
1866
  if (root.#lifecycle.isPaused) {
1950
1867
  processor.pause();
1951
1868
  }
1952
- await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
1869
+ await processor.processGraph(this.#run.context, this.#run.graphInputs, this.#contextValues);
1870
+ executionFailed = false;
1953
1871
  }
1954
1872
  finally {
1955
- root.#totalCost += processor.#totalCost;
1956
- unwireLifecycle();
1957
- unwireEvents();
1958
- root.#subprocessors.delete(processor);
1873
+ root.#accumulateChildCost(processor);
1874
+ this.#releaseChildInvocation(processor, root, unwireLifecycle, unwireEvents, executionFailed);
1959
1875
  }
1960
1876
  }
1961
1877
  #recordManagedAsyncBranchFailure(triggerNode, processor, error) {
@@ -1966,22 +1882,22 @@ export class GraphProcessor {
1966
1882
  });
1967
1883
  }
1968
1884
  #getSubprocessorNodeErrors(processor) {
1969
- if (!processor || !processor.#erroredNodes) {
1885
+ if (!processor || !processor.#run.erroredNodes) {
1970
1886
  return [];
1971
1887
  }
1972
- return [...processor.#erroredNodes.entries()].flatMap(([nodeId, nodeError]) => {
1888
+ return [...processor.#run.erroredNodes.entries()].flatMap(([nodeId, nodeError]) => {
1973
1889
  const node = processor.#nodesById[nodeId];
1974
1890
  return node ? [{ error: nodeError, node }] : [];
1975
1891
  });
1976
1892
  }
1977
1893
  #recordStreamingWatchFailure(watchNode, error, processor) {
1978
- if (this.#streamingWatchFailures.some((failure) => failure.error === error)) {
1894
+ if (this.#boundaries.streamingWatchFailures.some((failure) => failure.error === error)) {
1979
1895
  return;
1980
1896
  }
1981
1897
  // The child processor already emitted the precise nodeError before its
1982
1898
  // failure reaches the coordinator. Keep a root-owned failure too so the
1983
1899
  // normal graphError/error lifecycle remains truthful after draining.
1984
- this.#streamingWatchFailures.push({
1900
+ this.#boundaries.streamingWatchFailures.push({
1985
1901
  error,
1986
1902
  nodeErrors: this.#getSubprocessorNodeErrors(processor),
1987
1903
  triggerNode: watchNode,
@@ -1989,18 +1905,18 @@ export class GraphProcessor {
1989
1905
  }
1990
1906
  #getAttachedDataTo(node) {
1991
1907
  const nodeId = typeof node === 'string' ? node : node.id;
1992
- let nodeData = this.#attachedNodeData.get(nodeId);
1908
+ let nodeData = this.#run.attachedNodeData.get(nodeId);
1993
1909
  if (nodeData == null) {
1994
1910
  nodeData = {};
1995
- this.#attachedNodeData.set(nodeId, nodeData);
1911
+ this.#run.attachedNodeData.set(nodeId, nodeData);
1996
1912
  }
1997
1913
  return nodeData;
1998
1914
  }
1999
1915
  async #processNode(node, inputValues) {
2000
1916
  const processId = nanoid();
2001
- if (this.#abortController.signal.aborted) {
2002
- await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#abortController.signal), processId);
2003
- this.#successfulAbortTerminalProcessIds.delete(processId);
1917
+ if (this.#run.abortController.signal.aborted) {
1918
+ await this.#nodeErrored(node, createGraphAbortErrorFromSignal(this.#run.abortController.signal), processId);
1919
+ this.#run.successfulAbortTerminalProcessIds.delete(processId);
2004
1920
  return { processId, shouldQueueOutputNodes: false };
2005
1921
  }
2006
1922
  const frozenOutputs = this.#resolveFrozenNodeOutputs(node, inputValues, processId);
@@ -2019,7 +1935,7 @@ export class GraphProcessor {
2019
1935
  else {
2020
1936
  await this.#processNormalNode(node, processId, inputValues);
2021
1937
  }
2022
- const successfulAbortTerminal = this.#successfulAbortTerminalProcessIds.delete(processId);
1938
+ const successfulAbortTerminal = this.#run.successfulAbortTerminalProcessIds.delete(processId);
2023
1939
  return { processId, shouldQueueOutputNodes: !successfulAbortTerminal };
2024
1940
  }
2025
1941
  async #processSplitRunNode(node, processId) {
@@ -2030,13 +1946,13 @@ export class GraphProcessor {
2030
1946
  isExcludedDueToControlFlow: (n, inputs, pid) => this.#excludedDueToControlFlow(n, inputs, pid) !== false,
2031
1947
  processNodeWithInputData: (n, inputs, idx, pid, partial, markResultAsEditorCacheHit) => this.#processNodeWithInputData(n, inputs, idx, pid, partial, markResultAsEditorCacheHit),
2032
1948
  splitRunConcurrency: this.#concurrency.splitRunConcurrency,
2033
- accumulateCost: (output) => this.#accumulateCost(output),
2034
- setNodeResults: (nodeId, outputs) => this.#nodeResults.set(nodeId, outputs),
2035
- markNodeVisited: (nodeId) => this.#visitedNodes.add(nodeId),
1949
+ accumulateCost: (output) => this.#accumulateCost(output, node.type),
1950
+ setNodeResults: (nodeId, outputs) => this.#run.nodeResults.set(nodeId, outputs),
1951
+ markNodeVisited: (nodeId) => this.#run.visitedNodes.add(nodeId),
2036
1952
  nodeErrored: (n, err, pid, durationMs, splitRunDurationMs, resultOrigin, splitOutputs) => this.#nodeErrored(n, err, pid, durationMs, splitRunDurationMs, resultOrigin, undefined, splitOutputs),
2037
1953
  takeFailureOutputs: (pid, index) => this.#takeFailureOutputs(pid, index),
2038
1954
  isAborted: () => this.#lifecycle.isAborted,
2039
- getAbortError: () => createGraphAbortErrorFromSignal(this.#abortController.signal),
1955
+ getAbortError: () => createGraphAbortErrorFromSignal(this.#run.abortController.signal),
2040
1956
  emit: (event, data) => {
2041
1957
  if (event === 'partialOutput') {
2042
1958
  emitDetached(this.#emitter, event, this.#withExecution(data));
@@ -2072,9 +1988,9 @@ export class GraphProcessor {
2072
1988
  resultOrigin: 'frozen',
2073
1989
  }));
2074
1990
  const timingStart = this.#startNodeTiming();
2075
- this.#nodeResults.set(node.id, outputValues);
2076
- this.#visitedNodes.add(node.id);
2077
- this.#accumulateCost(outputValues);
1991
+ this.#run.nodeResults.set(node.id, outputValues);
1992
+ this.#run.visitedNodes.add(node.id);
1993
+ this.#accumulateCost(outputValues, node.type);
2078
1994
  await this.#applyFrozenNodeDataflowEffects(node, outputValues, processId);
2079
1995
  this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
2080
1996
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
@@ -2086,15 +2002,15 @@ export class GraphProcessor {
2086
2002
  this.#finishStreamingOutputWatches(node, outputValues);
2087
2003
  }
2088
2004
  async #applyFrozenNodeDataflowEffects(node, outputValues, processId) {
2089
- const effect = applyFrozenGraphBoundaryEffects(this.#graphOutputs, node, outputValues);
2005
+ const effect = applyFrozenGraphBoundaryEffects(this.#run.graphOutputs, node, outputValues);
2090
2006
  if (!effect) {
2091
2007
  return;
2092
2008
  }
2093
2009
  if (effect.type === 'setStoredValue') {
2094
- await this.#storedValueController.seed(effect.key, effect.value);
2010
+ await this.#shared.storedValueController.seed(effect.key, effect.value);
2095
2011
  return;
2096
2012
  }
2097
- this.#globals.set(effect.variableId, effect.value);
2013
+ this.#shared.globals.set(effect.variableId, effect.value);
2098
2014
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id: effect.variableId, value: effect.value, processId }));
2099
2015
  }
2100
2016
  async #processNormalNode(node, processId, inputValues) {
@@ -2113,9 +2029,9 @@ export class GraphProcessor {
2113
2029
  const outputValues = await this.#processNodeWithInputData(node, inputValues, 0, processId, (node, partialOutputs, index) => this.#emitNodePartialOutput(node, partialOutputs, index, processId), () => {
2114
2030
  resultOrigin = 'editor-cache';
2115
2031
  });
2116
- this.#nodeResults.set(node.id, outputValues);
2117
- this.#visitedNodes.add(node.id);
2118
- this.#accumulateCost(outputValues);
2032
+ this.#run.nodeResults.set(node.id, outputValues);
2033
+ this.#run.visitedNodes.add(node.id);
2034
+ this.#accumulateCost(outputValues, node.type);
2119
2035
  this.#assertStreamingOutputWatchFinalOutputs(node, outputValues);
2120
2036
  const stopClaim = this.#claimStreamingWatchStopFromInvocation(node, outputValues);
2121
2037
  await this.#emitter.emit('nodeFinish', this.#withExecution(withOptionalDuration({
@@ -2134,7 +2050,7 @@ export class GraphProcessor {
2134
2050
  }
2135
2051
  async #nodeErrored(node, e, processId, durationMs, splitRunDurationMs, resultOrigin = 'executed', outputs, splitOutputs) {
2136
2052
  const error = getError(e);
2137
- for (const route of this.#inputStreamRoutes.get(node.id) ?? [])
2053
+ for (const route of this.#boundaries.inputStreamRoutes.get(node.id) ?? [])
2138
2054
  route.relay.finish({ error });
2139
2055
  // Most callers are ordinary (non-split) node executions. Let those retain
2140
2056
  // any checkpoint without requiring every error path to know about the
@@ -2148,7 +2064,7 @@ export class GraphProcessor {
2148
2064
  }
2149
2065
  this.#cancelStreamingOutputWatchesForSource(node.id);
2150
2066
  this.#cancelStreamingCatchesForSource(node.id);
2151
- this.#erroredNodes.set(node.id, error);
2067
+ this.#run.erroredNodes.set(node.id, error);
2152
2068
  await this.#emitter.emit('nodeError', this.#withExecution(withOptionalDuration({
2153
2069
  node,
2154
2070
  error,
@@ -2163,19 +2079,19 @@ export class GraphProcessor {
2163
2079
  emitDetached(this.#emitter, 'partialOutput', this.#withExecution({ node, outputs, index, processId, resultOrigin: 'executed' }));
2164
2080
  }
2165
2081
  #setFailureOutputs(processId, index, outputs) {
2166
- let outputsByIndex = this.#failureOutputsByProcessId.get(processId);
2082
+ let outputsByIndex = this.#run.failureOutputsByProcessId.get(processId);
2167
2083
  if (!outputsByIndex) {
2168
2084
  outputsByIndex = new Map();
2169
- this.#failureOutputsByProcessId.set(processId, outputsByIndex);
2085
+ this.#run.failureOutputsByProcessId.set(processId, outputsByIndex);
2170
2086
  }
2171
2087
  outputsByIndex.set(index, outputs);
2172
2088
  }
2173
2089
  #takeFailureOutputs(processId, index) {
2174
- const outputsByIndex = this.#failureOutputsByProcessId.get(processId);
2090
+ const outputsByIndex = this.#run.failureOutputsByProcessId.get(processId);
2175
2091
  const outputs = outputsByIndex?.get(index);
2176
2092
  outputsByIndex?.delete(index);
2177
2093
  if (outputsByIndex?.size === 0) {
2178
- this.#failureOutputsByProcessId.delete(processId);
2094
+ this.#run.failureOutputsByProcessId.delete(processId);
2179
2095
  }
2180
2096
  return outputs;
2181
2097
  }
@@ -2191,7 +2107,7 @@ export class GraphProcessor {
2191
2107
  return RACE_LOSER_EXCLUSION_REASON;
2192
2108
  }
2193
2109
  if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
2194
- this.#successfulAbortTerminalProcessIds.add(processId);
2110
+ this.#run.successfulAbortTerminalProcessIds.add(processId);
2195
2111
  return SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
2196
2112
  }
2197
2113
  if (this.#lifecycle.abortSuccessful && isAbortLikeError(error)) {
@@ -2199,7 +2115,7 @@ export class GraphProcessor {
2199
2115
  ? RACE_LOSER_EXCLUSION_REASON
2200
2116
  : SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON;
2201
2117
  if (exclusionReason === SUCCESSFUL_GRAPH_ABORT_EXCLUSION_REASON) {
2202
- this.#successfulAbortTerminalProcessIds.add(processId);
2118
+ this.#run.successfulAbortTerminalProcessIds.add(processId);
2203
2119
  }
2204
2120
  return exclusionReason;
2205
2121
  }
@@ -2223,17 +2139,12 @@ export class GraphProcessor {
2223
2139
  return undefined;
2224
2140
  }
2225
2141
  #getManagedAsyncBranchWatchViolation(triggerNode) {
2226
- const invocation = this.#getEnclosingStreamingWatchInvocation();
2227
- if (!invocation) {
2228
- return undefined;
2229
- }
2230
- return new Error(`Start Async Branch "${triggerNode.title}" cannot run inside Watch Streaming Output "${invocation.plan.watchNode.title}". ` +
2231
- 'A Watch invocation must keep all work within the Watch scheduler. Move Start Async Branch after Stop Watching Streaming Output, or run the work directly inside the watched branch.');
2142
+ return getAsyncBranchWatchViolation(triggerNode, this.#getEnclosingStreamingWatchInvocation()?.plan.watchNode);
2232
2143
  }
2233
2144
  /** Raise a user event on the processor, all subprocessors, and their children. */
2234
2145
  raiseEvent(event, data) {
2235
2146
  emitDetached(this.#emitter, `userEvent:${event}`, data);
2236
- for (const subprocessor of this.#subprocessors) {
2147
+ for (const subprocessor of this.#run.subprocessors) {
2237
2148
  subprocessor.raiseEvent(event, data);
2238
2149
  }
2239
2150
  }
@@ -2243,9 +2154,9 @@ export class GraphProcessor {
2243
2154
  return controller;
2244
2155
  }
2245
2156
  #registerNodeAbortController(nodeId, abortController) {
2246
- const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
2157
+ const existingAbortControllers = this.#run.nodeAbortControllers.get(nodeId);
2247
2158
  if (!existingAbortControllers) {
2248
- this.#nodeAbortControllers.set(nodeId, abortController);
2159
+ this.#run.nodeAbortControllers.set(nodeId, abortController);
2249
2160
  return;
2250
2161
  }
2251
2162
  if (existingAbortControllers instanceof Set) {
@@ -2255,15 +2166,15 @@ export class GraphProcessor {
2255
2166
  if (existingAbortControllers === abortController) {
2256
2167
  return;
2257
2168
  }
2258
- this.#nodeAbortControllers.set(nodeId, new Set([existingAbortControllers, abortController]));
2169
+ this.#run.nodeAbortControllers.set(nodeId, new Set([existingAbortControllers, abortController]));
2259
2170
  }
2260
2171
  #unregisterNodeAbortController(nodeId, abortController) {
2261
- const existingAbortControllers = this.#nodeAbortControllers.get(nodeId);
2172
+ const existingAbortControllers = this.#run.nodeAbortControllers.get(nodeId);
2262
2173
  if (!existingAbortControllers) {
2263
2174
  return;
2264
2175
  }
2265
2176
  if (existingAbortControllers === abortController) {
2266
- this.#nodeAbortControllers.delete(nodeId);
2177
+ this.#run.nodeAbortControllers.delete(nodeId);
2267
2178
  return;
2268
2179
  }
2269
2180
  if (!(existingAbortControllers instanceof Set)) {
@@ -2271,14 +2182,14 @@ export class GraphProcessor {
2271
2182
  }
2272
2183
  existingAbortControllers.delete(abortController);
2273
2184
  if (existingAbortControllers.size === 0) {
2274
- this.#nodeAbortControllers.delete(nodeId);
2185
+ this.#run.nodeAbortControllers.delete(nodeId);
2275
2186
  }
2276
2187
  else if (existingAbortControllers.size === 1) {
2277
- this.#nodeAbortControllers.set(nodeId, existingAbortControllers.values().next().value);
2188
+ this.#run.nodeAbortControllers.set(nodeId, existingAbortControllers.values().next().value);
2278
2189
  }
2279
2190
  }
2280
2191
  #abortNodeControllersForNode(nodeId, traceMessage, reason) {
2281
- const abortControllerEntry = this.#nodeAbortControllers.get(nodeId);
2192
+ const abortControllerEntry = this.#run.nodeAbortControllers.get(nodeId);
2282
2193
  if (!abortControllerEntry) {
2283
2194
  return;
2284
2195
  }
@@ -2297,7 +2208,7 @@ export class GraphProcessor {
2297
2208
  }
2298
2209
  }
2299
2210
  #abortActiveNodeControllers(reason) {
2300
- for (const nodeId of [...this.#nodeAbortControllers.keys()]) {
2211
+ for (const nodeId of [...this.#run.nodeAbortControllers.keys()]) {
2301
2212
  this.#abortNodeControllersForNode(nodeId, undefined, reason);
2302
2213
  }
2303
2214
  }
@@ -2310,8 +2221,8 @@ export class GraphProcessor {
2310
2221
  const instance = this.#nodeInstances[node.id];
2311
2222
  const nodeAbortController = this.#newAbortController();
2312
2223
  this.#registerNodeAbortController(node.id, nodeAbortController);
2313
- if (this.#abortController.signal.aborted) {
2314
- nodeAbortController.abort(getAbortSignalReason(this.#abortController.signal));
2224
+ if (this.#run.abortController.signal.aborted) {
2225
+ nodeAbortController.abort(getAbortSignalReason(this.#run.abortController.signal));
2315
2226
  }
2316
2227
  let continuationFinalized = false;
2317
2228
  try {
@@ -2338,7 +2249,7 @@ export class GraphProcessor {
2338
2249
  const abortReason = getGraphAbortReasonFromSignal(nodeAbortController.signal);
2339
2250
  if (nodeAbortController.signal.aborted) {
2340
2251
  if (isSuccessfulNonRaceGraphAbortReason(abortReason)) {
2341
- this.#successfulAbortTerminalProcessIds.add(processId);
2252
+ this.#run.successfulAbortTerminalProcessIds.add(processId);
2342
2253
  this.#discardFailureOutputs(processId, index);
2343
2254
  return results;
2344
2255
  }
@@ -2359,21 +2270,21 @@ export class GraphProcessor {
2359
2270
  }
2360
2271
  }
2361
2272
  #getTokenizer() {
2362
- return this.#context.tokenizer;
2273
+ return this.#run.context.tokenizer;
2363
2274
  }
2364
2275
  #createNodeProcessContext(node, inputValues, index, processId, nodeAbortController, partialOutput, toolCallTraceSource, markResultAsEditorCacheHit) {
2365
2276
  const plugin = this.#registry.getPluginFor(node.type);
2366
2277
  const acceptsPartialOutputs = () => {
2367
2278
  if (nodeAbortController.signal.aborted)
2368
2279
  return false;
2369
- const active = this.#nodeAbortControllers.get(node.id);
2280
+ const active = this.#run.nodeAbortControllers.get(node.id);
2370
2281
  return active === nodeAbortController || (active instanceof Set && active.has(nodeAbortController));
2371
2282
  };
2372
2283
  const onGraphOutputPartial = canForwardGraphCallerOutputPartials(node) &&
2373
- (this.#streamingWatchPlansBySourceNodeId.has(node.id) ||
2374
- this.#streamingCatchPlansBySourceNodeId.has(node.id) ||
2375
- this.#inputStreamRoutes.has(node.id) ||
2376
- this.#graphOutputPartialBindingsBySourceNodeId.has(node.id))
2284
+ (this.#boundaries.streamingWatchPlansBySourceNodeId.has(node.id) ||
2285
+ this.#boundaries.streamingCatchPlansBySourceNodeId.has(node.id) ||
2286
+ this.#boundaries.inputStreamRoutes.has(node.id) ||
2287
+ this.#boundaries.graphOutputPartialBindingsBySourceNodeId.has(node.id))
2377
2288
  ? (partialOutputs) => {
2378
2289
  if (!acceptsPartialOutputs())
2379
2290
  return;
@@ -2386,17 +2297,17 @@ export class GraphProcessor {
2386
2297
  const processContext = buildNodeProcessContext({
2387
2298
  activeOutputPortIds: this.#getActiveOutputPortIds(node),
2388
2299
  attachedData: this.#getAttachedDataTo(node),
2389
- base: this.#nodeProcessContextBase,
2300
+ base: this.#run.nodeProcessContextBase,
2390
2301
  createSubProcessor: (subGraphId, options = {}) => this.#createSubProcessor(node, index, processId, subGraphId, options),
2391
2302
  execution: this.#buildExecutionMetadata(),
2392
2303
  externalFunctions: this.#externalFunctions,
2393
- getPluginConfig: (name) => getPluginConfig(plugin, this.#context.settings, name),
2304
+ getPluginConfig: (name) => getPluginConfig(plugin, this.#run.context.settings, name),
2394
2305
  isDirectRunTarget: this.runToNodeIds?.includes(node.id) ?? false,
2395
2306
  markResultAsEditorCacheHit,
2396
2307
  node,
2397
2308
  nodeAbortController,
2398
2309
  onGraphOutputPartial,
2399
- graphInputStreams: this.#callerInputStreams.get(node.id),
2310
+ graphInputStreams: this.#boundaries.callerInputStreams.get(node.id),
2400
2311
  onPartialOutputs: (partialOutputs) => {
2401
2312
  if (!acceptsPartialOutputs())
2402
2313
  return;
@@ -2424,7 +2335,7 @@ export class GraphProcessor {
2424
2335
  },
2425
2336
  splitIndex: node.isSplitRun ? index : 0,
2426
2337
  setGlobal: (id, value) => {
2427
- this.#globals.set(id, value);
2338
+ this.#shared.globals.set(id, value);
2428
2339
  emitDetached(this.#emitter, 'globalSet', this.#withExecution({ id, value, processId }));
2429
2340
  },
2430
2341
  toolCallContinuation,
@@ -2456,7 +2367,7 @@ export class GraphProcessor {
2456
2367
  });
2457
2368
  if (node.type === 'subGraph' && node.data.targetProjectId) {
2458
2369
  const data = node.data;
2459
- processContext.subgraphTarget = this.#subgraphTargetCache.get(getSubgraphProjectKey({
2370
+ processContext.subgraphTarget = this.#shared.subgraphTargetCache.get(getSubgraphProjectKey({
2460
2371
  projectId: data.targetProjectId,
2461
2372
  version: data.targetVersion ?? 'latest',
2462
2373
  }));
@@ -2506,9 +2417,9 @@ export class GraphProcessor {
2506
2417
  },
2507
2418
  commit: (invocation) => {
2508
2419
  for (const [nodeId, outputs] of invocation.latestOutputs) {
2509
- this.#nodeResults.set(nodeId, outputs);
2510
- this.#visitedNodes.add(nodeId);
2511
- this.#remainingNodes.delete(nodeId);
2420
+ this.#run.nodeResults.set(nodeId, outputs);
2421
+ this.#run.visitedNodes.add(nodeId);
2422
+ this.#run.remainingNodes.delete(nodeId);
2512
2423
  this.#continuationCompletionOwnerByNodeId.set(nodeId, invocation.llmNodeId);
2513
2424
  }
2514
2425
  },
@@ -2569,10 +2480,10 @@ export class GraphProcessor {
2569
2480
  resultOrigin: 'executed',
2570
2481
  })),
2571
2482
  getActiveOutputPortIds: (node) => this.#getActiveOutputPortIds(node),
2572
- getContinuationBranchBoundaryNodeIds: (llmNode) => new Set([llmNode.id, ...this.#currentlyProcessing]),
2573
- hasPreloadedOrFrozenDelegateOutput: (node, inputs, processId) => this.#nodeResults.has(node.id) || this.#resolveFrozenNodeOutputs(node, inputs, processId) != null,
2483
+ getContinuationBranchBoundaryNodeIds: (llmNode) => new Set([llmNode.id, ...this.#run.currentlyProcessing]),
2484
+ hasPreloadedOrFrozenDelegateOutput: (node, inputs, processId) => this.#run.nodeResults.has(node.id) || this.#resolveFrozenNodeOutputs(node, inputs, processId) != null,
2574
2485
  registerNodeAbortController: (nodeId, controller) => this.#registerNodeAbortController(nodeId, controller),
2575
- rootAbortSignal: this.#abortController.signal,
2486
+ rootAbortSignal: this.#run.abortController.signal,
2576
2487
  unregisterNodeAbortController: (nodeId, controller) => this.#unregisterNodeAbortController(nodeId, controller),
2577
2488
  startNodeTiming: () => this.#startNodeTiming(),
2578
2489
  waitUntilUnpaused: () => this.#waitUntilUnpaused(),
@@ -2590,116 +2501,69 @@ export class GraphProcessor {
2590
2501
  if (!graphId) {
2591
2502
  throw new Error('Cannot execute a tool continuation branch because the current graph has no ID.');
2592
2503
  }
2593
- const branchRuntimeCache = {
2594
- ...this.#runtimeCache,
2595
- graphBoundaries: undefined,
2596
- loadedProjects: { ...this.#loadedProjects },
2597
- };
2598
- const branchGraphOutputs = createGraphOutputsOverlay(this.#graphOutputs);
2599
- const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
2600
- cacheLoadedProjects: true,
2601
- captureNodeTimings: this.#captureNodeTimings,
2602
- concurrency: this.#concurrency,
2603
- executionPlanCacheMode: this.#executionPlanCacheMode,
2604
- runtimeCache: branchRuntimeCache,
2605
- runtimeProfiler: this.#runtimeProfiler,
2606
- scheduler: this.#scheduler,
2607
- [graphProcessorGraphOverride]: branchPlan.graph,
2608
- });
2609
- processor.executor = this.executor;
2610
- processor.#isSubProcessor = true;
2611
- processor.#subgraphTargetCache = this.#subgraphTargetCache;
2612
- processor.#executionCache = this.#executionCache;
2613
- processor.#externalFunctions = this.#externalFunctions;
2614
- processor.#contextValues = this.#contextValues;
2615
- processor.#parent = this;
2616
- processor.#recordingProjectScope = this.#recordingProjectScope;
2617
- processor.#graphCallPath = this.#graphCallPath;
2504
+ const branchGraphOutputs = createGraphOutputsOverlay(this.#run.graphOutputs);
2505
+ const processor = this.#constructChildInvocation({ kind: 'continuation', graph: branchPlan.graph });
2618
2506
  processor.#abortOwnerOverride = this.#abortOwnerOverride ?? this;
2619
2507
  processor.#sameGraphRunOwnerOverride = this.#sameGraphRunOwnerOverride ?? this;
2620
- processor.#globals = this.#globals;
2621
- processor.#storedValueController = this.#storedValueController;
2622
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
2623
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
2624
- processor.#executor = this.#executor;
2625
2508
  processor.#suppressGraphLifecycleEvents = true;
2626
2509
  processor.#sharedRunStateOverride = {
2627
- attachedNodeData: this.#attachedNodeData,
2628
- graphInputNodeValues: this.#graphInputNodeValues,
2510
+ attachedNodeData: this.#run.attachedNodeData,
2511
+ graphInputNodeValues: this.#run.graphInputNodeValues,
2629
2512
  graphOutputs: branchGraphOutputs.view,
2630
2513
  };
2631
2514
  const branchNodeIds = new Set(branchPlan.graph.nodes.map((node) => node.id));
2632
2515
  const branchRunToNodeIds = this.runToNodeIds?.filter((nodeId) => branchNodeIds.has(nodeId));
2633
2516
  processor.runToNodeIds = branchRunToNodeIds?.length ? branchRunToNodeIds : undefined;
2634
2517
  processor.#executionIdentityOverride = {
2635
- rootRunId: this.#rootRunId,
2636
- graphRunId: this.#graphRunId,
2637
- parentGraphRunId: this.#parentGraphRunId,
2518
+ rootRunId: this.#run.rootRunId,
2519
+ graphRunId: this.#run.graphRunId,
2520
+ parentGraphRunId: this.#run.parentGraphRunId,
2638
2521
  };
2639
2522
  for (const [nodeId, outputs] of branchPlan.preloadedOutputs) {
2640
2523
  processor.preloadNodeData(nodeId, outputs);
2641
2524
  processor.#suppressedPreloadedNodeIds.add(nodeId);
2642
2525
  }
2643
- const unwireEvents = wireSubprocessorEvents(processor, this.#emitter, {
2526
+ const unwireEvents = this.#wireChildEvents(processor, this, {
2644
2527
  autoCleanup: false,
2645
- isPaused: () => this.#lifecycle.isPaused,
2646
- pause: () => {
2647
- void this.pause();
2648
- },
2649
- resume: () => {
2650
- void this.resume();
2651
- },
2652
2528
  });
2653
- const unwireLifecycle = wireSubprocessorLifecycle(processor, {
2529
+ const unwireLifecycle = this.#wireChildLifecycle(processor, this, unwireEvents, {
2654
2530
  autoCleanup: false,
2655
2531
  signal,
2656
- parentAbortSignal: this.#abortController.signal,
2657
- onParentPause: (listener) => {
2658
- this.on('pause', listener);
2659
- return () => {
2660
- this.off('pause', listener);
2661
- };
2662
- },
2663
- onParentResume: (listener) => {
2664
- this.on('resume', listener);
2665
- return () => {
2666
- this.off('resume', listener);
2667
- };
2668
- },
2669
2532
  });
2670
- this.#subprocessors.add(processor);
2533
+ this.#run.subprocessors.add(processor);
2534
+ let executionFailed = true;
2671
2535
  try {
2672
2536
  if (signal.aborted) {
2673
2537
  throw createGraphAbortErrorFromSignal(signal, 'Tool continuation branch aborted');
2674
2538
  }
2675
- await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
2539
+ await processor.processGraph(this.#run.context, this.#run.graphInputs, this.#contextValues);
2676
2540
  if (!deferGraphOutputCommit) {
2677
2541
  this.#commitContinuationGraphOutputs(branchGraphOutputs.writes);
2678
2542
  }
2679
- return {
2543
+ const result = {
2680
2544
  graphOutputWrites: branchGraphOutputs.writes,
2681
2545
  nodeOutputs: this.#getContinuationBranchResults(processor, branchPlan),
2682
2546
  };
2547
+ executionFailed = false;
2548
+ return result;
2683
2549
  }
2684
2550
  finally {
2685
- this.#totalCost += processor.#totalCost;
2686
- unwireLifecycle();
2687
- unwireEvents();
2688
- this.#subprocessors.delete(processor);
2551
+ this.#accumulateChildCost(processor);
2552
+ this.#releaseChildInvocation(processor, this, unwireLifecycle, unwireEvents, executionFailed);
2689
2553
  }
2690
2554
  }
2691
2555
  #commitContinuationGraphOutputs(writes) {
2692
2556
  for (const [outputId, value] of Object.entries(writes)) {
2693
- const existingValue = this.#graphOutputs[outputId];
2557
+ const existingValue = this.#run.graphOutputs[outputId];
2694
2558
  if (existingValue == null || existingValue.type === 'control-flow-excluded') {
2695
- this.#graphOutputs[outputId] = value;
2559
+ this.#run.graphOutputs[outputId] = value;
2696
2560
  }
2697
2561
  }
2698
2562
  }
2699
2563
  #getContinuationBranchResults(processor, branchPlan) {
2700
2564
  const results = new Map();
2701
- for (const [nodeId, outputs] of processor.#nodeResults) {
2702
- if (branchPlan.preloadedOutputs.has(nodeId) || !processor.#visitedNodes.has(nodeId)) {
2565
+ for (const [nodeId, outputs] of processor.#run.nodeResults) {
2566
+ if (branchPlan.preloadedOutputs.has(nodeId) || !processor.#run.visitedNodes.has(nodeId)) {
2703
2567
  continue;
2704
2568
  }
2705
2569
  results.set(nodeId, outputs);
@@ -2715,17 +2579,17 @@ export class GraphProcessor {
2715
2579
  sourceNode,
2716
2580
  sourceOutputs,
2717
2581
  state: {
2718
- erroredNodeIds: new Set(this.#erroredNodes.keys()),
2719
- nodeOutputs: this.#nodeResults,
2582
+ erroredNodeIds: new Set(this.#run.erroredNodes.keys()),
2583
+ nodeOutputs: this.#run.nodeResults,
2720
2584
  runToRelevantNodeIds: this.#getExecutionRelevantNodeIds(),
2721
- visitedNodeIds: this.#visitedNodes,
2585
+ visitedNodeIds: this.#run.visitedNodes,
2722
2586
  },
2723
2587
  });
2724
2588
  }
2725
2589
  #createToolCallContinuationBranchPlanner() {
2726
2590
  return createToolCallContinuationBranchPlanner({
2727
2591
  asyncBranchPlansByTriggerNodeId: this.#asyncBranchPlansByTriggerNodeId,
2728
- attachedNodeDataByNodeId: this.#attachedNodeData,
2592
+ attachedNodeDataByNodeId: this.#run.attachedNodeData,
2729
2593
  effectiveConnections: this.#getEffectiveConnections(),
2730
2594
  graph: this.#getExecutionGraph(),
2731
2595
  isDefinitionValidConnection: (connection) => this.#isDefinitionValidConnection(connection),
@@ -2771,140 +2635,26 @@ export class GraphProcessor {
2771
2635
  return this.#effectiveConnectionsForRun;
2772
2636
  }
2773
2637
  #prepareStreamingWatchTopology() {
2774
- const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2775
- const outgoingByNodeId = new Map();
2776
- const incomingByNodeId = new Map();
2777
- const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2778
- const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
2779
- for (const connection of connections) {
2780
- const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
2781
- outgoing.push(connection);
2782
- outgoingByNodeId.set(connection.outputNodeId, outgoing);
2783
- const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
2784
- incoming.push(connection);
2785
- incomingByNodeId.set(connection.inputNodeId, incoming);
2786
- }
2787
- for (const watchNode of Object.values(this.#nodesById)) {
2788
- if (watchNode.type !== 'watchStreamingOutput' || watchNode.disabled || !isRelevant(watchNode.id)) {
2789
- continue;
2790
- }
2791
- if (watchNode.id === this.#consumedStreamingWatchNodeId) {
2792
- continue;
2793
- }
2794
- const enclosingWatchInvocation = this.#getEnclosingStreamingWatchInvocation();
2795
- if (enclosingWatchInvocation) {
2796
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run inside Watch Streaming Output ` +
2797
- `"${enclosingWatchInvocation.plan.watchNode.title}". A Watch branch cannot contain another Watch, including through Subgraph.`);
2798
- }
2799
- if (this.#nodeResults.has(watchNode.id)) {
2800
- throw new Error(`Cannot preload ${watchNode.title} because a streaming boundary must be scheduled. ` +
2801
- "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
2802
- }
2803
- const incoming = incomingByNodeId.get(watchNode.id) ?? [];
2804
- if (incoming.length === 0) {
2805
- // An unattached Watch is an ordinary in-progress authoring state. Keep
2806
- // it dormant rather than making an incomplete canvas fail to run.
2807
- this.#ignoreNodes.add(watchNode.id);
2808
- continue;
2809
- }
2810
- if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
2811
- throw new Error(`Watch Streaming Output "${watchNode.title}" must have exactly one Streaming Output input connection.`);
2812
- }
2813
- const sourceConnection = incoming[0];
2814
- const sourceNode = this.#nodesById[sourceConnection.outputNodeId];
2815
- if (!sourceNode || sourceNode.disabled || !isRelevant(sourceNode.id)) {
2816
- throw new Error(`Watch Streaming Output "${watchNode.title}" has no runnable streaming source.`);
2817
- }
2818
- if (sourceNode.isSplitRun) {
2819
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot watch split-run node "${sourceNode.title}". ` +
2820
- 'Assemble a single streaming value before the watch boundary.');
2821
- }
2822
- const branchNodeIds = new Set();
2823
- const pendingNodeIds = (outgoingByNodeId.get(watchNode.id) ?? [])
2824
- .map((connection) => connection.inputNodeId)
2825
- .filter(isRelevant);
2826
- let stopNodeId;
2827
- while (pendingNodeIds.length > 0) {
2828
- const nodeId = pendingNodeIds.pop();
2829
- if (nodeId === watchNode.id) {
2830
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot reconnect to itself.`);
2831
- }
2832
- if (branchNodeIds.has(nodeId)) {
2833
- continue;
2834
- }
2835
- const node = this.#nodesById[nodeId];
2836
- if (!node || !isRelevant(nodeId)) {
2837
- continue;
2838
- }
2839
- if (node.disabled) {
2840
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot include disabled node "${node.title}".`);
2841
- }
2842
- if (node.type === 'watchStreamingOutput') {
2843
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain another Watch Streaming Output node.`);
2844
- }
2845
- if (node.type === 'catchStreamingChunks') {
2846
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Catch streaming chunks "${node.title}". ` +
2847
- 'Put Catch streaming chunks outside the repeated Watch branch.');
2848
- }
2849
- if (node.type === 'graphOutput') {
2850
- throw new Error(`Watch Streaming Output "${watchNode.title}" must reach Stop Watching Streaming Output before Graph Output "${node.title}".`);
2851
- }
2852
- if (node.type === 'startBackgroundBranch') {
2853
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot contain Start Async Branch. ` +
2854
- 'Keep watched work in the bounded watch branch instead.');
2855
- }
2856
- branchNodeIds.add(nodeId);
2857
- if (node.type === 'stopWatchingStreamingOutput') {
2858
- if (stopNodeId && stopNodeId !== nodeId) {
2859
- throw new Error(`Watch Streaming Output "${watchNode.title}" must have one Stop Watching Streaming Output boundary.`);
2860
- }
2861
- stopNodeId = nodeId;
2862
- continue;
2863
- }
2864
- for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
2865
- if (isRelevant(connection.inputNodeId)) {
2866
- pendingNodeIds.push(connection.inputNodeId);
2867
- }
2868
- }
2869
- }
2870
- if (branchNodeIds.size === 0) {
2871
- // Source -> Watch is also a useful intermediate authoring state. There
2872
- // is no downstream work to schedule yet, so do not create a coordinator.
2873
- this.#ignoreNodes.add(watchNode.id);
2638
+ for (const topology of planStreamingWatchTopology({
2639
+ graph: this.#graph,
2640
+ executionNodes: this.#executionGraphNodes,
2641
+ nodesById: this.#nodesById,
2642
+ connections: this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection)),
2643
+ relevantNodeIds: this.#getExecutionRelevantNodeIds(),
2644
+ preloadedNodes: this.#run.nodeResults,
2645
+ consumedWatchNodeId: this.#consumedStreamingWatchNodeId,
2646
+ enclosingWatchNode: this.#getEnclosingStreamingWatchInvocation()?.plan.watchNode,
2647
+ })) {
2648
+ const { watchNode } = topology;
2649
+ if (topology.kind === 'dormant') {
2650
+ this.#run.ignoreNodes.add(watchNode.id);
2874
2651
  continue;
2875
2652
  }
2876
- if (stopNodeId) {
2877
- const reentry = (outgoingByNodeId.get(stopNodeId) ?? []).find((connection) => connection.inputNodeId === watchNode.id || branchNodeIds.has(connection.inputNodeId));
2878
- if (reentry) {
2879
- const stopNode = this.#nodesById[stopNodeId];
2880
- throw new Error(`Stop Watching Streaming Output "${stopNode.title}" cannot reconnect to its own Watch Streaming Output branch. ` +
2881
- 'Connect it only to ordinary downstream execution.');
2882
- }
2883
- }
2884
- for (const nodeId of branchNodeIds) {
2885
- const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== watchNode.id && !branchNodeIds.has(connection.outputNodeId));
2886
- if (externalInput) {
2887
- const node = this.#nodesById[nodeId];
2888
- const externalNode = this.#nodesById[externalInput.outputNodeId];
2889
- throw new Error(`Watch Streaming Output "${watchNode.title}" cannot run "${node.title}" because it also depends on ` +
2890
- `"${externalNode?.title ?? externalInput.outputNodeId}" outside the watch branch. ` +
2891
- 'Assemble every required value inside the watch boundary.');
2892
- }
2893
- }
2894
- const graph = {
2895
- metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
2896
- nodes: this.#executionGraphNodes.filter((node) => node.id === watchNode.id || branchNodeIds.has(node.id)),
2897
- connections: connections.filter((connection) => connection.inputNodeId === watchNode.id ||
2898
- (branchNodeIds.has(connection.inputNodeId) &&
2899
- (connection.outputNodeId === watchNode.id || branchNodeIds.has(connection.outputNodeId)))),
2900
- };
2901
2653
  const plan = {
2902
- graph,
2903
- includeAllStreamedOutput: connections.some((connection) => connection.outputNodeId === watchNode.id &&
2904
- connection.outputId === 'allStreamedOutput' &&
2905
- branchNodeIds.has(connection.inputNodeId)),
2906
- sourceOutputId: sourceConnection.outputId,
2907
- stopNodeId,
2654
+ graph: topology.graph,
2655
+ includeAllStreamedOutput: topology.includeAllStreamedOutput,
2656
+ sourceOutputId: topology.sourceOutputId,
2657
+ stopNodeId: topology.stopNodeId,
2908
2658
  streamedOutput: [],
2909
2659
  previousStreamedValue: undefined,
2910
2660
  watchNode,
@@ -2913,15 +2663,13 @@ export class GraphProcessor {
2913
2663
  historySummaryEmitted: false,
2914
2664
  unmatchedStopResolved: false,
2915
2665
  };
2916
- const plans = this.#streamingWatchPlansBySourceNodeId.get(sourceNode.id) ?? [];
2666
+ const plans = this.#boundaries.streamingWatchPlansBySourceNodeId.get(topology.sourceNodeId) ?? [];
2917
2667
  plans.push(plan);
2918
- this.#streamingWatchPlansBySourceNodeId.set(sourceNode.id, plans);
2919
- this.#streamingWatchPlansByWatchNodeId.set(watchNode.id, plan);
2920
- const watch = new StreamingOutputWatch(watchNode.data, (snapshot, registerCancel) => this.#runStreamingOutputWatchInvocation(plan, snapshot, registerCancel), (error) => this.#recordStreamingWatchFailure(watchNode, error));
2921
- this.#streamingOutputWatches.set(watchNode.id, watch);
2922
- for (const nodeId of [watchNode.id, ...branchNodeIds]) {
2923
- this.#ignoreNodes.add(nodeId);
2924
- }
2668
+ this.#boundaries.streamingWatchPlansBySourceNodeId.set(topology.sourceNodeId, plans);
2669
+ this.#boundaries.streamingWatchPlansByWatchNodeId.set(watchNode.id, plan);
2670
+ this.#boundaries.streamingOutputWatches.set(watchNode.id, new StreamingOutputWatch(watchNode.data, (snapshot, registerCancel) => this.#runStreamingOutputWatchInvocation(plan, snapshot, registerCancel), (error) => this.#recordStreamingWatchFailure(watchNode, error)));
2671
+ for (const nodeId of [watchNode.id, ...topology.branchNodeIds])
2672
+ this.#run.ignoreNodes.add(nodeId);
2925
2673
  }
2926
2674
  this.#assertStreamingOutputWatchPreloadsAreSafe();
2927
2675
  }
@@ -2929,20 +2677,18 @@ export class GraphProcessor {
2929
2677
  const relevantNodeIds = this.#getExecutionRelevantNodeIds();
2930
2678
  const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
2931
2679
  for (const node of this.#executionGraphNodes) {
2932
- if (node.type !== 'catchStreamingChunks' ||
2933
- node.disabled ||
2934
- (relevantNodeIds && !relevantNodeIds.has(node.id)))
2680
+ if (node.type !== 'catchStreamingChunks' || node.disabled || (relevantNodeIds && !relevantNodeIds.has(node.id)))
2935
2681
  continue;
2936
2682
  // A saved Catch result is an ordinary once-only value. Run-from may reuse
2937
2683
  // it, but a live Catch still needs its own streaming coordinator.
2938
- if (this.#nodeResults.has(node.id))
2684
+ if (this.#run.nodeResults.has(node.id))
2939
2685
  continue;
2940
2686
  if (node.isConditional || node.isSplitRun) {
2941
2687
  throw new Error(`Catch streaming chunks "${node.title}" cannot use Conditional or Many runs.`);
2942
2688
  }
2943
2689
  const incoming = connections.filter((connection) => connection.inputNodeId === node.id);
2944
2690
  if (incoming.length === 0) {
2945
- this.#ignoreNodes.add(node.id);
2691
+ this.#run.ignoreNodes.add(node.id);
2946
2692
  continue;
2947
2693
  }
2948
2694
  if (incoming.length !== 1 || incoming[0].inputId !== 'stream') {
@@ -2963,14 +2709,16 @@ export class GraphProcessor {
2963
2709
  chunks: [],
2964
2710
  settled: false,
2965
2711
  };
2966
- const plans = this.#streamingCatchPlansBySourceNodeId.get(source.id) ?? [];
2712
+ const plans = this.#boundaries.streamingCatchPlansBySourceNodeId.get(source.id) ?? [];
2967
2713
  plans.push(plan);
2968
- this.#streamingCatchPlansBySourceNodeId.set(source.id, plans);
2969
- this.#ignoreNodes.add(node.id);
2714
+ this.#boundaries.streamingCatchPlansBySourceNodeId.set(source.id, plans);
2715
+ this.#run.ignoreNodes.add(node.id);
2970
2716
  }
2971
2717
  }
2972
2718
  #isStreamingOutputWatchBoundary(node) {
2973
- return node.type === 'watchStreamingOutput' || node.type === 'stopWatchingStreamingOutput' || node.type === 'catchStreamingChunks';
2719
+ return (node.type === 'watchStreamingOutput' ||
2720
+ node.type === 'stopWatchingStreamingOutput' ||
2721
+ node.type === 'catchStreamingChunks');
2974
2722
  }
2975
2723
  #assertStreamingOutputWatchPreloadCanBeAdded(nodeId) {
2976
2724
  // Before initialization, referenced projects and the effective graph are
@@ -2987,7 +2735,7 @@ export class GraphProcessor {
2987
2735
  throw new Error(`Cannot preload ${node.title} while it is running because a streaming boundary must be scheduled. ` +
2988
2736
  'Preload the producer before starting a new run instead.');
2989
2737
  }
2990
- for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
2738
+ for (const [sourceNodeId, plans] of this.#boundaries.streamingWatchPlansBySourceNodeId) {
2991
2739
  for (const plan of plans) {
2992
2740
  if (sourceNodeId === node.id || plan.graph.nodes.some((branchNode) => branchNode.id === node.id)) {
2993
2741
  throw new Error(`Cannot preload ${node.title} while Watch Streaming Output "${plan.watchNode.title}" is running. ` +
@@ -3007,7 +2755,7 @@ export class GraphProcessor {
3007
2755
  "Run from Watch Streaming Output to reuse a producer's saved final value, or run from the producer to stream again.");
3008
2756
  }
3009
2757
  }
3010
- for (const [sourceNodeId, plans] of this.#streamingWatchPlansBySourceNodeId) {
2758
+ for (const [sourceNodeId, plans] of this.#boundaries.streamingWatchPlansBySourceNodeId) {
3011
2759
  const sourceOutputs = this.#preloadedNodeResults.get(sourceNodeId);
3012
2760
  for (const plan of plans) {
3013
2761
  const preloadedBranchNode = plan.graph.nodes.find((node) => node.id !== this.#consumedStreamingWatchNodeId && this.#preloadedNodeResults.has(node.id));
@@ -3025,7 +2773,7 @@ export class GraphProcessor {
3025
2773
  }
3026
2774
  }
3027
2775
  #publishStreamingOutputWatchPartial(node, partialOutputs, coalesced = 0) {
3028
- for (const plan of this.#streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
2776
+ for (const plan of this.#boundaries.streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
3029
2777
  if (plan.settled)
3030
2778
  continue;
3031
2779
  const value = partialOutputs[plan.sourceOutputId];
@@ -3036,12 +2784,12 @@ export class GraphProcessor {
3036
2784
  if (plan.chunks.length >= plan.count)
3037
2785
  this.#scheduleStreamingCatchCompletion(plan);
3038
2786
  }
3039
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
2787
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3040
2788
  const value = partialOutputs[plan.sourceOutputId];
3041
2789
  if (value == null || value.type === 'control-flow-excluded') {
3042
2790
  continue;
3043
2791
  }
3044
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
2792
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3045
2793
  if (!watch || watch.stopped) {
3046
2794
  continue;
3047
2795
  }
@@ -3056,26 +2804,24 @@ export class GraphProcessor {
3056
2804
  return;
3057
2805
  plan.settled = true;
3058
2806
  const task = this.#completeStreamingCatch(plan).catch((error) => this.#nodeErrored(plan.node, error, nanoid()));
3059
- this.#streamingCatchTasks.add(task);
3060
- void task.then(() => this.#streamingCatchTasks.delete(task), () => this.#streamingCatchTasks.delete(task));
2807
+ this.#boundaries.streamingCatchTasks.add(task);
2808
+ void task.then(() => this.#boundaries.streamingCatchTasks.delete(task), () => this.#boundaries.streamingCatchTasks.delete(task));
3061
2809
  }
3062
2810
  async #completeStreamingCatch(plan) {
3063
- if (this.#abortController.signal.aborted)
2811
+ if (this.#run.abortController.signal.aborted)
3064
2812
  return;
3065
2813
  const node = plan.node;
3066
2814
  const processId = nanoid();
3067
2815
  const chunks = plan.chunks.slice(0, plan.count);
3068
- const output = plan.count === 1
3069
- ? chunks[0]
3070
- : { type: 'any[]', value: chunks.map((chunk) => chunk.value) };
2816
+ const output = plan.count === 1 ? chunks[0] : { type: 'any[]', value: chunks.map((chunk) => chunk.value) };
3071
2817
  const outputs = { ['value']: output };
3072
2818
  plan.chunks.length = 0;
3073
2819
  await this.#emitter.emit('nodeStart', this.#withExecution({ node, inputs: {}, processId, resultOrigin: 'executed' }));
3074
- if (this.#abortController.signal.aborted)
2820
+ if (this.#run.abortController.signal.aborted)
3075
2821
  return;
3076
- this.#nodeResults.set(node.id, outputs);
3077
- this.#visitedNodes.add(node.id);
3078
- this.#remainingNodes.delete(node.id);
2822
+ this.#run.nodeResults.set(node.id, outputs);
2823
+ this.#run.visitedNodes.add(node.id);
2824
+ this.#run.remainingNodes.delete(node.id);
3079
2825
  await this.#emitter.emit('nodeFinish', this.#withExecution({ node, outputs, processId, resultOrigin: 'executed' }));
3080
2826
  this.#finishStreamingOutputWatches(node, outputs);
3081
2827
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
@@ -3083,10 +2829,7 @@ export class GraphProcessor {
3083
2829
  this.#queueOutputNodes(node, outputNodes.nodes);
3084
2830
  }
3085
2831
  async #drainStreamingCatchTasks() {
3086
- while (this.#streamingCatchTasks.size > 0) {
3087
- await Promise.all([...this.#streamingCatchTasks]);
3088
- await this.#processingQueue.onIdle();
3089
- }
2832
+ await this.#boundaries.drainCatchTasks(() => this.#run.processingQueue.onIdle());
3090
2833
  }
3091
2834
  #prepareGraphInputStreamRoutes() {
3092
2835
  if (!this.#executionGraphNodes.some((node) => canStreamThroughGraphCaller(node) && this.#isNodeSelected(node.id)))
@@ -3094,7 +2837,7 @@ export class GraphProcessor {
3094
2837
  const marked = getProjectStreamingOutputWatchConnections({
3095
2838
  project: this.#project,
3096
2839
  graph: this.#graph,
3097
- referencedProjects: this.#loadedProjects,
2840
+ referencedProjects: this.#run.loadedProjects,
3098
2841
  registry: this.#registry,
3099
2842
  fullGraphCallers: new Set(this.runToNodeIds ?? []),
3100
2843
  isNodeFrozen: (_owner, candidate, node) => this.#frozenNodeOutputResolver != null &&
@@ -3128,39 +2871,39 @@ export class GraphProcessor {
3128
2871
  continue;
3129
2872
  const relay = new GraphInputStreamRelay();
3130
2873
  streams[edge.inputId] = relay;
3131
- const routes = this.#inputStreamRoutes.get(source.id) ?? [];
2874
+ const routes = this.#boundaries.inputStreamRoutes.get(source.id) ?? [];
3132
2875
  routes.push({ port: edge.outputId, relay });
3133
- this.#inputStreamRoutes.set(source.id, routes);
2876
+ this.#boundaries.inputStreamRoutes.set(source.id, routes);
3134
2877
  }
3135
2878
  if (Object.keys(streams).length)
3136
- this.#callerInputStreams.set(node.id, streams);
2879
+ this.#boundaries.callerInputStreams.set(node.id, streams);
3137
2880
  }
3138
2881
  const abort = () => {
3139
- const error = createGraphAbortErrorFromSignal(this.#abortController.signal);
3140
- for (const streams of this.#callerInputStreams.values()) {
2882
+ const error = createGraphAbortErrorFromSignal(this.#run.abortController.signal);
2883
+ for (const streams of this.#boundaries.callerInputStreams.values()) {
3141
2884
  for (const relay of Object.values(streams))
3142
2885
  relay.finish({ error });
3143
2886
  }
3144
2887
  };
3145
- this.#abortController.signal.addEventListener('abort', abort, { once: true });
3146
- this.#inputStreamDisposers.push(() => this.#abortController.signal.removeEventListener('abort', abort));
2888
+ this.#run.abortController.signal.addEventListener('abort', abort, { once: true });
2889
+ this.#boundaries.inputStreamDisposers.push(() => this.#run.abortController.signal.removeEventListener('abort', abort));
3147
2890
  }
3148
2891
  #publishGraphInputStreamPartial(node, outputs, coalesced = 0) {
3149
- for (const { port, relay } of this.#inputStreamRoutes.get(node.id) ?? []) {
2892
+ for (const { port, relay } of this.#boundaries.inputStreamRoutes.get(node.id) ?? []) {
3150
2893
  const value = outputs[port];
3151
2894
  if (value && value.type !== 'control-flow-excluded')
3152
2895
  relay.publish(value, coalesced);
3153
2896
  }
3154
2897
  }
3155
2898
  #subscribeGraphInputStreams() {
3156
- for (const [name, stream] of Object.entries(this.#graphInputStreams)) {
2899
+ for (const [name, stream] of Object.entries(this.#boundaries.graphInputStreams)) {
3157
2900
  const inputs = this.#executionGraphNodes.filter((node) => node.type === 'graphInput' &&
3158
2901
  node.data.id === name &&
3159
2902
  !node.disabled &&
3160
2903
  this.#isNodeSelected(node.id));
3161
2904
  let active = true;
3162
2905
  const unsubscribe = stream.subscribe((value, coalesced) => {
3163
- if (!active || this.#abortController.signal.aborted)
2906
+ if (!active || this.#run.abortController.signal.aborted)
3164
2907
  return;
3165
2908
  for (const node of inputs) {
3166
2909
  if (!canStreamThroughGraphInput(node) || this.#hasFrozenNodeOutputOrUnknownResolver(node))
@@ -3172,28 +2915,28 @@ export class GraphProcessor {
3172
2915
  this.#publishGraphInputStreamPartial(node, output, coalesced);
3173
2916
  }
3174
2917
  });
3175
- this.#inputStreamDisposers.push(() => {
2918
+ this.#boundaries.inputStreamDisposers.push(() => {
3176
2919
  active = false;
3177
2920
  unsubscribe();
3178
2921
  });
3179
2922
  void stream.settled.then((result) => {
3180
- if (!active || this.#abortController.signal.aborted)
2923
+ if (!active || this.#run.abortController.signal.aborted)
3181
2924
  return;
3182
2925
  if (result.value)
3183
- this.#graphInputs[name] = result.value;
2926
+ this.#run.graphInputs[name] = result.value;
3184
2927
  for (const node of inputs)
3185
- void this.#processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
2928
+ void this.#run.processingQueue.add(() => this.#processNodeIfAllInputsAvailable(node));
3186
2929
  });
3187
2930
  }
3188
2931
  }
3189
2932
  async #waitForGraphInputStreams() {
3190
- const signal = this.#abortController.signal;
2933
+ const signal = this.#run.abortController.signal;
3191
2934
  if (signal.aborted)
3192
2935
  throw createGraphAbortErrorFromSignal(signal);
3193
2936
  let abort;
3194
2937
  try {
3195
2938
  await Promise.race([
3196
- Promise.all(Object.values(this.#graphInputStreams).map((stream) => stream.settled)),
2939
+ Promise.all(Object.values(this.#boundaries.graphInputStreams).map((stream) => stream.settled)),
3197
2940
  new Promise((_resolve, reject) => {
3198
2941
  abort = () => reject(createGraphAbortErrorFromSignal(signal));
3199
2942
  signal.addEventListener('abort', abort, { once: true });
@@ -3240,13 +2983,13 @@ export class GraphProcessor {
3240
2983
  !canForwardGraphOutputPartials(graphOutput, sourceNode, this.#hasFrozenNodeOutputOrUnknownResolver(graphOutput))) {
3241
2984
  continue;
3242
2985
  }
3243
- const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(connection.outputNodeId) ?? [];
2986
+ const bindings = this.#boundaries.graphOutputPartialBindingsBySourceNodeId.get(connection.outputNodeId) ?? [];
3244
2987
  bindings.push({
3245
2988
  dataType: graphOutputData.dataType,
3246
2989
  graphOutputId: graphOutputData.id,
3247
2990
  sourceOutputId: connection.outputId,
3248
2991
  });
3249
- this.#graphOutputPartialBindingsBySourceNodeId.set(connection.outputNodeId, bindings);
2992
+ this.#boundaries.graphOutputPartialBindingsBySourceNodeId.set(connection.outputNodeId, bindings);
3250
2993
  }
3251
2994
  }
3252
2995
  #hasFrozenNodeOutputOrUnknownResolver(node) {
@@ -3268,7 +3011,7 @@ export class GraphProcessor {
3268
3011
  */
3269
3012
  #publishGraphOutputPartial(node, partialOutputs) {
3270
3013
  const listener = this.#graphOutputPartialListener;
3271
- const bindings = this.#graphOutputPartialBindingsBySourceNodeId.get(node.id);
3014
+ const bindings = this.#boundaries.graphOutputPartialBindingsBySourceNodeId.get(node.id);
3272
3015
  if (!listener || !bindings) {
3273
3016
  return;
3274
3017
  }
@@ -3286,16 +3029,16 @@ export class GraphProcessor {
3286
3029
  }
3287
3030
  #finishStreamingOutputWatches(node, outputs) {
3288
3031
  if (node.type === 'graphInput') {
3289
- const terminals = Object.values(this.#graphInputStreams).map((stream) => stream.result);
3032
+ const terminals = Object.values(this.#boundaries.graphInputStreams).map((stream) => stream.result);
3290
3033
  if (terminals.some((result) => !result)) {
3291
3034
  // Defaults/non-streamed arguments may be needed for caller startup, but
3292
3035
  // their final Watch delivery must not release ordinary nested work early.
3293
- this.#pendingGraphInputFinals.set(node.id, cloneExecutionOutputs(outputs));
3036
+ this.#boundaries.pendingGraphInputFinals.set(node.id, cloneExecutionOutputs(outputs));
3294
3037
  return;
3295
3038
  }
3296
3039
  const failure = terminals.find((result) => result?.error);
3297
3040
  if (failure?.error) {
3298
- for (const route of this.#inputStreamRoutes.get(node.id) ?? [])
3041
+ for (const route of this.#boundaries.inputStreamRoutes.get(node.id) ?? [])
3299
3042
  route.relay.finish({ error: failure.error });
3300
3043
  this.#cancelStreamingOutputWatchesForSource(node.id);
3301
3044
  this.#cancelStreamingCatchesForSource(node.id);
@@ -3305,13 +3048,11 @@ export class GraphProcessor {
3305
3048
  outputs = Object.fromEntries(Object.keys(outputs).map((port) => [port, { type: 'control-flow-excluded', value: undefined }]));
3306
3049
  }
3307
3050
  }
3308
- for (const plan of this.#streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
3051
+ for (const plan of this.#boundaries.streamingCatchPlansBySourceNodeId.get(node.id) ?? []) {
3309
3052
  if (plan.settled)
3310
3053
  continue;
3311
3054
  const finalValue = outputs[plan.sourceOutputId];
3312
- if (finalValue &&
3313
- finalValue.type !== 'control-flow-excluded' &&
3314
- !isEqual(plan.chunks.at(-1), finalValue)) {
3055
+ if (finalValue && finalValue.type !== 'control-flow-excluded' && !isEqual(plan.chunks.at(-1), finalValue)) {
3315
3056
  plan.chunks.push(cloneExecutionOutputs({ ['value']: finalValue })['value']);
3316
3057
  }
3317
3058
  if (plan.chunks.length > 0) {
@@ -3322,13 +3063,13 @@ export class GraphProcessor {
3322
3063
  this.#excludeNode(plan.node, nanoid(), {}, 'stream completed without a value');
3323
3064
  }
3324
3065
  }
3325
- for (const { port, relay } of this.#inputStreamRoutes.get(node.id) ?? []) {
3066
+ for (const { port, relay } of this.#boundaries.inputStreamRoutes.get(node.id) ?? []) {
3326
3067
  const value = outputs[port];
3327
3068
  relay.finish(value ? { value } : { error: new Error(`Missing final streamed output ${port}`) });
3328
3069
  }
3329
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3070
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3330
3071
  const value = outputs[plan.sourceOutputId];
3331
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3072
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3332
3073
  if (!watch || watch.stopped) {
3333
3074
  continue;
3334
3075
  }
@@ -3349,8 +3090,8 @@ export class GraphProcessor {
3349
3090
  }
3350
3091
  }
3351
3092
  #assertStreamingOutputWatchFinalOutputs(node, outputs) {
3352
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3353
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3093
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(node.id) ?? []) {
3094
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3354
3095
  if (!watch || watch.stopped || outputs[plan.sourceOutputId] != null) {
3355
3096
  continue;
3356
3097
  }
@@ -3417,118 +3158,83 @@ export class GraphProcessor {
3417
3158
  }
3418
3159
  async #runStreamingOutputWatchInvocation(plan, snapshot, registerCancel) {
3419
3160
  const root = this.getRootProcessor();
3420
- if (root.#abortController.signal.aborted) {
3421
- throw createGraphAbortErrorFromSignal(root.#abortController.signal, 'Streaming watch branch aborted before it started');
3161
+ if (root.#run.abortController.signal.aborted) {
3162
+ throw createGraphAbortErrorFromSignal(root.#run.abortController.signal, 'Streaming watch branch aborted before it started');
3422
3163
  }
3423
3164
  const graphId = plan.graph.metadata?.id;
3424
3165
  if (!graphId) {
3425
3166
  throw new Error('Cannot start a streaming watch branch because the current graph has no ID.');
3426
3167
  }
3427
3168
  const historyIteration = plan.history.start(nanoid(), snapshot.updateIndex);
3428
- const branchRuntimeCache = {
3429
- ...this.#runtimeCache,
3430
- graphBoundaries: undefined,
3431
- loadedProjects: { ...this.#loadedProjects },
3432
- };
3433
- const processor = new GraphProcessor(this.#project, graphId, this.#registry, this.#includeTrace, {
3434
- cacheLoadedProjects: true,
3435
- captureNodeTimings: this.#captureNodeTimings,
3436
- concurrency: this.#concurrency,
3437
- executionPlanCacheMode: this.#executionPlanCacheMode,
3438
- runtimeCache: branchRuntimeCache,
3439
- runtimeProfiler: this.#runtimeProfiler,
3440
- scheduler: this.#scheduler,
3441
- [consumedStreamingWatchNodeOverride]: plan.watchNode.id,
3442
- [graphProcessorGraphOverride]: plan.graph,
3443
- });
3444
- processor.executor = this.executor;
3445
- processor.#isSubProcessor = true;
3446
- processor.#subgraphTargetCache = this.#subgraphTargetCache;
3447
- processor.#executionCache = this.#executionCache;
3448
- processor.#externalFunctions = this.#externalFunctions;
3449
- processor.#contextValues = this.#contextValues;
3450
- processor.#parent = this;
3451
- processor.#recordingProjectScope = this.#recordingProjectScope;
3452
- processor.#graphCallPath = this.#graphCallPath;
3453
- processor.#abortOwnerOverride = root;
3454
- processor.#suppressGraphPartialOutputs = true;
3455
- processor.#globals = this.#globals;
3456
- processor.#storedValueController = this.#storedValueController;
3457
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
3458
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3459
- processor.#executor = this.#executor;
3460
- processor.#suppressGraphLifecycleEvents = true;
3461
- processor.#sharedRunStateOverride = {
3462
- // Repeated node IDs do not imply shared race/loop state between snapshots.
3463
- attachedNodeData: new Map(),
3464
- graphInputNodeValues: { ...this.#graphInputNodeValues },
3465
- graphOutputs: {},
3466
- };
3467
- processor.#executionIdentityOverride = {
3468
- rootRunId: root.#rootRunId,
3469
- graphRunId: historyIteration.graphRunId,
3470
- parentGraphRunId: this.#graphRunId,
3471
- };
3472
- processor.#streamingWatchInvocation = {
3473
- plan,
3474
- historyIteration,
3475
- claimStop: (value) => this.#claimAcceptedStreamingWatchStop(plan, historyIteration, value, snapshot.updateIndex),
3476
- stopReached: false,
3477
- };
3478
- processor.preloadNodeData(plan.watchNode.id, this.#materializeStreamingOutputWatchSnapshot(snapshot));
3479
- processor.#suppressedPreloadedNodeIds.add(plan.watchNode.id);
3169
+ let processor;
3170
+ let unwireEvents;
3171
+ let unwireLifecycle;
3480
3172
  let cancellationRequested = false;
3481
- registerCancel(() => {
3482
- cancellationRequested = true;
3483
- if (processor.isRunning) {
3484
- void processor.abort(true);
3485
- }
3486
- });
3487
- const unwireEvents = wireSubprocessorEvents(processor, root.#emitter, {
3488
- autoCleanup: false,
3489
- isPaused: () => root.#lifecycle.isPaused,
3490
- pause: () => {
3491
- void root.pause();
3492
- },
3493
- resume: () => {
3494
- void root.resume();
3495
- },
3496
- forwardEvent: (event, data) => {
3497
- // Interactive/global control events are side effects, not execution
3498
- // history. They must remain live even when their enclosing iteration
3499
- // is not selected for retained evidence.
3500
- if (event === 'userInput' ||
3501
- event === 'globalSet' ||
3502
- event === 'newAbortController' ||
3503
- event.startsWith('globalSet:')) {
3504
- return root.#emitter.emit(event, data);
3505
- }
3506
- return plan.history.forward(historyIteration, event, data, (nextEvent, nextData) => root.#emitter.emit(nextEvent, nextData));
3507
- },
3508
- });
3509
- const unwireLifecycle = wireSubprocessorLifecycle(processor, {
3510
- autoCleanup: false,
3511
- signal: this.#abortController.signal,
3512
- parentAbortSignal: root.#abortController.signal,
3513
- onParentPause: (listener) => {
3514
- root.on('pause', listener);
3515
- return () => root.off('pause', listener);
3516
- },
3517
- onParentResume: (listener) => {
3518
- root.on('resume', listener);
3519
- return () => root.off('resume', listener);
3520
- },
3521
- });
3522
- root.#subprocessors.add(processor);
3173
+ let executionFailed = true;
3523
3174
  try {
3175
+ processor = this.#constructChildInvocation({
3176
+ kind: 'watch',
3177
+ graph: plan.graph,
3178
+ watchNodeId: plan.watchNode.id,
3179
+ });
3180
+ processor.#abortOwnerOverride = root;
3181
+ processor.#suppressGraphPartialOutputs = true;
3182
+ processor.#suppressGraphLifecycleEvents = true;
3183
+ processor.#sharedRunStateOverride = {
3184
+ // Repeated node IDs do not imply shared race/loop state between snapshots.
3185
+ attachedNodeData: new Map(),
3186
+ graphInputNodeValues: { ...this.#run.graphInputNodeValues },
3187
+ graphOutputs: {},
3188
+ };
3189
+ processor.#executionIdentityOverride = {
3190
+ rootRunId: root.#run.rootRunId,
3191
+ graphRunId: historyIteration.graphRunId,
3192
+ parentGraphRunId: this.#run.graphRunId,
3193
+ };
3194
+ processor.#streamingWatchInvocation = {
3195
+ plan,
3196
+ historyIteration,
3197
+ claimStop: (value) => this.#claimAcceptedStreamingWatchStop(plan, historyIteration, value, snapshot.updateIndex),
3198
+ stopReached: false,
3199
+ };
3200
+ processor.preloadNodeData(plan.watchNode.id, this.#materializeStreamingOutputWatchSnapshot(snapshot));
3201
+ processor.#suppressedPreloadedNodeIds.add(plan.watchNode.id);
3202
+ const watchProcessor = processor;
3203
+ registerCancel(() => {
3204
+ cancellationRequested = true;
3205
+ if (watchProcessor.isRunning) {
3206
+ void watchProcessor.abort(true);
3207
+ }
3208
+ });
3209
+ unwireEvents = this.#wireChildEvents(processor, root, {
3210
+ autoCleanup: false,
3211
+ forwardEvent: (event, data) => {
3212
+ // Interactive/global control events are side effects, not execution
3213
+ // history. They must remain live even when their enclosing iteration
3214
+ // is not selected for retained evidence.
3215
+ if (event === 'userInput' ||
3216
+ event === 'globalSet' ||
3217
+ event === 'newAbortController' ||
3218
+ event.startsWith('globalSet:')) {
3219
+ return root.#emitter.emit(event, data);
3220
+ }
3221
+ return plan.history.forward(historyIteration, event, data, (nextEvent, nextData) => root.#emitter.emit(nextEvent, nextData));
3222
+ },
3223
+ });
3224
+ unwireLifecycle = this.#wireChildLifecycle(processor, root, unwireEvents, {
3225
+ autoCleanup: false,
3226
+ signal: this.#run.abortController.signal,
3227
+ });
3228
+ root.#run.subprocessors.add(processor);
3524
3229
  if (root.#lifecycle.isPaused) {
3525
3230
  processor.pause();
3526
3231
  }
3527
- await processor.processGraph(this.#context, this.#graphInputs, this.#contextValues);
3232
+ await processor.processGraph(this.#run.context, this.#run.graphInputs, this.#contextValues);
3233
+ executionFailed = false;
3528
3234
  }
3529
3235
  catch (error) {
3530
3236
  const normalizedError = getError(error);
3531
- const wasCancelled = isAbortLikeError(normalizedError) || root.#abortController.signal.aborted || cancellationRequested;
3237
+ const wasCancelled = isAbortLikeError(normalizedError) || root.#run.abortController.signal.aborted || cancellationRequested;
3532
3238
  if (wasCancelled) {
3533
3239
  plan.history.cancel(historyIteration);
3534
3240
  }
@@ -3547,10 +3253,10 @@ export class GraphProcessor {
3547
3253
  plan.history.cancel(historyIteration);
3548
3254
  }
3549
3255
  plan.history.complete(historyIteration);
3550
- this.#totalCost += processor.#totalCost;
3551
- unwireLifecycle();
3552
- unwireEvents();
3553
- root.#subprocessors.delete(processor);
3256
+ if (processor) {
3257
+ this.#accumulateChildCost(processor);
3258
+ this.#releaseChildInvocation(processor, root, unwireLifecycle, unwireEvents, executionFailed);
3259
+ }
3554
3260
  }
3555
3261
  }
3556
3262
  #claimStreamingWatchStopFromInvocation(node, outputs) {
@@ -3569,7 +3275,7 @@ export class GraphProcessor {
3569
3275
  if (!stopNodeId) {
3570
3276
  return undefined;
3571
3277
  }
3572
- const watch = this.#streamingOutputWatches.get(plan.watchNode.id);
3278
+ const watch = this.#boundaries.streamingOutputWatches.get(plan.watchNode.id);
3573
3279
  if (!watch || watch.stopped) {
3574
3280
  return undefined;
3575
3281
  }
@@ -3586,9 +3292,9 @@ export class GraphProcessor {
3586
3292
  if (committed)
3587
3293
  return;
3588
3294
  committed = true;
3589
- this.#nodeResults.set(stopNode.id, { ['value']: acceptedValue });
3590
- this.#visitedNodes.add(stopNode.id);
3591
- this.#remainingNodes.delete(stopNode.id);
3295
+ this.#run.nodeResults.set(stopNode.id, { ['value']: acceptedValue });
3296
+ this.#run.visitedNodes.add(stopNode.id);
3297
+ this.#run.remainingNodes.delete(stopNode.id);
3592
3298
  const attachedData = this.#getAttachedDataTo(stopNode);
3593
3299
  const outputNodes = getOutputNodesFrom(this.#executionState, stopNode);
3594
3300
  this.#propagateAttachedDataToOutputNodes(stopNode, attachedData, outputNodes.connectionsToNodes);
@@ -3597,12 +3303,12 @@ export class GraphProcessor {
3597
3303
  };
3598
3304
  }
3599
3305
  #cancelStreamingOutputWatchesForSource(nodeId) {
3600
- for (const plan of this.#streamingWatchPlansBySourceNodeId.get(nodeId) ?? []) {
3601
- this.#streamingOutputWatches.get(plan.watchNode.id)?.stop();
3306
+ for (const plan of this.#boundaries.streamingWatchPlansBySourceNodeId.get(nodeId) ?? []) {
3307
+ this.#boundaries.streamingOutputWatches.get(plan.watchNode.id)?.stop();
3602
3308
  }
3603
3309
  }
3604
3310
  #cancelStreamingCatchesForSource(nodeId) {
3605
- for (const plan of this.#streamingCatchPlansBySourceNodeId.get(nodeId) ?? []) {
3311
+ for (const plan of this.#boundaries.streamingCatchPlansBySourceNodeId.get(nodeId) ?? []) {
3606
3312
  if (plan.settled)
3607
3313
  continue;
3608
3314
  plan.settled = true;
@@ -3610,21 +3316,21 @@ export class GraphProcessor {
3610
3316
  }
3611
3317
  }
3612
3318
  #cancelStreamingOutputWatches() {
3613
- for (const watch of this.#streamingOutputWatches.values()) {
3319
+ for (const watch of this.#boundaries.streamingOutputWatches.values()) {
3614
3320
  watch.stop();
3615
3321
  }
3616
3322
  }
3617
3323
  #hasPendingStreamingOutputWatches() {
3618
- return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending);
3324
+ return [...this.#boundaries.streamingOutputWatches.values()].some((watch) => watch.hasPending);
3619
3325
  }
3620
3326
  #hasUnresolvedForegroundOutputStreamingWatch() {
3621
- return [...this.#streamingOutputWatches].some(([watchNodeId, watch]) => {
3622
- const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3327
+ return [...this.#boundaries.streamingOutputWatches].some(([watchNodeId, watch]) => {
3328
+ const plan = this.#boundaries.streamingWatchPlansByWatchNodeId.get(watchNodeId);
3623
3329
  return plan?.stopNodeId != null && !plan.unmatchedStopResolved && !watch.stopped;
3624
3330
  });
3625
3331
  }
3626
3332
  #hasDrainableStreamingOutputWatches() {
3627
- return [...this.#streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
3333
+ return [...this.#boundaries.streamingOutputWatches.values()].some((watch) => watch.hasPending && !watch.isAwaitingProducer);
3628
3334
  }
3629
3335
  async #drainSchedulerBoundaries() {
3630
3336
  do {
@@ -3635,25 +3341,25 @@ export class GraphProcessor {
3635
3341
  await this.#profileRuntimeAsync('drainStreamingOutputWatches', () => this.#drainStreamingOutputWatches());
3636
3342
  } while ((!this.#isSubProcessor && this.#managedAsyncBranches.hasPending) ||
3637
3343
  this.#hasDrainableStreamingOutputWatches() ||
3638
- this.#streamingCatchTasks.size > 0);
3344
+ this.#boundaries.streamingCatchTasks.size > 0);
3639
3345
  }
3640
3346
  async #drainStreamingOutputWatches() {
3641
3347
  do {
3642
- for (const watch of this.#streamingOutputWatches.values()) {
3348
+ for (const watch of this.#boundaries.streamingOutputWatches.values()) {
3643
3349
  await watch.drain();
3644
3350
  }
3645
3351
  // Accepting Stop happens in a child run. It can enqueue ordinary parent
3646
3352
  // work after the compatible scheduler has returned, so wait for that work
3647
3353
  // before deciding every Watch boundary is quiet.
3648
- await this.#processingQueue.onIdle();
3354
+ await this.#run.processingQueue.onIdle();
3649
3355
  this.#resolveUnmatchedStreamingWatchStops();
3650
3356
  // Excluding the parent Stop queues its ordinary downstream nodes. Let
3651
3357
  // their normal control-flow rules run before emitting the settled Watch
3652
3358
  // summary or finalizing the root graph.
3653
- await this.#processingQueue.onIdle();
3359
+ await this.#run.processingQueue.onIdle();
3654
3360
  } while (this.#hasDrainableStreamingOutputWatches());
3655
- for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3656
- const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3361
+ for (const [watchNodeId, watch] of this.#boundaries.streamingOutputWatches) {
3362
+ const plan = this.#boundaries.streamingWatchPlansByWatchNodeId.get(watchNodeId);
3657
3363
  if (!plan || plan.historySummaryEmitted || !watch.isSettled)
3658
3364
  continue;
3659
3365
  const summary = await plan.history.finalize(watch.runtimeSummary, (event, data) => this.#emitter.emit(event, data));
@@ -3662,8 +3368,8 @@ export class GraphProcessor {
3662
3368
  }
3663
3369
  }
3664
3370
  #resolveUnmatchedStreamingWatchStops() {
3665
- for (const [watchNodeId, watch] of this.#streamingOutputWatches) {
3666
- const plan = this.#streamingWatchPlansByWatchNodeId.get(watchNodeId);
3371
+ for (const [watchNodeId, watch] of this.#boundaries.streamingOutputWatches) {
3372
+ const plan = this.#boundaries.streamingWatchPlansByWatchNodeId.get(watchNodeId);
3667
3373
  if (!plan?.stopNodeId || plan.unmatchedStopResolved || !watch.finishedNormally) {
3668
3374
  continue;
3669
3375
  }
@@ -3676,97 +3382,23 @@ export class GraphProcessor {
3676
3382
  }
3677
3383
  }
3678
3384
  #prepareAsyncBranchTopology() {
3679
- const connections = this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection));
3680
- const outgoingByNodeId = new Map();
3681
- const incomingByNodeId = new Map();
3682
- const relevantNodeIds = this.#getExecutionRelevantNodeIds();
3683
- const isRelevant = (nodeId) => !relevantNodeIds || relevantNodeIds.has(nodeId);
3684
- for (const connection of connections) {
3685
- const outgoing = outgoingByNodeId.get(connection.outputNodeId) ?? [];
3686
- outgoing.push(connection);
3687
- outgoingByNodeId.set(connection.outputNodeId, outgoing);
3688
- const incoming = incomingByNodeId.get(connection.inputNodeId) ?? [];
3689
- incoming.push(connection);
3690
- incomingByNodeId.set(connection.inputNodeId, incoming);
3691
- }
3692
- for (const triggerNode of Object.values(this.#nodesById)) {
3693
- // Input anchors describe the consumed trigger's ports, not executable work.
3694
- // A variadic anchor may itself be an outer async trigger.
3695
- if (this.#asyncBranchInputAnchors?.[triggerNode.id])
3696
- continue;
3697
- if (triggerNode.type !== 'startBackgroundBranch' || triggerNode.disabled || !isRelevant(triggerNode.id)) {
3698
- continue;
3699
- }
3700
- if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId && this.#nodeResults.has(triggerNode.id)) {
3701
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot use preloaded outputs because replaying it could repeat async side effects.`);
3702
- }
3703
- const nodeIds = new Set();
3704
- const pendingNodeIds = (outgoingByNodeId.get(triggerNode.id) ?? [])
3705
- .map((connection) => connection.inputNodeId)
3706
- .filter(isRelevant);
3707
- while (pendingNodeIds.length > 0) {
3708
- const nodeId = pendingNodeIds.pop();
3709
- if (nodeId === triggerNode.id) {
3710
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot be part of a cycle or reconnect to its own inputs.`);
3711
- }
3712
- if (nodeIds.has(nodeId)) {
3713
- continue;
3714
- }
3715
- const node = this.#nodesById[nodeId];
3716
- if (!node) {
3717
- continue;
3718
- }
3719
- if (node.disabled) {
3720
- continue;
3721
- }
3722
- if (node.type === 'graphOutput') {
3723
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain Graph Output node "${node.title}". Async branches are side-effect-only.`);
3724
- }
3725
- nodeIds.add(nodeId);
3726
- for (const connection of outgoingByNodeId.get(nodeId) ?? []) {
3727
- if (isRelevant(connection.inputNodeId)) {
3728
- pendingNodeIds.push(connection.inputNodeId);
3729
- }
3730
- }
3731
- }
3732
- for (const nodeId of nodeIds) {
3733
- const externalInput = (incomingByNodeId.get(nodeId) ?? []).find((connection) => connection.outputNodeId !== triggerNode.id && !nodeIds.has(connection.outputNodeId));
3734
- if (externalInput) {
3735
- const node = this.#nodesById[nodeId];
3736
- const externalNode = this.#nodesById[externalInput.outputNodeId];
3737
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot run "${node.title}" because it also depends on ` +
3738
- `"${externalNode?.title ?? externalInput.outputNodeId}" outside the async branch. Assemble all required values before the async trigger.`);
3739
- }
3740
- }
3741
- if (nodeIds.size === 0) {
3742
- continue;
3743
- }
3744
- const managedAsyncBranchWatchViolation = this.#getManagedAsyncBranchWatchViolation(triggerNode);
3745
- if (managedAsyncBranchWatchViolation) {
3746
- throw managedAsyncBranchWatchViolation;
3747
- }
3748
- const preloadedNodeId = [...nodeIds].find((nodeId) => this.#nodeResults.has(nodeId));
3749
- if (preloadedNodeId) {
3750
- const preloadedNode = this.#nodesById[preloadedNodeId];
3751
- throw new Error(`Start Async Branch "${triggerNode.title}" cannot contain preloaded node "${preloadedNode.title}". Preloading an async descendant would bypass the trigger boundary.`);
3752
- }
3753
- // The node derives its variadic output definitions from connected inputs.
3754
- // Retain shallow input anchors in the slice even though the trigger itself is preloaded.
3755
- const triggerInputConnections = connections.filter((connection) => connection.inputNodeId === triggerNode.id);
3756
- const inputAnchorNodeIds = new Set(triggerInputConnections.map((connection) => connection.outputNodeId));
3757
- const includedNodeIds = new Set([triggerNode.id, ...nodeIds, ...inputAnchorNodeIds]);
3758
- const graph = {
3759
- metadata: this.#graph.metadata ? { ...this.#graph.metadata } : undefined,
3760
- nodes: this.#executionGraphNodes.filter((node) => includedNodeIds.has(node.id)),
3761
- connections: connections.filter((connection) => connection.inputNodeId === triggerNode.id ||
3762
- (nodeIds.has(connection.inputNodeId) &&
3763
- (connection.outputNodeId === triggerNode.id || nodeIds.has(connection.outputNodeId)))),
3764
- };
3385
+ for (const { triggerNode, graph, nodeIds } of planAsyncBranchTopology({
3386
+ graph: this.#graph,
3387
+ executionNodes: this.#executionGraphNodes,
3388
+ nodesById: this.#nodesById,
3389
+ connections: this.#getEffectiveConnections().filter((connection) => this.#isDefinitionValidConnection(connection)),
3390
+ relevantNodeIds: this.#getExecutionRelevantNodeIds(),
3391
+ preloadedNodes: this.#run.nodeResults,
3392
+ consumedTriggerNodeId: this.#consumedAsyncBranchTriggerNodeId,
3393
+ inputAnchorNodeIds: this.#asyncBranchInputAnchors
3394
+ ? new Set(Object.keys(this.#asyncBranchInputAnchors))
3395
+ : undefined,
3396
+ enclosingWatchNode: this.#getEnclosingStreamingWatchInvocation()?.plan.watchNode,
3397
+ })) {
3765
3398
  this.#asyncBranchPlansByTriggerNodeId.set(triggerNode.id, { graph, nodeIds });
3766
3399
  if (triggerNode.id !== this.#consumedAsyncBranchTriggerNodeId) {
3767
- for (const nodeId of nodeIds) {
3768
- this.#ignoreNodes.add(nodeId);
3769
- }
3400
+ for (const nodeId of nodeIds)
3401
+ this.#run.ignoreNodes.add(nodeId);
3770
3402
  }
3771
3403
  }
3772
3404
  }
@@ -3856,20 +3488,20 @@ export class GraphProcessor {
3856
3488
  }
3857
3489
  }
3858
3490
  #isNodeSelected(nodeId) {
3859
- return !this.#graphOutputSelection || this.#graphOutputSelection.nodeIds.has(nodeId);
3491
+ return !this.#run.graphOutputSelection || this.#run.graphOutputSelection.nodeIds.has(nodeId);
3860
3492
  }
3861
3493
  #getExecutionRelevantNodeIds() {
3862
3494
  if (this.#sameGraphRunOwnerOverride) {
3863
3495
  return this.#sameGraphRunOwnerOverride.#getExecutionRelevantNodeIds();
3864
3496
  }
3865
- return this.#graphOutputSelection?.nodeIds ?? this.#getRunToRelevantNodeIds();
3497
+ return this.#run.graphOutputSelection?.nodeIds ?? this.#getRunToRelevantNodeIds();
3866
3498
  }
3867
3499
  #getRunToRelevantNodeIds() {
3868
3500
  if (!this.runToNodeIds) {
3869
3501
  return undefined;
3870
3502
  }
3871
- if (this.#runToRelevantNodeIds) {
3872
- return this.#runToRelevantNodeIds;
3503
+ if (this.#run.runToRelevantNodeIds) {
3504
+ return this.#run.runToRelevantNodeIds;
3873
3505
  }
3874
3506
  const relevantNodeIds = new Set();
3875
3507
  for (const runToNodeId of this.runToNodeIds) {
@@ -3877,7 +3509,7 @@ export class GraphProcessor {
3877
3509
  relevantNodeIds.add(dependencyNodeId);
3878
3510
  }
3879
3511
  }
3880
- this.#runToRelevantNodeIds = relevantNodeIds;
3512
+ this.#run.runToRelevantNodeIds = relevantNodeIds;
3881
3513
  return relevantNodeIds;
3882
3514
  }
3883
3515
  #emitGraphPartialOutputIfNeeded(node, partialOutputs) {
@@ -3906,6 +3538,91 @@ export class GraphProcessor {
3906
3538
  execution: parentExecution,
3907
3539
  });
3908
3540
  }
3541
+ /** Common construction only. Aliases, execution identity and terminal commits
3542
+ * remain explicit in each invocation path rather than a matrix of flags. */
3543
+ #constructChildInvocation(invocation) {
3544
+ const ordinary = invocation.kind === 'subgraph';
3545
+ const processor = new GraphProcessor(ordinary ? invocation.project : this.#project, ordinary ? invocation.graphId : invocation.graph.metadata.id, this.#registry, this.#includeTrace, {
3546
+ cacheLoadedProjects: ordinary ? this.#cacheLoadedProjects : true,
3547
+ captureNodeTimings: this.#captureNodeTimings,
3548
+ concurrency: this.#concurrency,
3549
+ executionPlanCacheMode: this.#executionPlanCacheMode,
3550
+ runtimeCache: ordinary
3551
+ ? this.#runtimeCache
3552
+ : {
3553
+ ...this.#runtimeCache,
3554
+ graphBoundaries: undefined,
3555
+ loadedProjects: { ...this.#run.loadedProjects },
3556
+ },
3557
+ runtimeProfiler: this.#runtimeProfiler,
3558
+ scheduler: this.#scheduler,
3559
+ ...(ordinary
3560
+ ? { initialExecutionPlan: invocation.initialExecutionPlan }
3561
+ : { [graphProcessorGraphOverride]: invocation.graph }),
3562
+ ...(invocation.kind === 'watch' ? { [consumedStreamingWatchNodeOverride]: invocation.watchNodeId } : {}),
3563
+ ...(invocation.kind === 'async'
3564
+ ? {
3565
+ [consumedAsyncBranchTriggerOverride]: invocation.triggerNodeId,
3566
+ [asyncBranchInputAnchorsOverride]: invocation.inputAnchors,
3567
+ }
3568
+ : {}),
3569
+ });
3570
+ if (invocation.kind === 'async')
3571
+ invocation.onCreated(processor);
3572
+ processor.executor = this.executor;
3573
+ processor.#isSubProcessor = true;
3574
+ processor.#shared = this.#shared;
3575
+ processor.#externalFunctions = this.#externalFunctions;
3576
+ processor.#contextValues = this.#contextValues;
3577
+ processor.#parent = this;
3578
+ processor.#recordingProjectScope = this.#recordingProjectScope;
3579
+ processor.#graphCallPath = this.#graphCallPath;
3580
+ processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3581
+ processor.#executor = this.#executor;
3582
+ return processor;
3583
+ }
3584
+ #wireChildEvents(processor, owner, options = {}) {
3585
+ return wireSubprocessorEvents(processor, owner.#emitter, {
3586
+ ...options,
3587
+ isPaused: () => owner.#lifecycle.isPaused,
3588
+ pause: () => {
3589
+ void owner.pause();
3590
+ },
3591
+ resume: () => {
3592
+ void owner.resume();
3593
+ },
3594
+ });
3595
+ }
3596
+ #releaseChildInvocation(processor, owner, lifecycle, events, executionFailed) {
3597
+ try {
3598
+ cleanupSubprocessorBindings(lifecycle, events, executionFailed);
3599
+ }
3600
+ finally {
3601
+ owner.#run.subprocessors.delete(processor);
3602
+ }
3603
+ }
3604
+ #wireChildLifecycle(processor, owner, unwireEvents, options = {}) {
3605
+ try {
3606
+ return wireSubprocessorLifecycle(processor, {
3607
+ ...options,
3608
+ parentAbortSignal: owner.#run.abortController.signal,
3609
+ onParentPause: (listener) => owner.on('pause', listener),
3610
+ onParentResume: (listener) => owner.on('resume', listener),
3611
+ });
3612
+ }
3613
+ catch (error) {
3614
+ // Lifecycle setup rolls back its own partial bindings. Undo the earlier
3615
+ // event bridge and registration too, preserving the original setup error.
3616
+ try {
3617
+ unwireEvents();
3618
+ }
3619
+ catch {
3620
+ /* Setup failure remains authoritative. */
3621
+ }
3622
+ owner.#run.subprocessors.delete(processor);
3623
+ throw error;
3624
+ }
3625
+ }
3909
3626
  #createSubProcessor(node, index, processId, subGraphId, { signal, project } = {}) {
3910
3627
  const subprocessorProject = project ?? this.#project;
3911
3628
  const subprocessorGraph = resolveProcessorGraph(subprocessorProject, subGraphId);
@@ -3915,42 +3632,29 @@ export class GraphProcessor {
3915
3632
  const createProfileStart = this.#startRuntimeProfile();
3916
3633
  let processor;
3917
3634
  try {
3918
- processor = new GraphProcessor(subprocessorProject, subGraphId, this.#registry, this.#includeTrace, {
3919
- cacheLoadedProjects: this.#cacheLoadedProjects,
3920
- captureNodeTimings: this.#captureNodeTimings,
3921
- concurrency: this.#concurrency,
3922
- executionPlanCacheMode: this.#executionPlanCacheMode,
3635
+ processor = this.#constructChildInvocation({
3636
+ kind: 'subgraph',
3637
+ project: subprocessorProject,
3638
+ graphId: subGraphId,
3923
3639
  initialExecutionPlan,
3924
- runtimeCache: this.#runtimeCache,
3925
- runtimeProfiler: this.#runtimeProfiler,
3926
- scheduler: this.#scheduler,
3927
3640
  });
3928
3641
  }
3929
3642
  finally {
3930
3643
  this.#finishRuntimeProfile('createSubProcessor', createProfileStart);
3931
3644
  }
3932
- processor.executor = this.executor;
3933
- processor.#isSubProcessor = true;
3934
- processor.#subgraphTargetCache = this.#subgraphTargetCache;
3935
- processor.#executionCache = this.#executionCache;
3936
- processor.#externalFunctions = this.#externalFunctions;
3937
- processor.#contextValues = this.#contextValues;
3938
- processor.#parent = this;
3939
3645
  processor.#recordingProjectScope =
3940
3646
  node.type === 'subGraph' && node.data.targetProjectId
3941
3647
  ? getSubgraphProjectKey({
3942
3648
  projectId: node.data.targetProjectId,
3943
3649
  version: node.data.targetVersion ?? 'latest',
3944
3650
  })
3945
- : this.#recordingProjectScope;
3651
+ : subprocessorProject.metadata.id !== this.#project.metadata.id
3652
+ ? getSubgraphProjectKey({ projectId: subprocessorProject.metadata.id, version: 'latest' })
3653
+ : this.#recordingProjectScope;
3946
3654
  processor.#graphCallPath = Object.freeze([
3947
3655
  ...this.#graphCallPath,
3948
3656
  processor.#graph.metadata?.name || '(Unnamed Graph)',
3949
3657
  ]);
3950
- processor.#globals = this.#globals;
3951
- processor.#storedValueController = this.#storedValueController;
3952
- processor.#knowledgeStoreController = this.#knowledgeStoreController;
3953
- processor.#frozenNodeOutputResolver = this.#frozenNodeOutputResolver;
3954
3658
  processor.#executor = {
3955
3659
  nodeId: node.id,
3956
3660
  parentGraphId: this.#graph.metadata.id,
@@ -3958,39 +3662,17 @@ export class GraphProcessor {
3958
3662
  processId,
3959
3663
  };
3960
3664
  const wireEventsProfileStart = this.#startRuntimeProfile();
3665
+ let unwireEvents;
3961
3666
  try {
3962
- wireSubprocessorEvents(processor, this.#emitter, {
3963
- isPaused: () => this.#lifecycle.isPaused,
3964
- pause: () => {
3965
- void this.pause();
3966
- },
3967
- resume: () => {
3968
- void this.resume();
3969
- },
3970
- });
3667
+ unwireEvents = this.#wireChildEvents(processor, this);
3971
3668
  }
3972
3669
  finally {
3973
3670
  this.#finishRuntimeProfile('wireSubProcessorEvents', wireEventsProfileStart);
3974
3671
  }
3975
- this.#subprocessors.add(processor);
3672
+ this.#run.subprocessors.add(processor);
3976
3673
  const wireLifecycleProfileStart = this.#startRuntimeProfile();
3977
3674
  try {
3978
- wireSubprocessorLifecycle(processor, {
3979
- signal,
3980
- parentAbortSignal: this.#abortController.signal,
3981
- onParentPause: (listener) => {
3982
- this.on('pause', listener);
3983
- return () => {
3984
- this.off('pause', listener);
3985
- };
3986
- },
3987
- onParentResume: (listener) => {
3988
- this.on('resume', listener);
3989
- return () => {
3990
- this.off('resume', listener);
3991
- };
3992
- },
3993
- });
3675
+ this.#wireChildLifecycle(processor, this, unwireEvents, { signal });
3994
3676
  }
3995
3677
  finally {
3996
3678
  this.#finishRuntimeProfile('wireSubProcessorLifecycle', wireLifecycleProfileStart);
@@ -4005,8 +3687,8 @@ export class GraphProcessor {
4005
3687
  let settled = false;
4006
3688
  const cleanup = () => {
4007
3689
  signal.removeEventListener('abort', abortListener);
4008
- if (this.#pendingUserInputs[node.id] === pending) {
4009
- delete this.#pendingUserInputs[node.id];
3690
+ if (this.#run.pendingUserInputs[node.id] === pending) {
3691
+ delete this.#run.pendingUserInputs[node.id];
4010
3692
  }
4011
3693
  };
4012
3694
  const abortListener = () => {
@@ -4024,7 +3706,7 @@ export class GraphProcessor {
4024
3706
  resolve(results);
4025
3707
  };
4026
3708
  const pending = { resolve: respond };
4027
- this.#pendingUserInputs[node.id] = pending;
3709
+ this.#run.pendingUserInputs[node.id] = pending;
4028
3710
  signal.addEventListener('abort', abortListener, { once: true });
4029
3711
  if (signal.aborted) {
4030
3712
  abortListener();
@@ -4055,11 +3737,11 @@ export class GraphProcessor {
4055
3737
  const { queueOutputNodes = true } = options;
4056
3738
  const attachedData = this.#getAttachedDataTo(node);
4057
3739
  this.#registerNodeInActiveLoop(node, attachedData);
4058
- this.#visitedNodes.add(node.id);
3740
+ this.#run.visitedNodes.add(node.id);
4059
3741
  this.#markAsExcluded(node, processId, inputValues, reason);
4060
- this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
4061
- this.#currentlyProcessing.delete(node.id);
4062
- this.#remainingNodes.delete(node.id);
3742
+ this.#finishStreamingOutputWatches(node, this.#run.nodeResults.get(node.id));
3743
+ this.#run.currentlyProcessing.delete(node.id);
3744
+ this.#run.remainingNodes.delete(node.id);
4063
3745
  const outputNodes = getOutputNodesFrom(this.#executionState, node);
4064
3746
  this.#propagateAttachedDataToOutputNodes(node, attachedData, outputNodes.connectionsToNodes);
4065
3747
  if (queueOutputNodes) {
@@ -4072,11 +3754,11 @@ export class GraphProcessor {
4072
3754
  }
4073
3755
  async #emitNodeExcluded(node, processId, inputValues, reason, resultOrigin = 'executed') {
4074
3756
  await this.#emitter.emit('nodeExcluded', this.#createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin));
4075
- this.#finishStreamingOutputWatches(node, this.#nodeResults.get(node.id));
3757
+ this.#finishStreamingOutputWatches(node, this.#run.nodeResults.get(node.id));
4076
3758
  }
4077
3759
  #createNodeExcludedEvent(node, processId, inputValues, reason, resultOrigin = 'executed') {
4078
3760
  const outputs = createExcludedNodeOutputs(node, this.#definitions[node.id].outputs);
4079
- this.#nodeResults.set(node.id, outputs);
3761
+ this.#run.nodeResults.set(node.id, outputs);
4080
3762
  this.#commitExcludedGraphOutput(node, inputValues, outputs);
4081
3763
  return this.#withExecution({
4082
3764
  node,
@@ -4095,7 +3777,7 @@ export class GraphProcessor {
4095
3777
  const outputId = node.data.id;
4096
3778
  const value = outputs['valueOutput'];
4097
3779
  if (value) {
4098
- commitGraphOutputValue(this.#graphOutputs, outputId, value);
3780
+ commitGraphOutputValue(this.#run.graphOutputs, outputId, value);
4099
3781
  }
4100
3782
  }
4101
3783
  #getInputValuesForNode(node) {
@@ -4105,7 +3787,7 @@ export class GraphProcessor {
4105
3787
  connections?.find((conn) => conn.inputId === input.id && conn.inputNodeId === node.id);
4106
3788
  if (connection) {
4107
3789
  const outputNode = this.#nodeInstances[connection.outputNodeId].chartNode;
4108
- const outputNodeOutputs = this.#nodeResults.get(outputNode.id);
3790
+ const outputNodeOutputs = this.#run.nodeResults.get(outputNode.id);
4109
3791
  const outputResult = outputNodeOutputs?.[connection.outputId];
4110
3792
  values[input.id] = outputResult;
4111
3793
  }
@@ -4126,12 +3808,12 @@ export class GraphProcessor {
4126
3808
  return {
4127
3809
  connections: this.#connections,
4128
3810
  definitions: this.#definitions,
4129
- erroredNodes: this.#erroredNodes,
3811
+ erroredNodes: this.#run.erroredNodes,
4130
3812
  executionPlan: this.#graphExecutionPlan,
4131
- loopControllersSeen: this.#loopControllersSeen,
3813
+ loopControllersSeen: this.#run.loopControllersSeen,
4132
3814
  nodesById: this.#nodesById,
4133
3815
  stronglyConnectedComponents: this.#scc,
4134
- visitedNodes: this.#visitedNodes,
3816
+ visitedNodes: this.#run.visitedNodes,
4135
3817
  };
4136
3818
  }
4137
3819
  }